lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
9cedc61d6b0bfef762e9f44e5e25081498aab4f7
0
cmebarrow/gateway,nemigaservices/gateway,mgherghe/gateway,danibusu/gateway,dpwspoon/gateway,adrian-galbenus/gateway,kaazing/gateway,a-zuckut/gateway,adrian-galbenus/gateway,vmaraloiu/gateway,nemigaservices/gateway,AdrianCozma/gateway,adrian-galbenus/gateway,jfallows/gateway,Anisotrop/gateway,kaazing/gateway,nemigaservices/gateway,vmaraloiu/gateway,jitsni/gateway,cmebarrow/gateway,Anisotrop/gateway,a-zuckut/gateway,danibusu/gateway,stanculescu/gateway,a-zuckut/gateway,dpwspoon/gateway,AdrianCozma/gateway,Anisotrop/gateway,kaazing/gateway,DoruM/gateway,danibusu/gateway,adrian-galbenus/gateway,nemigaservices/gateway,jitsni/gateway,jfallows/gateway,a-zuckut/gateway,mgherghe/gateway,jitsni/gateway,vmaraloiu/gateway,danibusu/gateway,mgherghe/gateway,jitsni/gateway,DoruM/gateway,vmaraloiu/gateway,cmebarrow/gateway,kaazing/gateway,AdrianCozma/gateway,Anisotrop/gateway,stanculescu/gateway,DoruM/gateway,DoruM/gateway,stanculescu/gateway,dpwspoon/gateway,cmebarrow/gateway,jfallows/gateway,jfallows/gateway,stanculescu/gateway,mgherghe/gateway,dpwspoon/gateway,AdrianCozma/gateway
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.channel.socket.nio; import static java.lang.String.format; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.io.IOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.ConcurrentModificationException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ThreadNameDeterminer; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.DeadLockProofWorker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; abstract class AbstractNioSelector implements NioSelector { protected static final Logger PERF_LOGGER = LoggerFactory.getLogger("performance.tcp"); private static final AtomicInteger nextId = new AtomicInteger(); protected static final long LATENCY_BEFORE_LOG_PROCESS_SELECT = MILLISECONDS.toNanos(100); private static final long LATENCY_BEFORE_LOG_TASK = MILLISECONDS.toNanos(100); private final int id = nextId.incrementAndGet(); private final IdleStrategy idleStrategy = new BackoffIdleStrategy(50, 50, MILLISECONDS.toNanos(10), MILLISECONDS.toNanos(50)); /** * Internal Netty logger. */ protected static final InternalLogger logger = InternalLoggerFactory .getInstance(AbstractNioSelector.class); private static final int CLEANUP_INTERVAL = 256; // XXX Hard-coded value, but won't need customization. /** * Executor used to execute {@link Runnable}s such as channel registration * task. */ private final Executor executor; /** * If this worker has been started thread will be a reference to the thread * used when starting. i.e. the current thread when the run method is executed. */ protected volatile Thread thread; /** * Count down to 0 when the I/O thread starts and {@link #thread} is set to non-null. */ final CountDownLatch startupLatch = new CountDownLatch(1); /** * The NIO {@link Selector}. */ protected volatile Selector selector; /** * Boolean that controls determines if a blocked Selector.select should * break out of its selection process. In our case we use a timeone for * the select method and the select method will block for that time unless * waken up. */ protected final AtomicBoolean wakenUp = new AtomicBoolean(); private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<>(); private volatile int cancelledKeys; // should use AtomicInteger but we just need approximation private final CountDownLatch shutdownLatch = new CountDownLatch(1); private volatile boolean shutdown; AbstractNioSelector(Executor executor) { this(executor, null); } AbstractNioSelector(Executor executor, ThreadNameDeterminer determiner) { this.executor = executor; openSelector(determiner); } @Override public void register(Channel channel, ChannelFuture future) { Runnable task = createRegisterTask(channel, future); registerTask(task); } protected final void registerTask(Runnable task) { taskQueue.add(task); Selector selector = this.selector; if (selector != null) { if (wakenUp.compareAndSet(false, true)) { selector.wakeup(); } // log("Task added to queue"); } else { if (taskQueue.remove(task)) { // the selector was null this means the Worker has already been shutdown. throw new RejectedExecutionException("Worker has already been shutdown"); } } } protected final boolean isIoThread() { return Thread.currentThread() == thread; } @Override public void rebuildSelector() { if (!isIoThread()) { taskQueue.add(new Runnable() { @Override public void run() { rebuildSelector(); } }); return; } final Selector oldSelector = selector; final Selector newSelector; if (oldSelector == null) { return; } try { newSelector = Selector.open(); } catch (Exception e) { logger.warn("Failed to create a new Selector.", e); return; } // Register all channels to the new Selector. int nChannels = 0; for (;;) { try { for (SelectionKey key: oldSelector.keys()) { try { if (key.channel().keyFor(newSelector) != null) { continue; } int interestOps = key.interestOps(); key.cancel(); key.channel().register(newSelector, interestOps, key.attachment()); nChannels ++; } catch (Exception e) { logger.warn("Failed to re-register a Channel to the new Selector,", e); close(key); } } } catch (ConcurrentModificationException e) { // Probably due to concurrent modification of the key set. continue; } break; } selector = newSelector; try { // time to close the old selector as everything else is registered to the new one oldSelector.close(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("Failed to close the old Selector.", t); } } logger.info("Migrated " + nChannels + " channel(s) to the new Selector,"); } @Override public void run() { thread = Thread.currentThread(); startupLatch.countDown(); int selectReturnsImmediately = 0; Selector selector = this.selector; if (selector == null) { return; } // use 80% of the timeout for measure final long minSelectTimeout = SelectorUtil.SELECT_TIMEOUT_NANOS * 80 / 100; boolean wakenupFromLoop = false; boolean quickSelect = false; long maximumProcessTaskQueueNanos = getMaximumProcessTaskQueueTimeNanos(); for (;;) { wakenUp.set(false); try { long beforeSelect = System.nanoTime(); int selected = select(selector, quickSelect); if (SelectorUtil.EPOLL_BUG_WORKAROUND && selected == 0 && !wakenupFromLoop && !wakenUp.get()) { long timeBlocked = System.nanoTime() - beforeSelect; if (timeBlocked < minSelectTimeout) { boolean notConnected = false; // loop over all keys as the selector may was unblocked because of a closed channel for (SelectionKey key: selector.keys()) { SelectableChannel ch = key.channel(); try { if (ch instanceof DatagramChannel && !((DatagramChannel) ch).isConnected() || ch instanceof SocketChannel && !((SocketChannel) ch).isConnected()) { notConnected = true; // cancel the key just to be on the safe side key.cancel(); } } catch (CancelledKeyException e) { // ignore } } if (notConnected) { selectReturnsImmediately = 0; } else { // returned before the minSelectTimeout elapsed with nothing select. // this may be the cause of the jdk epoll(..) bug, so increment the counter // which we use later to see if its really the jdk bug. selectReturnsImmediately ++; } } else { selectReturnsImmediately = 0; } if (selectReturnsImmediately == 1024) { // The selector returned immediately for 10 times in a row, // so recreate one selector as it seems like we hit the // famous epoll(..) jdk bug. rebuildSelector(); selector = this.selector; selectReturnsImmediately = 0; wakenupFromLoop = false; // try to select again continue; } } else { // reset counter selectReturnsImmediately = 0; } // 'wakenUp.compareAndSet(false, true)' is always evaluated // before calling 'selector.wakeup()' to reduce the wake-up // overhead. (Selector.wakeup() is an expensive operation.) // // However, there is a race condition in this approach. // The race condition is triggered when 'wakenUp' is set to // true too early. // // 'wakenUp' is set to true too early if: // 1) Selector is waken up between 'wakenUp.set(false)' and // 'selector.select(...)'. (BAD) // 2) Selector is waken up between 'selector.select(...)' and // 'if (wakenUp.get()) { ... }'. (OK) // // In the first case, 'wakenUp' is set to true and the // following 'selector.select(...)' will wake up immediately. // Until 'wakenUp' is set to false again in the next round, // 'wakenUp.compareAndSet(false, true)' will fail, and therefore // any attempt to wake up the Selector will fail, too, causing // the following 'selector.select(...)' call to block // unnecessarily. // // To fix this problem, we wake up the selector again if wakenUp // is true immediately after selector.select(...). // It is inefficient in that it wakes up the selector for both // the first case (BAD - wake-up required) and the second case // (OK - no wake-up required). if (wakenUp.get()) { wakenupFromLoop = true; selector.wakeup(); } else { wakenupFromLoop = false; } cancelledKeys = 0; if (maximumProcessTaskQueueNanos > 0) { long deadlineNanos = System.nanoTime() + maximumProcessTaskQueueNanos; quickSelect = processTaskQueue(deadlineNanos); } else { processTaskQueue(); } selector = this.selector; // processTaskQueue() can call rebuildSelector() if (shutdown) { this.selector = null; // process one time again processTaskQueue(); for (SelectionKey k: selector.keys()) { close(k); } try { selector.close(); } catch (IOException e) { logger.warn( "Failed to close a selector.", e); } shutdownLatch.countDown(); break; } else { process(selector); processRead(); } } catch (Throwable t) { logger.warn( "Unexpected exception in the selector loop.", t); PERF_LOGGER.warn(format("Unexpected exception %s in selector loop", t)); t.printStackTrace(); // Prevent possible consecutive immediate failures that lead to // excessive CPU consumption. try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore. } } } } /** * Start the {@link AbstractNioWorker} and return the {@link Selector} that will be used for * the {@link AbstractNioChannel}'s when they get registered */ private void openSelector(ThreadNameDeterminer determiner) { try { selector = Selector.open(); } catch (Throwable t) { throw new ChannelException("Failed to create a selector.", t); } // Start the worker thread with the new Selector. boolean success = false; try { DeadLockProofWorker.start(executor, newThreadRenamingRunnable(id, determiner)); success = true; } finally { if (!success) { // Release the Selector if the execution fails. try { selector.close(); } catch (Throwable t) { logger.warn("Failed to close a selector.", t); } selector = null; // The method will return to the caller at this point. } } assert selector != null && selector.isOpen(); } protected void processTaskQueue() { for (;;) { final Runnable task = taskQueue.poll(); if (task == null) { break; } task.run(); try { cleanUpCancelledKeys(); } catch (IOException e) { // Ignore } } } private boolean processTaskQueue(long deadLineNanos) { long numTasks = 0; boolean perfLogEnabled = PERF_LOGGER.isInfoEnabled(); long startTime = perfLogEnabled ? System.nanoTime() : 0; boolean quickSelect; for (;;) { final Runnable task = taskQueue.poll(); if (task == null) { quickSelect = false; break; } numTasks++; task.run(); try { cleanUpCancelledKeys(); } catch (IOException e) { // Ignore } long now = System.nanoTime(); if (now > deadLineNanos) { if (perfLogEnabled) { long timeSoFar = now - startTime; if (PERF_LOGGER.isDebugEnabled() || timeSoFar > LATENCY_BEFORE_LOG_TASK) { PERF_LOGGER.info(format( "AbstractyNioSelector.processTaskQueue: exiting after processing %d tasks in %d ms", numTasks, TimeUnit.NANOSECONDS.toMillis(timeSoFar))); } } // Make sure select in run() loop is no wait or short since we still have tasks to do quickSelect = true; break; } } return quickSelect; } protected final void increaseCancelledKeys() { cancelledKeys ++; } protected final boolean cleanUpCancelledKeys() throws IOException { if (cancelledKeys >= CLEANUP_INTERVAL) { cancelledKeys = 0; selector.selectNow(); return true; } return false; } @Override public void shutdown() { if (isIoThread()) { throw new IllegalStateException("Must not be called from a I/O-Thread to prevent deadlocks!"); } Selector selector = this.selector; shutdown = true; if (selector != null) { selector.wakeup(); } try { shutdownLatch.await(); } catch (InterruptedException e) { logger.error("Interrupted while wait for resources to be released #" + id); Thread.currentThread().interrupt(); } } protected abstract void process(Selector selector) throws IOException; protected void processRead() throws IOException { } protected int select(Selector selector, boolean quickSelect) throws IOException { return select(selector); } protected int select(Selector selector) throws IOException { return SelectorUtil.select(selector); } protected abstract void close(SelectionKey k); protected abstract ThreadRenamingRunnable newThreadRenamingRunnable(int id, ThreadNameDeterminer determiner); protected abstract Runnable createRegisterTask(Channel channel, ChannelFuture future); protected long getMaximumProcessTaskQueueTimeNanos() { return 0; // no limit (process all tasks) } }
mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/AbstractNioSelector.java
/** * Copyright 2007-2016, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.channel.socket.nio; import static java.lang.String.format; import java.io.IOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.DatagramChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.ConcurrentModificationException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ThreadNameDeterminer; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.DeadLockProofWorker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; abstract class AbstractNioSelector implements NioSelector { protected static final Logger PERF_LOGGER = LoggerFactory.getLogger("performance.tcp"); private static final AtomicInteger nextId = new AtomicInteger(); protected static final long LATENCY_BEFORE_LOG_PROCESS_SELECT = TimeUnit.MILLISECONDS.toNanos(100); private static final long LATENCY_BEFORE_LOG_TASK = TimeUnit.MILLISECONDS.toNanos(100); private final int id = nextId.incrementAndGet(); /** * Internal Netty logger. */ protected static final InternalLogger logger = InternalLoggerFactory .getInstance(AbstractNioSelector.class); private static final int CLEANUP_INTERVAL = 256; // XXX Hard-coded value, but won't need customization. /** * Executor used to execute {@link Runnable}s such as channel registration * task. */ private final Executor executor; /** * If this worker has been started thread will be a reference to the thread * used when starting. i.e. the current thread when the run method is executed. */ protected volatile Thread thread; /** * Count down to 0 when the I/O thread starts and {@link #thread} is set to non-null. */ final CountDownLatch startupLatch = new CountDownLatch(1); /** * The NIO {@link Selector}. */ protected volatile Selector selector; /** * Boolean that controls determines if a blocked Selector.select should * break out of its selection process. In our case we use a timeone for * the select method and the select method will block for that time unless * waken up. */ protected final AtomicBoolean wakenUp = new AtomicBoolean(); private final Queue<Runnable> taskQueue = new ConcurrentLinkedQueue<>(); private volatile int cancelledKeys; // should use AtomicInteger but we just need approximation private final CountDownLatch shutdownLatch = new CountDownLatch(1); private volatile boolean shutdown; AbstractNioSelector(Executor executor) { this(executor, null); } AbstractNioSelector(Executor executor, ThreadNameDeterminer determiner) { this.executor = executor; openSelector(determiner); } @Override public void register(Channel channel, ChannelFuture future) { Runnable task = createRegisterTask(channel, future); registerTask(task); } protected final void registerTask(Runnable task) { taskQueue.add(task); Selector selector = this.selector; if (selector != null) { if (wakenUp.compareAndSet(false, true)) { selector.wakeup(); } // log("Task added to queue"); } else { if (taskQueue.remove(task)) { // the selector was null this means the Worker has already been shutdown. throw new RejectedExecutionException("Worker has already been shutdown"); } } } protected final boolean isIoThread() { return Thread.currentThread() == thread; } @Override public void rebuildSelector() { if (!isIoThread()) { taskQueue.add(new Runnable() { @Override public void run() { rebuildSelector(); } }); return; } final Selector oldSelector = selector; final Selector newSelector; if (oldSelector == null) { return; } try { newSelector = Selector.open(); } catch (Exception e) { logger.warn("Failed to create a new Selector.", e); return; } // Register all channels to the new Selector. int nChannels = 0; for (;;) { try { for (SelectionKey key: oldSelector.keys()) { try { if (key.channel().keyFor(newSelector) != null) { continue; } int interestOps = key.interestOps(); key.cancel(); key.channel().register(newSelector, interestOps, key.attachment()); nChannels ++; } catch (Exception e) { logger.warn("Failed to re-register a Channel to the new Selector,", e); close(key); } } } catch (ConcurrentModificationException e) { // Probably due to concurrent modification of the key set. continue; } break; } selector = newSelector; try { // time to close the old selector as everything else is registered to the new one oldSelector.close(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("Failed to close the old Selector.", t); } } logger.info("Migrated " + nChannels + " channel(s) to the new Selector,"); } @Override public void run() { thread = Thread.currentThread(); startupLatch.countDown(); int selectReturnsImmediately = 0; Selector selector = this.selector; if (selector == null) { return; } // use 80% of the timeout for measure final long minSelectTimeout = SelectorUtil.SELECT_TIMEOUT_NANOS * 80 / 100; boolean wakenupFromLoop = false; boolean quickSelect = false; long maximumProcessTaskQueueNanos = getMaximumProcessTaskQueueTimeNanos(); for (;;) { wakenUp.set(false); try { long beforeSelect = System.nanoTime(); int selected = select(selector, quickSelect); if (SelectorUtil.EPOLL_BUG_WORKAROUND && selected == 0 && !wakenupFromLoop && !wakenUp.get()) { long timeBlocked = System.nanoTime() - beforeSelect; if (timeBlocked < minSelectTimeout) { boolean notConnected = false; // loop over all keys as the selector may was unblocked because of a closed channel for (SelectionKey key: selector.keys()) { SelectableChannel ch = key.channel(); try { if (ch instanceof DatagramChannel && !((DatagramChannel) ch).isConnected() || ch instanceof SocketChannel && !((SocketChannel) ch).isConnected()) { notConnected = true; // cancel the key just to be on the safe side key.cancel(); } } catch (CancelledKeyException e) { // ignore } } if (notConnected) { selectReturnsImmediately = 0; } else { // returned before the minSelectTimeout elapsed with nothing select. // this may be the cause of the jdk epoll(..) bug, so increment the counter // which we use later to see if its really the jdk bug. selectReturnsImmediately ++; } } else { selectReturnsImmediately = 0; } if (selectReturnsImmediately == 1024) { // The selector returned immediately for 10 times in a row, // so recreate one selector as it seems like we hit the // famous epoll(..) jdk bug. rebuildSelector(); selector = this.selector; selectReturnsImmediately = 0; wakenupFromLoop = false; // try to select again continue; } } else { // reset counter selectReturnsImmediately = 0; } // 'wakenUp.compareAndSet(false, true)' is always evaluated // before calling 'selector.wakeup()' to reduce the wake-up // overhead. (Selector.wakeup() is an expensive operation.) // // However, there is a race condition in this approach. // The race condition is triggered when 'wakenUp' is set to // true too early. // // 'wakenUp' is set to true too early if: // 1) Selector is waken up between 'wakenUp.set(false)' and // 'selector.select(...)'. (BAD) // 2) Selector is waken up between 'selector.select(...)' and // 'if (wakenUp.get()) { ... }'. (OK) // // In the first case, 'wakenUp' is set to true and the // following 'selector.select(...)' will wake up immediately. // Until 'wakenUp' is set to false again in the next round, // 'wakenUp.compareAndSet(false, true)' will fail, and therefore // any attempt to wake up the Selector will fail, too, causing // the following 'selector.select(...)' call to block // unnecessarily. // // To fix this problem, we wake up the selector again if wakenUp // is true immediately after selector.select(...). // It is inefficient in that it wakes up the selector for both // the first case (BAD - wake-up required) and the second case // (OK - no wake-up required). if (wakenUp.get()) { wakenupFromLoop = true; selector.wakeup(); } else { wakenupFromLoop = false; } cancelledKeys = 0; if (maximumProcessTaskQueueNanos > 0) { long deadlineNanos = System.nanoTime() + maximumProcessTaskQueueNanos; quickSelect = processTaskQueue(deadlineNanos); } else { processTaskQueue(); } selector = this.selector; // processTaskQueue() can call rebuildSelector() if (shutdown) { this.selector = null; // process one time again processTaskQueue(); for (SelectionKey k: selector.keys()) { close(k); } try { selector.close(); } catch (IOException e) { logger.warn( "Failed to close a selector.", e); } shutdownLatch.countDown(); break; } else { process(selector); processRead(); } } catch (Throwable t) { logger.warn( "Unexpected exception in the selector loop.", t); PERF_LOGGER.warn(format("Unexpected exception %s in selector loop", t)); t.printStackTrace(); // Prevent possible consecutive immediate failures that lead to // excessive CPU consumption. try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore. } } } } /** * Start the {@link AbstractNioWorker} and return the {@link Selector} that will be used for * the {@link AbstractNioChannel}'s when they get registered */ private void openSelector(ThreadNameDeterminer determiner) { try { selector = Selector.open(); } catch (Throwable t) { throw new ChannelException("Failed to create a selector.", t); } // Start the worker thread with the new Selector. boolean success = false; try { DeadLockProofWorker.start(executor, newThreadRenamingRunnable(id, determiner)); success = true; } finally { if (!success) { // Release the Selector if the execution fails. try { selector.close(); } catch (Throwable t) { logger.warn("Failed to close a selector.", t); } selector = null; // The method will return to the caller at this point. } } assert selector != null && selector.isOpen(); } protected void processTaskQueue() { for (;;) { final Runnable task = taskQueue.poll(); if (task == null) { break; } task.run(); try { cleanUpCancelledKeys(); } catch (IOException e) { // Ignore } } } private boolean processTaskQueue(long deadLineNanos) { long numTasks = 0; boolean perfLogEnabled = PERF_LOGGER.isInfoEnabled(); long startTime = perfLogEnabled ? System.nanoTime() : 0; boolean quickSelect; for (;;) { final Runnable task = taskQueue.poll(); if (task == null) { quickSelect = false; break; } numTasks++; task.run(); try { cleanUpCancelledKeys(); } catch (IOException e) { // Ignore } long now = System.nanoTime(); if (now > deadLineNanos) { if (perfLogEnabled) { long timeSoFar = now - startTime; if (PERF_LOGGER.isDebugEnabled() || timeSoFar > LATENCY_BEFORE_LOG_TASK) { PERF_LOGGER.info(format( "AbstractyNioSelector.processTaskQueue: exiting after processing %d tasks in %d ms", numTasks, TimeUnit.NANOSECONDS.toMillis(timeSoFar))); } } // Make sure select in run() loop is no wait or short since we still have tasks to do quickSelect = true; break; } } return quickSelect; } protected final void increaseCancelledKeys() { cancelledKeys ++; } protected final boolean cleanUpCancelledKeys() throws IOException { if (cancelledKeys >= CLEANUP_INTERVAL) { cancelledKeys = 0; selector.selectNow(); return true; } return false; } @Override public void shutdown() { if (isIoThread()) { throw new IllegalStateException("Must not be called from a I/O-Thread to prevent deadlocks!"); } Selector selector = this.selector; shutdown = true; if (selector != null) { selector.wakeup(); } try { shutdownLatch.await(); } catch (InterruptedException e) { logger.error("Interrupted while wait for resources to be released #" + id); Thread.currentThread().interrupt(); } } protected abstract void process(Selector selector) throws IOException; protected void processRead() throws IOException { } protected int select(Selector selector, boolean quickSelect) throws IOException { return select(selector); } protected int select(Selector selector) throws IOException { return SelectorUtil.select(selector); } protected abstract void close(SelectionKey k); protected abstract ThreadRenamingRunnable newThreadRenamingRunnable(int id, ThreadNameDeterminer determiner); protected abstract Runnable createRegisterTask(Channel channel, ChannelFuture future); protected long getMaximumProcessTaskQueueTimeNanos() { return 0; // no limit (process all tasks) } }
Parking the thread for 10mills instead of 10micros Conflicts: mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/AbstractNioSelector.java
mina.netty/src/main/java/org/jboss/netty/channel/socket/nio/AbstractNioSelector.java
Parking the thread for 10mills instead of 10micros
Java
apache-2.0
8d02bf6661c74a9718542550c1588c06f74f1d89
0
zregvart/camel,pmoerenhout/camel,ullgren/camel,christophd/camel,CodeSmell/camel,CodeSmell/camel,christophd/camel,nikhilvibhav/camel,objectiser/camel,CodeSmell/camel,nicolaferraro/camel,cunningt/camel,objectiser/camel,ullgren/camel,cunningt/camel,zregvart/camel,gnodet/camel,alvinkwekel/camel,alvinkwekel/camel,alvinkwekel/camel,alvinkwekel/camel,nicolaferraro/camel,objectiser/camel,cunningt/camel,tadayosi/camel,DariusX/camel,adessaigne/camel,adessaigne/camel,apache/camel,tdiesler/camel,pax95/camel,nicolaferraro/camel,adessaigne/camel,cunningt/camel,gnodet/camel,nikhilvibhav/camel,apache/camel,pax95/camel,zregvart/camel,christophd/camel,christophd/camel,pmoerenhout/camel,mcollovati/camel,tadayosi/camel,CodeSmell/camel,Fabryprog/camel,pmoerenhout/camel,cunningt/camel,tadayosi/camel,christophd/camel,davidkarlsen/camel,apache/camel,tdiesler/camel,pmoerenhout/camel,pax95/camel,apache/camel,apache/camel,nikhilvibhav/camel,mcollovati/camel,pmoerenhout/camel,Fabryprog/camel,pax95/camel,tdiesler/camel,cunningt/camel,zregvart/camel,adessaigne/camel,christophd/camel,Fabryprog/camel,gnodet/camel,davidkarlsen/camel,tdiesler/camel,ullgren/camel,DariusX/camel,mcollovati/camel,davidkarlsen/camel,apache/camel,tadayosi/camel,adessaigne/camel,DariusX/camel,nicolaferraro/camel,adessaigne/camel,tdiesler/camel,gnodet/camel,mcollovati/camel,pax95/camel,nikhilvibhav/camel,gnodet/camel,objectiser/camel,Fabryprog/camel,tdiesler/camel,pmoerenhout/camel,pax95/camel,tadayosi/camel,tadayosi/camel,davidkarlsen/camel,DariusX/camel,ullgren/camel
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.main; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.ExtendedCamelContext; import org.apache.camel.NoSuchLanguageException; import org.apache.camel.ProducerTemplate; import org.apache.camel.PropertyBindingException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.HystrixConfigurationDefinition; import org.apache.camel.model.Model; import org.apache.camel.model.ModelCamelContext; import org.apache.camel.model.RouteDefinition; import org.apache.camel.spi.CamelBeanPostProcessor; import org.apache.camel.spi.DataFormat; import org.apache.camel.spi.EventNotifier; import org.apache.camel.spi.Language; import org.apache.camel.spi.PropertiesComponent; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.support.LifecycleStrategySupport; import org.apache.camel.support.PropertyBindingSupport; import org.apache.camel.support.service.ServiceHelper; import org.apache.camel.support.service.ServiceSupport; import org.apache.camel.util.FileUtil; import org.apache.camel.util.IOHelper; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.OrderedProperties; import org.apache.camel.util.StringHelper; import org.apache.camel.util.concurrent.ThreadHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.camel.support.ObjectHelper.invokeMethod; import static org.apache.camel.util.ReflectionHelper.findMethod; import static org.apache.camel.util.StringHelper.matches; /** * Base class for main implementations to allow starting up a JVM with Camel embedded. */ public abstract class MainSupport extends ServiceSupport { protected static final Logger LOG = LoggerFactory.getLogger(MainSupport.class); protected static final int UNINITIALIZED_EXIT_CODE = Integer.MIN_VALUE; protected static final int DEFAULT_EXIT_CODE = 0; protected final List<MainListener> listeners = new ArrayList<>(); protected final List<Option> options = new ArrayList<>(); protected final CountDownLatch latch = new CountDownLatch(1); protected final AtomicBoolean completed = new AtomicBoolean(false); protected final AtomicInteger exitCode = new AtomicInteger(UNINITIALIZED_EXIT_CODE); protected volatile CamelContext camelContext; protected volatile ProducerTemplate camelTemplate; protected final MainConfigurationProperties mainConfigurationProperties = new MainConfigurationProperties(); protected List<RouteBuilder> routeBuilders = new ArrayList<>(); protected String routeBuilderClasses; protected List<Object> configurations = new ArrayList<>(); protected String configurationClasses; protected String propertyPlaceholderLocations; protected Properties initialProperties; protected Properties overrideProperties; /** * A class for intercepting the hang up signal and do a graceful shutdown of the Camel. */ private static final class HangupInterceptor extends Thread { Logger log = LoggerFactory.getLogger(this.getClass()); final MainSupport mainInstance; HangupInterceptor(MainSupport main) { mainInstance = main; } @Override public void run() { log.info("Received hang up - stopping the main instance."); try { mainInstance.stop(); } catch (Exception ex) { log.warn("Error during stopping the main instance.", ex); } } } protected MainSupport(Class... configurationClasses) { this(); addConfigurationClass(configurationClasses); } protected MainSupport() { addOption(new Option("h", "help", "Displays the help screen") { protected void doProcess(String arg, LinkedList<String> remainingArgs) { showOptions(); completed(); } }); addOption(new ParameterOption("r", "routers", "Sets the router builder classes which will be loaded while starting the camel context", "routerBuilderClasses") { @Override protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { setRouteBuilderClasses(parameter); } }); addOption(new ParameterOption("d", "duration", "Sets the time duration (seconds) that the application will run for before terminating.", "duration") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { // skip second marker to be backwards compatible if (parameter.endsWith("s") || parameter.endsWith("S")) { parameter = parameter.substring(0, parameter.length() - 1); } configure().setDurationMaxSeconds(Integer.parseInt(parameter)); } }); addOption(new ParameterOption("dm", "durationMaxMessages", "Sets the duration of maximum number of messages that the application will process before terminating.", "durationMaxMessages") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { configure().setDurationMaxMessages(Integer.parseInt(parameter)); } }); addOption(new ParameterOption("di", "durationIdle", "Sets the idle time duration (seconds) duration that the application can be idle before terminating.", "durationIdle") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { // skip second marker to be backwards compatible if (parameter.endsWith("s") || parameter.endsWith("S")) { parameter = parameter.substring(0, parameter.length() - 1); } configure().setDurationMaxIdleSeconds(Integer.parseInt(parameter)); } }); addOption(new Option("t", "trace", "Enables tracing") { protected void doProcess(String arg, LinkedList<String> remainingArgs) { enableTrace(); } }); addOption(new ParameterOption("e", "exitcode", "Sets the exit code if duration was hit", "exitcode") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { configure().setDurationHitExitCode(Integer.parseInt(parameter)); } }); addOption(new ParameterOption("pl", "propertiesLocation", "Sets location(s) to load properties, such as from classpath or file system.", "propertiesLocation") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { setPropertyPlaceholderLocations(parameter); } }); } /** * Runs this process with the given arguments, and will wait until completed, or the JVM terminates. */ public void run() throws Exception { if (!completed.get()) { internalBeforeStart(); // if we have an issue starting then propagate the exception to caller beforeStart(); start(); try { afterStart(); waitUntilCompleted(); internalBeforeStop(); beforeStop(); stop(); afterStop(); } catch (Exception e) { // however while running then just log errors LOG.error("Failed: {}", e, e); } } } /** * Disable the hangup support. No graceful stop by calling stop() on a * Hangup signal. */ public void disableHangupSupport() { mainConfigurationProperties.setHangupInterceptorEnabled(false); } /** * Hangup support is enabled by default. */ public void enableHangupSupport() { mainConfigurationProperties.setHangupInterceptorEnabled(true); } /** * Adds a {@link org.apache.camel.main.MainListener} to receive callbacks when the main is started or stopping * * @param listener the listener */ public void addMainListener(MainListener listener) { listeners.add(listener); } /** * Removes the {@link org.apache.camel.main.MainListener} * * @param listener the listener */ public void removeMainListener(MainListener listener) { listeners.remove(listener); } /** * Callback to run custom logic before CamelContext is being started. * <p/> * It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void beforeStart() throws Exception { for (MainListener listener : listeners) { listener.beforeStart(this); } } /** * Callback to run custom logic after CamelContext has been started. * <p/> * It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void afterStart() throws Exception { for (MainListener listener : listeners) { listener.afterStart(this); } } private void internalBeforeStart() { if (mainConfigurationProperties.isHangupInterceptorEnabled()) { String threadName = ThreadHelper.resolveThreadName(null, "CamelHangupInterceptor"); Thread task = new HangupInterceptor(this); task.setName(threadName); Runtime.getRuntime().addShutdownHook(task); } } /** * Callback to run custom logic before CamelContext is being stopped. * <p/> * It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void beforeStop() throws Exception { for (MainListener listener : listeners) { listener.beforeStop(this); } } /** * Callback to run custom logic after CamelContext has been stopped. * <p/> * It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void afterStop() throws Exception { for (MainListener listener : listeners) { listener.afterStop(this); } } private void internalBeforeStop() { try { if (camelTemplate != null) { ServiceHelper.stopService(camelTemplate); camelTemplate = null; } } catch (Exception e) { LOG.debug("Error stopping camelTemplate due " + e.getMessage() + ". This exception is ignored.", e); } } /** * Marks this process as being completed. */ public void completed() { completed.set(true); exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, DEFAULT_EXIT_CODE); latch.countDown(); } /** * Displays the command line options. */ public void showOptions() { showOptionsHeader(); for (Option option : options) { System.out.println(option.getInformation()); } } /** * Parses the command line arguments. */ public void parseArguments(String[] arguments) { LinkedList<String> args = new LinkedList<>(Arrays.asList(arguments)); boolean valid = true; while (!args.isEmpty()) { String arg = args.removeFirst(); boolean handled = false; for (Option option : options) { if (option.processOption(arg, args)) { handled = true; break; } } if (!handled) { System.out.println("Unknown option: " + arg); System.out.println(); valid = false; break; } } if (!valid) { showOptions(); completed(); } } public void addOption(Option option) { options.add(option); } /** * To configure options on Camel Main. */ public MainConfigurationProperties configure() { return mainConfigurationProperties; } @Deprecated public int getDuration() { return mainConfigurationProperties.getDurationMaxSeconds(); } /** * Sets the duration (in seconds) to run the application until it * should be terminated. Defaults to -1. Any value <= 0 will run forever. * @deprecated use {@link #configure()} */ @Deprecated public void setDuration(int duration) { mainConfigurationProperties.setDurationMaxSeconds(duration); } @Deprecated public int getDurationIdle() { return mainConfigurationProperties.getDurationMaxIdleSeconds(); } /** * Sets the maximum idle duration (in seconds) when running the application, and * if there has been no message processed after being idle for more than this duration * then the application should be terminated. * Defaults to -1. Any value <= 0 will run forever. * @deprecated use {@link #configure()} */ @Deprecated public void setDurationIdle(int durationIdle) { mainConfigurationProperties.setDurationMaxIdleSeconds(durationIdle); } @Deprecated public int getDurationMaxMessages() { return mainConfigurationProperties.getDurationMaxMessages(); } /** * Sets the duration to run the application to process at most max messages until it * should be terminated. Defaults to -1. Any value <= 0 will run forever. * @deprecated use {@link #configure()} */ @Deprecated public void setDurationMaxMessages(int durationMaxMessages) { mainConfigurationProperties.setDurationMaxMessages(durationMaxMessages); } /** * Sets the exit code for the application if duration was hit * @deprecated use {@link #configure()} */ @Deprecated public void setDurationHitExitCode(int durationHitExitCode) { mainConfigurationProperties.setDurationHitExitCode(durationHitExitCode); } @Deprecated public int getDurationHitExitCode() { return mainConfigurationProperties.getDurationHitExitCode(); } public int getExitCode() { return exitCode.get(); } public String getConfigurationClasses() { return configurationClasses; } public void setConfigurationClasses(String configurations) { this.configurationClasses = configurations; } public void addConfigurationClass(Class... configuration) { String existing = configurationClasses; if (existing == null) { existing = ""; } if (configuration != null) { for (Class clazz : configuration) { if (!existing.isEmpty()) { existing = existing + ","; } existing = existing + clazz.getName(); } } setConfigurationClasses(existing); } public void addConfiguration(Object configuration) { configurations.add(configuration); } public String getRouteBuilderClasses() { return routeBuilderClasses; } public void setRouteBuilderClasses(String builders) { this.routeBuilderClasses = builders; } public String getPropertyPlaceholderLocations() { return propertyPlaceholderLocations; } /** * A list of locations to add for loading properties. * You can use comma to separate multiple locations. */ public void setPropertyPlaceholderLocations(String location) { this.propertyPlaceholderLocations = location; } @Deprecated public boolean isAutoConfigurationEnabled() { return mainConfigurationProperties.isAutoConfigurationEnabled(); } /** * Whether auto-configuration of components/dataformats/languages is enabled or not. * When enabled the configuration parameters are loaded from the properties component * and configured as defaults (similar to spring-boot auto-configuration). You can prefix * the parameters in the properties file with: * - camel.component.name.option1=value1 * - camel.component.name.option2=value2 * - camel.dataformat.name.option1=value1 * - camel.dataformat.name.option2=value2 * - camel.language.name.option1=value1 * - camel.language.name.option2=value2 * Where name is the name of the component, dataformat or language such as seda,direct,jaxb. * <p/> * The auto-configuration also works for any options on components * that is a complex type (not standard Java type) and there has been an explicit single * bean instance registered to the Camel registry via the {@link org.apache.camel.spi.Registry#bind(String, Object)} method * or by using the {@link org.apache.camel.BindToRegistry} annotation style. * <p/> * This option is default enabled. * @deprecated use {@link #configure()} */ @Deprecated public void setAutoConfigurationEnabled(boolean autoConfigurationEnabled) { mainConfigurationProperties.setAutoConfigurationEnabled(autoConfigurationEnabled); } public Properties getInitialProperties() { return initialProperties; } /** * Sets initial properties for the properties component, * which will be used before any locations are resolved. */ public void setInitialProperties(Properties initialProperties) { this.initialProperties = initialProperties; } public Properties getOverrideProperties() { return overrideProperties; } /** * Sets a special list of override properties that take precedence * and will use first, if a property exist. */ public void setOverrideProperties(Properties overrideProperties) { this.overrideProperties = overrideProperties; } public boolean isTrace() { return mainConfigurationProperties.isTracing(); } public void enableTrace() { mainConfigurationProperties.setTracing(true); } protected void doStop() throws Exception { // call completed to properly stop as we count down the waiting latch completed(); } protected void doStart() throws Exception { } protected void waitUntilCompleted() { while (!completed.get()) { try { int idle = mainConfigurationProperties.getDurationMaxIdleSeconds(); int max = mainConfigurationProperties.getDurationMaxMessages(); long sec = mainConfigurationProperties.getDurationMaxSeconds(); if (sec > 0) { LOG.info("Waiting for: {} seconds", sec); latch.await(sec, TimeUnit.SECONDS); exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, mainConfigurationProperties.getDurationHitExitCode()); completed.set(true); } else if (idle > 0 || max > 0) { if (idle > 0 && max > 0) { LOG.info("Waiting to be idle for: {} seconds or until: {} messages has been processed", idle, max); } else if (idle > 0) { LOG.info("Waiting to be idle for: {} seconds", idle); } else { LOG.info("Waiting until: {} messages has been processed", max); } exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, mainConfigurationProperties.getDurationHitExitCode()); latch.await(); completed.set(true); } else { latch.await(); } } catch (InterruptedException e) { // okay something interrupted us so terminate completed.set(true); latch.countDown(); Thread.currentThread().interrupt(); } } } /** * Parses the command line arguments then runs the program. */ public void run(String[] args) throws Exception { parseArguments(args); run(); LOG.info("MainSupport exiting code: {}", getExitCode()); } /** * Displays the header message for the command line options. */ public void showOptionsHeader() { System.out.println("Apache Camel Runner takes the following options"); System.out.println(); } public CamelContext getCamelContext() { return camelContext; } public List<RouteBuilder> getRouteBuilders() { return routeBuilders; } public void setRouteBuilders(List<RouteBuilder> routeBuilders) { this.routeBuilders = routeBuilders; } public List<Object> getConfigurations() { return configurations; } public void setConfigurations(List<Object> configurations) { this.configurations = configurations; } public List<RouteDefinition> getRouteDefinitions() { List<RouteDefinition> answer = new ArrayList<>(); if (camelContext != null) { answer.addAll(camelContext.getExtension(Model.class).getRouteDefinitions()); } return answer; } public ProducerTemplate getCamelTemplate() throws Exception { if (camelTemplate == null) { camelTemplate = findOrCreateCamelTemplate(); } return camelTemplate; } protected abstract ProducerTemplate findOrCreateCamelTemplate(); protected abstract CamelContext createCamelContext(); protected void initCamelContext() throws Exception { camelContext = createCamelContext(); postProcessCamelContext(camelContext); } protected void loadRouteBuilders(CamelContext camelContext) throws Exception { // lets use Camel's bean post processor on any existing route builder classes // so the instance has some support for dependency injection CamelBeanPostProcessor postProcessor = camelContext.adapt(ExtendedCamelContext.class).getBeanPostProcessor(); for (RouteBuilder routeBuilder : getRouteBuilders()) { postProcessor.postProcessBeforeInitialization(routeBuilder, routeBuilder.getClass().getName()); postProcessor.postProcessAfterInitialization(routeBuilder, routeBuilder.getClass().getName()); } if (routeBuilderClasses != null) { String[] routeClasses = routeBuilderClasses.split(","); for (String routeClass : routeClasses) { Class<?> routeClazz = camelContext.getClassResolver().resolveClass(routeClass); // lets use Camel's injector so the class has some support for dependency injection Object builder = camelContext.getInjector().newInstance(routeClazz); if (builder instanceof RouteBuilder) { getRouteBuilders().add((RouteBuilder) builder); } else { LOG.warn("Class {} is not a RouteBuilder class", routeClazz); } } } } protected void loadConfigurations(CamelContext camelContext) throws Exception { // lets use Camel's bean post processor on any existing configuration classes // so the instance has some support for dependency injection CamelBeanPostProcessor postProcessor = camelContext.adapt(ExtendedCamelContext.class).getBeanPostProcessor(); for (Object configuration : getConfigurations()) { postProcessor.postProcessBeforeInitialization(configuration, configuration.getClass().getName()); postProcessor.postProcessAfterInitialization(configuration, configuration.getClass().getName()); } if (configurationClasses != null) { String[] configClasses = configurationClasses.split(","); for (String configClass : configClasses) { Class<?> configClazz = camelContext.getClassResolver().resolveClass(configClass); // lets use Camel's injector so the class has some support for dependency injection Object config = camelContext.getInjector().newInstance(configClazz); getConfigurations().add(config); } } for (Object config : getConfigurations()) { // invoke configure method if exists Method method = findMethod(config.getClass(), "configure"); if (method != null) { log.info("Calling configure method on configuration class: {}", config.getClass().getName()); invokeMethod(method, config); } } } protected void postProcessCamelContext(CamelContext camelContext) throws Exception { if (propertyPlaceholderLocations != null) { PropertiesComponent pc = camelContext.getPropertiesComponent(); pc.addLocation(propertyPlaceholderLocations); if (initialProperties != null) { pc.setInitialProperties(initialProperties); } if (overrideProperties != null) { pc.setOverrideProperties(overrideProperties); } LOG.info("Using properties from: {}", propertyPlaceholderLocations); } else { // lets default to application.properties and ignore if its missing PropertiesComponent pc = camelContext.getPropertiesComponent(); pc.addLocation("classpath:application.properties"); pc.setIgnoreMissingLocation(true); if (initialProperties != null) { pc.setInitialProperties(initialProperties); } if (overrideProperties != null) { pc.setOverrideProperties(overrideProperties); } LOG.info("Using optional properties from classpath:application.properties"); } if (mainConfigurationProperties.getDurationMaxMessages() > 0 || mainConfigurationProperties.getDurationMaxIdleSeconds() > 0) { // register lifecycle so we can trigger to shutdown the JVM when maximum number of messages has been processed EventNotifier notifier = new MainDurationEventNotifier(camelContext, mainConfigurationProperties.getDurationMaxMessages(), mainConfigurationProperties.getDurationMaxIdleSeconds(), completed, latch, true); // register our event notifier ServiceHelper.startService(notifier); camelContext.getManagementStrategy().addEventNotifier(notifier); } final Map<String, String> autoConfiguredProperties = new LinkedHashMap<>(); // need to eager allow to auto-configure properties component if (mainConfigurationProperties.isAutoConfigurationEnabled()) { autoConfigurationFailFast(camelContext, autoConfiguredProperties); autoConfigurationPropertiesComponent(camelContext, autoConfiguredProperties); autoConfigurationMainConfiguration(camelContext, mainConfigurationProperties, autoConfiguredProperties); } // configure from main configuration properties doConfigureCamelContextFromMainConfiguration(camelContext, mainConfigurationProperties, autoConfiguredProperties); // try to load configuration classes loadConfigurations(camelContext); // conventional configuration via properties to allow configuring options on // component, dataformat, and languages (like spring-boot auto-configuration) if (mainConfigurationProperties.isAutowireComponentProperties() || mainConfigurationProperties.isAutowireComponentPropertiesDeep()) { autowireConfigurationFromRegistry(camelContext, mainConfigurationProperties.isAutowireComponentPropertiesDeep()); } if (mainConfigurationProperties.isAutoConfigurationEnabled()) { autoConfigurationFromProperties(camelContext, autoConfiguredProperties); } // log summary of configurations if (!autoConfiguredProperties.isEmpty()) { LOG.info("Auto-configuration summary:"); autoConfiguredProperties.forEach((k, v) -> LOG.info("\t{}={}", k, v)); } // try to load the route builders loadRouteBuilders(camelContext); for (RouteBuilder routeBuilder : routeBuilders) { camelContext.addRoutes(routeBuilder); } // register lifecycle so we are notified in Camel is stopped from JMX or somewhere else camelContext.addLifecycleStrategy(new MainLifecycleStrategy(completed, latch)); // allow to do configuration before its started for (MainListener listener : listeners) { listener.configure(camelContext); } } protected void autoConfigurationFailFast(CamelContext camelContext, Map<String, String> autoConfiguredProperties) throws Exception { // load properties Properties prop = camelContext.getPropertiesComponent().loadProperties(); LOG.debug("Properties from Camel properties component:"); for (String key : prop.stringPropertyNames()) { LOG.debug(" {}={}", key, prop.getProperty(key)); } // special for environment-variable-enbaled as we need to know this early before we set all the other options Object envEnabled = prop.remove("camel.main.autoConfigurationEnvironmentVariablesEnabled"); if (envEnabled == null) { envEnabled = prop.remove("camel.main.auto-configuration-environment-variables-enabled"); if (envEnabled != null) { PropertyBindingSupport.bindMandatoryProperty(camelContext, mainConfigurationProperties, "autoConfigurationEnvironmentVariablesEnabled", envEnabled, true); autoConfiguredProperties.put("camel.main.auto-configuration-environment-variables-enabled", envEnabled.toString()); } } // load properties from ENV (override existing) Properties propENV = null; if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.main."}); if (!propENV.isEmpty()) { prop.putAll(propENV); LOG.debug("Properties from OS environment variables:"); for (String key : propENV.stringPropertyNames()) { LOG.debug(" {}={}", key, propENV.getProperty(key)); } } } // special for fail-fast as we need to know this early before we set all the other options Object failFast = propENV != null ? propENV.remove("camel.main.autoconfigurationfailfast") : null; if (failFast != null) { PropertyBindingSupport.bindMandatoryProperty(camelContext, mainConfigurationProperties, "autoConfigurationFailFast", failFast, true); } else { failFast = prop.remove("camel.main.autoConfigurationFailFast"); if (failFast == null) { failFast = prop.remove("camel.main.auto-configuration-fail-fast"); } if (failFast != null) { PropertyBindingSupport.bindMandatoryProperty(camelContext, mainConfigurationProperties, "autoConfigurationFailFast", failFast, true); autoConfiguredProperties.put("camel.main.auto-configuration-fail-fast", failFast.toString()); } } } /** * Configures CamelContext from the {@link MainConfigurationProperties} properties. */ protected void doConfigureCamelContextFromMainConfiguration(CamelContext camelContext, MainConfigurationProperties config, Map<String, String> autoConfiguredProperties) throws Exception { if (config.getFileConfigurations() != null) { String[] locs = config.getFileConfigurations().split(","); for (String loc : locs) { String path = FileUtil.onlyPath(loc); if (path != null) { String pattern = loc.length() > path.length() ? loc.substring(path.length() + 1) : null; File[] files = new File(path).listFiles(f -> matches(pattern, f.getName())); if (files != null) { for (File file : files) { Properties props = new Properties(); try (FileInputStream is = new FileInputStream(file)) { props.load(is); } if (!props.isEmpty()) { if (overrideProperties == null) { // setup override properties on properties component overrideProperties = new Properties(); PropertiesComponent pc = camelContext.getPropertiesComponent(); pc.setOverrideProperties(overrideProperties); } LOG.info("Loaded additional {} properties from file: {}", props.size(), file); overrideProperties.putAll(props); } } } } } } // configure the common/default options DefaultConfigurationConfigurer.configure(camelContext, config); // lookup and configure SPI beans DefaultConfigurationConfigurer.afterPropertiesSet(camelContext); // now configure context/hystrix/rest with additional properties Properties prop = camelContext.getPropertiesComponent().loadProperties(); // load properties from ENV (override existing) if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { Properties propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.component.properties."}); if (!propENV.isEmpty()) { prop.putAll(propENV); LOG.debug("Properties from OS environment variables:"); for (String key : propENV.stringPropertyNames()) { LOG.debug(" {}={}", key, propENV.getProperty(key)); } } } Map<String, Object> contextProperties = new LinkedHashMap<>(); Map<String, Object> hystrixProperties = new LinkedHashMap<>(); Map<String, Object> restProperties = new LinkedHashMap<>(); for (String key : prop.stringPropertyNames()) { if (key.startsWith("camel.context.")) { // grab the value String value = prop.getProperty(key); String option = key.substring(14); validateOptionAndValue(key, option, value); contextProperties.put(optionKey(option), value); } else if (key.startsWith("camel.hystrix.")) { // grab the value String value = prop.getProperty(key); String option = key.substring(14); validateOptionAndValue(key, option, value); hystrixProperties.put(optionKey(option), value); } else if (key.startsWith("camel.rest.")) { // grab the value String value = prop.getProperty(key); String option = key.substring(11); validateOptionAndValue(key, option, value); restProperties.put(optionKey(option), value); } } if (!contextProperties.isEmpty()) { LOG.debug("Auto-configuring CamelContext from loaded properties: {}", contextProperties.size()); setPropertiesOnTarget(camelContext, camelContext, contextProperties, null, "camel.context.", mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties); } if (!hystrixProperties.isEmpty()) { LOG.debug("Auto-configuring Hystrix EIP from loaded properties: {}", hystrixProperties.size()); ModelCamelContext model = camelContext.adapt(ModelCamelContext.class); HystrixConfigurationDefinition hystrix = model.getHystrixConfiguration(null); if (hystrix == null) { hystrix = new HystrixConfigurationDefinition(); model.setHystrixConfiguration(hystrix); } setPropertiesOnTarget(camelContext, hystrix, hystrixProperties, null, "camel.hsytrix.", mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties); } if (!restProperties.isEmpty()) { LOG.debug("Auto-configuring Rest DSL from loaded properties: {}", restProperties.size()); ModelCamelContext model = camelContext.adapt(ModelCamelContext.class); RestConfiguration rest = model.getRestConfiguration(); if (rest == null) { rest = new RestConfiguration(); model.setRestConfiguration(rest); } setPropertiesOnTarget(camelContext, rest, restProperties, null, "camel.rest.", mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties); } // log which options was not set if (!contextProperties.isEmpty()) { contextProperties.forEach((k, v) -> { LOG.warn("Property not auto-configured: camel.context.{}={} on bean: {}", k, v, camelContext); }); } if (!hystrixProperties.isEmpty()) { ModelCamelContext model = camelContext.adapt(ModelCamelContext.class); HystrixConfigurationDefinition hystrix = model.getHystrixConfiguration(null); hystrixProperties.forEach((k, v) -> { LOG.warn("Property not auto-configured: camel.hystrix.{}={} on bean: {}", k, v, hystrix); }); } if (!restProperties.isEmpty()) { ModelCamelContext model = camelContext.adapt(ModelCamelContext.class); RestConfiguration rest = model.getRestConfiguration(); restProperties.forEach((k, v) -> { LOG.warn("Property not auto-configured: camel.rest.{}={} on bean: {}", k, v, rest); }); } } protected void autoConfigurationPropertiesComponent(CamelContext camelContext, Map<String, String> autoConfiguredProperties) throws Exception { // load properties Properties prop = camelContext.getPropertiesComponent().loadProperties(); // load properties from ENV (override existing) if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { Properties propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.component.properties."}); if (!propENV.isEmpty()) { prop.putAll(propENV); } } Map<String, Object> properties = new LinkedHashMap<>(); for (String key : prop.stringPropertyNames()) { if (key.startsWith("camel.component.properties.")) { int dot = key.indexOf(".", 26); String option = dot == -1 ? "" : key.substring(dot + 1); String value = prop.getProperty(key, ""); validateOptionAndValue(key, option, value); properties.put(optionKey(option), value); } } if (!properties.isEmpty()) { LOG.debug("Auto-configuring properties component from loaded properties: {}", properties.size()); setPropertiesOnTarget(camelContext, camelContext.getPropertiesComponent(), properties, null, "camel.component.properties.", mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties); } // log which options was not set if (!properties.isEmpty()) { properties.forEach((k, v) -> { LOG.warn("Property not auto-configured: camel.component.properties.{}={} on object: {}", k, v, camelContext.getPropertiesComponent()); }); } } protected void autoConfigurationMainConfiguration(CamelContext camelContext, MainConfigurationProperties config, Map<String, String> autoConfiguredProperties) throws Exception { // load properties Properties prop = camelContext.getPropertiesComponent().loadProperties(); // load properties from ENV (override existing) if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { Properties propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.main."}); if (!propENV.isEmpty()) { prop.putAll(propENV); } } Map<String, Object> properties = new LinkedHashMap<>(); for (String key : prop.stringPropertyNames()) { if (key.startsWith("camel.main.")) { // grab the value String value = prop.getProperty(key); String option = key.substring(11); validateOptionAndValue(key, option, value); properties.put(optionKey(option), value); } } if (!properties.isEmpty()) { LOG.debug("Auto-configuring main from loaded properties: {}", properties.size()); setPropertiesOnTarget(camelContext, config, properties, null, "camel.main.", mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties); } // log which options was not set if (!properties.isEmpty()) { properties.forEach((k, v) -> { LOG.warn("Property not auto-configured: camel.main.{}={} on bean: {}", k, v, config); }); } } protected void autoConfigurationFromProperties(CamelContext camelContext, Map<String, String> autoConfiguredProperties) throws Exception { // load optional META-INF/services/org/apache/camel/autowire.properties Properties prop = new OrderedProperties(); try { InputStream is = camelContext.getClassResolver().loadResourceAsStream("/META-INF/services/org/apache/camel/autowire.properties"); if (is != null) { prop.load(is); if (!prop.isEmpty()) { LOG.info("Autowired enabled from classpath: META-INF/services/org/apache/camel/autowire.properties with {} properties", prop.size()); if (LOG.isDebugEnabled()) { LOG.debug("Properties from classpath: META-INF/services/org/apache/camel/autowire.properties:"); for (String key : prop.stringPropertyNames()) { LOG.debug(" {}={}", key, prop.getProperty(key)); } } } IOHelper.close(is); } } catch (Throwable e) { // ignore as this file is optional } // load properties from properties component (override existing) Properties propPC = camelContext.getPropertiesComponent().loadProperties(); prop.putAll(propPC); // load properties from ENV (override existing) if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { Properties propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.component.", "camel.dataformat.", "camel.language."}); if (!propENV.isEmpty()) { prop.putAll(propENV); } } Map<PropertyOptionKey, Map<String, Object>> properties = new LinkedHashMap<>(); for (String key : prop.stringPropertyNames()) { if (key.startsWith("camel.component.")) { // grab name int dot = key.indexOf(".", 16); String name = dot == -1 ? key.substring(16) : key.substring(16, dot); // skip properties as its already configured earlier if ("properties".equals(name)) { continue; } Component component = camelContext.getComponent(name); if (component == null) { throw new IllegalArgumentException("Error configuring property: " + key + " because cannot find component with name " + name + ". Make sure you have the component on the classpath"); } String option = dot == -1 ? "" : key.substring(dot + 1); String value = prop.getProperty(key, ""); String prefix = dot == -1 ? "" : key.substring(0, dot); validateOptionAndValue(key, option, value); PropertyOptionKey pok = new PropertyOptionKey(key, component, prefix); Map<String, Object> values = properties.getOrDefault(pok, new LinkedHashMap<>()); // we ignore case for property keys (so we should store them in canonical style values.put(optionKey(option), value); properties.put(pok, values); } if (key.startsWith("camel.dataformat.")) { // grab name int dot = key.indexOf(".", 17); String name = dot == -1 ? key.substring(17) : key.substring(17, dot); DataFormat dataformat = camelContext.resolveDataFormat(name); if (dataformat == null) { throw new IllegalArgumentException("Error configuring property: " + key + " because cannot find dataformat with name " + name + ". Make sure you have the dataformat on the classpath"); } String option = dot == -1 ? "" : key.substring(dot + 1); String value = prop.getProperty(key, ""); String prefix = dot == -1 ? "" : key.substring(0, dot); validateOptionAndValue(key, option, value); PropertyOptionKey pok = new PropertyOptionKey(key, dataformat, prefix); Map<String, Object> values = properties.getOrDefault(pok, new LinkedHashMap<>()); values.put(optionKey(option), value); properties.put(pok, values); } if (key.startsWith("camel.language.")) { // grab name int dot = key.indexOf(".", 15); String name = dot == -1 ? key.substring(15) : key.substring(15, dot); Language language; try { language = camelContext.resolveLanguage(name); } catch (NoSuchLanguageException e) { throw new IllegalArgumentException("Error configuring property: " + key + " because cannot find language with name " + name + ". Make sure you have the language on the classpath"); } String option = dot == -1 ? "" : key.substring(dot + 1); String value = prop.getProperty(key, ""); String prefix = dot == -1 ? "" : key.substring(0, dot); validateOptionAndValue(key, option, value); PropertyOptionKey pok = new PropertyOptionKey(key, language, prefix); Map<String, Object> values = properties.getOrDefault(pok, new LinkedHashMap<>()); values.put(optionKey(option), value); properties.put(pok, values); } } if (!properties.isEmpty()) { long total = properties.values().stream().mapToLong(Map::size).sum(); LOG.debug("Auto-configuring {} components/dataformat/languages from loaded properties: {}", properties.size(), total); } for (PropertyOptionKey pok : properties.keySet()) { Map<String, Object> values = properties.get(pok); String optionKey = pok.getKey().substring(pok.getOptionPrefix().length() + 1); setPropertiesOnTarget(camelContext, pok.getInstance(), values, optionKey, pok.getOptionPrefix(), mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties); } // log which options was not set if (!properties.isEmpty()) { for (PropertyOptionKey pok : properties.keySet()) { Map<String, Object> values = properties.get(pok); values.forEach((k, v) -> { String stringValue = v != null ? v.toString() : null; LOG.warn("Property ({}={}) not auto-configured with name: {} on bean: {} with value: {}", pok.getKey(), stringValue, k, pok.getInstance(), stringValue); }); } } } protected void autowireConfigurationFromRegistry(CamelContext camelContext, boolean deepNesting) throws Exception { camelContext.addLifecycleStrategy(new LifecycleStrategySupport() { @Override public void onComponentAdd(String name, Component component) { PropertyBindingSupport.autowireSingletonPropertiesFromRegistry(camelContext, component, false, deepNesting, (obj, propertyName, type, value) -> { LOG.info("Autowired property: {} on component: {} as exactly one instance of type: {} found in the registry", propertyName, component.getClass().getSimpleName(), type.getName()); }); } }); } protected static Properties loadEnvironmentVariablesAsProperties(String[] prefixes) { Properties answer = new OrderedProperties(); if (prefixes == null || prefixes.length == 0) { return answer; } for (String prefix : prefixes) { final String pk = prefix.toUpperCase(Locale.US).replaceAll("[^\\w]", "-"); final String pk2 = pk.replace('-', '_'); System.getenv().forEach((k, v) -> { k = k.toUpperCase(Locale.US); if (k.startsWith(pk) || k.startsWith(pk2)) { String key = k.toLowerCase(Locale.US).replace('_', '.'); answer.put(key, v); } }); } return answer; } protected void validateOptionAndValue(String key, String option, String value) { if (ObjectHelper.isEmpty(option)) { throw new IllegalArgumentException("Error configuring property: " + key + " because option is empty"); } if (ObjectHelper.isEmpty(value)) { throw new IllegalArgumentException("Error configuring property: " + key + " because value is empty"); } } private static String optionKey(String key) { // as we ignore case for property names we should use keys in same case and without dashes key = StringHelper.replaceAll(key, "-", ""); key = key.toLowerCase(Locale.US); return key; } public void addRouteBuilder(RouteBuilder routeBuilder) { getRouteBuilders().add(routeBuilder); } public void addRouteBuilder(Class... routeBuilder) { String existing = routeBuilderClasses; if (existing == null) { existing = ""; } if (routeBuilder != null) { for (Class clazz : routeBuilder) { if (!existing.isEmpty()) { existing = existing + ","; } existing = existing + clazz.getName(); } } setRouteBuilderClasses(existing); } private static boolean setPropertiesOnTarget(CamelContext context, Object target, Map<String, Object> properties, String optionKey, String optionPrefix, boolean failIfNotSet, boolean ignoreCase, Map<String, String> autoConfiguredProperties) throws Exception { ObjectHelper.notNull(context, "context"); ObjectHelper.notNull(target, "target"); ObjectHelper.notNull(properties, "properties"); boolean rc = false; Iterator it = properties.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = (Map.Entry) it.next(); String name = entry.getKey(); Object value = entry.getValue(); String stringValue = value != null ? value.toString() : null; String key = name; if (optionPrefix != null && optionKey != null) { key = optionPrefix + optionKey; } else if (optionPrefix != null) { key = optionPrefix + name; } LOG.debug("Configuring property: {}={} on bean: {}", key, stringValue, target); try { boolean hit; if (failIfNotSet) { PropertyBindingSupport.bindMandatoryProperty(context, target, name, stringValue, ignoreCase); hit = true; } else { hit = PropertyBindingSupport.bindProperty(context, target, name, stringValue, ignoreCase); } if (hit) { it.remove(); rc = true; LOG.debug("Configured property: {}={} on bean: {}", key, stringValue, target); autoConfiguredProperties.put(key, stringValue); } } catch (PropertyBindingException e) { if (failIfNotSet) { // enrich the error with more precise details with option prefix and key throw new PropertyBindingException(e.getTarget(), e.getPropertyName(), e.getValue(), optionPrefix, optionKey, e.getCause()); } else { LOG.debug("Error configuring property (" + key + ") with name: " + name + ") on bean: " + target + " with value: " + stringValue + ". This exception is ignored as failIfNotSet=false.", e); } } } return rc; } private static final class PropertyOptionKey { private final String key; private final Object instance; private final String optionPrefix; private PropertyOptionKey(String key, Object instance, String optionPrefix) { this.key = key; this.instance = instance; this.optionPrefix = optionPrefix; } public String getKey() { return key; } public Object getInstance() { return instance; } public String getOptionPrefix() { return optionPrefix; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PropertyOptionKey that = (PropertyOptionKey) o; return key.equals(that.key) && instance.equals(that.instance); } @Override public int hashCode() { return Objects.hash(key, instance); } } public abstract class Option { private String abbreviation; private String fullName; private String description; protected Option(String abbreviation, String fullName, String description) { this.abbreviation = "-" + abbreviation; this.fullName = "-" + fullName; this.description = description; } public boolean processOption(String arg, LinkedList<String> remainingArgs) { if (arg.equalsIgnoreCase(abbreviation) || fullName.startsWith(arg)) { doProcess(arg, remainingArgs); return true; } return false; } public String getAbbreviation() { return abbreviation; } public String getDescription() { return description; } public String getFullName() { return fullName; } public String getInformation() { return " " + getAbbreviation() + " or " + getFullName() + " = " + getDescription(); } protected abstract void doProcess(String arg, LinkedList<String> remainingArgs); } public abstract class ParameterOption extends Option { private String parameterName; protected ParameterOption(String abbreviation, String fullName, String description, String parameterName) { super(abbreviation, fullName, description); this.parameterName = parameterName; } protected void doProcess(String arg, LinkedList<String> remainingArgs) { if (remainingArgs.isEmpty()) { System.err.println("Expected fileName for "); showOptions(); completed(); } else { String parameter = remainingArgs.removeFirst(); doProcess(arg, parameter, remainingArgs); } } public String getInformation() { return " " + getAbbreviation() + " or " + getFullName() + " <" + parameterName + "> = " + getDescription(); } protected abstract void doProcess(String arg, String parameter, LinkedList<String> remainingArgs); } }
core/camel-main/src/main/java/org/apache/camel/main/MainSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.main; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.ExtendedCamelContext; import org.apache.camel.NoSuchLanguageException; import org.apache.camel.ProducerTemplate; import org.apache.camel.PropertyBindingException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.HystrixConfigurationDefinition; import org.apache.camel.model.Model; import org.apache.camel.model.ModelCamelContext; import org.apache.camel.model.RouteDefinition; import org.apache.camel.spi.CamelBeanPostProcessor; import org.apache.camel.spi.DataFormat; import org.apache.camel.spi.EventNotifier; import org.apache.camel.spi.Language; import org.apache.camel.spi.PropertiesComponent; import org.apache.camel.spi.RestConfiguration; import org.apache.camel.support.LifecycleStrategySupport; import org.apache.camel.support.PropertyBindingSupport; import org.apache.camel.support.service.ServiceHelper; import org.apache.camel.support.service.ServiceSupport; import org.apache.camel.util.FileUtil; import org.apache.camel.util.IOHelper; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.OrderedProperties; import org.apache.camel.util.StringHelper; import org.apache.camel.util.concurrent.ThreadHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.camel.support.ObjectHelper.invokeMethod; import static org.apache.camel.util.ReflectionHelper.findMethod; import static org.apache.camel.util.StringHelper.matches; /** * Base class for main implementations to allow starting up a JVM with Camel embedded. */ public abstract class MainSupport extends ServiceSupport { protected static final Logger LOG = LoggerFactory.getLogger(MainSupport.class); protected static final int UNINITIALIZED_EXIT_CODE = Integer.MIN_VALUE; protected static final int DEFAULT_EXIT_CODE = 0; protected final List<MainListener> listeners = new ArrayList<>(); protected final List<Option> options = new ArrayList<>(); protected final CountDownLatch latch = new CountDownLatch(1); protected final AtomicBoolean completed = new AtomicBoolean(false); protected final AtomicInteger exitCode = new AtomicInteger(UNINITIALIZED_EXIT_CODE); protected volatile CamelContext camelContext; protected volatile ProducerTemplate camelTemplate; protected final MainConfigurationProperties mainConfigurationProperties = new MainConfigurationProperties(); protected List<RouteBuilder> routeBuilders = new ArrayList<>(); protected String routeBuilderClasses; protected List<Object> configurations = new ArrayList<>(); protected String configurationClasses; protected String propertyPlaceholderLocations; protected Properties initialProperties; protected Properties overrideProperties; /** * A class for intercepting the hang up signal and do a graceful shutdown of the Camel. */ private static final class HangupInterceptor extends Thread { Logger log = LoggerFactory.getLogger(this.getClass()); final MainSupport mainInstance; HangupInterceptor(MainSupport main) { mainInstance = main; } @Override public void run() { log.info("Received hang up - stopping the main instance."); try { mainInstance.stop(); } catch (Exception ex) { log.warn("Error during stopping the main instance.", ex); } } } protected MainSupport(Class... configurationClasses) { this(); addConfigurationClass(configurationClasses); } protected MainSupport() { addOption(new Option("h", "help", "Displays the help screen") { protected void doProcess(String arg, LinkedList<String> remainingArgs) { showOptions(); completed(); } }); addOption(new ParameterOption("r", "routers", "Sets the router builder classes which will be loaded while starting the camel context", "routerBuilderClasses") { @Override protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { setRouteBuilderClasses(parameter); } }); addOption(new ParameterOption("d", "duration", "Sets the time duration (seconds) that the application will run for before terminating.", "duration") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { // skip second marker to be backwards compatible if (parameter.endsWith("s") || parameter.endsWith("S")) { parameter = parameter.substring(0, parameter.length() - 1); } configure().setDurationMaxSeconds(Integer.parseInt(parameter)); } }); addOption(new ParameterOption("dm", "durationMaxMessages", "Sets the duration of maximum number of messages that the application will process before terminating.", "durationMaxMessages") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { configure().setDurationMaxMessages(Integer.parseInt(parameter)); } }); addOption(new ParameterOption("di", "durationIdle", "Sets the idle time duration (seconds) duration that the application can be idle before terminating.", "durationIdle") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { // skip second marker to be backwards compatible if (parameter.endsWith("s") || parameter.endsWith("S")) { parameter = parameter.substring(0, parameter.length() - 1); } configure().setDurationMaxIdleSeconds(Integer.parseInt(parameter)); } }); addOption(new Option("t", "trace", "Enables tracing") { protected void doProcess(String arg, LinkedList<String> remainingArgs) { enableTrace(); } }); addOption(new ParameterOption("e", "exitcode", "Sets the exit code if duration was hit", "exitcode") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { configure().setDurationHitExitCode(Integer.parseInt(parameter)); } }); addOption(new ParameterOption("pl", "propertiesLocation", "Sets location(s) to load properties, such as from classpath or file system.", "propertiesLocation") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { setPropertyPlaceholderLocations(parameter); } }); } /** * Runs this process with the given arguments, and will wait until completed, or the JVM terminates. */ public void run() throws Exception { if (!completed.get()) { internalBeforeStart(); // if we have an issue starting then propagate the exception to caller beforeStart(); start(); try { afterStart(); waitUntilCompleted(); internalBeforeStop(); beforeStop(); stop(); afterStop(); } catch (Exception e) { // however while running then just log errors LOG.error("Failed: {}", e, e); } } } /** * Disable the hangup support. No graceful stop by calling stop() on a * Hangup signal. */ public void disableHangupSupport() { mainConfigurationProperties.setHangupInterceptorEnabled(false); } /** * Hangup support is enabled by default. */ public void enableHangupSupport() { mainConfigurationProperties.setHangupInterceptorEnabled(true); } /** * Adds a {@link org.apache.camel.main.MainListener} to receive callbacks when the main is started or stopping * * @param listener the listener */ public void addMainListener(MainListener listener) { listeners.add(listener); } /** * Removes the {@link org.apache.camel.main.MainListener} * * @param listener the listener */ public void removeMainListener(MainListener listener) { listeners.remove(listener); } /** * Callback to run custom logic before CamelContext is being started. * <p/> * It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void beforeStart() throws Exception { for (MainListener listener : listeners) { listener.beforeStart(this); } } /** * Callback to run custom logic after CamelContext has been started. * <p/> * It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void afterStart() throws Exception { for (MainListener listener : listeners) { listener.afterStart(this); } } private void internalBeforeStart() { if (mainConfigurationProperties.isHangupInterceptorEnabled()) { String threadName = ThreadHelper.resolveThreadName(null, "CamelHangupInterceptor"); Thread task = new HangupInterceptor(this); task.setName(threadName); Runtime.getRuntime().addShutdownHook(task); } } /** * Callback to run custom logic before CamelContext is being stopped. * <p/> * It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void beforeStop() throws Exception { for (MainListener listener : listeners) { listener.beforeStop(this); } } /** * Callback to run custom logic after CamelContext has been stopped. * <p/> * It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void afterStop() throws Exception { for (MainListener listener : listeners) { listener.afterStop(this); } } private void internalBeforeStop() { try { if (camelTemplate != null) { ServiceHelper.stopService(camelTemplate); camelTemplate = null; } } catch (Exception e) { LOG.debug("Error stopping camelTemplate due " + e.getMessage() + ". This exception is ignored.", e); } } /** * Marks this process as being completed. */ public void completed() { completed.set(true); exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, DEFAULT_EXIT_CODE); latch.countDown(); } /** * Displays the command line options. */ public void showOptions() { showOptionsHeader(); for (Option option : options) { System.out.println(option.getInformation()); } } /** * Parses the command line arguments. */ public void parseArguments(String[] arguments) { LinkedList<String> args = new LinkedList<>(Arrays.asList(arguments)); boolean valid = true; while (!args.isEmpty()) { String arg = args.removeFirst(); boolean handled = false; for (Option option : options) { if (option.processOption(arg, args)) { handled = true; break; } } if (!handled) { System.out.println("Unknown option: " + arg); System.out.println(); valid = false; break; } } if (!valid) { showOptions(); completed(); } } public void addOption(Option option) { options.add(option); } /** * To configure options on Camel Main. */ public MainConfigurationProperties configure() { return mainConfigurationProperties; } @Deprecated public int getDuration() { return mainConfigurationProperties.getDurationMaxSeconds(); } /** * Sets the duration (in seconds) to run the application until it * should be terminated. Defaults to -1. Any value <= 0 will run forever. * @deprecated use {@link #configure()} */ @Deprecated public void setDuration(int duration) { mainConfigurationProperties.setDurationMaxSeconds(duration); } @Deprecated public int getDurationIdle() { return mainConfigurationProperties.getDurationMaxIdleSeconds(); } /** * Sets the maximum idle duration (in seconds) when running the application, and * if there has been no message processed after being idle for more than this duration * then the application should be terminated. * Defaults to -1. Any value <= 0 will run forever. * @deprecated use {@link #configure()} */ @Deprecated public void setDurationIdle(int durationIdle) { mainConfigurationProperties.setDurationMaxIdleSeconds(durationIdle); } @Deprecated public int getDurationMaxMessages() { return mainConfigurationProperties.getDurationMaxMessages(); } /** * Sets the duration to run the application to process at most max messages until it * should be terminated. Defaults to -1. Any value <= 0 will run forever. * @deprecated use {@link #configure()} */ @Deprecated public void setDurationMaxMessages(int durationMaxMessages) { mainConfigurationProperties.setDurationMaxMessages(durationMaxMessages); } /** * Sets the exit code for the application if duration was hit * @deprecated use {@link #configure()} */ @Deprecated public void setDurationHitExitCode(int durationHitExitCode) { mainConfigurationProperties.setDurationHitExitCode(durationHitExitCode); } @Deprecated public int getDurationHitExitCode() { return mainConfigurationProperties.getDurationHitExitCode(); } public int getExitCode() { return exitCode.get(); } public String getConfigurationClasses() { return configurationClasses; } public void setConfigurationClasses(String configurations) { this.configurationClasses = configurations; } public void addConfigurationClass(Class... configuration) { String existing = configurationClasses; if (existing == null) { existing = ""; } if (configuration != null) { for (Class clazz : configuration) { if (!existing.isEmpty()) { existing = existing + ","; } existing = existing + clazz.getName(); } } setConfigurationClasses(existing); } public void addConfiguration(Object configuration) { configurations.add(configuration); } public String getRouteBuilderClasses() { return routeBuilderClasses; } public void setRouteBuilderClasses(String builders) { this.routeBuilderClasses = builders; } public String getPropertyPlaceholderLocations() { return propertyPlaceholderLocations; } /** * A list of locations to add for loading properties. * You can use comma to separate multiple locations. */ public void setPropertyPlaceholderLocations(String location) { this.propertyPlaceholderLocations = location; } @Deprecated public boolean isAutoConfigurationEnabled() { return mainConfigurationProperties.isAutoConfigurationEnabled(); } /** * Whether auto configuration of components/dataformats/languages is enabled or not. * When enabled the configuration parameters are loaded from the properties component * and configured as defaults (similar to spring-boot auto-configuration). You can prefix * the parameters in the properties file with: * - camel.component.name.option1=value1 * - camel.component.name.option2=value2 * - camel.dataformat.name.option1=value1 * - camel.dataformat.name.option2=value2 * - camel.language.name.option1=value1 * - camel.language.name.option2=value2 * Where name is the name of the component, dataformat or language such as seda,direct,jaxb. * <p/> * The auto configuration also works for any options on components * that is a complex type (not standard Java type) and there has been an explicit single * bean instance registered to the Camel registry via the {@link org.apache.camel.spi.Registry#bind(String, Object)} method * or by using the {@link org.apache.camel.BindToRegistry} annotation style. * <p/> * This option is default enabled. * @deprecated use {@link #configure()} */ @Deprecated public void setAutoConfigurationEnabled(boolean autoConfigurationEnabled) { mainConfigurationProperties.setAutoConfigurationEnabled(autoConfigurationEnabled); } public Properties getInitialProperties() { return initialProperties; } /** * Sets initial properties for the properties component, * which will be used before any locations are resolved. */ public void setInitialProperties(Properties initialProperties) { this.initialProperties = initialProperties; } public Properties getOverrideProperties() { return overrideProperties; } /** * Sets a special list of override properties that take precedence * and will use first, if a property exist. */ public void setOverrideProperties(Properties overrideProperties) { this.overrideProperties = overrideProperties; } public boolean isTrace() { return mainConfigurationProperties.isTracing(); } public void enableTrace() { mainConfigurationProperties.setTracing(true); } protected void doStop() throws Exception { // call completed to properly stop as we count down the waiting latch completed(); } protected void doStart() throws Exception { } protected void waitUntilCompleted() { while (!completed.get()) { try { int idle = mainConfigurationProperties.getDurationMaxIdleSeconds(); int max = mainConfigurationProperties.getDurationMaxMessages(); long sec = mainConfigurationProperties.getDurationMaxSeconds(); if (sec > 0) { LOG.info("Waiting for: {} seconds", sec); latch.await(sec, TimeUnit.SECONDS); exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, mainConfigurationProperties.getDurationHitExitCode()); completed.set(true); } else if (idle > 0 || max > 0) { if (idle > 0 && max > 0) { LOG.info("Waiting to be idle for: {} seconds or until: {} messages has been processed", idle, max); } else if (idle > 0) { LOG.info("Waiting to be idle for: {} seconds", idle); } else { LOG.info("Waiting until: {} messages has been processed", max); } exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, mainConfigurationProperties.getDurationHitExitCode()); latch.await(); completed.set(true); } else { latch.await(); } } catch (InterruptedException e) { // okay something interrupted us so terminate completed.set(true); latch.countDown(); Thread.currentThread().interrupt(); } } } /** * Parses the command line arguments then runs the program. */ public void run(String[] args) throws Exception { parseArguments(args); run(); LOG.info("MainSupport exiting code: {}", getExitCode()); } /** * Displays the header message for the command line options. */ public void showOptionsHeader() { System.out.println("Apache Camel Runner takes the following options"); System.out.println(); } public CamelContext getCamelContext() { return camelContext; } public List<RouteBuilder> getRouteBuilders() { return routeBuilders; } public void setRouteBuilders(List<RouteBuilder> routeBuilders) { this.routeBuilders = routeBuilders; } public List<Object> getConfigurations() { return configurations; } public void setConfigurations(List<Object> configurations) { this.configurations = configurations; } public List<RouteDefinition> getRouteDefinitions() { List<RouteDefinition> answer = new ArrayList<>(); if (camelContext != null) { answer.addAll(camelContext.getExtension(Model.class).getRouteDefinitions()); } return answer; } public ProducerTemplate getCamelTemplate() throws Exception { if (camelTemplate == null) { camelTemplate = findOrCreateCamelTemplate(); } return camelTemplate; } protected abstract ProducerTemplate findOrCreateCamelTemplate(); protected abstract CamelContext createCamelContext(); protected void initCamelContext() throws Exception { camelContext = createCamelContext(); postProcessCamelContext(camelContext); } protected void loadRouteBuilders(CamelContext camelContext) throws Exception { // lets use Camel's bean post processor on any existing route builder classes // so the instance has some support for dependency injection CamelBeanPostProcessor postProcessor = camelContext.adapt(ExtendedCamelContext.class).getBeanPostProcessor(); for (RouteBuilder routeBuilder : getRouteBuilders()) { postProcessor.postProcessBeforeInitialization(routeBuilder, routeBuilder.getClass().getName()); postProcessor.postProcessAfterInitialization(routeBuilder, routeBuilder.getClass().getName()); } if (routeBuilderClasses != null) { String[] routeClasses = routeBuilderClasses.split(","); for (String routeClass : routeClasses) { Class<?> routeClazz = camelContext.getClassResolver().resolveClass(routeClass); // lets use Camel's injector so the class has some support for dependency injection Object builder = camelContext.getInjector().newInstance(routeClazz); if (builder instanceof RouteBuilder) { getRouteBuilders().add((RouteBuilder) builder); } else { LOG.warn("Class {} is not a RouteBuilder class", routeClazz); } } } } protected void loadConfigurations(CamelContext camelContext) throws Exception { // lets use Camel's bean post processor on any existing configuration classes // so the instance has some support for dependency injection CamelBeanPostProcessor postProcessor = camelContext.adapt(ExtendedCamelContext.class).getBeanPostProcessor(); for (Object configuration : getConfigurations()) { postProcessor.postProcessBeforeInitialization(configuration, configuration.getClass().getName()); postProcessor.postProcessAfterInitialization(configuration, configuration.getClass().getName()); } if (configurationClasses != null) { String[] configClasses = configurationClasses.split(","); for (String configClass : configClasses) { Class<?> configClazz = camelContext.getClassResolver().resolveClass(configClass); // lets use Camel's injector so the class has some support for dependency injection Object config = camelContext.getInjector().newInstance(configClazz); getConfigurations().add(config); } } for (Object config : getConfigurations()) { // invoke configure method if exists Method method = findMethod(config.getClass(), "configure"); if (method != null) { log.info("Calling configure method on configuration class: {}", config.getClass().getName()); invokeMethod(method, config); } } } protected void postProcessCamelContext(CamelContext camelContext) throws Exception { if (propertyPlaceholderLocations != null) { PropertiesComponent pc = camelContext.getPropertiesComponent(); pc.addLocation(propertyPlaceholderLocations); if (initialProperties != null) { pc.setInitialProperties(initialProperties); } if (overrideProperties != null) { pc.setOverrideProperties(overrideProperties); } LOG.info("Using properties from: {}", propertyPlaceholderLocations); } else { // lets default to application.properties and ignore if its missing PropertiesComponent pc = camelContext.getPropertiesComponent(); pc.addLocation("classpath:application.properties"); pc.setIgnoreMissingLocation(true); if (initialProperties != null) { pc.setInitialProperties(initialProperties); } if (overrideProperties != null) { pc.setOverrideProperties(overrideProperties); } LOG.info("Using optional properties from classpath:application.properties"); } if (mainConfigurationProperties.getDurationMaxMessages() > 0 || mainConfigurationProperties.getDurationMaxIdleSeconds() > 0) { // register lifecycle so we can trigger to shutdown the JVM when maximum number of messages has been processed EventNotifier notifier = new MainDurationEventNotifier(camelContext, mainConfigurationProperties.getDurationMaxMessages(), mainConfigurationProperties.getDurationMaxIdleSeconds(), completed, latch, true); // register our event notifier ServiceHelper.startService(notifier); camelContext.getManagementStrategy().addEventNotifier(notifier); } // need to eager allow to auto configure properties component if (mainConfigurationProperties.isAutoConfigurationEnabled()) { autoConfigurationFailFast(camelContext); autoConfigurationPropertiesComponent(camelContext); autoConfigurationMainConfiguration(camelContext, mainConfigurationProperties); } // configure from main configuration properties doConfigureCamelContextFromMainConfiguration(camelContext, mainConfigurationProperties); // try to load configuration classes loadConfigurations(camelContext); // conventional configuration via properties to allow configuring options on // component, dataformat, and languages (like spring-boot auto-configuration) if (mainConfigurationProperties.isAutowireComponentProperties() || mainConfigurationProperties.isAutowireComponentPropertiesDeep()) { autoConfigurationFromRegistry(camelContext, mainConfigurationProperties.isAutowireComponentPropertiesDeep()); } if (mainConfigurationProperties.isAutoConfigurationEnabled()) { autoConfigurationFromProperties(camelContext); } // try to load the route builders loadRouteBuilders(camelContext); for (RouteBuilder routeBuilder : routeBuilders) { camelContext.addRoutes(routeBuilder); } // register lifecycle so we are notified in Camel is stopped from JMX or somewhere else camelContext.addLifecycleStrategy(new MainLifecycleStrategy(completed, latch)); // allow to do configuration before its started for (MainListener listener : listeners) { listener.configure(camelContext); } } protected void autoConfigurationFailFast(CamelContext camelContext) throws Exception { // load properties Properties prop = camelContext.getPropertiesComponent().loadProperties(); LOG.debug("Properties from Camel properties component:"); for (String key : prop.stringPropertyNames()) { LOG.debug(" {}={}", key, prop.getProperty(key)); } // special for environment-variable-enbaled as we need to know this early before we set all the other options Object envEnabled = prop.remove("camel.main.autoConfigurationEnvironmentVariablesEnabled"); if (envEnabled == null) { envEnabled = prop.remove("camel.main.auto-configuration-environment-variables-enabled"); if (envEnabled != null) { PropertyBindingSupport.bindMandatoryProperty(camelContext, mainConfigurationProperties, "autoConfigurationEnvironmentVariablesEnabled", envEnabled, true); } } // load properties from ENV (override existing) Properties propENV = null; if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.main."}); if (!propENV.isEmpty()) { prop.putAll(propENV); LOG.debug("Properties from OS environment variables:"); for (String key : propENV.stringPropertyNames()) { LOG.debug(" {}={}", key, propENV.getProperty(key)); } } } // special for fail-fast as we need to know this early before we set all the other options Object failFast = propENV != null ? propENV.remove("camel.main.autoconfigurationfailfast") : null; if (failFast != null) { PropertyBindingSupport.bindMandatoryProperty(camelContext, mainConfigurationProperties, "autoConfigurationFailFast", failFast, true); } else { failFast = prop.remove("camel.main.autoConfigurationFailFast"); if (failFast == null) { failFast = prop.remove("camel.main.auto-configuration-fail-fast"); } if (failFast != null) { PropertyBindingSupport.bindMandatoryProperty(camelContext, mainConfigurationProperties, "autoConfigurationFailFast", failFast, true); } } } /** * Configures CamelContext from the {@link MainConfigurationProperties} properties. */ protected void doConfigureCamelContextFromMainConfiguration(CamelContext camelContext, MainConfigurationProperties config) throws Exception { if (config.getFileConfigurations() != null) { String[] locs = config.getFileConfigurations().split(","); for (String loc : locs) { String path = FileUtil.onlyPath(loc); if (path != null) { String pattern = loc.length() > path.length() ? loc.substring(path.length() + 1) : null; File[] files = new File(path).listFiles(f -> matches(pattern, f.getName())); if (files != null) { for (File file : files) { Properties props = new Properties(); try (FileInputStream is = new FileInputStream(file)) { props.load(is); } if (!props.isEmpty()) { if (overrideProperties == null) { // setup override properties on properties component overrideProperties = new Properties(); PropertiesComponent pc = camelContext.getPropertiesComponent(); pc.setOverrideProperties(overrideProperties); } LOG.info("Loaded additional {} properties from file: {}", props.size(), file); overrideProperties.putAll(props); } } } } } } // configure the common/default options DefaultConfigurationConfigurer.configure(camelContext, config); // lookup and configure SPI beans DefaultConfigurationConfigurer.afterPropertiesSet(camelContext); // now configure context/hystrix/rest with additional properties Properties prop = camelContext.getPropertiesComponent().loadProperties(); // load properties from ENV (override existing) if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { Properties propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.component.properties."}); if (!propENV.isEmpty()) { prop.putAll(propENV); LOG.debug("Properties from OS environment variables:"); for (String key : propENV.stringPropertyNames()) { LOG.debug(" {}={}", key, propENV.getProperty(key)); } } } Map<String, Object> contextProperties = new LinkedHashMap<>(); Map<String, Object> hystrixProperties = new LinkedHashMap<>(); Map<String, Object> restProperties = new LinkedHashMap<>(); for (String key : prop.stringPropertyNames()) { if (key.startsWith("camel.context.")) { // grab the value String value = prop.getProperty(key); String option = key.substring(14); validateOptionAndValue(key, option, value); contextProperties.put(optionKey(option), value); } else if (key.startsWith("camel.hystrix.")) { // grab the value String value = prop.getProperty(key); String option = key.substring(14); validateOptionAndValue(key, option, value); hystrixProperties.put(optionKey(option), value); } else if (key.startsWith("camel.rest.")) { // grab the value String value = prop.getProperty(key); String option = key.substring(11); validateOptionAndValue(key, option, value); restProperties.put(optionKey(option), value); } } if (!contextProperties.isEmpty()) { LOG.info("Auto configuring CamelContext from loaded properties: {}", contextProperties.size()); setPropertiesOnTarget(camelContext, camelContext, contextProperties, null, "camel.context.", mainConfigurationProperties.isAutoConfigurationFailFast(), true); } if (!hystrixProperties.isEmpty()) { LOG.info("Auto configuring Hystrix EIP from loaded properties: {}", hystrixProperties.size()); ModelCamelContext model = camelContext.adapt(ModelCamelContext.class); HystrixConfigurationDefinition hystrix = model.getHystrixConfiguration(null); if (hystrix == null) { hystrix = new HystrixConfigurationDefinition(); model.setHystrixConfiguration(hystrix); } setPropertiesOnTarget(camelContext, hystrix, hystrixProperties, null, "camel.hsytrix.", mainConfigurationProperties.isAutoConfigurationFailFast(), true); } if (!restProperties.isEmpty()) { LOG.info("Auto configuring Rest DSL from loaded properties: {}", restProperties.size()); ModelCamelContext model = camelContext.adapt(ModelCamelContext.class); RestConfiguration rest = model.getRestConfiguration(); if (rest == null) { rest = new RestConfiguration(); model.setRestConfiguration(rest); } setPropertiesOnTarget(camelContext, rest, restProperties, null, "camel.rest.", mainConfigurationProperties.isAutoConfigurationFailFast(), true); } // log which options was not set if (!contextProperties.isEmpty()) { contextProperties.forEach((k, v) -> { LOG.warn("Property not auto configured: camel.context.{}={} on object: {}", k, v, camelContext); }); } if (!hystrixProperties.isEmpty()) { ModelCamelContext model = camelContext.adapt(ModelCamelContext.class); HystrixConfigurationDefinition hystrix = model.getHystrixConfiguration(null); hystrixProperties.forEach((k, v) -> { LOG.warn("Property not auto configured: camel.hystrix.{}={} on object: {}", k, v, hystrix); }); } if (!restProperties.isEmpty()) { ModelCamelContext model = camelContext.adapt(ModelCamelContext.class); RestConfiguration rest = model.getRestConfiguration(); restProperties.forEach((k, v) -> { LOG.warn("Property not auto configured: camel.rest.{}={} on object: {}", k, v, rest); }); } } protected void autoConfigurationPropertiesComponent(CamelContext camelContext) throws Exception { // load properties Properties prop = camelContext.getPropertiesComponent().loadProperties(); // load properties from ENV (override existing) if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { Properties propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.component.properties."}); if (!propENV.isEmpty()) { prop.putAll(propENV); } } Map<String, Object> properties = new LinkedHashMap<>(); for (String key : prop.stringPropertyNames()) { if (key.startsWith("camel.component.properties.")) { int dot = key.indexOf(".", 26); String option = dot == -1 ? "" : key.substring(dot + 1); String value = prop.getProperty(key, ""); validateOptionAndValue(key, option, value); properties.put(optionKey(option), value); } } if (!properties.isEmpty()) { LOG.info("Auto configuring properties component from loaded properties: {}", properties.size()); setPropertiesOnTarget(camelContext, camelContext.getPropertiesComponent(), properties, null, "camel.component.properties.", mainConfigurationProperties.isAutoConfigurationFailFast(), true); } // log which options was not set if (!properties.isEmpty()) { properties.forEach((k, v) -> { LOG.warn("Property not auto configured: camel.component.properties.{}={} on object: {}", k, v, camelContext.getPropertiesComponent()); }); } } protected void autoConfigurationMainConfiguration(CamelContext camelContext, MainConfigurationProperties config) throws Exception { // load properties Properties prop = camelContext.getPropertiesComponent().loadProperties(); // load properties from ENV (override existing) if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { Properties propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.main."}); if (!propENV.isEmpty()) { prop.putAll(propENV); } } Map<String, Object> properties = new LinkedHashMap<>(); for (String key : prop.stringPropertyNames()) { if (key.startsWith("camel.main.")) { // grab the value String value = prop.getProperty(key); String option = key.substring(11); validateOptionAndValue(key, option, value); properties.put(optionKey(option), value); } } if (!properties.isEmpty()) { LOG.info("Auto configuring main from loaded properties: {}", properties.size()); setPropertiesOnTarget(camelContext, config, properties, null, "camel.main.", mainConfigurationProperties.isAutoConfigurationFailFast(), true); } // log which options was not set if (!properties.isEmpty()) { properties.forEach((k, v) -> { LOG.warn("Property not auto configured: camel.main.{}={} on object: {}", k, v, config); }); } } protected void autoConfigurationFromProperties(CamelContext camelContext) throws Exception { // load optional META-INF/services/org/apache/camel/autowire.properties Properties prop = new OrderedProperties(); try { InputStream is = camelContext.getClassResolver().loadResourceAsStream("/META-INF/services/org/apache/camel/autowire.properties"); if (is != null) { prop.load(is); if (!prop.isEmpty()) { LOG.info("Loaded {} properties from classpath: META-INF/services/org/apache/camel/autowire.properties", prop.size()); if (LOG.isDebugEnabled()) { LOG.debug("Properties from classpath: META-INF/services/org/apache/camel/autowire.properties:"); for (String key : prop.stringPropertyNames()) { LOG.debug(" {}={}", key, prop.getProperty(key)); } } } IOHelper.close(is); } } catch (Throwable e) { // ignore as this file is optional } // load properties from properties component (override existing) Properties propPC = camelContext.getPropertiesComponent().loadProperties(); prop.putAll(propPC); // load properties from ENV (override existing) if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) { Properties propENV = loadEnvironmentVariablesAsProperties(new String[]{"camel.component.", "camel.dataformat.", "camel.language."}); if (!propENV.isEmpty()) { prop.putAll(propENV); } } Map<PropertyOptionKey, Map<String, Object>> properties = new LinkedHashMap<>(); for (String key : prop.stringPropertyNames()) { if (key.startsWith("camel.component.")) { // grab name int dot = key.indexOf(".", 16); String name = dot == -1 ? key.substring(16) : key.substring(16, dot); // skip properties as its already configured earlier if ("properties".equals(name)) { continue; } Component component = camelContext.getComponent(name); if (component == null) { throw new IllegalArgumentException("Error configuring property: " + key + " because cannot find component with name " + name + ". Make sure you have the component on the classpath"); } String option = dot == -1 ? "" : key.substring(dot + 1); String value = prop.getProperty(key, ""); String prefix = dot == -1 ? "" : key.substring(0, dot); validateOptionAndValue(key, option, value); PropertyOptionKey pok = new PropertyOptionKey(key, component, prefix); Map<String, Object> values = properties.getOrDefault(pok, new LinkedHashMap<>()); // we ignore case for property keys (so we should store them in canonical style values.put(optionKey(option), value); properties.put(pok, values); } if (key.startsWith("camel.dataformat.")) { // grab name int dot = key.indexOf(".", 17); String name = dot == -1 ? key.substring(17) : key.substring(17, dot); DataFormat dataformat = camelContext.resolveDataFormat(name); if (dataformat == null) { throw new IllegalArgumentException("Error configuring property: " + key + " because cannot find dataformat with name " + name + ". Make sure you have the dataformat on the classpath"); } String option = dot == -1 ? "" : key.substring(dot + 1); String value = prop.getProperty(key, ""); String prefix = dot == -1 ? "" : key.substring(0, dot); validateOptionAndValue(key, option, value); PropertyOptionKey pok = new PropertyOptionKey(key, dataformat, prefix); Map<String, Object> values = properties.getOrDefault(pok, new LinkedHashMap<>()); values.put(optionKey(option), value); properties.put(pok, values); } if (key.startsWith("camel.language.")) { // grab name int dot = key.indexOf(".", 15); String name = dot == -1 ? key.substring(15) : key.substring(15, dot); Language language; try { language = camelContext.resolveLanguage(name); } catch (NoSuchLanguageException e) { throw new IllegalArgumentException("Error configuring property: " + key + " because cannot find language with name " + name + ". Make sure you have the language on the classpath"); } String option = dot == -1 ? "" : key.substring(dot + 1); String value = prop.getProperty(key, ""); String prefix = dot == -1 ? "" : key.substring(0, dot); validateOptionAndValue(key, option, value); PropertyOptionKey pok = new PropertyOptionKey(key, language, prefix); Map<String, Object> values = properties.getOrDefault(pok, new LinkedHashMap<>()); values.put(optionKey(option), value); properties.put(pok, values); } } if (!properties.isEmpty()) { long total = properties.values().stream().mapToLong(Map::size).sum(); LOG.info("Auto configuring {} components/dataformat/languages from loaded properties: {}", properties.size(), total); } for (PropertyOptionKey pok : properties.keySet()) { Map<String, Object> values = properties.get(pok); String optionKey = pok.getKey().substring(pok.getOptionPrefix().length() + 1); setPropertiesOnTarget(camelContext, pok.getInstance(), values, optionKey, pok.getOptionPrefix(), mainConfigurationProperties.isAutoConfigurationFailFast(), true); } // log which options was not set if (!properties.isEmpty()) { for (PropertyOptionKey pok : properties.keySet()) { Map<String, Object> values = properties.get(pok); values.forEach((k, v) -> { String stringValue = v != null ? v.toString() : null; LOG.warn("Property ({}={}) not auto configured with name: {} on bean: {} with value: {}", pok.getKey(), stringValue, k, pok.getInstance(), stringValue); }); } } } protected void autoConfigurationFromRegistry(CamelContext camelContext, boolean deepNesting) throws Exception { camelContext.addLifecycleStrategy(new LifecycleStrategySupport() { @Override public void onComponentAdd(String name, Component component) { PropertyBindingSupport.autowireSingletonPropertiesFromRegistry(camelContext, component, false, deepNesting, (obj, propertyName, type, value) -> { LOG.info("Auto configuring option: {} on component: {} as one instance of type: {} registered in the Camel Registry", propertyName, component.getClass().getSimpleName(), type.getName()); }); } }); } protected static Properties loadEnvironmentVariablesAsProperties(String[] prefixes) { Properties answer = new OrderedProperties(); if (prefixes == null || prefixes.length == 0) { return answer; } for (String prefix : prefixes) { final String pk = prefix.toUpperCase(Locale.US).replaceAll("[^\\w]", "-"); final String pk2 = pk.replace('-', '_'); System.getenv().forEach((k, v) -> { k = k.toUpperCase(Locale.US); if (k.startsWith(pk) || k.startsWith(pk2)) { String key = k.toLowerCase(Locale.US).replace('_', '.'); answer.put(key, v); } }); } return answer; } protected void validateOptionAndValue(String key, String option, String value) { if (ObjectHelper.isEmpty(option)) { throw new IllegalArgumentException("Error configuring property: " + key + " because option is empty"); } if (ObjectHelper.isEmpty(value)) { throw new IllegalArgumentException("Error configuring property: " + key + " because value is empty"); } } private static String optionKey(String key) { // as we ignore case for property names we should use keys in same case and without dashes key = StringHelper.replaceAll(key, "-", ""); key = key.toLowerCase(Locale.US); return key; } public void addRouteBuilder(RouteBuilder routeBuilder) { getRouteBuilders().add(routeBuilder); } public void addRouteBuilder(Class... routeBuilder) { String existing = routeBuilderClasses; if (existing == null) { existing = ""; } if (routeBuilder != null) { for (Class clazz : routeBuilder) { if (!existing.isEmpty()) { existing = existing + ","; } existing = existing + clazz.getName(); } } setRouteBuilderClasses(existing); } private static boolean setPropertiesOnTarget(CamelContext context, Object target, Map<String, Object> properties, String optionKey, String optionPrefix, boolean failIfNotSet, boolean ignoreCase) throws Exception { ObjectHelper.notNull(context, "context"); ObjectHelper.notNull(target, "target"); ObjectHelper.notNull(properties, "properties"); boolean rc = false; Iterator it = properties.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = (Map.Entry) it.next(); String name = entry.getKey(); Object value = entry.getValue(); String stringValue = value != null ? value.toString() : null; String key = name; if (optionPrefix != null && optionKey != null) { key = optionPrefix + "." + optionKey; } LOG.debug("Setting property ({}) with name: {} on bean: {} with value: {}", key, name, target, stringValue); try { boolean hit; if (failIfNotSet) { PropertyBindingSupport.bindMandatoryProperty(context, target, name, stringValue, ignoreCase); hit = true; } else { hit = PropertyBindingSupport.bindProperty(context, target, name, stringValue, ignoreCase); } if (hit) { it.remove(); rc = true; } } catch (PropertyBindingException e) { if (failIfNotSet) { // enrich the error with more precise details with option prefix and key throw new PropertyBindingException(e.getTarget(), e.getPropertyName(), e.getValue(), optionPrefix, optionKey, e.getCause()); } else { LOG.debug("Error setting property (" + key + ") with name: " + name + ") on bean: " + target + " with value: " + stringValue + ". This exception is ignored as failIfNotSet=false.", e); } } } return rc; } private static final class PropertyOptionKey { private final String key; private final Object instance; private final String optionPrefix; private PropertyOptionKey(String key, Object instance, String optionPrefix) { this.key = key; this.instance = instance; this.optionPrefix = optionPrefix; } public String getKey() { return key; } public Object getInstance() { return instance; } public String getOptionPrefix() { return optionPrefix; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PropertyOptionKey that = (PropertyOptionKey) o; return key.equals(that.key) && instance.equals(that.instance); } @Override public int hashCode() { return Objects.hash(key, instance); } } public abstract class Option { private String abbreviation; private String fullName; private String description; protected Option(String abbreviation, String fullName, String description) { this.abbreviation = "-" + abbreviation; this.fullName = "-" + fullName; this.description = description; } public boolean processOption(String arg, LinkedList<String> remainingArgs) { if (arg.equalsIgnoreCase(abbreviation) || fullName.startsWith(arg)) { doProcess(arg, remainingArgs); return true; } return false; } public String getAbbreviation() { return abbreviation; } public String getDescription() { return description; } public String getFullName() { return fullName; } public String getInformation() { return " " + getAbbreviation() + " or " + getFullName() + " = " + getDescription(); } protected abstract void doProcess(String arg, LinkedList<String> remainingArgs); } public abstract class ParameterOption extends Option { private String parameterName; protected ParameterOption(String abbreviation, String fullName, String description, String parameterName) { super(abbreviation, fullName, description); this.parameterName = parameterName; } protected void doProcess(String arg, LinkedList<String> remainingArgs) { if (remainingArgs.isEmpty()) { System.err.println("Expected fileName for "); showOptions(); completed(); } else { String parameter = remainingArgs.removeFirst(); doProcess(arg, parameter, remainingArgs); } } public String getInformation() { return " " + getAbbreviation() + " or " + getFullName() + " <" + parameterName + "> = " + getDescription(); } protected abstract void doProcess(String arg, String parameter, LinkedList<String> remainingArgs); } }
CAMEL-13686: camel-main - Refine logging output
core/camel-main/src/main/java/org/apache/camel/main/MainSupport.java
CAMEL-13686: camel-main - Refine logging output
Java
apache-2.0
3bb635f77968332c1496ecefa5268293e4cb8f21
0
JNOSQL/diana
package org.apache.diana.api.column; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; public class ColumnEntity implements Serializable { private final List<Column> columns = new ArrayList<>(); private final String columnFamily; private ColumnEntity(String columnFamily) { this.columnFamily = Objects.requireNonNull(columnFamily, "column family name is required"); } public static ColumnEntity of(String columnFamily) { return new ColumnEntity(columnFamily); } public List<Column> getColumns() { return Collections.unmodifiableList(columns); } public void add(Column column) { Objects.requireNonNull(column, "Document is required"); columns.add(column); } public String getColumnFamily() { return columnFamily; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ColumnEntity that = (ColumnEntity) o; return Objects.equals(columns, that.columns) && Objects.equals(columnFamily, that.columnFamily); } @Override public int hashCode() { return Objects.hash(columns, columnFamily); } @Override public String toString() { final StringBuilder sb = new StringBuilder("ColumnEntity{"); sb.append("columns=").append(columns); sb.append(", columnFamily='").append(columnFamily).append('\''); sb.append('}'); return sb.toString(); } }
diana-api/src/main/java/org/apache/diana/api/column/ColumnEntity.java
package org.apache.diana.api.column; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; public class ColumnEntity implements Serializable { private final Column key; private final List<Column> columns = new ArrayList<>(); private final String columnFamily; private ColumnEntity(Column key, String columnFamily) { this.key = Objects.requireNonNull(key, "key is required"); this.columnFamily = Objects.requireNonNull(columnFamily, "column family name is required"); } public static ColumnEntity of(Column key, String columnFamily) { return new ColumnEntity(key, columnFamily); } public Column getKey() { return key; } public List<Column> getColumns() { return Collections.unmodifiableList(columns); } public void add(Column column) { Objects.requireNonNull(column, "Document is required"); columns.add(column); } public String getColumnFamily() { return columnFamily; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ColumnEntity that = (ColumnEntity) o; return Objects.equals(key, that.key) && Objects.equals(columns, that.columns); } @Override public int hashCode() { return Objects.hash(key, columns); } @Override public String toString() { final StringBuilder sb = new StringBuilder("DocumentEntity{"); sb.append("key=").append(key); sb.append(", columns=").append(columns); sb.append('}'); return sb.toString(); } }
Defines new concepts in ColumnEntity
diana-api/src/main/java/org/apache/diana/api/column/ColumnEntity.java
Defines new concepts in ColumnEntity
Java
bsd-2-clause
a52d1554a5fdc68433573967d34d2084e9480934
0
TomasMikula/WellBehavedFX,TomasMikula/WellBehavedFX
package org.fxmisc.wellbehaved.event.template; import javafx.event.Event; import org.fxmisc.wellbehaved.event.InputHandler.Result; /** * Template version of {@link org.fxmisc.wellbehaved.event.InputHandler}. * * @param <S> the type of the object that will be passed into the {@link InputHandlerTemplate}'s block of code. * @param <E> the event type for which this InputMap's {@link org.fxmisc.wellbehaved.event.EventPattern} matches */ @FunctionalInterface public interface InputHandlerTemplate<S, E extends Event> { Result process(S state, E event); }
src/main/java/org/fxmisc/wellbehaved/event/template/InputHandlerTemplate.java
package org.fxmisc.wellbehaved.event.template; import javafx.event.Event; import org.fxmisc.wellbehaved.event.InputHandler.Result; @FunctionalInterface public interface InputHandlerTemplate<S, E extends Event> { Result process(S state, E event); }
Javadoc: refer readers to the non-template version for an explanation
src/main/java/org/fxmisc/wellbehaved/event/template/InputHandlerTemplate.java
Javadoc: refer readers to the non-template version for an explanation
Java
bsd-3-clause
2c1bcc8d5286c6fd9622ae9ac6c7456fafe3400d
0
aic-sri-international/aic-expresso,aic-sri-international/aic-expresso
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-expresso nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.grinder.plaindpll.theory; import static com.sri.ai.expresso.helper.Expressions.FALSE; import static com.sri.ai.expresso.helper.Expressions.TRUE; import static com.sri.ai.expresso.helper.Expressions.ZERO; import static com.sri.ai.expresso.helper.Expressions.apply; import static com.sri.ai.grinder.library.FunctorConstants.EQUALITY; import static com.sri.ai.util.Util.filter; import static com.sri.ai.util.Util.myAssert; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.sri.ai.expresso.api.Expression; import com.sri.ai.grinder.api.Rewriter; import com.sri.ai.grinder.api.RewritingProcess; import com.sri.ai.grinder.library.Disequality; import com.sri.ai.grinder.library.Equality; import com.sri.ai.grinder.library.FunctorConstants; import com.sri.ai.grinder.library.boole.And; import com.sri.ai.grinder.library.boole.Equivalence; import com.sri.ai.grinder.library.boole.ForAll; import com.sri.ai.grinder.library.boole.Implication; import com.sri.ai.grinder.library.boole.Not; import com.sri.ai.grinder.library.boole.Or; import com.sri.ai.grinder.library.boole.ThereExists; import com.sri.ai.grinder.library.controlflow.IfThenElse; import com.sri.ai.grinder.library.number.Division; import com.sri.ai.grinder.library.number.Minus; import com.sri.ai.grinder.library.number.Plus; import com.sri.ai.grinder.library.number.Times; import com.sri.ai.grinder.plaindpll.api.TermTheory; import com.sri.ai.grinder.plaindpll.core.AbstractConstraintTheory; import com.sri.ai.grinder.plaindpll.core.Contradiction; import com.sri.ai.grinder.plaindpll.core.SGDPLLT; import com.sri.ai.grinder.plaindpll.core.SimplifyLiteralGivenDisequality; import com.sri.ai.grinder.plaindpll.problemtype.Satisfiability; import com.sri.ai.grinder.plaindpll.problemtype.Tautologicality; import com.sri.ai.grinder.plaindpll.util.DPLLUtil; import com.sri.ai.util.Util; import com.sri.ai.util.base.BinaryFunction; import com.sri.ai.util.collect.CopyOnWriteMap; @Beta /** * A {@link ConstraintTheory} for equality literals. */ public class EqualityConstraintTheory extends AbstractConstraintTheory { public TermTheory termTheory; // Important: // this class generalizes the notion of a variable to a "generalized variable" (simply referred by as "variable"), // which is either a variable symbol, or an uninterpreted function application such as p(a, b, X). // It can also be seen as an indexed variable (typically represented as x_i, y_i,j etc). public EqualityConstraintTheory(TermTheory termTheory) { this.termTheory = termTheory; } public TermTheory getTermTheory() { return termTheory; } private static Rewriter plus = new Plus(); private static Rewriter times = new Times(); @Override protected boolean usesDefaultImplementationOfSimplifyByOverridingGetFunctionApplicationSimplifiersAndGetSyntacticFormTypeSimplifiers() { return true; } private static Map<String, BinaryFunction<Expression, RewritingProcess, Expression>> functionApplicationSimplifiers = Util.<String, BinaryFunction<Expression, RewritingProcess, Expression>>map( FunctorConstants.EQUALITY, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Equality.simplify(f, process), FunctorConstants.DISEQUALITY, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Disequality.simplify(f, process), FunctorConstants.AND, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> And.simplify(f), FunctorConstants.OR, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Or.simplify(f), FunctorConstants.NOT, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Not.simplify(f), FunctorConstants.IF_THEN_ELSE, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> IfThenElse.simplify(f), FunctorConstants.EQUIVALENCE, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Equivalence.simplify(f), FunctorConstants.IMPLICATION, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Implication.simplify(f), FunctorConstants.CARDINALITY, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> { Expression type = (Expression) process.getGlobalObject(f); return type == null? f : type; }, FunctorConstants.TIMES, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> times.rewrite(f, process), FunctorConstants.DIVISION, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Division.simplify(f), FunctorConstants.PLUS, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> plus.rewrite(f, process), FunctorConstants.MINUS, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> f.numberOfArguments() == 2? Minus.simplify(f) : f ); private Map<String, BinaryFunction<Expression, RewritingProcess, Expression>> syntacticFormTypeSimplifiers = Util.<String, BinaryFunction<Expression, RewritingProcess, Expression>>map( ForAll.SYNTACTIC_FORM_TYPE, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> (new SGDPLLT(new EqualityConstraintTheory(termTheory), new Tautologicality())).rewrite(f, process), ThereExists.SYNTACTIC_FORM_TYPE, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> (new SGDPLLT(new EqualityConstraintTheory(termTheory), new Satisfiability())).rewrite(f, process) ); @Override public Map<String, BinaryFunction<Expression, RewritingProcess, Expression>> getFunctionApplicationSimplifiers() { return functionApplicationSimplifiers; } @Override public Map<String, BinaryFunction<Expression, RewritingProcess, Expression>> getSyntacticFormTypeSimplifiers() { return syntacticFormTypeSimplifiers; } @Override protected String getCorrespondingSplitterFunctorOrNull(Expression expression) { String result; if (expression.hasFunctor(FunctorConstants.EQUALITY) || expression.hasFunctor(FunctorConstants.DISEQUALITY)) { // TODO: need to generalize to other types of constraint result = FunctorConstants.EQUALITY; } else { result = null; } return result; } @Override protected BinaryFunction<Expression, RewritingProcess, Expression> getSplitterApplier(boolean splitterSign, Expression splitter) { // TODO: generalize to other types of constraint BinaryFunction<Expression, RewritingProcess, Expression> applier; if (splitter.hasFunctor(FunctorConstants.EQUALITY)) { Expression term1 = splitter.get(0); Expression term2 = splitter.get(1); if (splitterSign) { applier = (Expression expression, RewritingProcess process) -> { Expression result = expression.replaceAllOccurrences(term1, term2, process); result = simplify(result, process); return result; }; } else { applier = (Expression expression, RewritingProcess process) -> { Expression result = expression.replaceAllOccurrences(new SimplifyLiteralGivenDisequality(term1, term2), process); result = simplify(result, process); return result; }; } } else { applier = null; } return applier; } @Override public EqualityTheoryConstraint makeConstraint(Collection<Expression> indices) { // TODO: generalize to other types of constraint return new EqualityTheoryConstraint(indices); } @Override public boolean isVariableTerm(Expression term, RewritingProcess process) { return termTheory.isVariableTerm(term, process); } /** A faster implementation than the default implementation, since we know more about splitters here. */ @Override public boolean splitterDependsOnIndex(Expression splitter, Collection<Expression> indices) { boolean result = indices.contains(splitter.get(0)); return result; } @Override public boolean applicationOfConstraintOnSplitterAlwaysEitherTrivializesItOrEffectsNoChangeAtAll() { return false; } /** * Represents and manipulates constraints in the theoryWithEquality of disequalities of terms (variables and constants). */ @SuppressWarnings("serial") @Beta public class EqualityTheoryConstraint extends AbstractOwnRepresentationConstraint { protected EqualitiesConstraint equalities; // TODO: make EqualitiesConstraint an interface protected NonEqualitiesConstraint nonEqualities; public EqualityTheoryConstraint(Collection<Expression> supportedIndices) { super(supportedIndices); this.equalities = new EqualitiesConstraint(getTheory(), getSupportedIndices()); this.nonEqualities = new DefaultNonEqualitiesConstraint(getTheory(), supportedIndices); } private EqualityTheoryConstraint(EqualityTheoryConstraint another) { super(another.getSupportedIndices()); this.equalities = new EqualitiesConstraint(another.equalities); this.nonEqualities = (NonEqualitiesConstraint) another.nonEqualities.clone(); } @Override public EqualityTheoryConstraint clone() { return new EqualityTheoryConstraint(this); } @Override public EqualityConstraintTheory getTheory() { return EqualityConstraintTheory.this; } public TermTheory getTermTheory() { return termTheory; } @Override public Expression pickSplitter(Collection<Expression> indicesSubSet, RewritingProcess process) { // equalities do not require splitters for model counting, so we ask only the non-equalities. Expression result = nonEqualities.pickSplitter(indicesSubSet, process); return result; } @Override public Expression normalizeSplitterGivenConstraint(Expression splitter, RewritingProcess process) { Expression result; if (splitter.hasFunctor(EQUALITY)) { Expression representativesEqualitySimplification; Expression representative1 = equalities.getRepresentative(splitter.get(0), process); Expression representative2 = equalities.getRepresentative(splitter.get(1), process); representativesEqualitySimplification = Equality.makeWithConstantSimplification(representative1, representative2, process); if ( ! representativesEqualitySimplification.getSyntacticFormType().equals("Symbol")) { if (nonEqualities.directlyImpliesNonTrivialDisequality(representative1, representative2, process)) { representativesEqualitySimplification = FALSE; } } result = representativesEqualitySimplification; } else { throw new Error("EqualityTheoryConstraint.normalizeSplitterGivenConstraint must receive equality splitters only, got: "+splitter); // TODO generalize for other constraint functors. } return result; } @Override public Expression normalizeExpressionWithoutLiterals(Expression expression, RewritingProcess process) { String syntacticTypeForm = "Symbol"; BinaryFunction<Expression, RewritingProcess, Expression> representativeReplacer = (BinaryFunction<Expression, RewritingProcess, Expression>) (s, p) -> equalities.getRepresentative(s, p); Expression result = DPLLUtil.simplifyWithExtraSyntacticFormTypeSimplifier( expression, functionApplicationSimplifiers, syntacticFormTypeSimplifiers, syntacticTypeForm, representativeReplacer, process); return result; } @Override protected void applyNormalizedSplitterDestructively(boolean splitterSign, Expression splitter, RewritingProcess process) { if (splitterSign) { Expression variable = splitter.get(0); Expression otherTerm = splitter.get(1); applyEqualityDestructively(variable, otherTerm, process); } else { nonEqualities.incorporateDestructively(splitterSign, splitter, process); } } private void applyEqualityDestructively(Expression variable, Expression otherTerm, RewritingProcess process) { equalities.setBinding(variable, otherTerm); updateRepresentativesWhereverTheyAreUsedDestructively(process); } protected void updateRepresentativesWhereverTheyAreUsedDestructively(RewritingProcess process) { equalities.updateRepresentativesInEqualitiesMap(process); Function<Expression, Expression> getRepresentative = t -> equalities.getRepresentative(t, process); // TODO: we should only pass the actually updated terms, instead of a function on them all. nonEqualities.updateRepresentativesDestructively(getRepresentative, process); } @Override public Expression modelCount(Collection<Expression> indicesSubSet, RewritingProcess process) { Collection<Expression> splittersToBeSatisfiedFromEqualities = new LinkedHashSet<Expression>(); equalities.getSplittersToBeSatisfiedFromEqualities(indicesSubSet, splittersToBeSatisfiedFromEqualities, process); Collection<Expression> splittersFromEqualitiesNotYetSatisfied = DPLLUtil.keepSplittersUnsatisfiedByContextualConstraint(splittersToBeSatisfiedFromEqualities, process); Collection<Expression> notBoundIndices = filter(indicesSubSet, i -> !equalities.indexIsBound(i)); Expression result = nonEqualities.modelCount(notBoundIndices, process); if ( ! result.equals(ZERO)) { for (Expression splitter : splittersFromEqualitiesNotYetSatisfied) { result = IfThenElse.make(splitter, result, ZERO); } } return result; } @Override public boolean directlyImpliesNonTrivialLiteral(Expression literal, RewritingProcess process) { boolean result; if (literal.hasFunctor(EQUALITY)) { result = equalities.directlyImpliesNonTrivialLiteral(literal, process); } else { // since non-equalities are defined on representatives only, we need to find them first before delegating. Expression representative1 = equalities.getRepresentative(literal.get(0), process); Expression representative2 = equalities.getRepresentative(literal.get(1), process); result = nonEqualities.directlyImpliesDisequality(representative1, representative2, process); } return result; } @Override protected Expression computeInnerExpression() { List<Expression> conjuncts = new LinkedList<Expression>(); conjuncts.addAll(And.getConjuncts(equalities)); // using getConjuncts to ensure a final flat conjunction instead of a conjunction of two conjunctions conjuncts.addAll(And.getConjuncts(nonEqualities)); Expression result = And.make(conjuncts); return result; } } /** * Represents and manipulates constraints in the theoryWithEquality of disequalities of terms (variables and constants). */ @Beta public static class EqualitiesConstraint extends AbstractOwnRepresentationConstraint { private static final long serialVersionUID = 1L; public Map<Expression, Expression> equalitiesMap; protected EqualityConstraintTheory theory; public EqualitiesConstraint(EqualityConstraintTheory theory, Collection<Expression> supportedIndices) { super(supportedIndices); this.theory = theory; this.equalitiesMap = new LinkedHashMap<Expression, Expression>(); } private EqualitiesConstraint(EqualitiesConstraint another) { super(another.getSupportedIndices()); this.theory = another.theory; this.equalitiesMap = new CopyOnWriteMap<Expression, Expression>(another.equalitiesMap); } @Override public EqualitiesConstraint clone() { return new EqualitiesConstraint(this); } @Override public EqualityConstraintTheory getTheory() { return theory; } public TermTheory getTermTheory() { return getTheory().getTermTheory(); } @Override public Expression pickSplitter(Collection<Expression> indicesSubSet, RewritingProcess process) { return null; } @Override public Expression normalizeSplitterGivenConstraint(Expression splitter, RewritingProcess process) { Expression simplifiedSplitterGivenConstraint; Expression representative1 = getRepresentative(splitter.get(0), process); Expression representative2 = getRepresentative(splitter.get(1), process); simplifiedSplitterGivenConstraint = Equality.makeWithConstantSimplification(representative1, representative2, process); return simplifiedSplitterGivenConstraint; } @Override public Expression normalizeExpressionWithoutLiterals(Expression expression, RewritingProcess process) { String syntacticTypeForm = "Symbol"; BinaryFunction<Expression, RewritingProcess, Expression> representativeReplacer = (BinaryFunction<Expression, RewritingProcess, Expression>) (s, p) -> getRepresentative(s, p); Expression result = DPLLUtil.simplifyWithExtraSyntacticFormTypeSimplifier( expression, theory.getFunctionApplicationSimplifiers(), theory.getSyntacticFormTypeSimplifiers(), syntacticTypeForm, representativeReplacer, process); return result; } @Override protected void applyNormalizedSplitterDestructively(boolean splitterSign, Expression splitter, RewritingProcess process) { myAssert(splitterSign, "EqualitiesConstraint.applyNormalizedSplitterDestructively must take positive splitters only."); Expression variable = splitter.get(0); Expression otherTerm = splitter.get(1); applyRepresentativesEqualityDestructively(variable, otherTerm, process); } private void applyRepresentativesEqualityDestructively(Expression variableRepresentative, Expression otherTermRepresentative, RewritingProcess process) { setBinding(variableRepresentative, otherTermRepresentative); updateRepresentativesInEqualitiesMap(process); } private void updateRepresentativesInEqualitiesMap(RewritingProcess process) { if ( ! getTermTheory().termsHaveNoArguments()) { // if terms have no arguments, simply keeping the bindings is enough; boolean equalitiesMapHasBeenUpdated; do { equalitiesMapHasBeenUpdated = false; Map<Expression, Expression> newEqualitiesMap = new LinkedHashMap<Expression, Expression>(); for (Expression variable : equalitiesMap.keySet()) { // TODO: use the representatives that we know to have been updated, and go where they are instead of scanning the entire map Expression representativeOfVariable = getRepresentative(variable, false /* do not update map as we are iterating over it */, process); Expression newVariable = getTermTheory().normalizeTermModuloRepresentatives(variable, t -> getRepresentative(t, process), process); if (newVariable == variable) { // no change for this variable, just copy this entry to the new map setBinding(newEqualitiesMap, variable, representativeOfVariable); } else { Expression representativeOfNewVariable = getRepresentative(newVariable, false, process); Expression representativesEquality = Equality.makeWithConstantSimplification(representativeOfVariable, representativeOfNewVariable, process); if (representativesEquality.equals(FALSE)) { throw new Contradiction(); } else { setBinding(newEqualitiesMap, newVariable, representativeOfNewVariable); if ( ! representativesEquality.equals(TRUE)) { // variable = representativeOfVariable and variable = newVariable = representativeOfNewVariable, // therefore, by transitivity, representativeOfVariable = representativeOfNewVariable setBinding(newEqualitiesMap, representativeOfVariable, representativeOfNewVariable); } equalitiesMapHasBeenUpdated = true; } } } equalitiesMap = equalitiesMapHasBeenUpdated? newEqualitiesMap : equalitiesMap; } while (equalitiesMapHasBeenUpdated); } } public void getSplittersToBeSatisfiedFromEqualities(Collection<Expression> indicesSubSet, Collection<Expression> result, RewritingProcess process) { for (Expression variable : equalitiesMap.keySet()) { if ( ! indicesSubSet.contains(variable)) { Expression representative = getRepresentative(variable, process); // Note that a free variable's representative is never a supported index, because // in splitters indices always come before free variables, // and that is the order of the binding. // A splitter with a free variable as the first term will always have another free variable // or a constant on the right-hand side. // This matters because the conditional model count has to be in terms of // free variables and constants only, never indices, so representative cannot be an index. // FIXED BUG: however, variable may be a supported index that is not in the indicesSubSet! So we need to check representative not to be in indicesSubSet! if ( ! representative.equals(variable) && ! indicesSubSet.contains(representative)) { Expression splitter = apply(EQUALITY, variable, representative); // making it with apply instead of Equality.make sidesteps simplifications, which will not occur in this case because otherwise this condition would have either rendered the constraint a contradiction, or would have been eliminated from it result.add(splitter); } } } } @Override public Expression modelCount(Collection<Expression> indicesSubSet, RewritingProcess process) { throw new Error("modelCount not yet implemented for EqualitiesConstraint"); // we don't need it for EqualityTheoryConstraint (see implementation to see why). } @Override protected Expression computeInnerExpression() { List<Expression> conjuncts = new LinkedList<Expression>(); for (Map.Entry<Expression, Expression> entry : equalitiesMap.entrySet()) { conjuncts.add(Equality.make(entry.getKey(), entry.getValue())); } Expression result = And.make(conjuncts); return result; } ////////// EQUALITY CONSTRAINTS MAINTENANCE /** * Indicates the binding of a variable in the equalities map. * A chain of bindings always links terms constrained to be equal and its * final element is the representative of the equivalent class of those terms. * @param variable * @return */ private Expression getBinding(Expression variable) { Expression result = equalitiesMap.get(variable); return result; } /** * Modifies the binding of a variable to a new one * (see {@link #getBinding(Expression)}). */ protected void setBinding(Expression variable, Expression newBinding) { if ( ! variable.equals(newBinding)) { equalitiesMap.put(variable, newBinding); } } /** * Same as {@link #setBinding(Expression, Expression, RewritingProcess), * but for an arbitrary equality map, as opposed to the constraint's. */ protected void setBinding(Map<Expression, Expression> equalitiesMap, Expression variable, Expression binding) { if ( ! variable.equals(binding)) { equalitiesMap.put(variable, binding); } } /** * Indicates whether an variable is bound to some other term. */ protected boolean indexIsBound(Expression index) { return equalitiesMap.containsKey(index); } /** * A normalized term's representative is itself, if the term is a constant, * the final term in the current binding chain, if the term is a variable and it has a binding, * or itself if it is a variable without a binding. * If the term is a variable with a binding, * this method sets its binding to the final term in the chain * for greater efficiency next time the method is invoked. * @param term * @param process * @return */ public Expression getRepresentative(Expression term, RewritingProcess process) { return getRepresentative(term, true /* record direct binding to representative */, process); } /** * A normalized term's representative is itself, if the term is a constant, * the final term in the current binding chain, if the term is a variable and it has a binding, * or itself if it is a variable without a binding. * If the term is a variable with a binding, * this method sets its binding to the final term in the chain * for greater efficiency next time the method is invoked. * @param term * @param process * @return */ protected Expression getRepresentative(Expression term, boolean recordDirectBindingToRepresentative, RewritingProcess process) { Expression current = term; Expression currentBinding; while (isVariableTerm(current, process) && (currentBinding = getBinding(current)) != null) { current = currentBinding; } // now, 'current' is in the chain started at term, // and it is either a constant or a variable without binding, therefore it is the equivalence class representative. if (recordDirectBindingToRepresentative && isVariableTerm(term, process)) { setBinding(term, current); // optional recording so that we do not need to traverse the entire chain next time } return current; } private boolean isVariableTerm(Expression term, RewritingProcess process) { return getTheory().isVariableTerm(term, process); } @Override public boolean directlyImpliesNonTrivialLiteral(Expression literal, RewritingProcess process) { myAssert( () -> literal.hasFunctor(EQUALITY), "EqualitiesConstraint.directlyImplies must take equality *atoms* only."); boolean result1 = getRepresentative(literal.get(0), process).equals(getRepresentative(literal.get(1), process)); boolean result = result1; return result; } ////////// END OF EQUALITY CONSTRAINTS MAINTENANCE } }
src/main/java/com/sri/ai/grinder/plaindpll/theory/EqualityConstraintTheory.java
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-expresso nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.grinder.plaindpll.theory; import static com.sri.ai.expresso.helper.Expressions.FALSE; import static com.sri.ai.expresso.helper.Expressions.TRUE; import static com.sri.ai.expresso.helper.Expressions.ZERO; import static com.sri.ai.expresso.helper.Expressions.apply; import static com.sri.ai.grinder.library.FunctorConstants.EQUALITY; import static com.sri.ai.util.Util.filter; import static com.sri.ai.util.Util.myAssert; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.sri.ai.expresso.api.Expression; import com.sri.ai.grinder.api.Rewriter; import com.sri.ai.grinder.api.RewritingProcess; import com.sri.ai.grinder.library.Disequality; import com.sri.ai.grinder.library.Equality; import com.sri.ai.grinder.library.FunctorConstants; import com.sri.ai.grinder.library.boole.And; import com.sri.ai.grinder.library.boole.Equivalence; import com.sri.ai.grinder.library.boole.ForAll; import com.sri.ai.grinder.library.boole.Implication; import com.sri.ai.grinder.library.boole.Not; import com.sri.ai.grinder.library.boole.Or; import com.sri.ai.grinder.library.boole.ThereExists; import com.sri.ai.grinder.library.controlflow.IfThenElse; import com.sri.ai.grinder.library.number.Division; import com.sri.ai.grinder.library.number.Minus; import com.sri.ai.grinder.library.number.Plus; import com.sri.ai.grinder.library.number.Times; import com.sri.ai.grinder.plaindpll.api.TermTheory; import com.sri.ai.grinder.plaindpll.core.AbstractConstraintTheory; import com.sri.ai.grinder.plaindpll.core.Contradiction; import com.sri.ai.grinder.plaindpll.core.SGDPLLT; import com.sri.ai.grinder.plaindpll.core.SimplifyLiteralGivenDisequality; import com.sri.ai.grinder.plaindpll.problemtype.Satisfiability; import com.sri.ai.grinder.plaindpll.problemtype.Tautologicality; import com.sri.ai.grinder.plaindpll.util.DPLLUtil; import com.sri.ai.util.Util; import com.sri.ai.util.base.BinaryFunction; import com.sri.ai.util.collect.CopyOnWriteMap; @Beta /** * A {@link ConstraintTheory} for equality literals. */ public class EqualityConstraintTheory extends AbstractConstraintTheory { public TermTheory termTheory; // Important: // this class generalizes the notion of a variable to a "generalized variable" (simply referred by as "variable"), // which is either a variable symbol, or an uninterpreted function application such as p(a, b, X). // It can also be seen as an indexed variable (typically represented as x_i, y_i,j etc). public EqualityConstraintTheory(TermTheory termTheory) { this.termTheory = termTheory; } public TermTheory getTermTheory() { return termTheory; } private static Rewriter plus = new Plus(); private static Rewriter times = new Times(); @Override protected boolean usesDefaultImplementationOfSimplifyByOverridingGetFunctionApplicationSimplifiersAndGetSyntacticFormTypeSimplifiers() { return true; } private static Map<String, BinaryFunction<Expression, RewritingProcess, Expression>> functionApplicationSimplifiers = Util.<String, BinaryFunction<Expression, RewritingProcess, Expression>>map( FunctorConstants.EQUALITY, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Equality.simplify(f, process), FunctorConstants.DISEQUALITY, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Disequality.simplify(f, process), FunctorConstants.AND, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> And.simplify(f), FunctorConstants.OR, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Or.simplify(f), FunctorConstants.NOT, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Not.simplify(f), FunctorConstants.IF_THEN_ELSE, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> IfThenElse.simplify(f), FunctorConstants.EQUIVALENCE, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Equivalence.simplify(f), FunctorConstants.IMPLICATION, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Implication.simplify(f), FunctorConstants.CARDINALITY, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> { Expression type = (Expression) process.getGlobalObject(f); return type == null? f : type; }, FunctorConstants.TIMES, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> times.rewrite(f, process), FunctorConstants.DIVISION, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> Division.simplify(f), FunctorConstants.PLUS, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> plus.rewrite(f, process), FunctorConstants.MINUS, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> f.numberOfArguments() == 2? Minus.simplify(f) : f ); private Map<String, BinaryFunction<Expression, RewritingProcess, Expression>> syntacticFormTypeSimplifiers = Util.<String, BinaryFunction<Expression, RewritingProcess, Expression>>map( ForAll.SYNTACTIC_FORM_TYPE, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> (new SGDPLLT(new EqualityConstraintTheory(termTheory), new Tautologicality())).rewrite(f, process), ThereExists.SYNTACTIC_FORM_TYPE, (BinaryFunction<Expression, RewritingProcess, Expression>) (f, process) -> (new SGDPLLT(new EqualityConstraintTheory(termTheory), new Satisfiability())).rewrite(f, process) ); @Override public Map<String, BinaryFunction<Expression, RewritingProcess, Expression>> getFunctionApplicationSimplifiers() { return functionApplicationSimplifiers; } @Override public Map<String, BinaryFunction<Expression, RewritingProcess, Expression>> getSyntacticFormTypeSimplifiers() { return syntacticFormTypeSimplifiers; } @Override protected String getCorrespondingSplitterFunctorOrNull(Expression expression) { String result; if (expression.hasFunctor(FunctorConstants.EQUALITY) || expression.hasFunctor(FunctorConstants.DISEQUALITY)) { // TODO: need to generalize to other types of constraint result = FunctorConstants.EQUALITY; } else { result = null; } return result; } @Override protected BinaryFunction<Expression, RewritingProcess, Expression> getSplitterApplier(boolean splitterSign, Expression splitter) { // TODO: generalize to other types of constraint BinaryFunction<Expression, RewritingProcess, Expression> applier; if (splitter.hasFunctor(FunctorConstants.EQUALITY)) { Expression term1 = splitter.get(0); Expression term2 = splitter.get(1); if (splitterSign) { applier = (Expression expression, RewritingProcess process) -> { Expression result = expression.replaceAllOccurrences(term1, term2, process); result = simplify(result, process); return result; }; } else { applier = (Expression expression, RewritingProcess process) -> { Expression result = expression.replaceAllOccurrences(new SimplifyLiteralGivenDisequality(term1, term2), process); result = simplify(result, process); return result; }; } } else { applier = null; } return applier; } @Override public EqualityTheoryConstraint makeConstraint(Collection<Expression> indices) { // TODO: generalize to other types of constraint return new EqualityTheoryConstraint(indices); } @Override public boolean isVariableTerm(Expression term, RewritingProcess process) { return termTheory.isVariableTerm(term, process); } /** A faster implementation than the default implementation, since we know more about splitters here. */ @Override public boolean splitterDependsOnIndex(Expression splitter, Collection<Expression> indices) { boolean result = indices.contains(splitter.get(0)); return result; } @Override public boolean applicationOfConstraintOnSplitterAlwaysEitherTrivializesItOrEffectsNoChangeAtAll() { return false; } /** * Represents and manipulates constraints in the theoryWithEquality of disequalities of terms (variables and constants). */ @SuppressWarnings("serial") @Beta public class EqualityTheoryConstraint extends AbstractOwnRepresentationConstraint { protected EqualitiesConstraint equalities; // TODO: make EqualitiesConstraint an interface protected NonEqualitiesConstraint nonEqualities; public EqualityTheoryConstraint(Collection<Expression> supportedIndices) { super(supportedIndices); this.equalities = new EqualitiesConstraint(getTheory(), getSupportedIndices()); this.nonEqualities = new DefaultNonEqualitiesConstraint(getTheory(), supportedIndices); } private EqualityTheoryConstraint(EqualityTheoryConstraint another) { super(another.getSupportedIndices()); this.equalities = new EqualitiesConstraint(another.equalities); this.nonEqualities = (NonEqualitiesConstraint) another.nonEqualities.clone(); } @Override public EqualityTheoryConstraint clone() { return new EqualityTheoryConstraint(this); } @Override public EqualityConstraintTheory getTheory() { return EqualityConstraintTheory.this; } public TermTheory getTermTheory() { return termTheory; } @Override public Expression pickSplitter(Collection<Expression> indicesSubSet, RewritingProcess process) { // equalities do not require splitters for model counting, so we ask only the non-equalities. Expression result = nonEqualities.pickSplitter(indicesSubSet, process); return result; } @Override public Expression normalizeSplitterGivenConstraint(Expression splitter, RewritingProcess process) { Expression result; if (splitter.hasFunctor(EQUALITY)) { Expression representativesEqualitySimplification; Expression representative1 = equalities.getRepresentative(splitter.get(0), process); Expression representative2 = equalities.getRepresentative(splitter.get(1), process); representativesEqualitySimplification = Equality.makeWithConstantSimplification(representative1, representative2, process); if ( ! representativesEqualitySimplification.getSyntacticFormType().equals("Symbol")) { if (nonEqualities.directlyImpliesNonTrivialDisequality(representative1, representative2, process)) { representativesEqualitySimplification = FALSE; } } result = representativesEqualitySimplification; } else { throw new Error("EqualityTheoryConstraint.normalizeSplitterGivenConstraint must receive equality splitters only, got: "+splitter); // TODO generalize for other constraint functors. } return result; } @Override public Expression normalizeExpressionWithoutLiterals(Expression expression, RewritingProcess process) { String syntacticTypeForm = "Symbol"; BinaryFunction<Expression, RewritingProcess, Expression> representativeReplacer = (BinaryFunction<Expression, RewritingProcess, Expression>) (s, p) -> equalities.getRepresentative(s, p); Expression result = DPLLUtil.simplifyWithExtraSyntacticFormTypeSimplifier( expression, functionApplicationSimplifiers, syntacticFormTypeSimplifiers, syntacticTypeForm, representativeReplacer, process); return result; } @Override protected void applyNormalizedSplitterDestructively(boolean splitterSign, Expression splitter, RewritingProcess process) { if (splitterSign) { Expression variable = splitter.get(0); Expression otherTerm = splitter.get(1); applyEqualityDestructively(variable, otherTerm, process); } else { nonEqualities.incorporateDestructively(splitterSign, splitter, process); } } private void applyEqualityDestructively(Expression variable, Expression otherTerm, RewritingProcess process) { equalities.setBinding(variable, otherTerm); updateRepresentativesWhereverTheyAreUsedDestructively(process); } protected void updateRepresentativesWhereverTheyAreUsedDestructively(RewritingProcess process) { equalities.updateRepresentativesInEqualitiesMap(process); Function<Expression, Expression> getRepresentative = t -> equalities.getRepresentative(t, process); // TODO: we should only pass the actually updated terms, instead of a function on them all. nonEqualities.updateRepresentativesDestructively(getRepresentative, process); } @Override public Expression modelCount(Collection<Expression> indicesSubSet, RewritingProcess process) { Collection<Expression> splittersToBeSatisfiedFromEqualities = new LinkedHashSet<Expression>(); equalities.getSplittersToBeSatisfiedFromEqualities(indicesSubSet, splittersToBeSatisfiedFromEqualities, process); Collection<Expression> splittersFromEqualitiesNotYetSatisfied = DPLLUtil.keepSplittersUnsatisfiedByContextualConstraint(splittersToBeSatisfiedFromEqualities, process); Collection<Expression> notBoundIndices = filter(indicesSubSet, i -> !equalities.indexIsBound(i)); Expression result = nonEqualities.modelCount(notBoundIndices, process); if ( ! result.equals(ZERO)) { for (Expression splitter : splittersFromEqualitiesNotYetSatisfied) { result = IfThenElse.make(splitter, result, ZERO); } } return result; } @Override public boolean directlyImpliesNonTrivialLiteral(Expression literal, RewritingProcess process) { boolean result; if (literal.hasFunctor(EQUALITY)) { result = equalities.directlyImpliesNonTrivialLiteral(literal, process); } else { // since non-equalities are defined on representatives only, we need to find them first before delegating. Expression representative1 = equalities.getRepresentative(literal.get(0), process); Expression representative2 = equalities.getRepresentative(literal.get(1), process); result = nonEqualities.directlyImpliesDisequality(representative1, representative2, process); } return result; } @Override protected Expression computeInnerExpression() { List<Expression> conjuncts = new LinkedList<Expression>(); conjuncts.addAll(And.getConjuncts(equalities)); // using getConjuncts to ensure a final flat conjunction instead of a conjunction of two conjunctions conjuncts.addAll(And.getConjuncts(nonEqualities)); Expression result = And.make(conjuncts); return result; } } /** * Represents and manipulates constraints in the theoryWithEquality of disequalities of terms (variables and constants). */ @Beta public static class EqualitiesConstraint extends AbstractOwnRepresentationConstraint { private static final long serialVersionUID = 1L; public Map<Expression, Expression> equalitiesMap; protected EqualityConstraintTheory theory; public EqualitiesConstraint(EqualityConstraintTheory theory, Collection<Expression> supportedIndices) { super(supportedIndices); this.theory = theory; this.equalitiesMap = new LinkedHashMap<Expression, Expression>(); } private EqualitiesConstraint(EqualitiesConstraint another) { super(another.getSupportedIndices()); this.theory = another.theory; this.equalitiesMap = new CopyOnWriteMap<Expression, Expression>(another.equalitiesMap); } @Override public EqualitiesConstraint clone() { return new EqualitiesConstraint(this); } @Override public EqualityConstraintTheory getTheory() { return theory; } public TermTheory getTermTheory() { return getTheory().getTermTheory(); } @Override public Expression pickSplitter(Collection<Expression> indicesSubSet, RewritingProcess process) { return null; } @Override public Expression normalizeSplitterGivenConstraint(Expression splitter, RewritingProcess process) { Expression simplifiedSplitterGivenConstraint; Expression representative1 = getRepresentative(splitter.get(0), process); Expression representative2 = getRepresentative(splitter.get(1), process); simplifiedSplitterGivenConstraint = Equality.makeWithConstantSimplification(representative1, representative2, process); return simplifiedSplitterGivenConstraint; } @Override public Expression normalizeExpressionWithoutLiterals(Expression expression, RewritingProcess process) { String syntacticTypeForm = "Symbol"; BinaryFunction<Expression, RewritingProcess, Expression> representativeReplacer = (BinaryFunction<Expression, RewritingProcess, Expression>) (s, p) -> getRepresentative(s, p); Expression result = DPLLUtil.simplifyWithExtraSyntacticFormTypeSimplifier( expression, theory.getFunctionApplicationSimplifiers(), theory.getSyntacticFormTypeSimplifiers(), syntacticTypeForm, representativeReplacer, process); return result; } @Override protected void applyNormalizedSplitterDestructively(boolean splitterSign, Expression splitter, RewritingProcess process) { myAssert(splitterSign, "EqualitiesConstraint.applyNormalizedSplitterDestructively must take positive splitters only."); Expression variable = splitter.get(0); Expression otherTerm = splitter.get(1); applyRepresentativesEqualityDestructively(variable, otherTerm, process); } private void applyRepresentativesEqualityDestructively(Expression variableRepresentative, Expression otherTermRepresentative, RewritingProcess process) { setBinding(variableRepresentative, otherTermRepresentative); updateRepresentativesInEqualitiesMap(process); } private void updateRepresentativesInEqualitiesMap(RewritingProcess process) { if ( ! getTermTheory().termsHaveNoArguments()) { // if terms have no arguments, simply keeping the bindings is enough; boolean equalitiesMapHasBeenUpdated; do { equalitiesMapHasBeenUpdated = false; Map<Expression, Expression> newEqualitiesMap = new LinkedHashMap<Expression, Expression>(); for (Expression variable : equalitiesMap.keySet()) { // TODO: use the representatives that we know to have been updated, and go where they are instead of scanning the entire map Expression representativeOfVariable = getRepresentative(variable, false /* do not update map as we are iterating over it */, process); Expression newVariable = getTermTheory().normalizeTermModuloRepresentatives(variable, t -> getRepresentative(t, process), process); if (newVariable == variable) { // no change for this variable, just copy this entry to the new map setBinding(newEqualitiesMap, variable, representativeOfVariable); } else { Expression representativeOfNewVariable = getRepresentative(newVariable, false, process); Expression representativesEquality = Equality.makeWithConstantSimplification(representativeOfVariable, representativeOfNewVariable, process); if (representativesEquality.equals(FALSE)) { throw new Contradiction(); } else { setBinding(newEqualitiesMap, newVariable, representativeOfNewVariable); if ( ! representativesEquality.equals(TRUE)) { // variable = representativeOfVariable and variable = newVariable = representativeOfNewVariable, // therefore, by transitivity, representativeOfVariable = representativeOfNewVariable setBinding(newEqualitiesMap, representativeOfVariable, representativeOfNewVariable); } equalitiesMapHasBeenUpdated = true; } } } equalitiesMap = equalitiesMapHasBeenUpdated? newEqualitiesMap : equalitiesMap; } while (equalitiesMapHasBeenUpdated); } } public void getSplittersToBeSatisfiedFromEqualities(Collection<Expression> indicesSubSet, Collection<Expression> result, RewritingProcess process) { for (Expression variable : equalitiesMap.keySet()) { if ( ! indicesSubSet.contains(variable)) { Expression representative = getRepresentative(variable, process); // Note that a free variable's representative is never a supported index, because // in splitters indices always come before free variables, // and that is the order of the binding. // A splitter with a free variable as the first term will always have another free variable // or a constant on the right-hand side. // This matters because the conditional model count has to be in terms of // free variables and constants only, never indices, so representative cannot be an index. if ( ! representative.equals(variable)) { Expression splitter = apply(EQUALITY, variable, representative); // making it with apply instead of Equality.make sidesteps simplifications, which will not occur in this case because otherwise this condition would have either rendered the constraint a contradiction, or would have been eliminated from it result.add(splitter); } } } } @Override public Expression modelCount(Collection<Expression> indicesSubSet, RewritingProcess process) { throw new Error("modelCount not yet implemented for EqualitiesConstraint"); // we don't need it for EqualityTheoryConstraint (see implementation to see why). } @Override protected Expression computeInnerExpression() { List<Expression> conjuncts = new LinkedList<Expression>(); for (Map.Entry<Expression, Expression> entry : equalitiesMap.entrySet()) { conjuncts.add(Equality.make(entry.getKey(), entry.getValue())); } Expression result = And.make(conjuncts); return result; } ////////// EQUALITY CONSTRAINTS MAINTENANCE /** * Indicates the binding of a variable in the equalities map. * A chain of bindings always links terms constrained to be equal and its * final element is the representative of the equivalent class of those terms. * @param variable * @return */ private Expression getBinding(Expression variable) { Expression result = equalitiesMap.get(variable); return result; } /** * Modifies the binding of a variable to a new one * (see {@link #getBinding(Expression)}). */ protected void setBinding(Expression variable, Expression newBinding) { if ( ! variable.equals(newBinding)) { equalitiesMap.put(variable, newBinding); } } /** * Same as {@link #setBinding(Expression, Expression, RewritingProcess), * but for an arbitrary equality map, as opposed to the constraint's. */ protected void setBinding(Map<Expression, Expression> equalitiesMap, Expression variable, Expression binding) { if ( ! variable.equals(binding)) { equalitiesMap.put(variable, binding); } } /** * Indicates whether an variable is bound to some other term. */ protected boolean indexIsBound(Expression index) { return equalitiesMap.containsKey(index); } /** * A normalized term's representative is itself, if the term is a constant, * the final term in the current binding chain, if the term is a variable and it has a binding, * or itself if it is a variable without a binding. * If the term is a variable with a binding, * this method sets its binding to the final term in the chain * for greater efficiency next time the method is invoked. * @param term * @param process * @return */ public Expression getRepresentative(Expression term, RewritingProcess process) { return getRepresentative(term, true /* record direct binding to representative */, process); } /** * A normalized term's representative is itself, if the term is a constant, * the final term in the current binding chain, if the term is a variable and it has a binding, * or itself if it is a variable without a binding. * If the term is a variable with a binding, * this method sets its binding to the final term in the chain * for greater efficiency next time the method is invoked. * @param term * @param process * @return */ protected Expression getRepresentative(Expression term, boolean recordDirectBindingToRepresentative, RewritingProcess process) { Expression current = term; Expression currentBinding; while (isVariableTerm(current, process) && (currentBinding = getBinding(current)) != null) { current = currentBinding; } // now, 'current' is in the chain started at term, // and it is either a constant or a variable without binding, therefore it is the equivalence class representative. if (recordDirectBindingToRepresentative && isVariableTerm(term, process)) { setBinding(term, current); // optional recording so that we do not need to traverse the entire chain next time } return current; } private boolean isVariableTerm(Expression term, RewritingProcess process) { return getTheory().isVariableTerm(term, process); } @Override public boolean directlyImpliesNonTrivialLiteral(Expression literal, RewritingProcess process) { myAssert( () -> literal.hasFunctor(EQUALITY), "EqualitiesConstraint.directlyImplies must take equality *atoms* only."); boolean result1 = getRepresentative(literal.get(0), process).equals(getRepresentative(literal.get(1), process)); boolean result = result1; return result; } ////////// END OF EQUALITY CONSTRAINTS MAINTENANCE } }
- fixed bug in Equality constraint model counting.
src/main/java/com/sri/ai/grinder/plaindpll/theory/EqualityConstraintTheory.java
- fixed bug in Equality constraint model counting.
Java
mit
3603f6540bb39207b1e0fd0f92c33987b85f140d
0
pawellinkshell/Supermarket,pawellinkshell/Supermarket
package pl.koszela.jan.service.impl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.springframework.stereotype.Service; import pl.koszela.jan.domain.Order; import pl.koszela.jan.service.OrderService; /** * Created on 12.08.2017. * * @author Jan Koszela */ @Service("orderService") public class DefaultOrderService implements OrderService { private static List<Order> orders; public DefaultOrderService() { this.orders = new ArrayList<>(); } @Override public Order findOrderByName(String productName) { for (Iterator<Order> i = orders.iterator(); i.hasNext(); ) { Order currentOrder = i.next(); if (isSameProduct(productName, currentOrder)) { return currentOrder; } } return null; } private boolean isSameProduct(String productName, Order currentOrder) { return productName.equals(currentOrder.getProductName()); } @Override public boolean createOrder(Order order) { if(order.getQuantity() > 0) { return this.orders.add(order); } return false; } @Override public void updateOrder(Order newOrder) { Order foundOrder = findOrderByName(newOrder.getProductName()); if (foundOrder != null) { if(newOrder.getQuantity() > 0) { orders.set(getIdFromOrders(foundOrder), newOrder); } else { orders.remove(getIdFromOrders(foundOrder)); } } } private int getIdFromOrders(Order order) { for (int i = 0; i < orders.size(); i++) { if (orders.get(i).equals(order)) { return i; } } throw new IndexOutOfBoundsException("Method should be null-checked before in calls"); } @Override public boolean removeOrder(Order order) { Order foundOrder = findOrderByName(order.getProductName()); if (foundOrder != null) { orders.remove(getIdFromOrders(foundOrder)); return true; } return false; } }
src/main/java/pl/koszela/jan/service/impl/DefaultOrderService.java
package pl.koszela.jan.service.impl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.springframework.stereotype.Service; import pl.koszela.jan.domain.Order; import pl.koszela.jan.service.OrderService; /** * Created on 12.08.2017. * * @author Jan Koszela */ @Service("orderService") public class DefaultOrderService implements OrderService { private static List<Order> orders; public DefaultOrderService() { this.orders = new ArrayList<>(); } @Override public Order findOrderByName(String productName) { for (Iterator<Order> i = orders.iterator(); i.hasNext(); ) { Order currentOrder = i.next(); if (isSameProduct(productName, currentOrder)) { return currentOrder; } } return null; } private boolean isSameProduct(String productName, Order currentOrder) { return productName.equals(currentOrder.getProductName()); } @Override public boolean createOrder(Order order) { if(order.getQuantity() > 0) { return this.orders.add(order); } return false; } @Override public void updateOrder(Order newOrder) { Order foundOrder = findOrderByName(newOrder.getProductName()); if (foundOrder != null) { if(newOrder.getQuantity() > 0) { orders.remove(getIdFromOrders(foundOrder)); } else { orders.set(getIdFromOrders(foundOrder), newOrder); } } } private int getIdFromOrders(Order order) { for (int i = 0; i < orders.size(); i++) { if (orders.get(i).equals(order)) { return i; } } throw new IndexOutOfBoundsException("Method should be null-checked before in calls"); } @Override public boolean removeOrder(Order order) { Order foundOrder = findOrderByName(order.getProductName()); if (foundOrder != null) { orders.remove(getIdFromOrders(foundOrder)); return true; } return false; } }
Fix logic for logic
src/main/java/pl/koszela/jan/service/impl/DefaultOrderService.java
Fix logic for logic
Java
mit
1e0488f19c6af1dd07fe25ba9d47da66e8b6e055
0
viqueen/jenkins,ikedam/jenkins,viqueen/jenkins,rsandell/jenkins,v1v/jenkins,v1v/jenkins,damianszczepanik/jenkins,viqueen/jenkins,v1v/jenkins,DanielWeber/jenkins,viqueen/jenkins,rsandell/jenkins,DanielWeber/jenkins,daniel-beck/jenkins,DanielWeber/jenkins,v1v/jenkins,viqueen/jenkins,jenkinsci/jenkins,pjanouse/jenkins,jenkinsci/jenkins,rsandell/jenkins,MarkEWaite/jenkins,daniel-beck/jenkins,ikedam/jenkins,ikedam/jenkins,rsandell/jenkins,damianszczepanik/jenkins,daniel-beck/jenkins,MarkEWaite/jenkins,daniel-beck/jenkins,pjanouse/jenkins,MarkEWaite/jenkins,MarkEWaite/jenkins,viqueen/jenkins,pjanouse/jenkins,viqueen/jenkins,damianszczepanik/jenkins,ikedam/jenkins,ikedam/jenkins,ikedam/jenkins,damianszczepanik/jenkins,daniel-beck/jenkins,daniel-beck/jenkins,rsandell/jenkins,v1v/jenkins,pjanouse/jenkins,damianszczepanik/jenkins,jenkinsci/jenkins,damianszczepanik/jenkins,pjanouse/jenkins,v1v/jenkins,DanielWeber/jenkins,ikedam/jenkins,damianszczepanik/jenkins,MarkEWaite/jenkins,ikedam/jenkins,jenkinsci/jenkins,DanielWeber/jenkins,rsandell/jenkins,daniel-beck/jenkins,pjanouse/jenkins,DanielWeber/jenkins,jenkinsci/jenkins,jenkinsci/jenkins,DanielWeber/jenkins,rsandell/jenkins,damianszczepanik/jenkins,MarkEWaite/jenkins,rsandell/jenkins,jenkinsci/jenkins,MarkEWaite/jenkins,jenkinsci/jenkins,MarkEWaite/jenkins,v1v/jenkins,daniel-beck/jenkins,pjanouse/jenkins
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import hudson.util.CopyOnWriteMap.Hash; import org.junit.Ignore; import org.junit.Test; import java.util.Random; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.Map.Entry; /** * @author Kohsuke Kawaguchi */ public class ConsistentHashTest { /** * Just some random tests to ensure that we have no silly NPE or that kind of error. */ @Test public void basic() { ConsistentHash<String> hash = new ConsistentHash<>(); hash.add("data1"); hash.add("data2"); hash.add("data3"); // In a pure random scenario, there's one in 2^32 chance that this test fails // but as we control the input and the hash function is deterministic, there is no risk of failure String x = hash.lookup(Integer.MIN_VALUE); String y = hash.lookup(Integer.MAX_VALUE); // both values are data3 assertEquals(x, y); // list them up Iterator<String> itr = hash.list(Integer.MIN_VALUE).iterator(); Set<String> all = new HashSet<>(); String z = itr.next(); all.add(z); assertEquals(z, x); all.add(itr.next()); all.add(itr.next()); assertFalse(itr.hasNext()); assertEquals(3, all.size()); } /** * Uneven distribution should result in uneven mapping. */ @Test public void unevenDistribution() { ConsistentHash<String> hash = new ConsistentHash<>(); hash.add("Even",10); hash.add("Odd",100); Random r = new Random(0); int even = 0; int odd = 0; for(int i = 0; i < 1000; i++) { String v = hash.lookup(r.nextInt()); if(v.equals("Even")) { even++; } else { odd++; } } System.out.printf("%d/%d%n", even, odd); assertTrue(even * 8 < odd); } /** * Removal shouldn't affect existing nodes */ @Test public void removal() { ConsistentHash<Integer> hash = new ConsistentHash<>(); for (int i = 0; i < 10; i++) { hash.add(i); } // what was the mapping before the mutation? Map<Integer, Integer> before = new HashMap<>(); Random r = new Random(0); for (int i = 0; i < 1000; i++) { int q = r.nextInt(); before.put(q, hash.lookup(q)); } // remove a node hash.remove(0); // verify that the mapping remains consistent for (Entry<Integer,Integer> e : before.entrySet()) { int m = hash.lookup(e.getKey()); assertTrue(e.getValue() == 0 || e.getValue() == m); } } @Test public void emptyBehavior() { ConsistentHash<String> hash = new ConsistentHash<>(); assertEquals(0, hash.countAllPoints()); assertFalse(hash.list(0).iterator().hasNext()); assertNull(hash.lookup(0)); assertNull(hash.lookup(999)); } @Test public void countAllPoints() { ConsistentHash<String> hash = new ConsistentHash<>(); assertEquals(0, hash.countAllPoints()); hash.add("foo", 10); assertEquals(10, hash.countAllPoints()); hash.add("bar", 5); assertEquals(15, hash.countAllPoints()); hash.remove("foo"); assertEquals(5, hash.countAllPoints()); } @Test public void defaultReplicationIsOneHundred() { ConsistentHash<String> hash = new ConsistentHash<>(); assertEquals(0, hash.countAllPoints()); hash.add("foo"); assertEquals(100, hash.countAllPoints()); } @Test public void setCustomDefaultReplication() { ConsistentHash<String> hash = new ConsistentHash<>((ConsistentHash.Hash<String>) ConsistentHash.DEFAULT_HASH, 7); assertEquals(0, hash.countAllPoints()); hash.add("foo"); assertEquals(7, hash.countAllPoints()); } @Test public void usesCustomHash() { final RuntimeException exception = new RuntimeException(); ConsistentHash.Hash<String> hashFunction = str -> { throw exception; }; try { ConsistentHash<String> hash = new ConsistentHash<>(hashFunction); hash.add("foo"); fail("Didn't use custom hash function"); } catch (RuntimeException e) { assertSame(exception, e); } } /** * This test doesn't fail but it's written to measure the performance of the consistent hash function with large data set. */ @Test @Ignore("Helper test for performance, no assertion") public void speed() { Map<String,Integer> data = new Hash<>(); for (int i = 0; i < 1000; i++) { data.put("node" + i, 100); } data.put("tail", 100); long start = System.currentTimeMillis(); for (int j = 0; j < 10; j++) { ConsistentHash<String> b = new ConsistentHash<>(); b.addAll(data); } System.out.println(System.currentTimeMillis() - start); } }
core/src/test/java/hudson/util/ConsistentHashTest.java
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import hudson.util.CopyOnWriteMap.Hash; import org.junit.Ignore; import org.junit.Test; import java.util.Random; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.Map.Entry; /** * @author Kohsuke Kawaguchi */ public class ConsistentHashTest { /** * Just some random tests to ensure that we have no silly NPE or that kind of error. */ @Test public void basic() { ConsistentHash<String> hash = new ConsistentHash<>(); hash.add("data1"); hash.add("data2"); hash.add("data3"); // In a pure random scenario, there's one in 2^32 chance that this test fails // but as we control the input and the hash function is deterministic, there is no risk of failure String x = hash.lookup(Integer.MIN_VALUE); String y = hash.lookup(Integer.MAX_VALUE); // both values are data3 assertEquals(x, y); // list them up Iterator<String> itr = hash.list(Integer.MIN_VALUE).iterator(); Set<String> all = new HashSet<>(); String z = itr.next(); all.add(z); assertEquals(z, x); all.add(itr.next()); all.add(itr.next()); assertFalse(itr.hasNext()); assertEquals(3, all.size()); } /** * Uneven distribution should result in uneven mapping. */ @Test public void unevenDistribution() { ConsistentHash<String> hash = new ConsistentHash<>(); hash.add("Even",10); hash.add("Odd",100); Random r = new Random(0); int even = 0; int odd = 0; for(int i = 0; i < 1000; i++) { String v = hash.lookup(r.nextInt()); if(v.equals("Even")) { even++; } else { odd++; } } System.out.printf("%d/%d\n", even, odd); assertTrue(even * 8 < odd); } /** * Removal shouldn't affect existing nodes */ @Test public void removal() { ConsistentHash<Integer> hash = new ConsistentHash<>(); for (int i = 0; i < 10; i++) { hash.add(i); } // what was the mapping before the mutation? Map<Integer, Integer> before = new HashMap<>(); Random r = new Random(0); for (int i = 0; i < 1000; i++) { int q = r.nextInt(); before.put(q, hash.lookup(q)); } // remove a node hash.remove(0); // verify that the mapping remains consistent for (Entry<Integer,Integer> e : before.entrySet()) { int m = hash.lookup(e.getKey()); assertTrue(e.getValue() == 0 || e.getValue() == m); } } @Test public void emptyBehavior() { ConsistentHash<String> hash = new ConsistentHash<>(); assertEquals(0, hash.countAllPoints()); assertFalse(hash.list(0).iterator().hasNext()); assertNull(hash.lookup(0)); assertNull(hash.lookup(999)); } @Test public void countAllPoints() { ConsistentHash<String> hash = new ConsistentHash<>(); assertEquals(0, hash.countAllPoints()); hash.add("foo", 10); assertEquals(10, hash.countAllPoints()); hash.add("bar", 5); assertEquals(15, hash.countAllPoints()); hash.remove("foo"); assertEquals(5, hash.countAllPoints()); } @Test public void defaultReplicationIsOneHundred() { ConsistentHash<String> hash = new ConsistentHash<>(); assertEquals(0, hash.countAllPoints()); hash.add("foo"); assertEquals(100, hash.countAllPoints()); } @Test public void setCustomDefaultReplication() { ConsistentHash<String> hash = new ConsistentHash<>((ConsistentHash.Hash<String>) ConsistentHash.DEFAULT_HASH, 7); assertEquals(0, hash.countAllPoints()); hash.add("foo"); assertEquals(7, hash.countAllPoints()); } @Test public void usesCustomHash() { final RuntimeException exception = new RuntimeException(); ConsistentHash.Hash<String> hashFunction = str -> { throw exception; }; try { ConsistentHash<String> hash = new ConsistentHash<>(hashFunction); hash.add("foo"); fail("Didn't use custom hash function"); } catch (RuntimeException e) { assertSame(exception, e); } } /** * This test doesn't fail but it's written to measure the performance of the consistent hash function with large data set. */ @Test @Ignore("Helper test for performance, no assertion") public void speed() { Map<String,Integer> data = new Hash<>(); for (int i = 0; i < 1000; i++) { data.put("node" + i, 100); } data.put("tail", 100); long start = System.currentTimeMillis(); for (int j = 0; j < 10; j++) { ConsistentHash<String> b = new ConsistentHash<>(); b.addAll(data); } System.out.println(System.currentTimeMillis() - start); } }
fixed SpotBugs VA_FORMAT_STRING_USES_NEWLINE
core/src/test/java/hudson/util/ConsistentHashTest.java
fixed SpotBugs VA_FORMAT_STRING_USES_NEWLINE
Java
mit
17c1aaf5c8ad2132e7c68b01b02387f139dc2ae0
0
caseif/TTT
/* * The MIT License (MIT) * * Copyright (c) 2013-2015, Maxim Roncacé <mproncace@lapis.blue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.caseif.ttt.listeners; import net.caseif.ttt.Body; import net.caseif.ttt.TTTCore; import net.caseif.ttt.scoreboard.ScoreboardManager; import net.caseif.ttt.util.Constants.Color; import net.caseif.ttt.util.Constants.Role; import net.caseif.ttt.util.Constants.Stage; import net.caseif.ttt.util.MiscUtil; import net.caseif.ttt.util.helper.ConfigHelper; import net.caseif.ttt.util.helper.InventoryHelper; import net.caseif.ttt.util.helper.KarmaHelper; import net.caseif.ttt.util.helper.LocationHelper; import net.caseif.ttt.util.helper.NmsHelper; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import net.caseif.flint.challenger.Challenger; import net.caseif.flint.util.physical.Location3D; import net.caseif.rosetta.Localizable; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.DoubleChest; import org.bukkit.entity.Arrow; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.projectiles.ProjectileSource; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; public class PlayerListener implements Listener { private final ImmutableList<String> disabledCommands = ImmutableList.of("kit", "msg", "pm", "r", "me"); private static Field fieldRbHelper; private static Method logBlockChange; @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) //TODO: fix the crazy nesting in this method public void onPlayerInteract(PlayerInteractEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { // check if player is in TTT round Challenger ch = TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get(); if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { // disallow cheating/bed setting if (event.getClickedBlock().getType() == Material.ENDER_CHEST || event.getClickedBlock().getType() == Material.BED_BLOCK) { event.setCancelled(true); return; } // handle body checking Location3D clicked = new Location3D( event.getClickedBlock().getWorld().getName(), event.getClickedBlock().getX(), event.getClickedBlock().getY(), event.getClickedBlock().getZ()); if (event.getClickedBlock().getType() == Material.CHEST || event.getClickedBlock().getType() == Material.TRAPPED_CHEST) { if (ch.isSpectating()) { event.setCancelled(true); for (Body b : TTTCore.bodies) { if (b.getLocation().equals(clicked)) { Inventory chestInv = ((Chest) event.getClickedBlock().getState()).getInventory(); Inventory inv = TTTCore.getInstance().getServer().createInventory(chestInv.getHolder(), chestInv.getSize()); inv.setContents(chestInv.getContents()); event.getPlayer().openInventory(inv); TTTCore.locale.getLocalizable("info.personal.status.discreet-search") .withPrefix(Color.INFO).sendTo(event.getPlayer()); break; } } } else { int index = -1; for (int i = 0; i < TTTCore.bodies.size(); i++) { if (TTTCore.bodies.get(i).getLocation() .equals(clicked)) { index = i; break; } } if (index != -1) { boolean found = false; for (Body b : TTTCore.foundBodies) { if (b.getLocation().equals(clicked)) { found = true; break; } } if (!found) { // it's a new body Body b = TTTCore.bodies.get(index); Optional<Challenger> bodyPlayer = TTTCore.mg.getChallenger(TTTCore.bodies.get(index).getPlayer()); //TODO: make this DRYer String color = ""; switch (b.getRole()) { case Role.INNOCENT: { color = Color.INNOCENT; break; } case Role.TRAITOR: { color = Color.TRAITOR; break; } case Role.DETECTIVE: { color = Color.DETECTIVE; break; } default: { event.getPlayer().sendMessage("Something's gone terribly wrong inside the TTT " + "plugin. Please notify an admin."); // eh, may as well tell the player throw new AssertionError("Failed to determine role of found body. " + "Report this immediately."); } } Localizable loc = TTTCore.locale.getLocalizable("info.global.round.event.body-find") .withPrefix(color); Localizable roleMsg = TTTCore.locale .getLocalizable("info.global.round.event.body-find." + b.getRole()); for (Challenger c : b.getRound().getChallengers()) { Player pl = Bukkit.getPlayer(c.getUniqueId()); pl.sendMessage(loc.withReplacements(event.getPlayer().getName(), b.getName()).localizeFor(pl) + " " + roleMsg.localizeFor(pl)); } TTTCore.foundBodies.add(TTTCore.bodies.get(index)); if (bodyPlayer.isPresent() && bodyPlayer.get().getRound().equals(TTTCore.bodies.get(index).getRound())) { //TODO: no Flint equivalent for this //bodyPlayer.setPrefix(Config.SB_ALIVE_PREFIX); bodyPlayer.get().getMetadata().set("bodyFound", true); if (ScoreboardManager.get(bodyPlayer.get().getRound()).isPresent()) { ScoreboardManager.get(bodyPlayer.get().getRound()).get() .update(bodyPlayer.get()); } } } if (ch.getMetadata().has(Role.DETECTIVE)) { // handle DNA scanning if (event.getPlayer().getItemInHand() != null && event.getPlayer().getItemInHand().getType() == Material.COMPASS && event.getPlayer().getItemInHand().getItemMeta() != null && event.getPlayer().getItemInHand().getItemMeta().getDisplayName() != null && event.getPlayer().getItemInHand().getItemMeta().getDisplayName().endsWith( TTTCore.locale.getLocalizable("item.dna-scanner.name").localize())) { event.setCancelled(true); Body body = TTTCore.bodies.get(index); if (body.getKiller().isPresent()) { Player killer = Bukkit.getPlayer(body.getKiller().get()); if (killer != null && TTTCore.mg.getChallenger(killer.getUniqueId()).isPresent()) { if (!TTTCore.mg.getChallenger(killer.getUniqueId()).get() .isSpectating()) { ch.getMetadata().set("tracking", body.getKiller().get()); } TTTCore.locale.getLocalizable("info.personal.status.collect-dna") .withPrefix(Color.INFO) .withReplacements(Bukkit.getPlayer(TTTCore.bodies.get(index) .getPlayer()).getName()) .sendTo(event.getPlayer()); } else { TTTCore.locale.getLocalizable("error.round.killer-left") .withPrefix(Color.ERROR).sendTo(event.getPlayer()); } } else { TTTCore.locale.getLocalizable("error.personal.status.no-dna") .withPrefix(Color.ERROR).sendTo(event.getPlayer()); } } } } } } } } // guns if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { if (event.getPlayer().getItemInHand() != null) { if (event.getPlayer().getItemInHand().getItemMeta() != null) { if (event.getPlayer().getItemInHand().getItemMeta().getDisplayName() != null) { if (event.getPlayer().getItemInHand().getItemMeta().getDisplayName() .endsWith(TTTCore.locale.getLocalizable("item.gun.name").localize())) { if ((TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent() && !TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get().isSpectating() && (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get().getRound() .getLifecycleStage() == Stage.PLAYING) )) { event.setCancelled(true); if (event.getPlayer().getInventory().contains(Material.ARROW) || !ConfigHelper.REQUIRE_AMMO_FOR_GUNS) { if (ConfigHelper.REQUIRE_AMMO_FOR_GUNS) { InventoryHelper.removeArrow(event.getPlayer().getInventory()); event.getPlayer().updateInventory(); } event.getPlayer().launchProjectile(Arrow.class); } else { TTTCore.locale.getLocalizable("info.personal.status.no-ammo") .withPrefix(Color.ERROR).sendTo(event.getPlayer()); } } } } } } } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamage(EntityDamageEvent event) { if (event.getEntityType() == EntityType.PLAYER) { Optional<Challenger> victim = TTTCore.mg.getChallenger(event.getEntity().getUniqueId()); if (victim.isPresent() && victim.get().getRound().getLifecycleStage() != Stage.PLAYING && event.getCause() == DamageCause.VOID) { event.setCancelled(true); Bukkit.getPlayer(victim.get().getUniqueId()).teleport( LocationHelper.convert(victim.get().getRound().getArena().getSpawnPoints().get(0)) ); return; } if (event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent ed = (EntityDamageByEntityEvent) event; if (ed.getDamager().getType() == EntityType.PLAYER || (ed.getDamager() instanceof Projectile && ((Projectile) ed.getDamager()).getShooter() instanceof Player)) { Player damager = ed.getDamager().getType() == EntityType.PLAYER ? (Player) ed.getDamager() : (Player) ((Projectile) ed.getDamager()).getShooter(); Optional<Challenger> damagerCh = TTTCore.mg.getChallenger(damager.getUniqueId()); if (damagerCh.isPresent()) { if (damagerCh.get().getRound().getLifecycleStage() != Stage.PLAYING || !victim.isPresent() || damagerCh.get().isSpectating()) { event.setCancelled(true); return; } if (damager.getItemInHand() != null) { if (damager.getItemInHand().getItemMeta() != null) { if (damager.getItemInHand().getItemMeta().getDisplayName() != null) { if (damager.getItemInHand().getItemMeta().getDisplayName() .endsWith(TTTCore.locale.getLocalizable("item.crowbar.name") .localize())) { event.setDamage(ConfigHelper.CROWBAR_DAMAGE); } } } } Optional<Double> reduc = damagerCh.get().getMetadata().get("damageRed"); if (reduc.isPresent()) { event.setDamage((int) (event.getDamage() * reduc.get())); } KarmaHelper.applyDamageKarma(damagerCh.get(), victim.get(), event.getDamage()); } } } } } @EventHandler public void onPlayerPickupItem(PlayerPickupItemEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); } } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); TTTCore.locale.getLocalizable("info.personal.status.no-drop").withPrefix(Color.ERROR) .sendTo(event.getPlayer()); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { if (!ConfigHelper.KARMA_PERSIST) { KarmaHelper.resetKarma(event.getPlayer().getUniqueId()); } } @EventHandler public void onHealthRegenerate(EntityRegainHealthEvent event) { if (event.getEntity() instanceof Player) { Player p = (Player) event.getEntity(); if (TTTCore.mg.getChallenger(p.getUniqueId()).isPresent()) { event.setCancelled(true); } } } @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryClick(InventoryClickEvent event) { for (HumanEntity he : event.getViewers()) { Player p = (Player) he; if (TTTCore.mg.getChallenger(p.getUniqueId()).isPresent()) { if (event.getInventory().getType() == InventoryType.CHEST) { Block block; Block block2 = null; if (event.getInventory().getHolder() instanceof Chest) { block = ((Chest) event.getInventory().getHolder()).getBlock(); } else if (event.getInventory().getHolder() instanceof DoubleChest) { block = ((Chest) ((DoubleChest) event.getInventory().getHolder()).getLeftSide()).getBlock(); block2 = ((Chest) ((DoubleChest) event.getInventory().getHolder()).getRightSide()).getBlock(); } else { return; } Location3D l1 = LocationHelper.convert(block.getLocation()); Location3D l2 = block2 != null ? LocationHelper.convert(block2.getLocation()) : null; for (Body b : TTTCore.bodies) { if (b.getLocation().equals(l1) || b.getLocation().equals(l2)) { event.setCancelled(true); return; } } } } } } //TODO: probably split this up a little @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { Player pl = event.getEntity(); // admittedly not the best way of doing this, but easiest for the purpose of porting Optional<Challenger> chOpt = TTTCore.mg.getChallenger(pl.getUniqueId()); if (chOpt.isPresent()) { Challenger ch = chOpt.get(); event.setDeathMessage(""); event.getDrops().clear(); Optional<Challenger> killer = Optional.absent(); if (event.getEntity().getKiller() != null) { UUID uuid = null; if (event.getEntity().getType() == EntityType.PLAYER) { uuid = event.getEntity().getKiller().getUniqueId(); } else if (event.getEntity().getKiller() instanceof Projectile) { ProjectileSource shooter = ((Projectile) event.getEntity()).getShooter(); if (shooter instanceof Player) { uuid = ((Player) shooter).getUniqueId(); } } if (uuid != null) { killer = TTTCore.mg.getChallenger(uuid); } } Location loc = pl.getLocation(); // sending the packet resets the location NmsHelper.sendRespawnPacket(pl); pl.teleport(loc); ch.setSpectating(true); //ch.setPrefix(Config.SB_MIA_PREFIX); //TODO pl.setHealth(pl.getMaxHealth()); if (ScoreboardManager.get(ch.getRound()).isPresent()) { ScoreboardManager.get(ch.getRound()).get().update(ch); } if (killer.isPresent()) { // set killer's karma KarmaHelper.applyKillKarma(killer.get(), ch); ch.getMetadata().set("killer", killer.get().getUniqueId()); } Block block = loc.getBlock(); //TTTCore.mg.getRollbackManager().logBlockChange(block, ch.getArena()); //TODO (probably Flint 1.1) //TODO: Add check for doors and such //TODO: move this code to another method try { //TODO: temporary hack (I'm still a terrible person for even writing this) if (fieldRbHelper == null) { fieldRbHelper = ch.getRound().getArena().getClass().getDeclaredField("rbHelper"); fieldRbHelper.setAccessible(true); } Object rbHelper = fieldRbHelper.get(ch.getRound().getArena()); if (logBlockChange == null) { logBlockChange = rbHelper.getClass().getDeclaredMethod("logBlockChange", Location.class, BlockState.class); logBlockChange.setAccessible(true); } logBlockChange.invoke(rbHelper, loc, loc.getBlock().getState()); } catch (IllegalAccessException | InvocationTargetException | NoSuchFieldException | NoSuchMethodException ex) { TTTCore.log.severe("Failed to log body for rollback"); ex.printStackTrace(); } block.setType(((loc.getBlockX() + loc.getBlockY()) % 2 == 0) ? Material.TRAPPED_CHEST : Material.CHEST); Chest chest = (Chest) block.getState(); // player identifier ItemStack id = new ItemStack(Material.PAPER, 1); ItemMeta idMeta = id.getItemMeta(); idMeta.setDisplayName(TTTCore.locale.getLocalizable("item.id.name").localize()); List<String> idLore = new ArrayList<>(); idLore.add(TTTCore.locale.getLocalizable("corpse.of").withReplacements(ch.getName()).localize()); idLore.add(ch.getName()); idMeta.setLore(idLore); id.setItemMeta(idMeta); // role identifier ItemStack ti = new ItemStack(Material.WOOL, 1); ItemMeta tiMeta = ti.getItemMeta(); short durability; String roleId = ""; if (ch.getMetadata().has(Role.DETECTIVE)) { durability = 11; roleId = "detective"; } else if (!MiscUtil.isTraitor(ch)) { durability = 5; roleId = "innocent"; } else { durability = 14; roleId = "traitor"; } ti.setDurability(durability); tiMeta.setDisplayName(TTTCore.locale.getLocalizable("fragment." + roleId) .withPrefix(Color.DETECTIVE).localize()); tiMeta.setLore(Collections.singletonList(TTTCore.locale.getLocalizable("item.id." + roleId).localize())); ti.setItemMeta(tiMeta); chest.getInventory().addItem(id, ti); TTTCore.bodies.add( new Body( ch.getRound(), LocationHelper.convert(block.getLocation()), ch.getUniqueId(), ch.getName(), killer.isPresent() ? killer.get().getUniqueId() : null, ch.getMetadata().has(Role.DETECTIVE) ? Role.DETECTIVE : (ch.getTeam().isPresent() ? ch.getTeam().get().getId() : null), System.currentTimeMillis() ) ); } } @EventHandler public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { String label = event.getMessage().split(" ")[0].substring(1); if (disabledCommands.contains(label)) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); TTTCore.locale.getLocalizable("error.round.disabled-command").withPrefix(Color.ERROR) .sendTo(event.getPlayer()); } } } @EventHandler public void onFoodLevelChange(FoodLevelChangeEvent event) { if (TTTCore.mg.getChallenger(event.getEntity().getUniqueId()).isPresent()) { event.setCancelled(true); } } }
src/main/java/net/caseif/ttt/listeners/PlayerListener.java
/* * The MIT License (MIT) * * Copyright (c) 2013-2015, Maxim Roncacé <mproncace@lapis.blue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.caseif.ttt.listeners; import net.caseif.ttt.Body; import net.caseif.ttt.TTTCore; import net.caseif.ttt.scoreboard.ScoreboardManager; import net.caseif.ttt.util.Constants.Color; import net.caseif.ttt.util.Constants.Role; import net.caseif.ttt.util.Constants.Stage; import net.caseif.ttt.util.MiscUtil; import net.caseif.ttt.util.helper.ConfigHelper; import net.caseif.ttt.util.helper.InventoryHelper; import net.caseif.ttt.util.helper.KarmaHelper; import net.caseif.ttt.util.helper.LocationHelper; import net.caseif.ttt.util.helper.NmsHelper; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import net.caseif.flint.challenger.Challenger; import net.caseif.flint.util.physical.Location3D; import net.caseif.rosetta.Localizable; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.DoubleChest; import org.bukkit.entity.Arrow; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.projectiles.ProjectileSource; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; public class PlayerListener implements Listener { private final ImmutableList<String> disabledCommands = ImmutableList.of("kit", "msg", "pm", "r", "me"); private static Field fieldRbHelper; private static Method logBlockChange; @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) //TODO: fix the crazy nesting in this method public void onPlayerInteract(PlayerInteractEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { // check if player is in TTT round Challenger ch = TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get(); if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { // disallow cheating/bed setting if (event.getClickedBlock().getType() == Material.ENDER_CHEST || event.getClickedBlock().getType() == Material.BED_BLOCK) { event.setCancelled(true); return; } // handle body checking Location3D clicked = new Location3D( event.getClickedBlock().getWorld().getName(), event.getClickedBlock().getX(), event.getClickedBlock().getY(), event.getClickedBlock().getZ()); if (event.getClickedBlock().getType() == Material.CHEST || event.getClickedBlock().getType() == Material.TRAPPED_CHEST) { if (ch.isSpectating()) { event.setCancelled(true); for (Body b : TTTCore.bodies) { if (b.getLocation().equals(clicked)) { Inventory chestInv = ((Chest) event.getClickedBlock().getState()).getInventory(); Inventory inv = TTTCore.getInstance().getServer().createInventory(chestInv.getHolder(), chestInv.getSize()); inv.setContents(chestInv.getContents()); event.getPlayer().openInventory(inv); TTTCore.locale.getLocalizable("info.personal.status.discreet-search") .withPrefix(Color.INFO).sendTo(event.getPlayer()); break; } } } else { int index = -1; for (int i = 0; i < TTTCore.bodies.size(); i++) { if (TTTCore.bodies.get(i).getLocation() .equals(clicked)) { index = i; break; } } if (index != -1) { boolean found = false; for (Body b : TTTCore.foundBodies) { if (b.getLocation().equals(clicked)) { found = true; break; } } if (!found) { // it's a new body Body b = TTTCore.bodies.get(index); Optional<Challenger> bodyPlayer = TTTCore.mg.getChallenger(TTTCore.bodies.get(index).getPlayer()); //TODO: make this DRYer String color = ""; switch (b.getRole()) { case Role.INNOCENT: { color = Color.INNOCENT; break; } case Role.TRAITOR: { color = Color.TRAITOR; break; } case Role.DETECTIVE: { color = Color.DETECTIVE; break; } default: { event.getPlayer().sendMessage("Something's gone terribly wrong inside the TTT " + "plugin. Please notify an admin."); // eh, may as well tell the player throw new AssertionError("Failed to determine role of found body. " + "Report this immediately."); } } Localizable loc = TTTCore.locale.getLocalizable("info.global.round.event.body-find") .withPrefix(color); Localizable roleMsg = TTTCore.locale .getLocalizable("info.global.round.event.body-find." + b.getRole()); for (Challenger c : b.getRound().getChallengers()) { Player pl = Bukkit.getPlayer(c.getUniqueId()); pl.sendMessage(loc.withReplacements(event.getPlayer().getName(), b.getName()).localizeFor(pl) + " " + roleMsg.localizeFor(pl)); } TTTCore.foundBodies.add(TTTCore.bodies.get(index)); if (bodyPlayer.isPresent() && bodyPlayer.get().getRound().equals(TTTCore.bodies.get(index).getRound())) { //TODO: no Flint equivalent for this //bodyPlayer.setPrefix(Config.SB_ALIVE_PREFIX); bodyPlayer.get().getMetadata().set("bodyFound", true); if (ScoreboardManager.get(bodyPlayer.get().getRound()).isPresent()) { ScoreboardManager.get(bodyPlayer.get().getRound()).get() .update(bodyPlayer.get()); } } } if (ch.getMetadata().has(Role.DETECTIVE)) { // handle DNA scanning if (event.getPlayer().getItemInHand() != null && event.getPlayer().getItemInHand().getType() == Material.COMPASS && event.getPlayer().getItemInHand().getItemMeta() != null && event.getPlayer().getItemInHand().getItemMeta().getDisplayName() != null && event.getPlayer().getItemInHand().getItemMeta().getDisplayName().endsWith( TTTCore.locale.getLocalizable("item.dna-scanner.name").localize())) { event.setCancelled(true); Body body = TTTCore.bodies.get(index); if (body.getKiller().isPresent()) { Player killer = Bukkit.getPlayer(body.getKiller().get()); if (killer != null && TTTCore.mg.getChallenger(killer.getUniqueId()).isPresent()) { if (!TTTCore.mg.getChallenger(killer.getUniqueId()).get() .isSpectating()) { ch.getMetadata().set("tracking", body.getKiller().get()); } TTTCore.locale.getLocalizable("info.personal.status.collect-dna") .withPrefix(Color.INFO) .withReplacements(Bukkit.getPlayer(TTTCore.bodies.get(index) .getPlayer()).getName()) .sendTo(event.getPlayer()); } else { TTTCore.locale.getLocalizable("error.round.killer-left") .withPrefix(Color.ERROR).sendTo(event.getPlayer()); } } else { TTTCore.locale.getLocalizable("error.personal.status.no-dna") .withPrefix(Color.ERROR).sendTo(event.getPlayer()); } } } } } } } } // guns if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { if (event.getPlayer().getItemInHand() != null) { if (event.getPlayer().getItemInHand().getItemMeta() != null) { if (event.getPlayer().getItemInHand().getItemMeta().getDisplayName() != null) { if (event.getPlayer().getItemInHand().getItemMeta().getDisplayName() .endsWith(TTTCore.locale.getLocalizable("item.gun.name").localize())) { if ((TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent() && !TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get().isSpectating() && (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get().getRound() .getLifecycleStage() == Stage.PLAYING) )) { event.setCancelled(true); if (event.getPlayer().getInventory().contains(Material.ARROW) || !ConfigHelper.REQUIRE_AMMO_FOR_GUNS) { if (ConfigHelper.REQUIRE_AMMO_FOR_GUNS) { InventoryHelper.removeArrow(event.getPlayer().getInventory()); event.getPlayer().updateInventory(); } event.getPlayer().launchProjectile(Arrow.class); } else { TTTCore.locale.getLocalizable("info.personal.status.no-ammo") .withPrefix(Color.ERROR).sendTo(event.getPlayer()); } } } } } } } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamage(EntityDamageEvent event) { if (event.getEntityType() == EntityType.PLAYER) { Optional<Challenger> victim = TTTCore.mg.getChallenger(event.getEntity().getUniqueId()); if (victim.isPresent() && victim.get().getRound().getLifecycleStage() != Stage.PLAYING) { if (event.getCause() == DamageCause.VOID) { Bukkit.getPlayer(victim.get().getUniqueId()); } else { event.setCancelled(true); } } if (event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent ed = (EntityDamageByEntityEvent) event; if (ed.getDamager().getType() == EntityType.PLAYER || (ed.getDamager() instanceof Projectile && ((Projectile) ed.getDamager()).getShooter() instanceof Player)) { Player damager = ed.getDamager().getType() == EntityType.PLAYER ? (Player) ed.getDamager() : (Player) ((Projectile) ed.getDamager()).getShooter(); if (TTTCore.mg.getChallenger(damager.getUniqueId()).isPresent()) { Challenger mgDamager = TTTCore.mg.getChallenger(damager.getUniqueId()).get(); if (mgDamager.getRound().getLifecycleStage() != Stage.PLAYING || !victim.isPresent()) { event.setCancelled(true); return; } if (damager.getItemInHand() != null) { if (damager.getItemInHand().getItemMeta() != null) { if (damager.getItemInHand().getItemMeta().getDisplayName() != null) { if (damager.getItemInHand().getItemMeta().getDisplayName() .endsWith(TTTCore.locale.getLocalizable("item.crowbar.name") .localize())) { event.setDamage(ConfigHelper.CROWBAR_DAMAGE); } } } } Optional<Double> reduc = mgDamager.getMetadata().get("damageRed"); if (reduc.isPresent()) { event.setDamage((int) (event.getDamage() * reduc.get())); } KarmaHelper.applyDamageKarma(mgDamager, victim.get(), event.getDamage()); } } } } } @EventHandler public void onPlayerPickupItem(PlayerPickupItemEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); } } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); TTTCore.locale.getLocalizable("info.personal.status.no-drop").withPrefix(Color.ERROR) .sendTo(event.getPlayer()); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { if (!ConfigHelper.KARMA_PERSIST) { KarmaHelper.resetKarma(event.getPlayer().getUniqueId()); } } @EventHandler public void onHealthRegenerate(EntityRegainHealthEvent event) { if (event.getEntity() instanceof Player) { Player p = (Player) event.getEntity(); if (TTTCore.mg.getChallenger(p.getUniqueId()).isPresent()) { event.setCancelled(true); } } } @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryClick(InventoryClickEvent event) { for (HumanEntity he : event.getViewers()) { Player p = (Player) he; if (TTTCore.mg.getChallenger(p.getUniqueId()).isPresent()) { if (event.getInventory().getType() == InventoryType.CHEST) { Block block; Block block2 = null; if (event.getInventory().getHolder() instanceof Chest) { block = ((Chest) event.getInventory().getHolder()).getBlock(); } else if (event.getInventory().getHolder() instanceof DoubleChest) { block = ((Chest) ((DoubleChest) event.getInventory().getHolder()).getLeftSide()).getBlock(); block2 = ((Chest) ((DoubleChest) event.getInventory().getHolder()).getRightSide()).getBlock(); } else { return; } Location3D l1 = LocationHelper.convert(block.getLocation()); Location3D l2 = block2 != null ? LocationHelper.convert(block2.getLocation()) : null; for (Body b : TTTCore.bodies) { if (b.getLocation().equals(l1) || b.getLocation().equals(l2)) { event.setCancelled(true); return; } } } } } } //TODO: probably split this up a little @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { Player pl = event.getEntity(); // admittedly not the best way of doing this, but easiest for the purpose of porting Optional<Challenger> chOpt = TTTCore.mg.getChallenger(pl.getUniqueId()); if (chOpt.isPresent()) { Challenger ch = chOpt.get(); event.setDeathMessage(""); event.getDrops().clear(); Optional<Challenger> killer = Optional.absent(); if (event.getEntity().getKiller() != null) { UUID uuid = null; if (event.getEntity().getType() == EntityType.PLAYER) { uuid = event.getEntity().getKiller().getUniqueId(); } else if (event.getEntity().getKiller() instanceof Projectile) { ProjectileSource shooter = ((Projectile) event.getEntity()).getShooter(); if (shooter instanceof Player) { uuid = ((Player) shooter).getUniqueId(); } } if (uuid != null) { killer = TTTCore.mg.getChallenger(uuid); } } Location loc = pl.getLocation(); // sending the packet resets the location NmsHelper.sendRespawnPacket(pl); pl.teleport(loc); ch.setSpectating(true); //ch.setPrefix(Config.SB_MIA_PREFIX); //TODO pl.setHealth(pl.getMaxHealth()); if (ScoreboardManager.get(ch.getRound()).isPresent()) { ScoreboardManager.get(ch.getRound()).get().update(ch); } if (killer.isPresent()) { // set killer's karma KarmaHelper.applyKillKarma(killer.get(), ch); ch.getMetadata().set("killer", killer.get().getUniqueId()); } Block block = loc.getBlock(); //TTTCore.mg.getRollbackManager().logBlockChange(block, ch.getArena()); //TODO (probably Flint 1.1) //TODO: Add check for doors and such //TODO: move this code to another method try { //TODO: temporary hack (I'm still a terrible person for even writing this) if (fieldRbHelper == null) { fieldRbHelper = ch.getRound().getArena().getClass().getDeclaredField("rbHelper"); fieldRbHelper.setAccessible(true); } Object rbHelper = fieldRbHelper.get(ch.getRound().getArena()); if (logBlockChange == null) { logBlockChange = rbHelper.getClass().getDeclaredMethod("logBlockChange", Location.class, BlockState.class); logBlockChange.setAccessible(true); } logBlockChange.invoke(rbHelper, loc, loc.getBlock().getState()); } catch (IllegalAccessException | InvocationTargetException | NoSuchFieldException | NoSuchMethodException ex) { TTTCore.log.severe("Failed to log body for rollback"); ex.printStackTrace(); } block.setType(((loc.getBlockX() + loc.getBlockY()) % 2 == 0) ? Material.TRAPPED_CHEST : Material.CHEST); Chest chest = (Chest) block.getState(); // player identifier ItemStack id = new ItemStack(Material.PAPER, 1); ItemMeta idMeta = id.getItemMeta(); idMeta.setDisplayName(TTTCore.locale.getLocalizable("item.id.name").localize()); List<String> idLore = new ArrayList<>(); idLore.add(TTTCore.locale.getLocalizable("corpse.of").withReplacements(ch.getName()).localize()); idLore.add(ch.getName()); idMeta.setLore(idLore); id.setItemMeta(idMeta); // role identifier ItemStack ti = new ItemStack(Material.WOOL, 1); ItemMeta tiMeta = ti.getItemMeta(); short durability; String roleId = ""; if (ch.getMetadata().has(Role.DETECTIVE)) { durability = 11; roleId = "detective"; } else if (!MiscUtil.isTraitor(ch)) { durability = 5; roleId = "innocent"; } else { durability = 14; roleId = "traitor"; } ti.setDurability(durability); tiMeta.setDisplayName(TTTCore.locale.getLocalizable("fragment." + roleId) .withPrefix(Color.DETECTIVE).localize()); tiMeta.setLore(Collections.singletonList(TTTCore.locale.getLocalizable("item.id." + roleId).localize())); ti.setItemMeta(tiMeta); chest.getInventory().addItem(id, ti); TTTCore.bodies.add( new Body( ch.getRound(), LocationHelper.convert(block.getLocation()), ch.getUniqueId(), ch.getName(), killer.isPresent() ? killer.get().getUniqueId() : null, ch.getMetadata().has(Role.DETECTIVE) ? Role.DETECTIVE : (ch.getTeam().isPresent() ? ch.getTeam().get().getId() : null), System.currentTimeMillis() ) ); } } @EventHandler public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { String label = event.getMessage().split(" ")[0].substring(1); if (disabledCommands.contains(label)) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); TTTCore.locale.getLocalizable("error.round.disabled-command").withPrefix(Color.ERROR) .sendTo(event.getPlayer()); } } } @EventHandler public void onFoodLevelChange(FoodLevelChangeEvent event) { if (TTTCore.mg.getChallenger(event.getEntity().getUniqueId()).isPresent()) { event.setCancelled(true); } } }
Fix karma update for spectators on 1.7
src/main/java/net/caseif/ttt/listeners/PlayerListener.java
Fix karma update for spectators on 1.7
Java
mit
ac41555ad0ed1b4433d5717a9527da55b6ac6bcc
0
OpenModularTurretsTeam/OMLib,OpenModularTurretsTeam/OMLib
package omtteam.omlib.render; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import omtteam.omlib.tileentity.ICamoSupport; import javax.annotation.Nullable; /** * Created by Keridos on 31/01/17. * This Class maps the camo state for the camo blocks to vanilla block colors. */ @SideOnly(Side.CLIENT) public class CamoBlockColor implements IBlockColor { @Override public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { if (worldIn != null && pos != null && worldIn.getTileEntity(pos) instanceof ICamoSupport && state != ((ICamoSupport) worldIn.getTileEntity(pos)).getCamoState()) { IBlockState camoState = ((ICamoSupport) worldIn.getTileEntity(pos)).getCamoState(); return Minecraft.getMinecraft().getBlockColors().colorMultiplier(camoState, worldIn, pos, tintIndex); } return -1; } }
src/main/java/omtteam/omlib/render/CamoBlockColor.java
package omtteam.omlib.render; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import omtteam.omlib.tileentity.ICamoSupport; import javax.annotation.Nullable; /** * Created by Keridos on 31/01/17. * This Class maps the camo state for the camo blocks to vanilla block colors. */ @SideOnly(Side.CLIENT) public class CamoBlockColor implements IBlockColor { @Override public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { if (worldIn.getTileEntity(pos) instanceof ICamoSupport && state != ((ICamoSupport) worldIn.getTileEntity(pos)).getCamoState()) { IBlockState camoState = ((ICamoSupport) worldIn.getTileEntity(pos)).getCamoState(); return Minecraft.getMinecraft().getBlockColors().colorMultiplier(camoState, worldIn, pos, tintIndex); } return -1; } }
fix https://github.com/OpenModularTurretsTeam/OpenModularTurrets/issues/316
src/main/java/omtteam/omlib/render/CamoBlockColor.java
fix https://github.com/OpenModularTurretsTeam/OpenModularTurrets/issues/316
Java
mit
a03f41081565221d029f22113325166667643982
0
lasarobotics/FTC4290-2015,lasarobotics/FTC4290-2015
package com.qualcomm.ftcrobotcontroller.opmodes; import com.lasarobotics.library.controller.ButtonState; import com.lasarobotics.library.controller.Controller; import com.lasarobotics.library.drive.Tank; import com.qualcomm.ftcrobotcontroller.Hardware; import com.qualcomm.robotcore.eventloop.opmode.OpMode; public class TeleOp extends OpMode { Hardware config; Controller driver, operator; double winchPower = 0, leftPosition = Hardware.LEFT_SERVO_TOP, rightPosition = Hardware.RIGHT_SERVO_TOP, climberPosition = Hardware.CLIMBER_BOTTOM, anglerPower = 0, stopperPosition = Hardware.STOPPER_OFF, leftGPosition = Hardware.LEFT_GRABBER_UP, rightGPosition = Hardware.RIGHT_GRABBER_UP; public static double grabberL(Controller controller, double pos) { if (controller.x == ButtonState.PRESSED && pos != Hardware.LEFT_GRABBER_DOWN) { return Hardware.LEFT_GRABBER_DOWN; } else if (controller.x == ButtonState.PRESSED) { return Hardware.LEFT_GRABBER_UP; } return pos; } public static double grabberR(Controller controller, double pos) { if (controller.x == ButtonState.PRESSED && pos != Hardware.RIGHT_GRABBER_DOWN) { return Hardware.RIGHT_GRABBER_DOWN; } else if (controller.x == ButtonState.PRESSED) { return Hardware.RIGHT_GRABBER_UP; } return pos; } public static double climberDump(Controller controller, double pos) { if (controller.y == ButtonState.PRESSED && pos != Hardware.CLIMBER_TOP) { return Hardware.CLIMBER_TOP; } else if (controller.y == ButtonState.PRESSED) { return Hardware.CLIMBER_BOTTOM; } return pos; } public static double leftServo(Controller controller, double pos) { if (controller.x == ButtonState.PRESSED && pos != Hardware.LEFT_SERVO_TOP) { return Hardware.LEFT_SERVO_TOP; } else if (controller.x == ButtonState.PRESSED) { return Hardware.LEFT_SERVO_BOTTOM; } return pos; } public static double rightServo(Controller controller, double pos) { if (controller.b == ButtonState.PRESSED && pos != Hardware.RIGHT_SERVO_TOP) { return Hardware.RIGHT_SERVO_TOP; } else if (controller.b == ButtonState.PRESSED) { return Hardware.RIGHT_SERVO_BOTTOM; } return pos; } public static double stopper(Controller controller, double pos) { if (controller.a == ButtonState.PRESSED && pos != Hardware.STOPPER_ON) { return Hardware.STOPPER_ON; } else if (controller.a == ButtonState.PRESSED) { return Hardware.STOPPER_OFF; } return pos; } public static double winch(Controller controller) { if (Math.abs(controller.right_stick_y) > .1) { return controller.right_stick_y; } else { return 0; } } public static double angler(Controller controller) { if (controller.y == ButtonState.HELD) {//go up return .75; } else if (controller.a == ButtonState.HELD) {//go down return -.75; } else { return 0; } } public void housekeeping() { driver.update(gamepad1); operator.update(gamepad2); displayTelemetry(); } @Override public void init() { config = new Hardware(hardwareMap); driver = new Controller(gamepad1); operator = new Controller(gamepad2); } @Override public void loop() { housekeeping(); config.leftGrabber.setPosition(grabberL(driver, config.leftGrabber.getPosition())); config.rightGrabber.setPosition(grabberR(driver, config.rightGrabber.getPosition())); config.climber.setPosition(climberDump(operator, config.climber.getPosition())); config.climberLeft.setPosition(leftServo(operator, config.climberLeft.getPosition())); config.climberRight.setPosition(rightServo(operator, config.climberRight.getPosition())); config.stopper.setPosition(stopper(operator, config.stopper.getPosition())); config.winch1.setPower(winch(operator)); config.winch2.setPower(winch(operator)); config.angler.setPower(angler(driver)); Tank.motor2(config.leftWheel, config.rightWheel, driver.left_stick_y, driver.right_stick_y); } public void displayTelemetry() { if (leftPosition == Hardware.LEFT_SERVO_TOP) { telemetry.addData("Left Servo Is", "Off"); } else if (leftPosition == Hardware.LEFT_SERVO_BOTTOM) { telemetry.addData("Left Servo Is", "On"); } else { telemetry.addData("Left Servo Is", "Not Connected!"); } if (leftGPosition == Hardware.LEFT_GRABBER_UP) { telemetry.addData("Left Grabber Is", "Up"); } else if (leftGPosition == Hardware.LEFT_GRABBER_DOWN) { telemetry.addData("Left Grabber Is", "Down"); } else { telemetry.addData("Left Grabber Is", "Not Connected!"); } if (rightGPosition == Hardware.RIGHT_GRABBER_DOWN) { telemetry.addData("Right Grabber Is", "Down"); } else if (rightGPosition == Hardware.RIGHT_GRABBER_UP) { telemetry.addData("Right Grabber Is", "Up"); } else { telemetry.addData("Left Grabber Is", "Not Connected!"); } if (rightPosition == Hardware.RIGHT_SERVO_TOP) { telemetry.addData("Right Servo Is", "Off"); } else if (rightPosition == Hardware.RIGHT_SERVO_BOTTOM) { telemetry.addData("Right Servo Is", "On"); } else { telemetry.addData("Right Servo Is", "Not Connected!"); } if (climberPosition == Hardware.CLIMBER_BOTTOM) { telemetry.addData("Climber Servo Is", "Off"); } else if (climberPosition == Hardware.CLIMBER_TOP) { telemetry.addData("Climber Servo Is", "On"); } else { telemetry.addData("Climber Servo Is", "Not Connected!"); } if (stopperPosition == Hardware.STOPPER_ON) { telemetry.addData("Stopper Servo Is", "On"); } else if (stopperPosition == Hardware.STOPPER_OFF) { telemetry.addData("Stopper Servo Is", "Off"); } telemetry.addData("Left Motor Encoder: ", config.leftWheel.getCurrentPosition()); telemetry.addData("Right Motor Encoder: ", config.rightWheel.getCurrentPosition()); telemetry.addData("Winch2 Encoder: ", config.winch2.getCurrentPosition()); telemetry.addData("Left Motor Power: ", driver.left_stick_y); telemetry.addData("Right Motor Power: ", driver.right_stick_y); telemetry.addData("Winch Power: ", winchPower); telemetry.addData("Angler Power:", anglerPower); } }
FtcRobotController/src/main/java/com/qualcomm/ftcrobotcontroller/opmodes/TeleOp.java
package com.qualcomm.ftcrobotcontroller.opmodes; import com.lasarobotics.library.controller.ButtonState; import com.lasarobotics.library.controller.Controller; import com.lasarobotics.library.drive.Tank; import com.qualcomm.ftcrobotcontroller.Hardware; import com.qualcomm.robotcore.eventloop.opmode.OpMode; public class TeleOp extends OpMode { Hardware config; Controller driver, operator; double winchPower = 0, leftPosition = Hardware.LEFT_SERVO_TOP, rightPosition = Hardware.RIGHT_SERVO_TOP, climberPosition = Hardware.CLIMBER_BOTTOM, anglerPower = 0, stopperPosition = Hardware.STOPPER_OFF, leftGPosition = Hardware.LEFT_GRABBER_UP, rightGPosition = Hardware.RIGHT_GRABBER_UP; public void grabbers() { if (driver.x == ButtonState.PRESSED && leftGPosition != Hardware.LEFT_GRABBER_DOWN) { leftGPosition = Hardware.LEFT_GRABBER_DOWN; rightGPosition = Hardware.RIGHT_GRABBER_DOWN; } else if (driver.x == ButtonState.PRESSED) { leftGPosition = Hardware.LEFT_GRABBER_UP; rightGPosition = Hardware.RIGHT_GRABBER_UP; } } public void climberDump() { if (operator.y == ButtonState.PRESSED && climberPosition != Hardware.CLIMBER_TOP) { climberPosition = Hardware.CLIMBER_TOP; } else if (operator.y == ButtonState.PRESSED) { climberPosition = Hardware.CLIMBER_BOTTOM; } } public void leftServo() { if (operator.x == ButtonState.PRESSED && leftPosition != Hardware.LEFT_SERVO_TOP) { leftPosition = Hardware.LEFT_SERVO_TOP; } else if (operator.x == ButtonState.PRESSED) { leftPosition = Hardware.LEFT_SERVO_BOTTOM; } } public void rightServo() { if (operator.b == ButtonState.PRESSED && rightPosition != Hardware.RIGHT_SERVO_TOP) { rightPosition = Hardware.RIGHT_SERVO_TOP; } else if (operator.b == ButtonState.PRESSED) { rightPosition = Hardware.RIGHT_SERVO_BOTTOM; } } public void stopper() { if (operator.a == ButtonState.PRESSED && stopperPosition != Hardware.STOPPER_ON) { stopperPosition = Hardware.STOPPER_ON; } else if (operator.a == ButtonState.PRESSED) { stopperPosition = Hardware.STOPPER_OFF; } } public void winch() { if (Math.abs(operator.right_stick_y) > .1 && stopperPosition != Hardware.STOPPER_ON) { winchPower = operator.right_stick_y; } else { winchPower = 0; } } public void angler() { if (driver.y == ButtonState.HELD) {//go up anglerPower = .75; } else if (driver.a == ButtonState.HELD) {//go down anglerPower = -.75; } else { anglerPower = 0; } } public void housekeeping() { driver.update(gamepad1); operator.update(gamepad2); displayTelemetry(); } @Override public void init() { config = new Hardware(hardwareMap); driver = new Controller(gamepad1); operator = new Controller(gamepad2); } @Override public void loop() { housekeeping(); grabbers(); config.rightGrabber.setPosition(rightGPosition); config.leftGrabber.setPosition(leftGPosition); climberDump(); config.climber.setPosition(climberPosition); leftServo(); config.climberLeft.setPosition(leftPosition); rightServo(); config.climberRight.setPosition(rightPosition); stopper(); config.stopper.setPosition(stopperPosition); winch(); config.winch1.setPower(winchPower); config.winch2.setPower(winchPower); angler(); config.angler.setPower(anglerPower); Tank.motor2(config.leftWheel, config.rightWheel, driver.left_stick_y, driver.right_stick_y); } public void displayTelemetry() { if (leftPosition == Hardware.LEFT_SERVO_TOP) { telemetry.addData("Left Servo Is", "Off"); } else if (leftPosition == Hardware.LEFT_SERVO_BOTTOM) { telemetry.addData("Left Servo Is", "On"); } else { telemetry.addData("Left Servo Is", "Not Connected!"); } if (leftGPosition == Hardware.LEFT_GRABBER_UP) { telemetry.addData("Left Grabber Is", "Up"); } else if (leftGPosition == Hardware.LEFT_GRABBER_DOWN) { telemetry.addData("Left Grabber Is", "Down"); } else { telemetry.addData("Left Grabber Is", "Not Connected!"); } if (rightGPosition == Hardware.RIGHT_GRABBER_DOWN) { telemetry.addData("Right Grabber Is", "Down"); } else if (rightGPosition == Hardware.RIGHT_GRABBER_UP) { telemetry.addData("Right Grabber Is", "Up"); } else { telemetry.addData("Left Grabber Is", "Not Connected!"); } if (rightPosition == Hardware.RIGHT_SERVO_TOP) { telemetry.addData("Right Servo Is", "Off"); } else if (rightPosition == Hardware.RIGHT_SERVO_BOTTOM) { telemetry.addData("Right Servo Is", "On"); } else { telemetry.addData("Right Servo Is", "Not Connected!"); } if (climberPosition == Hardware.CLIMBER_BOTTOM) { telemetry.addData("Climber Servo Is", "Off"); } else if (climberPosition == Hardware.CLIMBER_TOP) { telemetry.addData("Climber Servo Is", "On"); } else { telemetry.addData("Climber Servo Is", "Not Connected!"); } if (stopperPosition == Hardware.STOPPER_ON) { telemetry.addData("Stopper Servo Is", "On"); } else if (stopperPosition == Hardware.STOPPER_OFF) { telemetry.addData("Stopper Servo Is", "Off"); } telemetry.addData("Left Motor Encoder: ", config.leftWheel.getCurrentPosition()); telemetry.addData("Right Motor Encoder: ", config.rightWheel.getCurrentPosition()); telemetry.addData("Winch2 Encoder: ", config.winch2.getCurrentPosition()); telemetry.addData("Left Motor Power: ", driver.left_stick_y); telemetry.addData("Right Motor Power: ", driver.right_stick_y); telemetry.addData("Winch Power: ", winchPower); telemetry.addData("Angler Power:", anglerPower); } }
Modularity+Code Review Had to do some file diving, so @Oksisane and @Shwinn you should both make sure nothing seems out of place.
FtcRobotController/src/main/java/com/qualcomm/ftcrobotcontroller/opmodes/TeleOp.java
Modularity+Code Review
Java
mit
557f1785b5c4ab646aded52edc3b38d66dc8e074
0
TeamWizardry/TMT-Refraction
package com.teamwizardry.refraction.init; import com.teamwizardry.refraction.Refraction; import com.teamwizardry.refraction.common.achievement.ModAchievement; import net.minecraft.stats.Achievement; import net.minecraftforge.common.AchievementPage; /** * Created by Saad on 7/1/2016. */ public class ModAchievements { public static ModAchievement PRISM; public static ModAchievement TRANSLOCATOR; public static ModAchievement LIGHT_BRIDGE; public static ModAchievement LASER_PEN; public static ModAchievement GRENADE; public static ModAchievement AXYZ; public static AchievementPage PAGE; public static void init() { PRISM = new ModAchievement("prism", 1, -2, ModBlocks.PRISM, null); TRANSLOCATOR = new ModAchievement("translocator", 3, 0, ModBlocks.TRANSLOCATOR, null); LIGHT_BRIDGE = new ModAchievement("light_bridge", -1, 0, ModBlocks.ELECTRON_EXCITER, null); LASER_PEN = new ModAchievement("laser_pen", 1, 2, ModItems.LASER_PEN, null); GRENADE = new ModAchievement("grenade", -1, 2, ModItems.GRENADE, null); AXYZ = new ModAchievement("axyz", -1, 2, ModBlocks.AXYZ, TRANSLOCATOR); PAGE = new AchievementPage(Refraction.MOD_NAME, ModAchievement.achievements.toArray(new Achievement[ModAchievement.achievements.size()])); AchievementPage.registerAchievementPage(PAGE); } }
src/main/java/com/teamwizardry/refraction/init/ModAchievements.java
package com.teamwizardry.refraction.init; import com.teamwizardry.refraction.Refraction; import com.teamwizardry.refraction.common.achievement.ModAchievement; import net.minecraft.stats.Achievement; import net.minecraftforge.common.AchievementPage; /** * Created by Saad on 7/1/2016. */ public class ModAchievements { public static ModAchievement PRISM; public static ModAchievement TRANSLOCATOR; public static ModAchievement LIGHT_BRIDGE; public static ModAchievement LASER_PEN; public static ModAchievement GRENADE; public static ModAchievement AXYZ; public static AchievementPage PAGE; public static void init() { PRISM = new ModAchievement("prism", 1, -2, ModBlocks.PRISM, null); TRANSLOCATOR = new ModAchievement("translocator", 3, 0, ModBlocks.TRANSLOCATOR, null); LIGHT_BRIDGE = new ModAchievement("light_bridge", -1, 0, ModBlocks.ELECTRON_EXCITER, null); LASER_PEN = new ModAchievement("laser_pen", 1, 2, ModItems.LASER_PEN, null); GRENADE = new ModAchievement("grenade", -1, 2, ModItems.GRENADE, null); AXYZ = new ModAchievement("axyz", -1, 0, ModBlocks.AXYZ, TRANSLOCATOR); PAGE = new AchievementPage(Refraction.MOD_NAME, ModAchievement.achievements.toArray(new Achievement[ModAchievement.achievements.size()])); AchievementPage.registerAchievementPage(PAGE); } }
fix invalid placement for the axyz achieve
src/main/java/com/teamwizardry/refraction/init/ModAchievements.java
fix invalid placement for the axyz achieve
Java
mit
029162bb0bed49007de2ffb94c4a0d3e11223774
0
concord-consortium/energy3d
package org.concord.energy3d.scene; import java.awt.EventQueue; import java.awt.image.BufferedImage; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import org.concord.energy3d.gui.EnergyPanel; import org.concord.energy3d.gui.MainFrame; import org.concord.energy3d.gui.MainPanel; import org.concord.energy3d.logger.SnapshotLogger; import org.concord.energy3d.model.Door; import org.concord.energy3d.model.Floor; import org.concord.energy3d.model.Foundation; import org.concord.energy3d.model.HousePart; import org.concord.energy3d.model.Human; import org.concord.energy3d.model.Mirror; import org.concord.energy3d.model.Rack; import org.concord.energy3d.model.Roof; import org.concord.energy3d.model.Sensor; import org.concord.energy3d.model.Snap; import org.concord.energy3d.model.SolarPanel; import org.concord.energy3d.model.Thermalizable; import org.concord.energy3d.model.Trackable; import org.concord.energy3d.model.Tree; import org.concord.energy3d.model.Wall; import org.concord.energy3d.model.Window; import org.concord.energy3d.scene.SceneManager.ViewMode; import org.concord.energy3d.shapes.Heliodon; import org.concord.energy3d.simulation.Atmosphere; import org.concord.energy3d.simulation.DesignSpecs; import org.concord.energy3d.simulation.Ground; import org.concord.energy3d.simulation.UtilityBill; import org.concord.energy3d.undo.AddMultiplePartsCommand; import org.concord.energy3d.undo.LockAllCommand; import org.concord.energy3d.undo.PastePartCommand; import org.concord.energy3d.undo.RemoveMultiplePartsCommand; import org.concord.energy3d.undo.RemoveMultipleShuttersCommand; import org.concord.energy3d.undo.SaveCommand; import org.concord.energy3d.util.Config; import org.concord.energy3d.util.Pair; import org.concord.energy3d.util.Util; import org.concord.energy3d.util.WallVisitor; import com.ardor3d.image.Texture.MinificationFilter; import com.ardor3d.image.Texture2D; import com.ardor3d.image.util.awt.AWTImageLoader; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.Vector3; import com.ardor3d.math.type.ReadOnlyColorRGBA; import com.ardor3d.math.type.ReadOnlyVector3; import com.ardor3d.renderer.Camera; import com.ardor3d.renderer.state.TextureState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.ardor3d.util.TextureKey; public class Scene implements Serializable { public static final ReadOnlyColorRGBA WHITE = ColorRGBA.WHITE; public static final ReadOnlyColorRGBA GRAY = ColorRGBA.LIGHT_GRAY; public static final int CLOUDY_SKY_THEME = 0; public static final int DESERT_THEME = 1; public static final int GRASSLAND_THEME = 2; public static final int FOREST_THEME = 3; private static final long serialVersionUID = 1L; private static final Node root = new Node("House Root"); private static final Node originalHouseRoot = new Node("Original House Root"); private static final Node notReceivingShadowRoot = new Node("Trees Root"); private static final int currentVersion = 1; private static Scene instance; private static URL url = null; private static boolean redrawAll = false; private static boolean drawThickness = false; private static boolean drawAnnotationsInside = false; private static boolean isSaving; private transient boolean edited = false; private transient BufferedImage groundImage; private transient boolean avoidSavingGroundImage; private final List<HousePart> parts = new ArrayList<HousePart>(); private final Calendar calendar = Calendar.getInstance(); private TextureMode textureMode = TextureMode.Full; private ReadOnlyVector3 cameraLocation; private ReadOnlyVector3 cameraDirection; private ReadOnlyColorRGBA landColor = new ColorRGBA(0, 1, 0, 0.5f); private ReadOnlyColorRGBA foundationColor; private ReadOnlyColorRGBA wallColor; private ReadOnlyColorRGBA doorColor; private ReadOnlyColorRGBA floorColor; private ReadOnlyColorRGBA roofColor; private Unit unit = Unit.InternationalSystemOfUnits; private Ground ground = new Ground(); private Atmosphere atmosphere = new Atmosphere(); private DesignSpecs designSpecs = new DesignSpecs(); private HousePart copyBuffer, originalCopy; private UtilityBill utilityBill; private String projectName; private String city; private String note; private long idCounter; private int version = currentVersion; private int latitude; private int solarContrast; private int theme; private double annotationScale = 0.2; private double heatVectorLength = 2000; private double heatFluxGridSize = 2; private boolean isAnnotationsVisible = true; private boolean studentMode; private boolean isHeliodonVisible; private boolean hideAxes; private boolean hideLightBeams; private boolean showSunAngles; private boolean showBuildingLabels; private boolean cleanup; private boolean alwaysComputeHeatFluxVectors; private boolean fullEnergyInSolarMap = true; private boolean onlyReflectedEnergyInMirrorSolarMap; private boolean noSolarMapForLand; private boolean disallowFoundationOverlap; private boolean dashedlineOnRoofs = true; private boolean onlySolarAnalysis; private double groundImageScale = 1; private boolean hideGroundImage; private boolean groundImageIsEarthView; private boolean groundImageLightColored; // a parameter that user can choose to improve the contrast of edit points etc. (i.e., no white on white) private transient List<List<Foundation>> foundationGroups; private String[] instructionSheetText; private String[] instructionSheetTextType; /* the following parameters specify the resolution of discretization for a simulation */ // increment of time in minutes private int timeStep = 15; // number of points in x and y directions when a solar panel is discretized into a grid (to meet the need of texture, these numbers must be power of 2) // used in heat map visualization for solar panels (for radiation calculation, solar panels use the underlying solar cell layout, e.g., 6x10, as the discretization) private int solarPanelNx = 4, solarPanelNy = 4; // number of points in x and y directions when a solar rack is discretized into a grid (to meet the need of texture, these numbers must be power of 2) // used in heat map visualization for solar panel racks (for radiation calculation, specify the size of the unit cell as follows) private int rackNx = 8, rackNy = 8; private double rackCellSize = 1; // by default, the cell is 1 x 1 meter // number of points in x and y directions when a mirror is discretized into a grid (to meet the need of texture, these numbers must be power of 2) // used in both radiation calculation and heat map visualization for reflecting mirrors (which are closer to square, except parabolic troughs) private int mirrorNx = 4, mirrorNy = 4; // the step length of the discretized grid on any part that is not a plate private double solarStep = 2.0; public static enum Unit { InternationalSystemOfUnits, USCustomaryUnits }; public static enum TextureMode { None, Simple, Full }; public static Scene getInstance() { if (instance == null) { try { open(null); } catch (final Exception e) { e.printStackTrace(); } } return instance; } public static void newFile() { newFile(80, 60); // by default, the foundation is 16 meters x 12 meters (192 square meters seem right for a house) } private static void newFile(final double xLength, final double yLength) { try { open(null); } catch (final Exception e) { e.printStackTrace(); } SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { instance.add(new Human(Human.JACK, 1)); instance.add(new Foundation(xLength, yLength), true); return null; } }); EventQueue.invokeLater(new Runnable() { @Override public void run() { EnergyPanel.getInstance().update(); EnergyPanel.getInstance().clearAllGraphs(); EnergyPanel.getInstance().selectInstructionSheet(0); } }); } public static void open(final URL file) throws Exception { openNow(file); EventQueue.invokeLater(new Runnable() { @Override public void run() { final EnergyPanel e = EnergyPanel.getInstance(); e.update(); e.clearAllGraphs(); e.selectInstructionSheet(0); if (MainFrame.getInstance().getTopViewCheckBoxMenuItem().isSelected()) { // make sure we exist the 2D top view MainFrame.getInstance().getTopViewCheckBoxMenuItem().setSelected(false); SceneManager.getInstance().resetCamera(ViewMode.NORMAL); loadCameraLocation(); } final HousePart p = SceneManager.getInstance().getSelectedPart(); if (p instanceof Foundation) { final Foundation f = (Foundation) p; switch (f.getSupportingType()) { case Foundation.BUILDING: e.getConstructionCostGraph().addGraph(f); e.getBuildingDailyEnergyGraph().clearData(); e.getBuildingDailyEnergyGraph().addGraph(f); e.validate(); break; case Foundation.PV_STATION: e.getPvStationDailyEnergyGraph().clearData(); e.getPvStationDailyEnergyGraph().addGraph(f); e.validate(); break; case Foundation.CSP_STATION: e.getCspStationDailyEnergyGraph().clearData(); e.getCspStationDailyEnergyGraph().addGraph(f); e.validate(); break; } } } }); } public static void openNow(final URL file) throws Exception { if (PrintController.getInstance().isPrintPreview()) { MainPanel.getInstance().getPreviewButton().setSelected(false); while (!PrintController.getInstance().isFinished()) { Thread.yield(); } } Scene.url = file; EventQueue.invokeLater(new Runnable() { @Override public void run() { MainPanel.getInstance().getHeliodonButton().setSelected(false); MainPanel.getInstance().getSunAnimationButton().setSelected(false); } }); SceneManager.getInstance().setSolarHeatMapWithoutUpdate(false); Wall.resetDefaultWallHeight(); if (instance != null) { instance.deleteAll(); } if (url == null) { instance = new Scene(); System.out.println("done"); } else { System.out.print("Opening..." + file + "..."); final ObjectInputStream in = new ObjectInputStream(file.openStream()); instance = (Scene) in.readObject(); in.close(); for (final HousePart part : instance.parts) { part.getRoot(); } instance.upgradeSceneToNewVersion(); instance.cleanup(); loadCameraLocation(); } if (Util.isZero(instance.groundImageScale)) { instance.groundImageScale = 1; } instance.applyGroundImage(); SceneManager.getInstance().hideAllEditPoints(); final CameraControl cameraControl = SceneManager.getInstance().getCameraControl(); if (cameraControl != null) { cameraControl.reset(); } instance.init(); EventQueue.invokeLater(new Runnable() { // update GUI must be called in Event Queue to prevent possible deadlocks @Override public void run() { if (instance.textureMode == TextureMode.None) { MainFrame.getInstance().getNoTextureMenuItem().setSelected(true); } else if (instance.textureMode == TextureMode.Simple) { MainFrame.getInstance().getSimpleTextureMenuItem().setSelected(true); } else { MainFrame.getInstance().getFullTextureMenuItem().setSelected(true); } MainPanel.getInstance().getAnnotationButton().setSelected(instance.isAnnotationsVisible); MainFrame.getInstance().updateTitleBar(); } }); } private void init() { root.detachAllChildren(); originalHouseRoot.detachAllChildren(); notReceivingShadowRoot.detachAllChildren(); root.attachChild(originalHouseRoot); root.attachChild(notReceivingShadowRoot); if (url != null) { for (final HousePart p : parts) { final boolean b = p instanceof Tree || p instanceof Human; (b ? notReceivingShadowRoot : originalHouseRoot).attachChild(p.getRoot()); } System.out.println("initSceneNow done"); /* must redraw now so that heliodon can be initialized to right size if it is to be visible */ // redrawAllNow(); } root.updateWorldBound(true); SceneManager.getInstance().updateHeliodonAndAnnotationSize(); SceneManager.getInstance().setAxesVisible(!hideAxes); SceneManager.getInstance().setBuildingLabelsVisible(showBuildingLabels); SceneManager.getInstance().getSolarLand().setVisible(!noSolarMapForLand); setTheme(theme); SceneManager.getInstance().getLand().setDefaultColor(landColor != null ? landColor : new ColorRGBA(0, 1, 0, 0.5f)); final EnergyPanel energyPanel = EnergyPanel.getInstance(); if (calendar != null) { final Date time = calendar.getTime(); Heliodon.getInstance().setDate(time); Heliodon.getInstance().setTime(time); Util.setSilently(energyPanel.getDateSpinner(), time); Util.setSilently(energyPanel.getTimeSpinner(), time); if ("Boston".equals(city) || city == null || "".equals(city)) { city = "Boston, MA"; latitude = 42; } energyPanel.setLatitude(latitude); // already silent Util.selectSilently(energyPanel.getCityComboBox(), city); Scene.getInstance().setTreeLeaves(); MainPanel.getInstance().getHeliodonButton().setSelected(isHeliodonVisible); Heliodon.getInstance().drawSun(); SceneManager.getInstance().changeSkyTexture(); SceneManager.getInstance().setShading(Heliodon.getInstance().isNightTime()); } // previous versions do not have the following classes if (designSpecs == null) { designSpecs = new DesignSpecs(); } else { designSpecs.setDefaultValues(); } if (ground == null) { ground = new Ground(); } if (atmosphere == null) { atmosphere = new Atmosphere(); } if (unit == null) { unit = Unit.InternationalSystemOfUnits; } // restore the default values if (Util.isZero(heatVectorLength)) { heatVectorLength = 5000; } if (Util.isZero(heatFluxGridSize)) { heatFluxGridSize = 2; } if (Util.isZero(solarStep)) { solarStep = 2; } if (Util.isZero(timeStep)) { timeStep = 15; } if (Util.isZero(solarPanelNx)) { solarPanelNx = 4; } if (Util.isZero(solarPanelNy)) { solarPanelNy = 4; } if (Util.isZero(rackNx)) { rackNx = 8; } if (Util.isZero(rackNy)) { rackNy = 8; } if (Util.isZero(mirrorNx)) { mirrorNx = 4; } if (Util.isZero(mirrorNy)) { mirrorNy = 4; } if (Util.isZero(rackCellSize)) { rackCellSize = 1; } if (Util.isZero(solarContrast)) { solarContrast = 50; } setEdited(false); setCopyBuffer(null); Util.setSilently(energyPanel.getColorMapSlider(), solarContrast); Util.setSilently(MainPanel.getInstance().getNoteTextArea(), note == null ? "" : note); // need to do this to avoid logging EventQueue.invokeLater(new Runnable() { @Override public void run() { energyPanel.updateThermostat(); MainPanel.getInstance().setNoteVisible(MainPanel.getInstance().isNoteVisible()); // necessary for the scroll bars to show up appropriately MainPanel.getInstance().getEnergyViewButton().setSelected(false); // moved from OpenNow to here to avoid triggering EnergyComputer -> RedrawAllNow before open is completed SceneManager.getInstance().getUndoManager().die(); } }); } public static double parsePropertyString(final String s) { final int indexOfSpace = s.indexOf(' '); return Double.parseDouble(s.substring(0, indexOfSpace != -1 ? indexOfSpace : s.length())); } public static void loadCameraLocation() { final Camera camera = SceneManager.getInstance().getCamera(); if (instance.getCameraLocation() != null && instance.getCameraDirection() != null) { camera.setLocation(instance.getCameraLocation()); camera.lookAt(instance.getCameraLocation().add(instance.getCameraDirection(), null), Vector3.UNIT_Z); } SceneManager.getInstance().getCameraNode().updateFromCamera(); Scene.getInstance().updateEditShapes(); } public static void importFile(final URL url) throws Exception { if (PrintController.getInstance().isPrintPreview()) { MainPanel.getInstance().getPreviewButton().setSelected(false); while (!PrintController.getInstance().isFinished()) { Thread.yield(); } } if (url != null) { long max = -1; for (final HousePart x : Scene.getInstance().parts) { if (x.getId() > max) { max = x.getId(); } } if (max < 0) { max = 0; } System.out.print("Opening..." + url + "..."); final ObjectInputStream in = new ObjectInputStream(url.openStream()); final Scene instance = (Scene) in.readObject(); in.close(); // instance.cleanup(); instance.upgradeSceneToNewVersion(); if (url != null) { final AddMultiplePartsCommand cmd = new AddMultiplePartsCommand(new ArrayList<HousePart>(instance.getParts()), url); double cx = 0; double cy = 0; int count = 0; for (final HousePart p : instance.getParts()) { p.setId(max + p.getId()); Scene.getInstance().parts.add(p); originalHouseRoot.attachChild(p.getRoot()); if (p instanceof Foundation || p instanceof Tree || p instanceof Human) { final Vector3 c = p.getAbsCenter(); cx += c.getX(); cy += c.getY(); count++; } } final Vector3 position = SceneManager.getInstance().getPickedLocationOnLand(); if (position != null) { final Vector3 shift = position.subtractLocal(count == 0 ? new Vector3(0, 0, 0) : new Vector3(cx / count, cy / count, 0)); for (final HousePart p : instance.getParts()) { if (p instanceof Foundation || p instanceof Tree || p instanceof Human) { for (int i = 0; i < p.getPoints().size(); i++) { p.getPoints().get(i).addLocal(shift); } } } } redrawAll = true; SceneManager.getInstance().getUndoManager().addEdit(cmd); } root.updateWorldBound(true); EventQueue.invokeLater(new Runnable() { @Override public void run() { MainPanel.getInstance().getEnergyViewButton().setSelected(false); } }); } else { JOptionPane.showMessageDialog(MainFrame.getInstance(), "URL doesn't exist.", "Error", JOptionPane.ERROR_MESSAGE); } } /** This can be used by the user to fix problems that are caused by bugs based on our observations. This is different than cleanup() as the latter cannot be used to remove undrawables. */ public void fixProblems(final boolean redraw) { // remove all undrawables final ArrayList<HousePart> a = new ArrayList<HousePart>(); for (final HousePart p : parts) { if (!p.isDrawable()) { a.add(p); } } for (final HousePart p : a) { remove(p, false); } a.clear(); cleanup(); if (redraw) { redrawAll(true); } } private void deleteAll() { for (final HousePart p : parts) { p.delete(); } } private void cleanup() { // fix if roof and wall are not linked from each other for (final HousePart p : parts) { if (p instanceof Roof) { final Roof r = (Roof) p; final HousePart c = r.getContainer(); if (c != null && !c.getChildren().contains(r)) { c.getChildren().add(r); } } } final ArrayList<HousePart> toBeRemoved = new ArrayList<HousePart>(); for (final HousePart p : parts) { if (!p.isValid()) { // remove invalid parts toBeRemoved.add(p); } else if (p.getContainer() == null) { // remove orphan parts without a top container if (p instanceof Wall || p instanceof Roof || p instanceof Window || p instanceof Door || p instanceof SolarPanel || p instanceof Rack || p instanceof Floor) { toBeRemoved.add(p); } } else if (!parts.contains(p.getContainer())) { // remove parts whose container doesn't exist in the scene toBeRemoved.add(p); } else if (p instanceof Wall) { // remove walls that are at the same position if (((Wall) p).isAtSamePlaceAsAnotherPart()) { toBeRemoved.add(p); } } } for (final HousePart p : toBeRemoved) { remove(p, false); } // remove children with multiple parents toBeRemoved.clear(); for (final HousePart p : parts) { for (final HousePart child : p.getChildren()) { if (child.getContainer() != p && !toBeRemoved.contains(child)) { toBeRemoved.add(child); } } } for (final HousePart p : toBeRemoved) { remove(p, false); } // remove from remaining parents for (final HousePart p : parts) { for (final HousePart r : toBeRemoved) { p.getChildren().remove(r); } } // remove all the children that are not in parts toBeRemoved.clear(); for (final HousePart p : parts) { for (final HousePart child : p.getChildren()) { if (!parts.contains(child) && !toBeRemoved.contains(child)) { toBeRemoved.add(child); } } } for (final HousePart p : toBeRemoved) { remove(p, false); } // complete all non-completed parts for (final HousePart p : parts) { if (!p.isDrawCompleted()) { p.complete(); } } } private void upgradeSceneToNewVersion() { if (textureMode == null) { textureMode = TextureMode.Full; for (final HousePart p : parts) { if (p instanceof Roof) { ((Roof) p).setOverhangLength(0.2); } } } if (version < 1) { for (final HousePart part : parts) { if (part instanceof Foundation) { ((Foundation) part).scaleHouseForNewVersion(10); } } cameraLocation = cameraLocation.multiply(10, null); setAnnotationScale(1.0); } version = currentVersion; } public void connectWalls() { for (final HousePart part : parts) { if (part instanceof Wall) { part.reset(); } } for (final HousePart part : parts) { if (part instanceof Wall) { ((Wall) part).connectedWalls(); } } for (final HousePart part : parts) { if (part instanceof Wall) { ((Wall) part).computeInsideDirectionOfAttachedWalls(false); } } } public static void save(final URL url, final boolean setAsCurrentFile) { save(url, setAsCurrentFile, true, false); } public static void save(final URL url, final boolean setAsCurrentFile, final boolean notifyUndoManager, final boolean logger) { isSaving = true; SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { try { realSave(url, setAsCurrentFile, notifyUndoManager, logger); } catch (final Throwable e) { Util.reportError(e); } finally { isSaving = false; } return null; } }); } public static void saveOutsideTaskManager(final URL url, final boolean setAsCurrentFile, final boolean notifyUndoManager, final boolean logger) { isSaving = true; try { realSave(url, setAsCurrentFile, notifyUndoManager, logger); } catch (final Throwable e) { e.printStackTrace(); } finally { isSaving = false; } } private static void realSave(final URL url, final boolean setAsCurrentFile, final boolean notifyUndoManager, final boolean logger) throws Exception { if (logger) { instance.storeGroundImageData(); } if (notifyUndoManager) { instance.cleanup(); } // save camera to file if (SceneManager.getInstance().getViewMode() == ViewMode.NORMAL) { saveCameraLocation(); } instance.hideAxes = !SceneManager.getInstance().areAxesVisible(); instance.showBuildingLabels = SceneManager.getInstance().areBuildingLabelsVisible(); instance.calendar.setTime(Heliodon.getInstance().getCalendar().getTime()); instance.latitude = (int) Math.toDegrees(Heliodon.getInstance().getLatitude()); instance.city = (String) EnergyPanel.getInstance().getCityComboBox().getSelectedItem(); instance.isHeliodonVisible = Heliodon.getInstance().isVisible(); instance.note = MainPanel.getInstance().getNoteTextArea().getText().trim(); instance.solarContrast = EnergyPanel.getInstance().getColorMapSlider().getValue(); if (setAsCurrentFile) { Scene.url = url; } System.out.print("Saving " + url + "..."); final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(url.toURI().getPath())); out.writeObject(instance); out.close(); if (notifyUndoManager) { SceneManager.getInstance().getUndoManager().addEdit(new SaveCommand()); } if (logger) { instance.restoreGroundImageData(); } System.out.println("done"); } public static void saveCameraLocation() { final Camera camera = SceneManager.getInstance().getCamera(); instance.setCameraLocation(camera.getLocation().clone()); instance.setCameraDirection(SceneManager.getInstance().getCamera().getDirection().clone()); } public static Node getRoot() { return root; } private Scene() { } public void add(final HousePart housePart, final boolean redraw) { final HousePart container = housePart.getContainer(); if (container != null) { container.getChildren().add(housePart); } add(housePart); if (redraw) { redrawAll(); } } private void add(final HousePart housePart) { System.out.println("Adding: " + housePart); if (housePart instanceof Tree || housePart instanceof Human) { notReceivingShadowRoot.attachChild(housePart.getRoot()); } else { originalHouseRoot.attachChild(housePart.getRoot()); } parts.add(housePart); for (final HousePart child : housePart.getChildren()) { add(child); } } public void remove(final HousePart housePart, final boolean redraw) { if (housePart == null) { return; } housePart.setGridsVisible(false); final HousePart container = housePart.getContainer(); if (container != null) { container.getChildren().remove(housePart); } removeChildren(housePart); if (redraw) { redrawAll(); } } private void removeChildren(final HousePart housePart) { System.out.println("Removing: " + housePart); parts.remove(housePart); // this must happen before call to wall.delete() for (final HousePart child : housePart.getChildren()) { removeChildren(child); } // originalHouseRoot.detachChild(housePart.getRoot()); housePart.getRoot().removeFromParent(); housePart.delete(); } private static void setIdOfChildren(final HousePart p) { final ArrayList<HousePart> children = p.getChildren(); for (final HousePart c : children) { c.setId(Scene.getInstance().nextID()); if (!c.getChildren().isEmpty()) { setIdOfChildren(c); } } } public void setCopyBuffer(final HousePart p) { EnergyPanel.getInstance().clearRadiationHeatMap(); // exclude the following types of house parts if (p instanceof Roof || p instanceof Floor || p instanceof Sensor) { return; } copyBuffer = p; originalCopy = p; } public HousePart getCopyBuffer() { return copyBuffer; } public HousePart getOriginalCopy() { return originalCopy; } public void paste() { if (copyBuffer == null) { return; } if (copyBuffer instanceof Foundation) { return; } EnergyPanel.getInstance().clearRadiationHeatMap(); final HousePart c = copyBuffer.copy(true); if (c == null) { return; } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); EnergyPanel.getInstance().clearRadiationHeatMap(); EnergyPanel.getInstance().update(); } public void pasteToPickedLocationOnLand() { EnergyPanel.getInstance().clearRadiationHeatMap(); if (copyBuffer == null) { return; } final HousePart c = copyBuffer.copy(false); if (c == null) { return; } final Vector3 position = SceneManager.getInstance().getPickedLocationOnLand(); if (position == null) { return; } if (c instanceof Tree || c instanceof Human) { c.getPoints().set(0, position); add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } else if (c instanceof Foundation) { // pasting a foundation also clones the building above it final Vector3 shift = position.subtractLocal(c.getAbsCenter()).multiplyLocal(1, 1, 0); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { c.getPoints().get(i).addLocal(shift); } add(c, true); // copy gable info, too final Foundation oldFoundation = (Foundation) copyBuffer; final Foundation newFoundation = (Foundation) c; final List<Roof> oldRoofs = oldFoundation.getRoofs(); final List<Roof> newRoofs = newFoundation.getRoofs(); if (!oldRoofs.isEmpty() && !newRoofs.isEmpty()) { for (int i = 0; i < newRoofs.size(); i++) { final Map<Integer, List<Wall>> oldMap = oldRoofs.get(i).getGableEditPointToWallMap(); if (oldMap == null || oldMap.isEmpty()) { continue; } final Map<Integer, List<Wall>> newMap = new HashMap<Integer, List<Wall>>(); for (final Integer key : oldMap.keySet()) { final List<Wall> oldWalls = oldMap.get(key); final List<Wall> newWalls = new ArrayList<Wall>(); for (final Wall w : oldWalls) { newWalls.add(getCopiedWall(w, oldFoundation, newFoundation)); } newMap.put(key, newWalls); } newRoofs.get(i).setGableEditPointToWallMap(newMap); } } copyBuffer = c; setIdOfChildren(c); SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } } private Wall getCopiedWall(final Wall oldWall, final Foundation oldFoundation, final Foundation newFoundation) { final ArrayList<HousePart> oldWalls = oldFoundation.getChildren(); final ArrayList<HousePart> newWalls = newFoundation.getChildren(); final int index = oldWalls.indexOf(oldWall); if (index < 0) { return null; } return (Wall) newWalls.get(index); } public void pasteToPickedLocationOnWall() { EnergyPanel.getInstance().clearRadiationHeatMap(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (!(selectedPart instanceof Wall)) { return; } if (copyBuffer == null) { return; } if (copyBuffer instanceof Foundation) { return; } final HousePart c = copyBuffer.copy(false); if (c == null) { return; } Vector3 position = SceneManager.getInstance().getPickedLocationOnWall(); if (position == null) { return; } final Wall wall = (Wall) selectedPart; if (wall != c.getContainer()) { // windows and solar panels can be pasted to a different wall if (c instanceof Window) { ((Window) c).moveTo(wall); } else if (c instanceof SolarPanel) { ((SolarPanel) c).moveTo(wall); } } position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0))); final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0))); position = position.subtractLocal(center); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); v.addLocal(position); } // out of boundary check final List<Vector3> polygon = wall.getWallPolygonPoints(); final List<Vector3> relativePolygon = new ArrayList<Vector3>(); for (final Vector3 p : polygon) { relativePolygon.add(c.toRelative(p)); } for (final Vector3 p : relativePolygon) { final double y = p.getY(); p.setY(p.getZ()); p.setZ(y); } for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); if (!Util.insidePolygon(new Vector3(v.getX(), v.getZ(), v.getY()), relativePolygon)) { return; } } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } public void pasteToPickedLocationOnRoof() { EnergyPanel.getInstance().clearRadiationHeatMap(); if (copyBuffer == null) { return; } if (copyBuffer instanceof Foundation) { return; } final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (!(selectedPart instanceof Roof)) { return; } final HousePart c = copyBuffer.copy(false); if (c == null) { return; } Vector3 position = SceneManager.getInstance().getPickedLocationOnRoof(); if (position == null) { return; } if (selectedPart != c.getContainer()) { // solar panels and racks can be pasted to a different parent if (c instanceof SolarPanel) { ((SolarPanel) c).moveTo(selectedPart); } else if (c instanceof Rack) { ((Rack) c).moveTo(selectedPart); } } position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0))); final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0))); position = position.subtractLocal(center); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); v.addLocal(position); } if (c instanceof Rack) { ((Rack) c).moveSolarPanels(position); setIdOfChildren(c); } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } public void pasteToPickedLocationOnRack() { final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (!(selectedPart instanceof Rack)) { return; } if (!(copyBuffer instanceof SolarPanel)) { return; } EnergyPanel.getInstance().clearRadiationHeatMap(); final HousePart c = copyBuffer.copy(false); if (c == null) { return; } Vector3 position = SceneManager.getInstance().getPickedLocationOnRack(); if (position == null) { return; } if (selectedPart != c.getContainer()) { ((SolarPanel) c).moveTo(selectedPart); } position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0))); final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0))); position = position.subtractLocal(center); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); v.addLocal(position); } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } public void pasteToPickedLocationOnFoundation() { EnergyPanel.getInstance().clearRadiationHeatMap(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (!(selectedPart instanceof Foundation)) { return; } if (copyBuffer == null) { return; } final HousePart c = copyBuffer.copy(false); if (c == null) { return; } Vector3 position = SceneManager.getInstance().getPickedLocationOnFoundation(); if (position == null) { return; } c.setContainer(selectedPart); // move to this foundation position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0))); final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0))); position = position.subtractLocal(center); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); v.addLocal(position); } if (c instanceof Rack) { ((Rack) c).moveSolarPanels(position); setIdOfChildren(c); } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } public List<HousePart> getParts() { return parts; } public HousePart getPart(final long id) { for (final HousePart p : parts) { if (id == p.getId()) { return p; } } return null; } public void drawResizeBounds() { for (final HousePart part : parts) { if (part instanceof Foundation) { part.draw(); } } } public static Node getOriginalHouseRoot() { return originalHouseRoot; } public static Node getNotReceivingShadowRoot() { return notReceivingShadowRoot; } public static URL getURL() { return url; } public static boolean isInternalFile() { if (Config.isEclipse()) { return url != null && url.toString().indexOf("/energy3d/target/classes") != -1; } return url != null && url.toString().indexOf(".jar!") != -1; } public void setAnnotationsVisible(final boolean visible) { isAnnotationsVisible = visible; for (final HousePart part : parts) { part.setAnnotationsVisible(visible); } if (PrintController.getInstance().isPrintPreview()) { for (final HousePart part : PrintController.getInstance().getPrintParts()) { part.setAnnotationsVisible(visible); } } if (PrintController.getInstance().isPrintPreview()) { PrintController.getInstance().restartAnimation(); } else { SceneManager.getInstance().refresh(); } } public void setTextureMode(final TextureMode textureMode) { this.textureMode = textureMode; redrawAll(); Scene.getInstance().updateRoofDashLinesColor(); } public TextureMode getTextureMode() { return textureMode; } public void setDrawThickness(final boolean draw) { drawThickness = draw; redrawAll = true; } public boolean isDrawThickness() { return drawThickness; } public static boolean isDrawAnnotationsInside() { return drawAnnotationsInside; } public static void setDrawAnnotationsInside(final boolean drawAnnotationsInside) { Scene.drawAnnotationsInside = drawAnnotationsInside; for (final HousePart part : instance.getParts()) { part.drawAnnotations(); } if (PrintController.getInstance().getPrintParts() != null) { for (final HousePart part : PrintController.getInstance().getPrintParts()) { part.drawAnnotations(); } } } public void redrawAll() { redrawAll(false); } public void redrawAll(final boolean cleanup) { this.cleanup = cleanup; if (PrintController.getInstance().isPrintPreview()) { PrintController.getInstance().restartAnimation(); } else { redrawAll = true; } } public void redrawAllNow() { System.out.println("redrawAllNow()"); final long t = System.nanoTime(); if (cleanup) { cleanup(); cleanup = false; } connectWalls(); Snap.clearAnnotationDrawn(); for (final HousePart part : parts) { if (part instanceof Roof) { part.draw(); } } for (final HousePart part : parts) { if (!(part instanceof Roof)) { part.draw(); } } // need to draw roof again because roof holes depend on drawn windows for (final HousePart part : parts) { if (part instanceof Roof) { part.draw(); } } if (Heliodon.getInstance().isVisible()) { Heliodon.getInstance().updateSize(); } System.out.println("Time = " + (System.nanoTime() - t) / 1000000000.0); // no need for redrawing print parts because they will be regenerated from original parts anyways redrawAll = false; } public void updateAllTextures() { System.out.println("updateAllTextures()"); for (final HousePart part : parts) { part.updateTextureAndColor(); } SceneManager.getInstance().refresh(); } public void setUnit(final Unit unit) { this.unit = unit; redrawAll = true; } public Unit getUnit() { if (unit == null) { unit = Unit.InternationalSystemOfUnits; } return unit; } public void setAnnotationScale(final double scale) { annotationScale = scale; } public double getAnnotationScale() { if (annotationScale == 0) { annotationScale = 10; } return annotationScale; } public void updateRoofDashLinesColor() { for (final HousePart part : parts) { if (part instanceof Roof) { ((Roof) part).updateDashLinesColor(); } } if (PrintController.getInstance().getPrintParts() != null) { for (final HousePart part : PrintController.getInstance().getPrintParts()) { if (part instanceof Roof) { ((Roof) part).updateDashLinesColor(); } } } } public void removeAllTrees() { final ArrayList<HousePart> trees = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Tree && !part.isFrozen()) { trees.add(part); } } if (trees.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no tree to remove.", "No Tree", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + trees.size() + " trees?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(trees); for (final HousePart part : trees) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllHumans() { final ArrayList<HousePart> humans = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Human) { humans.add(part); } } if (humans.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no human to remove.", "No Human", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + humans.size() + " humans?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(humans); for (final HousePart part : humans) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllRoofs() { final ArrayList<HousePart> roofs = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Roof && !part.isFrozen()) { roofs.add(part); } } if (roofs.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no roof to remove.", "No Roof", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + roofs.size() + " roofs?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(roofs); for (final HousePart part : roofs) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllFloors() { final ArrayList<HousePart> floors = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Floor && !part.isFrozen()) { floors.add(part); } } if (floors.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no floor to remove.", "No Floor", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + floors.size() + " floors?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(floors); for (final HousePart part : floors) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllSolarPanels(List<SolarPanel> panels) { final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (panels == null) { panels = new ArrayList<SolarPanel>(); if (selectedPart != null) { if (selectedPart instanceof Rack) { for (final HousePart part : selectedPart.getChildren()) { if (part instanceof SolarPanel) { panels.add((SolarPanel) part); } } } else { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof SolarPanel && !part.isFrozen() && part.getTopContainer() == foundation) { panels.add((SolarPanel) part); } } } } else { for (final HousePart part : parts) { if (part instanceof SolarPanel && !part.isFrozen()) { panels.add((SolarPanel) part); } } } } if (panels.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no solar panel to remove.", "No Solar Panel", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + panels.size() + " solar panels" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(new ArrayList<HousePart>(panels)); for (final HousePart part : panels) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllRacks() { final ArrayList<HousePart> racks = new ArrayList<HousePart>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Rack && !part.isFrozen() && part.getTopContainer() == foundation) { racks.add(part); } } } else { for (final HousePart part : parts) { if (part instanceof Rack && !part.isFrozen()) { racks.add(part); } } } if (racks.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no rack to remove.", "No Rack", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + racks.size() + " solar panel racks" + (selectedPart != null ? " on the selected foundation" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(racks); for (final HousePart part : racks) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllMirrors() { final ArrayList<HousePart> mirrors = new ArrayList<HousePart>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Mirror && !part.isFrozen() && part.getTopContainer() == foundation) { mirrors.add(part); } } } else { for (final HousePart part : parts) { if (part instanceof Mirror && !part.isFrozen()) { mirrors.add(part); } } } if (mirrors.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no mirror to remove.", "No Mirror", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + mirrors.size() + " mirrors" + (selectedPart != null ? " on the selected foundation" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(mirrors); for (final HousePart part : mirrors) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllWalls() { final ArrayList<HousePart> walls = new ArrayList<HousePart>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Wall && !part.isFrozen() && part.getTopContainer() == foundation) { walls.add(part); } } } else { for (final HousePart part : parts) { if (part instanceof Wall && !part.isFrozen()) { walls.add(part); } } } if (walls.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no wall to remove.", "No Wall", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + walls.size() + " walls" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(walls); for (final HousePart part : walls) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllWindows() { final ArrayList<HousePart> windows = new ArrayList<HousePart>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Window && !part.isFrozen() && part.getTopContainer() == foundation) { windows.add(part); } } } else { for (final HousePart part : parts) { if (part instanceof Window && !part.isFrozen()) { windows.add(part); } } } if (windows.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no window to remove.", "No Window", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + windows.size() + " windows" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(windows); for (final HousePart part : windows) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllWindowShutters() { final ArrayList<Window> windows = new ArrayList<Window>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Window && !part.isFrozen() && part.getTopContainer() == foundation) { final Window w = (Window) part; if (w.getLeftShutter() || w.getRightShutter()) { windows.add(w); } } } } else { for (final HousePart part : parts) { if (part instanceof Window && !part.isFrozen()) { final Window w = (Window) part; if (w.getLeftShutter() || w.getRightShutter()) { windows.add(w); } } } } if (windows.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no window shutter to remove.", "No Shutter", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + windows.size() + " window shutters" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultipleShuttersCommand c = new RemoveMultipleShuttersCommand(windows); for (final HousePart part : windows) { final Window w = (Window) part; w.setLeftShutter(false); w.setRightShutter(false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllFoundations() { final ArrayList<HousePart> foundations = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Foundation && !part.isFrozen()) { foundations.add(part); } } if (foundations.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no activated foundation to remove.", "No Foundation", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + foundations.size() + " foundations?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(foundations); for (final HousePart part : foundations) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllChildren(final HousePart parent) { final List<HousePart> children = parent.getChildren(); final String s = parent.getClass().getSimpleName(); final List<HousePart> copy = new ArrayList<HousePart>(); // make a copy to avoid ConcurrentModificationException for (final HousePart p : children) { if (p instanceof Roof) { continue; // make an exception of roof (it is a child of a wall) } copy.add(p); } if (copy.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no element to remove from " + s + ".", "No Element", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + copy.size() + " elements of " + s + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(copy); for (final HousePart p : copy) { remove(p, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void lockAll(final boolean freeze) { if (parts.isEmpty()) { return; } int lockCount = 0; for (final HousePart part : parts) { if (part.isFrozen()) { lockCount++; } } if (!freeze) { if (lockCount > 0) { if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "<html>A lock prevents a component from being edited.<br>Do you really want to remove all the existing " + lockCount + " locks?</html>", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } } else { JOptionPane.showMessageDialog(MainFrame.getInstance(), "<html>A lock prevents a component from being edited.<br>There is no lock to remove.</html>"); return; } } SceneManager.getInstance().getUndoManager().addEdit(new LockAllCommand()); for (final HousePart part : parts) { part.setFreeze(freeze); } if (freeze) { SceneManager.getInstance().hideAllEditPoints(); } redrawAll(); edited = true; } public static boolean isRedrawAll() { return redrawAll; } public boolean areAnnotationsVisible() { return isAnnotationsVisible; } public ReadOnlyVector3 getCameraLocation() { return cameraLocation; } public void setCameraLocation(final ReadOnlyVector3 cameraLocation) { this.cameraLocation = cameraLocation; } public ReadOnlyVector3 getCameraDirection() { return cameraDirection; } public void setCameraDirection(final ReadOnlyVector3 cameraDirection) { this.cameraDirection = cameraDirection; } public void removeAllGables() { for (final HousePart part : parts) { if (part instanceof Roof) { ((Roof) part).removeAllGables(); } } } public ReadOnlyColorRGBA getLandColor() { return landColor; } public void setLandColor(final ReadOnlyColorRGBA c) { landColor = c; SceneManager.getInstance().getLand().setDefaultColor(landColor); } /** get the default color for foundations */ public ReadOnlyColorRGBA getFoundationColor() { if (foundationColor == null) { return WHITE; } return foundationColor; } /** set the default color for foundations */ public void setFoundationColor(final ReadOnlyColorRGBA foundationColor) { this.foundationColor = foundationColor; } /** get the default color for walls */ public ReadOnlyColorRGBA getWallColor() { if (wallColor == null) { return GRAY; } return wallColor; } /** set the default color for walls */ public void setWallColor(final ReadOnlyColorRGBA wallColor) { this.wallColor = wallColor; } /** get the default color for doors */ public ReadOnlyColorRGBA getDoorColor() { if (doorColor == null) { return WHITE; } return doorColor; } /** set the default color for doors */ public void setDoorColor(final ReadOnlyColorRGBA doorColor) { this.doorColor = doorColor; } /** get the default color for floors */ public ReadOnlyColorRGBA getFloorColor() { if (floorColor == null) { return WHITE; } return floorColor; } /** set the default color for floors */ public void setFloorColor(final ReadOnlyColorRGBA floorColor) { this.floorColor = floorColor; } /** get the default color for roofs */ public ReadOnlyColorRGBA getRoofColor() { if (roofColor == null) { return WHITE; } return roofColor; } /** set the default color for roofs */ public void setRoofColor(final ReadOnlyColorRGBA roofColor) { this.roofColor = roofColor; } public void setWindowColorInContainer(final HousePart container, final ColorRGBA c, final boolean shutter) { for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { final Window w = (Window) p; if (shutter) { w.setShutterColor(c); } else { w.setColor(c); } w.draw(); } } } public void setShutterLengthInContainer(final HousePart container, final double length) { for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { final Window w = (Window) p; w.setShutterLength(length); w.draw(); } } } public void setWindowSizeInContainer(final HousePart container, final double width, final double height) { for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { final Window w = (Window) p; w.setWindowWidth(width); w.setWindowHeight(height); w.draw(); w.getContainer().draw(); } } } public void setShutterColorOfBuilding(final HousePart part, final ReadOnlyColorRGBA color) { if (part instanceof Foundation) { return; } for (final HousePart p : parts) { if (p instanceof Window && p.getTopContainer() == part.getTopContainer()) { final Window w = (Window) p; w.setShutterColor(color); w.draw(); } } } public void setShutterLengthOfBuilding(final HousePart part, final double length) { if (part instanceof Foundation) { return; } for (final HousePart p : parts) { if (p instanceof Window && p.getTopContainer() == part.getTopContainer()) { final Window w = (Window) p; w.setShutterLength(length); w.draw(); } } } public void setPartColorOfBuilding(final HousePart part, final ReadOnlyColorRGBA color) { if (part instanceof Foundation) { part.setColor(color); } else { for (final HousePart p : parts) { if (p.getTopContainer() == part.getTopContainer() && p.getClass().equals(part.getClass())) { p.setColor(color); } } } } public void setColorOfAllPartsOfSameType(final HousePart part, final ReadOnlyColorRGBA color) { for (final HousePart p : parts) { if (p.getClass().equals(part.getClass())) { p.setColor(color); } } } public List<HousePart> getPartsOfSameTypeInBuilding(final HousePart x) { final List<HousePart> list = new ArrayList<HousePart>(); if (x instanceof Foundation) { list.add(x); } else { for (final HousePart p : parts) { if (p.getClass().equals(x.getClass()) && p.getTopContainer() == x.getTopContainer()) { list.add(p); } } } return list; } public List<HousePart> getAllPartsOfSameType(final HousePart x) { final List<HousePart> list = new ArrayList<HousePart>(); for (final HousePart p : parts) { if (p.getClass().equals(x.getClass())) { list.add(p); } } return list; } public void setUValuesOfSameTypeInBuilding(final HousePart x, final double uValue) { if (x instanceof Thermalizable) { if (x instanceof Foundation) { ((Foundation) x).setUValue(uValue); } else { for (final HousePart p : parts) { if (p.getClass().equals(x.getClass()) && p.getTopContainer() == x.getTopContainer()) { ((Thermalizable) p).setUValue(uValue); } } } } } public List<Window> getWindowsOnContainer(final HousePart container) { final List<Window> list = new ArrayList<Window>(); for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { list.add((Window) p); } } return list; } public void setWindowShgcInContainer(final HousePart container, final double shgc) { for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { ((Window) p).setSolarHeatGainCoefficient(shgc); } } } public List<Window> getWindowsOfBuilding(final Foundation foundation) { final List<Window> list = new ArrayList<Window>(); for (final HousePart p : parts) { if (p instanceof Window && p.getTopContainer() == foundation) { list.add((Window) p); } } return list; } public void setWindowShgcOfBuilding(final Foundation foundation, final double shgc) { for (final HousePart p : parts) { if (p instanceof Window && p.getTopContainer() == foundation) { ((Window) p).setSolarHeatGainCoefficient(shgc); } } } public List<SolarPanel> getAllSolarPanels() { final List<SolarPanel> list = new ArrayList<SolarPanel>(); for (final HousePart p : parts) { if (p instanceof SolarPanel) { list.add((SolarPanel) p); } } return list; } public void setCellNumbersForAllSolarPanels(final int nx, final int ny) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { final SolarPanel s = (SolarPanel) p; s.setNumberOfCellsInX(nx); s.setNumberOfCellsInY(ny); s.draw(); } } SceneManager.getInstance().refresh(); } public void setTiltAngleForAllSolarPanels(final double angle) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setTiltAngle(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setAzimuthForAllSolarPanels(final double angle) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setRelativeAzimuth(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setBaseHeightForAllSolarPanels(final double baseHeight) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setBaseHeight(baseHeight); p.draw(); } } SceneManager.getInstance().refresh(); } public void setTrackerForAllSolarPanels(final int tracker) { for (final HousePart p : parts) { if (p instanceof SolarPanel && !(p.getContainer() instanceof Rack)) { // no tracker for solar panels on racks as they use rack trackers ((SolarPanel) p).setTracker(tracker); p.draw(); } } SceneManager.getInstance().refresh(); } public void setColorOptionForAllSolarPanels(final int colorOption) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setColorOption(colorOption); p.draw(); } } SceneManager.getInstance().refresh(); } public void setShadeToleranceForAllSolarPanels(final int cellWiring) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setShadeTolerance(cellWiring); } } } public void setSolarCellEfficiencyForAll(final double eff) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setCellEfficiency(eff); } } } public void setTemperatureCoefficientPmaxForAll(final double tcPmax) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setTemperatureCoefficientPmax(tcPmax); } } } public void setSolarPanelInverterEfficiencyForAll(final double eff) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setInverterEfficiency(eff); } } } public List<Rack> getAllRacks() { final List<Rack> list = new ArrayList<Rack>(); for (final HousePart p : parts) { if (p instanceof Rack) { list.add((Rack) p); } } return list; } public void setTiltAngleForAllRacks(final double angle) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setTiltAngle(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setAzimuthForAllRacks(final double angle) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setRelativeAzimuth(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setBaseHeightForAllRacks(final double baseHeight) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setBaseHeight(baseHeight); p.draw(); } } SceneManager.getInstance().refresh(); } public void setSizeForAllRacks(final double width, final double height) { for (final HousePart p : parts) { if (p instanceof Rack) { final Rack rack = (Rack) p; rack.setRackWidth(width); rack.setRackHeight(height); rack.ensureFullSolarPanels(false); rack.draw(); } } SceneManager.getInstance().refresh(); } public void setSolarPanelSizeForAllRacks(final double width, final double height) { for (final HousePart p : parts) { if (p instanceof Rack) { final Rack rack = (Rack) p; rack.getSolarPanel().setPanelWidth(width); rack.getSolarPanel().setPanelHeight(height); rack.ensureFullSolarPanels(false); rack.draw(); } } SceneManager.getInstance().refresh(); } public void setSolarPanelColorForAllRacks(final int colorOption) { for (final HousePart p : parts) { if (p instanceof Rack) { final Rack rack = (Rack) p; rack.getSolarPanel().setColorOption(colorOption); rack.draw(); } } SceneManager.getInstance().refresh(); } public void setSolarPanelShadeToleranceForAllRacks(final int tolerance) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).getSolarPanel().setShadeTolerance(tolerance); } } } public void setSolarCellEfficiencyForAllRacks(final double eff) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).getSolarPanel().setCellEfficiency(eff); } } } public void setInverterEfficiencyForAllRacks(final double eff) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).getSolarPanel().setInverterEfficiency(eff); } } } public void setTemperatureCoefficientPmaxForAllRacks(final double pmax) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).getSolarPanel().setTemperatureCoefficientPmax(pmax); } } } public void rotateSolarPanelsOnAllRacks(final boolean rotated) { for (final HousePart p : parts) { if (p instanceof Rack) { final Rack rack = (Rack) p; rack.getSolarPanel().setRotated(rotated); rack.ensureFullSolarPanels(false); rack.draw(); } } SceneManager.getInstance().refresh(); } public void setPoleSpacingForAllRacks(final double dx, final double dy) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setPoleDistanceX(dx); ((Rack) p).setPoleDistanceY(dy); p.draw(); } } SceneManager.getInstance().refresh(); } public void setTrackerForAllRacks(final int tracker) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setTracker(tracker); p.draw(); } } SceneManager.getInstance().refresh(); } public List<Mirror> getAllMirrors() { final List<Mirror> list = new ArrayList<Mirror>(); for (final HousePart p : parts) { if (p instanceof Mirror) { list.add((Mirror) p); } } return list; } public void setTiltAngleForAllMirrors(final double angle) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setTiltAngle(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setAzimuthForAllMirrors(final double angle) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setRelativeAzimuth(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setReflectivityForAllMirrors(final double reflectivity) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setReflectivity(reflectivity); } } } public void setTargetForAllMirrors(final Foundation target) { final List<Foundation> oldTargets = new ArrayList<Foundation>(); for (final HousePart p : parts) { if (p instanceof Mirror) { final Mirror m = (Mirror) p; final Foundation t = m.getHeliostatTarget(); if (t != null && !oldTargets.contains(t)) { oldTargets.add(t); } m.setHeliostatTarget(target); p.draw(); } } if (target != null) { target.drawSolarReceiver(); } if (!oldTargets.isEmpty()) { for (final Foundation t : oldTargets) { t.drawSolarReceiver(); } } SceneManager.getInstance().refresh(); } public void setBaseHeightForAllMirrors(final double baseHeight) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setBaseHeight(baseHeight); p.draw(); } } SceneManager.getInstance().refresh(); } public void setSizeForAllMirrors(final double width, final double height) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setMirrorWidth(width); ((Mirror) p).setMirrorHeight(height); p.draw(); } } SceneManager.getInstance().refresh(); } public void setThicknessForAllWalls(final double thickness) { for (final HousePart p : parts) { if (p instanceof Wall) { ((Wall) p).setThickness(thickness); p.draw(); } } SceneManager.getInstance().refresh(); } public void setHeightOfConnectedWalls(final Wall w, final double height) { w.visitNeighbors(new WallVisitor() { @Override public void visit(final Wall currentWall, final Snap prev, final Snap next) { currentWall.setHeight(height, true); currentWall.draw(); } }); SceneManager.getInstance().refresh(); } public void setHeightForAllWalls(final double height) { for (final HousePart p : parts) { if (p instanceof Wall) { ((Wall) p).setHeight(height, true); p.draw(); } } SceneManager.getInstance().refresh(); } public void setColorOfConnectedWalls(final Wall w, final ColorRGBA color) { w.visitNeighbors(new WallVisitor() { @Override public void visit(final Wall currentWall, final Snap prev, final Snap next) { currentWall.setColor(color); currentWall.draw(); } }); SceneManager.getInstance().refresh(); } public boolean isEdited() { return edited; } public void setEdited(final boolean edited) { setEdited(edited, true); } public void setEdited(final boolean edited, final boolean recomputeEnergy) { if (edited) { SnapshotLogger.getInstance().setSceneEdited(true); } this.edited = edited; MainFrame.getInstance().updateTitleBar(); } public void updateEditShapes() { for (final HousePart part : parts) { part.updateEditShapes(); } } public long nextID() { return ++idCounter; } public boolean hasSensor() { for (final HousePart housePart : parts) { if (housePart instanceof Sensor) { return true; } } return false; } public void setProjectName(final String projectName) { this.projectName = projectName; } public String getProjectName() { return projectName; } public void setStudentMode(final boolean b) { studentMode = b; } public boolean isStudentMode() { return studentMode; } public void setCity(final String city) { this.city = city; } public String getCity() { return city; } public void setDate(final Date date) { if (calendar != null) { calendar.setTime(date); } } public Date getDate() { if (calendar != null) { return calendar.getTime(); } return Heliodon.getInstance().getCalendar().getTime(); } public void setHeatVectorLength(final double heatVectorLength) { this.heatVectorLength = heatVectorLength; } public double getHeatVectorLength() { return heatVectorLength; } public void setHeatFluxGridSize(final double heatFluxGridSize) { this.heatFluxGridSize = heatFluxGridSize; } public double getHeatVectorGridSize() { return heatFluxGridSize; } public boolean getAlwaysComputeHeatFluxVectors() { return alwaysComputeHeatFluxVectors; } public void setAlwaysComputeHeatFluxVectors(final boolean alwaysComputeHeatFluxVectors) { this.alwaysComputeHeatFluxVectors = alwaysComputeHeatFluxVectors; for (final HousePart part : Scene.getInstance().getParts()) { part.updateHeatFluxVisibility(); } } public boolean getOnlyAbsorptionInSolarMap() { return !fullEnergyInSolarMap; } public void setOnlyAbsorptionInSolarMap(final boolean onlyAbsorptionInSolarMap) { fullEnergyInSolarMap = !onlyAbsorptionInSolarMap; } public boolean getOnlyReflectedEnergyInMirrorSolarMap() { return onlyReflectedEnergyInMirrorSolarMap; } public void setOnlyReflectedEnergyInMirrorSolarMap(final boolean onlyReflectedEnergyInMirrorSolarMap) { this.onlyReflectedEnergyInMirrorSolarMap = onlyReflectedEnergyInMirrorSolarMap; } public void setSolarMapForLand(final boolean showSolarMapForLand) { noSolarMapForLand = !showSolarMapForLand; } public boolean getSolarMapForLand() { return !noSolarMapForLand; } public void setDisallowFoundationOverlap(final boolean disallowFoundationOverlap) { this.disallowFoundationOverlap = disallowFoundationOverlap; } public boolean getDisallowFoundationOverlap() { return disallowFoundationOverlap; } public void setSolarHeatMapColorContrast(final int solarContrast) { this.solarContrast = solarContrast; } public int getSolarHeatMapColorContrast() { return solarContrast; } public int countParts(final Class<?>[] clazz) { int count = 0; for (final HousePart p : parts) { for (final Class<?> c : clazz) { if (c.isInstance(p)) { count++; } } } return count; } public int getNumberOfSolarPanels() { int count = 0; for (final HousePart p : parts) { if (p instanceof SolarPanel) { count++; } else if (p instanceof Rack) { count += ((Rack) p).getNumberOfSolarPanels(); } } return count; } // XIE: This needs to be called for trees to change texture when the month changes public void setTreeLeaves() { SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { for (final HousePart p : parts) { if (p instanceof Tree) { p.updateTextureAndColor(); } } return null; } }); } public void updateTrackables() { SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { final boolean night = Heliodon.getInstance().isNightTime(); for (final HousePart part : parts) { if (part instanceof Trackable) { if (part instanceof Mirror) { final Mirror mirror = (Mirror) part; if (night) { mirror.drawLightBeams(); // call this so that the light beams can be set invisible } else { mirror.draw(); } } else if (part instanceof SolarPanel) { final SolarPanel panel = (SolarPanel) part; if (night) { panel.drawSunBeam(); // call this so that the sun beam can be set invisible } else { panel.draw(); } } else if (part instanceof Rack) { final Rack rack = (Rack) part; if (night) { rack.drawSunBeam(); // call this so that the sun beam can be set invisible } else { rack.draw(); } } } } return null; } }); } public Ground getGround() { return ground; } public Atmosphere getAtmosphere() { return atmosphere; } public DesignSpecs getDesignSpecs() { return designSpecs; } public void setDashedLinesOnRoofShown(final boolean dashedLineOnRoofs) { this.dashedlineOnRoofs = dashedLineOnRoofs; } public boolean areDashedLinesOnRoofShown() { return dashedlineOnRoofs; } public void setOnlySolarAnalysis(final boolean onlySolarAnalysis) { this.onlySolarAnalysis = onlySolarAnalysis; } public boolean getOnlySolarAnalysis() { return onlySolarAnalysis; } public void setUtilityBill(final UtilityBill utilityBill) { this.utilityBill = utilityBill; } public UtilityBill getUtilityBill() { return utilityBill; } public void setTheme(final int theme) { this.theme = theme; ReadOnlyColorRGBA c; switch (theme) { case DESERT_THEME: c = new ColorRGBA(1, 1, 1, 0.5f); break; case GRASSLAND_THEME: c = new ColorRGBA(0, 1, 0, 0.5f); break; case FOREST_THEME: c = new ColorRGBA(0, 1, 0.2f, 0.5f); break; default: c = new ColorRGBA(0, 1, 0, 0.5f); } setLandColor(c); SceneManager.getInstance().changeSkyTexture(); } public int getTheme() { return theme; } public void setLightBeamsVisible(final boolean showLightBeams) { hideLightBeams = !showLightBeams; } public boolean areLightBeamsVisible() { return !hideLightBeams; } public void setSunAnglesVisible(final boolean showSunAngles) { this.showSunAngles = showSunAngles; } public boolean areSunAnglesVisible() { return showSunAngles; } public void setSolarPanelNx(final int solarPanelNx) { this.solarPanelNx = solarPanelNx; } public int getSolarPanelNx() { return solarPanelNx; } public void setSolarPanelNy(final int solarPanelNy) { this.solarPanelNy = solarPanelNy; } public int getSolarPanelNy() { return solarPanelNy; } public void setRackNx(final int rackNx) { this.rackNx = rackNx; } public int getRackNx() { return rackNx; } public void setRackNy(final int rackNy) { this.rackNy = rackNy; } public int getRackNy() { return rackNy; } public void setRackCellSize(final double rackCellSize) { this.rackCellSize = rackCellSize; } public double getRackCellSize() { return rackCellSize; } public void setMirrorNx(final int mirrorNx) { this.mirrorNx = mirrorNx; } public int getMirrorNx() { return mirrorNx; } public void setMirrorNy(final int mirrorNy) { this.mirrorNy = mirrorNy; } public int getMirrorNy() { return mirrorNy; } public void setSolarStep(final double solarStep) { this.solarStep = solarStep; } public double getSolarStep() { return solarStep; } public void setTimeStep(final int timeStep) { this.timeStep = timeStep; } public int getTimeStep() { return timeStep; } public void setGroundImage(final BufferedImage groundImage, final double groundImageScale) { this.groundImage = groundImage; this.groundImageScale = groundImageScale; applyGroundImage(); } public void setGroundImageScale(final double groundImageScale) { if (isGroundImageEnabled()) { this.groundImageScale = groundImageScale; applyGroundImage(); } } public double getGroundImageScale() { return groundImageScale; } public boolean isGroundImageEnabled() { return groundImage != null; } private void applyGroundImage() { final Mesh mesh = SceneManager.getInstance().getGroundImageLand(); if (groundImage == null) { mesh.setRenderState(new TextureState()); // set a dummy texture in case the mesh holds the original buffered image and causes memory leak mesh.setVisible(false); setFoundationsVisible(true); } else { SceneManager.getInstance().resizeGroundImageLand(groundImageScale); final Texture2D texture = new Texture2D(); texture.setTextureKey(TextureKey.getRTTKey(MinificationFilter.NearestNeighborNoMipMaps)); texture.setImage(AWTImageLoader.makeArdor3dImage(groundImage, true)); final TextureState textureState = new TextureState(); textureState.setTexture(texture); mesh.setRenderState(textureState); mesh.setVisible(!hideGroundImage); setFoundationsVisible(false); } } public void setGroundImageEarthView(final boolean groundImageIsEarthView) { this.groundImageIsEarthView = groundImageIsEarthView; } public boolean isGroundImageEarthView() { return groundImageIsEarthView; } private void setFoundationsVisible(final boolean visible) { for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation) { part.getMesh().setVisible(visible); } } SceneManager.getInstance().refresh(); } public void setShowGroundImage(final boolean showGroundImage) { hideGroundImage = !showGroundImage; } public boolean getShowGroundImage() { return !hideGroundImage; } public void setGroundImageLightColored(final boolean groundImageLightColored) { this.groundImageLightColored = groundImageLightColored; } public boolean isGroundImageLightColored() { return groundImageLightColored; } /** used by SnapshotLogger */ private void storeGroundImageData() { avoidSavingGroundImage = true; } /** used by SnapshotLogger */ private void restoreGroundImageData() { avoidSavingGroundImage = false; } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); if (groundImage != null && !avoidSavingGroundImage) { ImageIO.write(groundImage, "jpg", out); } } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); groundImage = ImageIO.read(in); } public static boolean isSaving() { return isSaving; } public List<Foundation> getFoundationGroup(final Foundation master) { groupFoundations(); for (final List<Foundation> g : foundationGroups) { if (g.contains(master)) { return g; } } return null; } /* put overlapping foundations into separate groups */ private void groupFoundations() { if (foundationGroups == null) { foundationGroups = new ArrayList<List<Foundation>>(); } else { foundationGroups.clear(); } final List<Foundation> foundations = new ArrayList<Foundation>(); for (final HousePart p : parts) { if (p instanceof Foundation) { foundations.add((Foundation) p); } } final int n = foundations.size(); if (n > 1) { int count = 0; final List<Pair> pairs = new ArrayList<Pair>(); for (int i = 0; i < n - 1; i++) { final Foundation fi = foundations.get(i); for (int j = i + 1; j < n; j++) { final Foundation fj = foundations.get(j); if (fi.overlap(fj)) { final Pair p = new Pair(i, j); if (!pairs.contains(p)) { pairs.add(p); } } } } int m = pairs.size(); while (m > 0) { Pair p = pairs.get(0); final List<Integer> list = new ArrayList<Integer>(); list.add(p.i()); list.add(p.j()); pairs.remove(p); m = pairs.size(); if (m > 0) { final List<Pair> toRemove = new ArrayList<Pair>(); for (int x = 0; x < m; x++) { p = pairs.get(x); final int i = p.i(); final int j = p.j(); if (list.contains(i) && list.contains(j)) { if (!toRemove.contains(p)) { toRemove.add(p); } } else if (!list.contains(i) && list.contains(j)) { list.add(i); if (!toRemove.contains(p)) { toRemove.add(p); } } else if (!list.contains(j) && list.contains(i)) { list.add(j); if (!toRemove.contains(p)) { toRemove.add(p); } } } if (!toRemove.isEmpty()) { pairs.removeAll(toRemove); } } final List<Foundation> group = new ArrayList<Foundation>(); for (final Integer a : list) { group.add(foundations.get(a)); } foundationGroups.add(group); count += group.size(); m = pairs.size(); } if (count < foundations.size()) { for (final Foundation f : foundations) { boolean linked = false; for (final List<Foundation> g : foundationGroups) { if (g.contains(f)) { linked = true; break; } } if (!linked) { final List<Foundation> g = new ArrayList<Foundation>(); g.add(f); foundationGroups.add(g); } } } // System.out.println("###" + foundationGroups.size() + "," + (foundations.size() - count)); } else { foundationGroups.add(foundations); } } public void setInstructionSheetText(final int i, final String text) { if (instructionSheetText == null) { instructionSheetText = new String[3]; } if (i < instructionSheetText.length) { instructionSheetText[i] = text; } } public String getInstructionSheetText(final int i) { if (instructionSheetText == null) { return null; } if (i >= instructionSheetText.length) { return null; } return instructionSheetText[i]; } public void setInstructionSheetTextType(final int i, final String type) { if (instructionSheetTextType == null) { instructionSheetTextType = new String[3]; } if (i < instructionSheetTextType.length) { instructionSheetTextType[i] = type; } } public String getInstructionSheetTextType(final int i) { if (instructionSheetTextType == null) { return null; } if (i >= instructionSheetTextType.length) { return null; } return instructionSheetTextType[i]; } }
src/main/java/org/concord/energy3d/scene/Scene.java
package org.concord.energy3d.scene; import java.awt.EventQueue; import java.awt.image.BufferedImage; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import org.concord.energy3d.gui.EnergyPanel; import org.concord.energy3d.gui.MainFrame; import org.concord.energy3d.gui.MainPanel; import org.concord.energy3d.logger.SnapshotLogger; import org.concord.energy3d.model.Door; import org.concord.energy3d.model.Floor; import org.concord.energy3d.model.Foundation; import org.concord.energy3d.model.HousePart; import org.concord.energy3d.model.Human; import org.concord.energy3d.model.Mirror; import org.concord.energy3d.model.Rack; import org.concord.energy3d.model.Roof; import org.concord.energy3d.model.Sensor; import org.concord.energy3d.model.Snap; import org.concord.energy3d.model.SolarPanel; import org.concord.energy3d.model.Thermalizable; import org.concord.energy3d.model.Trackable; import org.concord.energy3d.model.Tree; import org.concord.energy3d.model.Wall; import org.concord.energy3d.model.Window; import org.concord.energy3d.scene.SceneManager.ViewMode; import org.concord.energy3d.shapes.Heliodon; import org.concord.energy3d.simulation.Atmosphere; import org.concord.energy3d.simulation.DesignSpecs; import org.concord.energy3d.simulation.Ground; import org.concord.energy3d.simulation.UtilityBill; import org.concord.energy3d.undo.AddMultiplePartsCommand; import org.concord.energy3d.undo.LockAllCommand; import org.concord.energy3d.undo.PastePartCommand; import org.concord.energy3d.undo.RemoveMultiplePartsCommand; import org.concord.energy3d.undo.RemoveMultipleShuttersCommand; import org.concord.energy3d.undo.SaveCommand; import org.concord.energy3d.util.Config; import org.concord.energy3d.util.Pair; import org.concord.energy3d.util.Util; import org.concord.energy3d.util.WallVisitor; import com.ardor3d.image.Texture.MinificationFilter; import com.ardor3d.image.Texture2D; import com.ardor3d.image.util.awt.AWTImageLoader; import com.ardor3d.math.ColorRGBA; import com.ardor3d.math.Vector3; import com.ardor3d.math.type.ReadOnlyColorRGBA; import com.ardor3d.math.type.ReadOnlyVector3; import com.ardor3d.renderer.Camera; import com.ardor3d.renderer.state.TextureState; import com.ardor3d.scenegraph.Mesh; import com.ardor3d.scenegraph.Node; import com.ardor3d.util.TextureKey; public class Scene implements Serializable { public static final ReadOnlyColorRGBA WHITE = ColorRGBA.WHITE; public static final ReadOnlyColorRGBA GRAY = ColorRGBA.LIGHT_GRAY; public static final int CLOUDY_SKY_THEME = 0; public static final int DESERT_THEME = 1; public static final int GRASSLAND_THEME = 2; public static final int FOREST_THEME = 3; private static final long serialVersionUID = 1L; private static final Node root = new Node("House Root"); private static final Node originalHouseRoot = new Node("Original House Root"); private static final Node notReceivingShadowRoot = new Node("Trees Root"); private static final int currentVersion = 1; private static Scene instance; private static URL url = null; private static boolean redrawAll = false; private static boolean drawThickness = false; private static boolean drawAnnotationsInside = false; private static boolean isSaving; private transient boolean edited = false; private transient BufferedImage groundImage; private transient boolean avoidSavingGroundImage; private final List<HousePart> parts = new ArrayList<HousePart>(); private final Calendar calendar = Calendar.getInstance(); private TextureMode textureMode = TextureMode.Full; private ReadOnlyVector3 cameraLocation; private ReadOnlyVector3 cameraDirection; private ReadOnlyColorRGBA landColor = new ColorRGBA(0, 1, 0, 0.5f); private ReadOnlyColorRGBA foundationColor; private ReadOnlyColorRGBA wallColor; private ReadOnlyColorRGBA doorColor; private ReadOnlyColorRGBA floorColor; private ReadOnlyColorRGBA roofColor; private Unit unit = Unit.InternationalSystemOfUnits; private Ground ground = new Ground(); private Atmosphere atmosphere = new Atmosphere(); private DesignSpecs designSpecs = new DesignSpecs(); private HousePart copyBuffer, originalCopy; private UtilityBill utilityBill; private String projectName; private String city; private String note; private long idCounter; private int version = currentVersion; private int latitude; private int solarContrast; private int theme; private double annotationScale = 0.2; private double heatVectorLength = 2000; private double heatFluxGridSize = 2; private boolean isAnnotationsVisible = true; private boolean studentMode; private boolean isHeliodonVisible; private boolean hideAxes; private boolean hideLightBeams; private boolean showSunAngles; private boolean showBuildingLabels; private boolean cleanup; private boolean alwaysComputeHeatFluxVectors; private boolean fullEnergyInSolarMap = true; private boolean onlyReflectedEnergyInMirrorSolarMap; private boolean noSolarMapForLand; private boolean disallowFoundationOverlap; private boolean dashedlineOnRoofs = true; private boolean onlySolarAnalysis; private double groundImageScale = 1; private boolean hideGroundImage; private boolean groundImageIsEarthView; private boolean groundImageLightColored; // a parameter that user can choose to improve the contrast of edit points etc. (i.e., no white on white) private transient List<List<Foundation>> foundationGroups; private String[] instructionSheetText; private String[] instructionSheetTextType; /* the following parameters specify the resolution of discretization for a simulation */ // increment of time in minutes private int timeStep = 15; // number of points in x and y directions when a solar panel is discretized into a grid (to meet the need of texture, these numbers must be power of 2) // used in heat map visualization for solar panels (for radiation calculation, solar panels use the underlying solar cell layout, e.g., 6x10, as the discretization) private int solarPanelNx = 4, solarPanelNy = 4; // number of points in x and y directions when a solar rack is discretized into a grid (to meet the need of texture, these numbers must be power of 2) // used in heat map visualization for solar panel racks (for radiation calculation, specify the size of the unit cell as follows) private int rackNx = 8, rackNy = 8; private double rackCellSize = 1; // by default, the cell is 1 x 1 meter // number of points in x and y directions when a mirror is discretized into a grid (to meet the need of texture, these numbers must be power of 2) // used in both radiation calculation and heat map visualization for reflecting mirrors (which are closer to square, except parabolic troughs) private int mirrorNx = 4, mirrorNy = 4; // the step length of the discretized grid on any part that is not a plate private double solarStep = 2.0; public static enum Unit { InternationalSystemOfUnits, USCustomaryUnits }; public static enum TextureMode { None, Simple, Full }; public static Scene getInstance() { if (instance == null) { try { open(null); } catch (final Exception e) { e.printStackTrace(); } } return instance; } public static void newFile() { newFile(80, 60); // by default, the foundation is 16 meters x 12 meters (192 square meters seem right for a house) } private static void newFile(final double xLength, final double yLength) { try { open(null); } catch (final Exception e) { e.printStackTrace(); } SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { instance.add(new Human(Human.JACK, 1)); instance.add(new Foundation(xLength, yLength), true); return null; } }); EventQueue.invokeLater(new Runnable() { @Override public void run() { EnergyPanel.getInstance().update(); EnergyPanel.getInstance().clearAllGraphs(); EnergyPanel.getInstance().selectInstructionSheet(0); } }); } public static void open(final URL file) throws Exception { openNow(file); EventQueue.invokeLater(new Runnable() { @Override public void run() { final EnergyPanel e = EnergyPanel.getInstance(); e.update(); e.clearAllGraphs(); e.selectInstructionSheet(0); if (MainFrame.getInstance().getTopViewCheckBoxMenuItem().isSelected()) { // make sure we exist the 2D top view MainFrame.getInstance().getTopViewCheckBoxMenuItem().setSelected(false); SceneManager.getInstance().resetCamera(ViewMode.NORMAL); loadCameraLocation(); } final HousePart p = SceneManager.getInstance().getSelectedPart(); if (p instanceof Foundation) { final Foundation f = (Foundation) p; switch (f.getSupportingType()) { case Foundation.BUILDING: e.getConstructionCostGraph().addGraph(f); e.getBuildingDailyEnergyGraph().clearData(); e.getBuildingDailyEnergyGraph().addGraph(f); e.validate(); break; case Foundation.PV_STATION: e.getPvStationDailyEnergyGraph().clearData(); e.getPvStationDailyEnergyGraph().addGraph(f); e.validate(); break; case Foundation.CSP_STATION: e.getCspStationDailyEnergyGraph().clearData(); e.getCspStationDailyEnergyGraph().addGraph(f); e.validate(); break; } } } }); } public static void openNow(final URL file) throws Exception { if (PrintController.getInstance().isPrintPreview()) { MainPanel.getInstance().getPreviewButton().setSelected(false); while (!PrintController.getInstance().isFinished()) { Thread.yield(); } } Scene.url = file; EventQueue.invokeLater(new Runnable() { @Override public void run() { MainPanel.getInstance().getHeliodonButton().setSelected(false); MainPanel.getInstance().getSunAnimationButton().setSelected(false); } }); SceneManager.getInstance().setSolarHeatMapWithoutUpdate(false); Wall.resetDefaultWallHeight(); if (instance != null) { instance.deleteAll(); } if (url == null) { instance = new Scene(); System.out.println("done"); } else { System.out.print("Opening..." + file + "..."); final ObjectInputStream in = new ObjectInputStream(file.openStream()); instance = (Scene) in.readObject(); in.close(); for (final HousePart part : instance.parts) { part.getRoot(); } instance.upgradeSceneToNewVersion(); instance.cleanup(); loadCameraLocation(); } if (Util.isZero(instance.groundImageScale)) { instance.groundImageScale = 1; } instance.applyGroundImage(); SceneManager.getInstance().hideAllEditPoints(); final CameraControl cameraControl = SceneManager.getInstance().getCameraControl(); if (cameraControl != null) { cameraControl.reset(); } instance.init(); EventQueue.invokeLater(new Runnable() { // update GUI must be called in Event Queue to prevent possible deadlocks @Override public void run() { if (instance.textureMode == TextureMode.None) { MainFrame.getInstance().getNoTextureMenuItem().setSelected(true); } else if (instance.textureMode == TextureMode.Simple) { MainFrame.getInstance().getSimpleTextureMenuItem().setSelected(true); } else { MainFrame.getInstance().getFullTextureMenuItem().setSelected(true); } MainPanel.getInstance().getAnnotationButton().setSelected(instance.isAnnotationsVisible); MainFrame.getInstance().updateTitleBar(); } }); } private void init() { root.detachAllChildren(); originalHouseRoot.detachAllChildren(); notReceivingShadowRoot.detachAllChildren(); root.attachChild(originalHouseRoot); root.attachChild(notReceivingShadowRoot); if (url != null) { for (final HousePart p : parts) { final boolean b = p instanceof Tree || p instanceof Human; (b ? notReceivingShadowRoot : originalHouseRoot).attachChild(p.getRoot()); } System.out.println("initSceneNow done"); /* must redraw now so that heliodon can be initialized to right size if it is to be visible */ // redrawAllNow(); } root.updateWorldBound(true); SceneManager.getInstance().updateHeliodonAndAnnotationSize(); SceneManager.getInstance().setAxesVisible(!hideAxes); SceneManager.getInstance().setBuildingLabelsVisible(showBuildingLabels); SceneManager.getInstance().getSolarLand().setVisible(!noSolarMapForLand); setTheme(theme); SceneManager.getInstance().getLand().setDefaultColor(landColor != null ? landColor : new ColorRGBA(0, 1, 0, 0.5f)); final EnergyPanel energyPanel = EnergyPanel.getInstance(); if (calendar != null) { final Date time = calendar.getTime(); Heliodon.getInstance().setDate(time); Heliodon.getInstance().setTime(time); Util.setSilently(energyPanel.getDateSpinner(), time); Util.setSilently(energyPanel.getTimeSpinner(), time); if ("Boston".equals(city) || city == null || "".equals(city)) { city = "Boston, MA"; latitude = 42; } energyPanel.setLatitude(latitude); // already silent Util.selectSilently(energyPanel.getCityComboBox(), city); Scene.getInstance().setTreeLeaves(); MainPanel.getInstance().getHeliodonButton().setSelected(isHeliodonVisible); Heliodon.getInstance().drawSun(); SceneManager.getInstance().changeSkyTexture(); SceneManager.getInstance().setShading(Heliodon.getInstance().isNightTime()); } // previous versions do not have the following classes if (designSpecs == null) { designSpecs = new DesignSpecs(); } else { designSpecs.setDefaultValues(); } if (ground == null) { ground = new Ground(); } if (atmosphere == null) { atmosphere = new Atmosphere(); } if (unit == null) { unit = Unit.InternationalSystemOfUnits; } // restore the default values if (Util.isZero(heatVectorLength)) { heatVectorLength = 5000; } if (Util.isZero(heatFluxGridSize)) { heatFluxGridSize = 2; } if (Util.isZero(solarStep)) { solarStep = 2; } if (Util.isZero(timeStep)) { timeStep = 15; } if (Util.isZero(solarPanelNx)) { solarPanelNx = 4; } if (Util.isZero(solarPanelNy)) { solarPanelNy = 4; } if (Util.isZero(rackNx)) { rackNx = 8; } if (Util.isZero(rackNy)) { rackNy = 8; } if (Util.isZero(mirrorNx)) { mirrorNx = 4; } if (Util.isZero(mirrorNy)) { mirrorNy = 4; } if (Util.isZero(rackCellSize)) { rackCellSize = 1; } if (Util.isZero(solarContrast)) { solarContrast = 50; } setEdited(false); setCopyBuffer(null); Util.setSilently(energyPanel.getColorMapSlider(), solarContrast); Util.setSilently(MainPanel.getInstance().getNoteTextArea(), note == null ? "" : note); // need to do this to avoid logging EventQueue.invokeLater(new Runnable() { @Override public void run() { energyPanel.updateThermostat(); MainPanel.getInstance().setNoteVisible(MainPanel.getInstance().isNoteVisible()); // necessary for the scroll bars to show up appropriately MainPanel.getInstance().getEnergyViewButton().setSelected(false); // moved from OpenNow to here to avoid triggering EnergyComputer -> RedrawAllNow before open is completed SceneManager.getInstance().getUndoManager().die(); } }); } public static double parsePropertyString(final String s) { final int indexOfSpace = s.indexOf(' '); return Double.parseDouble(s.substring(0, indexOfSpace != -1 ? indexOfSpace : s.length())); } public static void loadCameraLocation() { final Camera camera = SceneManager.getInstance().getCamera(); if (instance.getCameraLocation() != null && instance.getCameraDirection() != null) { camera.setLocation(instance.getCameraLocation()); camera.lookAt(instance.getCameraLocation().add(instance.getCameraDirection(), null), Vector3.UNIT_Z); } SceneManager.getInstance().getCameraNode().updateFromCamera(); Scene.getInstance().updateEditShapes(); } public static void importFile(final URL url) throws Exception { if (PrintController.getInstance().isPrintPreview()) { MainPanel.getInstance().getPreviewButton().setSelected(false); while (!PrintController.getInstance().isFinished()) { Thread.yield(); } } if (url != null) { long max = -1; for (final HousePart x : Scene.getInstance().parts) { if (x.getId() > max) { max = x.getId(); } } if (max < 0) { max = 0; } System.out.print("Opening..." + url + "..."); final ObjectInputStream in = new ObjectInputStream(url.openStream()); final Scene instance = (Scene) in.readObject(); in.close(); // instance.cleanup(); instance.upgradeSceneToNewVersion(); if (url != null) { final AddMultiplePartsCommand cmd = new AddMultiplePartsCommand(new ArrayList<HousePart>(instance.getParts()), url); double cx = 0; double cy = 0; int count = 0; for (final HousePart p : instance.getParts()) { p.setId(max + p.getId()); Scene.getInstance().parts.add(p); originalHouseRoot.attachChild(p.getRoot()); if (p instanceof Foundation || p instanceof Tree || p instanceof Human) { final Vector3 c = p.getAbsCenter(); cx += c.getX(); cy += c.getY(); count++; } } final Vector3 position = SceneManager.getInstance().getPickedLocationOnLand(); if (position != null) { final Vector3 shift = position.subtractLocal(count == 0 ? new Vector3(0, 0, 0) : new Vector3(cx / count, cy / count, 0)); for (final HousePart p : instance.getParts()) { if (p instanceof Foundation || p instanceof Tree || p instanceof Human) { for (int i = 0; i < p.getPoints().size(); i++) { p.getPoints().get(i).addLocal(shift); } } } } redrawAll = true; SceneManager.getInstance().getUndoManager().addEdit(cmd); } root.updateWorldBound(true); EventQueue.invokeLater(new Runnable() { @Override public void run() { MainPanel.getInstance().getEnergyViewButton().setSelected(false); } }); } else { JOptionPane.showMessageDialog(MainFrame.getInstance(), "URL doesn't exist.", "Error", JOptionPane.ERROR_MESSAGE); } } /** This can be used by the user to fix problems that are caused by bugs based on our observations. This is different than cleanup() as the latter cannot be used to remove undrawables. */ public void fixProblems(final boolean redraw) { // remove all undrawables final ArrayList<HousePart> a = new ArrayList<HousePart>(); for (final HousePart p : parts) { if (!p.isDrawable()) { a.add(p); } } for (final HousePart p : a) { remove(p, false); } a.clear(); cleanup(); if (redraw) { redrawAll(true); } } private void deleteAll() { for (final HousePart p : parts) { p.delete(); } } private void cleanup() { // fix if roof and wall are not linked from each other for (final HousePart p : parts) { if (p instanceof Roof) { final Roof r = (Roof) p; final HousePart c = r.getContainer(); if (c != null && !c.getChildren().contains(r)) { c.getChildren().add(r); } } } final ArrayList<HousePart> toBeRemoved = new ArrayList<HousePart>(); for (final HousePart p : parts) { if (!p.isValid()) { // remove invalid parts toBeRemoved.add(p); } else if (p.getContainer() == null) { // remove orphan parts without a top container if (p instanceof Wall || p instanceof Roof || p instanceof Window || p instanceof Door || p instanceof SolarPanel || p instanceof Rack || p instanceof Floor) { toBeRemoved.add(p); } } else if (!parts.contains(p.getContainer())) { // remove parts whose container doesn't exist in the scene toBeRemoved.add(p); } else if (p instanceof Wall) { // remove walls that are at the same position if (((Wall) p).isAtSamePlaceAsAnotherPart()) { toBeRemoved.add(p); } } } for (final HousePart p : toBeRemoved) { remove(p, false); } // remove children with multiple parents toBeRemoved.clear(); for (final HousePart p : parts) { for (final HousePart child : p.getChildren()) { if (child.getContainer() != p && !toBeRemoved.contains(child)) { toBeRemoved.add(child); } } } for (final HousePart p : toBeRemoved) { remove(p, false); } // remove from remaining parents for (final HousePart p : parts) { for (final HousePart r : toBeRemoved) { p.getChildren().remove(r); } } // remove all the children that are not in parts toBeRemoved.clear(); for (final HousePart p : parts) { for (final HousePart child : p.getChildren()) { if (!parts.contains(child) && !toBeRemoved.contains(child)) { toBeRemoved.add(child); } } } for (final HousePart p : toBeRemoved) { remove(p, false); } // complete all non-completed parts for (final HousePart p : parts) { if (!p.isDrawCompleted()) { p.complete(); } } } private void upgradeSceneToNewVersion() { if (textureMode == null) { textureMode = TextureMode.Full; for (final HousePart p : parts) { if (p instanceof Roof) { ((Roof) p).setOverhangLength(0.2); } } } if (version < 1) { for (final HousePart part : parts) { if (part instanceof Foundation) { ((Foundation) part).scaleHouseForNewVersion(10); } } cameraLocation = cameraLocation.multiply(10, null); setAnnotationScale(1.0); } version = currentVersion; } public void connectWalls() { for (final HousePart part : parts) { if (part instanceof Wall) { part.reset(); } } for (final HousePart part : parts) { if (part instanceof Wall) { ((Wall) part).connectedWalls(); } } for (final HousePart part : parts) { if (part instanceof Wall) { ((Wall) part).computeInsideDirectionOfAttachedWalls(false); } } } public static void save(final URL url, final boolean setAsCurrentFile) { save(url, setAsCurrentFile, true, false); } public static void save(final URL url, final boolean setAsCurrentFile, final boolean notifyUndoManager, final boolean logger) { isSaving = true; SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { try { realSave(url, setAsCurrentFile, notifyUndoManager, logger); } catch (final Throwable e) { Util.reportError(e); } finally { isSaving = false; } return null; } }); } public static void saveOutsideTaskManager(final URL url, final boolean setAsCurrentFile, final boolean notifyUndoManager, final boolean logger) { isSaving = true; try { realSave(url, setAsCurrentFile, notifyUndoManager, logger); } catch (final Throwable e) { e.printStackTrace(); } finally { isSaving = false; } } private static void realSave(final URL url, final boolean setAsCurrentFile, final boolean notifyUndoManager, final boolean logger) throws Exception { if (logger) { instance.storeGroundImageData(); } if (notifyUndoManager) { instance.cleanup(); } // save camera to file if (SceneManager.getInstance().getViewMode() == ViewMode.NORMAL) { saveCameraLocation(); } instance.hideAxes = !SceneManager.getInstance().areAxesVisible(); instance.showBuildingLabels = SceneManager.getInstance().areBuildingLabelsVisible(); instance.calendar.setTime(Heliodon.getInstance().getCalendar().getTime()); instance.latitude = (int) Math.toDegrees(Heliodon.getInstance().getLatitude()); instance.city = (String) EnergyPanel.getInstance().getCityComboBox().getSelectedItem(); instance.isHeliodonVisible = Heliodon.getInstance().isVisible(); instance.note = MainPanel.getInstance().getNoteTextArea().getText().trim(); instance.solarContrast = EnergyPanel.getInstance().getColorMapSlider().getValue(); if (setAsCurrentFile) { Scene.url = url; } System.out.print("Saving " + url + "..."); final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(url.toURI().getPath())); out.writeObject(instance); out.close(); if (notifyUndoManager) { SceneManager.getInstance().getUndoManager().addEdit(new SaveCommand()); } if (logger) { instance.restoreGroundImageData(); } System.out.println("done"); } public static void saveCameraLocation() { final Camera camera = SceneManager.getInstance().getCamera(); instance.setCameraLocation(camera.getLocation().clone()); instance.setCameraDirection(SceneManager.getInstance().getCamera().getDirection().clone()); } public static Node getRoot() { return root; } private Scene() { } public void add(final HousePart housePart, final boolean redraw) { final HousePart container = housePart.getContainer(); if (container != null) { container.getChildren().add(housePart); } add(housePart); if (redraw) { redrawAll(); } } private void add(final HousePart housePart) { System.out.println("Adding: " + housePart); if (housePart instanceof Tree || housePart instanceof Human) { notReceivingShadowRoot.attachChild(housePart.getRoot()); } else { originalHouseRoot.attachChild(housePart.getRoot()); } parts.add(housePart); for (final HousePart child : housePart.getChildren()) { add(child); } } public void remove(final HousePart housePart, final boolean redraw) { if (housePart == null) { return; } housePart.setGridsVisible(false); final HousePart container = housePart.getContainer(); if (container != null) { container.getChildren().remove(housePart); } removeChildren(housePart); if (redraw) { redrawAll(); } } private void removeChildren(final HousePart housePart) { System.out.println("Removing: " + housePart); parts.remove(housePart); // this must happen before call to wall.delete() for (final HousePart child : housePart.getChildren()) { removeChildren(child); } // originalHouseRoot.detachChild(housePart.getRoot()); housePart.getRoot().removeFromParent(); housePart.delete(); } private static void setIdOfChildren(final HousePart p) { final ArrayList<HousePart> children = p.getChildren(); for (final HousePart c : children) { c.setId(Scene.getInstance().nextID()); if (!c.getChildren().isEmpty()) { setIdOfChildren(c); } } } public void setCopyBuffer(final HousePart p) { EnergyPanel.getInstance().clearRadiationHeatMap(); // exclude the following types of house parts if (p instanceof Roof || p instanceof Floor || p instanceof Sensor) { return; } copyBuffer = p; originalCopy = p; } public HousePart getCopyBuffer() { return copyBuffer; } public HousePart getOriginalCopy() { return originalCopy; } public void paste() { if (copyBuffer == null) { return; } if (copyBuffer instanceof Foundation) { return; } EnergyPanel.getInstance().clearRadiationHeatMap(); final HousePart c = copyBuffer.copy(true); if (c == null) { return; } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); EnergyPanel.getInstance().clearRadiationHeatMap(); EnergyPanel.getInstance().update(); } public void pasteToPickedLocationOnLand() { EnergyPanel.getInstance().clearRadiationHeatMap(); if (copyBuffer == null) { return; } final HousePart c = copyBuffer.copy(false); if (c == null) { return; } final Vector3 position = SceneManager.getInstance().getPickedLocationOnLand(); if (position == null) { return; } if (c instanceof Tree || c instanceof Human) { c.getPoints().set(0, position); add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } else if (c instanceof Foundation) { // pasting a foundation also clones the building above it final Vector3 shift = position.subtractLocal(c.getAbsCenter()).multiplyLocal(1, 1, 0); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { c.getPoints().get(i).addLocal(shift); } add(c, true); // copy gable info, too final Foundation oldFoundation = (Foundation) copyBuffer; final Foundation newFoundation = (Foundation) c; final List<Roof> oldRoofs = oldFoundation.getRoofs(); final List<Roof> newRoofs = newFoundation.getRoofs(); if (!oldRoofs.isEmpty() && !newRoofs.isEmpty()) { for (int i = 0; i < newRoofs.size(); i++) { final Map<Integer, List<Wall>> oldMap = oldRoofs.get(i).getGableEditPointToWallMap(); if (oldMap == null || oldMap.isEmpty()) { continue; } final Map<Integer, List<Wall>> newMap = new HashMap<Integer, List<Wall>>(); for (final Integer key : oldMap.keySet()) { final List<Wall> oldWalls = oldMap.get(key); final List<Wall> newWalls = new ArrayList<Wall>(); for (final Wall w : oldWalls) { newWalls.add(getCopiedWall(w, oldFoundation, newFoundation)); } newMap.put(key, newWalls); } newRoofs.get(i).setGableEditPointToWallMap(newMap); } } copyBuffer = c; setIdOfChildren(c); SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } } private Wall getCopiedWall(final Wall oldWall, final Foundation oldFoundation, final Foundation newFoundation) { final ArrayList<HousePart> oldWalls = oldFoundation.getChildren(); final ArrayList<HousePart> newWalls = newFoundation.getChildren(); final int index = oldWalls.indexOf(oldWall); if (index < 0) { return null; } return (Wall) newWalls.get(index); } public void pasteToPickedLocationOnWall() { EnergyPanel.getInstance().clearRadiationHeatMap(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (!(selectedPart instanceof Wall)) { return; } if (copyBuffer == null) { return; } if (copyBuffer instanceof Foundation) { return; } final HousePart c = copyBuffer.copy(false); if (c == null) { return; } Vector3 position = SceneManager.getInstance().getPickedLocationOnWall(); if (position == null) { return; } final Wall wall = (Wall) selectedPart; if (wall != c.getContainer()) { // windows and solar panels can be pasted to a different wall if (c instanceof Window) { ((Window) c).moveTo(wall); } else if (c instanceof SolarPanel) { ((SolarPanel) c).moveTo(wall); } } position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0))); final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0))); position = position.subtractLocal(center); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); v.addLocal(position); } // out of boundary check final List<Vector3> polygon = wall.getWallPolygonPoints(); final List<Vector3> relativePolygon = new ArrayList<Vector3>(); for (final Vector3 p : polygon) { relativePolygon.add(c.toRelative(p)); } for (final Vector3 p : relativePolygon) { final double y = p.getY(); p.setY(p.getZ()); p.setZ(y); } for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); if (!Util.insidePolygon(new Vector3(v.getX(), v.getZ(), v.getY()), relativePolygon)) { return; } } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } public void pasteToPickedLocationOnRoof() { EnergyPanel.getInstance().clearRadiationHeatMap(); if (copyBuffer == null) { return; } if (copyBuffer instanceof Foundation) { return; } final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (!(selectedPart instanceof Roof)) { return; } final HousePart c = copyBuffer.copy(false); if (c == null) { return; } Vector3 position = SceneManager.getInstance().getPickedLocationOnRoof(); if (position == null) { return; } if (selectedPart != c.getContainer()) { // solar panels and racks can be pasted to a different parent if (c instanceof SolarPanel) { ((SolarPanel) c).moveTo(selectedPart); } else if (c instanceof Rack) { ((Rack) c).moveTo(selectedPart); } } position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0))); final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0))); position = position.subtractLocal(center); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); v.addLocal(position); } if (c instanceof Rack) { ((Rack) c).moveSolarPanels(position); setIdOfChildren(c); } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } public void pasteToPickedLocationOnRack() { final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (!(selectedPart instanceof Rack)) { return; } if (!(copyBuffer instanceof SolarPanel)) { return; } EnergyPanel.getInstance().clearRadiationHeatMap(); final HousePart c = copyBuffer.copy(false); if (c == null) { return; } Vector3 position = SceneManager.getInstance().getPickedLocationOnRack(); if (position == null) { return; } if (selectedPart != c.getContainer()) { ((SolarPanel) c).moveTo(selectedPart); } position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0))); final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0))); position = position.subtractLocal(center); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); v.addLocal(position); } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } public void pasteToPickedLocationOnFoundation() { EnergyPanel.getInstance().clearRadiationHeatMap(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (!(selectedPart instanceof Foundation)) { return; } if (copyBuffer == null) { return; } final HousePart c = copyBuffer.copy(false); if (c == null) { return; } Vector3 position = SceneManager.getInstance().getPickedLocationOnFoundation(); if (position == null) { return; } c.setContainer(selectedPart); // move to this foundation position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0))); final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0))); position = position.subtractLocal(center); final int n = c.getPoints().size(); for (int i = 0; i < n; i++) { final Vector3 v = c.getPoints().get(i); v.addLocal(position); } if (c instanceof Rack) { ((Rack) c).moveSolarPanels(position); setIdOfChildren(c); } add(c, true); copyBuffer = c; SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c)); } public List<HousePart> getParts() { return parts; } public HousePart getPart(final long id) { for (final HousePart p : parts) { if (id == p.getId()) { return p; } } return null; } public void drawResizeBounds() { for (final HousePart part : parts) { if (part instanceof Foundation) { part.draw(); } } } public static Node getOriginalHouseRoot() { return originalHouseRoot; } public static Node getNotReceivingShadowRoot() { return notReceivingShadowRoot; } public static URL getURL() { return url; } public static boolean isInternalFile() { if (Config.isEclipse()) { return url != null && url.toString().indexOf("/energy3d/target/classes") != -1; } return url != null && url.toString().indexOf(".jar!") != -1; } public void setAnnotationsVisible(final boolean visible) { isAnnotationsVisible = visible; for (final HousePart part : parts) { part.setAnnotationsVisible(visible); } if (PrintController.getInstance().isPrintPreview()) { for (final HousePart part : PrintController.getInstance().getPrintParts()) { part.setAnnotationsVisible(visible); } } if (PrintController.getInstance().isPrintPreview()) { PrintController.getInstance().restartAnimation(); } else { SceneManager.getInstance().refresh(); } } public void setTextureMode(final TextureMode textureMode) { this.textureMode = textureMode; redrawAll(); Scene.getInstance().updateRoofDashLinesColor(); } public TextureMode getTextureMode() { return textureMode; } public void setDrawThickness(final boolean draw) { drawThickness = draw; redrawAll = true; } public boolean isDrawThickness() { return drawThickness; } public static boolean isDrawAnnotationsInside() { return drawAnnotationsInside; } public static void setDrawAnnotationsInside(final boolean drawAnnotationsInside) { Scene.drawAnnotationsInside = drawAnnotationsInside; for (final HousePart part : instance.getParts()) { part.drawAnnotations(); } if (PrintController.getInstance().getPrintParts() != null) { for (final HousePart part : PrintController.getInstance().getPrintParts()) { part.drawAnnotations(); } } } public void redrawAll() { redrawAll(false); } public void redrawAll(final boolean cleanup) { this.cleanup = cleanup; if (PrintController.getInstance().isPrintPreview()) { PrintController.getInstance().restartAnimation(); } else { redrawAll = true; } } public void redrawAllNow() { System.out.println("redrawAllNow()"); final long t = System.nanoTime(); if (cleanup) { cleanup(); cleanup = false; } connectWalls(); Snap.clearAnnotationDrawn(); for (final HousePart part : parts) { if (part instanceof Roof) { part.draw(); } } for (final HousePart part : parts) { if (!(part instanceof Roof)) { part.draw(); } } // need to draw roof again because roof holes depend on drawn windows for (final HousePart part : parts) { if (part instanceof Roof) { part.draw(); } } if (Heliodon.getInstance().isVisible()) { Heliodon.getInstance().updateSize(); } System.out.println("Time = " + (System.nanoTime() - t) / 1000000000.0); // no need for redrawing print parts because they will be regenerated from original parts anyways redrawAll = false; } public void updateAllTextures() { System.out.println("updateAllTextures()"); for (final HousePart part : parts) { part.updateTextureAndColor(); } SceneManager.getInstance().refresh(); } public void setUnit(final Unit unit) { this.unit = unit; redrawAll = true; } public Unit getUnit() { if (unit == null) { unit = Unit.InternationalSystemOfUnits; } return unit; } public void setAnnotationScale(final double scale) { annotationScale = scale; } public double getAnnotationScale() { if (annotationScale == 0) { annotationScale = 10; } return annotationScale; } public void updateRoofDashLinesColor() { for (final HousePart part : parts) { if (part instanceof Roof) { ((Roof) part).updateDashLinesColor(); } } if (PrintController.getInstance().getPrintParts() != null) { for (final HousePart part : PrintController.getInstance().getPrintParts()) { if (part instanceof Roof) { ((Roof) part).updateDashLinesColor(); } } } } public void removeAllTrees() { final ArrayList<HousePart> trees = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Tree && !part.isFrozen()) { trees.add(part); } } if (trees.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no tree to remove.", "No Tree", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + trees.size() + " trees?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(trees); for (final HousePart part : trees) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllHumans() { final ArrayList<HousePart> humans = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Human) { humans.add(part); } } if (humans.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no human to remove.", "No Human", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + humans.size() + " humans?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(humans); for (final HousePart part : humans) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllRoofs() { final ArrayList<HousePart> roofs = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Roof && !part.isFrozen()) { roofs.add(part); } } if (roofs.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no roof to remove.", "No Roof", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + roofs.size() + " roofs?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(roofs); for (final HousePart part : roofs) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllFloors() { final ArrayList<HousePart> floors = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Floor && !part.isFrozen()) { floors.add(part); } } if (floors.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no floor to remove.", "No Floor", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + floors.size() + " floors?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(floors); for (final HousePart part : floors) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllSolarPanels(List<SolarPanel> panels) { final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (panels == null) { panels = new ArrayList<SolarPanel>(); if (selectedPart != null) { if (selectedPart instanceof Rack) { for (final HousePart part : selectedPart.getChildren()) { if (part instanceof SolarPanel) { panels.add((SolarPanel) part); } } } else { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof SolarPanel && !part.isFrozen() && part.getTopContainer() == foundation) { panels.add((SolarPanel) part); } } } } else { for (final HousePart part : parts) { if (part instanceof SolarPanel && !part.isFrozen()) { panels.add((SolarPanel) part); } } } } if (panels.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no solar panel to remove.", "No Solar Panel", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + panels.size() + " solar panels" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(new ArrayList<HousePart>(panels)); for (final HousePart part : panels) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllRacks() { final ArrayList<HousePart> racks = new ArrayList<HousePart>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Rack && !part.isFrozen() && part.getTopContainer() == foundation) { racks.add(part); } } } else { for (final HousePart part : parts) { if (part instanceof Rack && !part.isFrozen()) { racks.add(part); } } } if (racks.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no rack to remove.", "No Rack", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + racks.size() + " solar panel racks" + (selectedPart != null ? " on the selected foundation" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(racks); for (final HousePart part : racks) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllMirrors() { final ArrayList<HousePart> mirrors = new ArrayList<HousePart>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Mirror && !part.isFrozen() && part.getTopContainer() == foundation) { mirrors.add(part); } } } else { for (final HousePart part : parts) { if (part instanceof Mirror && !part.isFrozen()) { mirrors.add(part); } } } if (mirrors.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no mirror to remove.", "No Mirror", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + mirrors.size() + " mirrors" + (selectedPart != null ? " on the selected foundation" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(mirrors); for (final HousePart part : mirrors) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllWindows() { final ArrayList<HousePart> windows = new ArrayList<HousePart>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Window && !part.isFrozen() && part.getTopContainer() == foundation) { windows.add(part); } } } else { for (final HousePart part : parts) { if (part instanceof Window && !part.isFrozen()) { windows.add(part); } } } if (windows.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no window to remove.", "No Window", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + windows.size() + " windows" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(windows); for (final HousePart part : windows) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllWindowShutters() { final ArrayList<Window> windows = new ArrayList<Window>(); final HousePart selectedPart = SceneManager.getInstance().getSelectedPart(); if (selectedPart != null) { final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer(); for (final HousePart part : parts) { if (part instanceof Window && !part.isFrozen() && part.getTopContainer() == foundation) { final Window w = (Window) part; if (w.getLeftShutter() || w.getRightShutter()) { windows.add(w); } } } } else { for (final HousePart part : parts) { if (part instanceof Window && !part.isFrozen()) { final Window w = (Window) part; if (w.getLeftShutter() || w.getRightShutter()) { windows.add(w); } } } } if (windows.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no window shutter to remove.", "No Shutter", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + windows.size() + " window shutters" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultipleShuttersCommand c = new RemoveMultipleShuttersCommand(windows); for (final HousePart part : windows) { final Window w = (Window) part; w.setLeftShutter(false); w.setRightShutter(false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllFoundations() { final ArrayList<HousePart> foundations = new ArrayList<HousePart>(); for (final HousePart part : parts) { if (part instanceof Foundation && !part.isFrozen()) { foundations.add(part); } } if (foundations.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no activated foundation to remove.", "No Foundation", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + foundations.size() + " foundations?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(foundations); for (final HousePart part : foundations) { remove(part, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void removeAllChildren(final HousePart parent) { final List<HousePart> children = parent.getChildren(); final String s = parent.getClass().getSimpleName(); final List<HousePart> copy = new ArrayList<HousePart>(); // make a copy to avoid ConcurrentModificationException for (final HousePart p : children) { if (p instanceof Roof) { continue; // make an exception of roof (it is a child of a wall) } copy.add(p); } if (copy.isEmpty()) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no element to remove from " + s + ".", "No Element", JOptionPane.INFORMATION_MESSAGE); return; } if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + copy.size() + " elements of " + s + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) { return; } final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(copy); for (final HousePart p : copy) { remove(p, false); } redrawAll(); SceneManager.getInstance().getUndoManager().addEdit(c); edited = true; } public void lockAll(final boolean freeze) { if (parts.isEmpty()) { return; } int lockCount = 0; for (final HousePart part : parts) { if (part.isFrozen()) { lockCount++; } } if (!freeze) { if (lockCount > 0) { if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "<html>A lock prevents a component from being edited.<br>Do you really want to remove all the existing " + lockCount + " locks?</html>", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) { return; } } else { JOptionPane.showMessageDialog(MainFrame.getInstance(), "<html>A lock prevents a component from being edited.<br>There is no lock to remove.</html>"); return; } } SceneManager.getInstance().getUndoManager().addEdit(new LockAllCommand()); for (final HousePart part : parts) { part.setFreeze(freeze); } if (freeze) { SceneManager.getInstance().hideAllEditPoints(); } redrawAll(); edited = true; } public static boolean isRedrawAll() { return redrawAll; } public boolean areAnnotationsVisible() { return isAnnotationsVisible; } public ReadOnlyVector3 getCameraLocation() { return cameraLocation; } public void setCameraLocation(final ReadOnlyVector3 cameraLocation) { this.cameraLocation = cameraLocation; } public ReadOnlyVector3 getCameraDirection() { return cameraDirection; } public void setCameraDirection(final ReadOnlyVector3 cameraDirection) { this.cameraDirection = cameraDirection; } public void removeAllGables() { for (final HousePart part : parts) { if (part instanceof Roof) { ((Roof) part).removeAllGables(); } } } public ReadOnlyColorRGBA getLandColor() { return landColor; } public void setLandColor(final ReadOnlyColorRGBA c) { landColor = c; SceneManager.getInstance().getLand().setDefaultColor(landColor); } /** get the default color for foundations */ public ReadOnlyColorRGBA getFoundationColor() { if (foundationColor == null) { return WHITE; } return foundationColor; } /** set the default color for foundations */ public void setFoundationColor(final ReadOnlyColorRGBA foundationColor) { this.foundationColor = foundationColor; } /** get the default color for walls */ public ReadOnlyColorRGBA getWallColor() { if (wallColor == null) { return GRAY; } return wallColor; } /** set the default color for walls */ public void setWallColor(final ReadOnlyColorRGBA wallColor) { this.wallColor = wallColor; } /** get the default color for doors */ public ReadOnlyColorRGBA getDoorColor() { if (doorColor == null) { return WHITE; } return doorColor; } /** set the default color for doors */ public void setDoorColor(final ReadOnlyColorRGBA doorColor) { this.doorColor = doorColor; } /** get the default color for floors */ public ReadOnlyColorRGBA getFloorColor() { if (floorColor == null) { return WHITE; } return floorColor; } /** set the default color for floors */ public void setFloorColor(final ReadOnlyColorRGBA floorColor) { this.floorColor = floorColor; } /** get the default color for roofs */ public ReadOnlyColorRGBA getRoofColor() { if (roofColor == null) { return WHITE; } return roofColor; } /** set the default color for roofs */ public void setRoofColor(final ReadOnlyColorRGBA roofColor) { this.roofColor = roofColor; } public void setWindowColorInContainer(final HousePart container, final ColorRGBA c, final boolean shutter) { for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { final Window w = (Window) p; if (shutter) { w.setShutterColor(c); } else { w.setColor(c); } w.draw(); } } } public void setShutterLengthInContainer(final HousePart container, final double length) { for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { final Window w = (Window) p; w.setShutterLength(length); w.draw(); } } } public void setWindowSizeInContainer(final HousePart container, final double width, final double height) { for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { final Window w = (Window) p; w.setWindowWidth(width); w.setWindowHeight(height); w.draw(); w.getContainer().draw(); } } } public void setShutterColorOfBuilding(final HousePart part, final ReadOnlyColorRGBA color) { if (part instanceof Foundation) { return; } for (final HousePart p : parts) { if (p instanceof Window && p.getTopContainer() == part.getTopContainer()) { final Window w = (Window) p; w.setShutterColor(color); w.draw(); } } } public void setShutterLengthOfBuilding(final HousePart part, final double length) { if (part instanceof Foundation) { return; } for (final HousePart p : parts) { if (p instanceof Window && p.getTopContainer() == part.getTopContainer()) { final Window w = (Window) p; w.setShutterLength(length); w.draw(); } } } public void setPartColorOfBuilding(final HousePart part, final ReadOnlyColorRGBA color) { if (part instanceof Foundation) { part.setColor(color); } else { for (final HousePart p : parts) { if (p.getTopContainer() == part.getTopContainer() && p.getClass().equals(part.getClass())) { p.setColor(color); } } } } public void setColorOfAllPartsOfSameType(final HousePart part, final ReadOnlyColorRGBA color) { for (final HousePart p : parts) { if (p.getClass().equals(part.getClass())) { p.setColor(color); } } } public List<HousePart> getPartsOfSameTypeInBuilding(final HousePart x) { final List<HousePart> list = new ArrayList<HousePart>(); if (x instanceof Foundation) { list.add(x); } else { for (final HousePart p : parts) { if (p.getClass().equals(x.getClass()) && p.getTopContainer() == x.getTopContainer()) { list.add(p); } } } return list; } public List<HousePart> getAllPartsOfSameType(final HousePart x) { final List<HousePart> list = new ArrayList<HousePart>(); for (final HousePart p : parts) { if (p.getClass().equals(x.getClass())) { list.add(p); } } return list; } public void setUValuesOfSameTypeInBuilding(final HousePart x, final double uValue) { if (x instanceof Thermalizable) { if (x instanceof Foundation) { ((Foundation) x).setUValue(uValue); } else { for (final HousePart p : parts) { if (p.getClass().equals(x.getClass()) && p.getTopContainer() == x.getTopContainer()) { ((Thermalizable) p).setUValue(uValue); } } } } } public List<Window> getWindowsOnContainer(final HousePart container) { final List<Window> list = new ArrayList<Window>(); for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { list.add((Window) p); } } return list; } public void setWindowShgcInContainer(final HousePart container, final double shgc) { for (final HousePart p : parts) { if (p instanceof Window && p.getContainer() == container) { ((Window) p).setSolarHeatGainCoefficient(shgc); } } } public List<Window> getWindowsOfBuilding(final Foundation foundation) { final List<Window> list = new ArrayList<Window>(); for (final HousePart p : parts) { if (p instanceof Window && p.getTopContainer() == foundation) { list.add((Window) p); } } return list; } public void setWindowShgcOfBuilding(final Foundation foundation, final double shgc) { for (final HousePart p : parts) { if (p instanceof Window && p.getTopContainer() == foundation) { ((Window) p).setSolarHeatGainCoefficient(shgc); } } } public List<SolarPanel> getAllSolarPanels() { final List<SolarPanel> list = new ArrayList<SolarPanel>(); for (final HousePart p : parts) { if (p instanceof SolarPanel) { list.add((SolarPanel) p); } } return list; } public void setCellNumbersForAllSolarPanels(final int nx, final int ny) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { final SolarPanel s = (SolarPanel) p; s.setNumberOfCellsInX(nx); s.setNumberOfCellsInY(ny); s.draw(); } } SceneManager.getInstance().refresh(); } public void setTiltAngleForAllSolarPanels(final double angle) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setTiltAngle(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setAzimuthForAllSolarPanels(final double angle) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setRelativeAzimuth(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setBaseHeightForAllSolarPanels(final double baseHeight) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setBaseHeight(baseHeight); p.draw(); } } SceneManager.getInstance().refresh(); } public void setTrackerForAllSolarPanels(final int tracker) { for (final HousePart p : parts) { if (p instanceof SolarPanel && !(p.getContainer() instanceof Rack)) { // no tracker for solar panels on racks as they use rack trackers ((SolarPanel) p).setTracker(tracker); p.draw(); } } SceneManager.getInstance().refresh(); } public void setColorOptionForAllSolarPanels(final int colorOption) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setColorOption(colorOption); p.draw(); } } SceneManager.getInstance().refresh(); } public void setShadeToleranceForAllSolarPanels(final int cellWiring) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setShadeTolerance(cellWiring); } } } public void setSolarCellEfficiencyForAll(final double eff) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setCellEfficiency(eff); } } } public void setTemperatureCoefficientPmaxForAll(final double tcPmax) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setTemperatureCoefficientPmax(tcPmax); } } } public void setSolarPanelInverterEfficiencyForAll(final double eff) { for (final HousePart p : parts) { if (p instanceof SolarPanel) { ((SolarPanel) p).setInverterEfficiency(eff); } } } public List<Rack> getAllRacks() { final List<Rack> list = new ArrayList<Rack>(); for (final HousePart p : parts) { if (p instanceof Rack) { list.add((Rack) p); } } return list; } public void setTiltAngleForAllRacks(final double angle) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setTiltAngle(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setAzimuthForAllRacks(final double angle) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setRelativeAzimuth(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setBaseHeightForAllRacks(final double baseHeight) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setBaseHeight(baseHeight); p.draw(); } } SceneManager.getInstance().refresh(); } public void setSizeForAllRacks(final double width, final double height) { for (final HousePart p : parts) { if (p instanceof Rack) { final Rack rack = (Rack) p; rack.setRackWidth(width); rack.setRackHeight(height); rack.ensureFullSolarPanels(false); rack.draw(); } } SceneManager.getInstance().refresh(); } public void setSolarPanelSizeForAllRacks(final double width, final double height) { for (final HousePart p : parts) { if (p instanceof Rack) { final Rack rack = (Rack) p; rack.getSolarPanel().setPanelWidth(width); rack.getSolarPanel().setPanelHeight(height); rack.ensureFullSolarPanels(false); rack.draw(); } } SceneManager.getInstance().refresh(); } public void setSolarPanelColorForAllRacks(final int colorOption) { for (final HousePart p : parts) { if (p instanceof Rack) { final Rack rack = (Rack) p; rack.getSolarPanel().setColorOption(colorOption); rack.draw(); } } SceneManager.getInstance().refresh(); } public void setSolarPanelShadeToleranceForAllRacks(final int tolerance) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).getSolarPanel().setShadeTolerance(tolerance); } } } public void setSolarCellEfficiencyForAllRacks(final double eff) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).getSolarPanel().setCellEfficiency(eff); } } } public void setInverterEfficiencyForAllRacks(final double eff) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).getSolarPanel().setInverterEfficiency(eff); } } } public void setTemperatureCoefficientPmaxForAllRacks(final double pmax) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).getSolarPanel().setTemperatureCoefficientPmax(pmax); } } } public void rotateSolarPanelsOnAllRacks(final boolean rotated) { for (final HousePart p : parts) { if (p instanceof Rack) { final Rack rack = (Rack) p; rack.getSolarPanel().setRotated(rotated); rack.ensureFullSolarPanels(false); rack.draw(); } } SceneManager.getInstance().refresh(); } public void setPoleSpacingForAllRacks(final double dx, final double dy) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setPoleDistanceX(dx); ((Rack) p).setPoleDistanceY(dy); p.draw(); } } SceneManager.getInstance().refresh(); } public void setTrackerForAllRacks(final int tracker) { for (final HousePart p : parts) { if (p instanceof Rack) { ((Rack) p).setTracker(tracker); p.draw(); } } SceneManager.getInstance().refresh(); } public List<Mirror> getAllMirrors() { final List<Mirror> list = new ArrayList<Mirror>(); for (final HousePart p : parts) { if (p instanceof Mirror) { list.add((Mirror) p); } } return list; } public void setTiltAngleForAllMirrors(final double angle) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setTiltAngle(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setAzimuthForAllMirrors(final double angle) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setRelativeAzimuth(angle); p.draw(); } } SceneManager.getInstance().refresh(); } public void setReflectivityForAllMirrors(final double reflectivity) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setReflectivity(reflectivity); } } } public void setTargetForAllMirrors(final Foundation target) { final List<Foundation> oldTargets = new ArrayList<Foundation>(); for (final HousePart p : parts) { if (p instanceof Mirror) { final Mirror m = (Mirror) p; final Foundation t = m.getHeliostatTarget(); if (t != null && !oldTargets.contains(t)) { oldTargets.add(t); } m.setHeliostatTarget(target); p.draw(); } } if (target != null) { target.drawSolarReceiver(); } if (!oldTargets.isEmpty()) { for (final Foundation t : oldTargets) { t.drawSolarReceiver(); } } SceneManager.getInstance().refresh(); } public void setBaseHeightForAllMirrors(final double baseHeight) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setBaseHeight(baseHeight); p.draw(); } } SceneManager.getInstance().refresh(); } public void setSizeForAllMirrors(final double width, final double height) { for (final HousePart p : parts) { if (p instanceof Mirror) { ((Mirror) p).setMirrorWidth(width); ((Mirror) p).setMirrorHeight(height); p.draw(); } } SceneManager.getInstance().refresh(); } public void setThicknessForAllWalls(final double thickness) { for (final HousePart p : parts) { if (p instanceof Wall) { ((Wall) p).setThickness(thickness); p.draw(); } } SceneManager.getInstance().refresh(); } public void setHeightOfConnectedWalls(final Wall w, final double height) { w.visitNeighbors(new WallVisitor() { @Override public void visit(final Wall currentWall, final Snap prev, final Snap next) { currentWall.setHeight(height, true); currentWall.draw(); } }); SceneManager.getInstance().refresh(); } public void setHeightForAllWalls(final double height) { for (final HousePart p : parts) { if (p instanceof Wall) { ((Wall) p).setHeight(height, true); p.draw(); } } SceneManager.getInstance().refresh(); } public void setColorOfConnectedWalls(final Wall w, final ColorRGBA color) { w.visitNeighbors(new WallVisitor() { @Override public void visit(final Wall currentWall, final Snap prev, final Snap next) { currentWall.setColor(color); currentWall.draw(); } }); SceneManager.getInstance().refresh(); } public boolean isEdited() { return edited; } public void setEdited(final boolean edited) { setEdited(edited, true); } public void setEdited(final boolean edited, final boolean recomputeEnergy) { if (edited) { SnapshotLogger.getInstance().setSceneEdited(true); } this.edited = edited; MainFrame.getInstance().updateTitleBar(); } public void updateEditShapes() { for (final HousePart part : parts) { part.updateEditShapes(); } } public long nextID() { return ++idCounter; } public boolean hasSensor() { for (final HousePart housePart : parts) { if (housePart instanceof Sensor) { return true; } } return false; } public void setProjectName(final String projectName) { this.projectName = projectName; } public String getProjectName() { return projectName; } public void setStudentMode(final boolean b) { studentMode = b; } public boolean isStudentMode() { return studentMode; } public void setCity(final String city) { this.city = city; } public String getCity() { return city; } public void setDate(final Date date) { if (calendar != null) { calendar.setTime(date); } } public Date getDate() { if (calendar != null) { return calendar.getTime(); } return Heliodon.getInstance().getCalendar().getTime(); } public void setHeatVectorLength(final double heatVectorLength) { this.heatVectorLength = heatVectorLength; } public double getHeatVectorLength() { return heatVectorLength; } public void setHeatFluxGridSize(final double heatFluxGridSize) { this.heatFluxGridSize = heatFluxGridSize; } public double getHeatVectorGridSize() { return heatFluxGridSize; } public boolean getAlwaysComputeHeatFluxVectors() { return alwaysComputeHeatFluxVectors; } public void setAlwaysComputeHeatFluxVectors(final boolean alwaysComputeHeatFluxVectors) { this.alwaysComputeHeatFluxVectors = alwaysComputeHeatFluxVectors; for (final HousePart part : Scene.getInstance().getParts()) { part.updateHeatFluxVisibility(); } } public boolean getOnlyAbsorptionInSolarMap() { return !fullEnergyInSolarMap; } public void setOnlyAbsorptionInSolarMap(final boolean onlyAbsorptionInSolarMap) { fullEnergyInSolarMap = !onlyAbsorptionInSolarMap; } public boolean getOnlyReflectedEnergyInMirrorSolarMap() { return onlyReflectedEnergyInMirrorSolarMap; } public void setOnlyReflectedEnergyInMirrorSolarMap(final boolean onlyReflectedEnergyInMirrorSolarMap) { this.onlyReflectedEnergyInMirrorSolarMap = onlyReflectedEnergyInMirrorSolarMap; } public void setSolarMapForLand(final boolean showSolarMapForLand) { noSolarMapForLand = !showSolarMapForLand; } public boolean getSolarMapForLand() { return !noSolarMapForLand; } public void setDisallowFoundationOverlap(final boolean disallowFoundationOverlap) { this.disallowFoundationOverlap = disallowFoundationOverlap; } public boolean getDisallowFoundationOverlap() { return disallowFoundationOverlap; } public void setSolarHeatMapColorContrast(final int solarContrast) { this.solarContrast = solarContrast; } public int getSolarHeatMapColorContrast() { return solarContrast; } public int countParts(final Class<?>[] clazz) { int count = 0; for (final HousePart p : parts) { for (final Class<?> c : clazz) { if (c.isInstance(p)) { count++; } } } return count; } public int getNumberOfSolarPanels() { int count = 0; for (final HousePart p : parts) { if (p instanceof SolarPanel) { count++; } else if (p instanceof Rack) { count += ((Rack) p).getNumberOfSolarPanels(); } } return count; } // XIE: This needs to be called for trees to change texture when the month changes public void setTreeLeaves() { SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { for (final HousePart p : parts) { if (p instanceof Tree) { p.updateTextureAndColor(); } } return null; } }); } public void updateTrackables() { SceneManager.getTaskManager().update(new Callable<Object>() { @Override public Object call() throws Exception { final boolean night = Heliodon.getInstance().isNightTime(); for (final HousePart part : parts) { if (part instanceof Trackable) { if (part instanceof Mirror) { final Mirror mirror = (Mirror) part; if (night) { mirror.drawLightBeams(); // call this so that the light beams can be set invisible } else { mirror.draw(); } } else if (part instanceof SolarPanel) { final SolarPanel panel = (SolarPanel) part; if (night) { panel.drawSunBeam(); // call this so that the sun beam can be set invisible } else { panel.draw(); } } else if (part instanceof Rack) { final Rack rack = (Rack) part; if (night) { rack.drawSunBeam(); // call this so that the sun beam can be set invisible } else { rack.draw(); } } } } return null; } }); } public Ground getGround() { return ground; } public Atmosphere getAtmosphere() { return atmosphere; } public DesignSpecs getDesignSpecs() { return designSpecs; } public void setDashedLinesOnRoofShown(final boolean dashedLineOnRoofs) { this.dashedlineOnRoofs = dashedLineOnRoofs; } public boolean areDashedLinesOnRoofShown() { return dashedlineOnRoofs; } public void setOnlySolarAnalysis(final boolean onlySolarAnalysis) { this.onlySolarAnalysis = onlySolarAnalysis; } public boolean getOnlySolarAnalysis() { return onlySolarAnalysis; } public void setUtilityBill(final UtilityBill utilityBill) { this.utilityBill = utilityBill; } public UtilityBill getUtilityBill() { return utilityBill; } public void setTheme(final int theme) { this.theme = theme; ReadOnlyColorRGBA c; switch (theme) { case DESERT_THEME: c = new ColorRGBA(1, 1, 1, 0.5f); break; case GRASSLAND_THEME: c = new ColorRGBA(0, 1, 0, 0.5f); break; case FOREST_THEME: c = new ColorRGBA(0, 1, 0.2f, 0.5f); break; default: c = new ColorRGBA(0, 1, 0, 0.5f); } setLandColor(c); SceneManager.getInstance().changeSkyTexture(); } public int getTheme() { return theme; } public void setLightBeamsVisible(final boolean showLightBeams) { hideLightBeams = !showLightBeams; } public boolean areLightBeamsVisible() { return !hideLightBeams; } public void setSunAnglesVisible(final boolean showSunAngles) { this.showSunAngles = showSunAngles; } public boolean areSunAnglesVisible() { return showSunAngles; } public void setSolarPanelNx(final int solarPanelNx) { this.solarPanelNx = solarPanelNx; } public int getSolarPanelNx() { return solarPanelNx; } public void setSolarPanelNy(final int solarPanelNy) { this.solarPanelNy = solarPanelNy; } public int getSolarPanelNy() { return solarPanelNy; } public void setRackNx(final int rackNx) { this.rackNx = rackNx; } public int getRackNx() { return rackNx; } public void setRackNy(final int rackNy) { this.rackNy = rackNy; } public int getRackNy() { return rackNy; } public void setRackCellSize(final double rackCellSize) { this.rackCellSize = rackCellSize; } public double getRackCellSize() { return rackCellSize; } public void setMirrorNx(final int mirrorNx) { this.mirrorNx = mirrorNx; } public int getMirrorNx() { return mirrorNx; } public void setMirrorNy(final int mirrorNy) { this.mirrorNy = mirrorNy; } public int getMirrorNy() { return mirrorNy; } public void setSolarStep(final double solarStep) { this.solarStep = solarStep; } public double getSolarStep() { return solarStep; } public void setTimeStep(final int timeStep) { this.timeStep = timeStep; } public int getTimeStep() { return timeStep; } public void setGroundImage(final BufferedImage groundImage, final double groundImageScale) { this.groundImage = groundImage; this.groundImageScale = groundImageScale; applyGroundImage(); } public void setGroundImageScale(final double groundImageScale) { if (isGroundImageEnabled()) { this.groundImageScale = groundImageScale; applyGroundImage(); } } public double getGroundImageScale() { return groundImageScale; } public boolean isGroundImageEnabled() { return groundImage != null; } private void applyGroundImage() { final Mesh mesh = SceneManager.getInstance().getGroundImageLand(); if (groundImage == null) { mesh.setRenderState(new TextureState()); // set a dummy texture in case the mesh holds the original buffered image and causes memory leak mesh.setVisible(false); setFoundationsVisible(true); } else { SceneManager.getInstance().resizeGroundImageLand(groundImageScale); final Texture2D texture = new Texture2D(); texture.setTextureKey(TextureKey.getRTTKey(MinificationFilter.NearestNeighborNoMipMaps)); texture.setImage(AWTImageLoader.makeArdor3dImage(groundImage, true)); final TextureState textureState = new TextureState(); textureState.setTexture(texture); mesh.setRenderState(textureState); mesh.setVisible(!hideGroundImage); setFoundationsVisible(false); } } public void setGroundImageEarthView(final boolean groundImageIsEarthView) { this.groundImageIsEarthView = groundImageIsEarthView; } public boolean isGroundImageEarthView() { return groundImageIsEarthView; } private void setFoundationsVisible(final boolean visible) { for (final HousePart part : Scene.getInstance().getParts()) { if (part instanceof Foundation) { part.getMesh().setVisible(visible); } } SceneManager.getInstance().refresh(); } public void setShowGroundImage(final boolean showGroundImage) { hideGroundImage = !showGroundImage; } public boolean getShowGroundImage() { return !hideGroundImage; } public void setGroundImageLightColored(final boolean groundImageLightColored) { this.groundImageLightColored = groundImageLightColored; } public boolean isGroundImageLightColored() { return groundImageLightColored; } /** used by SnapshotLogger */ private void storeGroundImageData() { avoidSavingGroundImage = true; } /** used by SnapshotLogger */ private void restoreGroundImageData() { avoidSavingGroundImage = false; } private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); if (groundImage != null && !avoidSavingGroundImage) { ImageIO.write(groundImage, "jpg", out); } } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); groundImage = ImageIO.read(in); } public static boolean isSaving() { return isSaving; } public List<Foundation> getFoundationGroup(final Foundation master) { groupFoundations(); for (final List<Foundation> g : foundationGroups) { if (g.contains(master)) { return g; } } return null; } /* put overlapping foundations into separate groups */ private void groupFoundations() { if (foundationGroups == null) { foundationGroups = new ArrayList<List<Foundation>>(); } else { foundationGroups.clear(); } final List<Foundation> foundations = new ArrayList<Foundation>(); for (final HousePart p : parts) { if (p instanceof Foundation) { foundations.add((Foundation) p); } } final int n = foundations.size(); if (n > 1) { int count = 0; final List<Pair> pairs = new ArrayList<Pair>(); for (int i = 0; i < n - 1; i++) { final Foundation fi = foundations.get(i); for (int j = i + 1; j < n; j++) { final Foundation fj = foundations.get(j); if (fi.overlap(fj)) { final Pair p = new Pair(i, j); if (!pairs.contains(p)) { pairs.add(p); } } } } int m = pairs.size(); while (m > 0) { Pair p = pairs.get(0); final List<Integer> list = new ArrayList<Integer>(); list.add(p.i()); list.add(p.j()); pairs.remove(p); m = pairs.size(); if (m > 0) { final List<Pair> toRemove = new ArrayList<Pair>(); for (int x = 0; x < m; x++) { p = pairs.get(x); final int i = p.i(); final int j = p.j(); if (list.contains(i) && list.contains(j)) { if (!toRemove.contains(p)) { toRemove.add(p); } } else if (!list.contains(i) && list.contains(j)) { list.add(i); if (!toRemove.contains(p)) { toRemove.add(p); } } else if (!list.contains(j) && list.contains(i)) { list.add(j); if (!toRemove.contains(p)) { toRemove.add(p); } } } if (!toRemove.isEmpty()) { pairs.removeAll(toRemove); } } final List<Foundation> group = new ArrayList<Foundation>(); for (final Integer a : list) { group.add(foundations.get(a)); } foundationGroups.add(group); count += group.size(); m = pairs.size(); } if (count < foundations.size()) { for (final Foundation f : foundations) { boolean linked = false; for (final List<Foundation> g : foundationGroups) { if (g.contains(f)) { linked = true; break; } } if (!linked) { final List<Foundation> g = new ArrayList<Foundation>(); g.add(f); foundationGroups.add(g); } } } // System.out.println("###" + foundationGroups.size() + "," + (foundations.size() - count)); } else { foundationGroups.add(foundations); } } public void setInstructionSheetText(final int i, final String text) { if (instructionSheetText == null) { instructionSheetText = new String[3]; } if (i < instructionSheetText.length) { instructionSheetText[i] = text; } } public String getInstructionSheetText(final int i) { if (instructionSheetText == null) { return null; } if (i >= instructionSheetText.length) { return null; } return instructionSheetText[i]; } public void setInstructionSheetTextType(final int i, final String type) { if (instructionSheetTextType == null) { instructionSheetTextType = new String[3]; } if (i < instructionSheetTextType.length) { instructionSheetTextType[i] = type; } } public String getInstructionSheetTextType(final int i) { if (instructionSheetTextType == null) { return null; } if (i >= instructionSheetTextType.length) { return null; } return instructionSheetTextType[i]; } }
solar rack on imported structure
src/main/java/org/concord/energy3d/scene/Scene.java
solar rack on imported structure
Java
mit
ae03df178f3b95824e55ae2a9a2351a8aa1e1fef
0
tobiasdiez/jabref,oscargus/jabref,grimes2/jabref,mredaelli/jabref,Braunch/jabref,bartsch-dev/jabref,sauliusg/jabref,mairdl/jabref,JabRef/jabref,zellerdev/jabref,sauliusg/jabref,ayanai1/jabref,ayanai1/jabref,ayanai1/jabref,oscargus/jabref,mredaelli/jabref,bartsch-dev/jabref,shitikanth/jabref,shitikanth/jabref,JabRef/jabref,Siedlerchr/jabref,Mr-DLib/jabref,obraliar/jabref,Mr-DLib/jabref,obraliar/jabref,mairdl/jabref,Mr-DLib/jabref,motokito/jabref,mredaelli/jabref,tschechlovdev/jabref,zellerdev/jabref,mairdl/jabref,Braunch/jabref,tobiasdiez/jabref,mredaelli/jabref,shitikanth/jabref,shitikanth/jabref,Mr-DLib/jabref,obraliar/jabref,motokito/jabref,mredaelli/jabref,motokito/jabref,obraliar/jabref,shitikanth/jabref,oscargus/jabref,bartsch-dev/jabref,bartsch-dev/jabref,tschechlovdev/jabref,zellerdev/jabref,obraliar/jabref,grimes2/jabref,sauliusg/jabref,Mr-DLib/jabref,grimes2/jabref,Siedlerchr/jabref,jhshinn/jabref,tschechlovdev/jabref,mairdl/jabref,zellerdev/jabref,jhshinn/jabref,tschechlovdev/jabref,Siedlerchr/jabref,grimes2/jabref,jhshinn/jabref,motokito/jabref,Braunch/jabref,JabRef/jabref,ayanai1/jabref,bartsch-dev/jabref,jhshinn/jabref,motokito/jabref,mairdl/jabref,tobiasdiez/jabref,Siedlerchr/jabref,JabRef/jabref,Braunch/jabref,oscargus/jabref,zellerdev/jabref,tschechlovdev/jabref,jhshinn/jabref,grimes2/jabref,Braunch/jabref,oscargus/jabref,tobiasdiez/jabref,sauliusg/jabref,ayanai1/jabref
/* Copyright (C) 2003 Nizar N. Batada, Morten O. Alver All programs in this directory and subdirectories are published under the GNU General Public License as described below. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref.export; import java.util.Vector; import net.sf.jabref.BibtexFields; import net.sf.jabref.GUIGlobals; import net.sf.jabref.Globals; import net.sf.jabref.Util; public class LatexFieldFormatter implements FieldFormatter { StringBuffer sb; int col; // First line usually starts about so much further to the right. final int STARTCOL = 4; public String format(String text, String fieldName) throws IllegalArgumentException { if (Globals.prefs.putBracesAroundCapitals(fieldName) && !Globals.BIBTEX_STRING.equals(fieldName)) { text = Util.putBracesAroundCapitals(text); } // If the field is non-standard, we will just append braces, // wrap and write. boolean resolveStrings = true; if (Globals.prefs.getBoolean("resolveStringsAllFields")) { // Resolve strings for all fields except some: String[] exceptions = Globals.prefs.getStringArray("doNotResolveStringsFor"); for (int i = 0; i < exceptions.length; i++) { if (exceptions[i].equals(fieldName)) { resolveStrings = false; break; } } } else { // Default operation - we only resolve strings for standard fields: resolveStrings = BibtexFields.isStandardField(fieldName) || Globals.BIBTEX_STRING.equals(fieldName); } if (!resolveStrings) { int brc = 0; boolean ok = true; for (int i=0; i<text.length(); i++) { char c = text.charAt(i); //Util.pr(""+c); if (c == '{') brc++; if (c == '}') brc--; if (brc < 0) { ok = false; break; } } if (brc > 0) ok = false; if (!ok) throw new IllegalArgumentException("Curly braces { and } must be balanced."); sb = new StringBuffer("{"); // No formatting at all for these fields, to allow custom formatting? //if (Globals.prefs.getBoolean("preserveFieldFormatting")) // sb.append(text); //else if (!Globals.prefs.isNonWrappableField(fieldName)) sb.append(Util.wrap2(text, GUIGlobals.LINE_LENGTH)); else sb.append(text); sb.append('}'); return sb.toString(); } sb = new StringBuffer(); int pivot = 0, pos1, pos2; col = STARTCOL; // Here we assume that the user encloses any bibtex strings in #, e.g.: // #jan# - #feb# // ...which will be written to the file like this: // jan # { - } # feb checkBraces(text); while (pivot < text.length()) { int goFrom = pivot; pos1 = pivot; while (goFrom == pos1) { pos1 = text.indexOf('#', goFrom); if ((pos1 > 0) && (text.charAt(pos1 - 1) == '\\')) { goFrom = pos1 + 1; pos1++; } else goFrom = pos1 - 1; // Ends the loop. } if (pos1 == -1) { pos1 = text.length(); // No more occurences found. pos2 = -1; } else { pos2 = text.indexOf('#', pos1 + 1); //System.out.println("pos2:"+pos2); if (pos2 == -1) { throw new IllegalArgumentException (Globals.lang("The # character is not allowed in BibTeX fields") + ".\n" + Globals.lang("In JabRef, use pairs of # characters to indicate " + "a string.") + "\n" + Globals.lang("Note that the entry causing the problem has been selected.")); } } if (pos1 > pivot) writeText(text, pivot, pos1); if ((pos1 < text.length()) && (pos2 - 1 > pos1)) // We check that the string label is not empty. That means // an occurence of ## will simply be ignored. Should it instead // cause an error message? writeStringLabel(text, pos1 + 1, pos2, (pos1 == pivot), (pos2 + 1 == text.length())); if (pos2 > -1) pivot = pos2 + 1; else pivot = pos1 + 1; //if (tell++ > 10) System.exit(0); } if (!Globals.prefs.isNonWrappableField(fieldName)) return Util.wrap2(sb.toString(), GUIGlobals.LINE_LENGTH); else return sb.toString(); } private void writeText(String text, int start_pos, int end_pos) { /*sb.append("{"); sb.append(text.substring(start_pos, end_pos)); sb.append("}");*/ sb.append('{'); boolean escape = false, inCommandName = false, inCommand = false, inCommandOption = false; int nestedEnvironments = 0; StringBuffer commandName = new StringBuffer(); char c; for (int i=start_pos; i<end_pos; i++) { c = text.charAt(i); // Track whether we are in a LaTeX command of some sort. if (Character.isLetter(c) && (escape || inCommandName)) { inCommandName = true; if (!inCommandOption) commandName.append((char)c); } else if (Character.isWhitespace(c) && (inCommand || inCommandOption)) { //System.out.println("whitespace here"); } else if (inCommandName) { // This means the command name is ended. // Perhaps the beginning of an argument: if (c == '[') { inCommandOption = true; } // Or the end of an argument: else if (inCommandOption && (c == ']')) inCommandOption = false; // Or the beginning of the command body: else if (!inCommandOption && (c == '{')) { //System.out.println("Read command: '"+commandName.toString()+"'"); inCommandName = false; inCommand = true; } // Or simply the end of this command altogether: else { //System.out.println("I think I read command: '"+commandName.toString()+"'"); commandName.delete(0, commandName.length()); inCommandName = false; } } // If we are in a command body, see if it has ended: if (inCommand && (c == '}')) { //System.out.println("nestedEnvironments = " + nestedEnvironments); //System.out.println("Done with command: '"+commandName.toString()+"'"); if (commandName.toString().equals("begin")) { nestedEnvironments++; } if (nestedEnvironments > 0 && commandName.toString().equals("end")) { nestedEnvironments--; } //System.out.println("nestedEnvironments = " + nestedEnvironments); commandName.delete(0, commandName.length()); inCommand = false; } // We add a backslash before any ampersand characters, with one exception: if // we are inside an \\url{...} command, we should write it as it is. Maybe. if ((c == '&') && !escape && !(inCommand && commandName.toString().equals("url")) && (nestedEnvironments == 0)) { sb.append("\\&"); } else sb.append(c); escape = (c == '\\'); } sb.append('}'); } private void writeStringLabel(String text, int start_pos, int end_pos, boolean first, boolean last) { //sb.append(Util.wrap2((first ? "" : " # ") + text.substring(start_pos, end_pos) // + (last ? "" : " # "), GUIGlobals.LINE_LENGTH)); putIn((first ? "" : " # ") + text.substring(start_pos, end_pos) + (last ? "" : " # ")); } private void putIn(String s) { sb.append(Util.wrap2(s, GUIGlobals.LINE_LENGTH)); } private void checkBraces(String text) throws IllegalArgumentException { Vector<Integer> left = new Vector<Integer>(5, 3), right = new Vector<Integer>(5, 3); int current = -1; // First we collect all occurences: while ((current = text.indexOf('{', current+1)) != -1) left.add(new Integer(current)); while ((current = text.indexOf('}', current+1)) != -1) right.add(new Integer(current)); // Then we throw an exception if the error criteria are met. if ((right.size() > 0) && (left.size() == 0)) throw new IllegalArgumentException ("'}' character ends string prematurely."); if ((right.size() > 0) && (((Integer)right.elementAt(0)).intValue() < ((Integer)left.elementAt(0)).intValue())) throw new IllegalArgumentException ("'}' character ends string prematurely."); if (left.size() != right.size()) throw new IllegalArgumentException ("Braces don't match."); } }
src/java/net/sf/jabref/export/LatexFieldFormatter.java
/* Copyright (C) 2003 Nizar N. Batada, Morten O. Alver All programs in this directory and subdirectories are published under the GNU General Public License as described below. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref.export; import java.util.Vector; import net.sf.jabref.BibtexFields; import net.sf.jabref.GUIGlobals; import net.sf.jabref.Globals; import net.sf.jabref.Util; public class LatexFieldFormatter implements FieldFormatter { StringBuffer sb; int col; // First line usually starts about so much further to the right. final int STARTCOL = 4; public String format(String text, String fieldName) throws IllegalArgumentException { if (Globals.prefs.putBracesAroundCapitals(fieldName) && !Globals.BIBTEX_STRING.equals(fieldName)) { text = Util.putBracesAroundCapitals(text); } // If the field is non-standard, we will just append braces, // wrap and write. boolean resolveStrings = true; if (Globals.prefs.getBoolean("resolveStringsAllFields")) { // Resolve strings for all fields except some: String[] exceptions = Globals.prefs.getStringArray("doNotResolveStringsFor"); for (int i = 0; i < exceptions.length; i++) { if (exceptions[i].equals(fieldName)) { resolveStrings = false; break; } } } else { // Default operation - we only resolve strings for standard fields: resolveStrings = BibtexFields.isStandardField(fieldName) || Globals.BIBTEX_STRING.equals(fieldName); } if (!resolveStrings) { int brc = 0; boolean ok = true; for (int i=0; i<text.length(); i++) { char c = text.charAt(i); //Util.pr(""+c); if (c == '{') brc++; if (c == '}') brc--; if (brc < 0) { ok = false; break; } } if (brc > 0) ok = false; if (!ok) throw new IllegalArgumentException("Curly braces { and } must be balanced."); sb = new StringBuffer('{'); // No formatting at all for these fields, to allow custom formatting? //if (Globals.prefs.getBoolean("preserveFieldFormatting")) // sb.append(text); //else if (!Globals.prefs.isNonWrappableField(fieldName)) sb.append(Util.wrap2(text, GUIGlobals.LINE_LENGTH)); else sb.append(text); sb.append('}'); return sb.toString(); } sb = new StringBuffer(); int pivot = 0, pos1, pos2; col = STARTCOL; // Here we assume that the user encloses any bibtex strings in #, e.g.: // #jan# - #feb# // ...which will be written to the file like this: // jan # { - } # feb checkBraces(text); while (pivot < text.length()) { int goFrom = pivot; pos1 = pivot; while (goFrom == pos1) { pos1 = text.indexOf('#', goFrom); if ((pos1 > 0) && (text.charAt(pos1 - 1) == '\\')) { goFrom = pos1 + 1; pos1++; } else goFrom = pos1 - 1; // Ends the loop. } if (pos1 == -1) { pos1 = text.length(); // No more occurences found. pos2 = -1; } else { pos2 = text.indexOf('#', pos1 + 1); //System.out.println("pos2:"+pos2); if (pos2 == -1) { throw new IllegalArgumentException (Globals.lang("The # character is not allowed in BibTeX fields") + ".\n" + Globals.lang("In JabRef, use pairs of # characters to indicate " + "a string.") + "\n" + Globals.lang("Note that the entry causing the problem has been selected.")); } } if (pos1 > pivot) writeText(text, pivot, pos1); if ((pos1 < text.length()) && (pos2 - 1 > pos1)) // We check that the string label is not empty. That means // an occurence of ## will simply be ignored. Should it instead // cause an error message? writeStringLabel(text, pos1 + 1, pos2, (pos1 == pivot), (pos2 + 1 == text.length())); if (pos2 > -1) pivot = pos2 + 1; else pivot = pos1 + 1; //if (tell++ > 10) System.exit(0); } if (!Globals.prefs.isNonWrappableField(fieldName)) return Util.wrap2(sb.toString(), GUIGlobals.LINE_LENGTH); else return sb.toString(); } private void writeText(String text, int start_pos, int end_pos) { /*sb.append("{"); sb.append(text.substring(start_pos, end_pos)); sb.append("}");*/ sb.append('{'); boolean escape = false, inCommandName = false, inCommand = false, inCommandOption = false; int nestedEnvironments = 0; StringBuffer commandName = new StringBuffer(); char c; for (int i=start_pos; i<end_pos; i++) { c = text.charAt(i); // Track whether we are in a LaTeX command of some sort. if (Character.isLetter(c) && (escape || inCommandName)) { inCommandName = true; if (!inCommandOption) commandName.append((char)c); } else if (Character.isWhitespace(c) && (inCommand || inCommandOption)) { //System.out.println("whitespace here"); } else if (inCommandName) { // This means the command name is ended. // Perhaps the beginning of an argument: if (c == '[') { inCommandOption = true; } // Or the end of an argument: else if (inCommandOption && (c == ']')) inCommandOption = false; // Or the beginning of the command body: else if (!inCommandOption && (c == '{')) { //System.out.println("Read command: '"+commandName.toString()+"'"); inCommandName = false; inCommand = true; } // Or simply the end of this command altogether: else { //System.out.println("I think I read command: '"+commandName.toString()+"'"); commandName.delete(0, commandName.length()); inCommandName = false; } } // If we are in a command body, see if it has ended: if (inCommand && (c == '}')) { //System.out.println("nestedEnvironments = " + nestedEnvironments); //System.out.println("Done with command: '"+commandName.toString()+"'"); if (commandName.toString().equals("begin")) { nestedEnvironments++; } if (nestedEnvironments > 0 && commandName.toString().equals("end")) { nestedEnvironments--; } //System.out.println("nestedEnvironments = " + nestedEnvironments); commandName.delete(0, commandName.length()); inCommand = false; } // We add a backslash before any ampersand characters, with one exception: if // we are inside an \\url{...} command, we should write it as it is. Maybe. if ((c == '&') && !escape && !(inCommand && commandName.toString().equals("url")) && (nestedEnvironments == 0)) { sb.append("\\&"); } else sb.append(c); escape = (c == '\\'); } sb.append('}'); } private void writeStringLabel(String text, int start_pos, int end_pos, boolean first, boolean last) { //sb.append(Util.wrap2((first ? "" : " # ") + text.substring(start_pos, end_pos) // + (last ? "" : " # "), GUIGlobals.LINE_LENGTH)); putIn((first ? "" : " # ") + text.substring(start_pos, end_pos) + (last ? "" : " # ")); } private void putIn(String s) { sb.append(Util.wrap2(s, GUIGlobals.LINE_LENGTH)); } private void checkBraces(String text) throws IllegalArgumentException { Vector<Integer> left = new Vector<Integer>(5, 3), right = new Vector<Integer>(5, 3); int current = -1; // First we collect all occurences: while ((current = text.indexOf('{', current+1)) != -1) left.add(new Integer(current)); while ((current = text.indexOf('}', current+1)) != -1) right.add(new Integer(current)); // Then we throw an exception if the error criteria are met. if ((right.size() > 0) && (left.size() == 0)) throw new IllegalArgumentException ("'}' character ends string prematurely."); if ((right.size() > 0) && (((Integer)right.elementAt(0)).intValue() < ((Integer)left.elementAt(0)).intValue())) throw new IllegalArgumentException ("'}' character ends string prematurely."); if (left.size() != right.size()) throw new IllegalArgumentException ("Braces don't match."); } }
Fixed bug with '{' parameter in StringBuffer which was taken to be a int.
src/java/net/sf/jabref/export/LatexFieldFormatter.java
Fixed bug with '{' parameter in StringBuffer which was taken to be a int.
Java
cc0-1.0
0febd55bd4ffb189eaf3dfef9356bd50b1ba809b
0
HogeschoolLeiden/website,HogeschoolLeiden/website,HogeschoolLeiden/website,HogeschoolLeiden/website
package nl.hsleiden.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.onehippo.cms7.eforms.hst.beans.FormBean; import com.onehippo.cms7.eforms.hst.model.AbstractField; import com.onehippo.cms7.eforms.hst.model.Form; public class ITextPdfForm { private static final Logger LOG = LoggerFactory.getLogger(ITextPdfForm.class); public InputStream createFormPdf(FormBean formBean, Form form, String introText) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { Document doc = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter.getInstance(doc, baos); doc.open(); addTitle(formBean, doc); doc.add(Chunk.NEWLINE); addIntroduction(formBean, introText, doc); doc.add(Chunk.NEWLINE); addFormData(form, doc); doc.add(Chunk.NEWLINE); doc.close(); } catch (DocumentException e) { LOG.error("exception creating pdf out of form data", e); } return new ByteArrayInputStream(baos.toByteArray()); } private void addFormData(Form form, Document doc) throws DocumentException { List<AbstractField> fields = form.getFields(); PdfPTable tbl = new PdfPTable(2); for (AbstractField abstractField : fields) { if (abstractField.isMultiple()) { if ("radiogroup".equalsIgnoreCase(abstractField.getType())) { addSingleValueFields(tbl, abstractField); } else { addMultivalueFields(tbl, abstractField); } } else { addSingleValueFields(tbl, abstractField); } } doc.add(tbl); } private void addMultivalueFields(PdfPTable tbl, AbstractField abstractField) { Map<String, Collection<String>> multiValues = abstractField.getMultiValues(); for (Entry<String, Collection<String>> multivaluesEntry : multiValues.entrySet()) { if (multivaluesEntry.getValue().toString() != null && !multivaluesEntry.getValue().isEmpty() && !multivaluesEntry.getValue().toString().isEmpty()) { addTableCell(tbl, multivaluesEntry.getKey()); addTableCell(tbl, multivaluesEntry.getValue().toString()); } } } private void addSingleValueFields(PdfPTable tbl, AbstractField abstractField) { if (abstractField != null && abstractField.getValue() != null && !abstractField.getValue().isEmpty()) { addTableCell(tbl, abstractField.getName()); addTableCell(tbl, abstractField.getValue()); } } private void addTableCell(PdfPTable tbl, String content) { PdfPCell cell = new PdfPCell(new Phrase(content)); cell.disableBorderSide(Rectangle.BOX); tbl.addCell(cell); } private void addIntroduction(FormBean formBean, String introText, Document doc) throws DocumentException { if (introText != null && !introText.isEmpty()) { doc.add(new Paragraph(introText)); } } private void addTitle(FormBean formBean, Document doc) throws DocumentException { String formName = formBean.getFormName(); if (formName != null && !formName.isEmpty()) { Font font = new Font(FontFamily.HELVETICA, 20, Font.BOLD, BaseColor.BLACK); Phrase titlePhrase = new Phrase(formBean.getFormName(), font); doc.add(titlePhrase); doc.add(Chunk.NEWLINE); } } }
site/src/main/java/nl/hsleiden/utils/ITextPdfForm.java
package nl.hsleiden.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.onehippo.cms7.eforms.hst.beans.FormBean; import com.onehippo.cms7.eforms.hst.model.AbstractField; import com.onehippo.cms7.eforms.hst.model.Form; public class ITextPdfForm { private static final Logger LOG = LoggerFactory.getLogger(ITextPdfForm.class); public InputStream createFormPdf(FormBean formBean, Form form, String introText) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { Document doc = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter.getInstance(doc, baos); doc.open(); addTitle(formBean, doc); doc.add(Chunk.NEWLINE); addIntroduction(formBean, introText, doc); doc.add(Chunk.NEWLINE); addFormData(form, doc); doc.add(Chunk.NEWLINE); doc.close(); } catch (DocumentException e) { LOG.error("exception creating pdf out of form data", e); } return new ByteArrayInputStream(baos.toByteArray()); } private void addFormData(Form form, Document doc) throws DocumentException { List<AbstractField> fields = form.getFields(); PdfPTable tbl = new PdfPTable(2); for (AbstractField abstractField : fields) { if (abstractField.isMultiple()) { addMultivalueFields(tbl, abstractField); } else { addSingleValueFields(tbl, abstractField); } } doc.add(tbl); } private void addSingleValueFields(PdfPTable tbl, AbstractField abstractField) { if (abstractField != null && abstractField.getValue() != null && !abstractField.getValue().isEmpty()) { addTableCell(tbl, abstractField.getName()); addTableCell(tbl, abstractField.getValue()); } } private void addMultivalueFields(PdfPTable tbl, AbstractField abstractField) { Map<String, Collection<String>> multiValues = abstractField.getMultiValues(); for (Entry<String, Collection<String>> multivaluesEntry : multiValues.entrySet()) { if (multivaluesEntry.getValue().toString() != null && !multivaluesEntry.getValue().isEmpty() && isRadioValueNotEmpty(abstractField)) { addTableCell(tbl, multivaluesEntry.getKey()); addTableCell(tbl, multivaluesEntry.getValue().toString()); } } } private boolean isRadioValueNotEmpty(AbstractField abstractField) { return "radiogroup".equalsIgnoreCase(abstractField.getType()) && abstractField.getValue() != null && !abstractField.getValue().isEmpty(); } private void addTableCell(PdfPTable tbl, String content) { PdfPCell cell = new PdfPCell(new Phrase(content)); cell.disableBorderSide(Rectangle.BOX); tbl.addCell(cell); } private void addIntroduction(FormBean formBean, String introText, Document doc) throws DocumentException { if (introText != null && !introText.isEmpty()) { doc.add(new Paragraph(introText)); } } private void addTitle(FormBean formBean, Document doc) throws DocumentException { String formName = formBean.getFormName(); if (formName != null && !formName.isEmpty()) { Font font = new Font(FontFamily.HELVETICA, 20, Font.BOLD, BaseColor.BLACK); Phrase titlePhrase = new Phrase(formBean.getFormName(), font); doc.add(titlePhrase); doc.add(Chunk.NEWLINE); } } }
fix for radio buttons handling
site/src/main/java/nl/hsleiden/utils/ITextPdfForm.java
fix for radio buttons handling
Java
mpl-2.0
b63303318edebf24f6c6ef3b09e8436b6123cb67
0
mozilla-mobile/focus-android,ekager/focus-android,ekager/focus-android,jonalmeida/focus-android,ekager/focus-android,jonalmeida/focus-android,ekager/focus-android,jonalmeida/focus-android,ekager/focus-android,mozilla-mobile/focus-android,jonalmeida/focus-android,jonalmeida/focus-android,mozilla-mobile/focus-android,mozilla-mobile/focus-android,mozilla-mobile/focus-android,mozilla-mobile/focus-android,ekager/focus-android,jonalmeida/focus-android
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.browser; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.v4.util.ArrayMap; import android.view.View; import org.mozilla.focus.R; import org.mozilla.focus.locale.Locales; import org.mozilla.focus.utils.AppConstants; import org.mozilla.focus.utils.HtmlLoader; import org.mozilla.focus.utils.SupportUtils; import org.mozilla.focus.web.IWebView; import org.mozilla.geckoview.BuildConfig; import java.util.Map; public class LocalizedContent { // We can't use "about:" because webview silently swallows about: pages, hence we use // a custom scheme. public static final String URL_ABOUT = "focus:about"; public static final String URL_RIGHTS = "focus:rights"; public static boolean handleInternalContent(String url, IWebView webView, Context context) { if (URL_ABOUT.equals(url)) { loadAbout(webView, context); return true; } else if (URL_RIGHTS.equals(url)) { loadRights(webView, context); return true; } return false; } /** * Load the content for focus:about */ private static void loadAbout(@NonNull final IWebView webView, Context context) { final Resources resources = Locales.getLocalizedResources(context); final Map<String, String> substitutionMap = new ArrayMap<>(); final String appName = context.getResources().getString(R.string.app_name); final String learnMoreURL = SupportUtils.getManifestoURL(); String aboutVersion = ""; try { final String engineIndicator = AppConstants.isGeckoBuild() ? " \uD83E\uDD8E " + "Version: " + BuildConfig.MOZ_APP_VERSION + " Build ID: " + BuildConfig.MOZ_APP_BUILDID : ""; final PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); aboutVersion = String.format("%s (Build #%s)", packageInfo.versionName, packageInfo.versionCode + engineIndicator); } catch (PackageManager.NameNotFoundException e) { // Nothing to do if we can't find the package name. } substitutionMap.put("%about-version%", aboutVersion); final String aboutContent = resources.getString(R.string.about_content, appName, learnMoreURL); substitutionMap.put("%about-content%", aboutContent); final String wordmark = HtmlLoader.loadPngAsDataURI(context, R.drawable.wordmark); substitutionMap.put("%wordmark%", wordmark); putLayoutDirectionIntoMap(substitutionMap, context); final String data = HtmlLoader.loadResourceFile(context, R.raw.about, substitutionMap); webView.loadData(URL_ABOUT, data, "text/html", "UTF-8", URL_ABOUT); } /** * Load the content for focus:rights */ private static void loadRights(@NonNull final IWebView webView, Context context) { final Resources resources = Locales.getLocalizedResources(context); final Map<String, String> substitutionMap = new ArrayMap<>(); final String appName = context.getResources().getString(R.string.app_name); final String mplUrl = "https://www.mozilla.org/en-US/MPL/"; final String trademarkPolicyUrl = "https://www.mozilla.org/foundation/trademarks/policy/"; final String gplUrl = "gpl.html"; final String trackingProtectionUrl = "https://wiki.mozilla.org/Security/Tracking_protection#Lists"; final String licensesUrl = "licenses.html"; final String content1 = resources.getString(R.string.your_rights_content1, appName); substitutionMap.put("%your-rights-content1%", content1); final String content2 = resources.getString(R.string.your_rights_content2, appName, mplUrl); substitutionMap.put("%your-rights-content2%", content2); final String content3 = resources.getString(R.string.your_rights_content3, appName, trademarkPolicyUrl); substitutionMap.put("%your-rights-content3%", content3); final String content4 = resources.getString(R.string.your_rights_content4, appName, licensesUrl); substitutionMap.put("%your-rights-content4%", content4); final String content5 = resources.getString(R.string.your_rights_content5, appName, gplUrl, trackingProtectionUrl); substitutionMap.put("%your-rights-content5%", content5); putLayoutDirectionIntoMap(substitutionMap, context); final String data = HtmlLoader.loadResourceFile(context, R.raw.rights, substitutionMap); webView.loadData(URL_RIGHTS, data, "text/html", "UTF-8", URL_RIGHTS); } private static void putLayoutDirectionIntoMap(Map<String, String> substitutionMap, Context context) { final int layoutDirection = context.getResources().getConfiguration().getLayoutDirection(); final String direction; if (layoutDirection == View.LAYOUT_DIRECTION_LTR) { direction = "ltr"; } else if (layoutDirection == View.LAYOUT_DIRECTION_RTL) { direction = "rtl"; } else { direction = "auto"; } substitutionMap.put("%dir%", direction); } }
app/src/main/java/org/mozilla/focus/browser/LocalizedContent.java
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.browser; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.support.annotation.NonNull; import android.support.v4.util.ArrayMap; import android.view.View; import org.mozilla.focus.R; import org.mozilla.focus.locale.Locales; import org.mozilla.focus.utils.AppConstants; import org.mozilla.focus.utils.HtmlLoader; import org.mozilla.focus.utils.SupportUtils; import org.mozilla.focus.web.IWebView; import java.util.Map; public class LocalizedContent { // We can't use "about:" because webview silently swallows about: pages, hence we use // a custom scheme. public static final String URL_ABOUT = "focus:about"; public static final String URL_RIGHTS = "focus:rights"; public static boolean handleInternalContent(String url, IWebView webView, Context context) { if (URL_ABOUT.equals(url)) { loadAbout(webView, context); return true; } else if (URL_RIGHTS.equals(url)) { loadRights(webView, context); return true; } return false; } /** * Load the content for focus:about */ private static void loadAbout(@NonNull final IWebView webView, Context context) { final Resources resources = Locales.getLocalizedResources(context); final Map<String, String> substitutionMap = new ArrayMap<>(); final String appName = context.getResources().getString(R.string.app_name); final String learnMoreURL = SupportUtils.getManifestoURL(); String aboutVersion = ""; try { final String engineIndicator = AppConstants.isGeckoBuild() ? " \uD83E\uDD8E" : ""; final PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); aboutVersion = String.format("%s (Build #%s)", packageInfo.versionName, packageInfo.versionCode + engineIndicator); } catch (PackageManager.NameNotFoundException e) { // Nothing to do if we can't find the package name. } substitutionMap.put("%about-version%", aboutVersion); final String aboutContent = resources.getString(R.string.about_content, appName, learnMoreURL); substitutionMap.put("%about-content%", aboutContent); final String wordmark = HtmlLoader.loadPngAsDataURI(context, R.drawable.wordmark); substitutionMap.put("%wordmark%", wordmark); putLayoutDirectionIntoMap(substitutionMap, context); final String data = HtmlLoader.loadResourceFile(context, R.raw.about, substitutionMap); webView.loadData(URL_ABOUT, data, "text/html", "UTF-8", URL_ABOUT); } /** * Load the content for focus:rights */ private static void loadRights(@NonNull final IWebView webView, Context context) { final Resources resources = Locales.getLocalizedResources(context); final Map<String, String> substitutionMap = new ArrayMap<>(); final String appName = context.getResources().getString(R.string.app_name); final String mplUrl = "https://www.mozilla.org/en-US/MPL/"; final String trademarkPolicyUrl = "https://www.mozilla.org/foundation/trademarks/policy/"; final String gplUrl = "gpl.html"; final String trackingProtectionUrl = "https://wiki.mozilla.org/Security/Tracking_protection#Lists"; final String licensesUrl = "licenses.html"; final String content1 = resources.getString(R.string.your_rights_content1, appName); substitutionMap.put("%your-rights-content1%", content1); final String content2 = resources.getString(R.string.your_rights_content2, appName, mplUrl); substitutionMap.put("%your-rights-content2%", content2); final String content3 = resources.getString(R.string.your_rights_content3, appName, trademarkPolicyUrl); substitutionMap.put("%your-rights-content3%", content3); final String content4 = resources.getString(R.string.your_rights_content4, appName, licensesUrl); substitutionMap.put("%your-rights-content4%", content4); final String content5 = resources.getString(R.string.your_rights_content5, appName, gplUrl, trackingProtectionUrl); substitutionMap.put("%your-rights-content5%", content5); putLayoutDirectionIntoMap(substitutionMap, context); final String data = HtmlLoader.loadResourceFile(context, R.raw.rights, substitutionMap); webView.loadData(URL_RIGHTS, data, "text/html", "UTF-8", URL_RIGHTS); } private static void putLayoutDirectionIntoMap(Map<String, String> substitutionMap, Context context) { final int layoutDirection = context.getResources().getConfiguration().getLayoutDirection(); final String direction; if (layoutDirection == View.LAYOUT_DIRECTION_LTR) { direction = "ltr"; } else if (layoutDirection == View.LAYOUT_DIRECTION_RTL) { direction = "rtl"; } else { direction = "auto"; } substitutionMap.put("%dir%", direction); } }
Add GV Version + Build ID to focus:about
app/src/main/java/org/mozilla/focus/browser/LocalizedContent.java
Add GV Version + Build ID to focus:about
Java
agpl-3.0
98d4f5a44da33270e36b411fa413cd43b727e53a
0
WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central
package edu.yu.einstein.wasp.util; import java.io.File; import junit.framework.Assert; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Reporter; import org.testng.annotations.Parameters; import edu.yu.einstein.wasp.integration.selenium.SelBaseTest; /** * * @author nvolnova * */ public class SeleniumHelper { private static final Logger logger = LoggerFactory.getLogger(SeleniumHelper.class); /** * * @param value * @return boolean */ public static boolean verifyTextPresent(String value, WebDriver driver) { CharSequence csValue = value; if (driver.getPageSource().contains(csValue)) { logger.debug("Text - "+value+" - present"); return true; } return false; } /** * * @param xlFilePath * @param sheetName * @param tableName * @return tabArray */ public static String[][] getTableArray(String xlFilePath, String sheetName, String tableName){ String[][] tabArray=null; try{ logger.debug("xlFilePath="+xlFilePath); Workbook workbook = Workbook.getWorkbook(new File(xlFilePath)); if (workbook == null) logger.debug("workbook is null"); Sheet sheet = workbook.getSheet(sheetName); if (sheet == null) logger.debug("sheet is null"); logger.debug("sheet name="+sheetName); int startRow,startCol, endRow, endCol,ci,cj; logger.debug("table name="+tableName); Cell tableStart=sheet.findCell(tableName); logger.debug("tableStart="+tableStart+"\n table name="+tableName); startRow=tableStart.getRow(); logger.debug("got row start"); startCol=tableStart.getColumn(); Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000, false); endRow=tableEnd.getRow(); endCol=tableEnd.getColumn(); logger.debug("startRow="+startRow+", endRow="+endRow+", " + "startCol="+startCol+", endCol="+endCol); tabArray=new String[endRow-startRow-1][endCol-startCol-1]; ci=0; for (int i=startRow+1;i<endRow;i++,ci++){ cj=0; for (int j=startCol+1;j<endCol;j++,cj++){ tabArray[ci][cj]=sheet.getCell(j,i).getContents(); logger.debug("contents="+sheet.getCell(j,i).getContents()); } } } catch (Exception e) { logger.debug("error in getTableArray()"); } return(tabArray); } /** * * @param sUserName * @param sUserPass * @param driver */ public static void login(String sUserName, String sUserPass, WebDriver driver) { driver.get("http://"+SelBaseTest.baseUrl+"/wasp/auth/login.do");//test environment Assert.assertEquals("http://"+SelBaseTest.baseUrl+"/wasp/auth/login.do", "http://"+SelBaseTest.baseUrl+"/wasp/auth/login.do"); WebElement userName = driver.findElement(By.name("j_username")); WebElement userPassword = driver.findElement(By.name("j_password")); userName.clear(); userPassword.clear(); userName.sendKeys(sUserName); userPassword.sendKeys(sUserPass); WebElement submitLogin = driver.findElement(By.xpath("//input[@type='submit']")); if(submitLogin !=null){ submitLogin.click(); } else { Reporter.log("Element: " +submitLogin+ ", is not available on page - " + driver.getCurrentUrl()); } } public static boolean isElementPresent(WebDriver driver, String xpathLocator, Boolean displayCustomMessage, String customMessage) { try { driver.findElement(By.xpath(xpathLocator)); } catch (org.openqa.selenium.NoSuchElementException Ex) { if (displayCustomMessage) { if (!customMessage.equals("")) { logger.debug(customMessage); } } else { logger.debug("Unable to locate Element: " + xpathLocator); } return false; } return true; } }
wasp-integration-test/src/test/java/edu/yu/einstein/wasp/util/SeleniumHelper.java
package edu.yu.einstein.wasp.util; import java.io.File; import junit.framework.Assert; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Reporter; import org.testng.annotations.Parameters; import edu.yu.einstein.wasp.integration.selenium.SelBaseTest; /** * * @author nvolnova * */ public class SeleniumHelper { private static final Logger logger = LoggerFactory.getLogger(SeleniumHelper.class); /** * * @param value * @return boolean */ public static boolean verifyTextPresent(String value, WebDriver driver) { CharSequence csValue = value; if (driver.getPageSource().contains(csValue)) { logger.debug("Text - "+value+" - present"); return true; } return false; } /** * * @param xlFilePath * @param sheetName * @param tableName * @return tabArray */ public static String[][] getTableArray(String xlFilePath, String sheetName, String tableName){ String[][] tabArray=null; try{ logger.debug("xlFilePath="+xlFilePath); Workbook workbook = Workbook.getWorkbook(new File(xlFilePath)); if (workbook == null) logger.debug("workbook is null"); Sheet sheet = workbook.getSheet(sheetName); if (sheet == null) logger.debug("sheet is null"); logger.debug("sheet name="+sheetName); int startRow,startCol, endRow, endCol,ci,cj; logger.debug("table name="+tableName); Cell tableStart=sheet.findCell(tableName); logger.debug("tableStart="+tableStart+"\n table name="+tableName); startRow=tableStart.getRow(); logger.debug("got row start"); startCol=tableStart.getColumn(); Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000, false); endRow=tableEnd.getRow(); endCol=tableEnd.getColumn(); logger.debug("startRow="+startRow+", endRow="+endRow+", " + "startCol="+startCol+", endCol="+endCol); tabArray=new String[endRow-startRow-1][endCol-startCol-1]; ci=0; for (int i=startRow+1;i<endRow;i++,ci++){ cj=0; for (int j=startCol+1;j<endCol;j++,cj++){ tabArray[ci][cj]=sheet.getCell(j,i).getContents(); logger.debug("contents="+sheet.getCell(j,i).getContents()); } } } catch (Exception e) { logger.debug("error in getTableArray()"); } return(tabArray); } /** * * @param sUserName * @param sUserPass * @param driver */ public static void login(String sUserName, String sUserPass, WebDriver driver) { driver.get("http://"+SelBaseTest.baseUrl+"/wasp/auth/login.do");//test environment Assert.assertEquals("http://localhost:8080/wasp/auth/login.do", "http://"+SelBaseTest.baseUrl+"/wasp/auth/login.do"); WebElement userName = driver.findElement(By.name("j_username")); WebElement userPassword = driver.findElement(By.name("j_password")); userName.clear(); userPassword.clear(); userName.sendKeys(sUserName); userPassword.sendKeys(sUserPass); WebElement submitLogin = driver.findElement(By.xpath("//input[@type='submit']")); if(submitLogin !=null){ submitLogin.click(); } else { Reporter.log("Element: " +submitLogin+ ", is not available on page - " + driver.getCurrentUrl()); } } public static boolean isElementPresent(WebDriver driver, String xpathLocator, Boolean displayCustomMessage, String customMessage) { try { driver.findElement(By.xpath(xpathLocator)); } catch (org.openqa.selenium.NoSuchElementException Ex) { if (displayCustomMessage) { if (!customMessage.equals("")) { logger.debug(customMessage); } } else { logger.debug("Unable to locate Element: " + xpathLocator); } return false; } return true; } }
fixed baseUrl link
wasp-integration-test/src/test/java/edu/yu/einstein/wasp/util/SeleniumHelper.java
fixed baseUrl link
Java
lgpl-2.1
37bc019e905043ad081718bdce40907e05288b11
0
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
package org.intermine.tracker; import java.lang.ref.WeakReference; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.intermine.util.ShutdownHook; public class TemplateTracker extends TrackerAbstract { private static final Logger LOG = Logger.getLogger(TemplateTracker.class); private static TemplateTracker templateTracker = null; private static final String TRACKER_NAME = "TemplateTracker"; protected TemplateTracker(Connection conn) { this.connection = conn; trackTableName = "templatetrack"; trackTableColumns = new String[] {"templatename", "username", "timestamp", "sessionidentifier"}; ShutdownHook.registerObject(new WeakReference<Object>(this)); LOG.info("Creating new " + getClass().getName() + " tracker"); } public static TemplateTracker getInstance(Connection con) { if (templateTracker == null) { templateTracker = new TemplateTracker(con); try { templateTracker.createTrackerTable(); } catch (Exception e) { //TODO //LOG.warn("Error setting up execute log in database table" + e); } } return templateTracker; } public TemplateTrack getMostPopularTemplate() { ResultSet rs = null; try { Statement stm = connection.createStatement(); String sql = "SELECT tt.templatename, COUNT(tt.templatename) accessnumbers" + " FROM templatetrack tt, tag t" + " WHERE tt.templatename=t.objectidentifier " + " AND t.tagname LIKE '%public' AND t.type='template'" + " GROUP BY tt.templatename" + " ORDER BY accessnumbers DESC LIMIT 1"; rs = stm.executeQuery(sql); rs.next(); return new TemplateTrack(rs.getString(1), "", rs.getInt(2)); } catch (SQLException sqle) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("Problem closing resultset in getMostVisitedTemplateByUser", e); } } } return null; } public List<String> getMostPopularTemplateOrder() { ResultSet rs = null; List<String> mostPopularTemplateOrder = new ArrayList<String>(); try { Statement stm = connection.createStatement(); String sql = "SELECT tt.templatename, COUNT(tt.templatename) accessnumbers" + " FROM templatetrack tt, tag t" + " WHERE tt.templatename=t.objectidentifier " + " AND t.tagname LIKE '%public' AND t.type='template'" + " GROUP BY tt.templatename" + " ORDER BY accessnumbers DESC"; rs = stm.executeQuery(sql); while (rs.next()) { mostPopularTemplateOrder.add(rs.getString(1)); } return mostPopularTemplateOrder; } catch (SQLException sqle) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("Problem closing resultset in getMostVisitedTemplateByUser", e); } } } return null; } public List<String> getMostPopularTemplateOrder(String userName, String sessionId) { ResultSet rs = null; List<String> mostPopularTemplateOrder = new ArrayList<String>(); try { Statement stm = connection.createStatement(); String sql = "SELECT tt.templatename, COUNT(tt.templatename) accessnumbers" + " FROM templatetrack tt" + " WHERE username = '" + userName + "'" + " OR sessionidentifier = '" + sessionId + "'" + " GROUP BY tt.templatename" + " ORDER BY accessnumbers DESC"; rs = stm.executeQuery(sql); while (rs.next()) { mostPopularTemplateOrder.add(rs.getString(1)); } return mostPopularTemplateOrder; } catch (SQLException sqle) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("Problem closing resultset in getMostVisitedTemplateByUser", e); } } } return null; } public Map<String, Integer> getRank() { ResultSet rs = null; Map<String, Integer> templateRank = new HashMap<String, Integer>(); try { Statement stm = connection.createStatement(); String sql = "SELECT tt.templatename, COUNT(tt.templatename) accessnumbers" + " FROM templatetrack tt" + " GROUP BY tt.templatename"; rs = stm.executeQuery(sql); while (rs.next()) { templateRank.put(rs.getString(1), rs.getInt(2)); } return templateRank; } catch (SQLException sqle) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("Problem closing resultset in getMostVisitedTemplateByUser", e); } } } return null; } public Object getTrack() { return null; } public String getStatementCreatingTable() { return "CREATE TABLE " + trackTableName + "(templatename text, username text, timestamp bigint, sessionidentifier text)"; } public Object[] getFormattedTrack(TrackerInput track) { if (track instanceof TemplateTrack) { TemplateTrack tti = (TemplateTrack) track; return new Object[] {tti.getTemplateName(), tti.getUserName(), tti.getTimestamp(), tti.getSessionIdentifier()}; } else { return null; } } public static String getTrackerName() { return TRACKER_NAME; } public String getName() { return TRACKER_NAME; } }
intermine/objectstore/main/src/org/intermine/tracker/TemplateTracker.java
package org.intermine.tracker; import java.lang.ref.WeakReference; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.intermine.util.ShutdownHook; public class TemplateTracker extends TrackerAbstract { private static final Logger LOG = Logger.getLogger(TemplateTracker.class); private static TemplateTracker templateTracker = null; private static final String TRACKER_NAME = "TemplateTracker"; protected TemplateTracker(Connection conn) { this.connection = conn; trackTableName = "templatetrack"; trackTableColumns = new String[] {"templatename", "username", "timestamp", "sessionidentifier"}; ShutdownHook.registerObject(new WeakReference<Object>(this)); LOG.info("Creating new " + getClass().getName() + " tracker"); } public static TemplateTracker getInstance(Connection con) { if (templateTracker == null) { templateTracker = new TemplateTracker(con); try { templateTracker.createTrackerTable(); } catch (Exception e) { //TODO //LOG.warn("Error setting up execute log in database table" + e); } } return templateTracker; } public TemplateTrack getMostPopularTemplate() { ResultSet rs = null; try { Statement stm = connection.createStatement(); String sql = "SELECT tt.templatename, COUNT(tt.templatename) accessnumbers" + " FROM templatetrack tt, tag t" + " WHERE tt.templatename=t.objectidentifier " + " AND t.tagname LIKE '%public' AND t.type='template'" + " GROUP BY tt.templatename" + " ORDER BY accessnumbers DESC LIMIT 1"; rs = stm.executeQuery(sql); rs.next(); return new TemplateTrack(rs.getString(1), "", rs.getInt(2)); } catch (SQLException sqle) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("Problem closing resultset in getMostVisitedTemplateByUser", e); } } } return null; } public List<String> getMostPopularTemplateOrder() { ResultSet rs = null; List<String> mostPopularTemplateOrder = new ArrayList<String>(); try { Statement stm = connection.createStatement(); String sql = "SELECT tt.templatename, COUNT(tt.templatename) accessnumbers" + " FROM templatetrack tt, tag t" + " WHERE tt.templatename=t.objectidentifier " + " AND t.tagname LIKE '%public' AND t.type='template'" + " GROUP BY tt.templatename" + " ORDER BY accessnumbers DESC"; rs = stm.executeQuery(sql); while (rs.next()) { mostPopularTemplateOrder.add(rs.getString(1)); } return mostPopularTemplateOrder; } catch (SQLException sqle) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("Problem closing resultset in getMostVisitedTemplateByUser", e); } } } return null; } public TemplateTrack getMostPopularTemplate(String userName, String sessionId) { ResultSet rs = null; try { Statement stm = connection.createStatement(); StringBuffer sql = new StringBuffer("SELECT templatename, " + " COUNT(templatename) as accessnumbers," + " username as user " + " FROM templatetrack GROUP BY templatename" + " ORDER BY accessnumbers DESC LIMIT 1 " + " WHERE sessionidentifier = " + sessionId); if (userName != null && !"".equals(userName)) { sql.append(" OR user=" + userName); } rs = stm.executeQuery(sql.toString()); String templateName = rs.getString(0); int accessCounter = rs.getInt(1); rs.close(); return new TemplateTrack(templateName, userName, accessCounter); } catch (SQLException sqle) { LOG.error("Problem executing query mostVisitedTemplateByUser", sqle); if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("Problem closing resultset in getMostVisitedTemplateByUser", e); } } } return null; } public Object getTrack() { return null; } public String getStatementCreatingTable() { return "CREATE TABLE " + trackTableName + "(templatename text, username text, timestamp bigint, sessionidentifier text)"; } public Object[] getFormattedTrack(TrackerInput track) { if (track instanceof TemplateTrack) { TemplateTrack tti = (TemplateTrack) track; return new Object[] {tti.getTemplateName(), tti.getUserName(), tti.getTimestamp(), tti.getSessionIdentifier()}; } else { return null; } } public static String getTrackerName() { return TRACKER_NAME; } public String getName() { return TRACKER_NAME; } }
Added the column rank on mymine templates page, displayed only if the super user is logged in Former-commit-id: d9e14f2e49446bc1c84ae11b2dd77bdffce411ef
intermine/objectstore/main/src/org/intermine/tracker/TemplateTracker.java
Added the column rank on mymine templates page, displayed only if the super user is logged in
Java
lgpl-2.1
4c3a97d883fa7969abde9868427dfe2026ac084b
0
windauer/exist,jessealama/exist,lcahlander/exist,wshager/exist,jensopetersen/exist,wshager/exist,windauer/exist,olvidalo/exist,jensopetersen/exist,opax/exist,shabanovd/exist,MjAbuz/exist,zwobit/exist,zwobit/exist,windauer/exist,dizzzz/exist,hungerburg/exist,ambs/exist,jessealama/exist,zwobit/exist,kohsah/exist,ljo/exist,MjAbuz/exist,wshager/exist,joewiz/exist,zwobit/exist,adamretter/exist,adamretter/exist,adamretter/exist,RemiKoutcherawy/exist,ambs/exist,dizzzz/exist,joewiz/exist,MjAbuz/exist,wolfgangmm/exist,kohsah/exist,joewiz/exist,adamretter/exist,olvidalo/exist,ambs/exist,hungerburg/exist,shabanovd/exist,jensopetersen/exist,jensopetersen/exist,kohsah/exist,opax/exist,eXist-db/exist,hungerburg/exist,zwobit/exist,shabanovd/exist,patczar/exist,zwobit/exist,jensopetersen/exist,wshager/exist,windauer/exist,kohsah/exist,jessealama/exist,opax/exist,opax/exist,jessealama/exist,patczar/exist,ljo/exist,patczar/exist,eXist-db/exist,wolfgangmm/exist,kohsah/exist,eXist-db/exist,wolfgangmm/exist,MjAbuz/exist,dizzzz/exist,lcahlander/exist,joewiz/exist,patczar/exist,hungerburg/exist,ljo/exist,ambs/exist,dizzzz/exist,lcahlander/exist,RemiKoutcherawy/exist,RemiKoutcherawy/exist,ljo/exist,eXist-db/exist,olvidalo/exist,lcahlander/exist,adamretter/exist,joewiz/exist,patczar/exist,MjAbuz/exist,adamretter/exist,joewiz/exist,wolfgangmm/exist,lcahlander/exist,olvidalo/exist,ljo/exist,jessealama/exist,jensopetersen/exist,lcahlander/exist,windauer/exist,wshager/exist,ljo/exist,shabanovd/exist,RemiKoutcherawy/exist,dizzzz/exist,windauer/exist,olvidalo/exist,RemiKoutcherawy/exist,eXist-db/exist,jessealama/exist,wolfgangmm/exist,shabanovd/exist,shabanovd/exist,kohsah/exist,eXist-db/exist,opax/exist,wolfgangmm/exist,ambs/exist,wshager/exist,patczar/exist,MjAbuz/exist,ambs/exist,hungerburg/exist,dizzzz/exist,RemiKoutcherawy/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2001-04 Wolfgang M. Meier * wolfgang@exist-db.org * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery; import java.io.IOException; import java.io.Reader; import java.text.NumberFormat; import org.apache.log4j.Logger; import org.exist.security.PermissionDeniedException; import org.exist.security.xacml.AccessContext; import org.exist.security.xacml.ExistPDP; import org.exist.security.xacml.XACMLSource; import org.exist.source.Source; import org.exist.source.StringSource; import org.exist.storage.DBBroker; import org.exist.storage.XQueryPool; import org.exist.xquery.parser.XQueryLexer; import org.exist.xquery.parser.XQueryParser; import org.exist.xquery.parser.XQueryTreeParser; import org.exist.xquery.util.ExpressionDumper; import org.exist.xquery.util.HTTPUtils; import org.exist.xquery.value.Sequence; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.collections.AST; import com.sun.xacml.ctx.RequestCtx; /** * @author wolf */ public class XQuery { private final static Logger LOG = Logger.getLogger(XQuery.class); private DBBroker broker; /** * */ public XQuery(DBBroker broker) { this.broker = broker; } public XQueryContext newContext(AccessContext accessCtx) { return new XQueryContext(broker, accessCtx); } public XQueryPool getXQueryPool() { return broker.getBrokerPool().getXQueryPool(); } public CompiledXQuery compile(XQueryContext context, String expression) throws XPathException { Source source = new StringSource(expression); try { return compile(context, source); } catch(IOException ioe) { //should not happen because expression is a String throw new XPathException(ioe.getMessage(), ioe); } } public CompiledXQuery compile(XQueryContext context, Source source) throws XPathException, IOException { return compile(context, source, false); } public CompiledXQuery compile(XQueryContext context, Source source, boolean xpointer) throws XPathException, IOException { XACMLSource xsource = XACMLSource.getInstance(source); Reader reader = source.getReader(); try { CompiledXQuery compiled = compile(context, reader, xpointer); compiled.setSource(xsource); return compiled; } finally { reader.close(); } } private CompiledXQuery compile(XQueryContext context, Reader reader, boolean xpointer) throws XPathException { //TODO: move XQueryContext.getUserFromHttpSession() here, have to check if servlet.jar is in the classpath //before compiling/executing that code though to avoid a dependency on servlet.jar - reflection? - deliriumsky // how about - if(XQuery.class.getResource("servlet.jar") != null) do load my class with dependency and call method? /* <|wolf77|> I think last time I checked, I already had problems with the call to <|wolf77|> HTTPUtils.addLastModifiedHeader( result, context ); <|wolf77|> in line 184 of XQuery.java, because it introduces another dependency on HTTP. */ long start = System.currentTimeMillis(); XQueryLexer lexer = new XQueryLexer(context, reader); XQueryParser parser = new XQueryParser(lexer); XQueryTreeParser treeParser = new XQueryTreeParser(context); try { if (xpointer) parser.xpointer(); else parser.xpath(); if (parser.foundErrors()) { LOG.debug(parser.getErrorMessage()); throw new StaticXQueryException( parser.getErrorMessage()); } AST ast = parser.getAST(); // LOG.debug("Generated AST: " + ast.toStringTree()); PathExpr expr = new PathExpr(context); if (xpointer) treeParser.xpointer(ast, expr); else treeParser.xpath(ast, expr); if (treeParser.foundErrors()) { throw new StaticXQueryException( treeParser.getErrorMessage(), treeParser.getLastException()); } expr.analyze(new AnalyzeContextInfo()); if (context.optimizationsEnabled()) { Optimizer optimizer = new Optimizer(context); expr.accept(optimizer); if (optimizer.hasOptimized()) { context.reset(); expr.analyze(new AnalyzeContextInfo()); } } // Log the query if it is not too large, but avoid // dumping huge queries to the log if (context.getExpressionCount() < 150) { LOG.debug("Query diagnostics:\n" + ExpressionDumper.dump(expr)); } else { LOG.debug("Query diagnostics:\n" + "[skipped: more than 150 expressions]"); } if (LOG.isDebugEnabled()) { NumberFormat nf = NumberFormat.getNumberInstance(); LOG.debug("Compilation took " + nf.format(System.currentTimeMillis() - start) + " ms"); } return expr; } catch (RecognitionException e) { LOG.debug("Error compiling query: " + e.getMessage(), e); String msg = e.getMessage(); if (msg.endsWith(", found 'null'")) msg = msg.substring(0, msg.length() - ", found 'null'".length()); throw new StaticXQueryException(msg, e.getLine(), e.getColumn()); } catch (TokenStreamException e) { LOG.debug("Error compiling query: " + e.getMessage(), e); throw new StaticXQueryException(e.getMessage(), e); } } public Sequence execute(CompiledXQuery expression, Sequence contextSequence) throws XPathException { XQueryContext context = expression.getContext(); Sequence result = execute(expression, contextSequence, true); //TODO : move this elsewhere ! HTTPUtils.addLastModifiedHeader( result, context ); return result; } public Sequence execute(CompiledXQuery expression, Sequence contextSequence, boolean resetContext) throws XPathException { long start = System.currentTimeMillis(); XQueryContext context = expression.getContext(); //check access to the query XACMLSource source = expression.getSource(); try { ExistPDP pdp = context.getPDP(); if(pdp != null) { RequestCtx request = pdp.getRequestHelper().createQueryRequest(context, source); pdp.evaluate(request); } } catch (PermissionDeniedException pde) { throw new XPathException("Permission to execute query: " + source.createId() + " denied.", pde); } expression.reset(); if (resetContext) { context.setBroker(broker); context.getWatchDog().reset(); } //do any preparation before execution context.prepare(); broker.getBrokerPool().getXQueryMonitor().queryStarted(context.getWatchDog()); try { Sequence result = expression.eval(contextSequence); if (LOG.isDebugEnabled()) { NumberFormat nf = NumberFormat.getNumberInstance(); LOG.debug("Execution took " + nf.format(System.currentTimeMillis() - start) + " ms"); } return result; } finally { expression.reset(); if (resetContext) context.reset(); broker.getBrokerPool().getXQueryMonitor().queryCompleted(context.getWatchDog()); } } public Sequence execute(String expression, Sequence contextSequence, AccessContext accessCtx) throws XPathException { XQueryContext context = new XQueryContext(broker, accessCtx); CompiledXQuery compiled = compile(context, expression); return execute(compiled, null); } }
src/org/exist/xquery/XQuery.java
/* * eXist Open Source Native XML Database * Copyright (C) 2001-04 Wolfgang M. Meier * wolfgang@exist-db.org * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery; import java.io.IOException; import java.io.Reader; import java.text.NumberFormat; import org.apache.log4j.Logger; import org.exist.security.PermissionDeniedException; import org.exist.security.xacml.AccessContext; import org.exist.security.xacml.ExistPDP; import org.exist.security.xacml.XACMLSource; import org.exist.source.Source; import org.exist.source.StringSource; import org.exist.storage.DBBroker; import org.exist.storage.XQueryPool; import org.exist.xquery.parser.XQueryLexer; import org.exist.xquery.parser.XQueryParser; import org.exist.xquery.parser.XQueryTreeParser; import org.exist.xquery.util.ExpressionDumper; import org.exist.xquery.util.HTTPUtils; import org.exist.xquery.value.Sequence; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.collections.AST; import com.sun.xacml.ctx.RequestCtx; /** * @author wolf */ public class XQuery { private final static Logger LOG = Logger.getLogger(XQuery.class); private DBBroker broker; /** * */ public XQuery(DBBroker broker) { this.broker = broker; } public XQueryContext newContext(AccessContext accessCtx) { return new XQueryContext(broker, accessCtx); } public XQueryPool getXQueryPool() { return broker.getBrokerPool().getXQueryPool(); } public CompiledXQuery compile(XQueryContext context, String expression) throws XPathException { Source source = new StringSource(expression); try { return compile(context, source); } catch(IOException ioe) { //should not happen because expression is a String throw new XPathException(ioe.getMessage(), ioe); } } public CompiledXQuery compile(XQueryContext context, Source source) throws XPathException, IOException { return compile(context, source, false); } public CompiledXQuery compile(XQueryContext context, Source source, boolean xpointer) throws XPathException, IOException { XACMLSource xsource = XACMLSource.getInstance(source); Reader reader = source.getReader(); try { CompiledXQuery compiled = compile(context, reader, xpointer); compiled.setSource(xsource); return compiled; } finally { reader.close(); } } private CompiledXQuery compile(XQueryContext context, Reader reader, boolean xpointer) throws XPathException { //TODO: move XQueryContext.getUserFromHttpSession() here, have to check if servlet.jar is in the classpath //before compiling/executing that code though to avoid a dependency on servlet.jar - reflection? - deliriumsky // how about - if(XQuery.class.getResource("servlet.jar") != null) do load my class with dependency and call method? /* <|wolf77|> I think last time I checked, I already had problems with the call to <|wolf77|> HTTPUtils.addLastModifiedHeader( result, context ); <|wolf77|> in line 184 of XQuery.java, because it introduces another dependency on HTTP. */ long start = System.currentTimeMillis(); XQueryLexer lexer = new XQueryLexer(context, reader); XQueryParser parser = new XQueryParser(lexer); XQueryTreeParser treeParser = new XQueryTreeParser(context); try { if (xpointer) parser.xpointer(); else parser.xpath(); if (parser.foundErrors()) { LOG.debug(parser.getErrorMessage()); throw new StaticXQueryException( parser.getErrorMessage()); } AST ast = parser.getAST(); // LOG.debug("Generated AST: " + ast.toStringTree()); PathExpr expr = new PathExpr(context); if (xpointer) treeParser.xpointer(ast, expr); else treeParser.xpath(ast, expr); if (treeParser.foundErrors()) { throw new StaticXQueryException( treeParser.getErrorMessage(), treeParser.getLastException()); } expr.analyze(new AnalyzeContextInfo()); if (context.optimizationsEnabled()) { Optimizer optimizer = new Optimizer(context); expr.accept(optimizer); if (optimizer.hasOptimized()) expr.analyze(new AnalyzeContextInfo()); } // Log the query if it is not too large, but avoid // dumping huge queries to the log if (context.getExpressionCount() < 150) { LOG.debug("Query diagnostics:\n" + ExpressionDumper.dump(expr)); } else { LOG.debug("Query diagnostics:\n" + "[skipped: more than 150 expressions]"); } if (LOG.isDebugEnabled()) { NumberFormat nf = NumberFormat.getNumberInstance(); LOG.debug("Compilation took " + nf.format(System.currentTimeMillis() - start) + " ms"); } return expr; } catch (RecognitionException e) { LOG.debug("Error compiling query: " + e.getMessage(), e); String msg = e.getMessage(); if (msg.endsWith(", found 'null'")) msg = msg.substring(0, msg.length() - ", found 'null'".length()); throw new StaticXQueryException(msg, e.getLine(), e.getColumn()); } catch (TokenStreamException e) { LOG.debug("Error compiling query: " + e.getMessage(), e); throw new StaticXQueryException(e.getMessage(), e); } } public Sequence execute(CompiledXQuery expression, Sequence contextSequence) throws XPathException { XQueryContext context = expression.getContext(); Sequence result = execute(expression, contextSequence, true); //TODO : move this elsewhere ! HTTPUtils.addLastModifiedHeader( result, context ); return result; } public Sequence execute(CompiledXQuery expression, Sequence contextSequence, boolean resetContext) throws XPathException { long start = System.currentTimeMillis(); XQueryContext context = expression.getContext(); //check access to the query XACMLSource source = expression.getSource(); try { ExistPDP pdp = context.getPDP(); if(pdp != null) { RequestCtx request = pdp.getRequestHelper().createQueryRequest(context, source); pdp.evaluate(request); } } catch (PermissionDeniedException pde) { throw new XPathException("Permission to execute query: " + source.createId() + " denied.", pde); } expression.reset(); if (resetContext) { context.setBroker(broker); context.getWatchDog().reset(); } //do any preparation before execution context.prepare(); broker.getBrokerPool().getXQueryMonitor().queryStarted(context.getWatchDog()); try { Sequence result = expression.eval(contextSequence); if (LOG.isDebugEnabled()) { NumberFormat nf = NumberFormat.getNumberInstance(); LOG.debug("Execution took " + nf.format(System.currentTimeMillis() - start) + " ms"); } return result; } finally { expression.reset(); if (resetContext) context.reset(); broker.getBrokerPool().getXQueryMonitor().queryCompleted(context.getWatchDog()); } } public Sequence execute(String expression, Sequence contextSequence, AccessContext accessCtx) throws XPathException { XQueryContext context = new XQueryContext(broker, accessCtx); CompiledXQuery compiled = compile(context, expression); return execute(compiled, null); } }
Reset XQuery context before analyzing the query a second time. Otherwise we may get static errors. svn path=/trunk/eXist/; revision=5812
src/org/exist/xquery/XQuery.java
Reset XQuery context before analyzing the query a second time. Otherwise we may get static errors.
Java
apache-2.0
caed934ff080a6d1e719b1344629f1b25e369680
0
gdi-by/downloadclient,Intevation/downloadclient,gdi-by/downloadclient,Intevation/downloadclient,gdi-by/downloadclient,gdi-by/downloadclient,Intevation/downloadclient,Intevation/downloadclient
/* * DownloadClient Geodateninfrastruktur Bayern * * (c) 2016 GSt. GDI-BY (gdi.bayern.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.bayern.gdi.processor; import de.bayern.gdi.utils.CountingInputStream; import de.bayern.gdi.utils.FileResponseHandler; import de.bayern.gdi.utils.HTTP; import de.bayern.gdi.utils.I18n; import de.bayern.gdi.utils.Log; import de.bayern.gdi.utils.RemoteFileState; import de.bayern.gdi.utils.WrapInputStreamFactory; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; /** Abstract class to do multiple file downloads. */ public abstract class MultipleFileDownloadJob extends AbstractDownloadJob { private static final Logger log = Logger.getLogger(MultipleFileDownloadJob.class.getName()); /** Number to re-tries for a failed download. */ protected static final int MAX_TRIES = 5; /** Pause after failed downloads. */ protected static final long FAIL_SLEEP = 30 * 1000; /** Stores a file location to down from and to. */ protected static class DLFile { /** Destination location of the file. */ File file; /** The url to download from. */ URL url; /** The number of tries yet. */ int tries; DLFile(File file, URL url) { this.file = file; this.url = url; } } /** Number of bytes of the currently downloading file. */ protected long currentCount; /** Total number of bytes of downloaded files do far. */ protected long totalCount; public MultipleFileDownloadJob() { } public MultipleFileDownloadJob(String user, String password, Log logger) { super(user, password, logger); } @Override public void bytesCounted(long count) { String msg = I18n.format( "atom.bytes.downloaded", this.totalCount + count); broadcastMessage(msg); this.currentCount = count; } /** * Downloads a file. * @param dlf The file to download. * @return true if download succeed false otherwise. * @throws JobExecutionException If something went wrong. */ protected RemoteFileState downloadFile(DLFile dlf) throws JobExecutionException { String msg = I18n.format("download.file", dlf.url, dlf.file); log(msg); log.log(Level.INFO, msg); this.currentCount = 0; CloseableHttpClient client = getClient(dlf.url); HttpGet httpget = getGetRequest(dlf.url); WrapInputStreamFactory wrapFactory = CountingInputStream.createWrapFactory(this); try { FileResponseHandler frh = new FileResponseHandler(dlf.file, wrapFactory, httpget); client.execute(httpget, frh); return RemoteFileState.SUCCESS; } catch (ClientProtocolException cpe) { return RemoteFileState.FATAL; } catch (IOException ioe) { return RemoteFileState.RETRY; } finally { HTTP.closeGraceful(client); this.totalCount += this.currentCount; } } /** * Downloads a list of files. * @param files The files to download. * @throws JobExecutionException If something went wrong. */ protected void downloadFiles(List<DLFile> files) throws JobExecutionException { int failed = 0; int numFiles = files.size(); broadcastMessage(I18n.format("file.download.start")); for (;;) { for (int i = 0; i < files.size();) { DLFile file = files.get(i); broadcastMessage(I18n.format( "download.file", file.url, file.file.getAbsolutePath())); RemoteFileState rfs = downloadFile(file); if (RemoteFileState.SUCCESS == rfs) { files.remove(i); } else if (RemoteFileState.FATAL == rfs) { for (int j = i; j < files.size();) { files.remove(j); failed++; } i = files.size(); } else { if (++file.tries < MAX_TRIES) { i++; } else { failed++; files.remove(i); } } broadcastMessage(I18n.format( "atom.downloaded.files", numFiles - failed - files.size(), files.size())); } if (files.isEmpty()) { break; } try { Thread.sleep(FAIL_SLEEP); } catch (InterruptedException ie) { break; } } // TODO: i18n String msg = "Bytes downloaded: " + this.totalCount; log(msg); log.log(Level.INFO, msg); if (failed > 0) { msg = I18n.format( "atom.downloaded.failed", numFiles - failed, failed); JobExecutionException jee = new JobExecutionException(msg); broadcastException(jee); throw jee; } msg = I18n.format("atom.downloaded.success", numFiles); broadcastMessage(msg); } }
src/main/java/de/bayern/gdi/processor/MultipleFileDownloadJob.java
/* * DownloadClient Geodateninfrastruktur Bayern * * (c) 2016 GSt. GDI-BY (gdi.bayern.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.bayern.gdi.processor; import de.bayern.gdi.utils.CountingInputStream; import de.bayern.gdi.utils.FileResponseHandler; import de.bayern.gdi.utils.HTTP; import de.bayern.gdi.utils.I18n; import de.bayern.gdi.utils.Log; import de.bayern.gdi.utils.RemoteFileState; import de.bayern.gdi.utils.WrapInputStreamFactory; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; /** Abstract class to do multiple file downloads. */ public abstract class MultipleFileDownloadJob extends AbstractDownloadJob { private static final Logger log = Logger.getLogger(MultipleFileDownloadJob.class.getName()); /** Number to re-tries for a failed download. */ protected static final int MAX_TRIES = 5; /** Pause after failed downloads. */ protected static final long FAIL_SLEEP = 30 * 1000; /** Stores a file location to down from and to. */ protected static class DLFile { /** Destination location of the file. */ File file; /** The url to download from. */ URL url; /** The number of tries yet. */ int tries; DLFile(File file, URL url) { this.file = file; this.url = url; } } /** Number of bytes of the currently downloading file. */ protected long currentCount; /** Total number of bytes of downloaded files do far. */ protected long totalCount; public MultipleFileDownloadJob() { } public MultipleFileDownloadJob(String user, String password, Log logger) { super(user, password, logger); } @Override public void bytesCounted(long count) { String msg = I18n.format( "atom.bytes.downloaded", this.totalCount + count); broadcastMessage(msg); this.currentCount = count; } /** * Downloads a file. * @param dlf The file to download. * @return true if download succeed false otherwise. * @throws JobExecutionException If something went wrong. */ protected RemoteFileState downloadFile(DLFile dlf) throws JobExecutionException { String msg = I18n.format("download.file", dlf.url, dlf.file); log(msg); log.log(Level.INFO, msg); this.currentCount = 0; CloseableHttpClient client = getClient(dlf.url); HttpGet httpget = getGetRequest(dlf.url); WrapInputStreamFactory wrapFactory = CountingInputStream.createWrapFactory(this); try { FileResponseHandler frh = new FileResponseHandler(dlf.file, wrapFactory, httpget); client.execute(httpget, frh); return RemoteFileState.SUCCESS; } catch (ClientProtocolException cpe) { return RemoteFileState.FATAL; } catch (IOException ioe) { return RemoteFileState.RETRY; } finally { HTTP.closeGraceful(client); this.totalCount += this.currentCount; } } /** * Downloads a list of files. * @param files The files to download. * @throws JobExecutionException If something went wrong. */ protected void downloadFiles(List<DLFile> files) throws JobExecutionException { int failed = 0; int numFiles = files.size(); for (;;) { for (int i = 0; i < files.size();) { DLFile file = files.get(i); RemoteFileState rfs = downloadFile(file); if (RemoteFileState.SUCCESS == rfs) { files.remove(i); } else if (RemoteFileState.FATAL == rfs) { for (int j = i; j < files.size();) { files.remove(j); failed++; } i = files.size(); } else { if (++file.tries < MAX_TRIES) { i++; } else { failed++; files.remove(i); } } broadcastMessage(I18n.format( "atom.downloaded.files", numFiles - failed - files.size(), files.size())); } if (files.isEmpty()) { break; } try { Thread.sleep(FAIL_SLEEP); } catch (InterruptedException ie) { break; } } // TODO: i18n String msg = "Bytes downloaded: " + this.totalCount; log(msg); log.log(Level.INFO, msg); if (failed > 0) { msg = I18n.format( "atom.downloaded.failed", numFiles - failed, failed); JobExecutionException jee = new JobExecutionException(msg); broadcastException(jee); throw jee; } msg = I18n.format("atom.downloaded.success", numFiles); broadcastMessage(msg); } }
Add download start status to atom downloads
src/main/java/de/bayern/gdi/processor/MultipleFileDownloadJob.java
Add download start status to atom downloads
Java
apache-2.0
766996ba326832b880a25f9879b332bfea488e78
0
symbiote-h2020/AuthenticationAuthorizationManager,symbiote-h2020/AuthenticationAuthorizationManager,symbiote-h2020/AuthenticationAuthorizationManager
package eu.h2020.symbiote.security.commons; import eu.h2020.symbiote.security.certificate.Certificate; import eu.h2020.symbiote.security.constants.AAMConstants; import eu.h2020.symbiote.security.enums.CoreAttributes; import eu.h2020.symbiote.security.enums.IssuingAuthorityType; import eu.h2020.symbiote.security.enums.UserRole; import eu.h2020.symbiote.security.enums.ValidationStatus; import eu.h2020.symbiote.security.exceptions.custom.*; import eu.h2020.symbiote.security.interfaces.ICoreServices; import eu.h2020.symbiote.security.payloads.CheckRevocationResponse; import eu.h2020.symbiote.security.payloads.Credentials; import eu.h2020.symbiote.security.repositories.PlatformRepository; import eu.h2020.symbiote.security.repositories.RevokedKeysRepository; import eu.h2020.symbiote.security.repositories.RevokedTokensRepository; import eu.h2020.symbiote.security.repositories.UserRepository; import eu.h2020.symbiote.security.services.TokenService; import eu.h2020.symbiote.security.session.AAM; import eu.h2020.symbiote.security.token.Token; import eu.h2020.symbiote.security.token.jwt.JWTClaims; import eu.h2020.symbiote.security.token.jwt.JWTEngine; import io.jsonwebtoken.Claims; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.security.*; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.X509Certificate; import java.util.*; /** * Class for managing operations (creation, verification checking, etc.) on * tokens in token related service ({@link TokenService}). * * @author Daniele Caldarola (CNIT) * @author Nemanja Ignjatov (UNIVIE) * @author Mikołaj Dobski (PSNC) * @author Piotr Kicki (PSNC) */ @Component public class TokenManager { private static Log log = LogFactory.getLog(TokenManager.class); public Map<String, String> federatedMappingRules = new HashMap<>(); private RestTemplate restTemplate = new RestTemplate(); private ICoreServices coreServices; private RegistrationManager regManager; private PlatformRepository platformRepository; private String deploymentId = ""; private IssuingAuthorityType deploymentType = IssuingAuthorityType.NULL; private RevokedKeysRepository revokedKeysRepository; private RevokedTokensRepository revokedTokensRepository; private UserRepository userRepository; private PasswordEncoder passwordEncoder; @Value("${aam.deployment.token.validityMillis}") private Long tokenValidity; @Autowired public TokenManager(ICoreServices coreServices, RegistrationManager regManager, PlatformRepository platformRepository, RevokedKeysRepository revokedKeysRepository, RevokedTokensRepository revokedTokensRepository, UserRepository userRepository, PasswordEncoder passwordEncoder) { this.coreServices = coreServices; this.regManager = regManager; this.deploymentId = regManager.getAAMInstanceIdentifier(); this.deploymentType = regManager.getDeploymentType(); this.platformRepository = platformRepository; this.revokedKeysRepository = revokedKeysRepository; this.revokedTokensRepository = revokedTokensRepository; this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } /** * @param user for which to issue to token * @return core or platform token issued for given user * @throws JWTCreationException on error */ public Token createHomeToken(User user) throws JWTCreationException { try { Map<String, String> attributes = new HashMap<>(); switch (deploymentType) { case CORE: switch (user.getRole()) { case APPLICATION: attributes.put(CoreAttributes.ROLE.toString(), UserRole.APPLICATION.toString()); break; case PLATFORM_OWNER: attributes.put(CoreAttributes.ROLE.toString(), UserRole.PLATFORM_OWNER.toString()); attributes.put(CoreAttributes.OWNED_PLATFORM.toString(), platformRepository .findByPlatformOwner(user).getPlatformInstanceId()); break; case NULL: throw new JWTCreationException("User Role unspecified"); } break; case PLATFORM: // TODO R3 federation break; case NULL: throw new JWTCreationException("Misconfigured AAM deployment type"); } return new Token(JWTEngine.generateJWTToken(user.getUsername(), attributes, user.getCertificate().getX509() .getPublicKey().getEncoded(), deploymentType, tokenValidity, deploymentId, regManager .getAAMPublicKey(), regManager.getAAMPrivateKey())); } catch (Exception e) { log.error(e); throw new JWTCreationException(e); } } public Token createForeignToken(String foreignToken) throws JWTCreationException { try { JWTClaims claims = JWTEngine.getClaimsFromToken(foreignToken); // TODO R3 Attribute Mapping Function Map<String, String> federatedAttributes = new HashMap<>(); // disabling federated token issuing when the mapping rule is empty if (federatedMappingRules.isEmpty()) throw new SecurityMisconfigurationException("AAM has no federation rules defined"); return new Token( JWTEngine.generateJWTToken(claims.getIss(), federatedAttributes, Base64.getDecoder().decode(claims .getIpk()), deploymentType, tokenValidity, deploymentId, regManager .getAAMPublicKey(), regManager.getAAMPrivateKey())); } catch (Exception e) { log.error(e); throw new JWTCreationException(e); } } public ValidationStatus validate(String tokenString) { try { // basic validation (signature and exp) ValidationStatus validationStatus = JWTEngine.validateTokenString(tokenString); if (validationStatus != ValidationStatus.VALID) { return validationStatus; } Claims claims = JWTEngine.getClaims(tokenString); String spk = claims.get("spk").toString(); String ipk = claims.get("ipk").toString(); // flow for Platform AAM if (deploymentType != IssuingAuthorityType.CORE) { if (!deploymentId.equals(claims.getIssuer())) { // relay validation to issuer return validateFederatedToken(tokenString); } // check IPK is not equal to current AAM PK if (!Base64.getEncoder().encodeToString( regManager.getAAMCertificate().getPublicKey().getEncoded()).equals(ipk)) { return ValidationStatus.REVOKED_IPK; } // check if issuer certificate is not expired if (certificateExpired(regManager.getAAMCertificate())) { return ValidationStatus.EXPIRED_ISSUER_CERTIFICATE; } // todo R3 possible validation of revoked IPK from CoreAAM - check if IPK was not revoked in the core // possibly throw runtime exception so that AAM crashes as it is no more valid } else { // check if IPK is in the revoked set if (revokedKeysRepository.exists(claims.getIssuer()) && revokedKeysRepository.findOne(claims.getIssuer()).getRevokedKeysSet().contains(ipk)) { return ValidationStatus.REVOKED_IPK; } // check if core is not an issuer if (!deploymentId.equals(claims.getIssuer())) { // relay validation to issuer return validateFederatedToken(tokenString); } // check if issuer certificate is not expired if (certificateExpired(regManager.getAAMCertificate())) return ValidationStatus.EXPIRED_ISSUER_CERTIFICATE; // check if it is core but with not valid PK if (!Base64.getEncoder().encodeToString( regManager.getAAMCertificate().getPublicKey().getEncoded()).equals(ipk)) { return ValidationStatus.INVALID_TRUST_CHAIN; } } // check revoked JTI if (revokedTokensRepository.exists(claims.getId())) { return ValidationStatus.REVOKED_TOKEN; } // check if SPK is is in the revoked set if (revokedKeysRepository.exists(claims.getSubject()) && revokedKeysRepository.findOne(claims.getSubject()).getRevokedKeysSet().contains(spk)) { return ValidationStatus.REVOKED_SPK; } if (certificateExpired(userRepository.findOne(claims.getSubject()).getCertificate().getX509())) { return ValidationStatus.EXPIRED_SUBJECT_CERTIFICATE; } } catch (ValidationException | IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException e) { log.error(e); return ValidationStatus.UNKNOWN; } return ValidationStatus.VALID; } public ValidationStatus validateFederatedToken(String tokenString) throws CertificateException, NullPointerException, ValidationException { Map<String, AAM> aams = new HashMap<>(); for (AAM aam : coreServices.getAvailableAAMs().getBody()) aams.put(aam.getAamInstanceId(), aam); Claims claims = JWTEngine.getClaims(tokenString); String issuer = claims.getIssuer(); // Core does not know such an issuer and therefore this might be a forfeit if (!aams.containsKey(issuer)) return ValidationStatus.INVALID_TRUST_CHAIN; AAM issuerAAM = aams.get(issuer); String aamAddress = issuerAAM.getAamAddress(); PublicKey publicKey = issuerAAM.getCertificate().getX509().getPublicKey(); // check IPK if (!Base64.getEncoder().encodeToString(publicKey.getEncoded()).equals(claims.get("ipk"))) { return ValidationStatus.REVOKED_IPK; } // rest check revocation // preparing request HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(AAMConstants.TOKEN_HEADER_NAME, tokenString); HttpEntity<String> entity = new HttpEntity<>(null, httpHeaders); // checking token revocation with proper AAM try { ResponseEntity<CheckRevocationResponse> status = restTemplate.postForEntity( aamAddress + AAMConstants.AAM_CHECK_HOME_TOKEN_REVOCATION, entity, CheckRevocationResponse.class); if (status.getStatusCode().is2xxSuccessful()) return ValidationStatus.valueOf(status.getBody().getStatus()); } catch (Exception e) { log.error(e); } return ValidationStatus.WRONG_AAM; } private boolean certificateExpired(X509Certificate certificate) throws NoSuchAlgorithmException, CertificateException, NoSuchProviderException, KeyStoreException, IOException { try { certificate.checkValidity(new Date()); } catch (CertificateExpiredException e) { log.info(e); return true; } return false; } public void revoke(Credentials credentials, Certificate certificate) throws CertificateException, WrongCredentialsException, NotExistingUserException { // user public key revocation User user = userRepository.findOne(credentials.getUsername()); if (user == null) { throw new NotExistingUserException(); } if (passwordEncoder.matches(credentials.getPassword(), user.getPasswordEncrypted())) { if (user.getCertificate().getCertificateString().equals(certificate.getCertificateString())) { SubjectsRevokedKeys subjectsRevokedKeys = revokedKeysRepository.findOne(user.getUsername()); Set<String> keySet = (subjectsRevokedKeys == null) ? new HashSet<>() : subjectsRevokedKeys.getRevokedKeysSet(); keySet.add(Base64.getEncoder().encodeToString( certificate.getX509().getPublicKey().getEncoded())); // adding key to revoked repository revokedKeysRepository.save(new SubjectsRevokedKeys(user.getUsername(), keySet)); } else { throw new CertificateException(); } } else { throw new WrongCredentialsException(); } } public void revoke(Credentials credentials, Token token) throws CertificateException, WrongCredentialsException, NotExistingUserException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, IOException, ValidationException { if (validate(token.getToken()) != ValidationStatus.VALID) throw new ValidationException("Invalid token"); // user token revocation User user = userRepository.findOne(credentials.getUsername()); if (user != null) { if (passwordEncoder.matches(credentials.getPassword(), user.getPasswordEncrypted())) { // user if (Base64.getEncoder().encodeToString(user.getCertificate().getX509().getPublicKey().getEncoded()).equals(token.getClaims().get("spk"))) { revokedTokensRepository.save(token); return; } // platform owner Platform platform = platformRepository.findByPlatformOwner(user); if (platform != null && Base64.getEncoder().encodeToString( platform.getPlatformAAMCertificate().getX509().getPublicKey().getEncoded()) .equals(token.getClaims().get("ipk").toString())) { revokedTokensRepository.save(token); return; } throw new ValidationException("You have no rights to this token"); } else { throw new WrongCredentialsException(); } } else { throw new NotExistingUserException(); } } }
src/main/java/eu/h2020/symbiote/security/commons/TokenManager.java
package eu.h2020.symbiote.security.commons; import eu.h2020.symbiote.security.certificate.Certificate; import eu.h2020.symbiote.security.constants.AAMConstants; import eu.h2020.symbiote.security.enums.CoreAttributes; import eu.h2020.symbiote.security.enums.IssuingAuthorityType; import eu.h2020.symbiote.security.enums.UserRole; import eu.h2020.symbiote.security.enums.ValidationStatus; import eu.h2020.symbiote.security.exceptions.custom.*; import eu.h2020.symbiote.security.interfaces.ICoreServices; import eu.h2020.symbiote.security.payloads.CheckRevocationResponse; import eu.h2020.symbiote.security.payloads.Credentials; import eu.h2020.symbiote.security.repositories.PlatformRepository; import eu.h2020.symbiote.security.repositories.RevokedKeysRepository; import eu.h2020.symbiote.security.repositories.RevokedTokensRepository; import eu.h2020.symbiote.security.repositories.UserRepository; import eu.h2020.symbiote.security.services.TokenService; import eu.h2020.symbiote.security.session.AAM; import eu.h2020.symbiote.security.token.Token; import eu.h2020.symbiote.security.token.jwt.JWTClaims; import eu.h2020.symbiote.security.token.jwt.JWTEngine; import io.jsonwebtoken.Claims; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.security.*; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.X509Certificate; import java.util.*; /** * Class for managing operations (creation, verification checking, etc.) on * tokens in token related service ({@link TokenService}). * * @author Daniele Caldarola (CNIT) * @author Nemanja Ignjatov (UNIVIE) * @author Mikołaj Dobski (PSNC) * @author Piotr Kicki (PSNC) */ @Component public class TokenManager { private static Log log = LogFactory.getLog(TokenManager.class); public Map<String, String> federatedMappingRules = new HashMap<>(); private RestTemplate restTemplate = new RestTemplate(); private ICoreServices coreServices; private RegistrationManager regManager; private PlatformRepository platformRepository; private String deploymentId = ""; private IssuingAuthorityType deploymentType = IssuingAuthorityType.NULL; private RevokedKeysRepository revokedKeysRepository; private RevokedTokensRepository revokedTokensRepository; private UserRepository userRepository; private PasswordEncoder passwordEncoder; @Value("${aam.deployment.token.validityMillis}") private Long tokenValidity; @Autowired public TokenManager(ICoreServices coreServices, RegistrationManager regManager, PlatformRepository platformRepository, RevokedKeysRepository revokedKeysRepository, RevokedTokensRepository revokedTokensRepository, UserRepository userRepository, PasswordEncoder passwordEncoder) { this.coreServices = coreServices; this.regManager = regManager; this.deploymentId = regManager.getAAMInstanceIdentifier(); this.deploymentType = regManager.getDeploymentType(); this.platformRepository = platformRepository; this.revokedKeysRepository = revokedKeysRepository; this.revokedTokensRepository = revokedTokensRepository; this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } /** * @param user for which to issue to token * @return core or platform token issued for given user * @throws JWTCreationException on error */ public Token createHomeToken(User user) throws JWTCreationException { try { Map<String, String> attributes = new HashMap<>(); switch (deploymentType) { case CORE: switch (user.getRole()) { case APPLICATION: attributes.put(CoreAttributes.ROLE.toString(), UserRole.APPLICATION.toString()); break; case PLATFORM_OWNER: attributes.put(CoreAttributes.ROLE.toString(), UserRole.PLATFORM_OWNER.toString()); attributes.put(CoreAttributes.OWNED_PLATFORM.toString(), platformRepository .findByPlatformOwner(user).getPlatformInstanceId()); break; case NULL: throw new JWTCreationException("User Role unspecified"); } break; case PLATFORM: // TODO R3 federation break; case NULL: throw new JWTCreationException("Misconfigured AAM deployment type"); } return new Token(JWTEngine.generateJWTToken(user.getUsername(), attributes, user.getCertificate().getX509() .getPublicKey().getEncoded(), deploymentType, tokenValidity, deploymentId, regManager .getAAMPublicKey(), regManager.getAAMPrivateKey())); } catch (Exception e) { log.error(e); throw new JWTCreationException(e); } } public Token createForeignToken(String foreignToken) throws JWTCreationException { try { JWTClaims claims = JWTEngine.getClaimsFromToken(foreignToken); // TODO R3 Attribute Mapping Function Map<String, String> federatedAttributes = new HashMap<>(); // disabling federated token issuing when the mapping rule is empty if (federatedMappingRules.isEmpty()) throw new SecurityMisconfigurationException("AAM has no federation rules defined"); return new Token( JWTEngine.generateJWTToken(claims.getIss(), federatedAttributes, Base64.getDecoder().decode(claims .getIpk()), deploymentType, tokenValidity, deploymentId, regManager .getAAMPublicKey(), regManager.getAAMPrivateKey())); } catch (Exception e) { log.error(e); throw new JWTCreationException(e); } } public ValidationStatus validate(String tokenString) { try { // basic validation (signature and exp) ValidationStatus validationStatus = JWTEngine.validateTokenString(tokenString); if (validationStatus != ValidationStatus.VALID) { return validationStatus; } Claims claims = JWTEngine.getClaims(tokenString); String spk = claims.get("spk").toString(); String ipk = claims.get("ipk").toString(); // flow for Platform AAM if (deploymentType != IssuingAuthorityType.CORE) { if (!deploymentId.equals(claims.getIssuer())) { // relay validation to issuer return validateFederatedToken(tokenString); } // check IPK is not equal to current AAM PK if (!Base64.getEncoder().encodeToString( regManager.getAAMCertificate().getPublicKey().getEncoded()).equals(ipk)) { return ValidationStatus.REVOKED_IPK; } // check if issuer certificate is not expired if (certificateExpired(regManager.getAAMCertificate())) { return ValidationStatus.EXPIRED_ISSUER_CERTIFICATE; } // todo R3 possible validation of revoked IPK from CoreAAM - check if IPK was not revoked in the core // possibly throw runtime exception so that AAM crashes as it is no more valid } else { // check if IPK is in the revoked set if (revokedKeysRepository.exists(claims.getIssuer()) && revokedKeysRepository.findOne(claims.getIssuer()).getRevokedKeysSet().contains(ipk)) { return ValidationStatus.REVOKED_IPK; } // check if core is not an issuer if (!deploymentId.equals(claims.getIssuer())) { // relay validation to issuer return validateFederatedToken(tokenString); } // check if issuer certificate is not expired if (certificateExpired(regManager.getAAMCertificate())) return ValidationStatus.EXPIRED_ISSUER_CERTIFICATE; // check if it is core but with not valid PK if (!Base64.getEncoder().encodeToString( regManager.getAAMCertificate().getPublicKey().getEncoded()).equals(ipk)) { return ValidationStatus.INVALID_TRUST_CHAIN; } } // check revoked JTI if (revokedTokensRepository.exists(claims.getId())) { return ValidationStatus.REVOKED_TOKEN; } // check if SPK is is in the revoked set if (revokedKeysRepository.exists(claims.getSubject()) && revokedKeysRepository.findOne(claims.getSubject()).getRevokedKeysSet().contains(spk)) { return ValidationStatus.REVOKED_SPK; } if (certificateExpired(userRepository.findOne(claims.getSubject()).getCertificate().getX509())) { return ValidationStatus.EXPIRED_SUBJECT_CERTIFICATE; } } catch (ValidationException | IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException e) { log.error(e); return ValidationStatus.UNKNOWN; } return ValidationStatus.VALID; } public ValidationStatus validateFederatedToken(String tokenString) throws CertificateException, NullPointerException, ValidationException { Map<String, AAM> aams = new HashMap<>(); for (AAM aam : coreServices.getAvailableAAMs().getBody()) aams.put(aam.getAamInstanceId(), aam); Claims claims = JWTEngine.getClaims(tokenString); String issuer = claims.getIssuer(); // Core does not know such an issuer and therefore this might be a forfeit if (!aams.containsKey(issuer)) return ValidationStatus.INVALID_TRUST_CHAIN; AAM issuerAAM = aams.get(issuer); String aamAddress = issuerAAM.getAamAddress(); PublicKey publicKey = issuerAAM.getCertificate().getX509().getPublicKey(); // check IPK if (!Base64.getEncoder().encodeToString(publicKey.getEncoded()).equals(claims.get("ipk"))) { return ValidationStatus.REVOKED_IPK; } // rest check revocation // preparing request HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(AAMConstants.TOKEN_HEADER_NAME, tokenString); HttpEntity<String> entity = new HttpEntity<>(null, httpHeaders); // checking token revocation with proper AAM try { ResponseEntity<CheckRevocationResponse> status = restTemplate.postForEntity( aamAddress + AAMConstants.AAM_CHECK_HOME_TOKEN_REVOCATION, entity, CheckRevocationResponse.class); if (status.getStatusCode().is2xxSuccessful()) return ValidationStatus.valueOf(status.getBody().getStatus()); } catch (Exception e) { log.error(e); } return ValidationStatus.WRONG_AAM; } private boolean certificateExpired(X509Certificate certificate) throws NoSuchAlgorithmException, CertificateException, NoSuchProviderException, KeyStoreException, IOException { try { certificate.checkValidity(new Date()); } catch (CertificateExpiredException e) { log.info(e); return true; } return false; } public void revoke(Credentials credentials, Certificate certificate) throws CertificateException, WrongCredentialsException, NotExistingUserException { // user public key revocation User user = userRepository.findOne(credentials.getUsername()); if (user == null) { throw new NotExistingUserException(); } if (passwordEncoder.matches(credentials.getPassword(), user.getPasswordEncrypted())) { if (user.getCertificate().getCertificateString().equals(certificate.getCertificateString())) { SubjectsRevokedKeys subjectsRevokedKeys = revokedKeysRepository.findOne(user.getUsername()); Set<String> keySet = (subjectsRevokedKeys == null) ? new HashSet<>() : subjectsRevokedKeys.getRevokedKeysSet(); keySet.add(Base64.getEncoder().encodeToString( certificate.getX509().getPublicKey().getEncoded())); // adding key to revoked repository revokedKeysRepository.save(new SubjectsRevokedKeys(user.getUsername(), keySet)); } else { throw new CertificateException(); } } else { throw new WrongCredentialsException(); } } public void revoke(Credentials credentials, Token token) throws CertificateException, WrongCredentialsException, NotExistingUserException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, IOException, ValidationException { // user token revocation User user = userRepository.findOne(credentials.getUsername()); if (user != null) { if (passwordEncoder.matches(credentials.getPassword(), user.getPasswordEncrypted())) { if (Base64.getEncoder().encodeToString(user.getCertificate().getX509().getPublicKey().getEncoded()).equals(token.getClaims().get("spk"))) { revokedTokensRepository.save(token); return; } Map<String, AAM> aams = new HashMap<>(); for (AAM aam : coreServices.getAvailableAAMs().getBody()) aams.put(aam.getAamInstanceId(), aam); if (!aams.containsKey(token.getClaims().getIssuer())) throw new NoSuchProviderException(); PublicKey publicKey = aams.get(token.getClaims().getIssuer()).getCertificate().getX509().getPublicKey(); // check IPK if (Base64.getEncoder().encodeToString(publicKey.getEncoded()).equals(token.getClaims().get("ipk").toString())) { revokedTokensRepository.save(token); return; } throw new ValidationException("You have no rights to this token"); } else { throw new WrongCredentialsException(); } } else { throw new NotExistingUserException(); } } }
Invalid AAM revocation removed and token revocation by PlatformAAM added
src/main/java/eu/h2020/symbiote/security/commons/TokenManager.java
Invalid AAM revocation removed and token revocation by PlatformAAM added
Java
apache-2.0
c09e2f6ec4e8e3052ce5de644f938d165f8b8ea8
0
adridadou/eth-propeller-core
package org.adridadou.ethereum.propeller; import org.adridadou.ethereum.propeller.converters.future.FutureConverter; import org.adridadou.ethereum.propeller.event.EthereumEventHandler; import org.adridadou.ethereum.propeller.exception.EthereumApiException; import org.adridadou.ethereum.propeller.solidity.*; import org.adridadou.ethereum.propeller.solidity.abi.AbiParam; import org.adridadou.ethereum.propeller.solidity.EvmVersion; import org.adridadou.ethereum.propeller.solidity.converters.SolidityTypeGroup; import org.adridadou.ethereum.propeller.solidity.converters.decoders.SolidityTypeDecoder; import org.adridadou.ethereum.propeller.solidity.converters.encoders.SolidityTypeEncoder; import org.adridadou.ethereum.propeller.swarm.SwarmHash; import org.adridadou.ethereum.propeller.swarm.SwarmService; import org.adridadou.ethereum.propeller.values.*; import io.reactivex.Observable; import org.web3j.abi.datatypes.Event; import org.web3j.protocol.core.methods.response.Log; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static java.lang.reflect.Proxy.newProxyInstance; /** * Created by davidroon on 31.03.16. * This code is released under Apache 2 license */ public class EthereumFacade { public static final Charset CHARSET = StandardCharsets.UTF_8; private final EthereumContractInvocationHandler handler; private final EthereumProxy ethereumProxy; private final SwarmService swarmService; private final SolidityCompiler solidityCompiler; EthereumFacade(EthereumProxy ethereumProxy, SwarmService swarmService, SolidityCompiler solidityCompiler) { this.swarmService = swarmService; this.solidityCompiler = solidityCompiler; this.handler = new EthereumContractInvocationHandler(ethereumProxy); this.ethereumProxy = ethereumProxy; } /** * This method defines a new type as void. This means that for this type, no decoder will be used and null will be returned. * This is used usually by wrapper projects to define language specific void types, for example Unit in Scala * * @param cls the class that needs to be seen as Void * @return The EthereumFacade object itself */ public EthereumFacade addVoidType(Class<?> cls) { ethereumProxy.addVoidClass(cls); return this; } /** * This method adds a converter from CompletableFuture to another future type. This is useful if you wnat to integrate a library with its own * Future type or for a wrapper project that wants to convert CompletableFuture to another Future type. for example scala Future * @param futureConverter the future converter to add * @return The EthereumFacade object itself */ public EthereumFacade addFutureConverter(FutureConverter futureConverter) { handler.addFutureConverter(futureConverter); return this; } /** * Creates a proxy object representing the interface with the smart contract. * This method reads the swarm url from the deployed code and then tries to download the smart contract metadata from Swarm. * It then reads the ABI from the smart contract's metadata to create the proxy. * @param address the address of the smart contract * @param account the account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(EthAddress address, EthAccount account, Class<T> contractInterface) { return createContractProxy(getDetails(address), address, account, contractInterface); } public SmartContract createSmartContract(SolidityContractDetails contract, EthAddress address, EthAccount account) { return ethereumProxy.getSmartContract(contract, address, account); } public SmartContract createSmartContract(EthAddress address, EthAccount account) { return createSmartContract(getDetails(address), address, account); } public SmartContract createSmartContract(EthAbi abi, EthAddress address, EthAccount account) { return createSmartContract(new SolcSolidityContractDetails(abi.getAbi(), null, null), address, account); } /** * Creates a proxy object representing the interface with the smart contract. * @param abi The ABI of the smart contract * @param address The address of the smart contract * @param account The account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(EthAbi abi, EthAddress address, EthAccount account, Class<T> contractInterface) { T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler); handler.register(proxy, contractInterface, new SolcSolidityContractDetails(abi.getAbi(), null, null), address, account); return proxy; } /** * Creates a proxy object representing the interface with the smart contract. * @param details The compiled smart contract * @param address The address of the smart contract * @param account The account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(SolidityContractDetails details, EthAddress address, EthAccount account, Class<T> contractInterface) { T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler); handler.register(proxy, contractInterface, details, address, account); return proxy; } /** * Publishes the contract * @param contract The compiled contract to publish * @param account The account that publishes it * @param constructorArgs The constructor arguments * @return The future address of the newly created smart contract */ public CompletableFuture<EthAddress> publishContract(SolidityContractDetails contract, EthAccount account, Object... constructorArgs) { return ethereumProxy.publish(contract, account, constructorArgs); } /** * Publishes the contract and sends ether at the same time * @param contract The compiled contract to publish * @param account The account that publishes it * @param value How much ether to send while publishing the smart contract * @param constructorArgs The constructor arguments * @return The future address of the newly created smart contract */ public CompletableFuture<EthAddress> publishContractWithValue(SolidityContractDetails contract, EthAccount account, EthValue value, Object... constructorArgs) { return ethereumProxy.publishWithValue(contract, account, value, constructorArgs); } /** * Publishes the smart contract metadata to Swarm * @param contract The compiled contract * @return The swarm hash */ public SwarmHash publishMetadataToSwarm(SolidityContractDetails contract) { return swarmService.publish(contract.getMetadata()); } /** * Checks if an address exists * @param address The address to check * @return Whether it exists or not */ public boolean addressExists(EthAddress address) { return ethereumProxy.addressExists(address); } /** * Gets the balance at an address * @param addr The address to check * @return The current balance */ public EthValue getBalance(EthAddress addr) { return ethereumProxy.getBalance(addr); } /** * Gets the balance of an account * @param account The account to check * @return The current balance */ public EthValue getBalance(EthAccount account) { return ethereumProxy.getBalance(account.getAddress()); } /** * Returns the event handler object * This object is used to observe transactions and blocks * @return The event handler */ public EthereumEventHandler events() { return ethereumProxy.events(); } /** /** * Returns the current best block number * @return The best block number */ public long getCurrentBlockNumber() { return ethereumProxy.getCurrentBlockNumber(); } /** * Sends ether * @param fromAccount The account that sends ether * @param to The target address * @param value The value to send * @return The future details of the call */ public CompletableFuture<CallDetails> sendEther(EthAccount fromAccount, EthAddress to, EthValue value) { return ethereumProxy.sendTx(value, EthData.empty(), fromAccount, to); } /** * Sends the transaction * @param value The value to send * @param data The data to send * @param account The account that sends ether * @param address The target address * @return The future details of the call */ public CompletableFuture<CallDetails> sendTx(EthValue value, EthData data, EthAccount account, EthAddress address) { return ethereumProxy.sendTx(value, data, account, address); } /** * Returns the current Nonce of an address. * It takes into account pending transactions as well * @param address The address from which we want the Nonce * @return The Nonce */ public Nonce getNonce(EthAddress address) { return ethereumProxy.getNonce(address); } /** * Returns the GasUsage of the transaction data. * It takes into account additional gas usage for contract creation * @param value The value to send * @param data The data to send * @param account The account that sends ether * @param address The target address * @return The GasUsage */ public GasUsage estimateGas(EthValue value, EthData data, EthAccount account, EthAddress address) { return ethereumProxy.estimateGas(value, data, account, address); } /** * Returns the set of transactions that are being sent by propeller and but not added to the chain yet * @param address The transaction sender * @return the set of transaction hashes */ public Set<EthHash> getPendingTransactions(EthAddress address) { return ethereumProxy.getPendingTransactions(address); } /** * Returns the binary code from a deployed smart contract * @param address The smart contract's address * @return The code */ public SmartContractByteCode getCode(EthAddress address) { return ethereumProxy.getCode(address); } /** * Downloads and returns the smart contract's metadata * @param swarmMetadaLink Swarm url * @return The metadata */ public SmartContractMetadata getMetadata(SwarmMetadaLink swarmMetadaLink) { try { return swarmService.getMetadata(swarmMetadaLink.getHash()); } catch (IOException e) { throw new EthereumApiException("error while getting metadata", e); } } /** * Compiles the solidity file * @param src the source file * @return The compilation result */ public CompilationResult compile(SoliditySourceFile src, Optional<EvmVersion> evmVersion) { return solidityCompiler.compileSrc(src, evmVersion); } public CompilationResult compile(SoliditySourceFile src) { return solidityCompiler.compileSrc(src, Optional.empty()); } /** * Search an event definition from the ABI * @param contract The compiled contract * @param eventName The event name * @param eventEntity The entity that will represent the event * @param <T> The event entity tpye * @return The solidity event definition if found */ public <T> Optional<TypedSolidityEvent<T>> findEventDefinition(SolidityContractDetails contract, String eventName, Class<T> eventEntity) { return contract.getAbi().stream() .filter(entry -> entry.getType().equals("event")) .filter(entry -> entry.getName().equals(eventName)) .filter(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return entry.findConstructor(decoders, eventEntity).isPresent(); }) .map(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return new TypedSolidityEvent<>(entry, decoders, eventEntity); }).findFirst(); } /** * Search an event definition from the ABI * @param contract The compiled contract * @param eventName The event name * @param eventParams the type of each parameter in the event. Useful when you don't want to map it to a class * @return The solidity event definition if found */ public Optional<RawSolidityEvent> findEventDefinitionForParameters(SolidityContractDetails contract, String eventName, List<Class<?>> eventParams) { return contract.getAbi().stream() .filter(entry -> entry.getType().equals("event")) .filter(entry -> entry.getName().equals(eventName)) .filter(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); if(decoders.size() != eventParams.size()) { return false; } for(int i = 0; i < decoders.size(); i++) { Class<?> cls = eventParams.get(i); if (decoders.get(i).stream().noneMatch(decoder -> decoder.canDecode(cls))) { return false; } } return true; }) .map(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return new RawSolidityEvent(entry, decoders, eventParams); }).findFirst(); } /** * Search an event definition from the ABI * * @param abi The ABI * @param eventName The event name * @param eventParameters The types of each parameter in the event. Useful when you don't want to map the event to a class * @return The solidity event definition if found */ public Optional<RawSolidityEvent> findEventDefinitionForParametersByAbi(EthAbi abi, String eventName, List<Class<?>> eventParameters) { return findEventDefinitionForParameters(new SolcSolidityContractDetails(abi.getAbi(), "", ""), eventName, eventParameters); } /** * Search an event definition from the ABI * * @param abi The ABI * @param eventName The event name * @param eventEntity The entity that will represent the event * @param <T> The event entity * @return The solidity event definition if found */ public <T> Optional<TypedSolidityEvent<T>> findEventDefinition(EthAbi abi, String eventName, Class<T> eventEntity) { return findEventDefinition(new SolcSolidityContractDetails(abi.getAbi(), "", ""), eventName, eventEntity); } /** * Observe an event from a smart contract * @param eventDefiniton The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The event observable */ public <T> Observable<T> observeEvents(SolidityEvent<T> eventDefiniton, EthAddress address) { return ethereumProxy.observeEvents(eventDefiniton, address); } /** * Observe an event from a smart contract and returns not only the event but the transaction info as well * * @param eventDefiniton The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The event observable with the info */ public <T> Observable<EventInfo<T>> observeEventsWithInfo(SolidityEvent<T> eventDefiniton, EthAddress address) { return ethereumProxy.observeEventsWithInfo(eventDefiniton, address); } /** * Returns all the events that happened at a specific block * * @param blockNumber The block number * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtBlock(Long blockNumber, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlock(eventDefinition, address, blockNumber); } /** * Returns all the events that happened at a specific block * * @param blockHash The block hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtBlock(EthHash blockHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlock(eventDefinition, address, blockHash); } /** * Returns all the events that happened at a specific block * * @param transactionHash The transactionHash hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtTransaction(EthHash transactionHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtTransaction(eventDefinition, address, transactionHash); } /** * Returns all the events that happened at a specific block * * @param blockNumber The block number * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtBlockWithInfo(Long blockNumber, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlockWithInfo(eventDefinition, address, blockNumber); } /** * Returns all the events that happened at a specific block * * @param blockHash The block hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtBlockWithInfo(EthHash blockHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlockWithInfo(eventDefinition, address, blockHash); } /** * Returns all the events that happened at a specific block * * @param transactionHash The transactionHash hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtTransactionWithInfo(EthHash transactionHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtTransactionWithInfo(eventDefinition, address, transactionHash); } /** * Returns all the events that happened at a smart contract matching an event signature and indexed parameters * * @param event Event that should be matched * @param address address of the smart contract that emits the events * @param optionalTopics Optional indexed event parameters * @return */ public List<EventInfo> getSpecificEvents(Event event, EthAddress address, String... optionalTopics) { return ethereumProxy.getSpecificEvents(event, address, optionalTopics); } /** * Encodes an argument manually. This can be useful when you need to send a value to a bytes or bytes32 input * @param arg The argument to encode * @param solidityType Which solidity type is the argument represented * @return The Encoded result */ public EthData encode(Object arg, SolidityType solidityType) { return Optional.of(arg).map(argument -> { SolidityTypeEncoder encoder = ethereumProxy.getEncoders(new AbiParam(false, "", solidityType.name())) .stream().filter(enc -> enc.canConvert(arg.getClass())) .findFirst().orElseThrow(() -> new EthereumApiException("cannot convert the type " + argument.getClass() + " to the solidty type " + solidityType)); return encoder.encode(arg, solidityType); }).orElseGet(EthData::empty); } public <T> T decode(EthData data, SolidityType solidityType, Class<T> cls) { return decode(0, data, solidityType, cls); } /** * Decodes an ouput. This is useful when a function returns bytes or bytes32 and you want to cast it to a specific type * @param index It can be that more than one value has been encoded in the data. This is the index of this value. It starts with 0 * @param data The data to decode * @param solidityType The target solidity type * @param cls The target class * @param <T> The value type * @return The decoded value */ public <T> T decode(Integer index, EthData data, SolidityType solidityType, Class<T> cls) { if (ethereumProxy.isVoidType(cls)) { return null; } SolidityTypeDecoder decoder = ethereumProxy.getDecoders(new AbiParam(false, "", solidityType.name())) .stream() .filter(dec -> dec.canDecode(cls)) .findFirst().orElseThrow(() -> new EthereumApiException("cannot decode " + solidityType.name() + " to " + cls.getTypeName())); return (T) decoder.decode(index, data, cls); } /** * Gets info for the transaction with the specific hash * * @param hash The hash of the transaction * @return the info */ public Optional<TransactionInfo> getTransactionInfo(EthHash hash) { return ethereumProxy.getTransactionInfo(hash); } public EthereumFacade addDecoder(SolidityTypeGroup solidityTypeGroup, SolidityTypeDecoder decoder) { ethereumProxy.addDecoder(solidityTypeGroup, decoder); return this; } public EthereumFacade addEncoder(SolidityTypeGroup solidityTypeGroup, SolidityTypeEncoder encoder) { ethereumProxy.addEncoder(solidityTypeGroup, encoder); return this; } private SolidityContractDetails getDetails(final EthAddress address) { SmartContractByteCode code = ethereumProxy.getCode(address); SmartContractMetadata metadata = getMetadata(code.getMetadaLink().orElseThrow(() -> new EthereumApiException("no metadata link found for smart contract on address " + address.toString()))); return new SolcSolidityContractDetails(metadata.getAbi(), "", ""); } }
src/main/java/org/adridadou/ethereum/propeller/EthereumFacade.java
package org.adridadou.ethereum.propeller; import org.adridadou.ethereum.propeller.converters.future.FutureConverter; import org.adridadou.ethereum.propeller.event.EthereumEventHandler; import org.adridadou.ethereum.propeller.exception.EthereumApiException; import org.adridadou.ethereum.propeller.solidity.*; import org.adridadou.ethereum.propeller.solidity.abi.AbiParam; import org.adridadou.ethereum.propeller.solidity.EvmVersion; import org.adridadou.ethereum.propeller.solidity.converters.SolidityTypeGroup; import org.adridadou.ethereum.propeller.solidity.converters.decoders.SolidityTypeDecoder; import org.adridadou.ethereum.propeller.solidity.converters.encoders.SolidityTypeEncoder; import org.adridadou.ethereum.propeller.swarm.SwarmHash; import org.adridadou.ethereum.propeller.swarm.SwarmService; import org.adridadou.ethereum.propeller.values.*; import io.reactivex.Observable; import org.web3j.abi.datatypes.Event; import org.web3j.protocol.core.methods.response.Log; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static java.lang.reflect.Proxy.newProxyInstance; /** * Created by davidroon on 31.03.16. * This code is released under Apache 2 license */ public class EthereumFacade { public static final Charset CHARSET = StandardCharsets.UTF_8; private final EthereumContractInvocationHandler handler; private final EthereumProxy ethereumProxy; private final SwarmService swarmService; private final SolidityCompiler solidityCompiler; EthereumFacade(EthereumProxy ethereumProxy, SwarmService swarmService, SolidityCompiler solidityCompiler) { this.swarmService = swarmService; this.solidityCompiler = solidityCompiler; this.handler = new EthereumContractInvocationHandler(ethereumProxy); this.ethereumProxy = ethereumProxy; } /** * This method defines a new type as void. This means that for this type, no decoder will be used and null will be returned. * This is used usually by wrapper projects to define language specific void types, for example Unit in Scala * * @param cls the class that needs to be seen as Void * @return The EthereumFacade object itself */ public EthereumFacade addVoidType(Class<?> cls) { ethereumProxy.addVoidClass(cls); return this; } /** * This method adds a converter from CompletableFuture to another future type. This is useful if you wnat to integrate a library with its own * Future type or for a wrapper project that wants to convert CompletableFuture to another Future type. for example scala Future * @param futureConverter the future converter to add * @return The EthereumFacade object itself */ public EthereumFacade addFutureConverter(FutureConverter futureConverter) { handler.addFutureConverter(futureConverter); return this; } /** * Creates a proxy object representing the interface with the smart contract. * This method reads the swarm url from the deployed code and then tries to download the smart contract metadata from Swarm. * It then reads the ABI from the smart contract's metadata to create the proxy. * @param address the address of the smart contract * @param account the account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(EthAddress address, EthAccount account, Class<T> contractInterface) { return createContractProxy(getDetails(address), address, account, contractInterface); } public SmartContract createSmartContract(SolidityContractDetails contract, EthAddress address, EthAccount account) { return ethereumProxy.getSmartContract(contract, address, account); } public SmartContract createSmartContract(EthAddress address, EthAccount account) { return createSmartContract(getDetails(address), address, account); } public SmartContract createSmartContract(EthAbi abi, EthAddress address, EthAccount account) { return createSmartContract(new SolcSolidityContractDetails(abi.getAbi(), null, null), address, account); } /** * Creates a proxy object representing the interface with the smart contract. * @param abi The ABI of the smart contract * @param address The address of the smart contract * @param account The account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(EthAbi abi, EthAddress address, EthAccount account, Class<T> contractInterface) { T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler); handler.register(proxy, contractInterface, new SolcSolidityContractDetails(abi.getAbi(), null, null), address, account); return proxy; } /** * Creates a proxy object representing the interface with the smart contract. * @param details The compiled smart contract * @param address The address of the smart contract * @param account The account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(SolidityContractDetails details, EthAddress address, EthAccount account, Class<T> contractInterface) { T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler); handler.register(proxy, contractInterface, details, address, account); return proxy; } /** * Publishes the contract * @param contract The compiled contract to publish * @param account The account that publishes it * @param constructorArgs The constructor arguments * @return The future address of the newly created smart contract */ public CompletableFuture<EthAddress> publishContract(SolidityContractDetails contract, EthAccount account, Object... constructorArgs) { return ethereumProxy.publish(contract, account, constructorArgs); } /** * Publishes the contract and sends ether at the same time * @param contract The compiled contract to publish * @param account The account that publishes it * @param value How much ether to send while publishing the smart contract * @param constructorArgs The constructor arguments * @return The future address of the newly created smart contract */ public CompletableFuture<EthAddress> publishContractWithValue(SolidityContractDetails contract, EthAccount account, EthValue value, Object... constructorArgs) { return ethereumProxy.publishWithValue(contract, account, value, constructorArgs); } /** * Publishes the smart contract metadata to Swarm * @param contract The compiled contract * @return The swarm hash */ public SwarmHash publishMetadataToSwarm(SolidityContractDetails contract) { return swarmService.publish(contract.getMetadata()); } /** * Checks if an address exists * @param address The address to check * @return Whether it exists or not */ public boolean addressExists(EthAddress address) { return ethereumProxy.addressExists(address); } /** * Gets the balance at an address * @param addr The address to check * @return The current balance */ public EthValue getBalance(EthAddress addr) { return ethereumProxy.getBalance(addr); } /** * Gets the balance of an account * @param account The account to check * @return The current balance */ public EthValue getBalance(EthAccount account) { return ethereumProxy.getBalance(account.getAddress()); } /** * Returns the event handler object * This object is used to observe transactions and blocks * @return The event handler */ public EthereumEventHandler events() { return ethereumProxy.events(); } /** /** * Returns the current best block number * @return The best block number */ public long getCurrentBlockNumber() { return ethereumProxy.getCurrentBlockNumber(); } /** * Sends ether * @param fromAccount The account that sends ether * @param to The target address * @param value The value to send * @return The future details of the call */ public CompletableFuture<CallDetails> sendEther(EthAccount fromAccount, EthAddress to, EthValue value) { return ethereumProxy.sendTx(value, EthData.empty(), fromAccount, to); } /** * Sends the transaction * @param value The value to send * @param data The data to send * @param account The account that sends ether * @param address The target address * @return The future details of the call */ public CompletableFuture<CallDetails> sendTx(EthValue value, EthData data, EthAccount account, EthAddress address) { return ethereumProxy.sendTx(value, data, account, address); } /** * Returns the current Nonce of an address. * It takes into account pending transactions as well * @param address The address from which we want the Nonce * @return The Nonce */ public Nonce getNonce(EthAddress address) { return ethereumProxy.getNonce(address); } /** * Returns the GasUsage of the transaction data. * It takes into account additional gas usage for contract creation * @param value The value to send * @param data The data to send * @param account The account that sends ether * @param address The target address * @return The GasUsage */ public GasUsage estimateGas(EthValue value, EthData data, EthAccount account, EthAddress address) { return ethereumProxy.estimateGas(value, data, account, address); } /** * Returns the set of transactions that are being sent by propeller and but not added to the chain yet * @param address The transaction sender * @return the set of transaction hashes */ public Set<EthHash> getPendingTransactions(EthAddress address) { return ethereumProxy.getPendingTransactions(address); } /** * Returns the binary code from a deployed smart contract * @param address The smart contract's address * @return The code */ public SmartContractByteCode getCode(EthAddress address) { return ethereumProxy.getCode(address); } /** * Downloads and returns the smart contract's metadata * @param swarmMetadaLink Swarm url * @return The metadata */ public SmartContractMetadata getMetadata(SwarmMetadaLink swarmMetadaLink) { try { return swarmService.getMetadata(swarmMetadaLink.getHash()); } catch (IOException e) { throw new EthereumApiException("error while getting metadata", e); } } /** * Compiles the solidity file * @param src the source file * @return The compilation result */ public CompilationResult compile(SoliditySourceFile src, Optional<EvmVersion> evmVersion) { return solidityCompiler.compileSrc(src, evmVersion); } public CompilationResult compile(SoliditySourceFile src) { return solidityCompiler.compileSrc(src, Optional.empty()); } /** * Search an event definition from the ABI * @param contract The compiled contract * @param eventName The event name * @param eventEntity The entity that will represent the event * @param <T> The event entity tpye * @return The solidity event definition if found */ public <T> Optional<TypedSolidityEvent<T>> findEventDefinition(SolidityContractDetails contract, String eventName, Class<T> eventEntity) { return contract.getAbi().stream() .filter(entry -> entry.getType().equals("event")) .filter(entry -> entry.getName().equals(eventName)) .filter(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return entry.findConstructor(decoders, eventEntity).isPresent(); }) .map(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return new TypedSolidityEvent<>(entry, decoders, eventEntity); }).findFirst(); } /** * Search an event definition from the ABI * @param contract The compiled contract * @param eventName The event name * @param eventParams the type of each parameter in the event. Useful when you don't want to map it to a class * @return The solidity event definition if found */ public Optional<RawSolidityEvent> findEventDefinitionForParameters(SolidityContractDetails contract, String eventName, List<Class<?>> eventParams) { return contract.getAbi().stream() .filter(entry -> entry.getType().equals("event")) .filter(entry -> entry.getName().equals(eventName)) .filter(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); if(decoders.size() != eventParams.size()) { return false; } for(int i = 0; i < decoders.size(); i++) { Class<?> cls = eventParams.get(i); if (decoders.get(i).stream().noneMatch(decoder -> decoder.canDecode(cls))) { return false; } } return true; }) .map(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return new RawSolidityEvent(entry, decoders, eventParams); }).findFirst(); } /** * Search an event definition from the ABI * * @param abi The ABI * @param eventName The event name * @param eventParameters The types of each parameter in the event. Useful when you don't want to map the event to a class * @return The solidity event definition if found */ public Optional<RawSolidityEvent> findEventDefinitionForParametersByAbi(EthAbi abi, String eventName, List<Class<?>> eventParameters) { return findEventDefinitionForParameters(new SolcSolidityContractDetails(abi.getAbi(), "", ""), eventName, eventParameters); } /** * Search an event definition from the ABI * * @param abi The ABI * @param eventName The event name * @param eventEntity The entity that will represent the event * @param <T> The event entity * @return The solidity event definition if found */ public <T> Optional<TypedSolidityEvent<T>> findEventDefinition(EthAbi abi, String eventName, Class<T> eventEntity) { return findEventDefinition(new SolcSolidityContractDetails(abi.getAbi(), "", ""), eventName, eventEntity); } /** * Observe an event from a smart contract * @param eventDefiniton The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The event observable */ public <T> Observable<T> observeEvents(SolidityEvent<T> eventDefiniton, EthAddress address) { return ethereumProxy.observeEvents(eventDefiniton, address); } /** * Observe an event from a smart contract and returns not only the event but the transaction info as well * * @param eventDefiniton The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The event observable with the info */ public <T> Observable<EventInfo<T>> observeEventsWithInfo(SolidityEvent<T> eventDefiniton, EthAddress address) { return ethereumProxy.observeEventsWithInfo(eventDefiniton, address); } /** * Returns all the events that happened at a specific block * * @param blockNumber The block number * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtBlock(Long blockNumber, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlock(eventDefinition, address, blockNumber); } /** * Returns all the events that happened at a specific block * * @param blockHash The block hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtBlock(EthHash blockHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlock(eventDefinition, address, blockHash); } /** * Returns all the events that happened at a specific block * * @param transactionHash The transactionHash hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtTransaction(EthHash transactionHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtTransaction(eventDefinition, address, transactionHash); } /** * Returns all the events that happened at a specific block * * @param blockNumber The block number * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtBlockWithInfo(Long blockNumber, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlockWithInfo(eventDefinition, address, blockNumber); } /** * Returns all the events that happened at a specific block * * @param blockHash The block hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtBlockWithInfo(EthHash blockHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlockWithInfo(eventDefinition, address, blockHash); } /** * Returns all the events that happened at a specific block * * @param transactionHash The transactionHash hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtTransactionWithInfo(EthHash transactionHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtTransactionWithInfo(eventDefinition, address, transactionHash); } /** * Returns all the events that happened at a smart contract matching an event signature and indexed parameters * * @param event Event that should be matched * @param address address of the smart contract that emits the events * @param optionalTopics Optional indexed event parameters * @return */ public List<EventInfo> getSpecificEvents(Event event, EthAddress address, String... optionalTopics) { return ethereumProxy.getSpecificEvents(event, address, optionalTopics); } /** * Encodes an argument manually. This can be useful when you need to send a value to a bytes or bytes32 input * @param arg The argument to encode * @param solidityType Which solidity type is the argument represented * @return The Encoded result */ public EthData encode(Object arg, SolidityType solidityType) { return Optional.of(arg).map(argument -> { SolidityTypeEncoder encoder = ethereumProxy.getEncoders(new AbiParam(false, "", solidityType.name())) .stream().filter(enc -> enc.canConvert(arg.getClass())) .findFirst().orElseThrow(() -> new EthereumApiException("cannot convert the type " + argument.getClass() + " to the solidty type " + solidityType)); return encoder.encode(arg, solidityType); }).orElseGet(EthData::empty); } public <T> T decode(EthData data, SolidityType solidityType, Class<T> cls) { return decode(0, data, solidityType, cls); } /** * Decodes an ouput. This is useful when a function returns bytes or bytes32 and you want to cast it to a specific type * @param index It can be that more than one value has been encoded in the data. This is the index of this value. It starts with 0 * @param data The data to decode * @param solidityType The target solidity type * @param cls The target class * @param <T> The value type * @return The decoded value */ public <T> T decode(Integer index, EthData data, SolidityType solidityType, Class<T> cls) { if (ethereumProxy.isVoidType(cls)) { return null; } SolidityTypeDecoder decoder = ethereumProxy.getDecoders(new AbiParam(false, "", solidityType.name())) .stream() .filter(dec -> dec.canDecode(cls)) .findFirst().orElseThrow(() -> new EthereumApiException("cannot decode " + solidityType.name() + " to " + cls.getTypeName())); return (T) decoder.decode(index, data, cls); } /** * Gets info for the transaction with the specific hash * * @param hash The hash of the transaction * @return the info */ public Optional<TransactionInfo> getTransactionInfo(EthHash hash) { return ethereumProxy.getTransactionInfo(hash); } public EthereumFacade addDecoder(SolidityTypeGroup solidityTypeGroup, SolidityTypeDecoder decoder) { ethereumProxy.addDecoder(solidityTypeGroup, decoder); return this; } public EthereumFacade addEncoder(SolidityTypeGroup solidityTypeGroup, SolidityTypeEncoder encoder) { ethereumProxy.addEncoder(solidityTypeGroup, encoder); return this; } private SolidityContractDetails getDetails(final EthAddress address) { SmartContractByteCode code = ethereumProxy.getCode(address); SmartContractMetadata metadata = getMetadata(code.getMetadaLink().orElseThrow(() -> new EthereumApiException("no metadata link found for smart contract on address " + address.toString()))); return new SolcSolidityContractDetails(metadata.getAbi(), "", ""); } }
Remove white space
src/main/java/org/adridadou/ethereum/propeller/EthereumFacade.java
Remove white space
Java
apache-2.0
aeeb63c7385b84f4da07f25f9898d2b21ad051e6
0
akosyakov/intellij-community,da1z/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,dslomov/intellij-community,samthor/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,signed/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,signed/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,kool79/intellij-community,signed/intellij-community,jagguli/intellij-community,xfournet/intellij-community,slisson/intellij-community,slisson/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,consulo/consulo,semonte/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,signed/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,supersven/intellij-community,nicolargo/intellij-community,supersven/intellij-community,Distrotech/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,ernestp/consulo,youdonghai/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,semonte/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,kool79/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,adedayo/intellij-community,amith01994/intellij-community,apixandru/intellij-community,hurricup/intellij-community,vladmm/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,caot/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,ryano144/intellij-community,allotria/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,signed/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,apixandru/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,samthor/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,kdwink/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,retomerz/intellij-community,allotria/intellij-community,holmes/intellij-community,jagguli/intellij-community,fitermay/intellij-community,dslomov/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ernestp/consulo,holmes/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,FHannes/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,ibinti/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,hurricup/intellij-community,signed/intellij-community,FHannes/intellij-community,izonder/intellij-community,kool79/intellij-community,FHannes/intellij-community,robovm/robovm-studio,robovm/robovm-studio,retomerz/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,holmes/intellij-community,amith01994/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,holmes/intellij-community,jagguli/intellij-community,jagguli/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,caot/intellij-community,slisson/intellij-community,adedayo/intellij-community,fnouama/intellij-community,apixandru/intellij-community,supersven/intellij-community,semonte/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,amith01994/intellij-community,asedunov/intellij-community,caot/intellij-community,supersven/intellij-community,amith01994/intellij-community,consulo/consulo,caot/intellij-community,jagguli/intellij-community,clumsy/intellij-community,blademainer/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,fnouama/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,allotria/intellij-community,kool79/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ryano144/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ryano144/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,jagguli/intellij-community,caot/intellij-community,consulo/consulo,diorcety/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,vladmm/intellij-community,allotria/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,dslomov/intellij-community,amith01994/intellij-community,jagguli/intellij-community,blademainer/intellij-community,amith01994/intellij-community,FHannes/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,retomerz/intellij-community,amith01994/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,da1z/intellij-community,suncycheng/intellij-community,izonder/intellij-community,vvv1559/intellij-community,ernestp/consulo,ibinti/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,dslomov/intellij-community,holmes/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,consulo/consulo,robovm/robovm-studio,SerCeMan/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,fitermay/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,kool79/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,FHannes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,holmes/intellij-community,kool79/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,da1z/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ernestp/consulo,samthor/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,clumsy/intellij-community,vladmm/intellij-community,izonder/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,fitermay/intellij-community,slisson/intellij-community,caot/intellij-community,holmes/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,kool79/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,supersven/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,slisson/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,supersven/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,semonte/intellij-community,vladmm/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ryano144/intellij-community,da1z/intellij-community,slisson/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,petteyg/intellij-community,hurricup/intellij-community,hurricup/intellij-community,supersven/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,allotria/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,semonte/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,caot/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,gnuhub/intellij-community,semonte/intellij-community,samthor/intellij-community,allotria/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,signed/intellij-community,ibinti/intellij-community,caot/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,signed/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,samthor/intellij-community,Distrotech/intellij-community,samthor/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,allotria/intellij-community,apixandru/intellij-community,vladmm/intellij-community,blademainer/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,clumsy/intellij-community,ibinti/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,caot/intellij-community,petteyg/intellij-community,semonte/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,caot/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,kool79/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,blademainer/intellij-community,supersven/intellij-community,hurricup/intellij-community,apixandru/intellij-community,slisson/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,consulo/consulo,signed/intellij-community,FHannes/intellij-community,kdwink/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,retomerz/intellij-community,diorcety/intellij-community,da1z/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ernestp/consulo,holmes/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,allotria/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,da1z/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,asedunov/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,samthor/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,semonte/intellij-community,orekyuu/intellij-community,da1z/intellij-community,adedayo/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,slisson/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.ui; import com.intellij.CommonBundle; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.WindowManager; import com.intellij.ui.*; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.mac.MacMessages; import com.intellij.util.PairFunction; import com.intellij.util.execution.ParametersListUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.*; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.plaf.basic.BasicHTML; import javax.swing.text.JTextComponent; import javax.swing.text.html.HTMLEditorKit; import java.awt.*; import java.awt.event.*; import java.util.List; public class Messages { public static final int OK = 0; public static final int YES = 0; public static final int NO = 1; public static final int CANCEL = 2; private static TestDialog ourTestImplementation = TestDialog.DEFAULT; private static TestInputDialog ourTestInputImplementation = TestInputDialog.DEFAULT; private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.ui.Messages"); protected static final String OK_BUTTON = CommonBundle.getOkButtonText(); protected static final String YES_BUTTON = CommonBundle.getYesButtonText(); protected static final String NO_BUTTON = CommonBundle.getNoButtonText(); protected static final String CANCEL_BUTTON = CommonBundle.getCancelButtonText(); @TestOnly public static TestDialog setTestDialog(TestDialog newValue) { Application application = ApplicationManager.getApplication(); if (application != null) { LOG.assertTrue(application.isUnitTestMode(), "This method is available for tests only"); } TestDialog oldValue = ourTestImplementation; ourTestImplementation = newValue; return oldValue; } @TestOnly public static TestInputDialog setTestInputDialog(TestInputDialog newValue) { Application application = ApplicationManager.getApplication(); if (application != null) { LOG.assertTrue(application.isUnitTestMode(), "This method is available for tests only"); } TestInputDialog oldValue = ourTestInputImplementation; ourTestInputImplementation = newValue; return oldValue; } public static Icon getErrorIcon() { return UIUtil.getErrorIcon(); } public static Icon getInformationIcon() { return UIUtil.getInformationIcon(); } public static Icon getWarningIcon() { return UIUtil.getWarningIcon(); } public static Icon getQuestionIcon() { return UIUtil.getQuestionIcon(); } /** * Please, use {@link #showOkCancelDialog} or {@link #showYesNoCancelDialog} if possible (these dialogs implements native OS behavior)! */ public static int showDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { return showDialog(project, message, title, options, defaultOptionIndex, icon, null); } /** * Please, use {@link #showOkCancelDialog} or {@link #showYesNoCancelDialog} if possible (these dialogs implements native OS behavior)! */ public static int showDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } if (canShowMacSheetPanel()) { return MacMessages.getInstance() .showMessageDialog(title, message, options, false, WindowManager.getInstance().suggestParentWindow(project), defaultOptionIndex, defaultOptionIndex, doNotAskOption); } return showIdeaMessageDialog(project, message, title, options, defaultOptionIndex, icon, doNotAskOption); } public static int showIdeaMessageDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { MessageDialog dialog = new MessageDialog(project, message, title, options, defaultOptionIndex, -1, icon, doNotAskOption, false); dialog.show(); return dialog.getExitCode(); } public static boolean canShowMacSheetPanel() { return SystemInfo.isMac && !isApplicationInUnitTestOrHeadless() && Registry.is("ide.mac.message.dialogs.as.sheets") && !DialogWrapper.isMultipleModalDialogs(); } public static int showDialog(Project project, String message, String title, String moreInfo, String[] options, int defaultOptionIndex, int focusedOptionIndex, Icon icon) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } if (canShowMacSheetPanel() && moreInfo == null) { return MacMessages.getInstance() .showMessageDialog(title, message, options, false, WindowManager.getInstance().suggestParentWindow(project), defaultOptionIndex, focusedOptionIndex, null); } MessageDialog dialog = new MoreInfoMessageDialog(project, message, title, moreInfo, options, defaultOptionIndex, focusedOptionIndex, icon); dialog.show(); return dialog.getExitCode(); } private static boolean isApplicationInUnitTestOrHeadless(){ final Application application = ApplicationManager.getApplication(); return application != null && (application.isUnitTestMode() || application.isHeadlessEnvironment()); } public static int showDialog(Component parent, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { if (canShowMacSheetPanel()) { return MacMessages.getInstance() .showMessageDialog(title, message, options, false, SwingUtilities.getWindowAncestor(parent), defaultOptionIndex, defaultOptionIndex, null); } MessageDialog dialog = new MessageDialog(parent, message, title, options, defaultOptionIndex, defaultOptionIndex, icon, false); dialog.show(); return dialog.getExitCode(); } } /** * Use this method only if you do not know project or component * * @see #showDialog(Project, String, String, String[], int, Icon, DialogWrapper.DoNotAskOption) * @see #showDialog(Component, String, String, String[], int, Icon) */ public static int showDialog(String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showMessageDialog(title, message, options, false, null, defaultOptionIndex, focusedOptionIndex, doNotAskOption); } //what's it? if (application.isUnitTestMode()) throw new RuntimeException(message); MessageDialog dialog = new MessageDialog(message, title, options, defaultOptionIndex, focusedOptionIndex, icon, doNotAskOption); dialog.show(); return dialog.getExitCode(); } } /** * Use this method only if you do not know project or component * * @see #showDialog(Project, String, String, String[], int, Icon) * @see #showDialog(Component, String, String, String[], int, Icon) */ public static int showDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { return showDialog(message, title, options, defaultOptionIndex, defaultOptionIndex, icon, doNotAskOption); } /** * Use this method only if you do not know project or component * * @see #showDialog(Project, String, String, String[], int, Icon) * @see #showDialog(Component, String, String, String[], int, Icon) */ public static int showDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { return showDialog(message, title, options, defaultOptionIndex, icon, null); } /** * @see com.intellij.openapi.ui.DialogWrapper#DialogWrapper(Project,boolean) */ public static void showMessageDialog(@Nullable Project project, String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); return; } showDialog(project, message, title, new String[]{OK_BUTTON}, 0, icon); } public static void showMessageDialog(Component parent, String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, SwingUtilities.getWindowAncestor(parent)); return; } showDialog(parent, message, title, new String[]{OK_BUTTON}, 0, icon); } /** * Use this method only if you do not know project or component * * @see #showMessageDialog(Project, String, String, Icon) * @see #showMessageDialog(Component, String, String, Icon) */ public static void showMessageDialog(String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON); return; } showDialog(message, title, new String[]{OK_BUTTON}, 0, icon); } /** * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. */ public static int showYesNoDialog(@Nullable Project project, String message, String title, String yesText, String noText, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, yesText, noText, WindowManager.getInstance().suggestParentWindow(project)); } return showDialog(project, message, title, new String[]{yesText, noText}, 0, icon); } /** * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. */ public static int showYesNoDialog(@Nullable Project project, String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, YES_BUTTON, NO_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); } return showYesNoDialog(project, message, title, YES_BUTTON, NO_BUTTON, icon); } /** * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. */ public static int showYesNoDialog(Component parent, String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, YES_BUTTON, NO_BUTTON, SwingUtilities.getWindowAncestor(parent)); } return showDialog(parent, message, title, new String[]{YES_BUTTON, NO_BUTTON}, 0, icon); } /** * Use this method only if you do not know project or component * * @see #showYesNoDialog(com.intellij.openapi.project.Project, String, String, javax.swing.Icon) * @see #showYesNoCancelDialog(java.awt.Component, String, String, javax.swing.Icon) */ public static int showYesNoDialog(String message, String title, String yesText, String noText, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, yesText, noText, null, doNotAskOption); } return showDialog(message, title, new String[]{yesText, noText}, 0, icon, doNotAskOption); } /** * Use this method only if you do not know project or component * * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. * @see #showYesNoDialog(Project, String, String, String, String, Icon) * @see #showYesNoDialog(java.awt.Component, String, String, javax.swing.Icon) */ public static int showYesNoDialog(String message, String title, String yesText, String noText, @Nullable Icon icon) { return showYesNoDialog(message, title, yesText, noText, icon, null); } /** * Use this method only if you do not know project or component * * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. * @see #showYesNoDialog(Project, String, String, Icon) * @see #showYesNoDialog(Component, String, String, Icon) */ public static int showYesNoDialog(String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, YES_BUTTON, NO_BUTTON, null); } return showYesNoDialog(message, title, YES_BUTTON, NO_BUTTON, icon); } public static int showOkCancelDialog(Project project, String message, String title, String okText, String cancelText, Icon icon, DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, WindowManager.getInstance().suggestParentWindow(project), doNotAskOption); } return showDialog(project, message, title, new String[]{okText, cancelText}, 0, icon, doNotAskOption); } public static int showOkCancelDialog(Project project, String message, String title, String okText, String cancelText, Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, WindowManager.getInstance().suggestParentWindow(project)); } return showDialog(project, message, title, new String[]{okText, cancelText}, 0, icon); } public static int showOkCancelDialog(Project project, String message, String title, Icon icon) { return showOkCancelDialog(project, message, title, OK_BUTTON, CANCEL_BUTTON, icon); } public static int showOkCancelDialog(Component parent, String message, String title, String okText, String cancelText, Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, SwingUtilities.getWindowAncestor(parent)); } return showDialog(parent, message, title, new String[]{okText, cancelText}, 0, icon); } public static int showOkCancelDialog(Component parent, String message, String title, Icon icon) { return showOkCancelDialog(parent, message, title, OK_BUTTON, CANCEL_BUTTON, icon); } /** * Use this method only if you do not know project or component * * @see #showOkCancelDialog(Project, String, String, Icon) * @see #showOkCancelDialog(Component, String, String, Icon) */ public static int showOkCancelDialog(String message, String title, Icon icon) { return showOkCancelDialog(message, title, OK_BUTTON, CANCEL_BUTTON, icon, null); } /** * Use this method only if you do not know project or component * * @see #showOkCancelDialog(Project, String, String, String, String, Icon) * @see #showOkCancelDialog(Component, String, String, String, String, Icon) */ public static int showOkCancelDialog(String message, String title, String okText, String cancelText, Icon icon) { return showOkCancelDialog(message, title, okText, cancelText, icon, null); } /** * Use this method only if you do not know project or component * * @see #showOkCancelDialog(Project, String, String, String, String, Icon, DialogWrapper.DoNotAskOption) * @see #showOkCancelDialog(Component, String, String, String, String, Icon) */ public static int showOkCancelDialog(String message, String title, String okText, String cancelText, Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, null, doNotAskOption); } return showDialog(message, title, new String[]{okText, cancelText}, 0, icon, doNotAskOption); } public static int showCheckboxOkCancelDialog(String message, String title, String checkboxText, final boolean checked, final int defaultOptionIndex, final int focusedOptionIndex, Icon icon) { return showCheckboxMessageDialog(message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, checkboxText, checked, defaultOptionIndex, focusedOptionIndex, icon, new PairFunction<Integer, JCheckBox, Integer>() { @Override public Integer fun(final Integer exitCode, final JCheckBox cb) { return exitCode == -1 ? CANCEL : exitCode + (cb.isSelected() ? 1 : 0); } }); } public static int showCheckboxMessageDialog(String message, String title, String[] options, String checkboxText, final boolean checked, final int defaultOptionIndex, final int focusedOptionIndex, Icon icon, @Nullable final PairFunction<Integer, JCheckBox, Integer> exitFunc) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { TwoStepConfirmationDialog dialog = new TwoStepConfirmationDialog(message, title, options, checkboxText, checked, defaultOptionIndex, focusedOptionIndex, icon, exitFunc); dialog.show(); return dialog.getExitCode(); } } public static int showTwoStepConfirmationDialog(String message, String title, String checkboxText, Icon icon) { return showCheckboxMessageDialog(message, title, new String[]{OK_BUTTON}, checkboxText, true, -1, -1, icon, null); } public static void showErrorDialog(@Nullable Project project, @Nls String message, @Nls String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(title, message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); return; } showDialog(project, message, title, new String[]{OK_BUTTON}, 0, getErrorIcon()); } public static void showErrorDialog(Component component, String message, @Nls String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(title, message, OK_BUTTON, SwingUtilities.getWindowAncestor(component)); return; } showDialog(component, message, title, new String[]{OK_BUTTON}, 0, getErrorIcon()); } public static void showErrorDialog(Component component, String message) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getErrorTitle(), message, OK_BUTTON, SwingUtilities.getWindowAncestor(component)); return; } showDialog(component, message, CommonBundle.getErrorTitle(), new String[]{OK_BUTTON}, 0, getErrorIcon()); } /** * Use this method only if you do not know project or component * * @see #showErrorDialog(Project, String, String) * @see #showErrorDialog(Component, String, String) */ public static void showErrorDialog(String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getErrorTitle(), message, OK_BUTTON, null); return; } showDialog(message, title, new String[]{OK_BUTTON}, 0, getErrorIcon()); } public static void showWarningDialog(Project project, String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getWarningTitle(), message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); return; } showDialog(project, message, title, new String[]{OK_BUTTON}, 0, getWarningIcon()); } public static void showWarningDialog(Component component, String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getWarningTitle(), message, OK_BUTTON, SwingUtilities.getWindowAncestor(component)); return; } showDialog(component, message, title, new String[]{OK_BUTTON}, 0, getWarningIcon()); } /** * Use this method only if you do not know project or component * * @see #showWarningDialog(Project, String, String) * @see #showWarningDialog(Component, String, String) */ public static void showWarningDialog(String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getWarningTitle(), message, OK_BUTTON, null); return; } showDialog(message, title, new String[]{OK_BUTTON}, 0, getWarningIcon()); } public static int showYesNoCancelDialog(Project project, String message, String title, String yes, String no, String cancel, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoCancelDialog(title, message, yes, no, cancel, WindowManager.getInstance().suggestParentWindow(project), null); } return showDialog(project, message, title, new String[]{yes, no, cancel}, 0, icon); } public static int showYesNoCancelDialog(Project project, String message, String title, Icon icon) { return showYesNoCancelDialog(project, message, title, YES_BUTTON, NO_BUTTON, CANCEL_BUTTON, icon); } public static int showYesNoCancelDialog(Component parent, String message, String title, String yes, String no, String cancel, Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoCancelDialog(title, message, yes, no, cancel, SwingUtilities.getWindowAncestor(parent), null); } return showDialog(parent, message, title, new String[]{yes, no, cancel}, 0, icon); } public static int showYesNoCancelDialog(Component parent, String message, String title, Icon icon) { return showYesNoCancelDialog(parent, message, title, YES_BUTTON, NO_BUTTON, CANCEL_BUTTON, icon); } /** * Use this method only if you do not know project or component * * @see #showYesNoCancelDialog(Project, String, String, String, String, String, Icon) * @see #showYesNoCancelDialog(Component, String, String, String, String, String, Icon) */ public static int showYesNoCancelDialog(String message, String title, String yes, String no, String cancel, Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoCancelDialog(title, message, yes, no, cancel, null, doNotAskOption); } return showDialog(message, title, new String[]{yes, no, cancel}, 0, icon, doNotAskOption); } /** * Use this method only if you do not know project or component * * @see #showYesNoCancelDialog(Project, String, String, String, String, String, Icon) * @see #showYesNoCancelDialog(Component, String, String, String, String, String, Icon) */ public static int showYesNoCancelDialog(String message, String title, String yes, String no, String cancel, Icon icon) { return showYesNoCancelDialog(message, title, yes, no, cancel, icon, null); } /** * Use this method only if you do not know project or component * * @see #showYesNoCancelDialog(Project, String, String, Icon) * @see #showYesNoCancelDialog(Component, String, String, Icon) */ public static int showYesNoCancelDialog(String message, String title, Icon icon) { return showYesNoCancelDialog(message, title, YES_BUTTON, NO_BUTTON, CANCEL_BUTTON, icon); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showPasswordDialog(@Nls String message, @Nls String title) { return showPasswordDialog(null, message, title, null, null); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showPasswordDialog(Project project, @Nls String message, @Nls String title, @Nullable Icon icon) { return showPasswordDialog(project, message, title, icon, null); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showPasswordDialog(@Nullable Project project, @Nls String message, @Nls String title, @Nullable Icon icon, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } final InputDialog dialog = project != null ? new PasswordInputDialog(project, message, title, icon, validator) : new PasswordInputDialog(message, title, icon, validator); dialog.show(); return dialog.getInputString(); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showInputDialog(@Nullable Project project, String message, String title, @Nullable Icon icon) { return showInputDialog(project, message, title, icon, null, null); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showInputDialog(Component parent, String message, String title, @Nullable Icon icon) { return showInputDialog(parent, message, title, icon, null, null); } /** * Use this method only if you do not know project or component * * @see #showInputDialog(Project, String, String, Icon) * @see #showInputDialog(Component, String, String, Icon) */ @Nullable public static String showInputDialog(String message, String title, @Nullable Icon icon) { return showInputDialog(message, title, icon, null, null); } @Nullable public static String showInputDialog(@Nullable Project project, @Nls String message, @Nls String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { InputDialog dialog = new InputDialog(project, message, title, icon, initialValue, validator); dialog.show(); return dialog.getInputString(); } } @Nullable public static String showInputDialog(Project project, @Nls String message, @Nls String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator, @Nullable TextRange selection) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { InputDialog dialog = new InputDialog(project, message, title, icon, initialValue, validator); final JTextComponent field = dialog.getTextField(); if (selection != null) { // set custom selection field.select(selection.getStartOffset(), selection.getEndOffset()); } else { // reset selection final int length = field.getDocument().getLength(); field.select(length, length); } field.putClientProperty(DialogWrapperPeer.HAVE_INITIAL_SELECTION, true); dialog.show(); return dialog.getInputString(); } } @Nullable public static String showInputDialog(Component parent, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { InputDialog dialog = new InputDialog(parent, message, title, icon, initialValue, validator); dialog.show(); return dialog.getInputString(); } } /** * Use this method only if you do not know project or component * * @see #showInputDialog(Project, String, String, Icon, String, InputValidator) * @see #showInputDialog(Component, String, String, Icon, String, InputValidator) */ @Nullable public static String showInputDialog(String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { InputDialog dialog = new InputDialog(message, title, icon, initialValue, validator); dialog.show(); return dialog.getInputString(); } } @Nullable public static String showMultilineInputDialog(Project project, String message, String title, @Nullable String initialValue, @Nullable Icon icon, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } InputDialog dialog = new MultilineInputDialog(project, message, title, icon, initialValue, validator, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0); dialog.show(); return dialog.getInputString(); } @NotNull public static Pair<String, Boolean> showInputDialogWithCheckBox(String message, String title, String checkboxText, boolean checked, boolean checkboxEnabled, @Nullable Icon icon, @NonNls String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return new Pair<String, Boolean>(ourTestInputImplementation.show(message), checked); } else { InputDialogWithCheckbox dialog = new InputDialogWithCheckbox(message, title, checkboxText, checked, checkboxEnabled, icon, initialValue, validator); dialog.show(); return new Pair<String, Boolean>(dialog.getInputString(), dialog.isChecked()); } } @Nullable public static String showEditableChooseDialog(String message, String title, @Nullable Icon icon, String[] values, String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { ChooseDialog dialog = new ChooseDialog(message, title, icon, values, initialValue); dialog.setValidator(validator); dialog.getComboBox().setEditable(true); dialog.getComboBox().getEditor().setItem(initialValue); dialog.getComboBox().setSelectedItem(initialValue); dialog.show(); return dialog.getInputString(); } } /** @deprecated It looks awful! */ @Deprecated public static int showChooseDialog(String message, String title, String[] values, String initialValue, @Nullable Icon icon) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { ChooseDialog dialog = new ChooseDialog(message, title, icon, values, initialValue); dialog.show(); return dialog.getSelectedIndex(); } } /** @deprecated It looks awful! */ @Deprecated public static int showChooseDialog(Component parent, String message, String title, String[] values, String initialValue, Icon icon) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { ChooseDialog dialog = new ChooseDialog(parent, message, title, icon, values, initialValue); dialog.show(); return dialog.getSelectedIndex(); } } /** * @deprecated It looks awful! * @see com.intellij.openapi.ui.DialogWrapper#DialogWrapper(Project,boolean) */ @Deprecated public static int showChooseDialog(Project project, String message, String title, Icon icon, String[] values, String initialValue) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { ChooseDialog dialog = new ChooseDialog(project, message, title, icon, values, initialValue); dialog.show(); return dialog.getSelectedIndex(); } } /** * Shows dialog with given message and title, information icon {@link #getInformationIcon()} and OK button */ public static void showInfoMessage(Component component, String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, SwingUtilities.getWindowAncestor(component)); return; } showMessageDialog(component, message, title, getInformationIcon()); } /** * Shows dialog with given message and title, information icon {@link #getInformationIcon()} and OK button */ public static void showInfoMessage(@Nullable Project project, @Nls String message, @Nls String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); return; } showMessageDialog(project, message, title, getInformationIcon()); } /** * Shows dialog with given message and title, information icon {@link #getInformationIcon()} and OK button * * Use this method only if you do not know project or component * * @see #showInputDialog(Project, String, String, Icon, String, InputValidator) * @see #showInputDialog(Component, String, String, Icon, String, InputValidator) */ public static void showInfoMessage(String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, null); return; } showMessageDialog(message, title, getInformationIcon()); } /** * Shows dialog with text area to edit long strings that don't fit in text field. */ public static void showTextAreaDialog(final JTextField textField, final String title, @NonNls final String dimensionServiceKey) { if (isApplicationInUnitTestOrHeadless()) { ourTestImplementation.show(title); } else { final JTextArea textArea = new JTextArea(10, 50); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); List<String> lines = ParametersListUtil.parse(textField.getText(), true); textArea.setText(StringUtil.join(lines, "\n")); InsertPathAction.copyFromTo(textField, textArea); final DialogBuilder builder = new DialogBuilder(textField); builder.setDimensionServiceKey(dimensionServiceKey); builder.setCenterPanel(ScrollPaneFactory.createScrollPane(textArea)); builder.setPreferredFocusComponent(textArea); String rawText = title; if (StringUtil.endsWithChar(rawText, ':')) { rawText = rawText.substring(0, rawText.length() - 1); } builder.setTitle(rawText); builder.addOkAction(); builder.addCancelAction(); builder.setOkOperation(new Runnable() { @Override public void run() { textField.setText(textArea.getText()); builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); } }); builder.addDisposable(new TextComponentUndoProvider(textArea)); builder.show(); } } private static class MoreInfoMessageDialog extends MessageDialog { private final String myInfoText; public MoreInfoMessageDialog(Project project, String message, String title, String moreInfo, String[] options, int defaultOptionIndex, int focusedOptionIndex, Icon icon) { super(project); myInfoText = moreInfo; _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, null); } @Override protected JComponent createNorthPanel() { return doCreateCenterPanel(); } @Override protected JComponent createCenterPanel() { final JPanel panel = new JPanel(new BorderLayout()); final JTextArea area = new JTextArea(myInfoText); area.setEditable(false); final JBScrollPane scrollPane = new JBScrollPane(area) { @Override public Dimension getPreferredSize() { final Dimension preferredSize = super.getPreferredSize(); final Container parent = getParent(); if (parent != null) { return new Dimension(preferredSize.width, Math.min(150, preferredSize.height)); } return preferredSize; } }; panel.add(scrollPane); return panel; } } private static class MessageDialog extends DialogWrapper { protected String myMessage; protected String[] myOptions; protected int myDefaultOptionIndex; protected int myFocusedOptionIndex; protected Icon myIcon; public MessageDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, boolean canBeParent) { this(project, message, title, options, defaultOptionIndex, -1, icon, canBeParent); } public MessageDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DoNotAskOption doNotAskOption, boolean canBeParent) { super(project, canBeParent); _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, doNotAskOption); } public MessageDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, boolean canBeParent) { super(project, canBeParent); _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, null); } public MessageDialog(Component parent, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { this(parent, message, title, options, defaultOptionIndex, icon, false); } public MessageDialog(Component parent, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, boolean canBeParent) { this(parent, message, title, options, defaultOptionIndex, -1, icon, canBeParent); } public MessageDialog(Component parent, String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, boolean canBeParent) { super(parent, canBeParent); _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, null); } public MessageDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { this(message, title, options, defaultOptionIndex, icon, false); } public MessageDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, boolean canBeParent) { super(canBeParent); _init(title, message, options, defaultOptionIndex, -1, icon, null); } public MessageDialog(String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DoNotAskOption doNotAskOption) { super(false); _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, doNotAskOption); } public MessageDialog(String message, String title, String[] options, int defaultOptionIndex, Icon icon, DoNotAskOption doNotAskOption) { this(message, title, options, defaultOptionIndex, -1, icon, doNotAskOption); } protected MessageDialog() { super(false); } protected MessageDialog(Project project) { super(project, false); } protected void _init(String title, String message, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DoNotAskOption doNotAskOption) { setTitle(title); myMessage = message; myOptions = options; myDefaultOptionIndex = defaultOptionIndex; myFocusedOptionIndex = focusedOptionIndex; myIcon = icon; setButtonsAlignment(SwingConstants.CENTER); setDoNotAskOption(doNotAskOption); init(); } @NotNull @Override protected Action[] createActions() { Action[] actions = new Action[myOptions.length]; for (int i = 0; i < myOptions.length; i++) { String option = myOptions[i]; final int exitCode = i; actions[i] = new AbstractAction(UIUtil.replaceMnemonicAmpersand(option)) { @Override public void actionPerformed(ActionEvent e) { close(exitCode, true); } }; if (i == myDefaultOptionIndex) { actions[i].putValue(DEFAULT_ACTION, Boolean.TRUE); } if (i == myFocusedOptionIndex) { actions[i].putValue(FOCUSED_ACTION, Boolean.TRUE); } assignMnemonic(option, actions[i]); } return actions; } private static void assignMnemonic(String option, Action action) { int mnemoPos = option.indexOf("&"); if (mnemoPos >= 0 && mnemoPos < option.length() - 2) { String mnemoChar = option.substring(mnemoPos + 1, mnemoPos + 2).trim(); if (mnemoChar.length() == 1) { action.putValue(Action.MNEMONIC_KEY, new Integer(mnemoChar.charAt(0))); } } } @Override public void doCancelAction() { close(-1); } @Override protected JComponent createCenterPanel() { return doCreateCenterPanel(); } protected JComponent doCreateCenterPanel() { JPanel panel = new JPanel(new BorderLayout(15, 0)); if (myIcon != null) { JLabel iconLabel = new JLabel(myIcon); Container container = new Container(); container.setLayout(new BorderLayout()); container.add(iconLabel, BorderLayout.NORTH); panel.add(container, BorderLayout.WEST); } if (myMessage != null) { final JTextPane messageComponent = createMessageComponent(myMessage); final Dimension screenSize = messageComponent.getToolkit().getScreenSize(); final Dimension textSize = messageComponent.getPreferredSize(); if (myMessage.length() > 100) { final JScrollPane pane = ScrollPaneFactory.createScrollPane(messageComponent); pane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); final int scrollSize = (int)new JScrollBar(Adjustable.VERTICAL).getPreferredSize().getWidth(); final Dimension preferredSize = new Dimension(Math.min(textSize.width, screenSize.width / 2) + scrollSize, Math.min(textSize.height, screenSize.height / 3) + scrollSize); pane.setPreferredSize(preferredSize); panel.add(pane, BorderLayout.CENTER); } else { panel.add(messageComponent, BorderLayout.CENTER); } } return panel; } protected static JTextPane createMessageComponent(final String message) { final JTextPane messageComponent = new JTextPane(); return configureMessagePaneUi(messageComponent, message); } @Override protected void doHelpAction() { // do nothing } } public static void installHyperlinkSupport(JTextPane messageComponent) { configureMessagePaneUi(messageComponent, "<html></html>"); } public static JTextPane configureMessagePaneUi(JTextPane messageComponent, String message) { return configureMessagePaneUi(messageComponent, message, true); } public static JTextPane configureMessagePaneUi(JTextPane messageComponent, String message, final boolean addBrowserHyperlinkListener) { messageComponent.setFont(UIUtil.getLabelFont()); if (BasicHTML.isHTMLString(message)) { final HTMLEditorKit editorKit = new HTMLEditorKit(); editorKit.getStyleSheet().addRule(UIUtil.displayPropertiesToCSS(UIUtil.getLabelFont(), UIUtil.getLabelForeground())); messageComponent.setEditorKit(editorKit); messageComponent.setContentType(UIUtil.HTML_MIME); if (addBrowserHyperlinkListener) { messageComponent.addHyperlinkListener(new BrowserHyperlinkListener()); } } messageComponent.setText(message); messageComponent.setEditable(false); if (messageComponent.getCaret() != null) { messageComponent.setCaretPosition(0); } if (UIUtil.isUnderNimbusLookAndFeel()) { messageComponent.setOpaque(false); messageComponent.setBackground(UIUtil.TRANSPARENT_COLOR); } else { messageComponent.setBackground(UIUtil.getOptionPaneBackground()); } messageComponent.setForeground(UIUtil.getLabelForeground()); return messageComponent; } protected static class TwoStepConfirmationDialog extends MessageDialog { private JCheckBox myCheckBox; private final String myCheckboxText; private boolean myChecked; private PairFunction<Integer, JCheckBox, Integer> myExitFunc; public TwoStepConfirmationDialog(String message, String title, String[] options, String checkboxText, boolean checked, final int defaultOptionInxed, final int focusedOptionIndex, Icon icon, @Nullable final PairFunction<Integer, JCheckBox, Integer> exitFunc) { myCheckboxText = checkboxText; myChecked = checked; myExitFunc = exitFunc; _init(title, message, options, defaultOptionInxed, focusedOptionIndex, icon, null); } @Override protected JComponent createNorthPanel() { JPanel panel = new JPanel(new BorderLayout(15, 0)); if (myIcon != null) { JLabel iconLabel = new JLabel(myIcon); Container container = new Container(); container.setLayout(new BorderLayout()); container.add(iconLabel, BorderLayout.NORTH); panel.add(container, BorderLayout.WEST); } JPanel messagePanel = new JPanel(new BorderLayout()); if (myMessage != null) { JLabel textLabel = new JLabel(myMessage); textLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); textLabel.setUI(new MultiLineLabelUI()); messagePanel.add(textLabel, BorderLayout.NORTH); } final JPanel checkboxPanel = new JPanel(); checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.X_AXIS)); myCheckBox = new JCheckBox(myCheckboxText); myCheckBox.setSelected(myChecked); messagePanel.add(myCheckBox, BorderLayout.SOUTH); panel.add(messagePanel, BorderLayout.CENTER); return panel; } @Override public int getExitCode() { final int exitCode = super.getExitCode(); if (myExitFunc != null) { return myExitFunc.fun(exitCode, myCheckBox); } return exitCode == OK_EXIT_CODE ? myCheckBox.isSelected() ? OK_EXIT_CODE : CANCEL_EXIT_CODE : CANCEL_EXIT_CODE; } @Override public JComponent getPreferredFocusedComponent() { return myDefaultOptionIndex == -1 ? myCheckBox : super.getPreferredFocusedComponent(); } @Override protected JComponent createCenterPanel() { return null; } } protected static class InputDialog extends MessageDialog { protected JTextComponent myField; private final InputValidator myValidator; public InputDialog(@Nullable Project project, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator, String[] options, int defaultOption) { super(project, message, title, options, defaultOption, icon, true); myValidator = validator; myField.setText(initialValue); } public InputDialog(@Nullable Project project, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { this(project, message, title, icon, initialValue, validator, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0); } public InputDialog(Component parent, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { super(parent, message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0, icon, true); myValidator = validator; myField.setText(initialValue); } public InputDialog(String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { super(message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0, icon, true); myValidator = validator; myField.setText(initialValue); } @NotNull @Override protected Action[] createActions() { final Action[] actions = new Action[myOptions.length]; for (int i = 0; i < myOptions.length; i++) { String option = myOptions[i]; final int exitCode = i; if (i == 0) { // "OK" is default button. It has index 0. actions[i] = getOKAction(); actions[i].putValue(DEFAULT_ACTION, Boolean.TRUE); myField.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void textChanged(DocumentEvent event) { final String text = myField.getText().trim(); actions[exitCode].setEnabled(myValidator == null || myValidator.checkInput(text)); if (myValidator instanceof InputValidatorEx) { setErrorText(((InputValidatorEx) myValidator).getErrorText(text)); } } }); } else { actions[i] = new AbstractAction(option) { @Override public void actionPerformed(ActionEvent e) { close(exitCode); } }; } } return actions; } @Override protected void doOKAction() { String inputString = myField.getText().trim(); if (myValidator == null || myValidator.checkInput(inputString) && myValidator.canClose(inputString)) { close(0); } } @Override protected JComponent createCenterPanel() { return null; } @Override protected JComponent createNorthPanel() { JPanel panel = new JPanel(new BorderLayout(15, 0)); if (myIcon != null) { JLabel iconLabel = new JLabel(myIcon); Container container = new Container(); container.setLayout(new BorderLayout()); container.add(iconLabel, BorderLayout.NORTH); panel.add(container, BorderLayout.WEST); } JPanel messagePanel = createMessagePanel(); panel.add(messagePanel, BorderLayout.CENTER); return panel; } protected JPanel createMessagePanel() { JPanel messagePanel = new JPanel(new BorderLayout()); if (myMessage != null) { JComponent textComponent = createTextComponent(); messagePanel.add(textComponent, BorderLayout.NORTH); } myField = createTextFieldComponent(); messagePanel.add(myField, BorderLayout.SOUTH); return messagePanel; } protected JComponent createTextComponent() { JComponent textComponent; if (BasicHTML.isHTMLString(myMessage)) { textComponent = createMessageComponent(myMessage); } else { JLabel textLabel = new JLabel(myMessage); textLabel.setUI(new MultiLineLabelUI()); textComponent = textLabel; } textComponent.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); return textComponent; } public JTextComponent getTextField() { return myField; } protected JTextComponent createTextFieldComponent() { return new JTextField(30); } @Override public JComponent getPreferredFocusedComponent() { return myField; } @Nullable public String getInputString() { if (getExitCode() == 0) { return myField.getText().trim(); } else { return null; } } } protected static class MultilineInputDialog extends InputDialog { public MultilineInputDialog(Project project, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator, String[] options, int defaultOption) { super(project, message, title, icon, initialValue, validator, options, defaultOption); } @Override protected JTextComponent createTextFieldComponent() { return new JTextArea(7, 50); } } protected static class PasswordInputDialog extends InputDialog { public PasswordInputDialog(String message, String title, @Nullable Icon icon, @Nullable InputValidator validator) { super(message, title, icon, null, validator); } public PasswordInputDialog(Project project, String message, String title, @Nullable Icon icon, @Nullable InputValidator validator) { super(project, message, title, icon, null, validator); } @Override protected JTextComponent createTextFieldComponent() { return new JPasswordField(30); } } protected static class InputDialogWithCheckbox extends InputDialog { private JCheckBox myCheckBox; public InputDialogWithCheckbox(String message, String title, String checkboxText, boolean checked, boolean checkboxEnabled, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { super(message, title, icon, initialValue, validator); myCheckBox.setText(checkboxText); myCheckBox.setSelected(checked); myCheckBox.setEnabled(checkboxEnabled); } @Override protected JPanel createMessagePanel() { JPanel messagePanel = new JPanel(new BorderLayout()); if (myMessage != null) { JComponent textComponent = createTextComponent(); messagePanel.add(textComponent, BorderLayout.NORTH); } myField = createTextFieldComponent(); messagePanel.add(myField, BorderLayout.CENTER); myCheckBox = new JCheckBox(); messagePanel.add(myCheckBox, BorderLayout.SOUTH); return messagePanel; } public Boolean isChecked() { return myCheckBox.isSelected(); } } /** It looks awful! */ @Deprecated protected static class ChooseDialog extends MessageDialog { private ComboBox myComboBox; private InputValidator myValidator; public ChooseDialog(Project project, String message, String title, @Nullable Icon icon, String[] values, String initialValue, String[] options, int defaultOption) { super(project, message, title, options, defaultOption, icon, true); myComboBox.setModel(new DefaultComboBoxModel(values)); myComboBox.setSelectedItem(initialValue); } public ChooseDialog(Project project, String message, String title, @Nullable Icon icon, String[] values, String initialValue) { this(project, message, title, icon, values, initialValue, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0); } public ChooseDialog(Component parent, String message, String title, @Nullable Icon icon, String[] values, String initialValue) { super(parent, message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0, icon); myComboBox.setModel(new DefaultComboBoxModel(values)); myComboBox.setSelectedItem(initialValue); } public ChooseDialog(String message, String title, @Nullable Icon icon, String[] values, String initialValue) { super(message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0, icon); myComboBox.setModel(new DefaultComboBoxModel(values)); myComboBox.setSelectedItem(initialValue); } @NotNull @Override protected Action[] createActions() { final Action[] actions = new Action[myOptions.length]; for (int i = 0; i < myOptions.length; i++) { String option = myOptions[i]; final int exitCode = i; if (i == myDefaultOptionIndex) { actions[i] = new AbstractAction(option) { @Override public void actionPerformed(ActionEvent e) { if (myValidator == null || myValidator.checkInput(myComboBox.getSelectedItem().toString().trim())) { close(exitCode); } } }; actions[i].putValue(DEFAULT_ACTION, Boolean.TRUE); myComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { actions[exitCode].setEnabled(myValidator == null || myValidator.checkInput(myComboBox.getSelectedItem().toString().trim())); } }); final JTextField textField = (JTextField)myComboBox.getEditor().getEditorComponent(); textField.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void textChanged(DocumentEvent event) { actions[exitCode].setEnabled(myValidator == null || myValidator.checkInput(textField.getText().trim())); } }); } else { // "Cancel" action actions[i] = new AbstractAction(option) { @Override public void actionPerformed(ActionEvent e) { close(exitCode); } }; } } return actions; } @Override protected JComponent createCenterPanel() { return null; } @Override protected JComponent createNorthPanel() { JPanel panel = new JPanel(new BorderLayout(15, 0)); if (myIcon != null) { JLabel iconLabel = new JLabel(myIcon); Container container = new Container(); container.setLayout(new BorderLayout()); container.add(iconLabel, BorderLayout.NORTH); panel.add(container, BorderLayout.WEST); } JPanel messagePanel = new JPanel(new BorderLayout()); if (myMessage != null) { JLabel textLabel = new JLabel(myMessage); textLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); textLabel.setUI(new MultiLineLabelUI()); messagePanel.add(textLabel, BorderLayout.NORTH); } myComboBox = new ComboBox(220); messagePanel.add(myComboBox, BorderLayout.SOUTH); panel.add(messagePanel, BorderLayout.CENTER); return panel; } @Override protected void doOKAction() { String inputString = myComboBox.getSelectedItem().toString().trim(); if (myValidator == null || myValidator.checkInput(inputString) && myValidator.canClose(inputString)) { super.doOKAction(); } } @Override public JComponent getPreferredFocusedComponent() { return myComboBox; } @Nullable public String getInputString() { if (getExitCode() == 0) { return myComboBox.getSelectedItem().toString(); } else { return null; } } public int getSelectedIndex() { if (getExitCode() == 0) { return myComboBox.getSelectedIndex(); } else { return -1; } } public JComboBox getComboBox() { return myComboBox; } public void setValidator(@Nullable InputValidator validator) { myValidator = validator; } } }
platform/platform-api/src/com/intellij/openapi/ui/Messages.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.ui; import com.intellij.CommonBundle; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.WindowManager; import com.intellij.ui.*; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.mac.MacMessages; import com.intellij.util.PairFunction; import com.intellij.util.execution.ParametersListUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.*; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.plaf.basic.BasicHTML; import javax.swing.text.JTextComponent; import javax.swing.text.html.HTMLEditorKit; import java.awt.*; import java.awt.event.*; import java.util.List; public class Messages { public static final int OK = 0; public static final int YES = 0; public static final int NO = 1; public static final int CANCEL = 2; private static TestDialog ourTestImplementation = TestDialog.DEFAULT; private static TestInputDialog ourTestInputImplementation = TestInputDialog.DEFAULT; private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.ui.Messages"); protected static final String OK_BUTTON = CommonBundle.getOkButtonText(); protected static final String YES_BUTTON = CommonBundle.getYesButtonText(); protected static final String NO_BUTTON = CommonBundle.getNoButtonText(); protected static final String CANCEL_BUTTON = CommonBundle.getCancelButtonText(); @TestOnly public static TestDialog setTestDialog(TestDialog newValue) { Application application = ApplicationManager.getApplication(); if (application != null) { LOG.assertTrue(application.isUnitTestMode(), "This method is available for tests only"); } TestDialog oldValue = ourTestImplementation; ourTestImplementation = newValue; return oldValue; } @TestOnly public static TestInputDialog setTestInputDialog(TestInputDialog newValue) { Application application = ApplicationManager.getApplication(); if (application != null) { LOG.assertTrue(application.isUnitTestMode(), "This method is available for tests only"); } TestInputDialog oldValue = ourTestInputImplementation; ourTestInputImplementation = newValue; return oldValue; } public static Icon getErrorIcon() { return UIUtil.getErrorIcon(); } public static Icon getInformationIcon() { return UIUtil.getInformationIcon(); } public static Icon getWarningIcon() { return UIUtil.getWarningIcon(); } public static Icon getQuestionIcon() { return UIUtil.getQuestionIcon(); } /** * Please, use {@link #showOkCancelDialog} or {@link #showYesNoCancelDialog} if possible (these dialogs implements native OS behavior)! */ public static int showDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { return showDialog(project, message, title, options, defaultOptionIndex, icon, null); } /** * Please, use {@link #showOkCancelDialog} or {@link #showYesNoCancelDialog} if possible (these dialogs implements native OS behavior)! */ public static int showDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } if (canShowMacSheetPanel()) { return MacMessages.getInstance() .showMessageDialog(title, message, options, false, WindowManager.getInstance().suggestParentWindow(project), defaultOptionIndex, defaultOptionIndex, doNotAskOption); } return showIdeaMessageDialog(project, message, title, options, defaultOptionIndex, icon, doNotAskOption); } public static int showIdeaMessageDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { MessageDialog dialog = new MessageDialog(project, message, title, options, defaultOptionIndex, -1, icon, doNotAskOption, false); dialog.show(); return dialog.getExitCode(); } public static boolean canShowMacSheetPanel() { return SystemInfo.isMac && !isApplicationInUnitTestOrHeadless() && Registry.is("ide.mac.message.dialogs.as.sheets") && !DialogWrapper.isMultipleModalDialogs(); } public static int showDialog(Project project, String message, String title, String moreInfo, String[] options, int defaultOptionIndex, int focusedOptionIndex, Icon icon) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } if (canShowMacSheetPanel() && moreInfo == null) { return MacMessages.getInstance() .showMessageDialog(title, message, options, false, WindowManager.getInstance().suggestParentWindow(project), defaultOptionIndex, focusedOptionIndex, null); } MessageDialog dialog = new MoreInfoMessageDialog(project, message, title, moreInfo, options, defaultOptionIndex, focusedOptionIndex, icon); dialog.show(); return dialog.getExitCode(); } private static boolean isApplicationInUnitTestOrHeadless(){ final Application application = ApplicationManager.getApplication(); return application != null && (application.isUnitTestMode() || application.isHeadlessEnvironment()); } public static int showDialog(Component parent, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { if (canShowMacSheetPanel()) { return MacMessages.getInstance() .showMessageDialog(title, message, options, false, SwingUtilities.getWindowAncestor(parent), defaultOptionIndex, defaultOptionIndex, null); } MessageDialog dialog = new MessageDialog(parent, message, title, options, defaultOptionIndex, defaultOptionIndex, icon, false); dialog.show(); return dialog.getExitCode(); } } /** * Use this method only if you do not know project or component * * @see #showDialog(Project, String, String, String[], int, Icon, DialogWrapper.DoNotAskOption) * @see #showDialog(Component, String, String, String[], int, Icon) */ public static int showDialog(String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showMessageDialog(title, message, options, false, null, defaultOptionIndex, focusedOptionIndex, doNotAskOption); } //what's it? if (application.isUnitTestMode()) throw new RuntimeException(message); MessageDialog dialog = new MessageDialog(message, title, options, defaultOptionIndex, focusedOptionIndex, icon, doNotAskOption); dialog.show(); return dialog.getExitCode(); } } /** * Use this method only if you do not know project or component * * @see #showDialog(Project, String, String, String[], int, Icon) * @see #showDialog(Component, String, String, String[], int, Icon) */ public static int showDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { return showDialog(message, title, options, defaultOptionIndex, defaultOptionIndex, icon, doNotAskOption); } /** * Use this method only if you do not know project or component * * @see #showDialog(Project, String, String, String[], int, Icon) * @see #showDialog(Component, String, String, String[], int, Icon) */ public static int showDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { return showDialog(message, title, options, defaultOptionIndex, icon, null); } /** * @see com.intellij.openapi.ui.DialogWrapper#DialogWrapper(Project,boolean) */ public static void showMessageDialog(@Nullable Project project, String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); return; } showDialog(project, message, title, new String[]{OK_BUTTON}, 0, icon); } public static void showMessageDialog(Component parent, String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, SwingUtilities.getWindowAncestor(parent)); return; } showDialog(parent, message, title, new String[]{OK_BUTTON}, 0, icon); } /** * Use this method only if you do not know project or component * * @see #showMessageDialog(Project, String, String, Icon) * @see #showMessageDialog(Component, String, String, Icon) */ public static void showMessageDialog(String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON); return; } showDialog(message, title, new String[]{OK_BUTTON}, 0, icon); } /** * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. */ public static int showYesNoDialog(@Nullable Project project, String message, String title, String yesText, String noText, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, yesText, noText, WindowManager.getInstance().suggestParentWindow(project)); } return showDialog(project, message, title, new String[]{yesText, noText}, 0, icon); } /** * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. */ public static int showYesNoDialog(@Nullable Project project, String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, YES_BUTTON, NO_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); } return showYesNoDialog(project, message, title, YES_BUTTON, NO_BUTTON, icon); } /** * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. */ public static int showYesNoDialog(Component parent, String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, YES_BUTTON, NO_BUTTON, SwingUtilities.getWindowAncestor(parent)); } return showDialog(parent, message, title, new String[]{YES_BUTTON, NO_BUTTON}, 0, icon); } /** * Use this method only if you do not know project or component * * @see #showYesNoDialog(com.intellij.openapi.project.Project, String, String, javax.swing.Icon) * @see #showYesNoCancelDialog(java.awt.Component, String, String, javax.swing.Icon) */ public static int showYesNoDialog(String message, String title, String yesText, String noText, @Nullable Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, yesText, noText, null, doNotAskOption); } return showDialog(message, title, new String[]{yesText, noText}, 0, icon, doNotAskOption); } /** * Use this method only if you do not know project or component * * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. * @see #showYesNoDialog(Project, String, String, String, String, Icon) * @see #showYesNoDialog(java.awt.Component, String, String, javax.swing.Icon) */ public static int showYesNoDialog(String message, String title, String yesText, String noText, @Nullable Icon icon) { return showYesNoDialog(message, title, yesText, noText, icon, null); } /** * Use this method only if you do not know project or component * * @return <code>0</code> if user pressed "Yes" and returns <code>1</code> if user pressed "No" button. * @see #showYesNoDialog(Project, String, String, Icon) * @see #showYesNoDialog(Component, String, String, Icon) */ public static int showYesNoDialog(String message, String title, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, YES_BUTTON, NO_BUTTON, null); } return showYesNoDialog(message, title, YES_BUTTON, NO_BUTTON, icon); } public static int showOkCancelDialog(Project project, String message, String title, String okText, String cancelText, Icon icon, DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, WindowManager.getInstance().suggestParentWindow(project), doNotAskOption); } return showDialog(project, message, title, new String[]{okText, cancelText}, 0, icon, doNotAskOption); } public static int showOkCancelDialog(Project project, String message, String title, String okText, String cancelText, Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, WindowManager.getInstance().suggestParentWindow(project)); } return showDialog(project, message, title, new String[]{okText, cancelText}, 0, icon); } public static int showOkCancelDialog(Project project, String message, String title, Icon icon) { return showOkCancelDialog(project, message, title, OK_BUTTON, CANCEL_BUTTON, icon); } public static int showOkCancelDialog(Component parent, String message, String title, String okText, String cancelText, Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, SwingUtilities.getWindowAncestor(parent)); } return showDialog(parent, message, title, new String[]{okText, cancelText}, 0, icon); } public static int showOkCancelDialog(Component parent, String message, String title, Icon icon) { return showOkCancelDialog(parent, message, title, OK_BUTTON, CANCEL_BUTTON, icon); } /** * Use this method only if you do not know project or component * * @see #showOkCancelDialog(Project, String, String, Icon) * @see #showOkCancelDialog(Component, String, String, Icon) */ public static int showOkCancelDialog(String message, String title, Icon icon) { return showOkCancelDialog(message, title, OK_BUTTON, CANCEL_BUTTON, icon, null); } /** * Use this method only if you do not know project or component * * @see #showOkCancelDialog(Project, String, String, String, String, Icon) * @see #showOkCancelDialog(Component, String, String, String, String, Icon) */ public static int showOkCancelDialog(String message, String title, String okText, String cancelText, Icon icon) { return showOkCancelDialog(message, title, okText, cancelText, icon, null); } /** * Use this method only if you do not know project or component * * @see #showOkCancelDialog(Project, String, String, String, String, Icon, DialogWrapper.DoNotAskOption) * @see #showOkCancelDialog(Component, String, String, String, String, Icon) */ public static int showOkCancelDialog(String message, String title, String okText, String cancelText, Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoDialog(title, message, okText, cancelText, null, doNotAskOption); } return showDialog(message, title, new String[]{okText, cancelText}, 0, icon, doNotAskOption); } public static int showCheckboxOkCancelDialog(String message, String title, String checkboxText, final boolean checked, final int defaultOptionIndex, final int focusedOptionIndex, Icon icon) { return showCheckboxMessageDialog(message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, checkboxText, checked, defaultOptionIndex, focusedOptionIndex, icon, new PairFunction<Integer, JCheckBox, Integer>() { @Override public Integer fun(final Integer exitCode, final JCheckBox cb) { return exitCode == -1 ? CANCEL : exitCode + (cb.isSelected() ? 1 : 0); } }); } public static int showCheckboxMessageDialog(String message, String title, String[] options, String checkboxText, final boolean checked, final int defaultOptionIndex, final int focusedOptionIndex, Icon icon, @Nullable final PairFunction<Integer, JCheckBox, Integer> exitFunc) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { TwoStepConfirmationDialog dialog = new TwoStepConfirmationDialog(message, title, options, checkboxText, checked, defaultOptionIndex, focusedOptionIndex, icon, exitFunc); dialog.show(); return dialog.getExitCode(); } } public static int showTwoStepConfirmationDialog(String message, String title, String checkboxText, Icon icon) { return showCheckboxMessageDialog(message, title, new String[]{OK_BUTTON}, checkboxText, true, -1, -1, icon, null); } public static void showErrorDialog(@Nullable Project project, @Nls String message, @Nls String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(title, message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); return; } showDialog(project, message, title, new String[]{OK_BUTTON}, 0, getErrorIcon()); } public static void showErrorDialog(Component component, String message, @Nls String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(title, message, OK_BUTTON, SwingUtilities.getWindowAncestor(component)); return; } showDialog(component, message, title, new String[]{OK_BUTTON}, 0, getErrorIcon()); } public static void showErrorDialog(Component component, String message) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getErrorTitle(), message, OK_BUTTON, SwingUtilities.getWindowAncestor(component)); return; } showDialog(component, message, CommonBundle.getErrorTitle(), new String[]{OK_BUTTON}, 0, getErrorIcon()); } /** * Use this method only if you do not know project or component * * @see #showErrorDialog(Project, String, String) * @see #showErrorDialog(Component, String, String) */ public static void showErrorDialog(String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getErrorTitle(), message, OK_BUTTON, null); return; } showDialog(message, title, new String[]{OK_BUTTON}, 0, getErrorIcon()); } public static void showWarningDialog(Project project, String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getWarningTitle(), message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); return; } showDialog(project, message, title, new String[]{OK_BUTTON}, 0, getWarningIcon()); } public static void showWarningDialog(Component component, String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getWarningTitle(), message, OK_BUTTON, SwingUtilities.getWindowAncestor(component)); return; } showDialog(component, message, title, new String[]{OK_BUTTON}, 0, getWarningIcon()); } /** * Use this method only if you do not know project or component * * @see #showWarningDialog(Project, String, String) * @see #showWarningDialog(Component, String, String) */ public static void showWarningDialog(String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showErrorDialog(CommonBundle.getWarningTitle(), message, OK_BUTTON, null); return; } showDialog(message, title, new String[]{OK_BUTTON}, 0, getWarningIcon()); } public static int showYesNoCancelDialog(Project project, String message, String title, String yes, String no, String cancel, @Nullable Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoCancelDialog(title, message, yes, no, cancel, WindowManager.getInstance().suggestParentWindow(project), null); } return showDialog(project, message, title, new String[]{yes, no, cancel}, 0, icon); } public static int showYesNoCancelDialog(Project project, String message, String title, Icon icon) { return showYesNoCancelDialog(project, message, title, YES_BUTTON, NO_BUTTON, CANCEL_BUTTON, icon); } public static int showYesNoCancelDialog(Component parent, String message, String title, String yes, String no, String cancel, Icon icon) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoCancelDialog(title, message, yes, no, cancel, SwingUtilities.getWindowAncestor(parent), null); } return showDialog(parent, message, title, new String[]{yes, no, cancel}, 0, icon); } public static int showYesNoCancelDialog(Component parent, String message, String title, Icon icon) { return showYesNoCancelDialog(parent, message, title, YES_BUTTON, NO_BUTTON, CANCEL_BUTTON, icon); } /** * Use this method only if you do not know project or component * * @see #showYesNoCancelDialog(Project, String, String, String, String, String, Icon) * @see #showYesNoCancelDialog(Component, String, String, String, String, String, Icon) */ public static int showYesNoCancelDialog(String message, String title, String yes, String no, String cancel, Icon icon, @Nullable DialogWrapper.DoNotAskOption doNotAskOption) { if (canShowMacSheetPanel()) { return MacMessages.getInstance().showYesNoCancelDialog(title, message, yes, no, cancel, null, doNotAskOption); } return showDialog(message, title, new String[]{yes, no, cancel}, 0, icon, doNotAskOption); } /** * Use this method only if you do not know project or component * * @see #showYesNoCancelDialog(Project, String, String, String, String, String, Icon) * @see #showYesNoCancelDialog(Component, String, String, String, String, String, Icon) */ public static int showYesNoCancelDialog(String message, String title, String yes, String no, String cancel, Icon icon) { return showYesNoCancelDialog(message, title, yes, no, cancel, icon, null); } /** * Use this method only if you do not know project or component * * @see #showYesNoCancelDialog(Project, String, String, Icon) * @see #showYesNoCancelDialog(Component, String, String, Icon) */ public static int showYesNoCancelDialog(String message, String title, Icon icon) { return showYesNoCancelDialog(message, title, YES_BUTTON, NO_BUTTON, CANCEL_BUTTON, icon); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showPasswordDialog(@Nls String message, @Nls String title) { return showPasswordDialog(null, message, title, null, null); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showPasswordDialog(Project project, @Nls String message, @Nls String title, @Nullable Icon icon) { return showPasswordDialog(project, message, title, icon, null); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showPasswordDialog(@Nullable Project project, @Nls String message, @Nls String title, @Nullable Icon icon, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } final InputDialog dialog = project != null ? new PasswordInputDialog(project, message, title, icon, validator) : new PasswordInputDialog(message, title, icon, validator); dialog.show(); return dialog.getInputString(); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showInputDialog(@Nullable Project project, String message, String title, @Nullable Icon icon) { return showInputDialog(project, message, title, icon, null, null); } /** * @return trimmed input string or <code>null</code> if user cancelled dialog. */ @Nullable public static String showInputDialog(Component parent, String message, String title, @Nullable Icon icon) { return showInputDialog(parent, message, title, icon, null, null); } /** * Use this method only if you do not know project or component * * @see #showInputDialog(Project, String, String, Icon) * @see #showInputDialog(Component, String, String, Icon) */ @Nullable public static String showInputDialog(String message, String title, @Nullable Icon icon) { return showInputDialog(message, title, icon, null, null); } @Nullable public static String showInputDialog(@Nullable Project project, @Nls String message, @Nls String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { InputDialog dialog = new InputDialog(project, message, title, icon, initialValue, validator); dialog.show(); return dialog.getInputString(); } } @Nullable public static String showInputDialog(Project project, @Nls String message, @Nls String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator, @Nullable TextRange selection) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { InputDialog dialog = new InputDialog(project, message, title, icon, initialValue, validator); final JTextComponent field = dialog.getTextField(); if (selection != null) { // set custom selection field.select(selection.getStartOffset(), selection.getEndOffset()); } else { // reset selection final int length = field.getDocument().getLength(); field.select(length, length); } field.putClientProperty(DialogWrapperPeer.HAVE_INITIAL_SELECTION, true); dialog.show(); return dialog.getInputString(); } } @Nullable public static String showInputDialog(Component parent, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { InputDialog dialog = new InputDialog(parent, message, title, icon, initialValue, validator); dialog.show(); return dialog.getInputString(); } } /** * Use this method only if you do not know project or component * * @see #showInputDialog(Project, String, String, Icon, String, InputValidator) * @see #showInputDialog(Component, String, String, Icon, String, InputValidator) */ @Nullable public static String showInputDialog(String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { InputDialog dialog = new InputDialog(message, title, icon, initialValue, validator); dialog.show(); return dialog.getInputString(); } } @Nullable public static String showMultilineInputDialog(Project project, String message, String title, @Nullable String initialValue, @Nullable Icon icon, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } InputDialog dialog = new MultilineInputDialog(project, message, title, icon, initialValue, validator, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0); dialog.show(); return dialog.getInputString(); } @NotNull public static Pair<String, Boolean> showInputDialogWithCheckBox(String message, String title, String checkboxText, boolean checked, boolean checkboxEnabled, @Nullable Icon icon, @NonNls String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return new Pair<String, Boolean>(ourTestInputImplementation.show(message), checked); } else { InputDialogWithCheckbox dialog = new InputDialogWithCheckbox(message, title, checkboxText, checked, checkboxEnabled, icon, initialValue, validator); dialog.show(); return new Pair<String, Boolean>(dialog.getInputString(), dialog.isChecked()); } } @Nullable public static String showEditableChooseDialog(String message, String title, @Nullable Icon icon, String[] values, String initialValue, @Nullable InputValidator validator) { if (isApplicationInUnitTestOrHeadless()) { return ourTestInputImplementation.show(message); } else { ChooseDialog dialog = new ChooseDialog(message, title, icon, values, initialValue); dialog.setValidator(validator); dialog.getComboBox().setEditable(true); dialog.getComboBox().getEditor().setItem(initialValue); dialog.getComboBox().setSelectedItem(initialValue); dialog.show(); return dialog.getInputString(); } } public static int showChooseDialog(String message, String title, String[] values, String initialValue, @Nullable Icon icon) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { ChooseDialog dialog = new ChooseDialog(message, title, icon, values, initialValue); dialog.show(); return dialog.getSelectedIndex(); } } public static int showChooseDialog(Component parent, String message, String title, String[] values, String initialValue, Icon icon) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { ChooseDialog dialog = new ChooseDialog(parent, message, title, icon, values, initialValue); dialog.show(); return dialog.getSelectedIndex(); } } /** * @deprecated It looks awful! * @see com.intellij.openapi.ui.DialogWrapper#DialogWrapper(Project,boolean) */ @Deprecated public static int showChooseDialog(Project project, String message, String title, Icon icon, String[] values, String initialValue) { if (isApplicationInUnitTestOrHeadless()) { return ourTestImplementation.show(message); } else { ChooseDialog dialog = new ChooseDialog(project, message, title, icon, values, initialValue); dialog.show(); return dialog.getSelectedIndex(); } } /** * Shows dialog with given message and title, information icon {@link #getInformationIcon()} and OK button */ public static void showInfoMessage(Component component, String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, SwingUtilities.getWindowAncestor(component)); return; } showMessageDialog(component, message, title, getInformationIcon()); } /** * Shows dialog with given message and title, information icon {@link #getInformationIcon()} and OK button */ public static void showInfoMessage(@Nullable Project project, @Nls String message, @Nls String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project)); return; } showMessageDialog(project, message, title, getInformationIcon()); } /** * Shows dialog with given message and title, information icon {@link #getInformationIcon()} and OK button * * Use this method only if you do not know project or component * * @see #showInputDialog(Project, String, String, Icon, String, InputValidator) * @see #showInputDialog(Component, String, String, Icon, String, InputValidator) */ public static void showInfoMessage(String message, String title) { if (canShowMacSheetPanel()) { MacMessages.getInstance().showOkMessageDialog(title, message, OK_BUTTON, null); return; } showMessageDialog(message, title, getInformationIcon()); } /** * Shows dialog with text area to edit long strings that don't fit in text field. */ public static void showTextAreaDialog(final JTextField textField, final String title, @NonNls final String dimensionServiceKey) { if (isApplicationInUnitTestOrHeadless()) { ourTestImplementation.show(title); } else { final JTextArea textArea = new JTextArea(10, 50); textArea.setWrapStyleWord(true); textArea.setLineWrap(true); List<String> lines = ParametersListUtil.parse(textField.getText(), true); textArea.setText(StringUtil.join(lines, "\n")); InsertPathAction.copyFromTo(textField, textArea); final DialogBuilder builder = new DialogBuilder(textField); builder.setDimensionServiceKey(dimensionServiceKey); builder.setCenterPanel(ScrollPaneFactory.createScrollPane(textArea)); builder.setPreferredFocusComponent(textArea); String rawText = title; if (StringUtil.endsWithChar(rawText, ':')) { rawText = rawText.substring(0, rawText.length() - 1); } builder.setTitle(rawText); builder.addOkAction(); builder.addCancelAction(); builder.setOkOperation(new Runnable() { @Override public void run() { textField.setText(textArea.getText()); builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE); } }); builder.addDisposable(new TextComponentUndoProvider(textArea)); builder.show(); } } private static class MoreInfoMessageDialog extends MessageDialog { private final String myInfoText; public MoreInfoMessageDialog(Project project, String message, String title, String moreInfo, String[] options, int defaultOptionIndex, int focusedOptionIndex, Icon icon) { super(project); myInfoText = moreInfo; _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, null); } @Override protected JComponent createNorthPanel() { return doCreateCenterPanel(); } @Override protected JComponent createCenterPanel() { final JPanel panel = new JPanel(new BorderLayout()); final JTextArea area = new JTextArea(myInfoText); area.setEditable(false); final JBScrollPane scrollPane = new JBScrollPane(area) { @Override public Dimension getPreferredSize() { final Dimension preferredSize = super.getPreferredSize(); final Container parent = getParent(); if (parent != null) { return new Dimension(preferredSize.width, Math.min(150, preferredSize.height)); } return preferredSize; } }; panel.add(scrollPane); return panel; } } private static class MessageDialog extends DialogWrapper { protected String myMessage; protected String[] myOptions; protected int myDefaultOptionIndex; protected int myFocusedOptionIndex; protected Icon myIcon; public MessageDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, boolean canBeParent) { this(project, message, title, options, defaultOptionIndex, -1, icon, canBeParent); } public MessageDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DoNotAskOption doNotAskOption, boolean canBeParent) { super(project, canBeParent); _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, doNotAskOption); } public MessageDialog(@Nullable Project project, String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, boolean canBeParent) { super(project, canBeParent); _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, null); } public MessageDialog(Component parent, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { this(parent, message, title, options, defaultOptionIndex, icon, false); } public MessageDialog(Component parent, String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, boolean canBeParent) { this(parent, message, title, options, defaultOptionIndex, -1, icon, canBeParent); } public MessageDialog(Component parent, String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, boolean canBeParent) { super(parent, canBeParent); _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, null); } public MessageDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon) { this(message, title, options, defaultOptionIndex, icon, false); } public MessageDialog(String message, String title, String[] options, int defaultOptionIndex, @Nullable Icon icon, boolean canBeParent) { super(canBeParent); _init(title, message, options, defaultOptionIndex, -1, icon, null); } public MessageDialog(String message, String title, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DoNotAskOption doNotAskOption) { super(false); _init(title, message, options, defaultOptionIndex, focusedOptionIndex, icon, doNotAskOption); } public MessageDialog(String message, String title, String[] options, int defaultOptionIndex, Icon icon, DoNotAskOption doNotAskOption) { this(message, title, options, defaultOptionIndex, -1, icon, doNotAskOption); } protected MessageDialog() { super(false); } protected MessageDialog(Project project) { super(project, false); } protected void _init(String title, String message, String[] options, int defaultOptionIndex, int focusedOptionIndex, @Nullable Icon icon, @Nullable DoNotAskOption doNotAskOption) { setTitle(title); myMessage = message; myOptions = options; myDefaultOptionIndex = defaultOptionIndex; myFocusedOptionIndex = focusedOptionIndex; myIcon = icon; setButtonsAlignment(SwingConstants.CENTER); setDoNotAskOption(doNotAskOption); init(); } @NotNull @Override protected Action[] createActions() { Action[] actions = new Action[myOptions.length]; for (int i = 0; i < myOptions.length; i++) { String option = myOptions[i]; final int exitCode = i; actions[i] = new AbstractAction(UIUtil.replaceMnemonicAmpersand(option)) { @Override public void actionPerformed(ActionEvent e) { close(exitCode, true); } }; if (i == myDefaultOptionIndex) { actions[i].putValue(DEFAULT_ACTION, Boolean.TRUE); } if (i == myFocusedOptionIndex) { actions[i].putValue(FOCUSED_ACTION, Boolean.TRUE); } assignMnemonic(option, actions[i]); } return actions; } private static void assignMnemonic(String option, Action action) { int mnemoPos = option.indexOf("&"); if (mnemoPos >= 0 && mnemoPos < option.length() - 2) { String mnemoChar = option.substring(mnemoPos + 1, mnemoPos + 2).trim(); if (mnemoChar.length() == 1) { action.putValue(Action.MNEMONIC_KEY, new Integer(mnemoChar.charAt(0))); } } } @Override public void doCancelAction() { close(-1); } @Override protected JComponent createCenterPanel() { return doCreateCenterPanel(); } protected JComponent doCreateCenterPanel() { JPanel panel = new JPanel(new BorderLayout(15, 0)); if (myIcon != null) { JLabel iconLabel = new JLabel(myIcon); Container container = new Container(); container.setLayout(new BorderLayout()); container.add(iconLabel, BorderLayout.NORTH); panel.add(container, BorderLayout.WEST); } if (myMessage != null) { final JTextPane messageComponent = createMessageComponent(myMessage); final Dimension screenSize = messageComponent.getToolkit().getScreenSize(); final Dimension textSize = messageComponent.getPreferredSize(); if (myMessage.length() > 100) { final JScrollPane pane = ScrollPaneFactory.createScrollPane(messageComponent); pane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); pane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); final int scrollSize = (int)new JScrollBar(Adjustable.VERTICAL).getPreferredSize().getWidth(); final Dimension preferredSize = new Dimension(Math.min(textSize.width, screenSize.width / 2) + scrollSize, Math.min(textSize.height, screenSize.height / 3) + scrollSize); pane.setPreferredSize(preferredSize); panel.add(pane, BorderLayout.CENTER); } else { panel.add(messageComponent, BorderLayout.CENTER); } } return panel; } protected static JTextPane createMessageComponent(final String message) { final JTextPane messageComponent = new JTextPane(); return configureMessagePaneUi(messageComponent, message); } @Override protected void doHelpAction() { // do nothing } } public static void installHyperlinkSupport(JTextPane messageComponent) { configureMessagePaneUi(messageComponent, "<html></html>"); } public static JTextPane configureMessagePaneUi(JTextPane messageComponent, String message) { return configureMessagePaneUi(messageComponent, message, true); } public static JTextPane configureMessagePaneUi(JTextPane messageComponent, String message, final boolean addBrowserHyperlinkListener) { messageComponent.setFont(UIUtil.getLabelFont()); if (BasicHTML.isHTMLString(message)) { final HTMLEditorKit editorKit = new HTMLEditorKit(); editorKit.getStyleSheet().addRule(UIUtil.displayPropertiesToCSS(UIUtil.getLabelFont(), UIUtil.getLabelForeground())); messageComponent.setEditorKit(editorKit); messageComponent.setContentType(UIUtil.HTML_MIME); if (addBrowserHyperlinkListener) { messageComponent.addHyperlinkListener(new BrowserHyperlinkListener()); } } messageComponent.setText(message); messageComponent.setEditable(false); if (messageComponent.getCaret() != null) { messageComponent.setCaretPosition(0); } if (UIUtil.isUnderNimbusLookAndFeel()) { messageComponent.setOpaque(false); messageComponent.setBackground(UIUtil.TRANSPARENT_COLOR); } else { messageComponent.setBackground(UIUtil.getOptionPaneBackground()); } messageComponent.setForeground(UIUtil.getLabelForeground()); return messageComponent; } protected static class TwoStepConfirmationDialog extends MessageDialog { private JCheckBox myCheckBox; private final String myCheckboxText; private boolean myChecked; private PairFunction<Integer, JCheckBox, Integer> myExitFunc; public TwoStepConfirmationDialog(String message, String title, String[] options, String checkboxText, boolean checked, final int defaultOptionInxed, final int focusedOptionIndex, Icon icon, @Nullable final PairFunction<Integer, JCheckBox, Integer> exitFunc) { myCheckboxText = checkboxText; myChecked = checked; myExitFunc = exitFunc; _init(title, message, options, defaultOptionInxed, focusedOptionIndex, icon, null); } @Override protected JComponent createNorthPanel() { JPanel panel = new JPanel(new BorderLayout(15, 0)); if (myIcon != null) { JLabel iconLabel = new JLabel(myIcon); Container container = new Container(); container.setLayout(new BorderLayout()); container.add(iconLabel, BorderLayout.NORTH); panel.add(container, BorderLayout.WEST); } JPanel messagePanel = new JPanel(new BorderLayout()); if (myMessage != null) { JLabel textLabel = new JLabel(myMessage); textLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); textLabel.setUI(new MultiLineLabelUI()); messagePanel.add(textLabel, BorderLayout.NORTH); } final JPanel checkboxPanel = new JPanel(); checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.X_AXIS)); myCheckBox = new JCheckBox(myCheckboxText); myCheckBox.setSelected(myChecked); messagePanel.add(myCheckBox, BorderLayout.SOUTH); panel.add(messagePanel, BorderLayout.CENTER); return panel; } @Override public int getExitCode() { final int exitCode = super.getExitCode(); if (myExitFunc != null) { return myExitFunc.fun(exitCode, myCheckBox); } return exitCode == OK_EXIT_CODE ? myCheckBox.isSelected() ? OK_EXIT_CODE : CANCEL_EXIT_CODE : CANCEL_EXIT_CODE; } @Override public JComponent getPreferredFocusedComponent() { return myDefaultOptionIndex == -1 ? myCheckBox : super.getPreferredFocusedComponent(); } @Override protected JComponent createCenterPanel() { return null; } } protected static class InputDialog extends MessageDialog { protected JTextComponent myField; private final InputValidator myValidator; public InputDialog(@Nullable Project project, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator, String[] options, int defaultOption) { super(project, message, title, options, defaultOption, icon, true); myValidator = validator; myField.setText(initialValue); } public InputDialog(@Nullable Project project, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { this(project, message, title, icon, initialValue, validator, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0); } public InputDialog(Component parent, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { super(parent, message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0, icon, true); myValidator = validator; myField.setText(initialValue); } public InputDialog(String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { super(message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0, icon, true); myValidator = validator; myField.setText(initialValue); } @NotNull @Override protected Action[] createActions() { final Action[] actions = new Action[myOptions.length]; for (int i = 0; i < myOptions.length; i++) { String option = myOptions[i]; final int exitCode = i; if (i == 0) { // "OK" is default button. It has index 0. actions[i] = getOKAction(); actions[i].putValue(DEFAULT_ACTION, Boolean.TRUE); myField.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void textChanged(DocumentEvent event) { final String text = myField.getText().trim(); actions[exitCode].setEnabled(myValidator == null || myValidator.checkInput(text)); if (myValidator instanceof InputValidatorEx) { setErrorText(((InputValidatorEx) myValidator).getErrorText(text)); } } }); } else { actions[i] = new AbstractAction(option) { @Override public void actionPerformed(ActionEvent e) { close(exitCode); } }; } } return actions; } @Override protected void doOKAction() { String inputString = myField.getText().trim(); if (myValidator == null || myValidator.checkInput(inputString) && myValidator.canClose(inputString)) { close(0); } } @Override protected JComponent createCenterPanel() { return null; } @Override protected JComponent createNorthPanel() { JPanel panel = new JPanel(new BorderLayout(15, 0)); if (myIcon != null) { JLabel iconLabel = new JLabel(myIcon); Container container = new Container(); container.setLayout(new BorderLayout()); container.add(iconLabel, BorderLayout.NORTH); panel.add(container, BorderLayout.WEST); } JPanel messagePanel = createMessagePanel(); panel.add(messagePanel, BorderLayout.CENTER); return panel; } protected JPanel createMessagePanel() { JPanel messagePanel = new JPanel(new BorderLayout()); if (myMessage != null) { JComponent textComponent = createTextComponent(); messagePanel.add(textComponent, BorderLayout.NORTH); } myField = createTextFieldComponent(); messagePanel.add(myField, BorderLayout.SOUTH); return messagePanel; } protected JComponent createTextComponent() { JComponent textComponent; if (BasicHTML.isHTMLString(myMessage)) { textComponent = createMessageComponent(myMessage); } else { JLabel textLabel = new JLabel(myMessage); textLabel.setUI(new MultiLineLabelUI()); textComponent = textLabel; } textComponent.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); return textComponent; } public JTextComponent getTextField() { return myField; } protected JTextComponent createTextFieldComponent() { return new JTextField(30); } @Override public JComponent getPreferredFocusedComponent() { return myField; } @Nullable public String getInputString() { if (getExitCode() == 0) { return myField.getText().trim(); } else { return null; } } } protected static class MultilineInputDialog extends InputDialog { public MultilineInputDialog(Project project, String message, String title, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator, String[] options, int defaultOption) { super(project, message, title, icon, initialValue, validator, options, defaultOption); } @Override protected JTextComponent createTextFieldComponent() { return new JTextArea(7, 50); } } protected static class PasswordInputDialog extends InputDialog { public PasswordInputDialog(String message, String title, @Nullable Icon icon, @Nullable InputValidator validator) { super(message, title, icon, null, validator); } public PasswordInputDialog(Project project, String message, String title, @Nullable Icon icon, @Nullable InputValidator validator) { super(project, message, title, icon, null, validator); } @Override protected JTextComponent createTextFieldComponent() { return new JPasswordField(30); } } protected static class InputDialogWithCheckbox extends InputDialog { private JCheckBox myCheckBox; public InputDialogWithCheckbox(String message, String title, String checkboxText, boolean checked, boolean checkboxEnabled, @Nullable Icon icon, @Nullable String initialValue, @Nullable InputValidator validator) { super(message, title, icon, initialValue, validator); myCheckBox.setText(checkboxText); myCheckBox.setSelected(checked); myCheckBox.setEnabled(checkboxEnabled); } @Override protected JPanel createMessagePanel() { JPanel messagePanel = new JPanel(new BorderLayout()); if (myMessage != null) { JComponent textComponent = createTextComponent(); messagePanel.add(textComponent, BorderLayout.NORTH); } myField = createTextFieldComponent(); messagePanel.add(myField, BorderLayout.CENTER); myCheckBox = new JCheckBox(); messagePanel.add(myCheckBox, BorderLayout.SOUTH); return messagePanel; } public Boolean isChecked() { return myCheckBox.isSelected(); } } /** It looks awful! */ @Deprecated protected static class ChooseDialog extends MessageDialog { private ComboBox myComboBox; private InputValidator myValidator; public ChooseDialog(Project project, String message, String title, @Nullable Icon icon, String[] values, String initialValue, String[] options, int defaultOption) { super(project, message, title, options, defaultOption, icon, true); myComboBox.setModel(new DefaultComboBoxModel(values)); myComboBox.setSelectedItem(initialValue); } public ChooseDialog(Project project, String message, String title, @Nullable Icon icon, String[] values, String initialValue) { this(project, message, title, icon, values, initialValue, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0); } public ChooseDialog(Component parent, String message, String title, @Nullable Icon icon, String[] values, String initialValue) { super(parent, message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0, icon); myComboBox.setModel(new DefaultComboBoxModel(values)); myComboBox.setSelectedItem(initialValue); } public ChooseDialog(String message, String title, @Nullable Icon icon, String[] values, String initialValue) { super(message, title, new String[]{OK_BUTTON, CANCEL_BUTTON}, 0, icon); myComboBox.setModel(new DefaultComboBoxModel(values)); myComboBox.setSelectedItem(initialValue); } @NotNull @Override protected Action[] createActions() { final Action[] actions = new Action[myOptions.length]; for (int i = 0; i < myOptions.length; i++) { String option = myOptions[i]; final int exitCode = i; if (i == myDefaultOptionIndex) { actions[i] = new AbstractAction(option) { @Override public void actionPerformed(ActionEvent e) { if (myValidator == null || myValidator.checkInput(myComboBox.getSelectedItem().toString().trim())) { close(exitCode); } } }; actions[i].putValue(DEFAULT_ACTION, Boolean.TRUE); myComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { actions[exitCode].setEnabled(myValidator == null || myValidator.checkInput(myComboBox.getSelectedItem().toString().trim())); } }); final JTextField textField = (JTextField)myComboBox.getEditor().getEditorComponent(); textField.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void textChanged(DocumentEvent event) { actions[exitCode].setEnabled(myValidator == null || myValidator.checkInput(textField.getText().trim())); } }); } else { // "Cancel" action actions[i] = new AbstractAction(option) { @Override public void actionPerformed(ActionEvent e) { close(exitCode); } }; } } return actions; } @Override protected JComponent createCenterPanel() { return null; } @Override protected JComponent createNorthPanel() { JPanel panel = new JPanel(new BorderLayout(15, 0)); if (myIcon != null) { JLabel iconLabel = new JLabel(myIcon); Container container = new Container(); container.setLayout(new BorderLayout()); container.add(iconLabel, BorderLayout.NORTH); panel.add(container, BorderLayout.WEST); } JPanel messagePanel = new JPanel(new BorderLayout()); if (myMessage != null) { JLabel textLabel = new JLabel(myMessage); textLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); textLabel.setUI(new MultiLineLabelUI()); messagePanel.add(textLabel, BorderLayout.NORTH); } myComboBox = new ComboBox(220); messagePanel.add(myComboBox, BorderLayout.SOUTH); panel.add(messagePanel, BorderLayout.CENTER); return panel; } @Override protected void doOKAction() { String inputString = myComboBox.getSelectedItem().toString().trim(); if (myValidator == null || myValidator.checkInput(inputString) && myValidator.canClose(inputString)) { super.doOKAction(); } } @Override public JComponent getPreferredFocusedComponent() { return myComboBox; } @Nullable public String getInputString() { if (getExitCode() == 0) { return myComboBox.getSelectedItem().toString(); } else { return null; } } public int getSelectedIndex() { if (getExitCode() == 0) { return myComboBox.getSelectedIndex(); } else { return -1; } } public JComboBox getComboBox() { return myComboBox; } public void setValidator(@Nullable InputValidator validator) { myValidator = validator; } } }
deprecations
platform/platform-api/src/com/intellij/openapi/ui/Messages.java
deprecations
Java
apache-2.0
8b61172a5fc028419187f2186c059bc41116f9dd
0
holmes/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,izonder/intellij-community,signed/intellij-community,ryano144/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,robovm/robovm-studio,ibinti/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,ryano144/intellij-community,clumsy/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,jexp/idea2,salguarnieri/intellij-community,apixandru/intellij-community,da1z/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,caot/intellij-community,TangHao1987/intellij-community,signed/intellij-community,TangHao1987/intellij-community,consulo/consulo,ahb0327/intellij-community,ryano144/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,jexp/idea2,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,consulo/consulo,orekyuu/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,ernestp/consulo,apixandru/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,allotria/intellij-community,nicolargo/intellij-community,ernestp/consulo,nicolargo/intellij-community,vladmm/intellij-community,asedunov/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,retomerz/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,fnouama/intellij-community,blademainer/intellij-community,da1z/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,blademainer/intellij-community,holmes/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,kdwink/intellij-community,allotria/intellij-community,diorcety/intellij-community,caot/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,joewalnes/idea-community,allotria/intellij-community,supersven/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,FHannes/intellij-community,blademainer/intellij-community,signed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,fitermay/intellij-community,xfournet/intellij-community,supersven/intellij-community,samthor/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,semonte/intellij-community,slisson/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ryano144/intellij-community,apixandru/intellij-community,signed/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,fitermay/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,fnouama/intellij-community,hurricup/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,diorcety/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,signed/intellij-community,blademainer/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,dslomov/intellij-community,semonte/intellij-community,vladmm/intellij-community,allotria/intellij-community,slisson/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,ernestp/consulo,retomerz/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,fitermay/intellij-community,clumsy/intellij-community,jagguli/intellij-community,apixandru/intellij-community,robovm/robovm-studio,vladmm/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,pwoodworth/intellij-community,caot/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,clumsy/intellij-community,allotria/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,caot/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,allotria/intellij-community,caot/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,izonder/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ibinti/intellij-community,clumsy/intellij-community,slisson/intellij-community,petteyg/intellij-community,jagguli/intellij-community,petteyg/intellij-community,slisson/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,gnuhub/intellij-community,jexp/idea2,MER-GROUP/intellij-community,signed/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,kool79/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,adedayo/intellij-community,blademainer/intellij-community,jexp/idea2,ahb0327/intellij-community,fitermay/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,ryano144/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,ernestp/consulo,FHannes/intellij-community,vladmm/intellij-community,petteyg/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,FHannes/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,apixandru/intellij-community,holmes/intellij-community,kdwink/intellij-community,da1z/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,semonte/intellij-community,samthor/intellij-community,retomerz/intellij-community,apixandru/intellij-community,semonte/intellij-community,retomerz/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,petteyg/intellij-community,slisson/intellij-community,Distrotech/intellij-community,signed/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,consulo/consulo,kdwink/intellij-community,semonte/intellij-community,izonder/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,caot/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,izonder/intellij-community,jagguli/intellij-community,signed/intellij-community,hurricup/intellij-community,petteyg/intellij-community,retomerz/intellij-community,consulo/consulo,vvv1559/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,jexp/idea2,diorcety/intellij-community,kdwink/intellij-community,clumsy/intellij-community,FHannes/intellij-community,kool79/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,FHannes/intellij-community,fitermay/intellij-community,da1z/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,ryano144/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,fnouama/intellij-community,da1z/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,consulo/consulo,retomerz/intellij-community,adedayo/intellij-community,kdwink/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,jexp/idea2,jagguli/intellij-community,caot/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,dslomov/intellij-community,caot/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,semonte/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,kool79/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,samthor/intellij-community,allotria/intellij-community,joewalnes/idea-community,adedayo/intellij-community,wreckJ/intellij-community,jexp/idea2,youdonghai/intellij-community,apixandru/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,holmes/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,Distrotech/intellij-community,kool79/intellij-community,asedunov/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,FHannes/intellij-community,adedayo/intellij-community,caot/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,izonder/intellij-community,semonte/intellij-community,holmes/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,caot/intellij-community,suncycheng/intellij-community,izonder/intellij-community,slisson/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,consulo/consulo,supersven/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,izonder/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,semonte/intellij-community,samthor/intellij-community,vladmm/intellij-community,holmes/intellij-community,robovm/robovm-studio,supersven/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ernestp/consulo,apixandru/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,joewalnes/idea-community,da1z/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,diorcety/intellij-community,adedayo/intellij-community,semonte/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,dslomov/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,gnuhub/intellij-community,dslomov/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,fitermay/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,holmes/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,adedayo/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,slisson/intellij-community,dslomov/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,clumsy/intellij-community,hurricup/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,retomerz/intellij-community,clumsy/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,FHannes/intellij-community,amith01994/intellij-community,caot/intellij-community,nicolargo/intellij-community,semonte/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,adedayo/intellij-community,allotria/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,signed/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,xfournet/intellij-community,da1z/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,vladmm/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community
package com.intellij.ide.util; import com.intellij.ide.IconUtilEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.impl.ModuleUtil; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import javax.swing.*; import java.awt.*; public class PsiElementModuleRenderer extends DefaultListCellRenderer{ private static final Icon TEST_ICON = IconLoader.getIcon("/nodes/testSourceFolder.png"); private static final Icon LIB_ICON = IconLoader.getIcon("/nodes/ppLibClosed.png"); private String myText; public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final Component listCellRendererComponent = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); customizeCellRenderer(list, value, index, isSelected, cellHasFocus); return listCellRendererComponent; } public String getText() { return myText; } protected void customizeCellRenderer( JList list, Object value, int index, boolean selected, boolean hasFocus ) { if (value instanceof PsiElement) { PsiElement element = (PsiElement)value; if (element.isValid()) { PsiFile psiFile = element.getContainingFile(); Module module = ModuleUtil.findModuleForPsiElement(element); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex(); if (module != null) { boolean inTestSource = false; if (psiFile != null) { VirtualFile vFile = psiFile.getVirtualFile(); if (vFile != null) { inTestSource = fileIndex.isInTestSourceContent(vFile); } } myText = module.getName(); if (inTestSource) { setIcon(TEST_ICON); } else { setIcon(module.getModuleType().getNodeIcon(false)); } } else { if (psiFile != null) { VirtualFile vFile = psiFile.getVirtualFile(); if (vFile != null) { final boolean isInLibraries = fileIndex.isInLibrarySource(vFile) || fileIndex.isInLibraryClasses(vFile); if (isInLibraries){ setIcon(LIB_ICON); OrderEntry[] orders = fileIndex.getOrderEntriesForFile(vFile); for (int i = 0; i < orders.length; i++) { OrderEntry order = orders[i]; if (order instanceof LibraryOrderEntry || order instanceof JdkOrderEntry){ myText = order.getPresentableName(); break; } } } /*else { setIcon(IconUtilEx.getEmptyIcon(false)); setText(value.toString()); }*/ } } } } else { myText = ""; } } /*else { setIcon(IconUtilEx.getEmptyIcon(false)); setText(value == null ? "" : value.toString()); }*/ setText(myText); setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 2)); setHorizontalTextPosition(SwingConstants.LEFT); setBackground(UIManager.getColor(selected ? "List.selectionBackground" : "List.background")); setForeground(selected ? UIManager.getColor("List.selectionForeground") : UIManager.getColor("textInactiveText")); } }
source/com/intellij/ide/util/PsiElementModuleRenderer.java
package com.intellij.ide.util; import com.intellij.ide.IconUtilEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.impl.ModuleUtil; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import javax.swing.*; import java.awt.*; public class PsiElementModuleRenderer extends DefaultListCellRenderer{ private static final Icon TEST_ICON = IconLoader.getIcon("/nodes/testSourceFolder.png"); private static final Icon LIB_ICON = IconLoader.getIcon("/nodes/ppLibClosed.png"); private String myText; public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final Component listCellRendererComponent = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); customizeCellRenderer(list, value, index, isSelected, cellHasFocus); return listCellRendererComponent; } public String getText() { return myText; } protected void customizeCellRenderer( JList list, Object value, int index, boolean selected, boolean hasFocus ) { if (value instanceof PsiElement) { PsiElement element = (PsiElement)value; PsiFile psiFile = element.getContainingFile(); Module module = ModuleUtil.findModuleForPsiElement(element); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex(); if (module != null) { boolean inTestSource = false; if (psiFile != null) { VirtualFile vFile = psiFile.getVirtualFile(); if (vFile != null) { inTestSource = fileIndex.isInTestSourceContent(vFile); } } myText = module.getName(); if (inTestSource) { setIcon(TEST_ICON); } else { setIcon(module.getModuleType().getNodeIcon(false)); } } else { if (psiFile != null) { VirtualFile vFile = psiFile.getVirtualFile(); if (vFile != null) { final boolean isInLibraries = fileIndex.isInLibrarySource(vFile) || fileIndex.isInLibraryClasses(vFile); if (isInLibraries){ setIcon(LIB_ICON); OrderEntry[] orders = fileIndex.getOrderEntriesForFile(vFile); for (int i = 0; i < orders.length; i++) { OrderEntry order = orders[i]; if (order instanceof LibraryOrderEntry || order instanceof JdkOrderEntry){ myText = order.getPresentableName(); break; } } } /*else { setIcon(IconUtilEx.getEmptyIcon(false)); setText(value.toString()); }*/ } } } } /*else { setIcon(IconUtilEx.getEmptyIcon(false)); setText(value == null ? "" : value.toString()); }*/ setText(myText); setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 2)); setHorizontalTextPosition(SwingConstants.LEFT); setBackground(UIManager.getColor(selected ? "List.selectionBackground" : "List.background")); setForeground(selected ? UIManager.getColor("List.selectionForeground") : UIManager.getColor("textInactiveText")); } }
51755
source/com/intellij/ide/util/PsiElementModuleRenderer.java
51755
Java
apache-2.0
0d0b8c281c5a3291e238fa96bb8bddf80057ec19
0
google/closure-templates,google/closure-templates,google/closure-templates,google/closure-templates,google/closure-templates
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.types; import static com.google.common.base.Preconditions.checkState; import static com.google.template.soy.types.SoyTypes.NUMBER_TYPE; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Interner; import com.google.common.collect.Interners; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.GenericDescriptor; import com.google.template.soy.base.internal.Identifier; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.error.SoyErrorKind; import com.google.template.soy.internal.proto.Field; import com.google.template.soy.types.SanitizedType.AttributesType; import com.google.template.soy.types.SanitizedType.HtmlType; import com.google.template.soy.types.SanitizedType.JsType; import com.google.template.soy.types.SanitizedType.StyleType; import com.google.template.soy.types.SanitizedType.TrustedResourceUriType; import com.google.template.soy.types.SanitizedType.UriType; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import javax.annotation.Nullable; /** Implementations of {@link TypeRegistry} and {@link TypeInterner}. */ public final class TypeRegistries { private static final SoyErrorKind PROTO_FQN = SoyErrorKind.of( "Proto types must be imported rather than referenced by their fully qualified names."); private TypeRegistries() {} private static final BuiltinTypeRegistry INSTANCE = new BuiltinTypeRegistry(); public static TypeInterner newTypeInterner() { return new TypeInternerImpl(); } public static TypeRegistry builtinTypeRegistry() { return INSTANCE; } public static SoyTypeRegistry newComposite(TypeRegistry typeRegistry, TypeInterner typeInterner) { return new CompositeSoyTypeRegistry(typeRegistry, typeInterner); } /** * Looks up a type by name, including by FQN proto name. Depending on whether FQN names are * allowed, deprecated, or disallowed this method may call {@code errorReporter} and may return * the type or null. */ public static SoyType getTypeOrProtoFqn( SoyTypeRegistry registry, ErrorReporter errorReporter, Identifier id) { return getTypeOrProtoFqn(registry, errorReporter, id, id.identifier()); } public static SoyType getTypeOrProtoFqn( SoyTypeRegistry registry, ErrorReporter errorReporter, Identifier id, String typeName) { SoyType nonProtoFqnType = registry.getType(typeName); if (nonProtoFqnType != null) { return nonProtoFqnType; } SoyType protoFqnType = registry.getProtoRegistry().getProtoType(typeName); if (protoFqnType != null) { errorReporter.report(id.location(), PROTO_FQN); } return null; } private static final class TypeInternerImpl implements TypeInterner { private final Interner<SoyType> types = Interners.newStrongInterner(); private final Map<String, SoyProtoType> protoTypes = new ConcurrentHashMap<>(); private final Map<GenericDescriptor, ImmutableMap<String, GenericDescriptor>> protoMembersCache = new ConcurrentHashMap<>(); private final Map<GenericDescriptor, ImportType> protoImportTypes = new ConcurrentHashMap<>(); public TypeInternerImpl() { // Register the special number type so == comparisons work checkState(types.intern(NUMBER_TYPE) == NUMBER_TYPE); } @Override @SuppressWarnings("unchecked") public <T extends SoyType> T intern(T type) { return (T) types.intern(type); } @Override public SoyProtoType getOrComputeProtoType( Descriptor descriptor, Function<? super String, ? extends SoyProtoType> mapper) { return protoTypes.computeIfAbsent(descriptor.getFullName(), mapper); } @Override public ImportType getProtoImportType(GenericDescriptor descriptor) { return protoImportTypes.computeIfAbsent( descriptor, d -> { if (d instanceof FileDescriptor) { return ProtoModuleImportType.create((FileDescriptor) d); } if (d instanceof Descriptor) { return ProtoImportType.create((Descriptor) d); } if (d instanceof EnumDescriptor) { return ProtoEnumImportType.create((EnumDescriptor) d); } if (d instanceof FieldDescriptor && ((FieldDescriptor) d).isExtension()) { return ProtoExtensionImportType.create((FieldDescriptor) d); } throw new ClassCastException(d.getClass().getName()); }); } @Override public SoyType getProtoImportType(FileDescriptor descriptor, String member) { return getProtoImportType( protoMembersCache.computeIfAbsent(descriptor, TypeInternerImpl::buildMemberIndex), member); } @Override public SoyType getProtoImportType(Descriptor descriptor, String member) { return getProtoImportType( protoMembersCache.computeIfAbsent(descriptor, TypeInternerImpl::buildMemberIndex), member); } private SoyType getProtoImportType(Map<String, GenericDescriptor> index, String member) { GenericDescriptor d = index.get(member); if (d != null) { return getProtoImportType(d); } return UnknownType.getInstance(); } private static ImmutableMap<String, GenericDescriptor> buildMemberIndex(GenericDescriptor d) { ImmutableMap.Builder<String, GenericDescriptor> index = ImmutableMap.builder(); if (d instanceof FileDescriptor) { FileDescriptor fileDescriptor = (FileDescriptor) d; fileDescriptor.getMessageTypes().forEach(t -> index.put(t.getName(), t)); fileDescriptor.getEnumTypes().forEach(t -> index.put(t.getName(), t)); fileDescriptor.getExtensions().forEach(t -> index.put(Field.computeSoyName(t), t)); } else if (d instanceof Descriptor) { Descriptor descriptor = (Descriptor) d; descriptor.getNestedTypes().forEach(t -> index.put(t.getName(), t)); descriptor.getEnumTypes().forEach(t -> index.put(t.getName(), t)); descriptor.getExtensions().forEach(t -> index.put(Field.computeSoyName(t), t)); } else { throw new AssertionError(d.getClass().getName()); } return index.build(); } } private static final class BuiltinTypeRegistry implements TypeRegistry { private static final ImmutableMap<String, SoyType> BUILTIN_TYPES = ImmutableSortedMap.<String, SoyType>naturalOrder() .put("?", UnknownType.getInstance()) .put("any", AnyType.getInstance()) .put("null", NullType.getInstance()) .put("bool", BoolType.getInstance()) .put("int", IntType.getInstance()) .put("float", FloatType.getInstance()) .put("string", StringType.getInstance()) .put("number", NUMBER_TYPE) .put("html", HtmlType.getInstance()) .put("attributes", AttributesType.getInstance()) .put("css", StyleType.getInstance()) .put("uri", UriType.getInstance()) .put("trusted_resource_uri", TrustedResourceUriType.getInstance()) .put("js", JsType.getInstance()) .put("ve_data", VeDataType.getInstance()) .put("Message", MessageType.getInstance()) .buildOrThrow(); private BuiltinTypeRegistry() {} @Nullable @Override public SoyType getType(String typeName) { return BUILTIN_TYPES.get(typeName); } @Override public ImmutableSet<String> getAllSortedTypeNames() { return BUILTIN_TYPES.keySet(); } } private static final class CompositeSoyTypeRegistry implements SoyTypeRegistry { private final TypeRegistry typeRegistry; private final TypeInterner typeInterner; public CompositeSoyTypeRegistry(TypeRegistry typeRegistry, TypeInterner typeInterner) { this.typeRegistry = typeRegistry; this.typeInterner = typeInterner; } @Override @Nullable public SoyType getType(String typeName) { return typeRegistry.getType(typeName); } @Override public Iterable<String> getAllSortedTypeNames() { return typeRegistry.getAllSortedTypeNames(); } @Override public <T extends SoyType> T intern(T type) { return typeInterner.intern(type); } @Override public SoyProtoType getOrComputeProtoType( Descriptor descriptor, Function<? super String, ? extends SoyProtoType> mapper) { return typeInterner.getOrComputeProtoType(descriptor, mapper); } @Override public SoyType getOrCreateElementType(String tagName) { return typeInterner.getOrCreateElementType(tagName); } @Override public ImportType getProtoImportType(GenericDescriptor descriptor) { return typeInterner.getProtoImportType(descriptor); } @Override public SoyType getProtoImportType(FileDescriptor descriptor, String member) { return typeInterner.getProtoImportType(descriptor, member); } @Override public SoyType getProtoImportType(Descriptor descriptor, String member) { return typeInterner.getProtoImportType(descriptor, member); } } }
java/src/com/google/template/soy/types/TypeRegistries.java
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.types; import static com.google.common.base.Preconditions.checkState; import static com.google.template.soy.types.SoyTypes.NUMBER_TYPE; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Interner; import com.google.common.collect.Interners; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.GenericDescriptor; import com.google.template.soy.base.internal.Identifier; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.error.SoyErrorKind; import com.google.template.soy.internal.proto.Field; import com.google.template.soy.types.SanitizedType.AttributesType; import com.google.template.soy.types.SanitizedType.HtmlType; import com.google.template.soy.types.SanitizedType.JsType; import com.google.template.soy.types.SanitizedType.StyleType; import com.google.template.soy.types.SanitizedType.TrustedResourceUriType; import com.google.template.soy.types.SanitizedType.UriType; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import javax.annotation.Nullable; /** Implementations of {@link TypeRegistry} and {@link TypeInterner}. */ public final class TypeRegistries { private static final SoyErrorKind PROTO_FQN = SoyErrorKind.of( "Proto types must be imported rather than referenced by their fully qualified names."); private TypeRegistries() {} private static final BuiltinTypeRegistry INSTANCE = new BuiltinTypeRegistry(); public static TypeInterner newTypeInterner() { return new TypeInternerImpl(); } public static TypeRegistry builtinTypeRegistry() { return INSTANCE; } public static SoyTypeRegistry newComposite(TypeRegistry typeRegistry, TypeInterner typeInterner) { return new CompositeSoyTypeRegistry(typeRegistry, typeInterner); } /** * Looks up a type by name, including by FQN proto name. Depending on whether FQN names are * allowed, deprecated, or disallowed this method may call {@code errorReporter} and may return * the type or null. */ public static SoyType getTypeOrProtoFqn( SoyTypeRegistry registry, ErrorReporter errorReporter, Identifier id) { return getTypeOrProtoFqn(registry, errorReporter, id, id.identifier()); } public static SoyType getTypeOrProtoFqn( SoyTypeRegistry registry, ErrorReporter errorReporter, Identifier id, String typeName) { SoyType nonProtoFqnType = registry.getType(typeName); if (nonProtoFqnType != null) { return nonProtoFqnType; } SoyType protoFqnType = registry.getProtoRegistry().getProtoType(typeName); if (protoFqnType != null) { errorReporter.report(id.location(), PROTO_FQN); } return null; } private static final class TypeInternerImpl implements TypeInterner { private final Interner<SoyType> types = Interners.newStrongInterner(); private final Map<String, SoyProtoType> protoTypes = new ConcurrentHashMap<>(); private final Map<GenericDescriptor, ImmutableMap<String, GenericDescriptor>> protoMembersCache = new ConcurrentHashMap<>(); private final Map<GenericDescriptor, ImportType> protoImportTypes = new ConcurrentHashMap<>(); public TypeInternerImpl() { // Register the special number type so == comparisons work checkState(types.intern(NUMBER_TYPE) == NUMBER_TYPE); } @Override @SuppressWarnings("unchecked") public <T extends SoyType> T intern(T type) { return (T) types.intern(type); } @Override public SoyProtoType getOrComputeProtoType( Descriptor descriptor, Function<? super String, ? extends SoyProtoType> mapper) { return protoTypes.computeIfAbsent(descriptor.getFullName(), mapper); } @Override public ImportType getProtoImportType(GenericDescriptor descriptor) { return protoImportTypes.computeIfAbsent( descriptor, d -> { if (d instanceof FileDescriptor) { return ProtoModuleImportType.create((FileDescriptor) d); } if (d instanceof Descriptor) { return ProtoImportType.create((Descriptor) d); } if (d instanceof EnumDescriptor) { return ProtoEnumImportType.create((EnumDescriptor) d); } if (d instanceof FieldDescriptor && ((FieldDescriptor) d).isExtension()) { return ProtoExtensionImportType.create((FieldDescriptor) d); } throw new ClassCastException(d.getClass().getName()); }); } @Override public SoyType getProtoImportType(FileDescriptor descriptor, String member) { return getProtoImportType( protoMembersCache.computeIfAbsent(descriptor, TypeInternerImpl::buildMemberIndex), member); } @Override public SoyType getProtoImportType(Descriptor descriptor, String member) { return getProtoImportType( protoMembersCache.computeIfAbsent(descriptor, TypeInternerImpl::buildMemberIndex), member); } private SoyType getProtoImportType(Map<String, GenericDescriptor> index, String member) { GenericDescriptor d = index.get(member); if (d != null) { return getProtoImportType(d); } return UnknownType.getInstance(); } private static ImmutableMap<String, GenericDescriptor> buildMemberIndex(GenericDescriptor d) { ImmutableMap.Builder<String, GenericDescriptor> index = ImmutableMap.builder(); if (d instanceof FileDescriptor) { FileDescriptor fileDescriptor = (FileDescriptor) d; fileDescriptor.getMessageTypes().forEach(t -> index.put(t.getName(), t)); fileDescriptor.getEnumTypes().forEach(t -> index.put(t.getName(), t)); fileDescriptor.getExtensions().forEach(t -> index.put(Field.computeSoyName(t), t)); } else if (d instanceof Descriptor) { Descriptor descriptor = (Descriptor) d; descriptor.getNestedTypes().forEach(t -> index.put(t.getName(), t)); descriptor.getEnumTypes().forEach(t -> index.put(t.getName(), t)); descriptor.getExtensions().forEach(t -> index.put(Field.computeSoyName(t), t)); } else { throw new AssertionError(d.getClass().getName()); } return index.build(); } } private static final class BuiltinTypeRegistry implements TypeRegistry { private static final ImmutableMap<String, SoyType> BUILTIN_TYPES = ImmutableSortedMap.<String, SoyType>naturalOrder() .put("?", UnknownType.getInstance()) .put("any", AnyType.getInstance()) .put("null", NullType.getInstance()) .put("bool", BoolType.getInstance()) .put("int", IntType.getInstance()) .put("float", FloatType.getInstance()) .put("string", StringType.getInstance()) .put("number", NUMBER_TYPE) .put("html", HtmlType.getInstance()) .put("attributes", AttributesType.getInstance()) .put("css", StyleType.getInstance()) .put("uri", UriType.getInstance()) .put("trusted_resource_uri", TrustedResourceUriType.getInstance()) .put("js", JsType.getInstance()) .put("ve_data", VeDataType.getInstance()) .put("Message", MessageType.getInstance()) .build(); private BuiltinTypeRegistry() {} @Nullable @Override public SoyType getType(String typeName) { return BUILTIN_TYPES.get(typeName); } @Override public ImmutableSet<String> getAllSortedTypeNames() { return BUILTIN_TYPES.keySet(); } } private static final class CompositeSoyTypeRegistry implements SoyTypeRegistry { private final TypeRegistry typeRegistry; private final TypeInterner typeInterner; public CompositeSoyTypeRegistry(TypeRegistry typeRegistry, TypeInterner typeInterner) { this.typeRegistry = typeRegistry; this.typeInterner = typeInterner; } @Override @Nullable public SoyType getType(String typeName) { return typeRegistry.getType(typeName); } @Override public Iterable<String> getAllSortedTypeNames() { return typeRegistry.getAllSortedTypeNames(); } @Override public <T extends SoyType> T intern(T type) { return typeInterner.intern(type); } @Override public SoyProtoType getOrComputeProtoType( Descriptor descriptor, Function<? super String, ? extends SoyProtoType> mapper) { return typeInterner.getOrComputeProtoType(descriptor, mapper); } @Override public SoyType getOrCreateElementType(String tagName) { return typeInterner.getOrCreateElementType(tagName); } @Override public ImportType getProtoImportType(GenericDescriptor descriptor) { return typeInterner.getProtoImportType(descriptor); } @Override public SoyType getProtoImportType(FileDescriptor descriptor, String member) { return typeInterner.getProtoImportType(descriptor, member); } @Override public SoyType getProtoImportType(Descriptor descriptor, String member) { return typeInterner.getProtoImportType(descriptor, member); } } }
Internal change PiperOrigin-RevId: 416050297
java/src/com/google/template/soy/types/TypeRegistries.java
Internal change
Java
apache-2.0
c0602993306cd1ba49adc5cf0397530a5f0bf2b2
0
google/turbine
/* * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.turbine.processing; import static java.util.Objects.requireNonNull; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.turbine.binder.bound.AnnotationMetadata; import com.google.turbine.binder.bound.SourceTypeBoundClass; import com.google.turbine.binder.bound.TurbineAnnotationValue; import com.google.turbine.binder.bound.TypeBoundClass; import com.google.turbine.binder.bound.TypeBoundClass.FieldInfo; import com.google.turbine.binder.bound.TypeBoundClass.MethodInfo; import com.google.turbine.binder.bound.TypeBoundClass.ParamInfo; import com.google.turbine.binder.bound.TypeBoundClass.TyVarInfo; import com.google.turbine.binder.lookup.PackageScope; import com.google.turbine.binder.sym.ClassSymbol; import com.google.turbine.binder.sym.FieldSymbol; import com.google.turbine.binder.sym.MethodSymbol; import com.google.turbine.binder.sym.PackageSymbol; import com.google.turbine.binder.sym.ParamSymbol; import com.google.turbine.binder.sym.Symbol; import com.google.turbine.binder.sym.TyVarSymbol; import com.google.turbine.diag.TurbineError; import com.google.turbine.diag.TurbineError.ErrorKind; import com.google.turbine.model.Const; import com.google.turbine.model.Const.ArrayInitValue; import com.google.turbine.model.TurbineFlag; import com.google.turbine.model.TurbineTyKind; import com.google.turbine.tree.Tree.MethDecl; import com.google.turbine.tree.Tree.TyDecl; import com.google.turbine.tree.Tree.VarDecl; import com.google.turbine.type.AnnoInfo; import com.google.turbine.type.Type; import com.google.turbine.type.Type.ClassTy; import com.google.turbine.type.Type.ClassTy.SimpleClassTy; import com.google.turbine.type.Type.ErrorTy; import java.lang.annotation.Annotation; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ElementVisitor; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.NestingKind; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import org.checkerframework.checker.nullness.qual.Nullable; /** An {@link Element} implementation backed by a {@link Symbol}. */ public abstract class TurbineElement implements Element { public abstract Symbol sym(); public abstract String javadoc(); @Override public abstract int hashCode(); @Override public abstract boolean equals(Object obj); protected final ModelFactory factory; private final Supplier<ImmutableList<AnnotationMirror>> annotationMirrors; protected <T> Supplier<T> memoize(Supplier<T> supplier) { return factory.memoize(supplier); } protected TurbineElement(ModelFactory factory) { this.factory = requireNonNull(factory); this.annotationMirrors = factory.memoize( new Supplier<ImmutableList<AnnotationMirror>>() { @Override public ImmutableList<AnnotationMirror> get() { ImmutableList.Builder<AnnotationMirror> result = ImmutableList.builder(); for (AnnoInfo anno : annos()) { result.add(TurbineAnnotationMirror.create(factory, anno)); } return result.build(); } }); } static AnnoInfo getAnnotation(Iterable<AnnoInfo> annos, ClassSymbol sym) { for (AnnoInfo anno : annos) { if (Objects.equals(anno.sym(), sym)) { return anno; } } return null; } @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) { ClassSymbol sym = new ClassSymbol(annotationType.getName().replace('.', '/')); TypeBoundClass info = factory.getSymbol(sym); if (info == null) { return null; } AnnoInfo anno = getAnnotation(annos(), sym); if (anno == null) { return null; } return TurbineAnnotationProxy.create(factory, annotationType, anno); } @Override public final <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) { ClassSymbol sym = new ClassSymbol(annotationType.getName().replace('.', '/')); TypeBoundClass info = factory.getSymbol(sym); if (info == null) { return null; } AnnotationMetadata metadata = info.annotationMetadata(); if (metadata == null) { return null; } List<A> result = new ArrayList<>(); for (AnnoInfo anno : annos()) { if (anno.sym().equals(sym)) { result.add(TurbineAnnotationProxy.create(factory, annotationType, anno)); continue; } if (anno.sym().equals(metadata.repeatable())) { ArrayInitValue arrayValue = (ArrayInitValue) anno.values().get("value"); for (Const element : arrayValue.elements()) { result.add( TurbineAnnotationProxy.create( factory, annotationType, ((TurbineAnnotationValue) element).info())); } } } return Iterables.toArray(result, annotationType); } @Override public final List<? extends AnnotationMirror> getAnnotationMirrors() { return annotationMirrors.get(); } List<? extends AnnotationMirror> getAllAnnotationMirrors() { return getAnnotationMirrors(); } protected abstract ImmutableList<AnnoInfo> annos(); /** A {@link TypeElement} implementation backed by a {@link ClassSymbol}. */ static class TurbineTypeElement extends TurbineElement implements TypeElement { @Override public int hashCode() { return sym.hashCode(); } private final ClassSymbol sym; private final Supplier<TypeBoundClass> info; TurbineTypeElement(ModelFactory factory, ClassSymbol sym) { super(factory); this.sym = requireNonNull(sym); this.info = memoize( new Supplier<TypeBoundClass>() { @Override public TypeBoundClass get() { return factory.getSymbol(sym); } }); } @Nullable TypeBoundClass info() { return info.get(); } TypeBoundClass infoNonNull() { TypeBoundClass info = info(); if (info == null) { throw TurbineError.format(/* source= */ null, ErrorKind.SYMBOL_NOT_FOUND, sym); } return info; } @Override public NestingKind getNestingKind() { TypeBoundClass info = info(); return (info != null && info.owner() != null) ? NestingKind.MEMBER : NestingKind.TOP_LEVEL; } private final Supplier<TurbineName> qualifiedName = memoize( new Supplier<TurbineName>() { @Override public TurbineName get() { TypeBoundClass info = info(); if (info == null || info.owner() == null) { return new TurbineName(sym.toString()); } ClassSymbol sym = sym(); Deque<String> flat = new ArrayDeque<>(); while (info.owner() != null) { flat.addFirst(sym.binaryName().substring(info.owner().binaryName().length() + 1)); sym = info.owner(); info = factory.getSymbol(sym); } flat.addFirst(sym.toString()); return new TurbineName(Joiner.on('.').join(flat)); } }); @Override public Name getQualifiedName() { return qualifiedName.get(); } private final Supplier<TypeMirror> superclass = memoize( new Supplier<TypeMirror>() { @Override public TypeMirror get() { TypeBoundClass info = infoNonNull(); switch (info.kind()) { case CLASS: case ENUM: if (info.superclass() != null) { return factory.asTypeMirror(info.superClassType()); } if (info instanceof SourceTypeBoundClass) { // support simple name for stuff that doesn't exist TyDecl decl = ((SourceTypeBoundClass) info).decl(); if (decl.xtnds().isPresent()) { return factory.asTypeMirror( ErrorTy.create(decl.xtnds().get().name().value())); } } return factory.noType(); case INTERFACE: case ANNOTATION: return factory.noType(); } throw new AssertionError(info.kind()); } }); @Override public TypeMirror getSuperclass() { return superclass.get(); } @Override public String toString() { return getQualifiedName().toString(); } private final Supplier<List<TypeMirror>> interfaces = memoize( new Supplier<List<TypeMirror>>() { @Override public List<TypeMirror> get() { return factory.asTypeMirrors(infoNonNull().interfaceTypes()); } }); @Override public List<? extends TypeMirror> getInterfaces() { return interfaces.get(); } private final Supplier<ImmutableList<TypeParameterElement>> typeParameters = memoize( new Supplier<ImmutableList<TypeParameterElement>>() { @Override public ImmutableList<TypeParameterElement> get() { ImmutableList.Builder<TypeParameterElement> result = ImmutableList.builder(); for (TyVarSymbol p : infoNonNull().typeParameters().values()) { result.add(factory.typeParameterElement(p)); } return result.build(); } }); @Override public List<? extends TypeParameterElement> getTypeParameters() { return typeParameters.get(); } private final Supplier<TypeMirror> type = memoize( new Supplier<TypeMirror>() { @Override public TypeMirror get() { return factory.asTypeMirror(asGenericType(sym)); } ClassTy asGenericType(ClassSymbol symbol) { TypeBoundClass info = info(); if (info == null) { return ClassTy.asNonParametricClassTy(symbol); } Deque<Type.ClassTy.SimpleClassTy> simples = new ArrayDeque<>(); simples.addFirst(simple(symbol, info)); while (info.owner() != null && (info.access() & TurbineFlag.ACC_STATIC) == 0) { symbol = info.owner(); info = factory.getSymbol(symbol); simples.addFirst(simple(symbol, info)); } return ClassTy.create(ImmutableList.copyOf(simples)); } private SimpleClassTy simple(ClassSymbol sym, TypeBoundClass info) { ImmutableList.Builder<Type> args = ImmutableList.builder(); for (TyVarSymbol t : info.typeParameters().values()) { args.add(Type.TyVar.create(t, ImmutableList.of())); } return SimpleClassTy.create(sym, args.build(), ImmutableList.of()); } }); @Override public TypeMirror asType() { return type.get(); } @Override public ElementKind getKind() { TypeBoundClass info = infoNonNull(); switch (info.kind()) { case CLASS: return ElementKind.CLASS; case INTERFACE: return ElementKind.INTERFACE; case ENUM: return ElementKind.ENUM; case ANNOTATION: return ElementKind.ANNOTATION_TYPE; } throw new AssertionError(info.kind()); } @Override public Set<Modifier> getModifiers() { return asModifierSet(ModifierOwner.TYPE, infoNonNull().access() & ~TurbineFlag.ACC_SUPER); } private final Supplier<TurbineName> simpleName = memoize( new Supplier<TurbineName>() { @Override public TurbineName get() { TypeBoundClass info = info(); if (info == null || info.owner() == null) { return new TurbineName(sym.simpleName()); } return new TurbineName( sym.binaryName().substring(info.owner().binaryName().length() + 1)); } }); @Override public Name getSimpleName() { return simpleName.get(); } private final Supplier<Element> enclosing = memoize( new Supplier<Element>() { @Override public Element get() { return getNestingKind().equals(NestingKind.TOP_LEVEL) ? factory.packageElement(sym.owner()) : factory.typeElement(info().owner()); } }); @Override public Element getEnclosingElement() { return enclosing.get(); } private final Supplier<ImmutableList<Element>> enclosed = memoize( new Supplier<ImmutableList<Element>>() { @Override public ImmutableList<Element> get() { TypeBoundClass info = infoNonNull(); ImmutableList.Builder<Element> result = ImmutableList.builder(); for (FieldInfo field : info.fields()) { result.add(factory.fieldElement(field.sym())); } for (MethodInfo method : info.methods()) { result.add(factory.executableElement(method.sym())); } for (ClassSymbol child : info.children().values()) { result.add(factory.typeElement(child)); } return result.build(); } }); @Override public List<? extends Element> getEnclosedElements() { return enclosed.get(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitType(this, p); } @Override public ClassSymbol sym() { return sym; } @Override public String javadoc() { TypeBoundClass info = info(); if (!(info instanceof SourceTypeBoundClass)) { return null; } return ((SourceTypeBoundClass) info).decl().javadoc(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineTypeElement && sym.equals(((TurbineTypeElement) obj).sym); } @Override protected ImmutableList<AnnoInfo> annos() { return infoNonNull().annotations(); } @Override public final <A extends Annotation> A getAnnotation(Class<A> annotationType) { ClassSymbol sym = new ClassSymbol(annotationType.getName().replace('.', '/')); AnnoInfo anno = getAnnotation(annos(), sym); if (anno != null) { return TurbineAnnotationProxy.create(factory, annotationType, anno); } if (!isAnnotationInherited(sym)) { return null; } ClassSymbol superclass = infoNonNull().superclass(); while (superclass != null) { TypeBoundClass info = factory.getSymbol(superclass); if (info == null) { break; } anno = getAnnotation(info.annotations(), sym); if (anno != null) { return TurbineAnnotationProxy.create(factory, annotationType, anno); } superclass = info.superclass(); } return null; } @Override List<? extends AnnotationMirror> getAllAnnotationMirrors() { Map<ClassSymbol, AnnotationMirror> result = new LinkedHashMap<>(); for (AnnoInfo anno : annos()) { result.put(anno.sym(), TurbineAnnotationMirror.create(factory, anno)); } ClassSymbol superclass = infoNonNull().superclass(); while (superclass != null) { TypeBoundClass i = factory.getSymbol(superclass); if (i == null) { break; } for (AnnoInfo anno : i.annotations()) { addAnnotationFromSuper(result, anno); } superclass = i.superclass(); } return ImmutableList.copyOf(result.values()); } private void addAnnotationFromSuper(Map<ClassSymbol, AnnotationMirror> result, AnnoInfo anno) { if (!isAnnotationInherited(anno.sym())) { return; } if (result.containsKey(anno.sym())) { // if the same inherited annotation is present on multiple supertypes, only return one return; } result.put(anno.sym(), TurbineAnnotationMirror.create(factory, anno)); } private boolean isAnnotationInherited(ClassSymbol sym) { TypeBoundClass annoInfo = factory.getSymbol(sym); if (annoInfo == null) { return false; } for (AnnoInfo anno : annoInfo.annotations()) { if (anno.sym().equals(ClassSymbol.INHERITED)) { return true; } } return false; } } /** A {@link TypeParameterElement} implementation backed by a {@link TyVarSymbol}. */ static class TurbineTypeParameterElement extends TurbineElement implements TypeParameterElement { @Override public int hashCode() { return sym.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineTypeParameterElement && sym.equals(((TurbineTypeParameterElement) obj).sym); } private final TyVarSymbol sym; public TurbineTypeParameterElement(ModelFactory factory, TyVarSymbol sym) { super(factory); this.sym = sym; } private final Supplier<TyVarInfo> info = memoize( new Supplier<TyVarInfo>() { @Override public TyVarInfo get() { return factory.getTyVarInfo(sym); } }); @Nullable private TyVarInfo info() { return info.get(); } @Override public String toString() { return sym.name(); } @Override public Element getGenericElement() { return factory.element(sym.owner()); } @Override public List<? extends TypeMirror> getBounds() { ImmutableList<Type> bounds = info().upperBound().bounds(); return factory.asTypeMirrors(bounds.isEmpty() ? ImmutableList.of(ClassTy.OBJECT) : bounds); } @Override public TypeMirror asType() { return factory.asTypeMirror(Type.TyVar.create(sym, info().annotations())); } @Override public ElementKind getKind() { return ElementKind.TYPE_PARAMETER; } @Override public Set<Modifier> getModifiers() { return ImmutableSet.of(); } @Override public Name getSimpleName() { return new TurbineName(sym.name()); } @Override public Element getEnclosingElement() { return getGenericElement(); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitTypeParameter(this, p); } @Override public TyVarSymbol sym() { return sym; } @Override public String javadoc() { return null; } @Override protected ImmutableList<AnnoInfo> annos() { return info().annotations(); } } /** An {@link ExecutableElement} implementation backed by a {@link MethodSymbol}. */ static class TurbineExecutableElement extends TurbineElement implements ExecutableElement { private final MethodSymbol sym; private final Supplier<MethodInfo> info = memoize( new Supplier<MethodInfo>() { @Override public MethodInfo get() { return factory.getMethodInfo(sym); } }); @Nullable MethodInfo info() { return info.get(); } TurbineExecutableElement(ModelFactory factory, MethodSymbol sym) { super(factory); this.sym = sym; } @Override public MethodSymbol sym() { return sym; } @Override public String javadoc() { MethDecl decl = info().decl(); return decl != null ? decl.javadoc() : null; } @Override public int hashCode() { return sym.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineExecutableElement && sym.equals(((TurbineExecutableElement) obj).sym); } @Override public List<? extends TypeParameterElement> getTypeParameters() { ImmutableList.Builder<TurbineTypeParameterElement> result = ImmutableList.builder(); for (Map.Entry<TyVarSymbol, TyVarInfo> p : info().tyParams().entrySet()) { result.add(factory.typeParameterElement(p.getKey())); } return result.build(); } @Override public TypeMirror getReturnType() { return factory.asTypeMirror(info().returnType()); } private final Supplier<ImmutableList<VariableElement>> parameters = memoize( new Supplier<ImmutableList<VariableElement>>() { @Override public ImmutableList<VariableElement> get() { ImmutableList.Builder<VariableElement> result = ImmutableList.builder(); for (ParamInfo param : info().parameters()) { if (param.synthetic()) { // ExecutableElement#getParameters doesn't expect synthetic or mandated // parameters continue; } result.add(factory.parameterElement(param.sym())); } return result.build(); } }); @Override public List<? extends VariableElement> getParameters() { return parameters.get(); } @Override public String toString() { MethodInfo info = info(); StringBuilder sb = new StringBuilder(); if (!info.tyParams().isEmpty()) { sb.append('<'); Joiner.on(',').appendTo(sb, info.tyParams().keySet()); sb.append('>'); } if (getKind() == ElementKind.CONSTRUCTOR) { sb.append(info.sym().owner().simpleName()); } else { sb.append(info.sym().name()); } sb.append('('); boolean first = true; for (ParamInfo p : info.parameters()) { if (!first) { sb.append(','); } sb.append(p.type()); first = false; } sb.append(')'); return sb.toString(); } @Override public TypeMirror getReceiverType() { return info().receiver() != null ? factory.asTypeMirror(info().receiver().type()) : factory.noType(); } @Override public boolean isVarArgs() { return (info().access() & TurbineFlag.ACC_VARARGS) == TurbineFlag.ACC_VARARGS; } @Override public boolean isDefault() { return (info().access() & TurbineFlag.ACC_DEFAULT) == TurbineFlag.ACC_DEFAULT; } @Override public List<? extends TypeMirror> getThrownTypes() { return factory.asTypeMirrors(info().exceptions()); } @Override public AnnotationValue getDefaultValue() { return info().defaultValue() != null ? TurbineAnnotationMirror.annotationValue(factory, info().defaultValue()) : null; } @Override public TypeMirror asType() { return factory.asTypeMirror(info().asType()); } @Override public ElementKind getKind() { return sym.name().equals("<init>") ? ElementKind.CONSTRUCTOR : ElementKind.METHOD; } @Override public Set<Modifier> getModifiers() { int access = info().access(); if (factory.getSymbol(info().sym().owner()).kind() == TurbineTyKind.INTERFACE) { if ((access & (TurbineFlag.ACC_ABSTRACT | TurbineFlag.ACC_STATIC)) == 0) { access |= TurbineFlag.ACC_DEFAULT; } } return asModifierSet(ModifierOwner.METHOD, access); } @Override public Name getSimpleName() { return new TurbineName(info().sym().name()); } @Override public Element getEnclosingElement() { return factory.typeElement(info().sym().owner()); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitExecutable(this, p); } @Override protected ImmutableList<AnnoInfo> annos() { return info().annotations(); } } /** An {@link VariableElement} implementation backed by a {@link FieldSymbol}. */ static class TurbineFieldElement extends TurbineElement implements VariableElement { @Override public String toString() { return sym.name(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineFieldElement && sym.equals(((TurbineFieldElement) obj).sym); } @Override public int hashCode() { return sym.hashCode(); } private final FieldSymbol sym; @Override public FieldSymbol sym() { return sym; } @Override public String javadoc() { VarDecl decl = info().decl(); return decl != null ? decl.javadoc() : null; } private final Supplier<FieldInfo> info = memoize( new Supplier<FieldInfo>() { @Override public FieldInfo get() { return factory.getFieldInfo(sym); } }); @Nullable FieldInfo info() { return info.get(); } TurbineFieldElement(ModelFactory factory, FieldSymbol sym) { super(factory); this.sym = sym; } @Override public Object getConstantValue() { if (info().value() == null) { return null; } return info().value().getValue(); } @Override public TypeMirror asType() { return factory.asTypeMirror(info().type()); } @Override public ElementKind getKind() { return ((info().access() & TurbineFlag.ACC_ENUM) == TurbineFlag.ACC_ENUM) ? ElementKind.ENUM_CONSTANT : ElementKind.FIELD; } @Override public Set<Modifier> getModifiers() { return asModifierSet(ModifierOwner.FIELD, info().access()); } @Override public Name getSimpleName() { return new TurbineName(sym.name()); } @Override public Element getEnclosingElement() { return factory.typeElement(sym.owner()); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitVariable(this, p); } @Override protected ImmutableList<AnnoInfo> annos() { return info().annotations(); } } private enum ModifierOwner { TYPE, PARAMETER, FIELD, METHOD } private static ImmutableSet<Modifier> asModifierSet(ModifierOwner modifierOwner, int access) { EnumSet<Modifier> modifiers = EnumSet.noneOf(Modifier.class); if ((access & TurbineFlag.ACC_PUBLIC) == TurbineFlag.ACC_PUBLIC) { modifiers.add(Modifier.PUBLIC); } if ((access & TurbineFlag.ACC_PROTECTED) == TurbineFlag.ACC_PROTECTED) { modifiers.add(Modifier.PROTECTED); } if ((access & TurbineFlag.ACC_PRIVATE) == TurbineFlag.ACC_PRIVATE) { modifiers.add(Modifier.PRIVATE); } if ((access & TurbineFlag.ACC_ABSTRACT) == TurbineFlag.ACC_ABSTRACT) { modifiers.add(Modifier.ABSTRACT); } if ((access & TurbineFlag.ACC_FINAL) == TurbineFlag.ACC_FINAL) { modifiers.add(Modifier.FINAL); } if ((access & TurbineFlag.ACC_DEFAULT) == TurbineFlag.ACC_DEFAULT) { modifiers.add(Modifier.DEFAULT); } if ((access & TurbineFlag.ACC_STATIC) == TurbineFlag.ACC_STATIC) { modifiers.add(Modifier.STATIC); } if ((access & TurbineFlag.ACC_TRANSIENT) == TurbineFlag.ACC_TRANSIENT) { switch (modifierOwner) { case METHOD: case PARAMETER: // varargs and transient use the same bits break; default: modifiers.add(Modifier.TRANSIENT); } } if ((access & TurbineFlag.ACC_VOLATILE) == TurbineFlag.ACC_VOLATILE) { modifiers.add(Modifier.VOLATILE); } if ((access & TurbineFlag.ACC_SYNCHRONIZED) == TurbineFlag.ACC_SYNCHRONIZED) { modifiers.add(Modifier.SYNCHRONIZED); } if ((access & TurbineFlag.ACC_NATIVE) == TurbineFlag.ACC_NATIVE) { modifiers.add(Modifier.NATIVE); } if ((access & TurbineFlag.ACC_STRICT) == TurbineFlag.ACC_STRICT) { modifiers.add(Modifier.STRICTFP); } return Sets.immutableEnumSet(modifiers); } /** A {@link PackageElement} implementation backed by a {@link PackageSymbol}. */ static class TurbinePackageElement extends TurbineElement implements PackageElement { private final PackageSymbol sym; public TurbinePackageElement(ModelFactory factory, PackageSymbol sym) { super(factory); this.sym = sym; } @Override public Name getQualifiedName() { return new TurbineName(sym.toString()); } @Override public boolean isUnnamed() { return sym.binaryName().isEmpty(); } @Override public TypeMirror asType() { return factory.packageType(sym); } @Override public ElementKind getKind() { return ElementKind.PACKAGE; } @Override public Set<Modifier> getModifiers() { return ImmutableSet.of(); } @Override public Name getSimpleName() { return new TurbineName(sym.binaryName().substring(sym.binaryName().lastIndexOf('/') + 1)); } @Override public Element getEnclosingElement() { // a package is not enclosed by another element return null; } @Override public List<TurbineTypeElement> getEnclosedElements() { ImmutableSet.Builder<TurbineTypeElement> result = ImmutableSet.builder(); PackageScope scope = factory.tli().lookupPackage(Splitter.on('/').split(sym.binaryName())); for (ClassSymbol key : scope.classes()) { if (key.binaryName().contains("$") && factory.getSymbol(key).owner() != null) { // Skip member classes: only top-level classes are enclosed by the package. // The initial check for '$' is an optimization. continue; } if (key.simpleName().equals("package-info")) { continue; } result.add(factory.typeElement(key)); } return result.build().asList(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitPackage(this, p); } @Override public PackageSymbol sym() { return sym; } @Override public String javadoc() { return null; } @Override public int hashCode() { return sym.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof TurbinePackageElement && sym.equals(((TurbinePackageElement) obj).sym); } private final Supplier<ImmutableList<AnnoInfo>> annos = memoize( new Supplier<ImmutableList<AnnoInfo>>() { @Override public ImmutableList<AnnoInfo> get() { TypeBoundClass info = factory.getSymbol(new ClassSymbol(sym.binaryName() + "/package-info")); return info != null ? info.annotations() : ImmutableList.of(); } }); @Override protected ImmutableList<AnnoInfo> annos() { return annos.get(); } @Override public String toString() { return sym.toString(); } } /** A {@link VariableElement} implementation backed by a {@link ParamSymbol}. */ static class TurbineParameterElement extends TurbineElement implements VariableElement { @Override public ParamSymbol sym() { return sym; } @Override public String javadoc() { return null; } @Override public int hashCode() { return sym.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineParameterElement && sym.equals(((TurbineParameterElement) obj).sym); } private final ParamSymbol sym; private final Supplier<ParamInfo> info = memoize( new Supplier<ParamInfo>() { @Override public ParamInfo get() { return factory.getParamInfo(sym); } }); @Nullable ParamInfo info() { return info.get(); } public TurbineParameterElement(ModelFactory factory, ParamSymbol sym) { super(factory); this.sym = sym; } @Override public Object getConstantValue() { return null; } private final Supplier<TypeMirror> type = memoize( new Supplier<TypeMirror>() { @Override public TypeMirror get() { return factory.asTypeMirror(info().type()); } }); @Override public TypeMirror asType() { return type.get(); } @Override public ElementKind getKind() { return ElementKind.PARAMETER; } @Override public Set<Modifier> getModifiers() { return asModifierSet(ModifierOwner.PARAMETER, info().access()); } @Override public Name getSimpleName() { return new TurbineName(sym.name()); } @Override public Element getEnclosingElement() { return factory.executableElement(sym.owner()); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitVariable(this, p); } @Override public String toString() { return String.valueOf(sym.name()); } @Override protected ImmutableList<AnnoInfo> annos() { return info().annotations(); } } static class TurbineNoTypeElement implements TypeElement { private final ModelFactory factory; private final String name; public TurbineNoTypeElement(ModelFactory factory, String name) { this.factory = factory; this.name = requireNonNull(name); } @Override public TypeMirror asType() { return factory.noType(); } @Override public ElementKind getKind() { return ElementKind.CLASS; } @Override public Set<Modifier> getModifiers() { return ImmutableSet.of(); } @Override public Name getSimpleName() { return new TurbineName(name.substring(name.lastIndexOf('.') + 1)); } @Override public TypeMirror getSuperclass() { return factory.noType(); } @Override public List<? extends TypeMirror> getInterfaces() { return ImmutableList.of(); } @Override public List<? extends TypeParameterElement> getTypeParameters() { return ImmutableList.of(); } @Override public Element getEnclosingElement() { int idx = name.lastIndexOf('.'); String packageName; if (idx == -1) { packageName = ""; } else { packageName = name.substring(0, idx).replace('.', '/'); } return factory.packageElement(new PackageSymbol(packageName)); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public NestingKind getNestingKind() { return NestingKind.TOP_LEVEL; } @Override public Name getQualifiedName() { return new TurbineName(name); } @Override public List<? extends AnnotationMirror> getAnnotationMirrors() { return ImmutableList.of(); } @Override public <A extends Annotation> A getAnnotation(Class<A> aClass) { return null; } @Override public <A extends Annotation> A[] getAnnotationsByType(Class<A> aClass) { return null; } @Override public <R, P> R accept(ElementVisitor<R, P> elementVisitor, P p) { return elementVisitor.visitType(this, p); } @Override public String toString() { return getSimpleName().toString(); } } }
java/com/google/turbine/processing/TurbineElement.java
/* * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.turbine.processing; import static java.util.Objects.requireNonNull; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.turbine.binder.bound.AnnotationMetadata; import com.google.turbine.binder.bound.SourceTypeBoundClass; import com.google.turbine.binder.bound.TurbineAnnotationValue; import com.google.turbine.binder.bound.TypeBoundClass; import com.google.turbine.binder.bound.TypeBoundClass.FieldInfo; import com.google.turbine.binder.bound.TypeBoundClass.MethodInfo; import com.google.turbine.binder.bound.TypeBoundClass.ParamInfo; import com.google.turbine.binder.bound.TypeBoundClass.TyVarInfo; import com.google.turbine.binder.lookup.PackageScope; import com.google.turbine.binder.sym.ClassSymbol; import com.google.turbine.binder.sym.FieldSymbol; import com.google.turbine.binder.sym.MethodSymbol; import com.google.turbine.binder.sym.PackageSymbol; import com.google.turbine.binder.sym.ParamSymbol; import com.google.turbine.binder.sym.Symbol; import com.google.turbine.binder.sym.TyVarSymbol; import com.google.turbine.diag.TurbineError; import com.google.turbine.diag.TurbineError.ErrorKind; import com.google.turbine.model.Const; import com.google.turbine.model.Const.ArrayInitValue; import com.google.turbine.model.TurbineFlag; import com.google.turbine.model.TurbineTyKind; import com.google.turbine.tree.Tree.MethDecl; import com.google.turbine.tree.Tree.TyDecl; import com.google.turbine.tree.Tree.VarDecl; import com.google.turbine.type.AnnoInfo; import com.google.turbine.type.Type; import com.google.turbine.type.Type.ClassTy; import com.google.turbine.type.Type.ClassTy.SimpleClassTy; import com.google.turbine.type.Type.ErrorTy; import java.lang.annotation.Annotation; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ElementVisitor; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.NestingKind; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import org.checkerframework.checker.nullness.qual.Nullable; /** An {@link Element} implementation backed by a {@link Symbol}. */ public abstract class TurbineElement implements Element { public abstract Symbol sym(); public abstract String javadoc(); @Override public abstract int hashCode(); @Override public abstract boolean equals(Object obj); protected final ModelFactory factory; private final Supplier<ImmutableList<AnnotationMirror>> annotationMirrors; protected <T> Supplier<T> memoize(Supplier<T> supplier) { return factory.memoize(supplier); } protected TurbineElement(ModelFactory factory) { this.factory = requireNonNull(factory); this.annotationMirrors = factory.memoize( new Supplier<ImmutableList<AnnotationMirror>>() { @Override public ImmutableList<AnnotationMirror> get() { ImmutableList.Builder<AnnotationMirror> result = ImmutableList.builder(); for (AnnoInfo anno : annos()) { result.add(TurbineAnnotationMirror.create(factory, anno)); } return result.build(); } }); } static AnnoInfo getAnnotation(Iterable<AnnoInfo> annos, ClassSymbol sym) { for (AnnoInfo anno : annos) { if (Objects.equals(anno.sym(), sym)) { return anno; } } return null; } @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) { ClassSymbol sym = new ClassSymbol(annotationType.getName().replace('.', '/')); TypeBoundClass info = factory.getSymbol(sym); if (info == null) { return null; } AnnoInfo anno = getAnnotation(annos(), sym); if (anno == null) { return null; } return TurbineAnnotationProxy.create(factory, annotationType, anno); } @Override public final <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) { ClassSymbol sym = new ClassSymbol(annotationType.getName().replace('.', '/')); TypeBoundClass info = factory.getSymbol(sym); if (info == null) { return null; } AnnotationMetadata metadata = info.annotationMetadata(); if (metadata == null) { return null; } List<A> result = new ArrayList<>(); for (AnnoInfo anno : annos()) { if (anno.sym().equals(sym)) { result.add(TurbineAnnotationProxy.create(factory, annotationType, anno)); continue; } if (anno.sym().equals(metadata.repeatable())) { ArrayInitValue arrayValue = (ArrayInitValue) anno.values().get("value"); for (Const element : arrayValue.elements()) { result.add( TurbineAnnotationProxy.create( factory, annotationType, ((TurbineAnnotationValue) element).info())); } } } return Iterables.toArray(result, annotationType); } @Override public final List<? extends AnnotationMirror> getAnnotationMirrors() { return annotationMirrors.get(); } List<? extends AnnotationMirror> getAllAnnotationMirrors() { return getAnnotationMirrors(); } protected abstract ImmutableList<AnnoInfo> annos(); /** A {@link TypeElement} implementation backed by a {@link ClassSymbol}. */ static class TurbineTypeElement extends TurbineElement implements TypeElement { @Override public int hashCode() { return sym.hashCode(); } private final ClassSymbol sym; private final Supplier<TypeBoundClass> info; TurbineTypeElement(ModelFactory factory, ClassSymbol sym) { super(factory); this.sym = requireNonNull(sym); this.info = memoize( new Supplier<TypeBoundClass>() { @Override public TypeBoundClass get() { return factory.getSymbol(sym); } }); } @Nullable TypeBoundClass info() { return info.get(); } TypeBoundClass infoNonNull() { TypeBoundClass info = info(); if (info == null) { throw TurbineError.format(/* source= */ null, ErrorKind.SYMBOL_NOT_FOUND, sym); } return info; } @Override public NestingKind getNestingKind() { TypeBoundClass info = info(); return (info != null && info.owner() != null) ? NestingKind.MEMBER : NestingKind.TOP_LEVEL; } private final Supplier<TurbineName> qualifiedName = memoize( new Supplier<TurbineName>() { @Override public TurbineName get() { TypeBoundClass info = info(); if (info == null || info.owner() == null) { return new TurbineName(sym.toString()); } ClassSymbol sym = sym(); Deque<String> flat = new ArrayDeque<>(); while (info.owner() != null) { flat.addFirst(sym.binaryName().substring(info.owner().binaryName().length() + 1)); sym = info.owner(); info = factory.getSymbol(sym); } flat.addFirst(sym.toString()); return new TurbineName(Joiner.on('.').join(flat)); } }); @Override public Name getQualifiedName() { return qualifiedName.get(); } private final Supplier<TypeMirror> superclass = memoize( new Supplier<TypeMirror>() { @Override public TypeMirror get() { TypeBoundClass info = infoNonNull(); switch (info.kind()) { case CLASS: case ENUM: if (info.superclass() != null) { return factory.asTypeMirror(info.superClassType()); } if (info instanceof SourceTypeBoundClass) { // support simple name for stuff that doesn't exist TyDecl decl = ((SourceTypeBoundClass) info).decl(); if (decl.xtnds().isPresent()) { return factory.asTypeMirror( ErrorTy.create(decl.xtnds().get().name().value())); } } return factory.noType(); case INTERFACE: case ANNOTATION: return factory.noType(); } throw new AssertionError(info.kind()); } }); @Override public TypeMirror getSuperclass() { return superclass.get(); } @Override public String toString() { return getQualifiedName().toString(); } private final Supplier<List<TypeMirror>> interfaces = memoize( new Supplier<List<TypeMirror>>() { @Override public List<TypeMirror> get() { return factory.asTypeMirrors(infoNonNull().interfaceTypes()); } }); @Override public List<? extends TypeMirror> getInterfaces() { return interfaces.get(); } private final Supplier<ImmutableList<TypeParameterElement>> typeParameters = memoize( new Supplier<ImmutableList<TypeParameterElement>>() { @Override public ImmutableList<TypeParameterElement> get() { ImmutableList.Builder<TypeParameterElement> result = ImmutableList.builder(); for (TyVarSymbol p : infoNonNull().typeParameters().values()) { result.add(factory.typeParameterElement(p)); } return result.build(); } }); @Override public List<? extends TypeParameterElement> getTypeParameters() { return typeParameters.get(); } private final Supplier<TypeMirror> type = memoize( new Supplier<TypeMirror>() { @Override public TypeMirror get() { return factory.asTypeMirror(asGenericType(sym)); } ClassTy asGenericType(ClassSymbol symbol) { TypeBoundClass info = info(); if (info == null) { return ClassTy.asNonParametricClassTy(symbol); } Deque<Type.ClassTy.SimpleClassTy> simples = new ArrayDeque<>(); simples.addFirst(simple(symbol, info)); while (info.owner() != null && (info.access() & TurbineFlag.ACC_STATIC) == 0) { symbol = info.owner(); info = factory.getSymbol(symbol); simples.addFirst(simple(symbol, info)); } return ClassTy.create(ImmutableList.copyOf(simples)); } private SimpleClassTy simple(ClassSymbol sym, TypeBoundClass info) { ImmutableList.Builder<Type> args = ImmutableList.builder(); for (TyVarSymbol t : info.typeParameters().values()) { args.add(Type.TyVar.create(t, ImmutableList.of())); } return SimpleClassTy.create(sym, args.build(), ImmutableList.of()); } }); @Override public TypeMirror asType() { return type.get(); } @Override public ElementKind getKind() { TypeBoundClass info = infoNonNull(); switch (info.kind()) { case CLASS: return ElementKind.CLASS; case INTERFACE: return ElementKind.INTERFACE; case ENUM: return ElementKind.ENUM; case ANNOTATION: return ElementKind.ANNOTATION_TYPE; } throw new AssertionError(info.kind()); } @Override public Set<Modifier> getModifiers() { return asModifierSet(ModifierOwner.TYPE, infoNonNull().access() & ~TurbineFlag.ACC_SUPER); } private final Supplier<TurbineName> simpleName = memoize( new Supplier<TurbineName>() { @Override public TurbineName get() { TypeBoundClass info = info(); if (info == null || info.owner() == null) { return new TurbineName(sym.simpleName()); } return new TurbineName( sym.binaryName().substring(info.owner().binaryName().length() + 1)); } }); @Override public Name getSimpleName() { return simpleName.get(); } private final Supplier<Element> enclosing = memoize( new Supplier<Element>() { @Override public Element get() { return getNestingKind().equals(NestingKind.TOP_LEVEL) ? factory.packageElement(sym.owner()) : factory.typeElement(info().owner()); } }); @Override public Element getEnclosingElement() { return enclosing.get(); } private final Supplier<ImmutableList<Element>> enclosed = memoize( new Supplier<ImmutableList<Element>>() { @Override public ImmutableList<Element> get() { TypeBoundClass info = infoNonNull(); ImmutableList.Builder<Element> result = ImmutableList.builder(); for (FieldInfo field : info.fields()) { result.add(factory.fieldElement(field.sym())); } for (MethodInfo method : info.methods()) { result.add(factory.executableElement(method.sym())); } for (ClassSymbol child : info.children().values()) { result.add(factory.typeElement(child)); } return result.build(); } }); @Override public List<? extends Element> getEnclosedElements() { return enclosed.get(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitType(this, p); } @Override public ClassSymbol sym() { return sym; } @Override public String javadoc() { TypeBoundClass info = info(); if (!(info instanceof SourceTypeBoundClass)) { return null; } return ((SourceTypeBoundClass) info).decl().javadoc(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineTypeElement && sym.equals(((TurbineTypeElement) obj).sym); } @Override protected ImmutableList<AnnoInfo> annos() { return infoNonNull().annotations(); } @Override public final <A extends Annotation> A getAnnotation(Class<A> annotationType) { ClassSymbol sym = new ClassSymbol(annotationType.getName().replace('.', '/')); AnnoInfo anno = getAnnotation(annos(), sym); if (anno != null) { return TurbineAnnotationProxy.create(factory, annotationType, anno); } if (!isAnnotationInherited(sym)) { return null; } ClassSymbol superclass = infoNonNull().superclass(); while (superclass != null) { TypeBoundClass info = factory.getSymbol(superclass); if (info == null) { break; } anno = getAnnotation(info.annotations(), sym); if (anno != null) { return TurbineAnnotationProxy.create(factory, annotationType, anno); } superclass = info.superclass(); } return null; } @Override List<? extends AnnotationMirror> getAllAnnotationMirrors() { Map<ClassSymbol, AnnotationMirror> result = new LinkedHashMap<>(); for (AnnoInfo anno : annos()) { result.put(anno.sym(), TurbineAnnotationMirror.create(factory, anno)); } ClassSymbol superclass = infoNonNull().superclass(); while (superclass != null) { TypeBoundClass i = factory.getSymbol(superclass); if (i == null) { break; } for (AnnoInfo anno : i.annotations()) { addAnnotationFromSuper(result, anno); } superclass = i.superclass(); } return ImmutableList.copyOf(result.values()); } private void addAnnotationFromSuper(Map<ClassSymbol, AnnotationMirror> result, AnnoInfo anno) { if (!isAnnotationInherited(anno.sym())) { return; } if (result.containsKey(anno.sym())) { // if the same inherited annotation is present on multiple supertypes, only return one return; } result.put(anno.sym(), TurbineAnnotationMirror.create(factory, anno)); } private boolean isAnnotationInherited(ClassSymbol sym) { TypeBoundClass annoInfo = factory.getSymbol(sym); if (annoInfo == null) { return false; } for (AnnoInfo anno : annoInfo.annotations()) { if (anno.sym().equals(ClassSymbol.INHERITED)) { return true; } } return false; } } /** A {@link TypeParameterElement} implementation backed by a {@link TyVarSymbol}. */ static class TurbineTypeParameterElement extends TurbineElement implements TypeParameterElement { @Override public int hashCode() { return sym.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineTypeParameterElement && sym.equals(((TurbineTypeParameterElement) obj).sym); } private final TyVarSymbol sym; public TurbineTypeParameterElement(ModelFactory factory, TyVarSymbol sym) { super(factory); this.sym = sym; } private final Supplier<TyVarInfo> info = memoize( new Supplier<TyVarInfo>() { @Override public TyVarInfo get() { return factory.getTyVarInfo(sym); } }); @Nullable private TyVarInfo info() { return info.get(); } @Override public String toString() { return sym.name(); } @Override public Element getGenericElement() { return factory.element(sym.owner()); } @Override public List<? extends TypeMirror> getBounds() { ImmutableList<Type> bounds = info().upperBound().bounds(); return factory.asTypeMirrors(bounds.isEmpty() ? ImmutableList.of(ClassTy.OBJECT) : bounds); } @Override public TypeMirror asType() { return factory.asTypeMirror(Type.TyVar.create(sym, info().annotations())); } @Override public ElementKind getKind() { return ElementKind.TYPE_PARAMETER; } @Override public Set<Modifier> getModifiers() { return ImmutableSet.of(); } @Override public Name getSimpleName() { return new TurbineName(sym.name()); } @Override public Element getEnclosingElement() { return getGenericElement(); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitTypeParameter(this, p); } @Override public TyVarSymbol sym() { return sym; } @Override public String javadoc() { return null; } @Override protected ImmutableList<AnnoInfo> annos() { return info().annotations(); } } /** An {@link ExecutableElement} implementation backed by a {@link MethodSymbol}. */ static class TurbineExecutableElement extends TurbineElement implements ExecutableElement { private final MethodSymbol sym; private final Supplier<MethodInfo> info = memoize( new Supplier<MethodInfo>() { @Override public MethodInfo get() { return factory.getMethodInfo(sym); } }); @Nullable MethodInfo info() { return info.get(); } TurbineExecutableElement(ModelFactory factory, MethodSymbol sym) { super(factory); this.sym = sym; } @Override public MethodSymbol sym() { return sym; } @Override public String javadoc() { MethDecl decl = info().decl(); return decl != null ? decl.javadoc() : null; } @Override public int hashCode() { return sym.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineExecutableElement && sym.equals(((TurbineExecutableElement) obj).sym); } @Override public List<? extends TypeParameterElement> getTypeParameters() { ImmutableList.Builder<TurbineTypeParameterElement> result = ImmutableList.builder(); for (Map.Entry<TyVarSymbol, TyVarInfo> p : info().tyParams().entrySet()) { result.add(factory.typeParameterElement(p.getKey())); } return result.build(); } @Override public TypeMirror getReturnType() { return factory.asTypeMirror(info().returnType()); } private final Supplier<ImmutableList<VariableElement>> parameters = memoize( new Supplier<ImmutableList<VariableElement>>() { @Override public ImmutableList<VariableElement> get() { ImmutableList.Builder<VariableElement> result = ImmutableList.builder(); for (ParamInfo param : info().parameters()) { if (param.synthetic()) { // ExecutableElement#getParameters doesn't expect synthetic or mandated // parameters continue; } result.add(factory.parameterElement(param.sym())); } return result.build(); } }); @Override public List<? extends VariableElement> getParameters() { return parameters.get(); } @Override public String toString() { MethodInfo info = info(); StringBuilder sb = new StringBuilder(); if (!info.tyParams().isEmpty()) { sb.append('<'); Joiner.on(',').appendTo(sb, info.tyParams().keySet()); sb.append('>'); } if (getKind() == ElementKind.CONSTRUCTOR) { sb.append(info.sym().owner().simpleName()); } else { sb.append(info.sym().name()); } sb.append('('); boolean first = true; for (ParamInfo p : info.parameters()) { if (!first) { sb.append(','); } sb.append(p.type()); first = false; } sb.append(')'); return sb.toString(); } @Override public TypeMirror getReceiverType() { return info().receiver() != null ? factory.asTypeMirror(info().receiver().type()) : factory.noType(); } @Override public boolean isVarArgs() { return (info().access() & TurbineFlag.ACC_VARARGS) == TurbineFlag.ACC_VARARGS; } @Override public boolean isDefault() { return (info().access() & TurbineFlag.ACC_DEFAULT) == TurbineFlag.ACC_DEFAULT; } @Override public List<? extends TypeMirror> getThrownTypes() { return factory.asTypeMirrors(info().exceptions()); } @Override public AnnotationValue getDefaultValue() { return info().defaultValue() != null ? TurbineAnnotationMirror.annotationValue(factory, info().defaultValue()) : null; } @Override public TypeMirror asType() { return factory.asTypeMirror(info().asType()); } @Override public ElementKind getKind() { return info().name().equals("<init>") ? ElementKind.CONSTRUCTOR : ElementKind.METHOD; } @Override public Set<Modifier> getModifiers() { int access = info().access(); if (factory.getSymbol(info().sym().owner()).kind() == TurbineTyKind.INTERFACE) { if ((access & (TurbineFlag.ACC_ABSTRACT | TurbineFlag.ACC_STATIC)) == 0) { access |= TurbineFlag.ACC_DEFAULT; } } return asModifierSet(ModifierOwner.METHOD, access); } @Override public Name getSimpleName() { return new TurbineName(info().sym().name()); } @Override public Element getEnclosingElement() { return factory.typeElement(info().sym().owner()); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitExecutable(this, p); } @Override protected ImmutableList<AnnoInfo> annos() { return info().annotations(); } } /** An {@link VariableElement} implementation backed by a {@link FieldSymbol}. */ static class TurbineFieldElement extends TurbineElement implements VariableElement { @Override public String toString() { return sym.name(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineFieldElement && sym.equals(((TurbineFieldElement) obj).sym); } @Override public int hashCode() { return sym.hashCode(); } private final FieldSymbol sym; @Override public FieldSymbol sym() { return sym; } @Override public String javadoc() { VarDecl decl = info().decl(); return decl != null ? decl.javadoc() : null; } private final Supplier<FieldInfo> info = memoize( new Supplier<FieldInfo>() { @Override public FieldInfo get() { return factory.getFieldInfo(sym); } }); @Nullable FieldInfo info() { return info.get(); } TurbineFieldElement(ModelFactory factory, FieldSymbol sym) { super(factory); this.sym = sym; } @Override public Object getConstantValue() { if (info().value() == null) { return null; } return info().value().getValue(); } @Override public TypeMirror asType() { return factory.asTypeMirror(info().type()); } @Override public ElementKind getKind() { return ((info().access() & TurbineFlag.ACC_ENUM) == TurbineFlag.ACC_ENUM) ? ElementKind.ENUM_CONSTANT : ElementKind.FIELD; } @Override public Set<Modifier> getModifiers() { return asModifierSet(ModifierOwner.FIELD, info().access()); } @Override public Name getSimpleName() { return new TurbineName(sym.name()); } @Override public Element getEnclosingElement() { return factory.typeElement(sym.owner()); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitVariable(this, p); } @Override protected ImmutableList<AnnoInfo> annos() { return info().annotations(); } } private enum ModifierOwner { TYPE, PARAMETER, FIELD, METHOD } private static ImmutableSet<Modifier> asModifierSet(ModifierOwner modifierOwner, int access) { EnumSet<Modifier> modifiers = EnumSet.noneOf(Modifier.class); if ((access & TurbineFlag.ACC_PUBLIC) == TurbineFlag.ACC_PUBLIC) { modifiers.add(Modifier.PUBLIC); } if ((access & TurbineFlag.ACC_PROTECTED) == TurbineFlag.ACC_PROTECTED) { modifiers.add(Modifier.PROTECTED); } if ((access & TurbineFlag.ACC_PRIVATE) == TurbineFlag.ACC_PRIVATE) { modifiers.add(Modifier.PRIVATE); } if ((access & TurbineFlag.ACC_ABSTRACT) == TurbineFlag.ACC_ABSTRACT) { modifiers.add(Modifier.ABSTRACT); } if ((access & TurbineFlag.ACC_FINAL) == TurbineFlag.ACC_FINAL) { modifiers.add(Modifier.FINAL); } if ((access & TurbineFlag.ACC_DEFAULT) == TurbineFlag.ACC_DEFAULT) { modifiers.add(Modifier.DEFAULT); } if ((access & TurbineFlag.ACC_STATIC) == TurbineFlag.ACC_STATIC) { modifiers.add(Modifier.STATIC); } if ((access & TurbineFlag.ACC_TRANSIENT) == TurbineFlag.ACC_TRANSIENT) { switch (modifierOwner) { case METHOD: case PARAMETER: // varargs and transient use the same bits break; default: modifiers.add(Modifier.TRANSIENT); } } if ((access & TurbineFlag.ACC_VOLATILE) == TurbineFlag.ACC_VOLATILE) { modifiers.add(Modifier.VOLATILE); } if ((access & TurbineFlag.ACC_SYNCHRONIZED) == TurbineFlag.ACC_SYNCHRONIZED) { modifiers.add(Modifier.SYNCHRONIZED); } if ((access & TurbineFlag.ACC_NATIVE) == TurbineFlag.ACC_NATIVE) { modifiers.add(Modifier.NATIVE); } if ((access & TurbineFlag.ACC_STRICT) == TurbineFlag.ACC_STRICT) { modifiers.add(Modifier.STRICTFP); } return Sets.immutableEnumSet(modifiers); } /** A {@link PackageElement} implementation backed by a {@link PackageSymbol}. */ static class TurbinePackageElement extends TurbineElement implements PackageElement { private final PackageSymbol sym; public TurbinePackageElement(ModelFactory factory, PackageSymbol sym) { super(factory); this.sym = sym; } @Override public Name getQualifiedName() { return new TurbineName(sym.toString()); } @Override public boolean isUnnamed() { return sym.binaryName().isEmpty(); } @Override public TypeMirror asType() { return factory.packageType(sym); } @Override public ElementKind getKind() { return ElementKind.PACKAGE; } @Override public Set<Modifier> getModifiers() { return ImmutableSet.of(); } @Override public Name getSimpleName() { return new TurbineName(sym.binaryName().substring(sym.binaryName().lastIndexOf('/') + 1)); } @Override public Element getEnclosingElement() { // a package is not enclosed by another element return null; } @Override public List<TurbineTypeElement> getEnclosedElements() { ImmutableSet.Builder<TurbineTypeElement> result = ImmutableSet.builder(); PackageScope scope = factory.tli().lookupPackage(Splitter.on('/').split(sym.binaryName())); for (ClassSymbol key : scope.classes()) { if (key.binaryName().contains("$") && factory.getSymbol(key).owner() != null) { // Skip member classes: only top-level classes are enclosed by the package. // The initial check for '$' is an optimization. continue; } if (key.simpleName().equals("package-info")) { continue; } result.add(factory.typeElement(key)); } return result.build().asList(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitPackage(this, p); } @Override public PackageSymbol sym() { return sym; } @Override public String javadoc() { return null; } @Override public int hashCode() { return sym.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof TurbinePackageElement && sym.equals(((TurbinePackageElement) obj).sym); } private final Supplier<ImmutableList<AnnoInfo>> annos = memoize( new Supplier<ImmutableList<AnnoInfo>>() { @Override public ImmutableList<AnnoInfo> get() { TypeBoundClass info = factory.getSymbol(new ClassSymbol(sym.binaryName() + "/package-info")); return info != null ? info.annotations() : ImmutableList.of(); } }); @Override protected ImmutableList<AnnoInfo> annos() { return annos.get(); } @Override public String toString() { return sym.toString(); } } /** A {@link VariableElement} implementation backed by a {@link ParamSymbol}. */ static class TurbineParameterElement extends TurbineElement implements VariableElement { @Override public ParamSymbol sym() { return sym; } @Override public String javadoc() { return null; } @Override public int hashCode() { return sym.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof TurbineParameterElement && sym.equals(((TurbineParameterElement) obj).sym); } private final ParamSymbol sym; private final Supplier<ParamInfo> info = memoize( new Supplier<ParamInfo>() { @Override public ParamInfo get() { return factory.getParamInfo(sym); } }); @Nullable ParamInfo info() { return info.get(); } public TurbineParameterElement(ModelFactory factory, ParamSymbol sym) { super(factory); this.sym = sym; } @Override public Object getConstantValue() { return null; } private final Supplier<TypeMirror> type = memoize( new Supplier<TypeMirror>() { @Override public TypeMirror get() { return factory.asTypeMirror(info().type()); } }); @Override public TypeMirror asType() { return type.get(); } @Override public ElementKind getKind() { return ElementKind.PARAMETER; } @Override public Set<Modifier> getModifiers() { return asModifierSet(ModifierOwner.PARAMETER, info().access()); } @Override public Name getSimpleName() { return new TurbineName(sym.name()); } @Override public Element getEnclosingElement() { return factory.executableElement(sym.owner()); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public <R, P> R accept(ElementVisitor<R, P> v, P p) { return v.visitVariable(this, p); } @Override public String toString() { return String.valueOf(sym.name()); } @Override protected ImmutableList<AnnoInfo> annos() { return info().annotations(); } } static class TurbineNoTypeElement implements TypeElement { private final ModelFactory factory; private final String name; public TurbineNoTypeElement(ModelFactory factory, String name) { this.factory = factory; this.name = requireNonNull(name); } @Override public TypeMirror asType() { return factory.noType(); } @Override public ElementKind getKind() { return ElementKind.CLASS; } @Override public Set<Modifier> getModifiers() { return ImmutableSet.of(); } @Override public Name getSimpleName() { return new TurbineName(name.substring(name.lastIndexOf('.') + 1)); } @Override public TypeMirror getSuperclass() { return factory.noType(); } @Override public List<? extends TypeMirror> getInterfaces() { return ImmutableList.of(); } @Override public List<? extends TypeParameterElement> getTypeParameters() { return ImmutableList.of(); } @Override public Element getEnclosingElement() { int idx = name.lastIndexOf('.'); String packageName; if (idx == -1) { packageName = ""; } else { packageName = name.substring(0, idx).replace('.', '/'); } return factory.packageElement(new PackageSymbol(packageName)); } @Override public List<? extends Element> getEnclosedElements() { return ImmutableList.of(); } @Override public NestingKind getNestingKind() { return NestingKind.TOP_LEVEL; } @Override public Name getQualifiedName() { return new TurbineName(name); } @Override public List<? extends AnnotationMirror> getAnnotationMirrors() { return ImmutableList.of(); } @Override public <A extends Annotation> A getAnnotation(Class<A> aClass) { return null; } @Override public <A extends Annotation> A[] getAnnotationsByType(Class<A> aClass) { return null; } @Override public <R, P> R accept(ElementVisitor<R, P> elementVisitor, P p) { return elementVisitor.visitType(this, p); } @Override public String toString() { return getSimpleName().toString(); } } }
Micro-optimize TurbineExecutableElement#getKind retrieving the MethodInfo is more expensive than looking at the symbol. PiperOrigin-RevId: 333428787
java/com/google/turbine/processing/TurbineElement.java
Micro-optimize TurbineExecutableElement#getKind
Java
apache-2.0
25a443c2423abdc56051057ae5d187577473bc0f
0
pongo710/urlaubsverwaltung,pongo710/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,Intera/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,Intera/urlaubsverwaltung,pongo710/urlaubsverwaltung,Intera/urlaubsverwaltung
package org.synyx.urlaubsverwaltung.core.startup; import org.apache.log4j.Logger; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.synyx.urlaubsverwaltung.core.application.domain.Application; import org.synyx.urlaubsverwaltung.core.application.domain.DayLength; import org.synyx.urlaubsverwaltung.core.application.domain.VacationType; import org.synyx.urlaubsverwaltung.core.application.service.ApplicationInteractionService; import org.synyx.urlaubsverwaltung.core.calendar.Day; import org.synyx.urlaubsverwaltung.core.calendar.WorkDaysService; import org.synyx.urlaubsverwaltung.core.department.Department; import org.synyx.urlaubsverwaltung.core.department.DepartmentService; import org.synyx.urlaubsverwaltung.core.mail.MailNotification; import org.synyx.urlaubsverwaltung.core.person.Person; import org.synyx.urlaubsverwaltung.core.person.PersonInteractionService; import org.synyx.urlaubsverwaltung.core.sicknote.SickNote; import org.synyx.urlaubsverwaltung.core.sicknote.SickNoteInteractionService; import org.synyx.urlaubsverwaltung.core.sicknote.SickNoteType; import org.synyx.urlaubsverwaltung.core.util.CalcUtil; import org.synyx.urlaubsverwaltung.security.Role; import org.synyx.urlaubsverwaltung.web.person.PersonForm; import java.math.BigDecimal; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import javax.annotation.PostConstruct; /** * @author Aljona Murygina - murygina@synyx.de */ @Service public class TestDataCreationService { private static final Logger LOG = Logger.getLogger(TestDataCreationService.class); private static final String ENVIRONMENT_PROPERTY = "env"; private static final String DEV_ENVIRONMENT = "dev"; public static final String USER = "testUser"; public static final String BOSS_USER = "testBoss"; public static final String OFFICE_USER = "test"; @Autowired private PersonInteractionService personInteractionService; @Autowired private ApplicationInteractionService applicationInteractionService; @Autowired private SickNoteInteractionService sickNoteInteractionService; @Autowired private WorkDaysService calendarService; @Autowired private DepartmentService departmentService; private Person user; private Person boss; private Person office; @PostConstruct public void createTestData() throws NoSuchAlgorithmException { String environment = System.getProperties().getProperty(ENVIRONMENT_PROPERTY); if (environment.equals(DEV_ENVIRONMENT)) { LOG.info("Test data will be created..."); user = createTestPerson(USER, "Klaus", "Müller", "mueller@muster.de", Role.USER); boss = createTestPerson(BOSS_USER, "Max", "Mustermann", "maxMuster@muster.de", Role.USER, Role.BOSS); office = createTestPerson(OFFICE_USER, "Marlene", "Muster", "mmuster@muster.de", Role.USER, Role.BOSS, Role.OFFICE); createTestPerson("hdampf", "Hans", "Dampf", "dampf@foo.bar", Role.USER, Role.OFFICE); createTestPerson("horst", "Horst", "Dieter", "hdieter@muster.de", Role.INACTIVE); createTestData(user); createTestData(boss); createTestData(office); createTestDepartment("Admins", "Das sind die, die so Admin Sachen machen"); createTestDepartment("Marketing", "Das sind die, die so Marketing Sachen machen"); createTestDepartment("Geschäftsführung", "Das sind die, die so Geschäftsführung Sachen machen"); } else { LOG.info("No test data will be created."); } } private void createTestDepartment(String name, String description) { Department department = new Department(); department.setName(name); department.setDescription(description); department.setLastModification(DateTime.now()); departmentService.create(department); } private Person createTestPerson(String login, String firstName, String lastName, String email, Role... roles) throws NoSuchAlgorithmException { int currentYear = DateMidnight.now().getYear(); PersonForm personForm = new PersonForm(DateMidnight.now().getYear()); personForm.setLoginName(login); personForm.setLastName(lastName); personForm.setFirstName(firstName); personForm.setEmail(email); personForm.setAnnualVacationDays(new BigDecimal("28.5")); personForm.setRemainingVacationDays(new BigDecimal("5")); personForm.setRemainingVacationDaysNotExpiring(BigDecimal.ZERO); personForm.setValidFrom(new DateMidnight(currentYear - 1, 1, 1)); personForm.setWorkingDays(Arrays.asList(Day.MONDAY.getDayOfWeek(), Day.TUESDAY.getDayOfWeek(), Day.WEDNESDAY.getDayOfWeek(), Day.THURSDAY.getDayOfWeek(), Day.FRIDAY.getDayOfWeek())); personForm.setPermissions(Arrays.asList(roles)); List<MailNotification> notifications = new ArrayList<>(); notifications.add(MailNotification.NOTIFICATION_USER); if (personForm.getPermissions().contains(Role.BOSS)) { notifications.add(MailNotification.NOTIFICATION_BOSS); } if (personForm.getPermissions().contains(Role.OFFICE)) { notifications.add(MailNotification.NOTIFICATION_OFFICE); } personForm.setNotifications(notifications); return personInteractionService.create(personForm); } private void createTestData(Person person) { DateMidnight now = DateMidnight.now(); // FUTURE APPLICATIONS FOR LEAVE createWaitingApplication(person, VacationType.HOLIDAY, DayLength.FULL, now.plusDays(10), now.plusDays(16)); // NOSONAR createWaitingApplication(person, VacationType.OVERTIME, DayLength.FULL, now.plusDays(1), now.plusDays(2)); // NOSONAR createWaitingApplication(person, VacationType.SPECIALLEAVE, DayLength.FULL, now.plusDays(4), now.plusDays(6)); // NOSONAR // PAST APPLICATIONS FOR LEAVE createAllowedApplication(person, VacationType.HOLIDAY, DayLength.FULL, now.minusDays(20), now.minusDays(13)); // NOSONAR createAllowedApplication(person, VacationType.HOLIDAY, DayLength.MORNING, now.minusDays(5), now.minusDays(5)); // NOSONAR createAllowedApplication(person, VacationType.SPECIALLEAVE, DayLength.MORNING, now.minusDays(9), // NOSONAR now.minusDays(9)); // NOSONAR createRejectedApplication(person, VacationType.HOLIDAY, DayLength.FULL, now.minusDays(33), now.minusDays(30)); // NOSONAR createCancelledApplication(person, VacationType.HOLIDAY, DayLength.FULL, now.minusDays(11), now.minusDays(10)); // NOSONAR // SICK NOTES createSickNote(person, now.minusDays(10), now.minusDays(10), SickNoteType.SICK_NOTE, false); // NOSONAR createSickNote(person, now.minusDays(30), now.minusDays(25), SickNoteType.SICK_NOTE, true); // NOSONAR createSickNote(person, now.minusDays(60), now.minusDays(55), SickNoteType.SICK_NOTE_CHILD, true); // NOSONAR createSickNote(person, now.minusDays(44), now.minusDays(44), SickNoteType.SICK_NOTE_CHILD, false); // NOSONAR } private Application createWaitingApplication(Person person, VacationType vacationType, DayLength dayLength, DateMidnight startDate, DateMidnight endDate) { Application application = null; if (startAndEndDatesAreInCurrentYear(startDate, endDate) && isMoreThanOneWorkDayDuration(startDate, endDate, person)) { application = new Application(); application.setPerson(person); application.setStartDate(startDate); application.setEndDate(endDate); application.setVacationType(vacationType); application.setHowLong(dayLength); application.setReason( "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores"); applicationInteractionService.apply(application, person, Optional.of("Ich hätte gerne Urlaub")); } return application; } private boolean startAndEndDatesAreInCurrentYear(DateMidnight start, DateMidnight end) { int currentYear = DateMidnight.now().getYear(); return start.getYear() == currentYear && end.getYear() == currentYear; } private boolean isMoreThanOneWorkDayDuration(DateMidnight start, DateMidnight end, Person person) { BigDecimal workDays = calendarService.getWorkDays(DayLength.FULL, start, end, person); return CalcUtil.isPositive(workDays); } private Application createAllowedApplication(Person person, VacationType vacationType, DayLength dayLength, DateMidnight startDate, DateMidnight endDate) { Application application = createWaitingApplication(person, vacationType, dayLength, startDate, endDate); if (application != null) { applicationInteractionService.allow(application, boss, Optional.of("Ist in Ordnung")); } return application; } private Application createRejectedApplication(Person person, VacationType vacationType, DayLength dayLength, DateMidnight startDate, DateMidnight endDate) { Application application = createWaitingApplication(person, vacationType, dayLength, startDate, endDate); if (application != null) { applicationInteractionService.reject(application, boss, Optional.of("Aus organisatorischen Gründen leider nicht möglich")); } return application; } private Application createCancelledApplication(Person person, VacationType vacationType, DayLength dayLength, DateMidnight startDate, DateMidnight endDate) { Application application = createAllowedApplication(person, vacationType, dayLength, startDate, endDate); if (application != null) { applicationInteractionService.cancel(application, office, Optional.of("Urlaub wurde nicht genommen, daher storniert")); } return application; } private SickNote createSickNote(Person person, DateMidnight startDate, DateMidnight endDate, SickNoteType type, boolean withAUB) { SickNote sickNote = null; if (startAndEndDatesAreInCurrentYear(startDate, endDate) && isMoreThanOneWorkDayDuration(startDate, endDate, person)) { sickNote = new SickNote(); sickNote.setPerson(person); sickNote.setStartDate(startDate); sickNote.setEndDate(endDate); sickNote.setActive(true); sickNote.setType(type); if (withAUB) { sickNote.setAubStartDate(startDate); sickNote.setAubEndDate(endDate); } sickNoteInteractionService.create(sickNote, office); } return sickNote; } }
src/main/java/org/synyx/urlaubsverwaltung/core/startup/TestDataCreationService.java
package org.synyx.urlaubsverwaltung.core.startup; import org.apache.log4j.Logger; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.synyx.urlaubsverwaltung.core.application.domain.Application; import org.synyx.urlaubsverwaltung.core.application.domain.DayLength; import org.synyx.urlaubsverwaltung.core.application.domain.VacationType; import org.synyx.urlaubsverwaltung.core.application.service.ApplicationInteractionService; import org.synyx.urlaubsverwaltung.core.calendar.Day; import org.synyx.urlaubsverwaltung.core.calendar.WorkDaysService; import org.synyx.urlaubsverwaltung.core.department.Department; import org.synyx.urlaubsverwaltung.core.department.DepartmentService; import org.synyx.urlaubsverwaltung.core.mail.MailNotification; import org.synyx.urlaubsverwaltung.core.person.Person; import org.synyx.urlaubsverwaltung.core.person.PersonInteractionService; import org.synyx.urlaubsverwaltung.core.sicknote.SickNote; import org.synyx.urlaubsverwaltung.core.sicknote.SickNoteInteractionService; import org.synyx.urlaubsverwaltung.core.sicknote.SickNoteType; import org.synyx.urlaubsverwaltung.core.util.CalcUtil; import org.synyx.urlaubsverwaltung.security.Role; import org.synyx.urlaubsverwaltung.web.person.PersonForm; import java.math.BigDecimal; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import javax.annotation.PostConstruct; /** * @author Aljona Murygina - murygina@synyx.de */ @Service public class TestDataCreationService { private static final Logger LOG = Logger.getLogger(TestDataCreationService.class); private static final String ENVIRONMENT_PROPERTY = "env"; private static final String DEV_ENVIRONMENT = "dev"; public static final String USER = "testUser"; public static final String BOSS_USER = "testBoss"; public static final String OFFICE_USER = "test"; @Autowired private PersonInteractionService personInteractionService; @Autowired private ApplicationInteractionService applicationInteractionService; @Autowired private SickNoteInteractionService sickNoteInteractionService; @Autowired private WorkDaysService calendarService; @Autowired private DepartmentService departmentService; private Person user; private Person boss; private Person office; @PostConstruct public void createTestData() throws NoSuchAlgorithmException { String environment = System.getProperties().getProperty(ENVIRONMENT_PROPERTY); if (environment.equals(DEV_ENVIRONMENT)) { LOG.info("Test data will be created..."); user = createTestPerson(USER, "Klaus", "Müller", "mueller@muster.de", Role.USER); boss = createTestPerson(BOSS_USER, "Max", "Mustermann", "maxMuster@muster.de", Role.USER, Role.BOSS); office = createTestPerson(OFFICE_USER, "Marlene", "Muster", "mmuster@muster.de", Role.USER, Role.BOSS, Role.OFFICE); createTestPerson("hdampf", "Hans", "Dampf", "dampf@foo.bar", Role.USER, Role.OFFICE); createTestPerson("horst", "Horst", "Dieter", "hdieter@muster.de", Role.INACTIVE); createTestData(user); createTestData(boss); createTestData(office); createTestDepartments(); } else { LOG.info("No test data will be created."); } } private void createTestDepartments() { Department department = new Department(); department.setName("Foobar Team"); department.setDescription("Foobar Description"); department.setLastModification(DateTime.now()); departmentService.create(department); } private Person createTestPerson(String login, String firstName, String lastName, String email, Role... roles) throws NoSuchAlgorithmException { int currentYear = DateMidnight.now().getYear(); PersonForm personForm = new PersonForm(DateMidnight.now().getYear()); personForm.setLoginName(login); personForm.setLastName(lastName); personForm.setFirstName(firstName); personForm.setEmail(email); personForm.setAnnualVacationDays(new BigDecimal("28.5")); personForm.setRemainingVacationDays(new BigDecimal("5")); personForm.setRemainingVacationDaysNotExpiring(BigDecimal.ZERO); personForm.setValidFrom(new DateMidnight(currentYear - 1, 1, 1)); personForm.setWorkingDays(Arrays.asList(Day.MONDAY.getDayOfWeek(), Day.TUESDAY.getDayOfWeek(), Day.WEDNESDAY.getDayOfWeek(), Day.THURSDAY.getDayOfWeek(), Day.FRIDAY.getDayOfWeek())); personForm.setPermissions(Arrays.asList(roles)); List<MailNotification> notifications = new ArrayList<>(); notifications.add(MailNotification.NOTIFICATION_USER); if (personForm.getPermissions().contains(Role.BOSS)) { notifications.add(MailNotification.NOTIFICATION_BOSS); } if (personForm.getPermissions().contains(Role.OFFICE)) { notifications.add(MailNotification.NOTIFICATION_OFFICE); } personForm.setNotifications(notifications); return personInteractionService.create(personForm); } private void createTestData(Person person) { DateMidnight now = DateMidnight.now(); // FUTURE APPLICATIONS FOR LEAVE createWaitingApplication(person, VacationType.HOLIDAY, DayLength.FULL, now.plusDays(10), now.plusDays(16)); // NOSONAR createWaitingApplication(person, VacationType.OVERTIME, DayLength.FULL, now.plusDays(1), now.plusDays(2)); // NOSONAR createWaitingApplication(person, VacationType.SPECIALLEAVE, DayLength.FULL, now.plusDays(4), now.plusDays(6)); // NOSONAR // PAST APPLICATIONS FOR LEAVE createAllowedApplication(person, VacationType.HOLIDAY, DayLength.FULL, now.minusDays(20), now.minusDays(13)); // NOSONAR createAllowedApplication(person, VacationType.HOLIDAY, DayLength.MORNING, now.minusDays(5), now.minusDays(5)); // NOSONAR createAllowedApplication(person, VacationType.SPECIALLEAVE, DayLength.MORNING, now.minusDays(9), // NOSONAR now.minusDays(9)); // NOSONAR createRejectedApplication(person, VacationType.HOLIDAY, DayLength.FULL, now.minusDays(33), now.minusDays(30)); // NOSONAR createCancelledApplication(person, VacationType.HOLIDAY, DayLength.FULL, now.minusDays(11), now.minusDays(10)); // NOSONAR // SICK NOTES createSickNote(person, now.minusDays(10), now.minusDays(10), SickNoteType.SICK_NOTE, false); // NOSONAR createSickNote(person, now.minusDays(30), now.minusDays(25), SickNoteType.SICK_NOTE, true); // NOSONAR createSickNote(person, now.minusDays(60), now.minusDays(55), SickNoteType.SICK_NOTE_CHILD, true); // NOSONAR createSickNote(person, now.minusDays(44), now.minusDays(44), SickNoteType.SICK_NOTE_CHILD, false); // NOSONAR } private Application createWaitingApplication(Person person, VacationType vacationType, DayLength dayLength, DateMidnight startDate, DateMidnight endDate) { Application application = null; if (startAndEndDatesAreInCurrentYear(startDate, endDate) && isMoreThanOneWorkDayDuration(startDate, endDate, person)) { application = new Application(); application.setPerson(person); application.setStartDate(startDate); application.setEndDate(endDate); application.setVacationType(vacationType); application.setHowLong(dayLength); application.setReason( "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores"); applicationInteractionService.apply(application, person, Optional.of("Ich hätte gerne Urlaub")); } return application; } private boolean startAndEndDatesAreInCurrentYear(DateMidnight start, DateMidnight end) { int currentYear = DateMidnight.now().getYear(); return start.getYear() == currentYear && end.getYear() == currentYear; } private boolean isMoreThanOneWorkDayDuration(DateMidnight start, DateMidnight end, Person person) { BigDecimal workDays = calendarService.getWorkDays(DayLength.FULL, start, end, person); return CalcUtil.isPositive(workDays); } private Application createAllowedApplication(Person person, VacationType vacationType, DayLength dayLength, DateMidnight startDate, DateMidnight endDate) { Application application = createWaitingApplication(person, vacationType, dayLength, startDate, endDate); if (application != null) { applicationInteractionService.allow(application, boss, Optional.of("Ist in Ordnung")); } return application; } private Application createRejectedApplication(Person person, VacationType vacationType, DayLength dayLength, DateMidnight startDate, DateMidnight endDate) { Application application = createWaitingApplication(person, vacationType, dayLength, startDate, endDate); if (application != null) { applicationInteractionService.reject(application, boss, Optional.of("Aus organisatorischen Gründen leider nicht möglich")); } return application; } private Application createCancelledApplication(Person person, VacationType vacationType, DayLength dayLength, DateMidnight startDate, DateMidnight endDate) { Application application = createAllowedApplication(person, vacationType, dayLength, startDate, endDate); if (application != null) { applicationInteractionService.cancel(application, office, Optional.of("Urlaub wurde nicht genommen, daher storniert")); } return application; } private SickNote createSickNote(Person person, DateMidnight startDate, DateMidnight endDate, SickNoteType type, boolean withAUB) { SickNote sickNote = null; if (startAndEndDatesAreInCurrentYear(startDate, endDate) && isMoreThanOneWorkDayDuration(startDate, endDate, person)) { sickNote = new SickNote(); sickNote.setPerson(person); sickNote.setStartDate(startDate); sickNote.setEndDate(endDate); sickNote.setActive(true); sickNote.setType(type); if (withAUB) { sickNote.setAubStartDate(startDate); sickNote.setAubEndDate(endDate); } sickNoteInteractionService.create(sickNote, office); } return sickNote; } }
Add some further test departments for development purpose * refs #81
src/main/java/org/synyx/urlaubsverwaltung/core/startup/TestDataCreationService.java
Add some further test departments for development purpose
Java
apache-2.0
beca1df19d71649d427ce441f3f1089ef482e52b
0
grzesuav/gjpf-core,grzesuav/gjpf-core
// // Copyright (C) 2006 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration // (NASA). All Rights Reserved. // // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file NOSA-1.3-JPF at the top of the distribution // directory tree for the complete NOSA document. // // THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT // THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. // package gov.nasa.jpf.jvm.bytecode; import gov.nasa.jpf.*; import gov.nasa.jpf.jvm.ChoiceGenerator; import gov.nasa.jpf.jvm.ElementInfo; import gov.nasa.jpf.jvm.KernelState; import gov.nasa.jpf.jvm.SystemState; import gov.nasa.jpf.jvm.ThreadInfo; import org.apache.bcel.classfile.ConstantPool; /** * Exit monitor for object * ..., objectref => ... */ public class MONITOREXIT extends LockInstruction { public void setPeer (org.apache.bcel.generic.Instruction i, ConstantPool cp) { } public Instruction execute (SystemState ss, KernelState ks, ThreadInfo ti) { int objref = ti.peek(); if (objref == -1) { return ti.createAndThrowException("java.lang.NullPointerException", "attempt to release lock for null object"); } lastLockRef = objref; ElementInfo ei = ks.da.get(objref); if (!isLockOwner(ti, ei)) throw new JPFException("Trying to release a lock that isn't owned by the current thread."); if (isLastUnlock(ei)) // If this is the last release, then consider a choice point //if (isShared(ti, ei)) // If the object is shared, then consider a choice point if (!ti.isFirstStepInsn()) // First time around - reexecute if the scheduling policy gives us a choice point if (executeChoicePoint(ss, ti, ei)) return this; // Repeat execution. Keep instruction on the stack. ti.pop(); // now we can safely purge the lock object, the unlocking alreday is done return getNext(ti); } private boolean executeChoicePoint(SystemState ss, ThreadInfo ti, ElementInfo ei) { ei.unlock(ti); // Do this before potentially creating the CG, but don't pop yet, since then we've lost the lock object (also in RETURN) ChoiceGenerator cg = ss.getSchedulerFactory().createMonitorExitCG(ei, ti); if (cg == null) { return false; } ss.setNextChoiceGenerator(cg); //ti.skipInstructionLogging(); return true; } public int getByteCode () { return 0xC3; } public void accept(InstructionVisitor insVisitor) { insVisitor.visit(this); } }
src/main/gov/nasa/jpf/jvm/bytecode/MONITOREXIT.java
// // Copyright (C) 2006 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration // (NASA). All Rights Reserved. // // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file NOSA-1.3-JPF at the top of the distribution // directory tree for the complete NOSA document. // // THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT // THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. // package gov.nasa.jpf.jvm.bytecode; import gov.nasa.jpf.*; import gov.nasa.jpf.jvm.ChoiceGenerator; import gov.nasa.jpf.jvm.ElementInfo; import gov.nasa.jpf.jvm.KernelState; import gov.nasa.jpf.jvm.SystemState; import gov.nasa.jpf.jvm.ThreadInfo; import org.apache.bcel.classfile.ConstantPool; /** * Exit monitor for object * ..., objectref => ... */ public class MONITOREXIT extends LockInstruction { public void setPeer (org.apache.bcel.generic.Instruction i, ConstantPool cp) { } public Instruction execute (SystemState ss, KernelState ks, ThreadInfo ti) { int objref = ti.peek(); if (objref == -1) { return ti.createAndThrowException("java.lang.NullPointerException", "attempt to release lock for null object"); } lastLockRef = objref; ElementInfo ei = ks.da.get(objref); if (!isLockOwner(ti, ei)) throw new JPFException("Trying to release a lock that isn't owned by the current thread."); if (isLastUnlock(ei)) // If this is the last release, then consider a choice point if (isShared(ti, ei)) // If the object is shared, then consider a choice point if (!ti.isFirstStepInsn()) // First time around - reexecute if the scheduling policy gives us a choice point if (executeChoicePoint(ss, ti, ei)) return this; // Repeat execution. Keep instruction on the stack. ti.pop(); // now we can safely purge the lock object, the unlocking alreday is done return getNext(ti); } private boolean executeChoicePoint(SystemState ss, ThreadInfo ti, ElementInfo ei) { ei.unlock(ti); // Do this before potentially creating the CG, but don't pop yet, since then we've lost the lock object (also in RETURN) ChoiceGenerator cg = ss.getSchedulerFactory().createMonitorExitCG(ei, ti); if (cg == null) { return false; } ss.setNextChoiceGenerator(cg); //ti.skipInstructionLogging(); return true; } public int getByteCode () { return 0xC3; } public void accept(InstructionVisitor insVisitor) { insVisitor.visit(this); } }
MONITOREXIT.execute() can't use isShared() to prevent a choice point. Will write a test case to catch this problem.
src/main/gov/nasa/jpf/jvm/bytecode/MONITOREXIT.java
MONITOREXIT.execute() can't use isShared() to prevent a choice point. Will write a test case to catch this problem.
Java
apache-2.0
2bacf63927effbe494ea8888191b950037d4606f
0
apache/commons-io,apache/commons-io,apache/commons-io
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.util.Arrays; import java.util.Objects; /** * Abstracts an OS' file system details, currently supporting the single use case of converting a file name String to a * legal file name with {@link #toLegalFileName(String, char)}. * <p> * The starting point of any operation is {@link #getCurrent()} which gets you the enum for the file system that matches * the OS hosting the running JVM. * </p> * * @since 2.7 */ public enum FileSystem { LINUX(255, 4096, new char[] { // KEEP THIS ARRAY SORTED! // @formatter:off // ASCII NUL 0, '/' // @formatter:on }), MAC_OSX(255, 1024, new char[] { // KEEP THIS ARRAY SORTED! // @formatter:off // ASCII NUL 0, '/', ':' // @formatter:on }), GENERIC(Integer.MAX_VALUE, Integer.MAX_VALUE, new char[] { 0 }), WINDOWS(255, 32000, new char[] { // KEEP THIS ARRAY SORTED! // @formatter:off // ASCII NUL 0, // 1-31 may be allowed in file streams 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '*', '/', ':', '<', '>', '?', '\\', '|' // @formatter:on }); /** * The prefix String for all Windows OS. */ private static final String OS_NAME_WINDOWS_PREFIX = "Windows"; /** * <p> * Is {@code true} if this is Windows. * </p> * <p> * The field will return {@code false} if {@code OS_NAME} is {@code null}. * </p> */ private static final boolean IS_OS_WINDOWS = getOsMatchesName(OS_NAME_WINDOWS_PREFIX); /** * <p> * Is {@code true} if this is Linux. * </p> * <p> * The field will return {@code false} if {@code OS_NAME} is {@code null}. * </p> */ private static final boolean IS_OS_LINUX = getOsMatchesName("Linux") || getOsMatchesName("LINUX"); /** * <p> * Is {@code true} if this is Mac. * </p> * <p> * The field will return {@code false} if {@code OS_NAME} is {@code null}. * </p> */ private static final boolean IS_OS_MAC = getOsMatchesName("Mac"); private static final String OS_NAME = getSystemProperty("os.name"); /** * Gets the current file system. * * @return the current file system */ public static FileSystem getCurrent() { if (IS_OS_LINUX) { return LINUX; } if (IS_OS_MAC) { return FileSystem.MAC_OSX; } if (IS_OS_WINDOWS) { return FileSystem.WINDOWS; } return GENERIC; } /** * Decides if the operating system matches. * * @param osNamePrefix * the prefix for the os name * @return true if matches, or false if not or can't determine */ private static boolean getOsMatchesName(final String osNamePrefix) { return isOsNameMatch(OS_NAME, osNamePrefix); } /** * <p> * Gets a System property, defaulting to {@code null} if the property cannot be read. * </p> * <p> * If a {@code SecurityException} is caught, the return value is {@code null} and a message is written to * {@code System.err}. * </p> * * @param property * the system property name * @return the system property value or {@code null} if a security problem occurs */ private static String getSystemProperty(final String property) { try { return System.getProperty(property); } catch (final SecurityException ex) { // we are not allowed to look at this property System.err.println("Caught a SecurityException reading the system property '" + property + "'; the SystemUtils property value will default to null."); return null; } } /** * Decides if the operating system matches. * <p> * This method is package private instead of private to support unit test invocation. * </p> * * @param osName * the actual OS name * @param osNamePrefix * the prefix for the expected OS name * @return true if matches, or false if not or can't determine */ private static boolean isOsNameMatch(final String osName, final String osNamePrefix) { if (osName == null) { return false; } return osName.startsWith(osNamePrefix); } private final char[] illegalFileNameChars; private final int maxFileNameLength; private final int maxPathLength; private FileSystem(final int maxFileLength, final int maxPathLength, final char[] illegalFileNameChars) { this.maxFileNameLength = maxFileLength; this.maxPathLength = maxPathLength; this.illegalFileNameChars = Objects.requireNonNull(illegalFileNameChars, "illegalFileNameChars"); } /** * Gets the illegal characters for this file system. * * @return the illegal characters for this file system. */ public char[] getIllegalFileNameChars() { return this.illegalFileNameChars.clone(); } /** * Gets the maximum length for file names. The file name does not include folders. * * @return the maximum length for file names. */ public int getMaxFileNameLength() { return maxFileNameLength; } /** * Gets the maximum length of the path to a file. This can include folders. * * @return the maximum length of the path to a file. */ public int getMaxPathLength() { return maxPathLength; } private boolean isIllegalFileNameChar(final char c) { return Arrays.binarySearch(illegalFileNameChars, c) >= 0; } /** * Converts a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} to a legal file * name. Illegal characters in the candidate name are replaced by the {@code replacement} character. If the file * name length exceeds {@link #getMaxFileNameLength()}, then the name is truncated to {@link #getMaxFileNameLength()}. * * @param candidate * a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} * @param replacement * Illegal characters in the candidate name are replaced by this character * @return a String without illegal characters */ public String toLegalFileName(final String candidate, final char replacement) { if (isIllegalFileNameChar(replacement)) { throw new IllegalArgumentException( String.format("The replacement character '%s' cannot be one of the %s illegal characters: %s", // %s does not work properly with NUL replacement == '\0' ? "\\0" : replacement, name(), Arrays.toString(illegalFileNameChars))); } final String truncated = candidate.length() > maxFileNameLength ? candidate.substring(0, maxFileNameLength) : candidate; boolean changed = false; final char[] charArray = truncated.toCharArray(); for (int i = 0; i < charArray.length; i++) { if (isIllegalFileNameChar(charArray[i])) { charArray[i] = replacement; changed = true; } } return changed ? String.valueOf(charArray) : truncated; } /** * Checks if a candidate file name (without a path) * such as {@code "filename.ext"} or {@code "filename"} * is a potentially legal file name. * If the file name length exceeds {@link #getMaxFileNameLength()}, * or if it contains an illegal character then the check fails. * * @param candidate * a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} * @return {@code true} if the candidate name is legal */ public boolean isLegalFileName(final CharSequence candidate) { if (candidate == null || candidate.length() == 0 || candidate.length() > maxFileNameLength) { return false; } for (int i = 0; i < candidate.length(); i++) { if (isIllegalFileNameChar(candidate.charAt(i))) { return false; } } return true; } }
src/main/java/org/apache/commons/io/FileSystem.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io; import java.util.Arrays; import java.util.Objects; /** * Abstracts an OS' file system details, currently supporting the single use case of converting a file name String to a * legal file name with {@link #toLegalFileName(String, char)}. * <p> * The starting point of any operation is {@link #getCurrent()} which gets you the enum for the file system that matches * the OS hosting the running JVM. * </p> * * @since 2.7 */ public enum FileSystem { LINUX(255, 4096, new char[] { // KEEP THIS ARRAY SORTED! // @formatter:off // ASCII NUL 0, '/' // @formatter:on }), MAC_OSX(255, 1024, new char[] { // KEEP THIS ARRAY SORTED! // @formatter:off // ASCII NUL 0, '/', ':' // @formatter:on }), GENERIC(Integer.MAX_VALUE, Integer.MAX_VALUE, new char[] { 0 }), WINDOWS(255, 32000, new char[] { // KEEP THIS ARRAY SORTED! // @formatter:off // ASCII NUL 0, // 1-31 may be allowed in file streams 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, '"', '*', '/', ':', '<', '>', '?', '\\', '|' // @formatter:on }); /** * The prefix String for all Windows OS. */ private static final String OS_NAME_WINDOWS_PREFIX = "Windows"; /** * <p> * Is {@code true} if this is Windows. * </p> * <p> * The field will return {@code false} if {@code OS_NAME} is {@code null}. * </p> */ private static final boolean IS_OS_WINDOWS = getOsMatchesName(OS_NAME_WINDOWS_PREFIX); /** * <p> * Is {@code true} if this is Linux. * </p> * <p> * The field will return {@code false} if {@code OS_NAME} is {@code null}. * </p> */ private static final boolean IS_OS_LINUX = getOsMatchesName("Linux") || getOsMatchesName("LINUX"); /** * <p> * Is {@code true} if this is Mac. * </p> * <p> * The field will return {@code false} if {@code OS_NAME} is {@code null}. * </p> */ private static final boolean IS_OS_MAC = getOsMatchesName("Mac"); private static final String OS_NAME = getSystemProperty("os.name"); public static FileSystem getCurrent() { if (IS_OS_LINUX) { return LINUX; } if (IS_OS_MAC) { return FileSystem.MAC_OSX; } if (IS_OS_WINDOWS) { return FileSystem.WINDOWS; } return GENERIC; } /** * Decides if the operating system matches. * * @param osNamePrefix * the prefix for the os name * @return true if matches, or false if not or can't determine */ private static boolean getOsMatchesName(final String osNamePrefix) { return isOsNameMatch(OS_NAME, osNamePrefix); } /** * <p> * Gets a System property, defaulting to {@code null} if the property cannot be read. * </p> * <p> * If a {@code SecurityException} is caught, the return value is {@code null} and a message is written to * {@code System.err}. * </p> * * @param property * the system property name * @return the system property value or {@code null} if a security problem occurs */ private static String getSystemProperty(final String property) { try { return System.getProperty(property); } catch (final SecurityException ex) { // we are not allowed to look at this property System.err.println("Caught a SecurityException reading the system property '" + property + "'; the SystemUtils property value will default to null."); return null; } } /** * Decides if the operating system matches. * <p> * This method is package private instead of private to support unit test invocation. * </p> * * @param osName * the actual OS name * @param osNamePrefix * the prefix for the expected OS name * @return true if matches, or false if not or can't determine */ private static boolean isOsNameMatch(final String osName, final String osNamePrefix) { if (osName == null) { return false; } return osName.startsWith(osNamePrefix); } private final char[] illegalFileNameChars; private final int maxFileNameLength; private final int maxPathLength; private FileSystem(final int maxFileLength, final int maxPathLength, final char[] illegalFileNameChars) { this.maxFileNameLength = maxFileLength; this.maxPathLength = maxPathLength; this.illegalFileNameChars = Objects.requireNonNull(illegalFileNameChars, "illegalFileNameChars"); } public char[] getIllegalFileNameChars() { return this.illegalFileNameChars.clone(); } public int getMaxFileNameLength() { return maxFileNameLength; } public int getMaxPathLength() { return maxPathLength; } private boolean isIllegalFileNameChar(final char c) { return Arrays.binarySearch(illegalFileNameChars, c) >= 0; } /** * Converts a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} to a legal file * name. Illegal characters in the candidate name are replaced by the {@code replacement} character. If the file * name length exceeds {@link #getMaxFileNameLength()}, then the name is truncated to {@link #getMaxFileNameLength()}. * * @param candidate * a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} * @param replacement * Illegal characters in the candidate name are replaced by this character * @return a String without illegal characters */ public String toLegalFileName(final String candidate, final char replacement) { if (isIllegalFileNameChar(replacement)) { throw new IllegalArgumentException( String.format("The replacement character '%s' cannot be one of the %s illegal characters: %s", // %s does not work properly with NUL replacement == '\0' ? "\\0" : replacement, name(), Arrays.toString(illegalFileNameChars))); } final String truncated = candidate.length() > maxFileNameLength ? candidate.substring(0, maxFileNameLength) : candidate; boolean changed = false; final char[] charArray = truncated.toCharArray(); for (int i = 0; i < charArray.length; i++) { if (isIllegalFileNameChar(charArray[i])) { charArray[i] = replacement; changed = true; } } return changed ? String.valueOf(charArray) : truncated; } /** * Checks if a candidate file name (without a path) * such as {@code "filename.ext"} or {@code "filename"} * is a potentially legal file name. * If the file name length exceeds {@link #getMaxFileNameLength()}, * or if it contains an illegal character then the check fails. * * @param candidate * a candidate file name (without a path) like {@code "filename.ext"} or {@code "filename"} * @return {@code true} if the candidate name is legal */ public boolean isLegalFileName(final CharSequence candidate) { if (candidate == null || candidate.length() == 0 || candidate.length() > maxFileNameLength) { return false; } for (int i = 0; i < candidate.length(); i++) { if (isIllegalFileNameChar(candidate.charAt(i))) { return false; } } return true; } }
Javadoc.
src/main/java/org/apache/commons/io/FileSystem.java
Javadoc.
Java
apache-2.0
6e74a947351868133c6b38bfe43d27d6f9d6ab49
0
cgeo/cgeo,cgeo/cgeo,cgeo/cgeo,cgeo/cgeo
package cgeo.geocaching.maps.mapsforge.v6; import cgeo.geocaching.AbstractDialogFragment; import cgeo.geocaching.AbstractDialogFragment.TargetInfo; import cgeo.geocaching.CacheListActivity; import cgeo.geocaching.CachePopup; import cgeo.geocaching.CompassActivity; import cgeo.geocaching.EditWaypointActivity; import cgeo.geocaching.Intents; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.WaypointPopup; import cgeo.geocaching.activity.AbstractBottomNavigationActivity; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.activity.FilteredActivity; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.connector.internal.InternalConnector; import cgeo.geocaching.databinding.MapMapsforgeV6Binding; import cgeo.geocaching.downloader.DownloaderUtils; import cgeo.geocaching.enumerations.CoordinatesType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.filters.core.GeocacheFilter; import cgeo.geocaching.filters.core.GeocacheFilterContext; import cgeo.geocaching.filters.gui.GeocacheFilterActivity; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.location.ProximityNotification; import cgeo.geocaching.location.Viewport; import cgeo.geocaching.maps.MapMode; import cgeo.geocaching.maps.MapOptions; import cgeo.geocaching.maps.MapProviderFactory; import cgeo.geocaching.maps.MapSettingsUtils; import cgeo.geocaching.maps.MapState; import cgeo.geocaching.maps.MapUtils; import cgeo.geocaching.maps.RouteTrackUtils; import cgeo.geocaching.maps.Tracks; import cgeo.geocaching.maps.interfaces.MapSource; import cgeo.geocaching.maps.interfaces.OnMapDragListener; import cgeo.geocaching.maps.mapsforge.AbstractMapsforgeMapSource; import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider; import cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle; import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemLayer; import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemRef; import cgeo.geocaching.maps.mapsforge.v6.layers.HistoryLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.ITileLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.NavigationLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.PositionLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.RouteLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.TapHandlerLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.TrackLayer; import cgeo.geocaching.maps.mapsforge.v6.legend.RenderThemeLegend; import cgeo.geocaching.maps.routing.Routing; import cgeo.geocaching.maps.routing.RoutingMode; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.models.IndividualRoute; import cgeo.geocaching.models.Route; import cgeo.geocaching.models.RouteItem; import cgeo.geocaching.models.TrailHistoryElement; import cgeo.geocaching.permission.PermissionHandler; import cgeo.geocaching.permission.PermissionRequestContext; import cgeo.geocaching.permission.RestartLocationPermissionGrantedCallback; import cgeo.geocaching.sensors.GeoData; import cgeo.geocaching.sensors.GeoDirHandler; import cgeo.geocaching.sensors.Sensors; import cgeo.geocaching.service.CacheDownloaderService; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.storage.DataStore; import cgeo.geocaching.storage.LocalStorage; import cgeo.geocaching.ui.GeoItemSelectorUtils; import cgeo.geocaching.ui.ViewUtils; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.utils.AndroidRxUtils; import cgeo.geocaching.utils.AngleUtils; import cgeo.geocaching.utils.ApplicationSettings; import cgeo.geocaching.utils.BranchDetectionHelper; import cgeo.geocaching.utils.CompactIconModeUtils; import cgeo.geocaching.utils.DisposableHandler; import cgeo.geocaching.utils.FilterUtils; import cgeo.geocaching.utils.Formatter; import cgeo.geocaching.utils.HistoryTrackUtils; import cgeo.geocaching.utils.Log; import static cgeo.geocaching.filters.core.GeocacheFilterContext.FilterType.LIVE; import static cgeo.geocaching.filters.gui.GeocacheFilterActivity.EXTRA_FILTER_CONTEXT; import static cgeo.geocaching.maps.MapProviderFactory.MAP_LANGUAGE_DEFAULT_ID; import static cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle.NO_OVERLAY_ID; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources.NotFoundException; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ListAdapter; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.core.text.HtmlCompat; import androidx.core.util.Supplier; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.RejectedExecutionException; import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.schedulers.Schedulers; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.mapsforge.core.model.BoundingBox; import org.mapsforge.core.model.LatLong; import org.mapsforge.core.model.MapPosition; import org.mapsforge.core.util.Parameters; import org.mapsforge.map.android.graphics.AndroidGraphicFactory; import org.mapsforge.map.android.graphics.AndroidResourceBitmap; import org.mapsforge.map.android.input.MapZoomControls; import org.mapsforge.map.android.util.AndroidUtil; import org.mapsforge.map.layer.Layers; import org.mapsforge.map.layer.cache.TileCache; import org.mapsforge.map.model.common.Observer; @SuppressLint("ClickableViewAccessibility") @SuppressWarnings("PMD.ExcessiveClassLength") // This is definitely a valid issue, but can't be refactored in one step public class NewMap extends AbstractBottomNavigationActivity implements Observer, FilteredActivity { private static final String STATE_ROUTETRACKUTILS = "routetrackutils"; private static final String ROUTING_SERVICE_KEY = "NewMap"; private MfMapView mapView; private TileCache tileCache; private MapSource mapSource; private ITileLayer tileLayer; private HistoryLayer historyLayer; private PositionLayer positionLayer; private NavigationLayer navigationLayer; private RouteLayer routeLayer; private TrackLayer trackLayer; private CachesBundle caches; private final MapHandlers mapHandlers = new MapHandlers(new TapHandler(this), new DisplayHandler(this), new ShowProgressHandler(this)); private RenderThemeHelper renderThemeHelper = null; //must be initialized in onCreate(); private DistanceView distanceView; private View mapAttribution; private final ArrayList<TrailHistoryElement> trailHistory = null; private String targetGeocode = null; private Geopoint lastNavTarget = null; private final Queue<String> popupGeocodes = new ConcurrentLinkedQueue<>(); private ProgressDialog waitDialog; private LoadDetails loadDetailsThread; private ProgressBar spinner; private final UpdateLoc geoDirUpdate = new UpdateLoc(this); /** * initialization with an empty subscription to make static code analysis tools more happy */ private ProximityNotification proximityNotification; private final CompositeDisposable resumeDisposables = new CompositeDisposable(); private CheckBox myLocSwitch; private MapOptions mapOptions; private TargetView targetView; private IndividualRoute individualRoute = null; private Tracks tracks = null; private static boolean followMyLocation = true; private static final String BUNDLE_MAP_STATE = "mapState"; private static final String BUNDLE_PROXIMITY_NOTIFICATION = "proximityNotification"; private static final String BUNDLE_ROUTE = "route"; // Handler messages // DisplayHandler public static final int UPDATE_TITLE = 0; // ShowProgressHandler public static final int HIDE_PROGRESS = 0; public static final int SHOW_PROGRESS = 1; // LoadDetailsHandler public static final int UPDATE_PROGRESS = 0; public static final int FINISHED_LOADING_DETAILS = 1; private Viewport lastViewport = null; private boolean lastCompactIconMode = false; private MapMode mapMode; private RouteTrackUtils routeTrackUtils = null; @Override public void onCreate(final Bundle savedInstanceState) { ApplicationSettings.setLocale(this); super.onCreate(savedInstanceState); Log.d("NewMap: onCreate"); routeTrackUtils = new RouteTrackUtils(this, savedInstanceState == null ? null : savedInstanceState.getBundle(STATE_ROUTETRACKUTILS), this::centerOnPosition, this::clearIndividualRoute, this::reloadIndividualRoute, this::setTrack, this::isTargetSet); tracks = new Tracks(routeTrackUtils, this::setTrack); ResourceBitmapCacheMonitor.addRef(); AndroidGraphicFactory.createInstance(this.getApplication()); AndroidGraphicFactory.INSTANCE.setSvgCacheDir(LocalStorage.getMapsforgeSvgCacheDir()); MapsforgeMapProvider.getInstance().updateOfflineMaps(); this.renderThemeHelper = new RenderThemeHelper(this); // Support for multi-threaded map painting Parameters.NUMBER_OF_THREADS = Settings.getMapOsmThreads(); Log.i("OSM #threads=" + Parameters.NUMBER_OF_THREADS); // Use fast parent tile rendering to increase performance when zooming in Parameters.PARENT_TILES_RENDERING = Parameters.ParentTilesRendering.SPEED; // Get parameters from the intent mapOptions = new MapOptions(this, getIntent().getExtras()); // Get fresh map information from the bundle if any if (savedInstanceState != null) { mapOptions.mapState = savedInstanceState.getParcelable(BUNDLE_MAP_STATE); proximityNotification = savedInstanceState.getParcelable(BUNDLE_PROXIMITY_NOTIFICATION); individualRoute = savedInstanceState.getParcelable(BUNDLE_ROUTE); followMyLocation = mapOptions.mapState.followsMyLocation(); } else { if (mapOptions.mapState != null) { followMyLocation = mapOptions.mapState.followsMyLocation(); } else { followMyLocation = followMyLocation && mapOptions.mapMode == MapMode.LIVE; } individualRoute = null; proximityNotification = Settings.isGeneralProximityNotificationActive() ? new ProximityNotification(true, false) : null; } if (null != proximityNotification) { proximityNotification.setTextNotifications(this); } ActivityMixin.onCreate(this, true); // set layout ActivityMixin.setTheme(this); // adding the bottom navigation component is handled by {@link AbstractBottomNavigationActivity#setContentView} setContentView(MapMapsforgeV6Binding.inflate(getLayoutInflater()).getRoot()); setTitle(); this.mapAttribution = findViewById(R.id.map_attribution); // map settings popup findViewById(R.id.map_settings_popup).setOnClickListener(v -> MapSettingsUtils.showSettingsPopup(this, individualRoute, this::refreshMapData, this::routingModeChanged, this::compactIconModeChanged, mapOptions.filterContext)); // routes / tracks popup findViewById(R.id.map_individualroute_popup).setOnClickListener(v -> routeTrackUtils.showPopup(individualRoute, this::setTarget)); // prepare circular progress spinner spinner = (ProgressBar) findViewById(R.id.map_progressbar); spinner.setVisibility(View.GONE); // initialize map mapView = (MfMapView) findViewById(R.id.mfmapv5); mapView.setClickable(true); mapView.getMapScaleBar().setVisible(true); mapView.setBuiltInZoomControls(true); // style zoom controls final MapZoomControls zoomControls = mapView.getMapZoomControls(); zoomControls.setZoomControlsOrientation(MapZoomControls.Orientation.VERTICAL_IN_OUT); zoomControls.setZoomInResource(R.drawable.map_zoomin); zoomControls.setZoomOutResource(R.drawable.map_zoomout); zoomControls.setPadding(0, 0, ViewUtils.dpToPixel(13.0f), ViewUtils.dpToPixel(18.0f)); zoomControls.setAutoHide(false); //make room for map attribution icon button final int mapAttPx = Math.round(this.getResources().getDisplayMetrics().density * 30); mapView.getMapScaleBar().setMarginHorizontal(mapAttPx); // create a tile cache of suitable size. always initialize it based on the smallest tile size to expect (256 for online tiles) tileCache = AndroidUtil.createTileCache(this, "mapcache", 256, 1f, this.mapView.getModel().frameBufferModel.getOverdrawFactor()); // attach drag handler final DragHandler dragHandler = new DragHandler(this); mapView.setOnMapDragListener(dragHandler); mapMode = (mapOptions != null && mapOptions.mapMode != null) ? mapOptions.mapMode : MapMode.LIVE; // prepare initial settings of mapView if (mapOptions.mapState != null) { this.mapView.getModel().mapViewPosition.setCenter(MapsforgeUtils.toLatLong(mapOptions.mapState.getCenter())); this.mapView.setMapZoomLevel((byte) mapOptions.mapState.getZoomLevel()); this.targetGeocode = mapOptions.mapState.getTargetGeocode(); this.lastNavTarget = mapOptions.mapState.getLastNavTarget(); mapOptions.isLiveEnabled = mapOptions.mapState.isLiveEnabled(); mapOptions.isStoredEnabled = mapOptions.mapState.isStoredEnabled(); } else if (mapOptions.searchResult != null) { final Viewport viewport = DataStore.getBounds(mapOptions.searchResult.getGeocodes()); if (viewport != null) { postZoomToViewport(viewport); } } else if (StringUtils.isNotEmpty(mapOptions.geocode) && mapOptions.mapMode != MapMode.COORDS) { final Viewport viewport = DataStore.getBounds(mapOptions.geocode, Settings.getZoomIncludingWaypoints()); if (viewport != null) { postZoomToViewport(viewport); } targetGeocode = mapOptions.geocode; final Geocache temp = getCurrentTargetCache(); if (temp != null) { lastNavTarget = temp.getCoords(); } } else if (mapOptions.coords != null) { postZoomToViewport(new Viewport(mapOptions.coords, 0, 0)); if (mapOptions.mapMode == MapMode.LIVE) { mapOptions.coords = null; // no direction line, even if enabled in settings followMyLocation = false; // do not center on GPS position, even if in LIVE mode } } else { postZoomToViewport(new Viewport(Settings.getMapCenter().getCoords(), 0, 0)); } FilterUtils.initializeFilterBar(this, this); MapUtils.updateFilterBar(this, mapOptions.filterContext); Routing.connect(ROUTING_SERVICE_KEY, () -> resumeRoute(true)); CompactIconModeUtils.setCompactIconModeThreshold(getResources()); MapsforgeMapProvider.getInstance().updateOfflineMaps(); MapUtils.showMapOneTimeMessages(this, mapMode); } private void postZoomToViewport(final Viewport viewport) { mapView.post(() -> mapView.zoomToViewport(viewport, this.mapMode)); } @Override public boolean onCreateOptionsMenu(@NonNull final Menu menu) { final boolean result = super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.map_activity, menu); MapProviderFactory.addMapviewMenuItems(this, menu); MapProviderFactory.addMapViewLanguageMenuItems(menu); initMyLocationSwitchButton(MapProviderFactory.createLocSwitchMenuItem(this, menu)); FilterUtils.initializeFilterMenu(this, this); return result; } @Override public int getSelectedBottomItemId() { return mapOptions.mapMode == MapMode.LIVE ? MENU_MAP : MENU_HIDE_BOTTOM_NAVIGATION; } @Override public boolean onPrepareOptionsMenu(@NonNull final Menu menu) { super.onPrepareOptionsMenu(menu); if (mapOptions != null) { ViewUtils.extendMenuActionBarDisplayItemCount(this, menu); } for (final MapSource mapSource : MapProviderFactory.getMapSources()) { final MenuItem menuItem = menu.findItem(mapSource.getNumericalId()); if (menuItem != null) { menuItem.setVisible(mapSource.isAvailable()); } } try { final MenuItem itemMapLive = menu.findItem(R.id.menu_map_live); if (mapOptions.isLiveEnabled) { itemMapLive.setIcon(R.drawable.ic_menu_sync_enabled); itemMapLive.setTitle(res.getString(R.string.map_live_disable)); } else { itemMapLive.setIcon(R.drawable.ic_menu_sync_disabled); itemMapLive.setTitle(res.getString(R.string.map_live_enable)); } itemMapLive.setVisible(mapOptions.coords == null || mapOptions.mapMode == MapMode.LIVE); final Set<String> visibleCacheGeocodes = caches.getVisibleCacheGeocodes(); menu.findItem(R.id.menu_store_caches).setVisible(false); menu.findItem(R.id.menu_store_caches).setVisible(!caches.isDownloading() && !visibleCacheGeocodes.isEmpty()); menu.findItem(R.id.menu_store_unsaved_caches).setVisible(false); menu.findItem(R.id.menu_store_unsaved_caches).setVisible(!caches.isDownloading() && new SearchResult(visibleCacheGeocodes).hasUnsavedCaches()); if (!BranchDetectionHelper.isProductionBuild()) { menu.findItem(R.id.menu_store_caches_background).setVisible(!caches.isDownloading() && !visibleCacheGeocodes.isEmpty()); } final boolean tileLayerHasThemes = tileLayerHasThemes(); menu.findItem(R.id.menu_theme_mode).setVisible(tileLayerHasThemes); menu.findItem(R.id.menu_theme_options).setVisible(tileLayerHasThemes); menu.findItem(R.id.menu_theme_legend).setVisible(tileLayerHasThemes && RenderThemeLegend.supportsLegend()); menu.findItem(R.id.menu_as_list).setVisible(!caches.isDownloading() && caches.getVisibleCachesCount() > 1); this.routeTrackUtils.onPrepareOptionsMenu(menu, findViewById(R.id.container_individualroute), individualRoute, tracks); menu.findItem(R.id.menu_hint).setVisible(mapOptions.mapMode == MapMode.SINGLE); menu.findItem(R.id.menu_compass).setVisible(mapOptions.mapMode == MapMode.SINGLE); HistoryTrackUtils.onPrepareOptionsMenu(menu); } catch (final RuntimeException e) { Log.e("NewMap.onPrepareOptionsMenu", e); } return true; } @Override public void onConfigurationChanged(@NonNull final Configuration newConfig) { super.onConfigurationChanged(newConfig); invalidateOptionsMenu(); } @Override public boolean onOptionsItemSelected(@NonNull final MenuItem item) { final int id = item.getItemId(); if (id == R.id.menu_map_live) { mapOptions.isLiveEnabled = !mapOptions.isLiveEnabled; if (mapOptions.isLiveEnabled) { mapOptions.isStoredEnabled = true; mapOptions.filterContext = new GeocacheFilterContext(LIVE); caches.setFilterContext(mapOptions.filterContext); refreshMapData(false); } if (mapOptions.mapMode == MapMode.LIVE) { Settings.setLiveMap(mapOptions.isLiveEnabled); } caches.handleStoredLayers(this, mapOptions); caches.handleLiveLayers(this, mapOptions); ActivityMixin.invalidateOptionsMenu(this); if (mapOptions.mapMode == MapMode.SINGLE) { setTarget(mapOptions.coords, mapOptions.geocode); } mapOptions.mapMode = MapMode.LIVE; updateSelectedBottomNavItemId(); mapOptions.title = StringUtils.EMPTY; setTitle(); } else if (id == R.id.menu_filter) { showFilterMenu(); } else if (id == R.id.menu_store_caches) { return storeCaches(caches.getVisibleCacheGeocodes()); } else if (id == R.id.menu_store_unsaved_caches) { return storeCaches(getUnsavedGeocodes(caches.getVisibleCacheGeocodes())); } else if (id == R.id.menu_store_caches_background) { CacheDownloaderService.downloadCaches(this, caches.getVisibleCacheGeocodes(), false, false); } else if (id == R.id.menu_theme_mode) { this.renderThemeHelper.selectMapTheme(this.tileLayer, this.tileCache); } else if (id == R.id.menu_theme_options) { this.renderThemeHelper.selectMapThemeOptions(); } else if (id == R.id.menu_theme_legend) { RenderThemeLegend.showLegend(this, this.renderThemeHelper, mapView.getModel().displayModel); } else if (id == R.id.menu_as_list) { CacheListActivity.startActivityMap(this, new SearchResult(caches.getVisibleCacheGeocodes())); ActivityMixin.overrideTransitionToFade(this); } else if (id == R.id.menu_hint) { menuShowHint(); } else if (id == R.id.menu_compass) { menuCompass(); } else if (id == R.id.menu_check_routingdata) { final BoundingBox bb = mapView.getBoundingBox(); MapUtils.checkRoutingData(this, bb.minLatitude, bb.minLongitude, bb.maxLatitude, bb.maxLongitude); } else if (HistoryTrackUtils.onOptionsItemSelected(this, id, () -> historyLayer.requestRedraw(), this::clearTrailHistory) || DownloaderUtils.onOptionsItemSelected(this, id)) { return true; } else if (id == R.id.menu_routetrack) { routeTrackUtils.showPopup(individualRoute, this::setTarget); } else { final String language = MapProviderFactory.getLanguage(id); final MapSource mapSource = MapProviderFactory.getMapSource(id); if (language != null || id == MAP_LANGUAGE_DEFAULT_ID) { item.setChecked(true); changeLanguage(language); return true; } if (mapSource != null) { item.setChecked(true); changeMapSource(mapSource); return true; } return super.onOptionsItemSelected(item); } return true; } private void refreshMapData(final boolean circlesSwitched) { if (circlesSwitched) { caches.switchCircles(); } if (caches != null) { caches.invalidate(); } Tile.cache.clear(); if (null != trackLayer) { // trackLayer.setHidden(Settings.isHideTrack()); trackLayer.requestRedraw(); } MapUtils.updateFilterBar(this, mapOptions.filterContext); } private void routingModeChanged(final RoutingMode newValue) { Settings.setRoutingMode(newValue); if ((null != individualRoute && individualRoute.getNumSegments() > 0) || null != tracks) { Toast.makeText(this, R.string.brouter_recalculating, Toast.LENGTH_SHORT).show(); } individualRoute.reloadRoute(routeLayer); if (null != tracks) { try { AndroidRxUtils.andThenOnUi(Schedulers.computation(), () -> tracks.traverse((key, route) -> { route.calculateNavigationRoute(); trackLayer.updateRoute(key, route); }), () -> trackLayer.requestRedraw()); } catch (RejectedExecutionException e) { Log.e("NewMap.routingModeChanged: RejectedExecutionException: " + e.getMessage()); } } navigationLayer.requestRedraw(); } private void compactIconModeChanged(final int newValue) { Settings.setCompactIconMode(newValue); caches.invalidateAll(NO_OVERLAY_ID); } private void clearTrailHistory() { this.historyLayer.reset(); this.historyLayer.requestRedraw(); showToast(res.getString(R.string.map_trailhistory_cleared)); } private void clearIndividualRoute() { individualRoute.clearRoute(routeLayer); distanceView.showRouteDistance(); ActivityMixin.invalidateOptionsMenu(this); showToast(res.getString(R.string.map_individual_route_cleared)); } private void centerOnPosition(final double latitude, final double longitude, final Viewport viewport) { followMyLocation = false; switchMyLocationButton(); mapView.getModel().mapViewPosition.setMapPosition(new MapPosition(new LatLong(latitude, longitude), (byte) mapView.getMapZoomLevel())); postZoomToViewport(viewport); } private Set<String> getUnsavedGeocodes(final Set<String> geocodes) { final Set<String> unsavedGeocodes = new HashSet<>(); for (final String geocode : geocodes) { if (!DataStore.isOffline(geocode, null)) { unsavedGeocodes.add(geocode); } } return unsavedGeocodes; } private boolean storeCaches(final Set<String> geocodes) { if (!caches.isDownloading()) { if (geocodes.isEmpty()) { ActivityMixin.showToast(this, res.getString(R.string.warn_save_nothing)); return true; } if (Settings.getChooseList()) { // let user select list to store cache in new StoredList.UserInterface(this).promptForMultiListSelection(R.string.lists_title, selectedListIds -> storeCaches(geocodes, selectedListIds), true, Collections.emptySet(), false); } else { storeCaches(geocodes, Collections.singleton(StoredList.STANDARD_LIST_ID)); } } return true; } private void menuCompass() { final Geocache cache = getCurrentTargetCache(); if (cache != null) { CompassActivity.startActivityCache(this, cache); } } private void menuShowHint() { final Geocache cache = getCurrentTargetCache(); if (cache != null) { cache.showHintToast(this); } } @Override public void showFilterMenu() { FilterUtils.openFilterActivity(this, mapOptions.filterContext, new SearchResult(caches.getVisibleCacheGeocodes()).getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB)); } @Override public boolean showSavedFilterList() { return FilterUtils.openFilterList(this, mapOptions.filterContext); } @Override public void refreshWithFilter(final GeocacheFilter filter) { mapOptions.filterContext.set(filter); refreshMapData(false); } private void changeMapSource(@NonNull final MapSource newSource) { final MapSource oldSource = Settings.getMapSource(); final boolean restartRequired = !MapProviderFactory.isSameActivity(oldSource, newSource); // Update MapSource in settings Settings.setMapSource(newSource); if (restartRequired) { mapRestart(); } else if (mapView != null) { // changeMapSource can be called by onCreate() switchTileLayer(newSource); } } private void changeLanguage(final String language) { Settings.setMapLanguage(language); mapRestart(); } /** * Restart the current activity with the default map source. */ private void mapRestart() { mapOptions.mapState = currentMapState(); finish(); mapOptions.startIntentWithoutTransition(this, Settings.getMapProvider().getMapClass()); } /** * Get the current map state from the map view if it exists or from the mapStateIntent field otherwise. * * @return the current map state as an array of int, or null if no map state is available */ private MapState currentMapState() { if (mapView == null) { return null; } final Geopoint mapCenter = mapView.getViewport().getCenter(); return new MapState(mapCenter.getCoords(), mapView.getMapZoomLevel(), followMyLocation, Settings.isShowCircles(), targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled); } private void switchTileLayer(final MapSource newSource) { final ITileLayer oldLayer = this.tileLayer; ITileLayer newLayer = null; mapSource = newSource; if (this.mapAttribution != null) { this.mapAttribution.setOnClickListener( new MapAttributionDisplayHandler(() -> this.mapSource.calculateMapAttribution(this))); } if (newSource instanceof AbstractMapsforgeMapSource) { newLayer = ((AbstractMapsforgeMapSource) newSource).createTileLayer(tileCache, this.mapView.getModel().mapViewPosition); } ActivityMixin.invalidateOptionsMenu(this); // Exchange layer if (newLayer != null) { mapView.setZoomLevelMax(newLayer.getZoomLevelMax()); mapView.setZoomLevelMin(newLayer.getZoomLevelMin()); // make sure map zoom level is within new zoom level boundaries final int currentZoomLevel = mapView.getMapZoomLevel(); if (currentZoomLevel < newLayer.getZoomLevelMin()) { mapView.setMapZoomLevel(newLayer.getZoomLevelMin()); } else if (currentZoomLevel > newLayer.getZoomLevelMax()) { mapView.setMapZoomLevel(newLayer.getZoomLevelMax()); } final Layers layers = this.mapView.getLayerManager().getLayers(); int index = 0; if (oldLayer != null) { index = layers.indexOf(oldLayer.getTileLayer()) + 1; } layers.add(index, newLayer.getTileLayer()); this.tileLayer = newLayer; this.renderThemeHelper.reapplyMapTheme(this.tileLayer, this.tileCache); //trigger mapscalebar redraw - otherwise the shown distances will be wrong. //See https://github.com/mapsforge/mapsforge/discussions/1313 this.mapView.getMapScaleBar().setDistanceUnitAdapter(this.mapView.getMapScaleBar().getDistanceUnitAdapter()); this.tileLayer.onResume(); } else { this.tileLayer = null; } // Cleanup if (oldLayer != null) { this.mapView.getLayerManager().getLayers().remove(oldLayer.getTileLayer()); oldLayer.getTileLayer().onDestroy(); } tileCache.purge(); } private void resumeTileLayer() { if (this.tileLayer != null) { this.tileLayer.onResume(); } } private void pauseTileLayer() { if (this.tileLayer != null) { this.tileLayer.onPause(); } } private boolean tileLayerHasThemes() { if (tileLayer != null) { return tileLayer.hasThemes(); } return false; } private void resumeRoute(final boolean force) { if (null == individualRoute || force) { individualRoute = new IndividualRoute(this::setTarget); individualRoute.reloadRoute(routeLayer); } else { individualRoute.updateRoute(routeLayer); } } private void resumeTrack(final String key, final boolean preventReloading) { if (null == tracks && !preventReloading) { this.tracks = new Tracks(this.routeTrackUtils, this::setTrack); } else if (null != trackLayer && null != tracks) { trackLayer.updateRoute(key, tracks.getRoute(key)); } } @Override protected void onResume() { super.onResume(); Log.d("NewMap: onResume"); resumeTileLayer(); resumeRoute(false); if (tracks != null) { tracks.resumeAllTracks(this::resumeTrack); } mapView.getModel().mapViewPosition.addObserver(this); MapUtils.updateFilterBar(this, mapOptions.filterContext); } @Override protected void onStart() { super.onStart(); Log.d("NewMap: onStart"); initializeLayers(); } private void initializeLayers() { switchTileLayer(Settings.getMapSource()); // History Layer this.historyLayer = new HistoryLayer(trailHistory); this.mapView.getLayerManager().getLayers().add(this.historyLayer); // RouteLayer this.routeLayer = new RouteLayer(realRouteDistance -> { if (null != this.distanceView) { this.distanceView.setRouteDistance(realRouteDistance); } }); this.mapView.getLayerManager().getLayers().add(this.routeLayer); // TrackLayer this.trackLayer = new TrackLayer(); this.mapView.getLayerManager().getLayers().add(this.trackLayer); // NavigationLayer Geopoint navTarget = lastNavTarget; if (navTarget == null) { navTarget = mapOptions.coords; if (navTarget == null && StringUtils.isNotEmpty(mapOptions.geocode)) { final Viewport bounds = DataStore.getBounds(mapOptions.geocode); if (bounds != null) { navTarget = bounds.center; } } } this.navigationLayer = new NavigationLayer(navTarget, realDistance -> { if (null != this.distanceView) { this.distanceView.setRealDistance(realDistance); } }); this.mapView.getLayerManager().getLayers().add(this.navigationLayer); // GeoitemLayer GeoitemLayer.resetColors(); // TapHandler final TapHandlerLayer tapHandlerLayer = new TapHandlerLayer(this.mapHandlers.getTapHandler()); this.mapView.getLayerManager().getLayers().add(tapHandlerLayer); // Caches bundle if (mapOptions.searchResult != null) { this.caches = new CachesBundle(this, mapOptions.searchResult, this.mapView, this.mapHandlers); } else if (StringUtils.isNotEmpty(mapOptions.geocode)) { if (mapOptions.mapMode == MapMode.COORDS && mapOptions.coords != null) { this.caches = new CachesBundle(this, mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers, mapOptions.geocode); } else { this.caches = new CachesBundle(this, mapOptions.geocode, this.mapView, this.mapHandlers); } } else if (mapOptions.coords != null) { this.caches = new CachesBundle(this, mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers, null); } else { caches = new CachesBundle(this, this.mapView, this.mapHandlers); } // Stored enabled map caches.handleStoredLayers(this, mapOptions); // Live enabled map caches.handleLiveLayers(this, mapOptions); caches.setFilterContext(mapOptions.filterContext); // Position layer this.positionLayer = new PositionLayer(); this.mapView.getLayerManager().getLayers().add(positionLayer); //Distance view this.distanceView = new DistanceView(findViewById(R.id.distance1).getRootView(), navTarget, Settings.isBrouterShowBothDistances()); //Target view this.targetView = new TargetView((TextView) findViewById(R.id.target), (TextView) findViewById(R.id.targetSupersize), StringUtils.EMPTY, StringUtils.EMPTY); final Geocache target = getCurrentTargetCache(); if (target != null) { targetView.setTarget(target.getShortGeocode(), target.getName()); } // resume location access PermissionHandler.executeIfLocationPermissionGranted(this, new RestartLocationPermissionGrantedCallback(PermissionRequestContext.NewMap) { @Override public void executeAfter() { resumeDisposables.add(geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR)); } }); } @Override public void onPause() { Log.d("NewMap: onPause"); savePrefs(); pauseTileLayer(); mapView.getModel().mapViewPosition.removeObserver(this); super.onPause(); } @Override protected void onStop() { Log.d("NewMap: onStop"); waitDialog = null; terminateLayers(); super.onStop(); } private void terminateLayers() { this.resumeDisposables.clear(); this.caches.onDestroy(); this.caches = null; this.mapView.getLayerManager().getLayers().remove(this.positionLayer); this.positionLayer = null; this.mapView.getLayerManager().getLayers().remove(this.navigationLayer); this.navigationLayer = null; this.mapView.getLayerManager().getLayers().remove(this.routeLayer); this.routeLayer = null; this.mapView.getLayerManager().getLayers().remove(this.trackLayer); this.trackLayer = null; this.mapView.getLayerManager().getLayers().remove(this.historyLayer); this.historyLayer = null; if (this.tileLayer != null) { this.mapView.getLayerManager().getLayers().remove(this.tileLayer.getTileLayer()); this.tileLayer.getTileLayer().onDestroy(); this.tileLayer = null; } } /** * store caches, invoked by "store offline" menu item * * @param listIds the lists to store the caches in */ private void storeCaches(final Set<String> geocodes, final Set<Integer> listIds) { final int count = geocodes.size(); final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(count, this); waitDialog = new ProgressDialog(this); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setCancelMessage(loadDetailsHandler.disposeMessage()); waitDialog.setMax(count); waitDialog.setOnCancelListener(arg0 -> { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } } catch (final Exception e) { Log.e("CGeoMap.storeCaches.onCancel", e); } }); final float etaTime = count * 7.0f / 60.0f; final int roundedEta = Math.round(etaTime); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta, roundedEta)); } loadDetailsHandler.setStart(); waitDialog.show(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes, listIds); loadDetailsThread.start(); } @Override protected void onDestroy() { Log.d("NewMap: onDestroy"); this.tileCache.destroy(); this.mapView.getModel().mapViewPosition.destroy(); this.mapView.destroy(); ResourceBitmapCacheMonitor.release(); Routing.disconnect(ROUTING_SERVICE_KEY); if (this.mapAttribution != null) { this.mapAttribution.setOnClickListener(null); } super.onDestroy(); } @Override protected void onSaveInstanceState(@NonNull final Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle(STATE_ROUTETRACKUTILS, routeTrackUtils.getState()); Log.d("New map: onSaveInstanceState"); final MapState state = prepareMapState(); outState.putParcelable(BUNDLE_MAP_STATE, state); if (proximityNotification != null) { outState.putParcelable(BUNDLE_PROXIMITY_NOTIFICATION, proximityNotification); } if (individualRoute != null) { outState.putParcelable(BUNDLE_ROUTE, individualRoute); } } private MapState prepareMapState() { return new MapState(MapsforgeUtils.toGeopoint(mapView.getModel().mapViewPosition.getCenter()), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled); } private void centerMap(final Geopoint geopoint) { mapView.getModel().mapViewPosition.setCenter(new LatLong(geopoint.getLatitude(), geopoint.getLongitude())); } public Location getCoordinates() { final LatLong center = mapView.getModel().mapViewPosition.getCenter(); final Location loc = new Location("newmap"); loc.setLatitude(center.latitude); loc.setLongitude(center.longitude); return loc; } private void initMyLocationSwitchButton(final CheckBox locSwitch) { myLocSwitch = locSwitch; /* * TODO: Switch back to ImageSwitcher for animations? * myLocSwitch.setFactory(this); * myLocSwitch.setInAnimation(activity, android.R.anim.fade_in); * myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); */ myLocSwitch.setOnClickListener(new MyLocationListener(this)); switchMyLocationButton(); } // switch My Location button image private void switchMyLocationButton() { myLocSwitch.setChecked(followMyLocation); if (followMyLocation) { myLocationInMiddle(Sensors.getInstance().currentGeo()); } } public void showAddWaypoint(final LatLong tapLatLong) { if (Settings.isLongTapOnMapActivated()) { final Geocache cache = getCurrentTargetCache(); if (cache != null) { EditWaypointActivity.startActivityAddWaypoint(this, cache, new Geopoint(tapLatLong.latitude, tapLatLong.longitude)); } else { InternalConnector.interactiveCreateCache(this, new Geopoint(tapLatLong.latitude, tapLatLong.longitude), mapOptions.fromList, true); } } } // set my location listener private static class MyLocationListener implements View.OnClickListener { @NonNull private final WeakReference<NewMap> mapRef; MyLocationListener(@NonNull final NewMap map) { mapRef = new WeakReference<>(map); } private void onFollowMyLocationClicked() { followMyLocation = !followMyLocation; final NewMap map = mapRef.get(); if (map != null) { map.switchMyLocationButton(); } } @Override public void onClick(final View view) { onFollowMyLocationClicked(); } } // Set center of map to my location if appropriate. private void myLocationInMiddle(final GeoData geo) { if (followMyLocation) { centerMap(geo.getCoords()); } } private static final class DisplayHandler extends Handler { @NonNull private final WeakReference<NewMap> mapRef; DisplayHandler(@NonNull final NewMap map) { this.mapRef = new WeakReference<>(map); } @Override public void handleMessage(final Message msg) { final NewMap map = mapRef.get(); if (map == null) { return; } final int what = msg.what; switch (what) { case UPDATE_TITLE: map.setTitle(); map.setSubtitle(); break; default: break; } } } private void setTitle() { final String title = calculateTitle(); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(MapUtils.getColoredValue(title)); } } @NonNull private String calculateTitle() { if (mapOptions.isLiveEnabled) { return res.getString(R.string.map_live); } if (mapOptions.mapMode == MapMode.SINGLE) { final Geocache cache = getSingleModeCache(); if (cache != null) { return cache.getName(); } } return StringUtils.defaultIfEmpty(mapOptions.title, res.getString(R.string.map_offline)); } private void setSubtitle() { final String subtitle = calculateSubtitle(); if (StringUtils.isEmpty(subtitle)) { return; } final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setSubtitle(MapUtils.getColoredValue(subtitle)); } } @NonNull private String calculateSubtitle() { if (!mapOptions.isLiveEnabled && mapOptions.mapMode == MapMode.SINGLE) { final Geocache cache = getSingleModeCache(); if (cache != null) { return Formatter.formatMapSubtitle(cache); } return ""; } // count caches in the sub title final int visible = countVisibleCaches(); final int total = countTotalCaches(); final StringBuilder subtitle = new StringBuilder(); if (visible != total && Settings.isDebug()) { subtitle.append(visible).append('/').append(res.getQuantityString(R.plurals.cache_counts, total, total)); } else { subtitle.append(res.getQuantityString(R.plurals.cache_counts, visible, visible)); } return subtitle.toString(); } private void switchCircles() { caches.switchCircles(); } private int countVisibleCaches() { return caches != null ? caches.getVisibleCachesCount() : 0; } private int countTotalCaches() { return caches != null ? caches.getCachesCount() : 0; } /** * Updates the progress. */ private static final class ShowProgressHandler extends Handler { private int counter = 0; @NonNull private final WeakReference<NewMap> mapRef; ShowProgressHandler(@NonNull final NewMap map) { this.mapRef = new WeakReference<>(map); } @Override public void handleMessage(final Message msg) { final int what = msg.what; if (what == HIDE_PROGRESS) { if (--counter == 0) { showProgress(false); } } else if (what == SHOW_PROGRESS) { showProgress(true); counter++; } } private void showProgress(final boolean show) { final NewMap map = mapRef.get(); if (map == null) { return; } map.spinner.setVisibility(show ? View.VISIBLE : View.GONE); } } private static final class LoadDetailsHandler extends DisposableHandler { private final int detailTotal; private int detailProgress; private long detailProgressTime; private final WeakReference<NewMap> mapRef; LoadDetailsHandler(final int detailTotal, final NewMap map) { super(); this.detailTotal = detailTotal; this.detailProgress = 0; this.mapRef = new WeakReference<>(map); } public void setStart() { detailProgressTime = System.currentTimeMillis(); } @Override public void handleRegularMessage(final Message msg) { final NewMap map = mapRef.get(); if (map == null) { return; } if (msg.what == UPDATE_PROGRESS) { if (detailProgress < detailTotal) { detailProgress++; } if (map.waitDialog != null) { final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); final int secondsRemaining; if (detailProgress > 0) { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress; } else { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed; } map.waitDialog.setProgress(detailProgress); if (secondsRemaining < 40) { map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getString(R.string.caches_eta_ltm)); } else { final int minsRemaining = secondsRemaining / 60; map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining)); } } } else if (msg.what == FINISHED_LOADING_DETAILS && map.waitDialog != null) { map.waitDialog.dismiss(); map.waitDialog.setOnCancelListener(null); } } @Override public void handleDispose() { final NewMap map = mapRef.get(); if (map == null) { return; } if (map.loadDetailsThread != null) { map.loadDetailsThread.stopIt(); } } } // class: update location private static class UpdateLoc extends GeoDirHandler { // use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible // minimum time in milliseconds between position overlay updates private static final long MIN_UPDATE_INTERVAL = 500; // minimum change of heading in grad for position overlay update private static final float MIN_HEADING_DELTA = 15f; // minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update private static final float MIN_LOCATION_DELTA = 0.01f; @NonNull Location currentLocation = Sensors.getInstance().currentGeo(); float currentHeading; private long timeLastPositionOverlayCalculation = 0; private long timeLastDistanceCheck = 0; /** * weak reference to the outer class */ @NonNull private final WeakReference<NewMap> mapRef; UpdateLoc(@NonNull final NewMap map) { mapRef = new WeakReference<>(map); } @Override public void updateGeoDir(@NonNull final GeoData geo, final float dir) { currentLocation = geo; currentHeading = AngleUtils.getDirectionNow(dir); repaintPositionOverlay(); } @NonNull public Location getCurrentLocation() { return currentLocation; } /** * Repaint position overlay but only with a max frequency and if position or heading changes sufficiently. */ void repaintPositionOverlay() { final long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis > (timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL)) { timeLastPositionOverlayCalculation = currentTimeMillis; try { final NewMap map = mapRef.get(); if (map != null) { final boolean needsRepaintForDistanceOrAccuracy = needsRepaintForDistanceOrAccuracy(); final boolean needsRepaintForHeading = needsRepaintForHeading(); if (needsRepaintForDistanceOrAccuracy && NewMap.followMyLocation) { map.centerMap(new Geopoint(currentLocation)); } if (needsRepaintForDistanceOrAccuracy || needsRepaintForHeading) { map.historyLayer.setCoordinates(currentLocation); map.navigationLayer.setCoordinates(currentLocation); map.distanceView.setCoordinates(currentLocation); map.distanceView.showRouteDistance(); map.positionLayer.setCoordinates(currentLocation); map.positionLayer.setHeading(currentHeading); map.positionLayer.requestRedraw(); if (null != map.proximityNotification && (timeLastDistanceCheck == 0 || currentTimeMillis > (timeLastDistanceCheck + MIN_UPDATE_INTERVAL))) { map.proximityNotification.checkDistance(map.caches.getClosestDistanceInM(new Geopoint(currentLocation.getLatitude(), currentLocation.getLongitude()))); timeLastDistanceCheck = System.currentTimeMillis(); } } } } catch (final RuntimeException e) { Log.w("Failed to update location", e); } } } boolean needsRepaintForHeading() { final NewMap map = mapRef.get(); if (map == null) { return false; } return Math.abs(AngleUtils.difference(currentHeading, map.positionLayer.getHeading())) > MIN_HEADING_DELTA; } boolean needsRepaintForDistanceOrAccuracy() { final NewMap map = mapRef.get(); if (map == null) { return false; } final Location lastLocation = map.getCoordinates(); float dist = Float.MAX_VALUE; if (lastLocation != null) { if (lastLocation.getAccuracy() != currentLocation.getAccuracy()) { return true; } dist = currentLocation.distanceTo(lastLocation); } final float[] mapDimension = new float[1]; if (map.mapView.getWidth() < map.mapView.getHeight()) { final double span = map.mapView.getLongitudeSpan() / 1e6; Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension); } else { final double span = map.mapView.getLatitudeSpan() / 1e6; Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension); } return dist > (mapDimension[0] * MIN_LOCATION_DELTA); } } private static class DragHandler implements OnMapDragListener { @NonNull private final WeakReference<NewMap> mapRef; DragHandler(@NonNull final NewMap parent) { mapRef = new WeakReference<>(parent); } @Override public void onDrag() { final NewMap map = mapRef.get(); if (map != null && NewMap.followMyLocation) { NewMap.followMyLocation = false; map.switchMyLocationButton(); } } } public void showSelection(@NonNull final List<GeoitemRef> items, final boolean longPressMode) { if (items.isEmpty()) { return; } if (items.size() == 1) { if (longPressMode) { if (Settings.isLongTapOnMapActivated()) { toggleRouteItem(items.get(0)); } } else { showPopup(items.get(0)); } return; } try { final ArrayList<GeoitemRef> sorted = new ArrayList<>(items); Collections.sort(sorted, GeoitemRef.NAME_COMPARATOR); final ListAdapter adapter = new ArrayAdapter<GeoitemRef>(this, R.layout.cacheslist_item_select, sorted) { @NonNull @Override public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) { return GeoItemSelectorUtils.createGeoItemView(NewMap.this, getItem(position), GeoItemSelectorUtils.getOrCreateView(NewMap.this, convertView, parent)); } }; final AlertDialog dialog = Dialogs.newBuilder(this) .setTitle(res.getString(R.string.map_select_multiple_items)) .setAdapter(adapter, new SelectionClickListener(sorted, longPressMode)) .create(); dialog.setCanceledOnTouchOutside(true); dialog.show(); } catch (final NotFoundException e) { Log.e("NewMap.showSelection", e); } } private class SelectionClickListener implements DialogInterface.OnClickListener { @NonNull private final List<GeoitemRef> items; private final boolean longPressMode; SelectionClickListener(@NonNull final List<GeoitemRef> items, final boolean longPressMode) { this.items = items; this.longPressMode = longPressMode; } @Override public void onClick(final DialogInterface dialog, final int which) { if (which >= 0 && which < items.size()) { final GeoitemRef item = items.get(which); if (longPressMode) { if (Settings.isLongTapOnMapActivated()) { toggleRouteItem(item); } } else { showPopup(item); } } } } private void showPopup(final GeoitemRef item) { if (item == null || StringUtils.isEmpty(item.getGeocode())) { return; } try { if (item.getType() == CoordinatesType.CACHE) { final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); if (cache != null) { popupGeocodes.add(cache.getGeocode()); CachePopup.startActivityAllowTarget(this, cache.getGeocode()); return; } return; } if (item.getType() == CoordinatesType.WAYPOINT && item.getId() >= 0) { popupGeocodes.add(item.getGeocode()); WaypointPopup.startActivityAllowTarget(this, item.getId(), item.getGeocode()); } } catch (final NotFoundException e) { Log.e("NewMap.showPopup", e); } } private void toggleRouteItem(final GeoitemRef item) { if (item == null || StringUtils.isEmpty(item.getGeocode())) { return; } if (individualRoute == null) { individualRoute = new IndividualRoute(this::setTarget); } individualRoute.toggleItem(this, new RouteItem(item), routeLayer); distanceView.showRouteDistance(); ActivityMixin.invalidateOptionsMenu(this); } @Nullable private Geocache getSingleModeCache() { if (StringUtils.isNotBlank(mapOptions.geocode)) { return DataStore.loadCache(mapOptions.geocode, LoadFlags.LOAD_CACHE_OR_DB); } return null; } @Nullable private Geocache getCurrentTargetCache() { if (StringUtils.isNotBlank(targetGeocode)) { return DataStore.loadCache(targetGeocode, LoadFlags.LOAD_CACHE_OR_DB); } return null; } private void setTarget(final Geopoint coords, final String geocode) { lastNavTarget = coords; if (StringUtils.isNotBlank(geocode)) { targetGeocode = geocode; final Geocache target = getCurrentTargetCache(); targetView.setTarget(targetGeocode, target != null ? target.getName() : StringUtils.EMPTY); if (lastNavTarget == null && target != null) { lastNavTarget = target.getCoords(); } } else { targetGeocode = null; targetView.setTarget(null, null); } if (navigationLayer != null) { navigationLayer.setDestination(lastNavTarget); navigationLayer.requestRedraw(); } if (distanceView != null) { distanceView.setDestination(lastNavTarget); distanceView.setCoordinates(geoDirUpdate.getCurrentLocation()); } ActivityMixin.invalidateOptionsMenu(this); } private void savePrefs() { Settings.setMapZoom(this.mapMode, mapView.getMapZoomLevel()); Settings.setMapCenter(new MapsforgeGeoPoint(mapView.getModel().mapViewPosition.getCenter())); } /** * Thread to store the caches in the viewport. Started by Activity. */ private class LoadDetails extends Thread { private final DisposableHandler handler; private final Collection<String> geocodes; private final Set<Integer> listIds; LoadDetails(final DisposableHandler handler, final Collection<String> geocodes, final Set<Integer> listIds) { this.handler = handler; this.geocodes = geocodes; this.listIds = listIds; } public void stopIt() { handler.dispose(); } @Override public void run() { if (CollectionUtils.isEmpty(geocodes)) { return; } for (final String geocode : geocodes) { try { if (handler.isDisposed()) { break; } Geocache.storeCache(null, geocode, listIds, false, handler); } catch (final Exception e) { Log.e("CGeoMap.LoadDetails.run", e); } finally { handler.sendEmptyMessage(UPDATE_PROGRESS); } } // we're done, but map might even have been closed. if (caches != null) { caches.invalidate(geocodes); } invalidateOptionsMenuCompatible(); handler.sendEmptyMessage(FINISHED_LOADING_DETAILS); } } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == AbstractDialogFragment.REQUEST_CODE_TARGET_INFO) { if (resultCode == AbstractDialogFragment.RESULT_CODE_SET_TARGET) { final TargetInfo targetInfo = data.getExtras().getParcelable(Intents.EXTRA_TARGET_INFO); if (targetInfo != null) { if (Settings.isAutotargetIndividualRoute()) { Settings.setAutotargetIndividualRoute(false); Toast.makeText(this, R.string.map_disable_autotarget_individual_route, Toast.LENGTH_SHORT).show(); } setTarget(targetInfo.coords, targetInfo.geocode); } } final List<String> changedGeocodes = new ArrayList<>(); String geocode = popupGeocodes.poll(); while (geocode != null) { changedGeocodes.add(geocode); geocode = popupGeocodes.poll(); } if (caches != null) { caches.invalidate(changedGeocodes); } } if (requestCode == GeocacheFilterActivity.REQUEST_SELECT_FILTER && resultCode == Activity.RESULT_OK) { mapOptions.filterContext = data.getParcelableExtra(EXTRA_FILTER_CONTEXT); refreshMapData(false); } this.routeTrackUtils.onActivityResult(requestCode, resultCode, data); } private void setTrack(final String key, final Route route) { tracks.setRoute(key, route); resumeTrack(key, null == route); } private void reloadIndividualRoute() { if (null != routeLayer) { individualRoute.reloadRoute(routeLayer); } else { // try again in 0.25 second new Handler(Looper.getMainLooper()).postDelayed(this::reloadIndividualRoute, 250); } } private Boolean isTargetSet() { return StringUtils.isNotBlank(targetGeocode) && null != lastNavTarget; } private static class ResourceBitmapCacheMonitor { private static int refCount = 0; static synchronized void addRef() { refCount++; Log.d("ResourceBitmapCacheMonitor.addRef"); } static synchronized void release() { if (refCount > 0) { refCount--; Log.d("ResourceBitmapCacheMonitor.release"); if (refCount == 0) { Log.d("ResourceBitmapCacheMonitor.clearResourceBitmaps"); AndroidResourceBitmap.clearResourceBitmaps(); } } } } public boolean getLastCompactIconMode() { return lastCompactIconMode; } public boolean checkCompactIconMode(final int overlayId, final int newCount) { boolean newCompactIconMode = lastCompactIconMode; if (null != caches) { newCompactIconMode = CompactIconModeUtils.forceCompactIconMode(caches.getVisibleCachesCount(overlayId, newCount)); if (lastCompactIconMode != newCompactIconMode) { lastCompactIconMode = newCompactIconMode; // @todo Exchanging & redrawing the icons would be sufficient, do not have to invalidate everything! caches.invalidateAll(overlayId); // redraw all icons except for the given overlay } } return newCompactIconMode; } // get notified for viewport changes (zoom/pan) public void onChange() { final Viewport newViewport = mapView.getViewport(); if (!newViewport.equals(lastViewport)) { lastViewport = newViewport; checkCompactIconMode(NO_OVERLAY_ID, 0); } } public static class MapAttributionDisplayHandler implements View.OnClickListener { private Supplier<ImmutablePair<String, Boolean>> attributionSupplier; private ImmutablePair<String, Boolean> attributionPair; public MapAttributionDisplayHandler(final Supplier<ImmutablePair<String, Boolean>> attributionSupplier) { this.attributionSupplier = attributionSupplier; } @Override public void onClick(final View v) { if (this.attributionPair == null) { this.attributionPair = attributionSupplier.get(); if (this.attributionPair == null || this.attributionPair.left == null) { this.attributionPair = new ImmutablePair<>("---", false); } this.attributionSupplier = null; //prevent possible memory leaks } displayMapAttribution(v.getContext(), this.attributionPair.left, this.attributionPair.right); } } private static void displayMapAttribution(final Context ctx, final String attribution, final boolean linkify) { //create text message CharSequence message = HtmlCompat.fromHtml(attribution, HtmlCompat.FROM_HTML_MODE_LEGACY); if (linkify) { final SpannableString s = new SpannableString(message); Linkify.addLinks(s, Linkify.ALL); message = s; } final AlertDialog alertDialog = Dialogs.newBuilder(ctx) .setTitle(ctx.getString(R.string.map_source_attribution_dialog_title)) .setCancelable(true) .setMessage(message) .setPositiveButton(android.R.string.ok, (dialog, pos) -> dialog.dismiss()) .create(); alertDialog.show(); // Make the URLs in TextView clickable. Must be called after show() // Note: we do NOT use the "setView()" option of AlertDialog because this screws up the layout ((TextView) alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); } }
main/src/cgeo/geocaching/maps/mapsforge/v6/NewMap.java
package cgeo.geocaching.maps.mapsforge.v6; import cgeo.geocaching.AbstractDialogFragment; import cgeo.geocaching.AbstractDialogFragment.TargetInfo; import cgeo.geocaching.CacheListActivity; import cgeo.geocaching.CachePopup; import cgeo.geocaching.CompassActivity; import cgeo.geocaching.EditWaypointActivity; import cgeo.geocaching.Intents; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.WaypointPopup; import cgeo.geocaching.activity.AbstractBottomNavigationActivity; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.activity.FilteredActivity; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.connector.internal.InternalConnector; import cgeo.geocaching.databinding.MapMapsforgeV6Binding; import cgeo.geocaching.downloader.DownloaderUtils; import cgeo.geocaching.enumerations.CoordinatesType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.filters.core.GeocacheFilter; import cgeo.geocaching.filters.core.GeocacheFilterContext; import cgeo.geocaching.filters.gui.GeocacheFilterActivity; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.location.ProximityNotification; import cgeo.geocaching.location.Viewport; import cgeo.geocaching.maps.MapMode; import cgeo.geocaching.maps.MapOptions; import cgeo.geocaching.maps.MapProviderFactory; import cgeo.geocaching.maps.MapSettingsUtils; import cgeo.geocaching.maps.MapState; import cgeo.geocaching.maps.MapUtils; import cgeo.geocaching.maps.RouteTrackUtils; import cgeo.geocaching.maps.Tracks; import cgeo.geocaching.maps.interfaces.MapSource; import cgeo.geocaching.maps.interfaces.OnMapDragListener; import cgeo.geocaching.maps.mapsforge.AbstractMapsforgeMapSource; import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider; import cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle; import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemLayer; import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemRef; import cgeo.geocaching.maps.mapsforge.v6.layers.HistoryLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.ITileLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.NavigationLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.PositionLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.RouteLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.TapHandlerLayer; import cgeo.geocaching.maps.mapsforge.v6.layers.TrackLayer; import cgeo.geocaching.maps.mapsforge.v6.legend.RenderThemeLegend; import cgeo.geocaching.maps.routing.Routing; import cgeo.geocaching.maps.routing.RoutingMode; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.models.IndividualRoute; import cgeo.geocaching.models.Route; import cgeo.geocaching.models.RouteItem; import cgeo.geocaching.models.TrailHistoryElement; import cgeo.geocaching.permission.PermissionHandler; import cgeo.geocaching.permission.PermissionRequestContext; import cgeo.geocaching.permission.RestartLocationPermissionGrantedCallback; import cgeo.geocaching.sensors.GeoData; import cgeo.geocaching.sensors.GeoDirHandler; import cgeo.geocaching.sensors.Sensors; import cgeo.geocaching.service.CacheDownloaderService; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.storage.DataStore; import cgeo.geocaching.storage.LocalStorage; import cgeo.geocaching.ui.GeoItemSelectorUtils; import cgeo.geocaching.ui.ViewUtils; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.utils.AndroidRxUtils; import cgeo.geocaching.utils.AngleUtils; import cgeo.geocaching.utils.ApplicationSettings; import cgeo.geocaching.utils.BranchDetectionHelper; import cgeo.geocaching.utils.CompactIconModeUtils; import cgeo.geocaching.utils.DisposableHandler; import cgeo.geocaching.utils.FilterUtils; import cgeo.geocaching.utils.Formatter; import cgeo.geocaching.utils.HistoryTrackUtils; import cgeo.geocaching.utils.Log; import static cgeo.geocaching.filters.core.GeocacheFilterContext.FilterType.LIVE; import static cgeo.geocaching.filters.gui.GeocacheFilterActivity.EXTRA_FILTER_CONTEXT; import static cgeo.geocaching.maps.MapProviderFactory.MAP_LANGUAGE_DEFAULT_ID; import static cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle.NO_OVERLAY_ID; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources.NotFoundException; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ListAdapter; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.core.text.HtmlCompat; import androidx.core.util.Supplier; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.RejectedExecutionException; import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.schedulers.Schedulers; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.mapsforge.core.model.BoundingBox; import org.mapsforge.core.model.LatLong; import org.mapsforge.core.model.MapPosition; import org.mapsforge.core.util.Parameters; import org.mapsforge.map.android.graphics.AndroidGraphicFactory; import org.mapsforge.map.android.graphics.AndroidResourceBitmap; import org.mapsforge.map.android.input.MapZoomControls; import org.mapsforge.map.android.util.AndroidUtil; import org.mapsforge.map.layer.Layers; import org.mapsforge.map.layer.cache.TileCache; import org.mapsforge.map.model.common.Observer; @SuppressLint("ClickableViewAccessibility") @SuppressWarnings("PMD.ExcessiveClassLength") // This is definitely a valid issue, but can't be refactored in one step public class NewMap extends AbstractBottomNavigationActivity implements Observer, FilteredActivity { private static final String STATE_ROUTETRACKUTILS = "routetrackutils"; private static final String ROUTING_SERVICE_KEY = "NewMap"; private MfMapView mapView; private TileCache tileCache; private MapSource mapSource; private ITileLayer tileLayer; private HistoryLayer historyLayer; private PositionLayer positionLayer; private NavigationLayer navigationLayer; private RouteLayer routeLayer; private TrackLayer trackLayer; private CachesBundle caches; private final MapHandlers mapHandlers = new MapHandlers(new TapHandler(this), new DisplayHandler(this), new ShowProgressHandler(this)); private RenderThemeHelper renderThemeHelper = null; //must be initialized in onCreate(); private DistanceView distanceView; private View mapAttribution; private final ArrayList<TrailHistoryElement> trailHistory = null; private String targetGeocode = null; private Geopoint lastNavTarget = null; private final Queue<String> popupGeocodes = new ConcurrentLinkedQueue<>(); private ProgressDialog waitDialog; private LoadDetails loadDetailsThread; private ProgressBar spinner; private final UpdateLoc geoDirUpdate = new UpdateLoc(this); /** * initialization with an empty subscription to make static code analysis tools more happy */ private ProximityNotification proximityNotification; private final CompositeDisposable resumeDisposables = new CompositeDisposable(); private CheckBox myLocSwitch; private MapOptions mapOptions; private TargetView targetView; private IndividualRoute individualRoute = null; private Tracks tracks = null; private static boolean followMyLocation = true; private static final String BUNDLE_MAP_STATE = "mapState"; private static final String BUNDLE_PROXIMITY_NOTIFICATION = "proximityNotification"; private static final String BUNDLE_ROUTE = "route"; // Handler messages // DisplayHandler public static final int UPDATE_TITLE = 0; // ShowProgressHandler public static final int HIDE_PROGRESS = 0; public static final int SHOW_PROGRESS = 1; // LoadDetailsHandler public static final int UPDATE_PROGRESS = 0; public static final int FINISHED_LOADING_DETAILS = 1; private Viewport lastViewport = null; private boolean lastCompactIconMode = false; private MapMode mapMode; private RouteTrackUtils routeTrackUtils = null; @Override public void onCreate(final Bundle savedInstanceState) { ApplicationSettings.setLocale(this); super.onCreate(savedInstanceState); Log.d("NewMap: onCreate"); routeTrackUtils = new RouteTrackUtils(this, savedInstanceState == null ? null : savedInstanceState.getBundle(STATE_ROUTETRACKUTILS), this::centerOnPosition, this::clearIndividualRoute, this::reloadIndividualRoute, this::setTrack, this::isTargetSet); tracks = new Tracks(routeTrackUtils, this::setTrack); ResourceBitmapCacheMonitor.addRef(); AndroidGraphicFactory.createInstance(this.getApplication()); AndroidGraphicFactory.INSTANCE.setSvgCacheDir(LocalStorage.getMapsforgeSvgCacheDir()); MapsforgeMapProvider.getInstance().updateOfflineMaps(); this.renderThemeHelper = new RenderThemeHelper(this); // Support for multi-threaded map painting Parameters.NUMBER_OF_THREADS = Settings.getMapOsmThreads(); Log.i("OSM #threads=" + Parameters.NUMBER_OF_THREADS); // Use fast parent tile rendering to increase performance when zooming in Parameters.PARENT_TILES_RENDERING = Parameters.ParentTilesRendering.SPEED; // Get parameters from the intent mapOptions = new MapOptions(this, getIntent().getExtras()); // Get fresh map information from the bundle if any if (savedInstanceState != null) { mapOptions.mapState = savedInstanceState.getParcelable(BUNDLE_MAP_STATE); proximityNotification = savedInstanceState.getParcelable(BUNDLE_PROXIMITY_NOTIFICATION); individualRoute = savedInstanceState.getParcelable(BUNDLE_ROUTE); followMyLocation = mapOptions.mapState.followsMyLocation(); } else { if (mapOptions.mapState != null) { followMyLocation = mapOptions.mapState.followsMyLocation(); } else { followMyLocation = followMyLocation && mapOptions.mapMode == MapMode.LIVE; } individualRoute = null; proximityNotification = Settings.isGeneralProximityNotificationActive() ? new ProximityNotification(true, false) : null; } if (null != proximityNotification) { proximityNotification.setTextNotifications(this); } ActivityMixin.onCreate(this, true); // set layout ActivityMixin.setTheme(this); // adding the bottom navigation component is handled by {@link AbstractBottomNavigationActivity#setContentView} setContentView(MapMapsforgeV6Binding.inflate(getLayoutInflater()).getRoot()); setTitle(); this.mapAttribution = findViewById(R.id.map_attribution); // map settings popup findViewById(R.id.map_settings_popup).setOnClickListener(v -> MapSettingsUtils.showSettingsPopup(this, individualRoute, this::refreshMapData, this::routingModeChanged, this::compactIconModeChanged, mapOptions.filterContext)); // routes / tracks popup findViewById(R.id.map_individualroute_popup).setOnClickListener(v -> routeTrackUtils.showPopup(individualRoute, this::setTarget)); // prepare circular progress spinner spinner = (ProgressBar) findViewById(R.id.map_progressbar); spinner.setVisibility(View.GONE); // initialize map mapView = (MfMapView) findViewById(R.id.mfmapv5); mapView.setClickable(true); mapView.getMapScaleBar().setVisible(true); mapView.setBuiltInZoomControls(true); // style zoom controls final MapZoomControls zoomControls = mapView.getMapZoomControls(); zoomControls.setZoomControlsOrientation(MapZoomControls.Orientation.VERTICAL_IN_OUT); zoomControls.setZoomInResource(R.drawable.map_zoomin); zoomControls.setZoomOutResource(R.drawable.map_zoomout); zoomControls.setPadding(0, 0, ViewUtils.dpToPixel(13.0f), ViewUtils.dpToPixel(18.0f)); zoomControls.setAutoHide(false); //make room for map attribution icon button final int mapAttPx = Math.round(this.getResources().getDisplayMetrics().density * 30); mapView.getMapScaleBar().setMarginHorizontal(mapAttPx); // create a tile cache of suitable size. always initialize it based on the smallest tile size to expect (256 for online tiles) tileCache = AndroidUtil.createTileCache(this, "mapcache", 256, 1f, this.mapView.getModel().frameBufferModel.getOverdrawFactor()); // attach drag handler final DragHandler dragHandler = new DragHandler(this); mapView.setOnMapDragListener(dragHandler); mapMode = (mapOptions != null && mapOptions.mapMode != null) ? mapOptions.mapMode : MapMode.LIVE; // prepare initial settings of mapView if (mapOptions.mapState != null) { this.mapView.getModel().mapViewPosition.setCenter(MapsforgeUtils.toLatLong(mapOptions.mapState.getCenter())); this.mapView.setMapZoomLevel((byte) mapOptions.mapState.getZoomLevel()); this.targetGeocode = mapOptions.mapState.getTargetGeocode(); this.lastNavTarget = mapOptions.mapState.getLastNavTarget(); mapOptions.isLiveEnabled = mapOptions.mapState.isLiveEnabled(); mapOptions.isStoredEnabled = mapOptions.mapState.isStoredEnabled(); } else if (mapOptions.searchResult != null) { final Viewport viewport = DataStore.getBounds(mapOptions.searchResult.getGeocodes()); if (viewport != null) { postZoomToViewport(viewport); } } else if (StringUtils.isNotEmpty(mapOptions.geocode) && mapOptions.mapMode != MapMode.COORDS) { final Viewport viewport = DataStore.getBounds(mapOptions.geocode, Settings.getZoomIncludingWaypoints()); if (viewport != null) { postZoomToViewport(viewport); } targetGeocode = mapOptions.geocode; final Geocache temp = getCurrentTargetCache(); if (temp != null) { lastNavTarget = temp.getCoords(); } } else if (mapOptions.coords != null) { postZoomToViewport(new Viewport(mapOptions.coords, 0, 0)); if (mapOptions.mapMode == MapMode.LIVE) { mapOptions.coords = null; // no direction line, even if enabled in settings followMyLocation = false; // do not center on GPS position, even if in LIVE mode } } else { postZoomToViewport(new Viewport(Settings.getMapCenter().getCoords(), 0, 0)); } FilterUtils.initializeFilterBar(this, this); MapUtils.updateFilterBar(this, mapOptions.filterContext); Routing.connect(ROUTING_SERVICE_KEY, () -> resumeRoute(true)); CompactIconModeUtils.setCompactIconModeThreshold(getResources()); MapsforgeMapProvider.getInstance().updateOfflineMaps(); MapUtils.showMapOneTimeMessages(this, mapMode); } private void postZoomToViewport(final Viewport viewport) { mapView.post(() -> mapView.zoomToViewport(viewport, this.mapMode)); } @Override public boolean onCreateOptionsMenu(@NonNull final Menu menu) { final boolean result = super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.map_activity, menu); MapProviderFactory.addMapviewMenuItems(this, menu); MapProviderFactory.addMapViewLanguageMenuItems(menu); initMyLocationSwitchButton(MapProviderFactory.createLocSwitchMenuItem(this, menu)); FilterUtils.initializeFilterMenu(this, this); return result; } @Override public int getSelectedBottomItemId() { return mapOptions.mapMode == MapMode.LIVE ? MENU_MAP : MENU_HIDE_BOTTOM_NAVIGATION; } @Override public boolean onPrepareOptionsMenu(@NonNull final Menu menu) { super.onPrepareOptionsMenu(menu); if (mapOptions != null) { ViewUtils.extendMenuActionBarDisplayItemCount(this, menu); } for (final MapSource mapSource : MapProviderFactory.getMapSources()) { final MenuItem menuItem = menu.findItem(mapSource.getNumericalId()); if (menuItem != null) { menuItem.setVisible(mapSource.isAvailable()); } } try { final MenuItem itemMapLive = menu.findItem(R.id.menu_map_live); if (mapOptions.isLiveEnabled) { itemMapLive.setIcon(R.drawable.ic_menu_sync_enabled); itemMapLive.setTitle(res.getString(R.string.map_live_disable)); } else { itemMapLive.setIcon(R.drawable.ic_menu_sync_disabled); itemMapLive.setTitle(res.getString(R.string.map_live_enable)); } itemMapLive.setVisible(mapOptions.coords == null || mapOptions.mapMode == MapMode.LIVE); final Set<String> visibleCacheGeocodes = caches.getVisibleCacheGeocodes(); menu.findItem(R.id.menu_store_caches).setVisible(false); menu.findItem(R.id.menu_store_caches).setVisible(!caches.isDownloading() && !visibleCacheGeocodes.isEmpty()); menu.findItem(R.id.menu_store_unsaved_caches).setVisible(false); menu.findItem(R.id.menu_store_unsaved_caches).setVisible(!caches.isDownloading() && new SearchResult(visibleCacheGeocodes).hasUnsavedCaches()); if (!BranchDetectionHelper.isProductionBuild()) { menu.findItem(R.id.menu_store_caches_background).setVisible(!caches.isDownloading() && !visibleCacheGeocodes.isEmpty()); } final boolean tileLayerHasThemes = tileLayerHasThemes(); menu.findItem(R.id.menu_theme_mode).setVisible(tileLayerHasThemes); menu.findItem(R.id.menu_theme_options).setVisible(tileLayerHasThemes); menu.findItem(R.id.menu_theme_legend).setVisible(tileLayerHasThemes && RenderThemeLegend.supportsLegend()); menu.findItem(R.id.menu_as_list).setVisible(!caches.isDownloading() && caches.getVisibleCachesCount() > 1); this.routeTrackUtils.onPrepareOptionsMenu(menu, findViewById(R.id.container_individualroute), individualRoute, tracks); menu.findItem(R.id.menu_hint).setVisible(mapOptions.mapMode == MapMode.SINGLE); menu.findItem(R.id.menu_compass).setVisible(mapOptions.mapMode == MapMode.SINGLE); HistoryTrackUtils.onPrepareOptionsMenu(menu); } catch (final RuntimeException e) { Log.e("NewMap.onPrepareOptionsMenu", e); } return true; } @Override public void onConfigurationChanged(@NonNull final Configuration newConfig) { super.onConfigurationChanged(newConfig); invalidateOptionsMenu(); } @Override public boolean onOptionsItemSelected(@NonNull final MenuItem item) { final int id = item.getItemId(); if (id == R.id.menu_map_live) { mapOptions.isLiveEnabled = !mapOptions.isLiveEnabled; if (mapOptions.isLiveEnabled) { mapOptions.isStoredEnabled = true; mapOptions.filterContext = new GeocacheFilterContext(LIVE); caches.setFilterContext(mapOptions.filterContext); refreshMapData(false); } if (mapOptions.mapMode == MapMode.LIVE) { Settings.setLiveMap(mapOptions.isLiveEnabled); } caches.handleStoredLayers(this, mapOptions); caches.handleLiveLayers(this, mapOptions); ActivityMixin.invalidateOptionsMenu(this); if (mapOptions.mapMode == MapMode.SINGLE) { setTarget(mapOptions.coords, mapOptions.geocode); } mapOptions.mapMode = MapMode.LIVE; updateSelectedBottomNavItemId(); mapOptions.title = StringUtils.EMPTY; setTitle(); } else if (id == R.id.menu_filter) { showFilterMenu(); } else if (id == R.id.menu_store_caches) { return storeCaches(caches.getVisibleCacheGeocodes()); } else if (id == R.id.menu_store_unsaved_caches) { return storeCaches(getUnsavedGeocodes(caches.getVisibleCacheGeocodes())); } else if (id == R.id.menu_store_caches_background) { CacheDownloaderService.downloadCaches(this, caches.getVisibleCacheGeocodes(), false, false); } else if (id == R.id.menu_theme_mode) { this.renderThemeHelper.selectMapTheme(this.tileLayer, this.tileCache); } else if (id == R.id.menu_theme_options) { this.renderThemeHelper.selectMapThemeOptions(); } else if (id == R.id.menu_theme_legend) { RenderThemeLegend.showLegend(this, this.renderThemeHelper, mapView.getModel().displayModel); } else if (id == R.id.menu_as_list) { CacheListActivity.startActivityMap(this, new SearchResult(caches.getVisibleCacheGeocodes())); ActivityMixin.overrideTransitionToFade(this); } else if (id == R.id.menu_hint) { menuShowHint(); } else if (id == R.id.menu_compass) { menuCompass(); } else if (id == R.id.menu_check_routingdata) { final BoundingBox bb = mapView.getBoundingBox(); MapUtils.checkRoutingData(this, bb.minLatitude, bb.minLongitude, bb.maxLatitude, bb.maxLongitude); } else if (HistoryTrackUtils.onOptionsItemSelected(this, id, () -> historyLayer.requestRedraw(), this::clearTrailHistory) || DownloaderUtils.onOptionsItemSelected(this, id)) { return true; } else if (id == R.id.menu_routetrack) { routeTrackUtils.showPopup(individualRoute, this::setTarget); } else { final String language = MapProviderFactory.getLanguage(id); final MapSource mapSource = MapProviderFactory.getMapSource(id); if (language != null || id == MAP_LANGUAGE_DEFAULT_ID) { item.setChecked(true); changeLanguage(language); return true; } if (mapSource != null) { item.setChecked(true); changeMapSource(mapSource); return true; } return super.onOptionsItemSelected(item); } return true; } private void refreshMapData(final boolean circlesSwitched) { if (circlesSwitched) { caches.switchCircles(); } if (caches != null) { caches.invalidate(); } Tile.cache.clear(); if (null != trackLayer) { // trackLayer.setHidden(Settings.isHideTrack()); trackLayer.requestRedraw(); } MapUtils.updateFilterBar(this, mapOptions.filterContext); } private void routingModeChanged(final RoutingMode newValue) { Settings.setRoutingMode(newValue); if ((null != individualRoute && individualRoute.getNumSegments() > 0) || null != tracks) { Toast.makeText(this, R.string.brouter_recalculating, Toast.LENGTH_SHORT).show(); } individualRoute.reloadRoute(routeLayer); if (null != tracks) { try { AndroidRxUtils.andThenOnUi(Schedulers.computation(), () -> tracks.traverse((key, route) -> { route.calculateNavigationRoute(); trackLayer.updateRoute(key, route); }), () -> trackLayer.requestRedraw()); } catch (RejectedExecutionException e) { Log.e("NewMap.routingModeChanged: RejectedExecutionException: " + e.getMessage()); } } navigationLayer.requestRedraw(); } private void compactIconModeChanged(final int newValue) { Settings.setCompactIconMode(newValue); caches.invalidateAll(NO_OVERLAY_ID); } private void clearTrailHistory() { this.historyLayer.reset(); this.historyLayer.requestRedraw(); showToast(res.getString(R.string.map_trailhistory_cleared)); } private void clearIndividualRoute() { individualRoute.clearRoute(routeLayer); distanceView.showRouteDistance(); ActivityMixin.invalidateOptionsMenu(this); showToast(res.getString(R.string.map_individual_route_cleared)); } private void centerOnPosition(final double latitude, final double longitude, final Viewport viewport) { followMyLocation = false; switchMyLocationButton(); mapView.getModel().mapViewPosition.setMapPosition(new MapPosition(new LatLong(latitude, longitude), (byte) mapView.getMapZoomLevel())); postZoomToViewport(viewport); } private Set<String> getUnsavedGeocodes(final Set<String> geocodes) { final Set<String> unsavedGeocodes = new HashSet<>(); for (final String geocode : geocodes) { if (!DataStore.isOffline(geocode, null)) { unsavedGeocodes.add(geocode); } } return unsavedGeocodes; } private boolean storeCaches(final Set<String> geocodes) { if (!caches.isDownloading()) { if (geocodes.isEmpty()) { ActivityMixin.showToast(this, res.getString(R.string.warn_save_nothing)); return true; } if (Settings.getChooseList()) { // let user select list to store cache in new StoredList.UserInterface(this).promptForMultiListSelection(R.string.lists_title, selectedListIds -> storeCaches(geocodes, selectedListIds), true, Collections.emptySet(), false); } else { storeCaches(geocodes, Collections.singleton(StoredList.STANDARD_LIST_ID)); } } return true; } private void menuCompass() { final Geocache cache = getCurrentTargetCache(); if (cache != null) { CompassActivity.startActivityCache(this, cache); } } private void menuShowHint() { final Geocache cache = getCurrentTargetCache(); if (cache != null) { cache.showHintToast(this); } } @Override public void showFilterMenu() { FilterUtils.openFilterActivity(this, mapOptions.filterContext, new SearchResult(caches.getVisibleCacheGeocodes()).getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB)); } @Override public boolean showSavedFilterList() { return FilterUtils.openFilterList(this, mapOptions.filterContext); } @Override public void refreshWithFilter(final GeocacheFilter filter) { mapOptions.filterContext.set(filter); refreshMapData(false); } private void changeMapSource(@NonNull final MapSource newSource) { final MapSource oldSource = Settings.getMapSource(); final boolean restartRequired = !MapProviderFactory.isSameActivity(oldSource, newSource); // Update MapSource in settings Settings.setMapSource(newSource); if (restartRequired) { mapRestart(); } else if (mapView != null) { // changeMapSource can be called by onCreate() switchTileLayer(newSource); } } private void changeLanguage(final String language) { Settings.setMapLanguage(language); mapRestart(); } /** * Restart the current activity with the default map source. */ private void mapRestart() { mapOptions.mapState = currentMapState(); finish(); mapOptions.startIntentWithoutTransition(this, Settings.getMapProvider().getMapClass()); } /** * Get the current map state from the map view if it exists or from the mapStateIntent field otherwise. * * @return the current map state as an array of int, or null if no map state is available */ private MapState currentMapState() { if (mapView == null) { return null; } final Geopoint mapCenter = mapView.getViewport().getCenter(); return new MapState(mapCenter.getCoords(), mapView.getMapZoomLevel(), followMyLocation, Settings.isShowCircles(), targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled); } private void switchTileLayer(final MapSource newSource) { final ITileLayer oldLayer = this.tileLayer; ITileLayer newLayer = null; mapSource = newSource; if (this.mapAttribution != null) { this.mapAttribution.setOnClickListener( new MapAttributionDisplayHandler(() -> this.mapSource.calculateMapAttribution(this))); } if (newSource instanceof AbstractMapsforgeMapSource) { newLayer = ((AbstractMapsforgeMapSource) newSource).createTileLayer(tileCache, this.mapView.getModel().mapViewPosition); } ActivityMixin.invalidateOptionsMenu(this); // Exchange layer if (newLayer != null) { mapView.setZoomLevelMax(newLayer.getZoomLevelMax()); mapView.setZoomLevelMin(newLayer.getZoomLevelMin()); // make sure map zoom level is within new zoom level boundaries final int currentZoomLevel = mapView.getMapZoomLevel(); if (currentZoomLevel < newLayer.getZoomLevelMin()) { mapView.setMapZoomLevel(newLayer.getZoomLevelMin()); } else if (currentZoomLevel > newLayer.getZoomLevelMax()) { mapView.setMapZoomLevel(newLayer.getZoomLevelMax()); } final Layers layers = this.mapView.getLayerManager().getLayers(); int index = 0; if (oldLayer != null) { index = layers.indexOf(oldLayer.getTileLayer()) + 1; } layers.add(index, newLayer.getTileLayer()); this.tileLayer = newLayer; this.renderThemeHelper.reapplyMapTheme(this.tileLayer, this.tileCache); this.tileLayer.onResume(); } else { this.tileLayer = null; } // Cleanup if (oldLayer != null) { this.mapView.getLayerManager().getLayers().remove(oldLayer.getTileLayer()); oldLayer.getTileLayer().onDestroy(); } tileCache.purge(); } private void resumeTileLayer() { if (this.tileLayer != null) { this.tileLayer.onResume(); } } private void pauseTileLayer() { if (this.tileLayer != null) { this.tileLayer.onPause(); } } private boolean tileLayerHasThemes() { if (tileLayer != null) { return tileLayer.hasThemes(); } return false; } private void resumeRoute(final boolean force) { if (null == individualRoute || force) { individualRoute = new IndividualRoute(this::setTarget); individualRoute.reloadRoute(routeLayer); } else { individualRoute.updateRoute(routeLayer); } } private void resumeTrack(final String key, final boolean preventReloading) { if (null == tracks && !preventReloading) { this.tracks = new Tracks(this.routeTrackUtils, this::setTrack); } else if (null != trackLayer && null != tracks) { trackLayer.updateRoute(key, tracks.getRoute(key)); } } @Override protected void onResume() { super.onResume(); Log.d("NewMap: onResume"); resumeTileLayer(); resumeRoute(false); if (tracks != null) { tracks.resumeAllTracks(this::resumeTrack); } mapView.getModel().mapViewPosition.addObserver(this); MapUtils.updateFilterBar(this, mapOptions.filterContext); } @Override protected void onStart() { super.onStart(); Log.d("NewMap: onStart"); initializeLayers(); } private void initializeLayers() { switchTileLayer(Settings.getMapSource()); // History Layer this.historyLayer = new HistoryLayer(trailHistory); this.mapView.getLayerManager().getLayers().add(this.historyLayer); // RouteLayer this.routeLayer = new RouteLayer(realRouteDistance -> { if (null != this.distanceView) { this.distanceView.setRouteDistance(realRouteDistance); } }); this.mapView.getLayerManager().getLayers().add(this.routeLayer); // TrackLayer this.trackLayer = new TrackLayer(); this.mapView.getLayerManager().getLayers().add(this.trackLayer); // NavigationLayer Geopoint navTarget = lastNavTarget; if (navTarget == null) { navTarget = mapOptions.coords; if (navTarget == null && StringUtils.isNotEmpty(mapOptions.geocode)) { final Viewport bounds = DataStore.getBounds(mapOptions.geocode); if (bounds != null) { navTarget = bounds.center; } } } this.navigationLayer = new NavigationLayer(navTarget, realDistance -> { if (null != this.distanceView) { this.distanceView.setRealDistance(realDistance); } }); this.mapView.getLayerManager().getLayers().add(this.navigationLayer); // GeoitemLayer GeoitemLayer.resetColors(); // TapHandler final TapHandlerLayer tapHandlerLayer = new TapHandlerLayer(this.mapHandlers.getTapHandler()); this.mapView.getLayerManager().getLayers().add(tapHandlerLayer); // Caches bundle if (mapOptions.searchResult != null) { this.caches = new CachesBundle(this, mapOptions.searchResult, this.mapView, this.mapHandlers); } else if (StringUtils.isNotEmpty(mapOptions.geocode)) { if (mapOptions.mapMode == MapMode.COORDS && mapOptions.coords != null) { this.caches = new CachesBundle(this, mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers, mapOptions.geocode); } else { this.caches = new CachesBundle(this, mapOptions.geocode, this.mapView, this.mapHandlers); } } else if (mapOptions.coords != null) { this.caches = new CachesBundle(this, mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers, null); } else { caches = new CachesBundle(this, this.mapView, this.mapHandlers); } // Stored enabled map caches.handleStoredLayers(this, mapOptions); // Live enabled map caches.handleLiveLayers(this, mapOptions); caches.setFilterContext(mapOptions.filterContext); // Position layer this.positionLayer = new PositionLayer(); this.mapView.getLayerManager().getLayers().add(positionLayer); //Distance view this.distanceView = new DistanceView(findViewById(R.id.distance1).getRootView(), navTarget, Settings.isBrouterShowBothDistances()); //Target view this.targetView = new TargetView((TextView) findViewById(R.id.target), (TextView) findViewById(R.id.targetSupersize), StringUtils.EMPTY, StringUtils.EMPTY); final Geocache target = getCurrentTargetCache(); if (target != null) { targetView.setTarget(target.getShortGeocode(), target.getName()); } // resume location access PermissionHandler.executeIfLocationPermissionGranted(this, new RestartLocationPermissionGrantedCallback(PermissionRequestContext.NewMap) { @Override public void executeAfter() { resumeDisposables.add(geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR)); } }); } @Override public void onPause() { Log.d("NewMap: onPause"); savePrefs(); pauseTileLayer(); mapView.getModel().mapViewPosition.removeObserver(this); super.onPause(); } @Override protected void onStop() { Log.d("NewMap: onStop"); waitDialog = null; terminateLayers(); super.onStop(); } private void terminateLayers() { this.resumeDisposables.clear(); this.caches.onDestroy(); this.caches = null; this.mapView.getLayerManager().getLayers().remove(this.positionLayer); this.positionLayer = null; this.mapView.getLayerManager().getLayers().remove(this.navigationLayer); this.navigationLayer = null; this.mapView.getLayerManager().getLayers().remove(this.routeLayer); this.routeLayer = null; this.mapView.getLayerManager().getLayers().remove(this.trackLayer); this.trackLayer = null; this.mapView.getLayerManager().getLayers().remove(this.historyLayer); this.historyLayer = null; if (this.tileLayer != null) { this.mapView.getLayerManager().getLayers().remove(this.tileLayer.getTileLayer()); this.tileLayer.getTileLayer().onDestroy(); this.tileLayer = null; } } /** * store caches, invoked by "store offline" menu item * * @param listIds the lists to store the caches in */ private void storeCaches(final Set<String> geocodes, final Set<Integer> listIds) { final int count = geocodes.size(); final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(count, this); waitDialog = new ProgressDialog(this); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setCancelMessage(loadDetailsHandler.disposeMessage()); waitDialog.setMax(count); waitDialog.setOnCancelListener(arg0 -> { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } } catch (final Exception e) { Log.e("CGeoMap.storeCaches.onCancel", e); } }); final float etaTime = count * 7.0f / 60.0f; final int roundedEta = Math.round(etaTime); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta, roundedEta)); } loadDetailsHandler.setStart(); waitDialog.show(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes, listIds); loadDetailsThread.start(); } @Override protected void onDestroy() { Log.d("NewMap: onDestroy"); this.tileCache.destroy(); this.mapView.getModel().mapViewPosition.destroy(); this.mapView.destroy(); ResourceBitmapCacheMonitor.release(); Routing.disconnect(ROUTING_SERVICE_KEY); if (this.mapAttribution != null) { this.mapAttribution.setOnClickListener(null); } super.onDestroy(); } @Override protected void onSaveInstanceState(@NonNull final Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle(STATE_ROUTETRACKUTILS, routeTrackUtils.getState()); Log.d("New map: onSaveInstanceState"); final MapState state = prepareMapState(); outState.putParcelable(BUNDLE_MAP_STATE, state); if (proximityNotification != null) { outState.putParcelable(BUNDLE_PROXIMITY_NOTIFICATION, proximityNotification); } if (individualRoute != null) { outState.putParcelable(BUNDLE_ROUTE, individualRoute); } } private MapState prepareMapState() { return new MapState(MapsforgeUtils.toGeopoint(mapView.getModel().mapViewPosition.getCenter()), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled); } private void centerMap(final Geopoint geopoint) { mapView.getModel().mapViewPosition.setCenter(new LatLong(geopoint.getLatitude(), geopoint.getLongitude())); } public Location getCoordinates() { final LatLong center = mapView.getModel().mapViewPosition.getCenter(); final Location loc = new Location("newmap"); loc.setLatitude(center.latitude); loc.setLongitude(center.longitude); return loc; } private void initMyLocationSwitchButton(final CheckBox locSwitch) { myLocSwitch = locSwitch; /* * TODO: Switch back to ImageSwitcher for animations? * myLocSwitch.setFactory(this); * myLocSwitch.setInAnimation(activity, android.R.anim.fade_in); * myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); */ myLocSwitch.setOnClickListener(new MyLocationListener(this)); switchMyLocationButton(); } // switch My Location button image private void switchMyLocationButton() { myLocSwitch.setChecked(followMyLocation); if (followMyLocation) { myLocationInMiddle(Sensors.getInstance().currentGeo()); } } public void showAddWaypoint(final LatLong tapLatLong) { if (Settings.isLongTapOnMapActivated()) { final Geocache cache = getCurrentTargetCache(); if (cache != null) { EditWaypointActivity.startActivityAddWaypoint(this, cache, new Geopoint(tapLatLong.latitude, tapLatLong.longitude)); } else { InternalConnector.interactiveCreateCache(this, new Geopoint(tapLatLong.latitude, tapLatLong.longitude), mapOptions.fromList, true); } } } // set my location listener private static class MyLocationListener implements View.OnClickListener { @NonNull private final WeakReference<NewMap> mapRef; MyLocationListener(@NonNull final NewMap map) { mapRef = new WeakReference<>(map); } private void onFollowMyLocationClicked() { followMyLocation = !followMyLocation; final NewMap map = mapRef.get(); if (map != null) { map.switchMyLocationButton(); } } @Override public void onClick(final View view) { onFollowMyLocationClicked(); } } // Set center of map to my location if appropriate. private void myLocationInMiddle(final GeoData geo) { if (followMyLocation) { centerMap(geo.getCoords()); } } private static final class DisplayHandler extends Handler { @NonNull private final WeakReference<NewMap> mapRef; DisplayHandler(@NonNull final NewMap map) { this.mapRef = new WeakReference<>(map); } @Override public void handleMessage(final Message msg) { final NewMap map = mapRef.get(); if (map == null) { return; } final int what = msg.what; switch (what) { case UPDATE_TITLE: map.setTitle(); map.setSubtitle(); break; default: break; } } } private void setTitle() { final String title = calculateTitle(); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(MapUtils.getColoredValue(title)); } } @NonNull private String calculateTitle() { if (mapOptions.isLiveEnabled) { return res.getString(R.string.map_live); } if (mapOptions.mapMode == MapMode.SINGLE) { final Geocache cache = getSingleModeCache(); if (cache != null) { return cache.getName(); } } return StringUtils.defaultIfEmpty(mapOptions.title, res.getString(R.string.map_offline)); } private void setSubtitle() { final String subtitle = calculateSubtitle(); if (StringUtils.isEmpty(subtitle)) { return; } final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setSubtitle(MapUtils.getColoredValue(subtitle)); } } @NonNull private String calculateSubtitle() { if (!mapOptions.isLiveEnabled && mapOptions.mapMode == MapMode.SINGLE) { final Geocache cache = getSingleModeCache(); if (cache != null) { return Formatter.formatMapSubtitle(cache); } return ""; } // count caches in the sub title final int visible = countVisibleCaches(); final int total = countTotalCaches(); final StringBuilder subtitle = new StringBuilder(); if (visible != total && Settings.isDebug()) { subtitle.append(visible).append('/').append(res.getQuantityString(R.plurals.cache_counts, total, total)); } else { subtitle.append(res.getQuantityString(R.plurals.cache_counts, visible, visible)); } return subtitle.toString(); } private void switchCircles() { caches.switchCircles(); } private int countVisibleCaches() { return caches != null ? caches.getVisibleCachesCount() : 0; } private int countTotalCaches() { return caches != null ? caches.getCachesCount() : 0; } /** * Updates the progress. */ private static final class ShowProgressHandler extends Handler { private int counter = 0; @NonNull private final WeakReference<NewMap> mapRef; ShowProgressHandler(@NonNull final NewMap map) { this.mapRef = new WeakReference<>(map); } @Override public void handleMessage(final Message msg) { final int what = msg.what; if (what == HIDE_PROGRESS) { if (--counter == 0) { showProgress(false); } } else if (what == SHOW_PROGRESS) { showProgress(true); counter++; } } private void showProgress(final boolean show) { final NewMap map = mapRef.get(); if (map == null) { return; } map.spinner.setVisibility(show ? View.VISIBLE : View.GONE); } } private static final class LoadDetailsHandler extends DisposableHandler { private final int detailTotal; private int detailProgress; private long detailProgressTime; private final WeakReference<NewMap> mapRef; LoadDetailsHandler(final int detailTotal, final NewMap map) { super(); this.detailTotal = detailTotal; this.detailProgress = 0; this.mapRef = new WeakReference<>(map); } public void setStart() { detailProgressTime = System.currentTimeMillis(); } @Override public void handleRegularMessage(final Message msg) { final NewMap map = mapRef.get(); if (map == null) { return; } if (msg.what == UPDATE_PROGRESS) { if (detailProgress < detailTotal) { detailProgress++; } if (map.waitDialog != null) { final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); final int secondsRemaining; if (detailProgress > 0) { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress; } else { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed; } map.waitDialog.setProgress(detailProgress); if (secondsRemaining < 40) { map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getString(R.string.caches_eta_ltm)); } else { final int minsRemaining = secondsRemaining / 60; map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining)); } } } else if (msg.what == FINISHED_LOADING_DETAILS && map.waitDialog != null) { map.waitDialog.dismiss(); map.waitDialog.setOnCancelListener(null); } } @Override public void handleDispose() { final NewMap map = mapRef.get(); if (map == null) { return; } if (map.loadDetailsThread != null) { map.loadDetailsThread.stopIt(); } } } // class: update location private static class UpdateLoc extends GeoDirHandler { // use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible // minimum time in milliseconds between position overlay updates private static final long MIN_UPDATE_INTERVAL = 500; // minimum change of heading in grad for position overlay update private static final float MIN_HEADING_DELTA = 15f; // minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update private static final float MIN_LOCATION_DELTA = 0.01f; @NonNull Location currentLocation = Sensors.getInstance().currentGeo(); float currentHeading; private long timeLastPositionOverlayCalculation = 0; private long timeLastDistanceCheck = 0; /** * weak reference to the outer class */ @NonNull private final WeakReference<NewMap> mapRef; UpdateLoc(@NonNull final NewMap map) { mapRef = new WeakReference<>(map); } @Override public void updateGeoDir(@NonNull final GeoData geo, final float dir) { currentLocation = geo; currentHeading = AngleUtils.getDirectionNow(dir); repaintPositionOverlay(); } @NonNull public Location getCurrentLocation() { return currentLocation; } /** * Repaint position overlay but only with a max frequency and if position or heading changes sufficiently. */ void repaintPositionOverlay() { final long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis > (timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL)) { timeLastPositionOverlayCalculation = currentTimeMillis; try { final NewMap map = mapRef.get(); if (map != null) { final boolean needsRepaintForDistanceOrAccuracy = needsRepaintForDistanceOrAccuracy(); final boolean needsRepaintForHeading = needsRepaintForHeading(); if (needsRepaintForDistanceOrAccuracy && NewMap.followMyLocation) { map.centerMap(new Geopoint(currentLocation)); } if (needsRepaintForDistanceOrAccuracy || needsRepaintForHeading) { map.historyLayer.setCoordinates(currentLocation); map.navigationLayer.setCoordinates(currentLocation); map.distanceView.setCoordinates(currentLocation); map.distanceView.showRouteDistance(); map.positionLayer.setCoordinates(currentLocation); map.positionLayer.setHeading(currentHeading); map.positionLayer.requestRedraw(); if (null != map.proximityNotification && (timeLastDistanceCheck == 0 || currentTimeMillis > (timeLastDistanceCheck + MIN_UPDATE_INTERVAL))) { map.proximityNotification.checkDistance(map.caches.getClosestDistanceInM(new Geopoint(currentLocation.getLatitude(), currentLocation.getLongitude()))); timeLastDistanceCheck = System.currentTimeMillis(); } } } } catch (final RuntimeException e) { Log.w("Failed to update location", e); } } } boolean needsRepaintForHeading() { final NewMap map = mapRef.get(); if (map == null) { return false; } return Math.abs(AngleUtils.difference(currentHeading, map.positionLayer.getHeading())) > MIN_HEADING_DELTA; } boolean needsRepaintForDistanceOrAccuracy() { final NewMap map = mapRef.get(); if (map == null) { return false; } final Location lastLocation = map.getCoordinates(); float dist = Float.MAX_VALUE; if (lastLocation != null) { if (lastLocation.getAccuracy() != currentLocation.getAccuracy()) { return true; } dist = currentLocation.distanceTo(lastLocation); } final float[] mapDimension = new float[1]; if (map.mapView.getWidth() < map.mapView.getHeight()) { final double span = map.mapView.getLongitudeSpan() / 1e6; Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension); } else { final double span = map.mapView.getLatitudeSpan() / 1e6; Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension); } return dist > (mapDimension[0] * MIN_LOCATION_DELTA); } } private static class DragHandler implements OnMapDragListener { @NonNull private final WeakReference<NewMap> mapRef; DragHandler(@NonNull final NewMap parent) { mapRef = new WeakReference<>(parent); } @Override public void onDrag() { final NewMap map = mapRef.get(); if (map != null && NewMap.followMyLocation) { NewMap.followMyLocation = false; map.switchMyLocationButton(); } } } public void showSelection(@NonNull final List<GeoitemRef> items, final boolean longPressMode) { if (items.isEmpty()) { return; } if (items.size() == 1) { if (longPressMode) { if (Settings.isLongTapOnMapActivated()) { toggleRouteItem(items.get(0)); } } else { showPopup(items.get(0)); } return; } try { final ArrayList<GeoitemRef> sorted = new ArrayList<>(items); Collections.sort(sorted, GeoitemRef.NAME_COMPARATOR); final ListAdapter adapter = new ArrayAdapter<GeoitemRef>(this, R.layout.cacheslist_item_select, sorted) { @NonNull @Override public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) { return GeoItemSelectorUtils.createGeoItemView(NewMap.this, getItem(position), GeoItemSelectorUtils.getOrCreateView(NewMap.this, convertView, parent)); } }; final AlertDialog dialog = Dialogs.newBuilder(this) .setTitle(res.getString(R.string.map_select_multiple_items)) .setAdapter(adapter, new SelectionClickListener(sorted, longPressMode)) .create(); dialog.setCanceledOnTouchOutside(true); dialog.show(); } catch (final NotFoundException e) { Log.e("NewMap.showSelection", e); } } private class SelectionClickListener implements DialogInterface.OnClickListener { @NonNull private final List<GeoitemRef> items; private final boolean longPressMode; SelectionClickListener(@NonNull final List<GeoitemRef> items, final boolean longPressMode) { this.items = items; this.longPressMode = longPressMode; } @Override public void onClick(final DialogInterface dialog, final int which) { if (which >= 0 && which < items.size()) { final GeoitemRef item = items.get(which); if (longPressMode) { if (Settings.isLongTapOnMapActivated()) { toggleRouteItem(item); } } else { showPopup(item); } } } } private void showPopup(final GeoitemRef item) { if (item == null || StringUtils.isEmpty(item.getGeocode())) { return; } try { if (item.getType() == CoordinatesType.CACHE) { final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB); if (cache != null) { popupGeocodes.add(cache.getGeocode()); CachePopup.startActivityAllowTarget(this, cache.getGeocode()); return; } return; } if (item.getType() == CoordinatesType.WAYPOINT && item.getId() >= 0) { popupGeocodes.add(item.getGeocode()); WaypointPopup.startActivityAllowTarget(this, item.getId(), item.getGeocode()); } } catch (final NotFoundException e) { Log.e("NewMap.showPopup", e); } } private void toggleRouteItem(final GeoitemRef item) { if (item == null || StringUtils.isEmpty(item.getGeocode())) { return; } if (individualRoute == null) { individualRoute = new IndividualRoute(this::setTarget); } individualRoute.toggleItem(this, new RouteItem(item), routeLayer); distanceView.showRouteDistance(); ActivityMixin.invalidateOptionsMenu(this); } @Nullable private Geocache getSingleModeCache() { if (StringUtils.isNotBlank(mapOptions.geocode)) { return DataStore.loadCache(mapOptions.geocode, LoadFlags.LOAD_CACHE_OR_DB); } return null; } @Nullable private Geocache getCurrentTargetCache() { if (StringUtils.isNotBlank(targetGeocode)) { return DataStore.loadCache(targetGeocode, LoadFlags.LOAD_CACHE_OR_DB); } return null; } private void setTarget(final Geopoint coords, final String geocode) { lastNavTarget = coords; if (StringUtils.isNotBlank(geocode)) { targetGeocode = geocode; final Geocache target = getCurrentTargetCache(); targetView.setTarget(targetGeocode, target != null ? target.getName() : StringUtils.EMPTY); if (lastNavTarget == null && target != null) { lastNavTarget = target.getCoords(); } } else { targetGeocode = null; targetView.setTarget(null, null); } if (navigationLayer != null) { navigationLayer.setDestination(lastNavTarget); navigationLayer.requestRedraw(); } if (distanceView != null) { distanceView.setDestination(lastNavTarget); distanceView.setCoordinates(geoDirUpdate.getCurrentLocation()); } ActivityMixin.invalidateOptionsMenu(this); } private void savePrefs() { Settings.setMapZoom(this.mapMode, mapView.getMapZoomLevel()); Settings.setMapCenter(new MapsforgeGeoPoint(mapView.getModel().mapViewPosition.getCenter())); } /** * Thread to store the caches in the viewport. Started by Activity. */ private class LoadDetails extends Thread { private final DisposableHandler handler; private final Collection<String> geocodes; private final Set<Integer> listIds; LoadDetails(final DisposableHandler handler, final Collection<String> geocodes, final Set<Integer> listIds) { this.handler = handler; this.geocodes = geocodes; this.listIds = listIds; } public void stopIt() { handler.dispose(); } @Override public void run() { if (CollectionUtils.isEmpty(geocodes)) { return; } for (final String geocode : geocodes) { try { if (handler.isDisposed()) { break; } Geocache.storeCache(null, geocode, listIds, false, handler); } catch (final Exception e) { Log.e("CGeoMap.LoadDetails.run", e); } finally { handler.sendEmptyMessage(UPDATE_PROGRESS); } } // we're done, but map might even have been closed. if (caches != null) { caches.invalidate(geocodes); } invalidateOptionsMenuCompatible(); handler.sendEmptyMessage(FINISHED_LOADING_DETAILS); } } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == AbstractDialogFragment.REQUEST_CODE_TARGET_INFO) { if (resultCode == AbstractDialogFragment.RESULT_CODE_SET_TARGET) { final TargetInfo targetInfo = data.getExtras().getParcelable(Intents.EXTRA_TARGET_INFO); if (targetInfo != null) { if (Settings.isAutotargetIndividualRoute()) { Settings.setAutotargetIndividualRoute(false); Toast.makeText(this, R.string.map_disable_autotarget_individual_route, Toast.LENGTH_SHORT).show(); } setTarget(targetInfo.coords, targetInfo.geocode); } } final List<String> changedGeocodes = new ArrayList<>(); String geocode = popupGeocodes.poll(); while (geocode != null) { changedGeocodes.add(geocode); geocode = popupGeocodes.poll(); } if (caches != null) { caches.invalidate(changedGeocodes); } } if (requestCode == GeocacheFilterActivity.REQUEST_SELECT_FILTER && resultCode == Activity.RESULT_OK) { mapOptions.filterContext = data.getParcelableExtra(EXTRA_FILTER_CONTEXT); refreshMapData(false); } this.routeTrackUtils.onActivityResult(requestCode, resultCode, data); } private void setTrack(final String key, final Route route) { tracks.setRoute(key, route); resumeTrack(key, null == route); } private void reloadIndividualRoute() { if (null != routeLayer) { individualRoute.reloadRoute(routeLayer); } else { // try again in 0.25 second new Handler(Looper.getMainLooper()).postDelayed(this::reloadIndividualRoute, 250); } } private Boolean isTargetSet() { return StringUtils.isNotBlank(targetGeocode) && null != lastNavTarget; } private static class ResourceBitmapCacheMonitor { private static int refCount = 0; static synchronized void addRef() { refCount++; Log.d("ResourceBitmapCacheMonitor.addRef"); } static synchronized void release() { if (refCount > 0) { refCount--; Log.d("ResourceBitmapCacheMonitor.release"); if (refCount == 0) { Log.d("ResourceBitmapCacheMonitor.clearResourceBitmaps"); AndroidResourceBitmap.clearResourceBitmaps(); } } } } public boolean getLastCompactIconMode() { return lastCompactIconMode; } public boolean checkCompactIconMode(final int overlayId, final int newCount) { boolean newCompactIconMode = lastCompactIconMode; if (null != caches) { newCompactIconMode = CompactIconModeUtils.forceCompactIconMode(caches.getVisibleCachesCount(overlayId, newCount)); if (lastCompactIconMode != newCompactIconMode) { lastCompactIconMode = newCompactIconMode; // @todo Exchanging & redrawing the icons would be sufficient, do not have to invalidate everything! caches.invalidateAll(overlayId); // redraw all icons except for the given overlay } } return newCompactIconMode; } // get notified for viewport changes (zoom/pan) public void onChange() { final Viewport newViewport = mapView.getViewport(); if (!newViewport.equals(lastViewport)) { lastViewport = newViewport; checkCompactIconMode(NO_OVERLAY_ID, 0); } } public static class MapAttributionDisplayHandler implements View.OnClickListener { private Supplier<ImmutablePair<String, Boolean>> attributionSupplier; private ImmutablePair<String, Boolean> attributionPair; public MapAttributionDisplayHandler(final Supplier<ImmutablePair<String, Boolean>> attributionSupplier) { this.attributionSupplier = attributionSupplier; } @Override public void onClick(final View v) { if (this.attributionPair == null) { this.attributionPair = attributionSupplier.get(); if (this.attributionPair == null || this.attributionPair.left == null) { this.attributionPair = new ImmutablePair<>("---", false); } this.attributionSupplier = null; //prevent possible memory leaks } displayMapAttribution(v.getContext(), this.attributionPair.left, this.attributionPair.right); } } private static void displayMapAttribution(final Context ctx, final String attribution, final boolean linkify) { //create text message CharSequence message = HtmlCompat.fromHtml(attribution, HtmlCompat.FROM_HTML_MODE_LEGACY); if (linkify) { final SpannableString s = new SpannableString(message); Linkify.addLinks(s, Linkify.ALL); message = s; } final AlertDialog alertDialog = Dialogs.newBuilder(ctx) .setTitle(ctx.getString(R.string.map_source_attribution_dialog_title)) .setCancelable(true) .setMessage(message) .setPositiveButton(android.R.string.ok, (dialog, pos) -> dialog.dismiss()) .create(); alertDialog.show(); // Make the URLs in TextView clickable. Must be called after show() // Note: we do NOT use the "setView()" option of AlertDialog because this screws up the layout ((TextView) alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); } }
fix #12972: scale scale bar together with map user scale
main/src/cgeo/geocaching/maps/mapsforge/v6/NewMap.java
fix #12972: scale scale bar together with map user scale
Java
apache-2.0
d114d43b6bcc50c522dee5d20f36d1cb3ca74335
0
TU-Berlin/mathosphere,TU-Berlin/mathosphere
package com.formulasearchengine.mathosphere.basex; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.InputStream; import java.util.*; public class TexQueryGenerator { private String LaTeXMLURL = "http://drmf-latexml.wmflabs.org"; private Map ob = new LinkedHashMap(); private List<NameValuePair> params; public List<NameValuePair> getParams () { if ( params == null ){ params = new ArrayList<>(); params.add( new BasicNameValuePair( "format", "xhtml" ) ); params.add( new BasicNameValuePair( "whatsin", "math" ) ); params.add( new BasicNameValuePair( "whatsout", "math" ) ); params.add( new BasicNameValuePair( "cmml", "" ) ); params.add( new BasicNameValuePair( "nodefaultresources", "" ) ); params.add( new BasicNameValuePair( "preload", "LaTeX.pool" ) ); params.add( new BasicNameValuePair( "preload", "article.cls" ) ); params.add( new BasicNameValuePair( "preload", "amsmath.sty" ) ); params.add( new BasicNameValuePair( "preload", "amsthm.sty" ) ); params.add( new BasicNameValuePair( "preload", "amstext.sty" ) ); params.add( new BasicNameValuePair( "preload", "amssymb.sty" ) ); params.add( new BasicNameValuePair( "preload", "eucal.sty" ) ); params.add( new BasicNameValuePair( "preload", "[dvipsnames]xcolor.sty" ) ); params.add( new BasicNameValuePair( "preload", "url.sty" ) ); params.add( new BasicNameValuePair( "preload", "hyperref.sty" ) ); params.add( new BasicNameValuePair( "preload", "mws.sty" ) ); params.add( new BasicNameValuePair( "preload", "texvc" ) ); } return params; } public void setParams (List<NameValuePair> params) { this.params = params; } public String getLaTeXMLURL () { return LaTeXMLURL; } public Map getOb () { return ob; } public void setLaTeXMLURL (String laTeXMLURL) { LaTeXMLURL = laTeXMLURL; } public String request (String tex) throws IOException, IllegalStateException { HttpPost httppost = new HttpPost( LaTeXMLURL ); CloseableHttpClient httpClient = HttpClients.createDefault(); List<NameValuePair> p = getParams(); p.add( new BasicNameValuePair( "tex", tex.trim() ) ); HttpResponse response; httppost.setEntity( new UrlEncodedFormEntity( p, "UTF-8" ) ); response = httpClient.execute( httppost ); HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); ob = new ObjectMapper().readValue( instream, Map.class ); if ( ob.get( "status_code" ) == null || ob.get( "result" ) == null ) { throw new IOException( "Unable to process MathML conversion server response to Tex request."); } if ( Integer.parseInt( ob.get( "status_code" ).toString() ) > 1 ) { throw new IOException( "Tex request to MathML conversion server produced failed response.", new IOException( ob.get( "result" ).toString())); } return ob.get( "result" ).toString(); } }
basex/src/main/java/com/formulasearchengine/mathosphere/basex/TexQueryGenerator.java
package com.formulasearchengine.mathosphere.basex; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.InputStream; import java.util.*; public class TexQueryGenerator { private String LaTeXMLURL = "http://gw125.iu.xsede.org:8888"; private Map ob = new LinkedHashMap(); private List<NameValuePair> params; public List<NameValuePair> getParams () { if ( params == null ){ params = new ArrayList<>(); params.add( new BasicNameValuePair( "format", "xhtml" ) ); params.add( new BasicNameValuePair( "whatsin", "math" ) ); params.add( new BasicNameValuePair( "whatsout", "math" ) ); params.add( new BasicNameValuePair( "cmml", "" ) ); params.add( new BasicNameValuePair( "nodefaultresources", "" ) ); params.add( new BasicNameValuePair( "preload", "LaTeX.pool" ) ); params.add( new BasicNameValuePair( "preload", "article.cls" ) ); params.add( new BasicNameValuePair( "preload", "amsmath.sty" ) ); params.add( new BasicNameValuePair( "preload", "amsthm.sty" ) ); params.add( new BasicNameValuePair( "preload", "amstext.sty" ) ); params.add( new BasicNameValuePair( "preload", "amssymb.sty" ) ); params.add( new BasicNameValuePair( "preload", "eucal.sty" ) ); params.add( new BasicNameValuePair( "preload", "[dvipsnames]xcolor.sty" ) ); params.add( new BasicNameValuePair( "preload", "url.sty" ) ); params.add( new BasicNameValuePair( "preload", "hyperref.sty" ) ); params.add( new BasicNameValuePair( "preload", "mws.sty" ) ); params.add( new BasicNameValuePair( "preload", "texvc" ) ); } return params; } public void setParams (List<NameValuePair> params) { this.params = params; } public String getLaTeXMLURL () { return LaTeXMLURL; } public Map getOb () { return ob; } public void setLaTeXMLURL (String laTeXMLURL) { LaTeXMLURL = laTeXMLURL; } public String request (String tex) throws IOException, IllegalStateException { HttpPost httppost = new HttpPost( LaTeXMLURL ); CloseableHttpClient httpClient = HttpClients.createDefault(); List<NameValuePair> p = getParams(); p.add( new BasicNameValuePair( "tex", tex.trim() ) ); HttpResponse response; httppost.setEntity( new UrlEncodedFormEntity( p, "UTF-8" ) ); response = httpClient.execute( httppost ); HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); ob = new ObjectMapper().readValue( instream, Map.class ); if ( ob.get( "status_code" ) == null || ob.get( "result" ) == null ) { throw new IOException( "Unable to process MathML conversion server response to Tex request."); } if ( Integer.parseInt( ob.get( "status_code" ).toString() ) > 1 ) { throw new IOException( "Tex request to MathML conversion server produced failed response.", new IOException( ob.get( "result" ).toString())); } return ob.get( "result" ).toString(); } }
Update reference to LaTeXML Server
basex/src/main/java/com/formulasearchengine/mathosphere/basex/TexQueryGenerator.java
Update reference to LaTeXML Server
Java
apache-2.0
2c0038c053b212017df7ee70dbf397ee81524884
0
mkarneim/luamod
package net.wizardsoflua.lua.module.events; import static java.util.Objects.requireNonNull; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.Event; import net.sandius.rembulan.runtime.LuaFunction; import net.sandius.rembulan.runtime.SchedulingContext; import net.wizardsoflua.event.CustomLuaEvent; import net.wizardsoflua.lua.classes.LuaClassLoader; import net.wizardsoflua.lua.classes.eventqueue.EventQueue; import net.wizardsoflua.lua.classes.eventsubscription.EventSubscription; import net.wizardsoflua.lua.data.Data; public class EventHandlers implements SchedulingContext { public interface Context { long getCurrentTime(); void call(LuaFunction function, Object... args); } private final Multimap<String, EventQueue> queues = HashMultimap.create(); private final EventQueue.Context eventQueueContext = new EventQueue.Context() { @Override public void disconnect(EventQueue eventQueue) { EventHandlers.this.disconnect(eventQueue); } @Override public long getCurrentTime() { return context.getCurrentTime(); } }; private final Multimap<String, EventSubscription> subscriptions = HashMultimap.create(); private final EventSubscription.Context subscriptionContext = new EventSubscription.Context() { @Override public void unsubscribe(EventSubscription subscription) { for (String eventName : subscription.getEventNames()) { subscriptions.remove(eventName, subscription); } } }; private final LuaClassLoader classLoader; private final Context context; public EventHandlers(LuaClassLoader classLoader, Context context) { this.classLoader = requireNonNull(classLoader, "classLoader == null!"); this.context = requireNonNull(context, "context == null!"); } /** * @return the value of {@link #subscriptions} */ public Multimap<String, EventSubscription> getSubscriptions() { return subscriptions; } public EventQueue connect(Iterable<String> eventNames) { EventQueue result = new EventQueue(eventNames, eventQueueContext); for (String name : eventNames) { queues.put(name, result); } return result; } public EventSubscription subscribe(Iterable<String> eventNames, LuaFunction eventHandler) { return subscribe(new EventSubscription(eventNames, eventHandler, subscriptionContext)); } private EventSubscription subscribe(EventSubscription subscription) { for (String eventName : subscription.getEventNames()) { subscriptions.put(eventName, subscription); } return subscription; } public void disconnect(EventQueue queue) { for (String name : queue.getNames()) { queues.remove(name, queue); } } @Override public void registerTicks(int ticks) {} @Override public boolean shouldPause() { if (queues.isEmpty()) { // no queues -> nothing to wait for, so keep running return false; } long now = context.getCurrentTime(); for (EventQueue queue : queues.values()) { long waitUntil = queue.getWaitUntil(); if (now <= waitUntil) { // we are still waiting for a message if (!queue.isEmpty()) { // but we have received one -> wake up return false; } // but we havn't yet received one -> pause return true; } } return false; } public void fire(String eventName, Object dataLuaObj) { Data data = Data.createData(dataLuaObj, classLoader); MinecraftForge.EVENT_BUS.post(new CustomLuaEvent(eventName, data)); } public void onEvent(String eventName, Event event) { if (event.isCanceled()) { return; } for (EventSubscription subscription : subscriptions.get(eventName)) { LuaFunction eventHandler = subscription.getEventHandler(); Object luaEvent = classLoader.getConverters().toLua(event); context.call(eventHandler, luaEvent); if (event.isCanceled()) { return; } } for (EventQueue eventQueue : queues.get(eventName)) { eventQueue.add(event); } } }
src/main/java/net/wizardsoflua/lua/module/events/EventHandlers.java
package net.wizardsoflua.lua.module.events; import static java.util.Objects.requireNonNull; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.Event; import net.sandius.rembulan.runtime.LuaFunction; import net.sandius.rembulan.runtime.SchedulingContext; import net.wizardsoflua.event.CustomLuaEvent; import net.wizardsoflua.lua.classes.LuaClassLoader; import net.wizardsoflua.lua.classes.eventqueue.EventQueue; import net.wizardsoflua.lua.classes.eventsubscription.EventSubscription; import net.wizardsoflua.lua.data.Data; public class EventHandlers implements SchedulingContext { public interface Context { long getCurrentTime(); void call(LuaFunction function, Object... args); } private final Multimap<String, EventQueue> queues = HashMultimap.create(); private final EventQueue.Context eventQueueContext = new EventQueue.Context() { @Override public void disconnect(EventQueue eventQueue) { EventHandlers.this.disconnect(eventQueue); } @Override public long getCurrentTime() { return context.getCurrentTime(); } }; private final Multimap<String, EventSubscription> subscriptions = HashMultimap.create(); private final EventSubscription.Context subscriptionContext = new EventSubscription.Context() { @Override public void unsubscribe(EventSubscription subscription) { for (String eventName : subscription.getEventNames()) { subscriptions.remove(eventName, subscription); } } }; private final LuaClassLoader classLoader; private final Context context; public EventHandlers(LuaClassLoader classLoader, Context context) { this.classLoader = requireNonNull(classLoader, "classLoader == null!"); this.context = requireNonNull(context, "context == null!"); } /** * @return the value of {@link #subscriptions} */ public Multimap<String, EventSubscription> getSubscriptions() { return subscriptions; } public EventQueue connect(Iterable<String> eventNames) { EventQueue result = new EventQueue(eventNames, eventQueueContext); for (String name : eventNames) { queues.put(name, result); } return result; } public EventSubscription subscribe(Iterable<String> eventNames, LuaFunction eventHandler) { return subscribe(new EventSubscription(eventNames, eventHandler, subscriptionContext)); } private EventSubscription subscribe(EventSubscription subscription) { for (String eventName : subscription.getEventNames()) { subscriptions.put(eventName, subscription); } return subscription; } public void disconnect(EventQueue queue) { for (String name : queue.getNames()) { queues.remove(name, queue); } } @Override public void registerTicks(int ticks) {} @Override public boolean shouldPause() { if (queues.isEmpty()) { // no queues -> nothing to wait for, so keep running return false; } long now = context.getCurrentTime(); for (EventQueue queue : queues.values()) { long waitUntil = queue.getWaitUntil(); if (now <= waitUntil) { // we are still waiting for a message if (!queue.isEmpty()) { // but we have received one -> wake up return false; } // but we havn't yet received one -> pause return true; } } return false; } public void fire(String eventName, Object dataLuaObj) { Data data = Data.createData(dataLuaObj, classLoader); MinecraftForge.EVENT_BUS.post(new CustomLuaEvent(eventName, data)); } public void onEvent(String eventName, Event event) { for (EventSubscription subscription : subscriptions.get(eventName)) { if (event.isCanceled()) { return; } LuaFunction eventHandler = subscription.getEventHandler(); Object luaEvent = classLoader.getConverters().toLua(event); context.call(eventHandler, luaEvent); } for (EventQueue eventQueue : queues.get(eventName)) { if (event.isCanceled()) { return; } eventQueue.add(event); } } }
Because events are not canceled when adding them to an event queue there is no need to check for that
src/main/java/net/wizardsoflua/lua/module/events/EventHandlers.java
Because events are not canceled when adding them to an event queue there is no need to check for that
Java
apache-2.0
d2360429c18bc9744ee3881182ae859fbcdc4c46
0
cobbzilla/cobbzilla-utils,cobbzilla/cobbzilla-utils,cobbzilla/cobbzilla-utils,cobbzilla/cobbzilla-utils,cobbzilla/cobbzilla-utils
package org.cobbzilla.util.http; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import org.apache.commons.exec.CommandLine; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.cobbzilla.util.collection.NameAndValue; import org.cobbzilla.util.string.StringUtil; import org.cobbzilla.util.system.CommandResult; import org.cobbzilla.util.system.CommandShell; import org.cobbzilla.util.system.Sleep; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; import static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.http.HttpHeaders.*; import static org.cobbzilla.util.daemon.ZillaRuntime.*; import static org.cobbzilla.util.http.HttpContentTypes.MULTIPART_FORM_DATA; import static org.cobbzilla.util.http.HttpContentTypes.contentType; import static org.cobbzilla.util.http.HttpMethods.*; import static org.cobbzilla.util.http.HttpStatusCodes.NO_CONTENT; import static org.cobbzilla.util.http.URIUtil.getFileExt; import static org.cobbzilla.util.io.FileUtil.getDefaultTempDir; import static org.cobbzilla.util.security.CryptStream.BUFFER_SIZE; import static org.cobbzilla.util.string.StringUtil.CRLF; import static org.cobbzilla.util.system.Sleep.sleep; import static org.cobbzilla.util.time.TimeUtil.DATE_FORMAT_LAST_MODIFIED; @Slf4j public class HttpUtil { public static final String CHUNKED_ENCODING = "chunked"; public static Map<String, String> queryParams(URL url) throws UnsupportedEncodingException { return queryParams(url, StringUtil.UTF8); } // from: http://stackoverflow.com/a/13592567 public static Map<String, String> queryParams(URL url, String encoding) throws UnsupportedEncodingException { final Map<String, String> query_pairs = new LinkedHashMap<>(); final String query = url.getQuery(); final String[] pairs = query.split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); query_pairs.put(URLDecoder.decode(pair.substring(0, idx), encoding), URLDecoder.decode(pair.substring(idx + 1), encoding)); } return query_pairs; } public static InputStream getUrlInputStream(String url) throws IOException { return get(url); } public static InputStream get (String urlString) throws IOException { return get(urlString, null); } public static InputStream get (String urlString, long connectTimeout) throws IOException { return get(urlString, null, null, connectTimeout); } public static InputStream get (String urlString, Map<String, String> headers) throws IOException { return get(urlString, headers, null); } public static InputStream get (String urlString, Map<String, String> headers, Map<String, String> headers2) throws IOException { return get(urlString, headers, headers2, null); } public static InputStream get (String urlString, Map<String, String> headers, Map<String, String> headers2, Long connectTimeout) throws IOException { final URL url = new URL(urlString); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (connectTimeout != null) urlConnection.setConnectTimeout(connectTimeout.intValue()); if (headers != null) addHeaders(urlConnection, headers); if (headers2 != null) addHeaders(urlConnection, headers2); return urlConnection.getInputStream(); } public static InputStream post (String urlString, InputStream data, String multipartFileName, Map<String, String> headers, Map<String, String> headers2) throws IOException { return upload(urlString, POST, multipartFileName, data, headers, headers2); } public static InputStream put (String urlString, InputStream data, String multipartFileName, Map<String, String> headers, Map<String, String> headers2) throws IOException { return upload(urlString, PUT, multipartFileName, data, headers, headers2); } public static InputStream upload (String urlString, String method, String multipartFileName, InputStream data, Map<String, String> headers, Map<String, String> headers2) throws IOException { final URL url = new URL(urlString); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); if (headers != null) addHeaders(urlConnection, headers); if (headers2 != null) addHeaders(urlConnection, headers2); if (data != null) { urlConnection.setDoOutput(true); OutputStream upload = null; try { if (multipartFileName != null) { final String boundary = randomAlphanumeric(10)+"_"+now(); urlConnection.setRequestProperty(CONTENT_TYPE, MULTIPART_FORM_DATA+"; boundary="+boundary); urlConnection.setRequestProperty(TRANSFER_ENCODING, CHUNKED_ENCODING); urlConnection.setChunkedStreamingMode(4096); final HttpEntity entity = MultipartEntityBuilder.create() .setBoundary(boundary) .setLaxMode() .addBinaryBody(multipartFileName, data, ContentType.APPLICATION_OCTET_STREAM, multipartFileName) .build(); upload = urlConnection.getOutputStream(); entity.writeTo(upload); } else { upload = urlConnection.getOutputStream(); IOUtils.copyLarge(data, upload); } } finally { if (upload != null) upload.close(); } } return urlConnection.getInputStream(); } public static void addHeaders(HttpURLConnection urlConnection, Map<String, String> headers) { for (Map.Entry<String, String> h : headers.entrySet()) { urlConnection.setRequestProperty(h.getKey(), h.getValue()); } } public static HttpResponseBean upload (String url, File file, Map<String, String> headers) throws IOException { @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost method = new HttpPost(url); final FileBody fileBody = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", fileBody); method.setEntity(builder.build()); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { method.addHeader(new BasicHeader(header.getKey(), header.getValue())); } } @Cleanup final CloseableHttpResponse response = client.execute(method); final HttpResponseBean responseBean = new HttpResponseBean() .setEntityBytes(EntityUtils.toByteArray(response.getEntity())) .setHttpHeaders(response.getAllHeaders()) .setStatus(response.getStatusLine().getStatusCode()); return responseBean; } public static final int DEFAULT_RETRIES = 3; public static File url2file (String url) throws IOException { return url2file(url, null, DEFAULT_RETRIES); } public static File url2file (String url, String file) throws IOException { return url2file(url, file == null ? null : new File(file), DEFAULT_RETRIES); } public static File url2file (String url, File file) throws IOException { return url2file(url, file, DEFAULT_RETRIES); } public static File url2file (String url, File file, int retries) throws IOException { if (file == null) file = File.createTempFile("url2file-", getFileExt((url)), getDefaultTempDir()); IOException lastException = null; long sleep = 100; for (int i=0; i<retries; i++) { try { @Cleanup final InputStream in = get(url); @Cleanup final OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); lastException = null; break; } catch (IOException e) { lastException = e; sleep(sleep, "waiting to possibly retry after IOException: "+lastException); sleep *= 5; } } if (lastException != null) throw lastException; return file; } public static String url2string (String url) throws IOException { @Cleanup final InputStream in = get(url); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return out.toString(); } public static String url2string (String url, long connectTimeout) throws IOException { @Cleanup final InputStream in = get(url, connectTimeout); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return out.toString(); } public static HttpResponseBean getResponse(HttpRequestBean requestBean) throws IOException { final HttpClientBuilder clientBuilder = requestBean.initClientBuilder(HttpClients.custom()); @Cleanup final CloseableHttpClient client = clientBuilder.build(); return getResponse(requestBean, client); } public static HttpResponseBean getResponse(HttpRequestBean requestBean, HttpClient client) throws IOException { if (requestBean.hasStream()) return getStreamResponse(requestBean); final HttpResponseBean bean = new HttpResponseBean(); final HttpUriRequest request = initHttpRequest(requestBean); if (requestBean.hasHeaders()) { for (NameAndValue header : requestBean.getHeaders()) { request.setHeader(header.getName(), header.getValue()); } } final HttpResponse response = client.execute(request); for (Header header : response.getAllHeaders()) { bean.addHeader(header.getName(), header.getValue()); } bean.setStatus(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != NO_CONTENT && response.getEntity() != null) { bean.setContentLength(response.getEntity().getContentLength()); final Header contentType = response.getEntity().getContentType(); if (contentType != null) { bean.setContentType(contentType.getValue()); } @Cleanup final InputStream content = response.getEntity().getContent(); bean.setEntity(content); } return bean; } public static HttpResponseBean getStreamResponse(HttpRequestBean request) { if (!request.hasStream()) return die("getStreamResponse: request stream was not set"); try { final String boundary = hexnow(); request.withHeader(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); @Cleanup("disconnect") final HttpURLConnection connection = (HttpURLConnection) new URL(request.getUri()).openConnection(); connection.setDoOutput(true); connection.setRequestMethod(request.getMethod()); if (!request.hasContentLength() || (request.hasContentLength() && request.getContentLength() > BUFFER_SIZE)) { connection.setChunkedStreamingMode(BUFFER_SIZE); } for (NameAndValue header : request.getHeaders()) { connection.setRequestProperty(header.getName(), header.getValue()); } @Cleanup final OutputStream output = connection.getOutputStream(); @Cleanup final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, Charset.defaultCharset()), true); writer.append("--").append(boundary).append(CRLF); final String filename = request.getEntity(); addStreamHeader(writer, CONTENT_DISPOSITION, "form-data; name=\"file\"; filename=\""+ filename +"\""); addStreamHeader(writer, CONTENT_TYPE, contentType(filename)); writer.append(CRLF).flush(); IOUtils.copy(request.getEntityInputStream(), output); output.flush(); writer.append(CRLF); writer.append("--").append(boundary).append("--").append(CRLF).flush(); final HttpResponseBean response = new HttpResponseBean() .setStatus(connection.getResponseCode()) .setHttpHeaders(connection.getHeaderFields()); if (!request.discardResponseEntity()) { try { response.setEntity(connection.getInputStream()); } catch (IOException ioe) { response.setEntity(connection.getErrorStream()); } } return response; } catch (Exception e) { return die("getStreamResponse: "+e, e); } } private static PrintWriter addStreamHeader(PrintWriter writer, String name, String value) { writer.append(name).append(": ").append(value).append(CRLF); return writer; } public static HttpResponseBean getResponse(String urlString) throws IOException { final HttpResponseBean bean = new HttpResponseBean(); @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpResponse response = client.execute(new HttpGet(urlString.trim())); for (Header header : response.getAllHeaders()) { bean.addHeader(header.getName(), header.getValue()); } bean.setStatus(response.getStatusLine().getStatusCode()); if (response.getEntity() != null) { final Header contentType = response.getEntity().getContentType(); if (contentType != null) bean.setContentType(contentType.getValue()); bean.setContentLength(response.getEntity().getContentLength()); bean.setEntity(response.getEntity().getContent()); } return bean; } public static HttpUriRequest initHttpRequest(HttpRequestBean requestBean) { try { final HttpUriRequest request; switch (requestBean.getMethod()) { case HEAD: request = new HttpHead(requestBean.getUri()); break; case GET: request = new HttpGet(requestBean.getUri()); break; case POST: request = new HttpPost(requestBean.getUri()); break; case PUT: request = new HttpPut(requestBean.getUri()); break; case PATCH: request = new HttpPatch(requestBean.getUri()); break; case DELETE: request = new HttpDelete(requestBean.getUri()); break; default: return die("Invalid request method: " + requestBean.getMethod()); } if (requestBean.hasData() && request instanceof HttpEntityEnclosingRequestBase) { setData(requestBean.getEntity(), (HttpEntityEnclosingRequestBase) request); } return request; } catch (UnsupportedEncodingException e) { return die("initHttpRequest: " + e, e); } } private static void setData(Object data, HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException { if (data == null) return; if (data instanceof String) { request.setEntity(new StringEntity((String) data)); } else if (data instanceof InputStream) { request.setEntity(new InputStreamEntity((InputStream) data)); } else { throw new IllegalArgumentException("Unsupported request entity type: "+data.getClass().getName()); } } public static String getContentType(HttpResponse response) { final Header contentTypeHeader = response.getFirstHeader(CONTENT_TYPE); return (contentTypeHeader == null) ? null : contentTypeHeader.getValue(); } public static boolean isOk(String url) { return isOk(url, URIUtil.getHost(url)); } public static boolean isOk(String url, String host) { final CommandLine command = new CommandLine("curl") .addArgument("--insecure") // since we are requested via the IP address, the cert will not match .addArgument("--header").addArgument("Host: " + host) // pass FQDN via Host header .addArgument("--silent") .addArgument("--location") // follow redirects .addArgument("--write-out").addArgument("%{http_code}") // just print status code .addArgument("--output").addArgument("/dev/null") // and ignore data .addArgument(url); try { final CommandResult result = CommandShell.exec(command); final String statusCode = result.getStdout(); return result.isZeroExitStatus() && statusCode != null && statusCode.trim().startsWith("2"); } catch (IOException e) { log.warn("isOk: Error fetching " + url + " with Host header=" + host + ": " + e); return false; } } public static boolean isOk(String url, String host, int maxTries, long sleepUnit) { long sleep = sleepUnit; for (int i = 0; i < maxTries; i++) { if (i > 0) { Sleep.sleep(sleep); sleep *= 2; } if (isOk(url, host)) return true; } return false; } public static HttpMeta getHeadMetadata(HttpRequestBean request) throws IOException { final HttpResponseBean headResponse = HttpUtil.getResponse(new HttpRequestBean(request).setMethod(HEAD)); if (!headResponse.isOk()) return die("HTTP HEAD response was not 200: "+headResponse); final HttpMeta meta = new HttpMeta(request.getUri()); final String lastModString = headResponse.getFirstHeaderValue(LAST_MODIFIED); if (lastModString != null) meta.setLastModified(DATE_FORMAT_LAST_MODIFIED.parseMillis(lastModString)); final String etag = headResponse.getFirstHeaderValue(ETAG); if (etag != null) meta.setEtag(etag); return meta; } public static final byte[] CHUNK_SEP = "\r\n".getBytes(); public static final int CHUNK_EXTRA_BYTES = 2 * CHUNK_SEP.length; public static final byte[] CHUNK_END = "0\r\n".getBytes(); public static byte[] makeHttpChunk(byte[] buffer, int bytesRead) { final byte[] httpChunkLengthBytes = Integer.toHexString(bytesRead).getBytes(); final byte[] httpChunk = new byte[bytesRead + httpChunkLengthBytes.length + CHUNK_EXTRA_BYTES]; System.arraycopy(httpChunkLengthBytes, 0, httpChunk, 0, httpChunkLengthBytes.length); System.arraycopy(buffer, 0, httpChunk, httpChunkLengthBytes.length, bytesRead); System.arraycopy(CHUNK_SEP, 0, httpChunk, httpChunkLengthBytes.length+bytesRead, CHUNK_SEP.length); return httpChunk; } // adapted from https://github.com/stuartpb/user-agent-is-browser public static boolean isBrowser (String ua) { final boolean browser = !empty(ua) && !ua.equals("NONE") && ( ua.startsWith("Mozilla/") // Older versions of Opera || ua.startsWith("Opera/") // Down the rabbit hole... || ua.startsWith("Lynx/") || ua.startsWith("Links ") || ua.startsWith("Elinks ") || ua.startsWith("ELinks ") || ua.startsWith("ELinks/") || ua.startsWith("Midori/") || ua.startsWith("w3m/") || ua.startsWith("Webkit/") || ua.startsWith("Vimprobable/") || ua.startsWith("Dooble/") || ua.startsWith("Dillo/") || ua.startsWith("Surf/") || ua.startsWith("NetSurf/") || ua.startsWith("Galaxy/") || ua.startsWith("Cyberdog/") || ua.startsWith("iCab/") || ua.startsWith("IBrowse/") || ua.startsWith("IBM WebExplorer /") || ua.startsWith("AmigaVoyager/") || ua.startsWith("HotJava/") || ua.startsWith("retawq/") || ua.startsWith("uzbl ") || ua.startsWith("Uzbl ") || ua.startsWith("NCSA Mosaic/") || ua.startsWith("NCSA_Mosaic/") // And, finally, we test to see if they"re using *the first browser ever*. || ua.equals("WorldWideweb (NEXT)") ); if (log.isDebugEnabled()) log.debug("isBrowser("+ua+") returning "+browser); return browser; } }
src/main/java/org/cobbzilla/util/http/HttpUtil.java
package org.cobbzilla.util.http; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import org.apache.commons.exec.CommandLine; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.*; import org.apache.http.entity.ContentType; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.cobbzilla.util.collection.NameAndValue; import org.cobbzilla.util.string.StringUtil; import org.cobbzilla.util.system.CommandResult; import org.cobbzilla.util.system.CommandShell; import org.cobbzilla.util.system.Sleep; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; import static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.http.HttpHeaders.*; import static org.cobbzilla.util.daemon.ZillaRuntime.*; import static org.cobbzilla.util.http.HttpContentTypes.MULTIPART_FORM_DATA; import static org.cobbzilla.util.http.HttpContentTypes.contentType; import static org.cobbzilla.util.http.HttpMethods.*; import static org.cobbzilla.util.http.HttpStatusCodes.NO_CONTENT; import static org.cobbzilla.util.http.URIUtil.getFileExt; import static org.cobbzilla.util.io.FileUtil.getDefaultTempDir; import static org.cobbzilla.util.security.CryptStream.BUFFER_SIZE; import static org.cobbzilla.util.string.StringUtil.CRLF; import static org.cobbzilla.util.system.Sleep.sleep; import static org.cobbzilla.util.time.TimeUtil.DATE_FORMAT_LAST_MODIFIED; @Slf4j public class HttpUtil { public static final String CHUNKED_ENCODING = "chunked"; public static Map<String, String> queryParams(URL url) throws UnsupportedEncodingException { return queryParams(url, StringUtil.UTF8); } // from: http://stackoverflow.com/a/13592567 public static Map<String, String> queryParams(URL url, String encoding) throws UnsupportedEncodingException { final Map<String, String> query_pairs = new LinkedHashMap<>(); final String query = url.getQuery(); final String[] pairs = query.split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); query_pairs.put(URLDecoder.decode(pair.substring(0, idx), encoding), URLDecoder.decode(pair.substring(idx + 1), encoding)); } return query_pairs; } public static InputStream getUrlInputStream(String url) throws IOException { return get(url); } public static InputStream get (String urlString) throws IOException { return get(urlString, null); } public static InputStream get (String urlString, long connectTimeout) throws IOException { return get(urlString, null, null, connectTimeout); } public static InputStream get (String urlString, Map<String, String> headers) throws IOException { return get(urlString, headers, null); } public static InputStream get (String urlString, Map<String, String> headers, Map<String, String> headers2) throws IOException { return get(urlString, headers, headers2, null); } public static InputStream get (String urlString, Map<String, String> headers, Map<String, String> headers2, Long connectTimeout) throws IOException { final URL url = new URL(urlString); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (connectTimeout != null) urlConnection.setConnectTimeout(connectTimeout.intValue()); if (headers != null) addHeaders(urlConnection, headers); if (headers2 != null) addHeaders(urlConnection, headers2); return urlConnection.getInputStream(); } public static InputStream post (String urlString, InputStream data, String multipartFileName, Map<String, String> headers, Map<String, String> headers2) throws IOException { return upload(urlString, POST, multipartFileName, data, headers, headers2); } public static InputStream put (String urlString, InputStream data, String multipartFileName, Map<String, String> headers, Map<String, String> headers2) throws IOException { return upload(urlString, PUT, multipartFileName, data, headers, headers2); } public static InputStream upload (String urlString, String method, String multipartFileName, InputStream data, Map<String, String> headers, Map<String, String> headers2) throws IOException { final URL url = new URL(urlString); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); if (headers != null) addHeaders(urlConnection, headers); if (headers2 != null) addHeaders(urlConnection, headers2); if (data != null) { urlConnection.setDoOutput(true); OutputStream upload = null; try { if (multipartFileName != null) { final String boundary = randomAlphanumeric(10)+"_"+now(); urlConnection.setRequestProperty(CONTENT_TYPE, MULTIPART_FORM_DATA+"; boundary="+boundary); urlConnection.setRequestProperty(TRANSFER_ENCODING, CHUNKED_ENCODING); urlConnection.setChunkedStreamingMode(4096); final HttpEntity entity = MultipartEntityBuilder.create() .setBoundary(boundary) .setLaxMode() .addBinaryBody(multipartFileName, data, ContentType.APPLICATION_OCTET_STREAM, multipartFileName) .build(); upload = urlConnection.getOutputStream(); entity.writeTo(upload); } else { upload = urlConnection.getOutputStream(); IOUtils.copyLarge(data, upload); } } finally { if (upload != null) upload.close(); } } return urlConnection.getInputStream(); } public static void addHeaders(HttpURLConnection urlConnection, Map<String, String> headers) { for (Map.Entry<String, String> h : headers.entrySet()) { urlConnection.setRequestProperty(h.getKey(), h.getValue()); } } public static HttpResponseBean upload (String url, File file, Map<String, String> headers) throws IOException { @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpPost method = new HttpPost(url); final FileBody fileBody = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", fileBody); method.setEntity(builder.build()); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { method.addHeader(new BasicHeader(header.getKey(), header.getValue())); } } @Cleanup final CloseableHttpResponse response = client.execute(method); final HttpResponseBean responseBean = new HttpResponseBean() .setEntityBytes(EntityUtils.toByteArray(response.getEntity())) .setHttpHeaders(response.getAllHeaders()) .setStatus(response.getStatusLine().getStatusCode()); return responseBean; } public static final int DEFAULT_RETRIES = 3; public static File url2file (String url) throws IOException { return url2file(url, null, DEFAULT_RETRIES); } public static File url2file (String url, String file) throws IOException { return url2file(url, file == null ? null : new File(file), DEFAULT_RETRIES); } public static File url2file (String url, File file) throws IOException { return url2file(url, file, DEFAULT_RETRIES); } public static File url2file (String url, File file, int retries) throws IOException { if (file == null) file = File.createTempFile("url2file-", getFileExt((url)), getDefaultTempDir()); IOException lastException = null; long sleep = 100; for (int i=0; i<retries; i++) { try { @Cleanup final InputStream in = get(url); @Cleanup final OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); lastException = null; break; } catch (IOException e) { lastException = e; sleep(sleep, "waiting to possibly retry after IOException: "+lastException); sleep *= 5; } } if (lastException != null) throw lastException; return file; } public static String url2string (String url) throws IOException { @Cleanup final InputStream in = get(url); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return out.toString(); } public static String url2string (String url, long connectTimeout) throws IOException { @Cleanup final InputStream in = get(url, connectTimeout); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return out.toString(); } public static HttpResponseBean getResponse(HttpRequestBean requestBean) throws IOException { final HttpClientBuilder clientBuilder = requestBean.initClientBuilder(HttpClients.custom()); @Cleanup final CloseableHttpClient client = clientBuilder.build(); return getResponse(requestBean, client); } public static HttpResponseBean getResponse(HttpRequestBean requestBean, HttpClient client) throws IOException { if (requestBean.hasStream()) return getStreamResponse(requestBean); final HttpResponseBean bean = new HttpResponseBean(); final HttpUriRequest request = initHttpRequest(requestBean); if (requestBean.hasHeaders()) { for (NameAndValue header : requestBean.getHeaders()) { request.setHeader(header.getName(), header.getValue()); } } final HttpResponse response = client.execute(request); for (Header header : response.getAllHeaders()) { bean.addHeader(header.getName(), header.getValue()); } bean.setStatus(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != NO_CONTENT && response.getEntity() != null) { bean.setContentLength(response.getEntity().getContentLength()); final Header contentType = response.getEntity().getContentType(); if (contentType != null) { bean.setContentType(contentType.getValue()); } @Cleanup final InputStream content = response.getEntity().getContent(); bean.setEntity(content); } return bean; } public static HttpResponseBean getStreamResponse(HttpRequestBean request) { if (!request.hasStream()) return die("getStreamResponse: request stream was not set"); try { final String boundary = hexnow(); request.withHeader(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); @Cleanup("disconnect") final HttpURLConnection connection = (HttpURLConnection) new URL(request.getUri()).openConnection(); connection.setDoOutput(true); connection.setRequestMethod(request.getMethod()); if (!request.hasContentLength() || (request.hasContentLength() && request.getContentLength() > BUFFER_SIZE)) { connection.setChunkedStreamingMode(BUFFER_SIZE); } for (NameAndValue header : request.getHeaders()) { connection.setRequestProperty(header.getName(), header.getValue()); } @Cleanup final OutputStream output = connection.getOutputStream(); @Cleanup final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, Charset.defaultCharset()), true); writer.append("--").append(boundary).append(CRLF); final String filename = request.getEntity(); addStreamHeader(writer, CONTENT_DISPOSITION, "form-data; name=\"file\"; filename=\""+ filename +"\""); addStreamHeader(writer, CONTENT_TYPE, contentType(filename)); writer.append(CRLF).flush(); IOUtils.copy(request.getEntityInputStream(), output); output.flush(); writer.append(CRLF); writer.append("--").append(boundary).append("--").append(CRLF).flush(); final HttpResponseBean response = new HttpResponseBean() .setStatus(connection.getResponseCode()) .setHttpHeaders(connection.getHeaderFields()); if (!request.discardResponseEntity()) { try { response.setEntity(connection.getInputStream()); } catch (IOException ioe) { response.setEntity(connection.getErrorStream()); } } return response; } catch (Exception e) { return die("getStreamResponse: "+e, e); } } private static PrintWriter addStreamHeader(PrintWriter writer, String name, String value) { writer.append(name).append(": ").append(value).append(CRLF); return writer; } public static HttpResponseBean getResponse(String urlString) throws IOException { final HttpResponseBean bean = new HttpResponseBean(); @Cleanup final CloseableHttpClient client = HttpClients.createDefault(); final HttpResponse response = client.execute(new HttpGet(urlString.trim())); for (Header header : response.getAllHeaders()) { bean.addHeader(header.getName(), header.getValue()); } bean.setStatus(response.getStatusLine().getStatusCode()); if (response.getEntity() != null) { final Header contentType = response.getEntity().getContentType(); if (contentType != null) bean.setContentType(contentType.getValue()); bean.setContentLength(response.getEntity().getContentLength()); bean.setEntity(response.getEntity().getContent()); } return bean; } public static HttpUriRequest initHttpRequest(HttpRequestBean requestBean) { try { final HttpUriRequest request; switch (requestBean.getMethod()) { case HEAD: request = new HttpHead(requestBean.getUri()); break; case GET: request = new HttpGet(requestBean.getUri()); break; case POST: request = new HttpPost(requestBean.getUri()); break; case PUT: request = new HttpPut(requestBean.getUri()); break; case PATCH: request = new HttpPatch(requestBean.getUri()); break; case DELETE: request = new HttpDelete(requestBean.getUri()); break; default: return die("Invalid request method: " + requestBean.getMethod()); } if (requestBean.hasData() && request instanceof HttpEntityEnclosingRequestBase) { setData(requestBean.getEntity(), (HttpEntityEnclosingRequestBase) request); } return request; } catch (UnsupportedEncodingException e) { return die("initHttpRequest: " + e, e); } } private static void setData(Object data, HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException { if (data == null) return; if (data instanceof String) { request.setEntity(new StringEntity((String) data)); } else if (data instanceof InputStream) { request.setEntity(new InputStreamEntity((InputStream) data)); } else { throw new IllegalArgumentException("Unsupported request entity type: "+data.getClass().getName()); } } public static String getContentType(HttpResponse response) { final Header contentTypeHeader = response.getFirstHeader(CONTENT_TYPE); return (contentTypeHeader == null) ? null : contentTypeHeader.getValue(); } public static boolean isOk(String url) { return isOk(url, URIUtil.getHost(url)); } public static boolean isOk(String url, String host) { final CommandLine command = new CommandLine("curl") .addArgument("--insecure") // since we are requested via the IP address, the cert will not match .addArgument("--header").addArgument("Host: " + host) // pass FQDN via Host header .addArgument("--silent") .addArgument("--location") // follow redirects .addArgument("--write-out").addArgument("%{http_code}") // just print status code .addArgument("--output").addArgument("/dev/null") // and ignore data .addArgument(url); try { final CommandResult result = CommandShell.exec(command); final String statusCode = result.getStdout(); return result.isZeroExitStatus() && statusCode != null && statusCode.trim().startsWith("2"); } catch (IOException e) { log.warn("isOk: Error fetching " + url + " with Host header=" + host + ": " + e); return false; } } public static boolean isOk(String url, String host, int maxTries, long sleepUnit) { long sleep = sleepUnit; for (int i = 0; i < maxTries; i++) { if (i > 0) { Sleep.sleep(sleep); sleep *= 2; } if (isOk(url, host)) return true; } return false; } public static HttpMeta getHeadMetadata(HttpRequestBean request) throws IOException { final HttpResponseBean headResponse = HttpUtil.getResponse(new HttpRequestBean(request).setMethod(HEAD)); if (!headResponse.isOk()) return die("HTTP HEAD response was not 200: "+headResponse); final HttpMeta meta = new HttpMeta(request.getUri()); final String lastModString = headResponse.getFirstHeaderValue(LAST_MODIFIED); if (lastModString != null) meta.setLastModified(DATE_FORMAT_LAST_MODIFIED.parseMillis(lastModString)); final String etag = headResponse.getFirstHeaderValue(ETAG); if (etag != null) meta.setEtag(etag); return meta; } public static final byte[] CHUNK_SEP = "\r\n".getBytes(); public static final int CHUNK_EXTRA_BYTES = 2 * CHUNK_SEP.length; public static final byte[] CHUNK_END = "0\r\n".getBytes(); public static byte[] makeHttpChunk(byte[] buffer, int bytesRead) { final byte[] httpChunkLengthBytes = Integer.toHexString(bytesRead).getBytes(); final byte[] httpChunk = new byte[bytesRead + httpChunkLengthBytes.length + CHUNK_EXTRA_BYTES]; System.arraycopy(httpChunkLengthBytes, 0, httpChunk, 0, httpChunkLengthBytes.length); System.arraycopy(buffer, 0, httpChunk, httpChunkLengthBytes.length, bytesRead); System.arraycopy(CHUNK_SEP, 0, httpChunk, httpChunkLengthBytes.length+bytesRead, CHUNK_SEP.length); return httpChunk; } }
add HttpUtil.isBrowser
src/main/java/org/cobbzilla/util/http/HttpUtil.java
add HttpUtil.isBrowser
Java
apache-2.0
2195fe31cd66d9c6455fbc4bcbad59f249bc56e6
0
apache/isis,apache/isis,apache/isis,apache/isis,apache/isis,apache/isis
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.applib.anyio; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.function.Function; import org.apache.isis.commons.internal.base._Strings; /** * Universal in-memory sink, that can be read from after having been written to. * * @since 2.0.0-M2 */ public class AnyOutBuffer implements AnyOut { private final ByteArrayOutputStream buffer; private Try<?> lastTry; AnyOutBuffer(int buffersize) { buffer = new ByteArrayOutputStream(buffersize); } @Override public <T> Try<T> tryApplyOutputStream(Function<OutputStream, Try<T>> outputConsumer) { if(lastTry!=null) { throw new IllegalStateException("Buffer was already written to."); } Try<T> _try = outputConsumer.apply(buffer); lastTry = _try; return _try; } public Try<byte[]> tryReadBytes(){ if(lastTry!=null && lastTry.isFailure()) { return Try.failure(lastTry.getFailure()); } return Try.success(buffer.toByteArray()); } public Try<CharSequence> tryReadCharacters(Charset charset){ return tryReadBytes().map(bytes->_Strings.ofBytes(bytes, charset)); } }
core/applib/src/main/java/org/apache/isis/applib/anyio/AnyOutBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.isis.applib.anyio; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.function.Function; import org.apache.isis.commons.internal.base._Strings; /** * Universal in-memory sink, that can be read from after having been written to. * * @since 2.0.0-M2 */ public class AnyOutBuffer implements AnyOut { private final ByteArrayOutputStream buffer; private Try<?> lastTry; AnyOutBuffer(int buffersize) { buffer = new ByteArrayOutputStream(buffersize); } @Override public <T> Try<T> tryApplyOutputStream(Function<OutputStream, Try<T>> outputConsumer) { if(lastTry!=null) { throw new IllegalStateException("Buffer was already written to."); } Try<T> _try = outputConsumer.apply(buffer); return _try; } public Try<byte[]> tryReadBytes(){ if(lastTry!=null && lastTry.isFailure()) { return Try.failure(lastTry.getFailure()); } return Try.success(buffer.toByteArray()); } public Try<CharSequence> tryReadCharacters(Charset charset){ return tryReadBytes().map(bytes->_Strings.ofBytes(bytes, charset)); } }
ISIS-2006: AnyOutBuffer: fix missing assignment
core/applib/src/main/java/org/apache/isis/applib/anyio/AnyOutBuffer.java
ISIS-2006: AnyOutBuffer: fix missing assignment
Java
apache-2.0
c1b000c68080552ce2ca527aade8e5a646800b89
0
309746069/Android-Universal-Image-Loader,hgl888/Android-Universal-Image-Loader,lq-ever/Android-Universal-Image-Loader,guoGavin/Android-Universal-Image-Loader,xiepengfei/Android-Universal-Image-Loader,maduhu/Android-Universal-Image-Loader,huihui4045/Android-Universal-Image-Loader,jjjjjjjjj99999/Android-Universal-Image-Loader,hzjsftw/hanzjProject,freeman0211/Android-Universal-Image-Loader,yummykwok/Android-Universal-Image-Loader,pchauhan/Android-Universal-Image-Loader,shizhongyu/Android-Universal-Image-Loader,kabouzeid/Android-Universal-Image-Loader,Genesis6/Android-Universal-Image-Loader,jinmiao0601/Android-Universal-Image-Loader,yyhat/Android-Universal-Image-Loader,johnjohndoe/Android-Universal-Image-Loader,Morddeka/Android-Universal-Image-Loader,hareshsandeep/Android-Universal-Image-Loader,kanjiandahai/Android-Universal-Image-Loader,yihr/Android-Universal-Image-Loader,jjzhoujun/Android-Universal-Image-Loader,3sidedcube/Android-Universal-Image-Loader,ForNowForever/Android-Universal-Image-Loader,masken2/Android-Universal-Image-Loader,lovecc0923/Android-Universal-Image-Loader,mpoozd/Android-Universal-Image-Loader,brianzzzzz/Android-Universal-Image-Loader,vivekkiran/Android-Universal-Image-Loader,n4android/Android-Universal-Image-Loader,kingdawin/Android-Universal-Image-Loader,askk/Android-Universal-Image-Loader,StevenWT/Android-Universal-Image-Loader,ManagerOrganization/Android-Universal-Image-Loader,junenn/Android-Universal-Image-Loader,yutail/Android-Universal-Image-Loader,littlefisher112291/Android-Universal-Image-Loader,panggirl/Android-Universal-Image-Loader,mengdd/Android-Universal-Image-Loader,triplezhao/Android-Universal-Image-Loader,Wei-JJ/Android-Image,Jokeby/Android-Universal-Image-Loader,MoskalenkoViktor/Android-Universal-Image-Loader,wenscript/Android-Universal-Image-Loader,yushiwo/Android-Universal-Image-Loader,moziqi/Android-Universal-Image-Loader,wiStar/Android-Universal-Image-Loader,xu509/Android-Universal-Image-Loader,Bibeknam/Android-Universal-Image-Loader,kys9261/Android-Universal-Image-Loader,lolevsky/Android-Universal-Image-Loader,RadiateWSG/Android-Universal-Image-Loader,yinzhiliang/Android-Universal-Image-Loader,ChanJLee/Android-Universal-Image-Loader,yigeyidian/Android-Universal-Image-Loader,hzysoft/Android-Universal-Image-Loader,wanjingyan001/Android-Universal-Image-Loader,guoxiaojun001/Android-Universal-Image-Loader,JerryloveEmily/Android-Universal-Image-Loader,tonycheng93/Android-Universal-Image-Loader,Rachel-Ding/Android-Universal-Image-Loader,wy315700/Android-Universal-Image-Loader,yc507/Android-Universal-Image-Loader,aLoyalStudent/Android-Universal-Image-Loader,DeathPluto/Android-Universal-Image-Loader,lostghoul/Android-Universal-Image-Loader,qingsong-xu/Android-Universal-Image-Loader,weikipeng/Android-Universal-Image-Loader,JunyiZhou/Android-Universal-Image-Loader,jekey/Android-Universal-Image-Loader,pobuing/Android-Universal-Image-Loader,RomzesRover/Android-Universal-Image-Loader,xiuweikang/Android-Universal-Image-Loader,krumman/Android-Universal-Image-Loader,vvandvv/Android-Universal-Image-Loader,SyllaJay/Android-Universal-Image-Loader,zhangtianqiu/imagLoader,Ringares/Android-Universal-Image-Loader,xiangwei/Android-Universal-Image-Loader,Fastrun/Android-Universal-Image-Loader,Jackie880823/Android-Universal-Image-Loader,chwnFlyPig/Android-Universal-Image-Loader,inexistence/Android-Universal-Image-Loader,lxhxhlw/Android-Universal-Image-Loader,ppk5457/Android-Universal-Image-Loader,java02014/Android-Universal-Image-Loader,akhilesh0707/Android-Universal-Image-Loader,teffy/Android-Universal-Image-Loader,5A59/Android-Universal-Image-Loader,LeonardoPhysh/Android-Universal-Image-Loader,sixgodIT/Android-Universal-Image-Loader,ijidan/Android-Universal-Image-Loader,bestwpw/Android-Universal-Image-Loader,zhupengGitHub/Android-Universal-Image-Loader,MayurAmipara/Android-Universal-Image-Loader,yuzhiboi/Android-Universal-Image-Loader,huanting/Android-Universal-Image-Loader,sahilk2579/Android-Universal-Image-Loader,captainJeck/Android-Universal-Image-Loader,lixinxinlove/Android-Universal-Image-Loader,VideoTec/Android-Universal-Image-Loader,LittleRobotRoad/Android-Universal-Image-Loader,cjpx00008/Android-Universal-Image-Loader,leixinstar/Android-Universal-Image-Loader,nostra13/Android-Universal-Image-Loader,yummy222/Android-Universal-Image-Loader,jxauchengchao/Android-Universal-Image-Loader,Meowzm/Android-Universal-Image-Loader,huangsongyan/Android-Universal-Image-Loader,jjfreeze/Android-Universal-Image-Loader,westlakestudent/Android-Universal-Image-Loader,cpetzel/Android-Universal-Image-Loader,ZhaoYukai/Android-Universal-Image-Loader,EricInCD/Android-Universal-Image-Loader,AdrianHsu/Android-Universal-Image-Loader,gaojinhua/Android-Universal-Image-Loader,crazysniper/Android-Universal-Image-Loader,dat0106/Android-Universal-Image-Loader,CJstar/Android-Universal-Image-Loader,zhaog/Android-Universal-Image-Loader,ranjith068/Android-Universal-Image-Loader,TY-tianyu/Android-Universal-Image-Loader,tanyixiu/Android-Universal-Image-Loader,yi291047383/Android-Universal-Image-Loader,Peter32/Android-Universal-Image-Loader,jianxiansining/Android-Universal-Image-Loader,xiaochilun/Android-Universal-Image-Loader,Topface/Android-Universal-Image-Loader,lemoclone/Android-Universal-Image-Loader,Jackear/Android-Universal-Image-Loader,hejunbinlan/Android-Universal-Image-Loader,kbajpai/Android-Universal-Image-Loader,FinalLevel/Android-Universal-Image-Loader,maolala/Android-Universal-Image-Loader,libo2007/Android-Universal-Image-Loader,simple88/Android-Universal-Image-Loader,hotarzhang/Android-Universal-Image-Loader,zhaokidd/Android-Universal-Image-Loader,jp1017/Android-Universal-Image-Loader,fhchina/Android-Universal-Image-Loader,maitho/Android-Universal-Image-Loader,HossainKhademian/AndroidUniversalImageLoader,liuguangli/Android-Universal-Image-Loader,tanweijiu/Android-Universal-Image-Loader,charlialiang/Android-Universal-Image-Loader,lypdemo/Android-Universal-Image-Loader,jiashie/Android-Universal-Image-Loader,wmg494005678/Android-Universal-Image-Loader,lzy-h2o2/Android-Universal-Image-Loader,wangqi504635/Android-Universal-Image-Loader,bobierbo/Android-Universal-Image-Loader,jinmiao/Android-Universal-Image-Loader,yangshangwei/Android-Universal-Image-Loader,OnlyWangyn/Android-Universal-Image-Loader,Faner007/Android-Universal-Image-Loader,nguyendinhduc/Android-Universal-Image-Loader,8tory/Android-Universal-Image-Loader,TomIsYourName/Android-Universal-Image-Loader,tandingbo/Android-Universal-Image-Loader,hxy0107/Android-Universal-Image-Loader,motian/Android-Universal-Image-Loader,zjutzhaodj/Android-Universal-Image-Loader
/******************************************************************************* * Copyright 2011-2014 Sergey Tarasevich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.nostra13.universalimageloader.core.download; import android.content.ContentResolver; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.net.Uri; import android.provider.ContactsContract; import android.provider.MediaStore; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.assist.ContentLengthInputStream; import com.nostra13.universalimageloader.utils.IoUtils; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** * Provides retrieving of {@link InputStream} of image by URI from network or file system or app resources.<br /> * {@link URLConnection} is used to retrieve image stream from network. * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @since 1.8.0 */ public class BaseImageDownloader implements ImageDownloader { /** {@value} */ public static final int DEFAULT_HTTP_CONNECT_TIMEOUT = 5 * 1000; // milliseconds /** {@value} */ public static final int DEFAULT_HTTP_READ_TIMEOUT = 20 * 1000; // milliseconds /** {@value} */ protected static final int BUFFER_SIZE = 32 * 1024; // 32 Kb /** {@value} */ protected static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%"; protected static final int MAX_REDIRECT_COUNT = 5; protected static final String CONTENT_CONTACTS_URI_PREFIX = "content://com.android.contacts/"; private static final String ERROR_UNSUPPORTED_SCHEME = "UIL doesn't support scheme(protocol) by default [%s]. " + "You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))"; protected final Context context; protected final int connectTimeout; protected final int readTimeout; /** * Whether read stream if server returned non-200 response */ protected final boolean readOnError; public BaseImageDownloader(Context context) { this(context.getApplicationContext(), DEFAULT_HTTP_CONNECT_TIMEOUT, DEFAULT_HTTP_READ_TIMEOUT, false); } public BaseImageDownloader(Context context, int connectTimeout, int readTimeout, boolean readOnError) { this.context = context.getApplicationContext(); this.connectTimeout = connectTimeout; this.readTimeout = readTimeout; this.readOnError = readOnError; } @Override public InputStream getStream(String imageUri, Object extra) throws IOException { switch (Scheme.ofUri(imageUri)) { case HTTP: case HTTPS: return getStreamFromNetwork(imageUri, extra); case FILE: return getStreamFromFile(imageUri, extra); case CONTENT: return getStreamFromContent(imageUri, extra); case ASSETS: return getStreamFromAssets(imageUri, extra); case DRAWABLE: return getStreamFromDrawable(imageUri, extra); case UNKNOWN: default: return getStreamFromOtherSource(imageUri, extra); } } /** * Retrieves {@link InputStream} of image by URI (image is located in the network). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for * URL. */ protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException { HttpURLConnection conn = createConnection(imageUri, extra); int redirectCount = 0; while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) { conn = createConnection(conn.getHeaderField("Location"), extra); redirectCount++; } InputStream imageStream; try { if (conn.getResponseCode() != 200 && !readOnError) { throw new IOException("Unable to retrieve image. Response code: " + conn.getResponseCode()); } imageStream = conn.getInputStream(); } catch (IOException e) { // Read all data to allow reuse connection (http://bit.ly/1ad35PY) IoUtils.readAndCloseStream(conn.getErrorStream()); throw e; } return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength()); } /** * Create {@linkplain HttpURLConnection HTTP connection} for incoming URL * * @param url URL to connect to * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@linkplain HttpURLConnection Connection} for incoming URL. Connection isn't established so it still configurable. * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for * URL. */ protected HttpURLConnection createConnection(String url, Object extra) throws IOException { String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS); HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection(); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); return conn; } /** * Retrieves {@link InputStream} of image by URI (image is located on the local file system or SD card). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs reading from file system */ protected InputStream getStreamFromFile(String imageUri, Object extra) throws IOException { String filePath = Scheme.FILE.crop(imageUri); return new ContentLengthInputStream(new BufferedInputStream(new FileInputStream(filePath), BUFFER_SIZE), (int) new File(filePath).length()); } /** * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws FileNotFoundException if the provided URI could not be opened */ protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException { ContentResolver res = context.getContentResolver(); Uri uri = Uri.parse(imageUri); if (isVideoUri(uri)) { // video thumbnail Long origId = Long.valueOf(uri.getLastPathSegment()); Bitmap bitmap = MediaStore.Video.Thumbnails .getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null); if (bitmap != null) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0, bos); return new ByteArrayInputStream(bos.toByteArray()); } } else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo return ContactsContract.Contacts.openContactPhotoInputStream(res, uri); } return res.openInputStream(uri); } /** * Retrieves {@link InputStream} of image by URI (image is located in assets of application). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs file reading */ protected InputStream getStreamFromAssets(String imageUri, Object extra) throws IOException { String filePath = Scheme.ASSETS.crop(imageUri); return context.getAssets().open(filePath); } /** * Retrieves {@link InputStream} of image by URI (image is located in drawable resources of application). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image */ protected InputStream getStreamFromDrawable(String imageUri, Object extra) { String drawableIdString = Scheme.DRAWABLE.crop(imageUri); int drawableId = Integer.parseInt(drawableIdString); return context.getResources().openRawResource(drawableId); } /** * Retrieves {@link InputStream} of image by URI from other source with unsupported scheme. Should be overriden by * successors to implement image downloading from special sources.<br /> * This method is called only if image URI has unsupported scheme. Throws {@link UnsupportedOperationException} by * default. * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs * @throws UnsupportedOperationException if image URI has unsupported scheme(protocol) */ protected InputStream getStreamFromOtherSource(String imageUri, Object extra) throws IOException { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_SCHEME, imageUri)); } private boolean isVideoUri(Uri uri) { String mimeType = context.getContentResolver().getType(uri); if (mimeType == null) { return false; } return mimeType.startsWith("video/"); } }
library/src/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java
/******************************************************************************* * Copyright 2011-2014 Sergey Tarasevich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.nostra13.universalimageloader.core.download; import android.content.ContentResolver; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.net.Uri; import android.provider.ContactsContract; import android.provider.MediaStore; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.assist.ContentLengthInputStream; import com.nostra13.universalimageloader.utils.IoUtils; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** * Provides retrieving of {@link InputStream} of image by URI from network or file system or app resources.<br /> * {@link URLConnection} is used to retrieve image stream from network. * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @since 1.8.0 */ public class BaseImageDownloader implements ImageDownloader { /** {@value} */ public static final int DEFAULT_HTTP_CONNECT_TIMEOUT = 5 * 1000; // milliseconds /** {@value} */ public static final int DEFAULT_HTTP_READ_TIMEOUT = 20 * 1000; // milliseconds /** {@value} */ protected static final int BUFFER_SIZE = 32 * 1024; // 32 Kb /** {@value} */ protected static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%"; protected static final int MAX_REDIRECT_COUNT = 5; protected static final String CONTENT_CONTACTS_URI_PREFIX = "content://com.android.contacts/"; private static final String ERROR_UNSUPPORTED_SCHEME = "UIL doesn't support scheme(protocol) by default [%s]. " + "You should implement this support yourself (BaseImageDownloader.getStreamFromOtherSource(...))"; protected final Context context; protected final int connectTimeout; protected final int readTimeout; public BaseImageDownloader(Context context) { this.context = context.getApplicationContext(); this.connectTimeout = DEFAULT_HTTP_CONNECT_TIMEOUT; this.readTimeout = DEFAULT_HTTP_READ_TIMEOUT; } public BaseImageDownloader(Context context, int connectTimeout, int readTimeout) { this.context = context.getApplicationContext(); this.connectTimeout = connectTimeout; this.readTimeout = readTimeout; } @Override public InputStream getStream(String imageUri, Object extra) throws IOException { switch (Scheme.ofUri(imageUri)) { case HTTP: case HTTPS: return getStreamFromNetwork(imageUri, extra); case FILE: return getStreamFromFile(imageUri, extra); case CONTENT: return getStreamFromContent(imageUri, extra); case ASSETS: return getStreamFromAssets(imageUri, extra); case DRAWABLE: return getStreamFromDrawable(imageUri, extra); case UNKNOWN: default: return getStreamFromOtherSource(imageUri, extra); } } /** * Retrieves {@link InputStream} of image by URI (image is located in the network). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for * URL. */ protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException { HttpURLConnection conn = createConnection(imageUri, extra); int redirectCount = 0; while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) { conn = createConnection(conn.getHeaderField("Location"), extra); redirectCount++; } InputStream imageStream; try { imageStream = conn.getInputStream(); } catch (IOException e) { // Read all data to allow reuse connection (http://bit.ly/1ad35PY) IoUtils.readAndCloseStream(conn.getErrorStream()); throw e; } return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength()); } /** * Create {@linkplain HttpURLConnection HTTP connection} for incoming URL * * @param url URL to connect to * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@linkplain HttpURLConnection Connection} for incoming URL. Connection isn't established so it still configurable. * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for * URL. */ protected HttpURLConnection createConnection(String url, Object extra) throws IOException { String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS); HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection(); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); return conn; } /** * Retrieves {@link InputStream} of image by URI (image is located on the local file system or SD card). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs reading from file system */ protected InputStream getStreamFromFile(String imageUri, Object extra) throws IOException { String filePath = Scheme.FILE.crop(imageUri); return new ContentLengthInputStream(new BufferedInputStream(new FileInputStream(filePath), BUFFER_SIZE), (int) new File(filePath).length()); } /** * Retrieves {@link InputStream} of image by URI (image is accessed using {@link ContentResolver}). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws FileNotFoundException if the provided URI could not be opened */ protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException { ContentResolver res = context.getContentResolver(); Uri uri = Uri.parse(imageUri); if (isVideoUri(uri)) { // video thumbnail Long origId = Long.valueOf(uri.getLastPathSegment()); Bitmap bitmap = MediaStore.Video.Thumbnails .getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null); if (bitmap != null) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0, bos); return new ByteArrayInputStream(bos.toByteArray()); } } else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo return ContactsContract.Contacts.openContactPhotoInputStream(res, uri); } return res.openInputStream(uri); } /** * Retrieves {@link InputStream} of image by URI (image is located in assets of application). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs file reading */ protected InputStream getStreamFromAssets(String imageUri, Object extra) throws IOException { String filePath = Scheme.ASSETS.crop(imageUri); return context.getAssets().open(filePath); } /** * Retrieves {@link InputStream} of image by URI (image is located in drawable resources of application). * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image */ protected InputStream getStreamFromDrawable(String imageUri, Object extra) { String drawableIdString = Scheme.DRAWABLE.crop(imageUri); int drawableId = Integer.parseInt(drawableIdString); return context.getResources().openRawResource(drawableId); } /** * Retrieves {@link InputStream} of image by URI from other source with unsupported scheme. Should be overriden by * successors to implement image downloading from special sources.<br /> * This method is called only if image URI has unsupported scheme. Throws {@link UnsupportedOperationException} by * default. * * @param imageUri Image URI * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object) * DisplayImageOptions.extraForDownloader(Object)}; can be null * @return {@link InputStream} of image * @throws IOException if some I/O error occurs * @throws UnsupportedOperationException if image URI has unsupported scheme(protocol) */ protected InputStream getStreamFromOtherSource(String imageUri, Object extra) throws IOException { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_SCHEME, imageUri)); } private boolean isVideoUri(Uri uri) { String mimeType = context.getContentResolver().getType(uri); if (mimeType == null) { return false; } return mimeType.startsWith("video/"); } }
optionally do not read response if server returned non-200 code
library/src/com/nostra13/universalimageloader/core/download/BaseImageDownloader.java
optionally do not read response if server returned non-200 code
Java
apache-2.0
33fac95bcdd163f56d35aaa34cdb3224d36ebf38
0
nasrallahmounir/Footlights,nasrallahmounir/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,trombonehero/Footlights,trombonehero/Footlights
package me.footlights.core.crypto; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.codec.binary.Base32; import org.apache.commons.codec.binary.Hex; import com.google.common.annotations.VisibleForTesting; import me.footlights.HasBytes; import me.footlights.core.Preferences; import me.footlights.core.ConfigurationError; /** A fingerprint for a number of bytes. */ public class Fingerprint { public static Fingerprint decode(String name) throws NoSuchAlgorithmException { String parts[] = name.replaceAll("\\+", "/").split(":"); if (parts.length != 2) throw new IllegalArgumentException("Invalid fingerprint '" + name + "'"); String algorithmName = parts[0].toLowerCase(); String hash = parts[1].toUpperCase(); MessageDigest algorithm = MessageDigest.getInstance(algorithmName); return new Fingerprint(algorithm, ByteBuffer.wrap(new Base32().decode(hash.getBytes()))); } public static Builder newBuilder() { return new Builder(); } public String encode() { StringBuffer sb = new StringBuffer(); sb.append(algorithm.getAlgorithm().toLowerCase()); sb.append(":"); sb.append(new String(new Base32().encode(bytes.array())).replaceAll("/", "+")); return sb.toString(); } public MessageDigest getAlgorithm() { return algorithm; } public boolean matches(ByteBuffer b) { return (0 == bytes.compareTo(b)); } public boolean matches(byte[] b) { return matches(ByteBuffer.wrap(b)); } public ByteBuffer getBytes() { return bytes.asReadOnlyBuffer(); } public byte[] copyBytes() { byte[] copy = new byte[bytes.remaining()]; bytes.get(copy); return copy; } public static class Builder { public Fingerprint build() { ByteBuffer hash = ByteBuffer.wrap(algorithm.digest(bytes)); return new Fingerprint(algorithm, hash); } public Builder setAlgorithm(String a) throws NoSuchAlgorithmException { algorithm = MessageDigest.getInstance(a); return this; } public Builder setContent(byte[] b) { bytes = b; return this; } public Builder setContent(HasBytes h) { return setContent(h.getBytes()); } public Builder setContent(ByteBuffer b) { if (b.isReadOnly()) { bytes = new byte[b.remaining()]; b.get(bytes); } else bytes = b.array(); return this; } private Builder() { try { algorithm = MessageDigest.getInstance( Preferences.getDefaultPreferences().getString("crypto.hash.algorithm")); } catch (NoSuchAlgorithmException e) { throw new ConfigurationError("Invalid hash algorithm: " + e); } } private MessageDigest algorithm; private byte[] bytes; } @Override public String toString() { return encode(); } @Override public int hashCode() { return bytes.duplicate().getInt(); } @Override public boolean equals(Object o) { if (!(o instanceof Fingerprint)) return false; Fingerprint f = (Fingerprint) o; if (!algorithm.getAlgorithm().toLowerCase() .equals(f.algorithm.getAlgorithm().toLowerCase())) return false; if (bytes.compareTo(f.bytes) != 0) return false; return true; } @VisibleForTesting String hex() { return Hex.encodeHexString(bytes.array()); } private Fingerprint(MessageDigest hashAlgorithm, ByteBuffer fingerprintBytes) { this.algorithm = hashAlgorithm; this.bytes = fingerprintBytes; } private MessageDigest algorithm; private ByteBuffer bytes; }
Client/Core/src/main/java/me/footlights/core/crypto/Fingerprint.java
package me.footlights.core.crypto; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import com.google.common.annotations.VisibleForTesting; import me.footlights.HasBytes; import me.footlights.core.Preferences; import me.footlights.core.ConfigurationError; /** A fingerprint for a number of bytes. */ public class Fingerprint { public static Fingerprint decode(String name) throws NoSuchAlgorithmException { String parts[] = name.replaceAll("\\+", "/").split(":"); MessageDigest algorithm = MessageDigest.getInstance(parts[0]); return new Fingerprint(algorithm, ByteBuffer.wrap(Base64.decodeBase64(parts[1]))); } public static Builder newBuilder() { return new Builder(); } public String encode() { StringBuffer sb = new StringBuffer(); sb.append(algorithm.getAlgorithm().toLowerCase()); sb.append(":"); sb.append(new String(Base64.encodeBase64(bytes.array())).replaceAll("/", "+")); return sb.toString(); } public MessageDigest getAlgorithm() { return algorithm; } public boolean matches(ByteBuffer b) { return (0 == bytes.compareTo(b)); } public boolean matches(byte[] b) { return matches(ByteBuffer.wrap(b)); } public ByteBuffer getBytes() { return bytes.asReadOnlyBuffer(); } public byte[] copyBytes() { byte[] copy = new byte[bytes.remaining()]; bytes.get(copy); return copy; } public static class Builder { public Fingerprint build() { ByteBuffer hash = ByteBuffer.wrap(algorithm.digest(bytes)); return new Fingerprint(algorithm, hash); } public Builder setAlgorithm(String a) throws NoSuchAlgorithmException { algorithm = MessageDigest.getInstance(a); return this; } public Builder setContent(byte[] b) { bytes = b; return this; } public Builder setContent(HasBytes h) { return setContent(h.getBytes()); } public Builder setContent(ByteBuffer b) { if (b.isReadOnly()) { bytes = new byte[b.remaining()]; b.get(bytes); } else bytes = b.array(); return this; } private Builder() { try { algorithm = MessageDigest.getInstance( Preferences.getDefaultPreferences().getString("crypto.hash.algorithm")); } catch (NoSuchAlgorithmException e) { throw new ConfigurationError("Invalid hash algorithm: " + e); } } private MessageDigest algorithm; private byte[] bytes; } @Override public boolean equals(Object o) { if (!(o instanceof Fingerprint)) return false; Fingerprint f = (Fingerprint) o; if (!algorithm.getAlgorithm().equals(f.algorithm.getAlgorithm())) return false; if (bytes.compareTo(f.bytes) != 0) return false; return true; } @VisibleForTesting String hex() { return Hex.encodeHexString(bytes.array()); } private Fingerprint(MessageDigest hashAlgorithm, ByteBuffer fingerprintBytes) { this.algorithm = hashAlgorithm; this.bytes = fingerprintBytes; } private MessageDigest algorithm; private ByteBuffer bytes; }
Use Base32, which can be stored in case-insensitive keystores
Client/Core/src/main/java/me/footlights/core/crypto/Fingerprint.java
Use Base32, which can be stored in case-insensitive keystores
Java
apache-2.0
91b253207bd1cbd526fb2fd67611f98a48b7b967
0
gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa
/* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.web; import ae3.dao.GeneSolrDAO; import ae3.model.AtlasGene; import com.google.common.base.Function; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.gxa.dao.AtlasDAO; import uk.ac.ebi.gxa.exceptions.LogUtil; import uk.ac.ebi.gxa.data.AtlasDataDAO; import uk.ac.ebi.gxa.data.AtlasDataException; import uk.ac.ebi.gxa.data.ExperimentWithData; import uk.ac.ebi.microarray.atlas.model.Experiment; import uk.ac.ebi.microarray.atlas.model.ArrayDesign; import uk.ac.ebi.microarray.atlas.model.ExpressionAnalysis; import javax.annotation.Nonnull; import java.io.IOException; import java.util.*; import java.util.regex.Pattern; import static com.google.common.collect.Collections2.transform; import static uk.ac.ebi.gxa.exceptions.LogUtil.createUnexpected; import static uk.ac.ebi.gxa.data.NetCDFPredicates.containsEfEfv; import static uk.ac.ebi.gxa.utils.CollectionUtil.makeMap; public class AtlasPlotter { private AtlasDataDAO atlasDataDAO; private AtlasDAO atlasDatabaseDAO; private GeneSolrDAO geneSolrDAO; private final Logger log = LoggerFactory.getLogger(getClass()); private static final String[] altColors = {"#D8D8D8", "#E8E8E8"}; private static final Pattern startsOrEndsWithDigits = java.util.regex.Pattern.compile("^\\d+|\\d+$"); // This constant is used to prevent empty efvs from being displayed in plots private static final String EMPTY_EFV = "(empty)"; private static final int MAX_POINTS_IN_THUMBNAIL = 500; public void setAtlasDatabaseDAO(AtlasDAO atlasDatabaseDAO) { this.atlasDatabaseDAO = atlasDatabaseDAO; } public void setGeneSolrDAO(GeneSolrDAO geneSolrDAO) { this.geneSolrDAO = geneSolrDAO; } public void setAtlasDataDAO(AtlasDataDAO atlasDataDAO) { this.atlasDataDAO = atlasDataDAO; } public Map<String, Object> getGeneInExpPlotData(final String geneIdKey, final Experiment experiment, final String ef, final String efv, final String plotType) { log.debug("Plotting gene {}, experiment {}, factor {}", new Object[]{geneIdKey, experiment, ef}); try { final List<AtlasGene> genes = parseGenes(geneIdKey); // geneId -> ef -> efv -> ea of best pValue for this geneid-ef-efv combination // Note that ea contains arrayDesign accession and designElement index from which it came, so that // the actual expression values can be easily retrieved later final Collection<Long> geneIds = transform(genes, new Function<AtlasGene, Long>() { public Long apply(@Nonnull AtlasGene input) { return (long) input.getGeneId(); } }); Map<Long, Map<String, Map<String, ExpressionAnalysis>>> geneIdsToEfToEfvToEA = atlasDataDAO.getExpressionAnalysesForGeneIds(experiment, geneIds, containsEfEfv(ef, efv)); if (geneIdsToEfToEfvToEA == null) return null; String efToPlot; if ("default".equals(ef)) { Long geneId = (long) genes.get(0).getGeneId(); // First try to get the highest ranking from top gene efToPlot = getHighestRankEF(geneIdsToEfToEfvToEA.get(geneId)); } else { efToPlot = ef; } if (efToPlot == null) throw LogUtil.createUnexpected("Can't find EF to plot"); if (plotType.equals("thumb")) { AtlasGene geneToPlot = genes.get(0); Long geneId = (long) geneToPlot.getGeneId(); final Map<String, Map<String, ExpressionAnalysis>> geneDetails = geneIdsToEfToEfvToEA.get(geneId); if (geneDetails == null) throw LogUtil.createUnexpected("Can't find analysis data for gene " + geneId); final Map<String, ExpressionAnalysis> analysisForEF = geneDetails.get(efToPlot); if (analysisForEF == null) throw LogUtil.createUnexpected("Can't find analysis data for gene " + geneId + ", " + " EF '" + efToPlot + "'"); ExpressionAnalysis bestEA = analysisForEF.get(efv); if (bestEA == null) throw LogUtil.createUnexpected("Can't find deIndex for min pValue for gene " + geneId + ", " + " EF '" + efToPlot + "', value '" + efv + "'"); return createThumbnailPlot(efToPlot, efv, bestEA, experiment); } else if (plotType.equals("bar")) { AtlasGene geneToPlot = genes.get(0); Long geneId = (long) geneToPlot.getGeneId(); Map<String, ExpressionAnalysis> efvToBestEA = geneIdsToEfToEfvToEA.get(geneId).get(efToPlot); if (!efvToBestEA.isEmpty()) return createBarPlot(geneId, efToPlot, efv, efvToBestEA, experiment); } } catch (AtlasDataException e) { throw createUnexpected("AtlasDataException whilst trying to read from NetCDFs for experiment " + experiment, e); } catch (IOException e) { throw createUnexpected("IOException whilst trying to read from NetCDFs for experiment " + experiment, e); } return null; } private List<AtlasGene> parseGenes(String geneIdKey) { List<AtlasGene> genes = new ArrayList<AtlasGene>(); // lookup gene names, again using SOLR index for (String geneIdStr : geneIdKey.split(",")) { GeneSolrDAO.AtlasGeneResult gene = geneSolrDAO.getGeneById(Long.parseLong(geneIdStr)); if (gene.isFound()) { AtlasGene atlasGene = gene.getGene(); genes.add(atlasGene); } } if (genes.isEmpty()) { throw LogUtil.createUnexpected("No existing genes specified by query: geneIdKey = '" + geneIdKey + "'"); } return genes; } /** * @param eas * @return list of proxy ids in eas */ private List<String> getArrayDesigns(Collection<ExpressionAnalysis> eas) { List<String> adAccessions = new ArrayList<String>(); for (ExpressionAnalysis ea : eas) { adAccessions.add(ea.getArrayDesignAccession()); } return adAccessions; } private String getMostFrequent(List<String> values) { final Set<String> uniqueValues = new HashSet<String>(values); int maxFrequency = 0; String bestValue = null; for (String v : uniqueValues) { final int freq = Collections.frequency(values, v); if (freq > maxFrequency) { bestValue = v; maxFrequency = freq; } } return bestValue; } private static class AssayInfo { private int assayIndex; private Float expression; private AssayInfo(int assayIndex) { this.assayIndex = assayIndex; } public void setExpression(List<Float> expressions) { if (expressions.size() <= assayIndex) { throw new IllegalStateException("No expression for assayIndex: " + assayIndex); } expression = expressions.get(assayIndex); } } private static class FactorValueInfo { private String name; private Boolean isUpOrDown; private Float pValue; private List<AssayInfo> assays = new ArrayList<AssayInfo>(); private boolean isInsignificant; public FactorValueInfo(String name) { this.name = name; } public void addAssayIndex(int assayIndex) { assays.add(new AssayInfo(assayIndex)); } public void setExpressions(List<Float> expressions) { for (AssayInfo assayInfo : assays) { assayInfo.setExpression(expressions); } Collections.sort(assays, new Comparator<AssayInfo>() { public int compare(AssayInfo o1, AssayInfo o2) { return -1 * compareExpressions(o1, o2); } private int compareExpressions(AssayInfo o1, AssayInfo o2) { Float e1 = o1.expression; Float e2 = o2.expression; if (e1 == null && e2 == null) { return 0; } else if (e2 == null) { return 1; } else if (e1 == null) { return -1; } return e1.compareTo(e2); } }); } public void setPValue(float pValue) { this.pValue = pValue; } public void setUpDown(Boolean upDown) { this.isUpOrDown = upDown; } public void setInsignificant(boolean insignificant) { isInsignificant = insignificant; } public boolean isUp() { return this.isUpOrDown != null && this.isUpOrDown; } public boolean isDown() { return this.isUpOrDown != null && !this.isUpOrDown; } public boolean isUpOrDown() { return isUp() || isDown(); } public Float maxValue() { return assays.get(0).expression; } public boolean isEmpty() { return assays.isEmpty(); } public void reduce(double reduceFactor) { int n = (int) Math.floor(reduceFactor * assays.size()); if (n >= assays.size()) { return; } List<AssayInfo> list = new ArrayList<AssayInfo>(); if (n > 0 && !assays.isEmpty()) { float max = assays.get(0).expression; float min = assays.get(assays.size() - 1).expression; float dv = Math.abs((max - min) / n); float v = max; float prevDx = 0; AssayInfo prev = null; for (AssayInfo assay : assays) { float x = assay.expression; float dx = Math.abs(x - v); if (prev != null && dx > prevDx) { list.add(prev); v -= dv; } prevDx = dx; prev = assay; } } assays.clear(); assays.addAll(list); } public int size() { return assays.size(); } } private static class BarPlotDataBuilder { Map<String, FactorValueInfo> fvMap = new HashMap<String, FactorValueInfo>(); private int numberOfValues = 0; public BarPlotDataBuilder(String[] allFactorValues) { for (int i = 0; i < allFactorValues.length; i++) { String factorValue = allFactorValues[i]; if (factorValue.equals(EMPTY_EFV)) { continue; } addFactorValue(factorValue, i); } } private void addFactorValue(String fv, int assayIndex) { FactorValueInfo fvInfo = fvMap.get(fv); if (fvInfo == null) { fvInfo = new FactorValueInfo(fv); fvMap.put(fv, fvInfo); } fvInfo.addAssayIndex(assayIndex); numberOfValues++; } private FactorValueInfo getFvInfo(String fv) { FactorValueInfo fvInfo = fvMap.get(fv); if (fvInfo == null) { throw new IllegalStateException("Factor value: " + fv + " not found in the BarPlotData"); } return fvInfo; } public List<String> getUniqueFactorValues() { List<String> uniqValues = new ArrayList<String>(); uniqValues.addAll(fvMap.keySet()); return uniqValues; } public void removeFactorValue(String fv) { fvMap.remove(fv); } public void setExpressions(String fv, List<Float> expressions) { getFvInfo(fv).setExpressions(expressions); } public void setPValue(String fv, float pValAdjusted) { getFvInfo(fv).setPValue(pValAdjusted); } public void setUpDown(String fv, Boolean upDown) { getFvInfo(fv).setUpDown(upDown); } public void setInsignificant(String fv, boolean b) { getFvInfo(fv).setInsignificant(b); } public Map<String, Object> toSeries(Map<String, Object> addToOptions) { List<FactorValueInfo> list = new ArrayList<FactorValueInfo>(); list.addAll(fvMap.values()); Collections.sort(list, new Comparator<FactorValueInfo>() { public int compare(FactorValueInfo o1, FactorValueInfo o2) { if (o1.isUp() && !o2.isUp()) { return -1; } if (o2.isUp() && !o1.isUp()) { return 1; } if (o1.isDown() && !o2.isDown()) { return -1; } if (o2.isDown() && !o1.isDown()) { return 1; } Float m1 = o1.maxValue(); Float m2 = o2.maxValue(); if (m1 == null && m2 == null) { return 0; } else if (m1 == null) { return 1; } else if (m2 == null) { return -1; } return -1 * m1.compareTo(m2); } }); int totalNumberOfPoints = numberOfValues; ListIterator<FactorValueInfo> iterator = list.listIterator(list.size()); while (totalNumberOfPoints > MAX_POINTS_IN_THUMBNAIL && iterator.hasPrevious()) { FactorValueInfo info = iterator.previous(); if (!info.isUpOrDown()) { iterator.remove(); totalNumberOfPoints -= info.size(); } else { break; } } List<Object> seriesList = new ArrayList<Object>(); List<List<Number>> meanSeriesData = new ArrayList<List<Number>>(); int position = 0; int insignificantSeries = 0; double reduceFactor = totalNumberOfPoints > 0 ? (1.0 * MAX_POINTS_IN_THUMBNAIL) / totalNumberOfPoints : 0.0; for (FactorValueInfo fvInfo : list) { fvInfo.reduce(reduceFactor); if (fvInfo.isEmpty()) { continue; } List<Object> seriesData = new ArrayList<Object>(); double meanValue = 0; int meanCount = 0; int startPosition = position; for (AssayInfo assayInfo : fvInfo.assays) { Float value = assayInfo.expression; // TODO Why -1E+6 threshold is used here? seriesData.add(Arrays.<Number>asList(position++, value <= -1E+6 ? null : value)); if (value > -1E+6) { meanValue += value; meanCount++; } } if (meanCount > 0) { meanValue /= meanCount; meanSeriesData.add(Arrays.<Number>asList(startPosition, meanValue)); meanSeriesData.add(Arrays.<Number>asList(position - 1, meanValue)); } Map<String, Object> series = makeMap( "data", seriesData, "bars", makeMap("show", true, "align", "center", "fill", true), "lines", makeMap("show", false), "points", makeMap("show", false), "label", fvInfo.name, "legend", makeMap("show", true) ); series.put("pvalue", fvInfo.pValue); series.put("expression", (fvInfo.isUp() ? "up" : (fvInfo.isDown() ? "dn" : "no"))); if (!fvInfo.isInsignificant) { series.put("color", altColors[insignificantSeries++ % 2]); series.put("legend", makeMap("show", false)); } seriesList.add(series); } seriesList.add(makeMap( "data", meanSeriesData, "lines", makeMap("show", true, "lineWidth", 1.0, "fill", false), "bars", makeMap("show", false), "points", makeMap("show", false), "color", "#5e5e5e", "label", "Mean", "legend", makeMap("show", false), "hoverable", "false", "shadowSize", 2)); Map<String, Object> options = makeMap( "xaxis", makeMap("ticks", 0), "legend", makeMap("show", true, "position", "sw", "insigLegend", makeMap("show", insignificantSeries > 0), "noColumns", 1), "grid", makeMap( "backgroundColor", "#fafafa", "autoHighlight", false, "hoverable", true, "clickable", true, "borderWidth", 1)); options.putAll(addToOptions); return makeMap( "series", seriesList, "options", options ); } } /** * @param geneId * @param ef experimental factor being plotted * @param efvClickedOn clicked on by the user on gene page. If non-null, its best Expression Analysis * will determine which proxy to draw expression data from. * @param efvToBestEA Map: efv -> best EA, for this ef * All efv keys in this map will be plotted * @return Map key -> value representing a single plot * @throws IOException */ private Map<String, Object> createBarPlot( Long geneId, String ef, String efvClickedOn, final Map<String, ExpressionAnalysis> efvToBestEA, final Experiment experiment) throws IOException, AtlasDataException { if (efvToBestEA.containsKey(EMPTY_EFV)) { // Don't plot (empty) efvs unless they are the only efv that could be plotted efvToBestEA.remove(EMPTY_EFV); } Set<String> efvsToPlot = efvToBestEA.keySet(); log.debug("Creating plot... EF: {}, Top FVs: [{}], Best EAs: [{}]", new Object[]{ef, StringUtils.join(efvsToPlot, ","), efvToBestEA}); final String bestArrayDesignAccession; if (efvClickedOn != null && efvToBestEA.get(efvClickedOn) != null) { // If the user has clicked on an efv, choose to plot expression data from NetCDF proxy in which // the best pValue for this proxy occurred. bestArrayDesignAccession = efvToBestEA.get(efvClickedOn).getArrayDesignAccession(); } else { // The user hasn't clicked on an efv - choose the proxy in most besEA across all efvs bestArrayDesignAccession = getMostFrequent(getArrayDesigns(efvToBestEA.values())); } final ArrayDesign ad = new ArrayDesign(bestArrayDesignAccession); final ExperimentWithData ewd = atlasDataDAO.createExperimentWithData(experiment); try { // Find array design accession for bestProxyId - this will be displayed under the plot String arrayDesignName = atlasDatabaseDAO.getArrayDesignShallowByAccession(bestArrayDesignAccession).getName(); String arrayDesignDescription = bestArrayDesignAccession + (arrayDesignName != null ? " " + arrayDesignName : ""); // Find best pValue expressions for geneId and ef in bestProxyId - it's expression values for these // that will be plotted Map<String, ExpressionAnalysis> bestEAsPerEfvInProxy = atlasDataDAO.getBestEAsPerEfvInProxy(experiment, ad, geneId, ef); BarPlotDataBuilder barPlotData = new BarPlotDataBuilder(ewd.getFactorValues(ad, ef)); for (String factorValue : barPlotData.getUniqueFactorValues()) { ExpressionAnalysis bestEA = bestEAsPerEfvInProxy.get(factorValue); if (bestEA == null) { // If no bestEA expression analysis for factorValue could be found in proxy // (e.g. factorValue is present, but only with pVal == 0) then don't // plot this factorValue for arrayDesign barPlotData.removeFactorValue(factorValue); continue; } // Get the actual expression data from the proxy-designindex corresponding to the best pValue List<Float> expressions = atlasDataDAO.getExpressionData(experiment, ad, bestEA.getDesignElementIndex()); barPlotData.setExpressions(factorValue, expressions); barPlotData.setPValue(factorValue, bestEA.getPValAdjusted()); barPlotData.setUpDown(factorValue, bestEA.isNo() ? null : bestEA.isUp()); barPlotData.setInsignificant(factorValue, efvsToPlot.contains(factorValue)); if (!efvsToPlot.contains(factorValue)) log.debug(experiment + ": Factor value: " + factorValue + " not present in efvsToPlot (" + StringUtils.join(efvsToPlot, ",") + "), " + "flagging this series insignificant"); } Map<String, Object> options = makeMap( "arrayDesign", arrayDesignDescription, "ef", ef); return barPlotData.toSeries(options); } finally { ewd.closeAllDataSources(); } } private Map<String, Object> createThumbnailPlot(String ef, String efv, ExpressionAnalysis ea, Experiment experiment) throws IOException, AtlasDataException { log.debug("Creating thumbnail plot... EF: {}, Top FVs: {}, ExpressionAnalysis: {}", new Object[]{ef, efv, ea}); List<Object> seriesData = new ArrayList<Object>(); int startMark = 0; int endMark = 0; // Get assayFVs from the proxy from which ea came final ArrayDesign arrayDesign = new ArrayDesign(ea.getArrayDesignAccession()); List<String> assayFVs = atlasDataDAO.getFactorValues(experiment, arrayDesign, ef); List<String> uniqueFVs = sortUniqueFVs(assayFVs); // Get actual expression data from the design element stored in ea List<Float> expressions = atlasDataDAO.getExpressionData(experiment, arrayDesign, ea.getDesignElementIndex()); // iterate over each factor value (in sorted order) for (String factorValue : uniqueFVs) { // mark start position, in list of all samples, of the factor value we're after if (factorValue.equals(efv)) { startMark = seriesData.size() + 1; } for (int assayIndex = 0; assayIndex < assayFVs.size(); assayIndex++) if (assayFVs.get(assayIndex).equals(factorValue)) { float value = expressions.get(assayIndex); seriesData.add(Arrays.<Number>asList(seriesData.size() + 1, value <= -1000000 ? null : value)); } // mark end position, in list of all samples, of the factor value we're after if (factorValue.equals(efv)) { endMark = seriesData.size(); } } return makeMap( "series", Collections.singletonList(makeMap( "data", seriesData, "lines", makeMap("show", true, "lineWidth", 2, "fill", false), "legend", makeMap("show", false))), "options", makeMap( "xaxis", makeMap("ticks", 0), "yaxis", makeMap("ticks", 0), "legend", makeMap("show", false), "colors", Collections.singletonList("#edc240"), "grid", makeMap( "backgroundColor", "#f0ffff", "autoHighlight", false, "hoverable", true, "clickable", true, "borderWidth", 1, "markings", Collections.singletonList( makeMap("xaxis", makeMap("from", startMark, "to", endMark), "color", "#F5F5DC")) ), "selection", makeMap("mode", "x") ) ); } private static List<String> sortUniqueFVs(Collection<String> assayFVs) { Set<String> uniqueSet = new HashSet<String>(assayFVs); List<String> uniqueFVs = new ArrayList<String>(uniqueSet); Collections.sort(uniqueFVs, new Comparator<String>() { public int compare(String s1, String s2) { // want to make sure that empty strings are pushed to the back boolean isEmptyS1 = (s1.length() == 0); boolean isEmptyS2 = (s2.length() == 0); if (isEmptyS1 && isEmptyS2) { return 0; } if (isEmptyS1) { return 1; } if (isEmptyS2) { return -1; } java.util.regex.Matcher m1 = startsOrEndsWithDigits.matcher(s1); java.util.regex.Matcher m2 = startsOrEndsWithDigits.matcher(s2); if (m1.find() && m2.find()) { Long i1 = new Long(s1.substring(m1.start(), m1.end())); Long i2 = new Long(s2.substring(m2.start(), m2.end())); int compareRes = i1.compareTo(i2); return (compareRes == 0) ? s1.compareToIgnoreCase(s2) : compareRes; } return s1.compareToIgnoreCase(s2); } }); return uniqueFVs; } /** * @param efToEfvToEA * @return the ef with the lowest pValue from ExpressionAnalyses in efToEfvToEA */ private String getHighestRankEF(Map<String, Map<String, ExpressionAnalysis>> efToEfvToEA) { String bestEf = null; Float bestPValue = null; Float bestTStat = null; for (Map<String, ExpressionAnalysis> efvToEa : efToEfvToEA.values()) { for (ExpressionAnalysis ea : efvToEa.values()) { // lower pVals, or for the same pVals, higher tStats, are better if (bestPValue == null || bestPValue > ea.getPValAdjusted() || (bestPValue == ea.getPValAdjusted() && bestTStat < ea.getTStatistic())) { bestEf = ea.getEfName(); bestPValue = ea.getPValAdjusted(); bestTStat = ea.getTStatistic(); } } } return bestEf; } }
atlas-web/src/main/java/uk/ac/ebi/gxa/web/AtlasPlotter.java
/* * Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.web; import ae3.dao.GeneSolrDAO; import ae3.model.AtlasGene; import com.google.common.base.Function; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.gxa.dao.AtlasDAO; import uk.ac.ebi.gxa.exceptions.LogUtil; import uk.ac.ebi.gxa.data.AtlasDataDAO; import uk.ac.ebi.gxa.data.NetCDFProxy; import uk.ac.ebi.gxa.data.AtlasDataException; import uk.ac.ebi.microarray.atlas.model.Experiment; import uk.ac.ebi.microarray.atlas.model.ArrayDesign; import uk.ac.ebi.microarray.atlas.model.ExpressionAnalysis; import javax.annotation.Nonnull; import java.io.IOException; import java.util.*; import java.util.regex.Pattern; import static com.google.common.collect.Collections2.transform; import static com.google.common.io.Closeables.closeQuietly; import static uk.ac.ebi.gxa.exceptions.LogUtil.createUnexpected; import static uk.ac.ebi.gxa.data.NetCDFPredicates.containsEfEfv; import static uk.ac.ebi.gxa.utils.CollectionUtil.makeMap; public class AtlasPlotter { private AtlasDataDAO atlasDataDAO; private AtlasDAO atlasDatabaseDAO; private GeneSolrDAO geneSolrDAO; private final Logger log = LoggerFactory.getLogger(getClass()); private static final String[] altColors = {"#D8D8D8", "#E8E8E8"}; private static final Pattern startsOrEndsWithDigits = java.util.regex.Pattern.compile("^\\d+|\\d+$"); // This constant is used to prevent empty efvs from being displayed in plots private static final String EMPTY_EFV = "(empty)"; private static final int MAX_POINTS_IN_THUMBNAIL = 500; public void setAtlasDatabaseDAO(AtlasDAO atlasDatabaseDAO) { this.atlasDatabaseDAO = atlasDatabaseDAO; } public void setGeneSolrDAO(GeneSolrDAO geneSolrDAO) { this.geneSolrDAO = geneSolrDAO; } public void setAtlasDataDAO(AtlasDataDAO atlasDataDAO) { this.atlasDataDAO = atlasDataDAO; } public Map<String, Object> getGeneInExpPlotData(final String geneIdKey, final Experiment experiment, final String ef, final String efv, final String plotType) { log.debug("Plotting gene {}, experiment {}, factor {}", new Object[]{geneIdKey, experiment, ef}); try { final List<AtlasGene> genes = parseGenes(geneIdKey); // geneId -> ef -> efv -> ea of best pValue for this geneid-ef-efv combination // Note that ea contains arrayDesign accession and designElement index from which it came, so that // the actual expression values can be easily retrieved later final Collection<Long> geneIds = transform(genes, new Function<AtlasGene, Long>() { public Long apply(@Nonnull AtlasGene input) { return (long) input.getGeneId(); } }); Map<Long, Map<String, Map<String, ExpressionAnalysis>>> geneIdsToEfToEfvToEA = atlasDataDAO.getExpressionAnalysesForGeneIds(experiment, geneIds, containsEfEfv(ef, efv)); if (geneIdsToEfToEfvToEA == null) return null; String efToPlot; if ("default".equals(ef)) { Long geneId = (long) genes.get(0).getGeneId(); // First try to get the highest ranking from top gene efToPlot = getHighestRankEF(geneIdsToEfToEfvToEA.get(geneId)); } else { efToPlot = ef; } if (efToPlot == null) throw LogUtil.createUnexpected("Can't find EF to plot"); if (plotType.equals("thumb")) { AtlasGene geneToPlot = genes.get(0); Long geneId = (long) geneToPlot.getGeneId(); final Map<String, Map<String, ExpressionAnalysis>> geneDetails = geneIdsToEfToEfvToEA.get(geneId); if (geneDetails == null) throw LogUtil.createUnexpected("Can't find analysis data for gene " + geneId); final Map<String, ExpressionAnalysis> analysisForEF = geneDetails.get(efToPlot); if (analysisForEF == null) throw LogUtil.createUnexpected("Can't find analysis data for gene " + geneId + ", " + " EF '" + efToPlot + "'"); ExpressionAnalysis bestEA = analysisForEF.get(efv); if (bestEA == null) throw LogUtil.createUnexpected("Can't find deIndex for min pValue for gene " + geneId + ", " + " EF '" + efToPlot + "', value '" + efv + "'"); return createThumbnailPlot(efToPlot, efv, bestEA, experiment); } else if (plotType.equals("bar")) { AtlasGene geneToPlot = genes.get(0); Long geneId = (long) geneToPlot.getGeneId(); Map<String, ExpressionAnalysis> efvToBestEA = geneIdsToEfToEfvToEA.get(geneId).get(efToPlot); if (!efvToBestEA.isEmpty()) return createBarPlot(geneId, efToPlot, efv, efvToBestEA, experiment); } } catch (AtlasDataException e) { throw createUnexpected("AtlasDataException whilst trying to read from NetCDFs for experiment " + experiment, e); } catch (IOException e) { throw createUnexpected("IOException whilst trying to read from NetCDFs for experiment " + experiment, e); } return null; } private List<AtlasGene> parseGenes(String geneIdKey) { List<AtlasGene> genes = new ArrayList<AtlasGene>(); // lookup gene names, again using SOLR index for (String geneIdStr : geneIdKey.split(",")) { GeneSolrDAO.AtlasGeneResult gene = geneSolrDAO.getGeneById(Long.parseLong(geneIdStr)); if (gene.isFound()) { AtlasGene atlasGene = gene.getGene(); genes.add(atlasGene); } } if (genes.isEmpty()) { throw LogUtil.createUnexpected("No existing genes specified by query: geneIdKey = '" + geneIdKey + "'"); } return genes; } /** * @param eas * @return list of proxy ids in eas */ private List<String> getArrayDesigns(Collection<ExpressionAnalysis> eas) { List<String> adAccessions = new ArrayList<String>(); for (ExpressionAnalysis ea : eas) { adAccessions.add(ea.getArrayDesignAccession()); } return adAccessions; } private String getMostFrequent(List<String> values) { final Set<String> uniqueValues = new HashSet<String>(values); int maxFrequency = 0; String bestValue = null; for (String v : uniqueValues) { final int freq = Collections.frequency(values, v); if (freq > maxFrequency) { bestValue = v; maxFrequency = freq; } } return bestValue; } private static class AssayInfo { private int assayIndex; private Float expression; private AssayInfo(int assayIndex) { this.assayIndex = assayIndex; } public void setExpression(List<Float> expressions) { if (expressions.size() <= assayIndex) { throw new IllegalStateException("No expression for assayIndex: " + assayIndex); } expression = expressions.get(assayIndex); } } private static class FactorValueInfo { private String name; private Boolean isUpOrDown; private Float pValue; private List<AssayInfo> assays = new ArrayList<AssayInfo>(); private boolean isInsignificant; public FactorValueInfo(String name) { this.name = name; } public void addAssayIndex(int assayIndex) { assays.add(new AssayInfo(assayIndex)); } public void setExpressions(List<Float> expressions) { for (AssayInfo assayInfo : assays) { assayInfo.setExpression(expressions); } Collections.sort(assays, new Comparator<AssayInfo>() { public int compare(AssayInfo o1, AssayInfo o2) { return -1 * compareExpressions(o1, o2); } private int compareExpressions(AssayInfo o1, AssayInfo o2) { Float e1 = o1.expression; Float e2 = o2.expression; if (e1 == null && e2 == null) { return 0; } else if (e2 == null) { return 1; } else if (e1 == null) { return -1; } return e1.compareTo(e2); } }); } public void setPValue(float pValue) { this.pValue = pValue; } public void setUpDown(Boolean upDown) { this.isUpOrDown = upDown; } public void setInsignificant(boolean insignificant) { isInsignificant = insignificant; } public boolean isUp() { return this.isUpOrDown != null && this.isUpOrDown; } public boolean isDown() { return this.isUpOrDown != null && !this.isUpOrDown; } public boolean isUpOrDown() { return isUp() || isDown(); } public Float maxValue() { return assays.get(0).expression; } public boolean isEmpty() { return assays.isEmpty(); } public void reduce(double reduceFactor) { int n = (int) Math.floor(reduceFactor * assays.size()); if (n >= assays.size()) { return; } List<AssayInfo> list = new ArrayList<AssayInfo>(); if (n > 0 && !assays.isEmpty()) { float max = assays.get(0).expression; float min = assays.get(assays.size() - 1).expression; float dv = Math.abs((max - min) / n); float v = max; float prevDx = 0; AssayInfo prev = null; for (AssayInfo assay : assays) { float x = assay.expression; float dx = Math.abs(x - v); if (prev != null && dx > prevDx) { list.add(prev); v -= dv; } prevDx = dx; prev = assay; } } assays.clear(); assays.addAll(list); } public int size() { return assays.size(); } } private static class BarPlotDataBuilder { Map<String, FactorValueInfo> fvMap = new HashMap<String, FactorValueInfo>(); private int numberOfValues = 0; public BarPlotDataBuilder(String[] allFactorValues) { for (int i = 0; i < allFactorValues.length; i++) { String factorValue = allFactorValues[i]; if (factorValue.equals(EMPTY_EFV)) { continue; } addFactorValue(factorValue, i); } } private void addFactorValue(String fv, int assayIndex) { FactorValueInfo fvInfo = fvMap.get(fv); if (fvInfo == null) { fvInfo = new FactorValueInfo(fv); fvMap.put(fv, fvInfo); } fvInfo.addAssayIndex(assayIndex); numberOfValues++; } private FactorValueInfo getFvInfo(String fv) { FactorValueInfo fvInfo = fvMap.get(fv); if (fvInfo == null) { throw new IllegalStateException("Factor value: " + fv + " not found in the BarPlotData"); } return fvInfo; } public List<String> getUniqueFactorValues() { List<String> uniqValues = new ArrayList<String>(); uniqValues.addAll(fvMap.keySet()); return uniqValues; } public void removeFactorValue(String fv) { fvMap.remove(fv); } public void setExpressions(String fv, List<Float> expressions) { getFvInfo(fv).setExpressions(expressions); } public void setPValue(String fv, float pValAdjusted) { getFvInfo(fv).setPValue(pValAdjusted); } public void setUpDown(String fv, Boolean upDown) { getFvInfo(fv).setUpDown(upDown); } public void setInsignificant(String fv, boolean b) { getFvInfo(fv).setInsignificant(b); } public Map<String, Object> toSeries(Map<String, Object> addToOptions) { List<FactorValueInfo> list = new ArrayList<FactorValueInfo>(); list.addAll(fvMap.values()); Collections.sort(list, new Comparator<FactorValueInfo>() { public int compare(FactorValueInfo o1, FactorValueInfo o2) { if (o1.isUp() && !o2.isUp()) { return -1; } if (o2.isUp() && !o1.isUp()) { return 1; } if (o1.isDown() && !o2.isDown()) { return -1; } if (o2.isDown() && !o1.isDown()) { return 1; } Float m1 = o1.maxValue(); Float m2 = o2.maxValue(); if (m1 == null && m2 == null) { return 0; } else if (m1 == null) { return 1; } else if (m2 == null) { return -1; } return -1 * m1.compareTo(m2); } }); int totalNumberOfPoints = numberOfValues; ListIterator<FactorValueInfo> iterator = list.listIterator(list.size()); while (totalNumberOfPoints > MAX_POINTS_IN_THUMBNAIL && iterator.hasPrevious()) { FactorValueInfo info = iterator.previous(); if (!info.isUpOrDown()) { iterator.remove(); totalNumberOfPoints -= info.size(); } else { break; } } List<Object> seriesList = new ArrayList<Object>(); List<List<Number>> meanSeriesData = new ArrayList<List<Number>>(); int position = 0; int insignificantSeries = 0; double reduceFactor = totalNumberOfPoints > 0 ? (1.0 * MAX_POINTS_IN_THUMBNAIL) / totalNumberOfPoints : 0.0; for (FactorValueInfo fvInfo : list) { fvInfo.reduce(reduceFactor); if (fvInfo.isEmpty()) { continue; } List<Object> seriesData = new ArrayList<Object>(); double meanValue = 0; int meanCount = 0; int startPosition = position; for (AssayInfo assayInfo : fvInfo.assays) { Float value = assayInfo.expression; // TODO Why -1E+6 threshold is used here? seriesData.add(Arrays.<Number>asList(position++, value <= -1E+6 ? null : value)); if (value > -1E+6) { meanValue += value; meanCount++; } } if (meanCount > 0) { meanValue /= meanCount; meanSeriesData.add(Arrays.<Number>asList(startPosition, meanValue)); meanSeriesData.add(Arrays.<Number>asList(position - 1, meanValue)); } Map<String, Object> series = makeMap( "data", seriesData, "bars", makeMap("show", true, "align", "center", "fill", true), "lines", makeMap("show", false), "points", makeMap("show", false), "label", fvInfo.name, "legend", makeMap("show", true) ); series.put("pvalue", fvInfo.pValue); series.put("expression", (fvInfo.isUp() ? "up" : (fvInfo.isDown() ? "dn" : "no"))); if (!fvInfo.isInsignificant) { series.put("color", altColors[insignificantSeries++ % 2]); series.put("legend", makeMap("show", false)); } seriesList.add(series); } seriesList.add(makeMap( "data", meanSeriesData, "lines", makeMap("show", true, "lineWidth", 1.0, "fill", false), "bars", makeMap("show", false), "points", makeMap("show", false), "color", "#5e5e5e", "label", "Mean", "legend", makeMap("show", false), "hoverable", "false", "shadowSize", 2)); Map<String, Object> options = makeMap( "xaxis", makeMap("ticks", 0), "legend", makeMap("show", true, "position", "sw", "insigLegend", makeMap("show", insignificantSeries > 0), "noColumns", 1), "grid", makeMap( "backgroundColor", "#fafafa", "autoHighlight", false, "hoverable", true, "clickable", true, "borderWidth", 1)); options.putAll(addToOptions); return makeMap( "series", seriesList, "options", options ); } } /** * @param geneId * @param ef experimental factor being plotted * @param efvClickedOn clicked on by the user on gene page. If non-null, its best Expression Analysis * will determine which proxy to draw expression data from. * @param efvToBestEA Map: efv -> best EA, for this ef * All efv keys in this map will be plotted * @return Map key -> value representing a single plot * @throws IOException */ private Map<String, Object> createBarPlot( Long geneId, String ef, String efvClickedOn, final Map<String, ExpressionAnalysis> efvToBestEA, final Experiment experiment) throws IOException, AtlasDataException { if (efvToBestEA.containsKey(EMPTY_EFV)) { // Don't plot (empty) efvs unless they are the only efv that could be plotted efvToBestEA.remove(EMPTY_EFV); } Set<String> efvsToPlot = efvToBestEA.keySet(); log.debug("Creating plot... EF: {}, Top FVs: [{}], Best EAs: [{}]", new Object[]{ef, StringUtils.join(efvsToPlot, ","), efvToBestEA}); final String bestArrayDesignAccession; if (efvClickedOn != null && efvToBestEA.get(efvClickedOn) != null) { // If the user has clicked on an efv, choose to plot expression data from NetCDF proxy in which // the best pValue for this proxy occurred. bestArrayDesignAccession = efvToBestEA.get(efvClickedOn).getArrayDesignAccession(); } else { // The user hasn't clicked on an efv - choose the proxy in most besEA across all efvs bestArrayDesignAccession = getMostFrequent(getArrayDesigns(efvToBestEA.values())); } NetCDFProxy proxy = null; try { final ArrayDesign ad = new ArrayDesign(bestArrayDesignAccession); proxy = atlasDataDAO.getNetCDFDescriptor(experiment, ad).createProxy(); // Find array design accession for bestProxyId - this will be displayed under the plot String arrayDesignName = atlasDatabaseDAO.getArrayDesignShallowByAccession(bestArrayDesignAccession).getName(); String arrayDesignDescription = bestArrayDesignAccession + (arrayDesignName != null ? " " + arrayDesignName : ""); // Find best pValue expressions for geneId and ef in bestProxyId - it's expression values for these // that will be plotted Map<String, ExpressionAnalysis> bestEAsPerEfvInProxy = atlasDataDAO.getBestEAsPerEfvInProxy(experiment, ad, geneId, ef); BarPlotDataBuilder barPlotData = new BarPlotDataBuilder(proxy.getFactorValues(ef)); for (String factorValue : barPlotData.getUniqueFactorValues()) { ExpressionAnalysis bestEA = bestEAsPerEfvInProxy.get(factorValue); if (bestEA == null) { // If no bestEA expression analysis for factorValue could be found in proxy // (e.g. factorValue is present, but only with pVal == 0) then don't // plot this factorValue for arrayDesign barPlotData.removeFactorValue(factorValue); continue; } // Get the actual expression data from the proxy-designindex corresponding to the best pValue List<Float> expressions = atlasDataDAO.getExpressionData(experiment, ad, bestEA.getDesignElementIndex()); barPlotData.setExpressions(factorValue, expressions); barPlotData.setPValue(factorValue, bestEA.getPValAdjusted()); barPlotData.setUpDown(factorValue, bestEA.isNo() ? null : bestEA.isUp()); barPlotData.setInsignificant(factorValue, efvsToPlot.contains(factorValue)); if (!efvsToPlot.contains(factorValue)) log.debug(experiment + ": Factor value: " + factorValue + " not present in efvsToPlot (" + StringUtils.join(efvsToPlot, ",") + "), " + "flagging this series insignificant"); } Map<String, Object> options = makeMap( "arrayDesign", arrayDesignDescription, "ef", ef); return barPlotData.toSeries(options); } finally { closeQuietly(proxy); } } private Map<String, Object> createThumbnailPlot(String ef, String efv, ExpressionAnalysis ea, Experiment experiment) throws IOException, AtlasDataException { log.debug("Creating thumbnail plot... EF: {}, Top FVs: {}, ExpressionAnalysis: {}", new Object[]{ef, efv, ea}); List<Object> seriesData = new ArrayList<Object>(); int startMark = 0; int endMark = 0; // Get assayFVs from the proxy from which ea came final ArrayDesign arrayDesign = new ArrayDesign(ea.getArrayDesignAccession()); List<String> assayFVs = atlasDataDAO.getFactorValues(experiment, arrayDesign, ef); List<String> uniqueFVs = sortUniqueFVs(assayFVs); // Get actual expression data from the design element stored in ea List<Float> expressions = atlasDataDAO.getExpressionData(experiment, arrayDesign, ea.getDesignElementIndex()); // iterate over each factor value (in sorted order) for (String factorValue : uniqueFVs) { // mark start position, in list of all samples, of the factor value we're after if (factorValue.equals(efv)) { startMark = seriesData.size() + 1; } for (int assayIndex = 0; assayIndex < assayFVs.size(); assayIndex++) if (assayFVs.get(assayIndex).equals(factorValue)) { float value = expressions.get(assayIndex); seriesData.add(Arrays.<Number>asList(seriesData.size() + 1, value <= -1000000 ? null : value)); } // mark end position, in list of all samples, of the factor value we're after if (factorValue.equals(efv)) { endMark = seriesData.size(); } } return makeMap( "series", Collections.singletonList(makeMap( "data", seriesData, "lines", makeMap("show", true, "lineWidth", 2, "fill", false), "legend", makeMap("show", false))), "options", makeMap( "xaxis", makeMap("ticks", 0), "yaxis", makeMap("ticks", 0), "legend", makeMap("show", false), "colors", Collections.singletonList("#edc240"), "grid", makeMap( "backgroundColor", "#f0ffff", "autoHighlight", false, "hoverable", true, "clickable", true, "borderWidth", 1, "markings", Collections.singletonList( makeMap("xaxis", makeMap("from", startMark, "to", endMark), "color", "#F5F5DC")) ), "selection", makeMap("mode", "x") ) ); } private static List<String> sortUniqueFVs(Collection<String> assayFVs) { Set<String> uniqueSet = new HashSet<String>(assayFVs); List<String> uniqueFVs = new ArrayList<String>(uniqueSet); Collections.sort(uniqueFVs, new Comparator<String>() { public int compare(String s1, String s2) { // want to make sure that empty strings are pushed to the back boolean isEmptyS1 = (s1.length() == 0); boolean isEmptyS2 = (s2.length() == 0); if (isEmptyS1 && isEmptyS2) { return 0; } if (isEmptyS1) { return 1; } if (isEmptyS2) { return -1; } java.util.regex.Matcher m1 = startsOrEndsWithDigits.matcher(s1); java.util.regex.Matcher m2 = startsOrEndsWithDigits.matcher(s2); if (m1.find() && m2.find()) { Long i1 = new Long(s1.substring(m1.start(), m1.end())); Long i2 = new Long(s2.substring(m2.start(), m2.end())); int compareRes = i1.compareTo(i2); return (compareRes == 0) ? s1.compareToIgnoreCase(s2) : compareRes; } return s1.compareToIgnoreCase(s2); } }); return uniqueFVs; } /** * @param efToEfvToEA * @return the ef with the lowest pValue from ExpressionAnalyses in efToEfvToEA */ private String getHighestRankEF(Map<String, Map<String, ExpressionAnalysis>> efToEfvToEA) { String bestEf = null; Float bestPValue = null; Float bestTStat = null; for (Map<String, ExpressionAnalysis> efvToEa : efToEfvToEA.values()) { for (ExpressionAnalysis ea : efvToEa.values()) { // lower pVals, or for the same pVals, higher tStats, are better if (bestPValue == null || bestPValue > ea.getPValAdjusted() || (bestPValue == ea.getPValAdjusted() && bestTStat < ea.getTStatistic())) { bestEf = ea.getEfName(); bestPValue = ea.getPValAdjusted(); bestTStat = ea.getTStatistic(); } } } return bestEf; } }
NetCDFProxy => ExperimentWithData
atlas-web/src/main/java/uk/ac/ebi/gxa/web/AtlasPlotter.java
NetCDFProxy => ExperimentWithData
Java
apache-2.0
eb3647661051a461d5842bcc7f8b6617fe5b41e6
0
konradxyz/cloudify-manager,konradxyz/dev_fileserver,cloudify-cosmo/cloudify-manager,cloudify-cosmo/cloudify-manager,geokala/cloudify-manager,konradxyz/cloudify-manager,codilime/cloudify-manager,cloudify-cosmo/cloudify-manager,geokala/cloudify-manager,konradxyz/dev_fileserver,isaac-s/cloudify-manager,codilime/cloudify-manager,codilime/cloudify-manager,isaac-s/cloudify-manager,isaac-s/cloudify-manager
/******************************************************************************* * Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.cloudifysource.cosmo.cep; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import org.cloudifysource.cosmo.logging.Logger; import org.cloudifysource.cosmo.logging.LoggerFactory; import org.cloudifysource.cosmo.messaging.consumer.MessageConsumer; import org.cloudifysource.cosmo.messaging.consumer.MessageConsumerListener; import org.cloudifysource.cosmo.messaging.producer.MessageProducer; import org.drools.KnowledgeBase; import org.drools.KnowledgeBaseConfiguration; import org.drools.KnowledgeBaseFactory; import org.drools.builder.KnowledgeBuilder; import org.drools.builder.KnowledgeBuilderError; import org.drools.builder.KnowledgeBuilderFactory; import org.drools.builder.ResourceType; import org.drools.conf.EventProcessingOption; import org.drools.definition.KnowledgePackage; import org.drools.io.Resource; import org.drools.runtime.Channel; import org.drools.runtime.KnowledgeSessionConfiguration; import org.drools.runtime.StatefulKnowledgeSession; import org.drools.runtime.conf.ClockTypeOption; import org.drools.runtime.rule.WorkingMemoryEntryPoint; import org.drools.time.SessionClock; import java.net.URI; import java.util.Collection; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Consumes event from message broker, processes events with Drools and * produces new events back to message broker. * @author itaif * @since 0.1 */ public class ResourceMonitorServer { private URI inputUri; private URI outputUri; private boolean pseudoClock; private final MessageProducer producer; private final MessageConsumer consumer; private StatefulKnowledgeSession ksession; private WorkingMemoryEntryPoint entryPoint; private final Resource droolsResource; private final ExecutorService executorService; private Future<Void> future; private Logger logger = LoggerFactory.getLogger(this.getClass()); private MessageConsumerListener<MonitoringMessage> listener; public ResourceMonitorServer(ResourceMonitorServerConfiguration config) { inputUri = config.getInputUri(); Preconditions.checkNotNull(inputUri); outputUri = config.getOutputUri(); Preconditions.checkNotNull(outputUri); pseudoClock = config.isPseudoClock(); droolsResource = config.getDroolsResource(); Preconditions.checkNotNull(droolsResource); executorService = Executors.newSingleThreadExecutor(); Preconditions.checkNotNull(executorService); producer = new MessageProducer(); consumer = new MessageConsumer(); } public void start() { initDrools(); initEntryPoint(); initExitChannel(); future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { ksession.fireUntilHalt(); return null; } }); } public void stop() { if (listener != null) { consumer.removeListener(listener); } destroyDrools(); executorService.shutdownNow(); } private void initDrools() { KnowledgeBaseConfiguration kbaseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); // Stream mode allows interacting with the clock (Drools Fusion) kbaseConfig.setOption(EventProcessingOption.STREAM); KnowledgeBase kbase = newKnowledgeBase(kbaseConfig); // start session KnowledgeSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); if (pseudoClock) { sessionConfig.setOption(ClockTypeOption.get("pseudo")); } else { sessionConfig.setOption(ClockTypeOption.get("realtime")); } ksession = kbase.newStatefulKnowledgeSession(sessionConfig, null); } private KnowledgeBase newKnowledgeBase(KnowledgeBaseConfiguration config) { KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(config); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); // parse and compile drl kbuilder.add(droolsResource, ResourceType.DRL); if (kbuilder.hasErrors()) { throw toException(kbuilder.getErrors()); } // add the compiled packages to a knowledgebase Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); kbase.addKnowledgePackages(pkgs); return kbase; } private void initExitChannel() { Channel exitChannel = new Channel() { @Override public void send(Object object) { producer.send(outputUri, object); } }; ksession.registerChannel("output", exitChannel); } private void initEntryPoint() { Collection<? extends WorkingMemoryEntryPoint> entryPoints = ksession.getWorkingMemoryEntryPoints(); //TODO: Disable drools auto creation of entry points when it reads DRL file. if (entryPoints.size() > 1) { throw new IllegalArgumentException("DRL file must use default entry point"); } entryPoint = Iterables.getOnlyElement(entryPoints); listener = new MessageConsumerListener<MonitoringMessage>() { @Override public void onMessage(URI uri, MonitoringMessage message) { entryPoint.insert(message); } @Override public void onFailure(Throwable t) { ResourceMonitorServer.this.onConsumerFailure(t); } @Override public Class<? extends MonitoringMessage> getMessageClass() { return MonitoringMessage.class; } }; consumer.addListener(inputUri, listener); } private void onConsumerFailure(Throwable t) { //TODO: Replace with official info logging: logger.debug("Failed to consume events", t); } public void destroyDrools() { if (ksession != null) { ksession.halt(); ksession.dispose(); } } public IllegalStateException toException(Iterable<KnowledgeBuilderError> droolsErrors) { return new IllegalStateException("Drools errors: " + Joiner.on(",").join( Iterables.transform(droolsErrors, new Function<KnowledgeBuilderError, String>() { @Override public String apply(KnowledgeBuilderError input) { return input == null ? "" : input.getMessage(); } }))); } /** * Used by tests in order to increment pseudo clock */ public SessionClock getClock() { return ksession.getSessionClock(); } }
resource-monitor/src/main/java/org/cloudifysource/cosmo/cep/ResourceMonitorServer.java
/******************************************************************************* * Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.cloudifysource.cosmo.cep; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import org.cloudifysource.cosmo.logging.Logger; import org.cloudifysource.cosmo.logging.LoggerFactory; import org.cloudifysource.cosmo.messaging.consumer.MessageConsumer; import org.cloudifysource.cosmo.messaging.consumer.MessageConsumerListener; import org.cloudifysource.cosmo.messaging.producer.MessageProducer; import org.drools.KnowledgeBase; import org.drools.KnowledgeBaseConfiguration; import org.drools.KnowledgeBaseFactory; import org.drools.builder.KnowledgeBuilder; import org.drools.builder.KnowledgeBuilderError; import org.drools.builder.KnowledgeBuilderFactory; import org.drools.builder.ResourceType; import org.drools.conf.EventProcessingOption; import org.drools.definition.KnowledgePackage; import org.drools.io.Resource; import org.drools.runtime.Channel; import org.drools.runtime.KnowledgeSessionConfiguration; import org.drools.runtime.StatefulKnowledgeSession; import org.drools.runtime.conf.ClockTypeOption; import org.drools.runtime.rule.WorkingMemoryEntryPoint; import org.drools.time.SessionClock; import java.net.URI; import java.util.Collection; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * Consumes event from message broker, processes events with Drools and * produces new events back to message broker. * @author itaif * @since 0.1 */ public class ResourceMonitorServer { private URI inputUri; private URI outputUri; private boolean pseudoClock; private final MessageProducer producer; private final MessageConsumer consumer; private StatefulKnowledgeSession ksession; private WorkingMemoryEntryPoint entryPoint; private final Resource droolsResource; private final ExecutorService executorService; private Future<Void> future; private Logger logger = LoggerFactory.getLogger(this.getClass()); private MessageConsumerListener<MonitoringMessage> listener; public ResourceMonitorServer(ResourceMonitorServerConfiguration config) { inputUri = config.getInputUri(); Preconditions.checkNotNull(inputUri); outputUri = config.getOutputUri(); Preconditions.checkNotNull(outputUri); pseudoClock = config.isPseudoClock(); droolsResource = config.getDroolsResource(); Preconditions.checkNotNull(droolsResource); executorService = Executors.newSingleThreadExecutor(); Preconditions.checkNotNull(executorService); producer = new MessageProducer(); consumer = new MessageConsumer(); } public void start() { initDrools(); initEntryPoint(); initExitChannel(); future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { ksession.fireUntilHalt(); return null; } }); } public void stop() { if (listener != null) { consumer.removeListener(listener); } destroyDrools(); executorService.shutdownNow(); } private void initDrools() { KnowledgeBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); // Stream mode allows interacting with the clock (Drools Fusion) config.setOption(EventProcessingOption.STREAM); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(config); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); // parse and compile drl kbuilder.add(droolsResource, ResourceType.DRL); if (kbuilder.hasErrors()) { throw toException(kbuilder.getErrors()); } // add the compiled packages to a knowledgebase Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages(); kbase.addKnowledgePackages(pkgs); // start session KnowledgeSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); if (pseudoClock) { conf.setOption(ClockTypeOption.get("pseudo")); } else { conf.setOption(ClockTypeOption.get("realtime")); } ksession = kbase.newStatefulKnowledgeSession(conf, null); } private void initExitChannel() { Channel exitChannel = new Channel() { @Override public void send(Object object) { producer.send(outputUri, object); } }; ksession.registerChannel("output", exitChannel); } private void initEntryPoint() { Collection<? extends WorkingMemoryEntryPoint> entryPoints = ksession.getWorkingMemoryEntryPoints(); if (entryPoints.size() > 1) { throw new IllegalArgumentException("DRL file must use default entry point"); } entryPoint = Iterables.getOnlyElement(entryPoints); listener = new MessageConsumerListener<MonitoringMessage>() { @Override public void onMessage(URI uri, MonitoringMessage message) { entryPoint.insert(message); } @Override public void onFailure(Throwable t) { ResourceMonitorServer.this.onConsumerFailure(t); } @Override public Class<? extends MonitoringMessage> getMessageClass() { return MonitoringMessage.class; } }; consumer.addListener(inputUri, listener); } private void onConsumerFailure(Throwable t) { //TODO: Replace with official info logging: logger.debug("Failed to consume events", t); } public void destroyDrools() { if (ksession != null) { ksession.halt(); ksession.dispose(); } } public IllegalStateException toException(Iterable<KnowledgeBuilderError> droolsErrors) { return new IllegalStateException("Drools errors: " + Joiner.on(",").join( Iterables.transform(droolsErrors, new Function<KnowledgeBuilderError, String>() { @Override public String apply(KnowledgeBuilderError input) { return input == null ? "" : input.getMessage(); } }))); } public SessionClock getClock() { return ksession.getSessionClock(); } }
Code Review comments
resource-monitor/src/main/java/org/cloudifysource/cosmo/cep/ResourceMonitorServer.java
Code Review comments
Java
apache-2.0
ac60f77d7d45fcd1cc4d38769adf449787228574
0
google/mug,google/mug
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; import static com.google.mu.function.CharPredicate.ALPHA; import static com.google.mu.function.CharPredicate.ANY; import static com.google.mu.function.CharPredicate.ASCII; import static com.google.mu.function.CharPredicate.DIGIT; import static com.google.mu.function.CharPredicate.LOWER_CASE; import static java.lang.Math.max; import static java.util.Objects.requireNonNull; import java.util.Iterator; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.stream.Stream; import com.google.mu.function.CharPredicate; import com.google.mu.util.stream.BiStream; import com.google.mu.util.stream.MoreStreams; /** * Utilities for creating patterns that attempt to match a substring in an input string. The matched * substring can be {@link Pattern#from extracted}, {@link Pattern#removeFrom removed}, {@link * Pattern#replaceFrom replaced}, or used to divide the input string into parts. * * <p>For example, to strip off the "http://" prefix from a uri string if present: * * <pre> * static String stripHttp(String uri) { * return Substring.prefix("http://").removeFrom(uri); * } * </pre> * * To strip off either an "http://" or "https://" prefix if present: * * <pre> * static import com.google.util.Substring.prefix; * * static String stripHttpOrHttps(String uri) { * return prefix("http://").or(prefix("https://")).removeFrom(uri); * } * </pre> * * To strip off a suffix starting with a dash (-) character: * * <pre> * static String stripDashSuffix(String str) { * return last('-').toEnd().removeFrom(str); * } * </pre> * * To replace a trailing "//" with "/": * * <pre> * static String fixTrailingSlash(String str) { * return Substring.suffix("//").replaceFrom(str, '/'); * } * </pre> * * To extract the 'name' and 'value' from an input string in the format of "name:value": * * <pre> * Substring.first(':') * .split("name:joe") * .map(NameValue::new) * .orElseThrow(BadFormatException::new); * </pre> * * To parse key-value pairs: * * <pre>{@code * import static com.google.mu.util.stream.GuavaCollectors.toImmutableListMultimap; * * ImmutableListMultimap<String, String> tags = * first(',') * .repeatedly() * .splitThenTrimKeyValuesAround(first('='), "k1=v1, k2=v2") // => [(k1, v1), (k2, v2)] * .collect(toImmutableListMultimap()); * }</pre> * * @since 2.0 */ public final class Substring { /** {@code Pattern} that never matches any substring. */ public static final Pattern NONE = new Pattern() { @Override Match match(String s, int fromIndex) { requireNonNull(s); return null; } @Override public String toString() { return "NONE"; } }; /** * {@code Pattern} that matches the empty substring at the beginning of the input string. * Typically used to represent an optional delimiter. For example, the following pattern matches * the substring after optional "header_name=": * * <pre> * static final Substring.Pattern VALUE = Substring.after(first('=').or(BEGINNING)); * </pre> */ public static final Pattern BEGINNING = new Pattern() { @Override Match match(String str, int fromIndex) { return new Match(str, fromIndex, 0); } @Override public String toString() { return "BEGINNING"; } }; /** * {@code Pattern} that matches the empty substring at the end of the input string. Typically used * to represent an optional delimiter. For example, the following pattern matches the text between * the first occurrence of the string "id=" and the end of that line, or the end of the string: * * <pre> * static final Substring.Pattern ID = * Substring.between(substring("id="), substring("\n").or(END)); * </pre> */ public static final Pattern END = new Pattern() { @Override Match match(String str, int fromIndex) { return new Match(str, str.length(), 0); } @Override public String toString() { return "END"; } }; /** * Returns a {@code Prefix} pattern that matches strings starting with {@code prefix}. * * <p>Typically if you have a {@code String} constant representing a prefix, consider to declare a * {@link Prefix} constant instead. The type is more explicit, and utilitiy methods like {@link * Pattern#removeFrom}, {@link Pattern#from} are easier to discover and use. */ public static Prefix prefix(String prefix) { return new Prefix(requireNonNull(prefix)); } /** * Returns a {@code Prefix} pattern that matches strings starting with {@code prefix}. * * <p>Typically if you have a {@code char} constant representing a prefix, consider to declare a * {@link Prefix} constant instead. The type is more explicit, and utilitiy methods like {@link * Pattern#removeFrom}, {@link Pattern#from} are easier to discover and use. */ public static Prefix prefix(char prefix) { return new Prefix(Character.toString(prefix)); } /** * Returns a {@code Suffix} pattern that matches strings ending with {@code suffix}. * * <p>Typically if you have a {@code String} constant representing a suffix, consider to declare a * {@link Suffix} constant instead. The type is more explicit, and utilitiy methods like {@link * Pattern#removeFrom}, {@link Pattern#from} are easier to discover and use. */ public static Suffix suffix(String suffix) { return new Suffix(requireNonNull(suffix)); } /** * Returns a {@code Suffix} pattern that matches strings ending with {@code suffix}. * * <p>Typically if you have a {@code char} constant representing a suffix, consider to declare a * {@link Suffix} constant instead. The type is more explicit, and utilitiy methods like {@link * Pattern#removeFrom}, {@link Pattern#from} are easier to discover and use. */ public static Suffix suffix(char suffix) { return new Suffix(Character.toString(suffix)); } /** Returns a {@code Pattern} that matches the first occurrence of {@code str}. */ public static Pattern first(String str) { if (str.length() == 1) { return first(str.charAt(0)); } return new Pattern() { @Override Match match(String input, int fromIndex) { int index = input.indexOf(str, fromIndex); return index >= 0 ? new Match(input, index, str.length()) : null; } @Override public String toString() { return "first('" + str + "')"; } }; } /** Returns a {@code Pattern} that matches the first occurrence of {@code character}. */ public static Pattern first(char character) { return new Pattern() { @Override Match match(String input, int fromIndex) { int index = input.indexOf(character, fromIndex); return index >= 0 ? new Match(input, index, 1) : null; } @Override public String toString() { return "first(\'" + character + "\')"; } }; } /** * Returns a {@code Pattern} that matches the first character found by {@code charMatcher}. * * @since 6.0 */ public static Pattern first(CharPredicate charMatcher) { requireNonNull(charMatcher); return new Pattern() { @Override Match match(String input, int fromIndex) { for (int i = fromIndex; i < input.length(); i++) { if (charMatcher.matches(input.charAt(i))) { return new Match(input, i, 1); } } return null; } @Override public String toString() { return "first(" + charMatcher + ")"; } }; } /** * Returns a {@code Pattern} that matches the last character found by {@code charMatcher}. * * @since 6.0 */ public static Pattern last(CharPredicate charMatcher) { requireNonNull(charMatcher); return new Pattern() { @Override Match match(String input, int fromIndex) { for (int i = input.length() - 1; i >= fromIndex; i--) { if (charMatcher.matches(input.charAt(i))) { return new Match(input, i, 1); } } return null; } @Override public String toString() { return "last(" + charMatcher + ")"; } }; } /** * Returns a {@code Pattern} that matches the first occurrence of {@code regexPattern}. * * <p>Unlike {@code str.replaceFirst(regexPattern, replacement)}, * * <pre>first(regexPattern).replaceFrom(str, replacement)</pre> * * treats the {@code replacement} as a literal string, with no special handling of backslash (\) * and dollar sign ($) characters. */ public static Pattern first(java.util.regex.Pattern regexPattern) { return first(regexPattern, 0); } /** * Returns a {@code Pattern} that matches the first occurrence of a word composed of {@code * [a-zA-Z0-9_]} characters. * * @since 6.0 */ public static Pattern word() { return consecutive(CharPredicate.WORD); } /** * Returns a {@code Pattern} that matches the first occurrence of {@code word} that isn't * immediately preceded or followed by another "word" ({@code [a-zA-Z0-9_]}) character. * * <p>For example, if you are looking for an English word "cat" in the string "catchie has a cat", * {@code first("cat")} won't work because it'll match the first three letters of "cathie". * Instead, you should use {@code word("cat")} to skip over "cathie". * * <p>If your word boundary isn't equivalent to the regex {@code \W} character class, you can * define your own word boundary {@code CharMatcher} and then use {@link Pattern#withBoundary} * instead. Say, if your word is lower-case alpha with dash ('-'), then: * * <pre>{@code * CharMatcher boundary = CharMatcher.inRange('a', 'z').or(CharMatcher.is('-')).negate(); * Substring.Pattern petFriendly = first("pet-friendly").withBoundary(boundary); * }</pre> * * @since 6.0 */ public static Pattern word(String word) { return first(word).withBoundary(CharPredicate.WORD.not()); } /** * Returns a lazy stream of substrings split out from {@code text}, delimited by non-alphanumeric * ascii characters as punctuations, and word boundaries in lowerCamelCase or UpperCamelCase. * * <p>Examples: * * <pre>{@code * splitAsciiByCase("userId") => ["user", "Id"] * splitAsciiByCase("field_name") => ["field", "name"] * splitAsciiByCase("CONSTANT_NAME") => ["CONSTANT", "NAME"] * splitAsciiByCase("dash-case") => ["dash", "case"] * splitAsciiByCase("3 separate words") => ["3", "separate", "words"] * splitAsciiByCase("TheURLs") => ["The", "URLs"] * splitAsciiByCase("UpgradeIPv4ToIPv6") => ["Upgrade", "IPv4", "To", "IPv6"] * }</pre> * * <p>Besides used as word delimiters, non-alphanumeric ascii characters are filtered out from the * returned words. * * <p>Non-ascii characters are not split. Splitting with ascii and non-ascii mixed is best-effort. * * @since 6.0 */ public static Stream<String> splitAsciiByCase(CharSequence text) { CharPredicate punctuation = ASCII.and(ALPHA.or(DIGIT).not()); CharPredicate lowerOrDigit = LOWER_CASE.or(DIGIT); Pattern camelHump = upToIncluding( first(lowerOrDigit).withBoundary(ANY, lowerOrDigit.not()).or(END)); return consecutive(punctuation) .repeatedly() .split(text.toString()) .filter(Match::isNotEmpty) .flatMap(camelHump.repeatedly()::from); } /** * Returns a {@code Pattern} that matches from the beginning of the input string, a non-empty * sequence of leading characters identified by {@code matcher}. * * <p>For example: {@code leading(javaLetter()).from("System.err")} will result in {@code * "System"}. * * <p>It's related to and complements {@link com.google.common.base.CharMatcher#trimLeadingFrom}, * which removes the leading characters instead of extracting them. * * @since 6.0 */ public static Pattern leading(CharPredicate matcher) { requireNonNull(matcher); return new Pattern() { @Override Match match(String input, int fromIndex) { int len = 0; for (int i = fromIndex; i < input.length(); i++, len++) { if (!matcher.matches(input.charAt(i))) { break; } } return len == 0 ? null : new Match(input, fromIndex, len); } @Override public String toString() { return "leading(" + matcher + ")"; } }; } /** * Returns a {@code Pattern} that matches from the end of the input string, a non-empty sequence * of trailing characters identified by {@code matcher}. * * <p>For example: {@code trailing(digit()).from("60612-3588")} will result in {@code "3588"}. * * <p>It's related to and complements {@link CharMatcher#trimTrailingFrom}, which removes the * trailing characters instead of extracting them. * * @since 6.0 */ public static Pattern trailing(CharPredicate matcher) { requireNonNull(matcher); return new Pattern() { @Override Match match(String input, int fromIndex) { int len = 0; for (int i = input.length() - 1; i >= fromIndex; i--, len++) { if (!matcher.matches(input.charAt(i))) { break; } } return len == 0 ? null : new Match(input, input.length() - len, len); } @Override public String toString() { return "trailing(" + matcher + ")"; } }; } /** * Returns a {@code Pattern} that matches the first non-empty sequence of consecutive characters * identified by {@code matcher}. * * <p>For example: {@code consecutive(javaLetter()).from("(System.out)")} will find {@code * "System"}, and {@code consecutive(javaLetter()).repeatedly().from("(System.out)")} will produce * {@code ["System", "out"]}. * * <p>Equivalent to {@code matcher.collapseFrom(string, replacement)}, you can do {@code * consecutive(matcher).repeatedly().replaceAllFrom(string, replacement)}. But you can also do * things other than collapsing these consecutive groups, for example to inspect their values and * replace conditionally: {@code consecutive(matcher).repeatedly().replaceAllFrom(string, group -> * ...)}, or other more sophisticated use cases like building index maps of these sub sequences. * * @since 6.0 */ public static Pattern consecutive(CharPredicate matcher) { requireNonNull(matcher); return new Pattern() { @Override Match match(String input, int fromIndex) { int end = input.length(); for (int i = fromIndex; i < end; i++) { if (matcher.matches(input.charAt(i))) { int len = 1; for (int j = i + 1; j < end; j++, len++) { if (!matcher.matches(input.charAt(j))) { break; } } return new Match(input, i, len); } } return null; } @Override public String toString() { return "consecutive(" + matcher + ")"; } }; } /** * Returns a repeating pattern representing all the top-level groups from {@code regexPattern}. * If {@code regexPattern} has no capture group, the entire pattern is considered the only group. * * <p>For example, {@code topLevelGroups(compile("(g+)(o+)")).from("ggooo")} will return * {@code ["gg", "ooo"]}. * * <p>Nested capture groups are not taken into account. For example: {@code * topLevelGroups(compile("((foo)+(bar)*)(zoo)")).from("foofoobarzoo")} will return * {@code ["foofoobar", "zoo"]}. * * <p>Note that the top-level groups are statically determined by the {@code regexPattern}. * Particularly, quantifiers on a capture group do not increase or decrease the number of captured * groups. That is, when matching {@code "(foo)+"} against {@code "foofoofoo"}, there will only * be one top-level group, with {@code "foo"} as the value. * * @since 5.3 */ public static RepeatingPattern topLevelGroups(java.util.regex.Pattern regexPattern) { requireNonNull(regexPattern); return new RepeatingPattern() { @Override public Stream<Match> match(String string) { Matcher matcher = regexPattern.matcher(string); if (!matcher.find()) return Stream.empty(); int groups = matcher.groupCount(); if (groups == 0) { return Stream.of(new Match(string, matcher.start(), matcher.end() - matcher.start())); } else { return MoreStreams.whileNotNull(new Supplier<Match>() { private int next = 0; private int g = 1; @Override public Match get() { for (; g <= groups; g++) { int start = matcher.start(g); int end = matcher.end(g); if (start >= next) { next = end; return new Match(string, start, end - start); } } return null; } }); } } @Override public String toString() { return "topLevelGroups(" + regexPattern + ")"; } }; } /** * Returns a {@code Pattern} that matches the first occurrence of {@code regexPattern} and then * selects the capturing group identified by {@code group}. * * <p>For example, the following pattern finds the shard number (12) from a string like {@code * 12-of-99}: * * <pre> * import java.util.regex.Pattern; * * private static final Substring.Pattern SHARD_NUMBER = * Substring.first(Pattern.compile("(\\d+)-of-\\d+"), 1); * </pre> * * @throws IndexOutOfBoundsException if {@code group} is negative or exceeds the number of * capturing groups in {@code regexPattern}. */ public static Pattern first(java.util.regex.Pattern regexPattern, int group) { requireNonNull(regexPattern); if (group < 0 || (group > 0 && group > regexPattern.matcher("").groupCount())) { throw new IndexOutOfBoundsException("Capturing group " + group + " doesn't exist."); } return new Pattern() { @Override Match match(String input, int fromIndex) { Matcher matcher = regexPattern.matcher(input); if (matcher.find(fromIndex)) { int start = matcher.start(group); return new Match(input, start, matcher.end(group) - start); } return null; } @Override public String toString() { return "first(\"" + regexPattern + "\", " + group + ")"; } }; } /** * Returns a {@code Pattern} that matches the first occurrence of {@code stop1}, followed by an * occurrence of {@code stop2}, followed sequentially by occurrences of {@code moreStops} in * order, including any characters between consecutive stops. */ public static Pattern spanningInOrder(String stop1, String stop2, String... moreStops) { Pattern result = first(stop1).extendTo(first(stop2)); for (String stop : moreStops) { result = result.extendTo(first(stop)); } return result; } /** Returns a {@code Pattern} that matches the last occurrence of {@code str}. */ public static Pattern last(String str) { if (str.length() == 1) { return last(str.charAt(0)); } return new Pattern() { @Override Match match(String input, int fromIndex) { int index = input.lastIndexOf(str); return index >= fromIndex ? new Match(input, index, str.length()) : null; } @Override public String toString() { return "last('" + str + "')"; } }; } /** Returns a {@code Pattern} that matches the last occurrence of {@code character}. */ public static Pattern last(char character) { return new Pattern() { @Override Match match(String input, int fromIndex) { int index = input.lastIndexOf(character); return index >= fromIndex ? new Match(input, index, 1) : null; } @Override public String toString() { return "last('" + character + "')"; } }; } /** * Returns a {@code Pattern} that covers the substring before {@code delimiter}. For example: * * <pre> * String file = "/home/path/file.txt"; * String path = Substring.before(last('/')).from(file).orElseThrow(...); * assertThat(path).isEqualTo("/home/path"); * </pre> */ public static Pattern before(Pattern delimiter) { requireNonNull(delimiter); return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = delimiter.match(input, fromIndex); return match == null ? null // For example when matching before(first("//")) against "http://", there should be // only one iteration, which is "http:". If the next scan starts before //, we'd get // an empty string match. : new Match(input, fromIndex, match.startIndex - fromIndex, match.repetitionStartIndex); } @Override public String toString() { return "before(" + delimiter + ")"; } }; } /** * Returns a {@code Pattern} that covers the substring after {@code delimiter}. For example: * * <pre> * String file = "/home/path/file.txt"; * String ext = Substring.after(last('.')).from(file).orElseThrow(...); * assertThat(ext).isEqualTo("txt"); * </pre> */ public static Pattern after(Pattern delimiter) { requireNonNull(delimiter); return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = delimiter.match(input, fromIndex); return match == null ? null : match.following(); } @Override public String toString() { return "after(" + delimiter + ")"; } }; } /** * Returns a {@code Pattern} that will match from the beginning of the original string up to the * substring matched by {@code pattern} <em>inclusively</em>. For example: * * <pre> * String uri = "http://google.com"; * String schemeStripped = upToIncluding(first("://")).removeFrom(uri); * assertThat(schemeStripped).isEqualTo("google.com"); * </pre> * * <p>To match from the start of {@code pattern} to the end of the original string, use {@link * Pattern#toEnd} instead. */ public static Pattern upToIncluding(Pattern pattern) { requireNonNull(pattern); return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = pattern.match(input, fromIndex); return match == null ? null // Do not include the delimiter pattern in the next iteration. : new Match(input, fromIndex, match.endIndex - fromIndex, match.repetitionStartIndex); } @Override public String toString() { return "upToIncluding(" + pattern + ")"; } }; } /** * Returns a {@code Pattern} that will match the substring between the first {@code open} and the * first {@code close} after it. * * <p>If for example you need to find the substring between the first {@code "<-"} and the * <em>last</em> {@code "->"}, use {@code between(first("<-"), last("->"))} instead. * * @since 6.0 */ public static Pattern between(String open, String close) { return between(first(open), first(close)); } /** * Returns a {@code Pattern} that will match the substring between the first {@code open} and the * first {@code close} after it. * * <p>If for example you need to find the substring between the first and the <em>last</em> {@code * '/'}, use {@code between(first('/'), last('/'))} instead. * * @since 6.0 */ public static Pattern between(char open, char close) { return between(first(open), first(close)); } /** * Returns a {@code Pattern} that will match the substring between {@code open} and {@code close}. * For example the following pattern finds the link text in markdown syntax: * * <pre> * private static final Substring.Pattern DEPOT_PATH = * Substring.between(first("//depot/"), last('/')); * assertThat(DEPOT_PATH.from("//depot/google3/foo/bar/baz.txt")).hasValue("google3/foo/bar"); * </pre> */ public static Pattern between(Pattern open, Pattern close) { requireNonNull(open); requireNonNull(close); return new Pattern() { @Override Match match(String input, int fromIndex) { Match left = open.match(input, fromIndex); if (left == null) { return null; } Match right = close.match(input, left.endIndex); if (right == null) { return null; } return new Match( // Include the closing delimiter in the next iteration. This allows delimiters in // patterns like "/foo/bar/baz/" to be treated more intuitively. input, /*startIndex=*/ left.endIndex, /*length=*/ right.startIndex - left.endIndex); } @Override public String toString() { return "between(" + open + ", " + close + ")"; } }; } /** A pattern that can be matched against a string, finding a single substring from it. */ public abstract static class Pattern { /** * Matches this pattern against {@code string}, returning a {@code Match} if successful, or * {@code empty()} otherwise. * * <p>This is useful if you need to call {@link Match} methods, like {@link Match#remove} or * {@link Match#before}. If you just need the matched substring itself, prefer to use {@link * #from} instead. */ public final Optional<Match> in(String string) { return Optional.ofNullable(match(string)); } /** * Matches this pattern against {@code string}, returning the matched substring if successful, * or {@code empty()} otherwise. {@code pattern.from(str)} is equivalent to {@code * pattern.in(str).map(Object::toString)}. * * <p>This is useful if you only need the matched substring itself. Use {@link #in} if you need * to call {@link Match} methods, like {@link Match#remove} or {@link Match#before}. */ public final Optional<String> from(CharSequence string) { return Optional.ofNullable(Objects.toString(match(string.toString()), null)); } /** * Matches this pattern against {@code string}, and returns a copy with the matched substring * removed if successful. Otherwise, returns {@code string} unchanged. */ public final String removeFrom(String string) { Match match = match(string); return match == null ? string : match.remove(); } /** * Returns a new string with the substring matched by {@code this} replaced by {@code * replacement}. Returns {@code string} as-is if a substring is not found. */ public final String replaceFrom(String string, CharSequence replacement) { requireNonNull(replacement); Match match = match(string); return match == null ? string : match.replaceWith(replacement); } /** * Returns a {@code Pattern} that will match from the substring matched by {@code this} to the * end of the input string. For example: * * <pre> * String line = "return foo; // some comment..."; * String commentRemoved = first("//").toEnd().removeFrom(line).trim(); * assertThat(commentRemoved).isEqualTo("return foo;"); * </pre> * * <p>To match from the beginning of the input string to the end of a pattern, use {@link * Substring#upToIncluding} instead. */ public final Pattern toEnd() { Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = base.match(input, fromIndex); return match == null ? null : match.toEnd(); } @Override public String toString() { return base + ".toEnd()"; } }; } /** * Returns a {@code Pattern} that falls back to using {@code that} if {@code this} fails to * match. */ public final Pattern or(Pattern that) { requireNonNull(that); Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = base.match(input, fromIndex); return match == null ? that.match(input, fromIndex) : match; } @Override public String toString() { return base + ".or(" + that + ")"; } }; } /** * Similar to regex lookahead, returns a pattern that matches the {@code following} * pattern after it has matched this pattern. For example {@code first('/').then(first('/'))} * finds the second '/' character. * * @since 5.7 */ public final Pattern then(Pattern following) { requireNonNull(following); Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match preceding = base.match(input, fromIndex); if (preceding == null) { return null; } Match next = following.match(input, preceding.endIndex); if (next == null) { return null; } // Keep the repetitionStartIndex strictly increasing to avoid the next iteration // in repeatedly() to be stuck with no progress. return next.repetitionStartIndex < preceding.repetitionStartIndex ? new Match(input, next.startIndex, next.length(), preceding.repetitionStartIndex) : next; } @Override public String toString() { return base + ".then(" + following + ")"; } }; } /** * Return a {@code Pattern} equivalent to this {@code Pattern}, except it will fail to match * if it's not followed by the {@code following} string. * * <p>Useful in asserting that the current match is followed by the expected keyword. For example: * {@code SCHEME_NAME.peek(":")} returns the URI scheme name. * * <p>Note that unlike regex lookahead, no backtracking is attempted. So {@code * first("foo").peek("bar")} will match "bafoobar" but won't match "foofoobar". * * <p>If you are trying to define a boundary around or after your pattern, consider to use * {@link #withBoundary} if the boundary can be detected by a character. * * @since 6.0 */ public final Pattern peek(String following) { return peek(prefix(following)); } /** * Return a {@code Pattern} equivalent to this {@code Pattern}, except it will fail to match * if the {@code following} pattern can't find a match in the substring after the current match. * * <p>Useful in asserting that the current match is followed by the expected pattern. For example: * {@code SCHEME_NAME.peek(prefix(':'))} returns the URI scheme name. * * <p>Note that unlike regex lookahead, no backtracking is attempted. So {@code * first("foo").peek("bar")} will match "bafoobar" but won't match "foofoobar" because * the first "foo" isn't followed by "bar". * * <p>If you are trying to define a boundary around or after your pattern, consider to use * {@link #withBoundary} if the boundary can be detected by a character. * * @since 6.0 */ public final Pattern peek(Pattern following) { requireNonNull(following); Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match preceding = base.match(input, fromIndex); if (preceding == null) { return null; } return following.match(input, preceding.endIndex) == null ? null : preceding; } @Override public String toString() { return base + ".peek(" + following + ")"; } }; } /** * Returns a {@code Pattern} that matches the first occurrence of this pattern, where the * beginning of the match must either be the beginning of the input, or be preceded by a * boundary character as defined by {@code boundary}; and the end of the match must either be * the end of the input, or be followed by a boundary character as defined by {@code boundary}. * * <p>In other words, whatever {@code boundary} is, the beginning and the end of the input * string are always considered implicit boundary. * * <p>Useful if you are trying to find a word with custom boundaries. To search for words * composed of regex {@code \w} character class, consider using {@link Substring#word} instead. * * @since 6.0 */ public final Pattern withBoundary(CharPredicate boundary) { return withBoundary(boundary, boundary); } /** * Returns a {@code Pattern} that matches the first occurrence of this pattern, where the * beginning of the match must either be the beginning of the input, or be preceded by a * boundary character as defined by {@code boundaryBefore}; and the end of the match must either * be the end of the input, or be followed by a boundary character as defined by {@code * boundaryAfter}. * * <p>In other words, the beginning and the end of the input string are always considered * implicit boundaries. * * <p>Useful if you are trying to find a word with custom boundaries. To search for words * composed of regex {@code \w} character class, consider using {@link Substring#word} instead. * * @since 6.0 */ public final Pattern withBoundary(CharPredicate boundaryBefore, CharPredicate boundaryAfter) { requireNonNull(boundaryBefore); requireNonNull(boundaryAfter); Pattern target = this; return new Pattern() { @Override Match match(String input, int fromIndex) { while (fromIndex <= input.length()) { if (fromIndex > 0 && !boundaryBefore.matches(input.charAt(fromIndex - 1))) { fromIndex++; continue; // The current position cannot possibly be the beginning of match. } Match match = target.match(input, fromIndex); if (match == null) { return null; } if (match.startIndex == fromIndex // Already checked boundaryBefore || boundaryBefore.matches(input.charAt(match.startIndex - 1))) { int boundaryIndex = match.endIndex; if (boundaryIndex >= input.length() || boundaryAfter.matches(input.charAt(boundaryIndex))) { return match; } } // Boundary mismatch, skip the first matched char then try again. fromIndex = match.startIndex + 1; } return null; } @Override public String toString() { return target + ".withBoundary(" + boundaryBefore + ", " + boundaryAfter + ")"; } }; } /** * Returns a {@code Pattern} that asserts that this pattern must <em>not</em> match the input, * in which case an empty match starting at the beginning of the input is returned. * * <p>Useful when combined with {@link #peek} to support negative lookahead. * * <p>Note that {@code pattern.not().not()} isn't equivalent to {@code pattern} because the * result match is empty. * * @since 6.0 */ public final Pattern not() { Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { return base.match(input, fromIndex) == null ? BEGINNING.match(input, fromIndex) : null; } @Override public String toString() { return base + ".not()"; } }; } /** * Matches this pattern and then matches {@code following}. * The result matches from the beginning of this pattern to the end of {@code following}. */ final Pattern extendTo(Pattern following) { requireNonNull(following); Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match preceding = base.match(input, fromIndex); if (preceding == null) { return null; } Match next = following.match(input, preceding.endIndex); if (next == null) { return null; } return new Match( input, preceding.startIndex, next.endIndex - preceding.startIndex, // Keep the repetitionStartIndex strictly increasing to avoid the next iteration // in repeatedly() to be stuck with no progress. Math.max(preceding.repetitionStartIndex, next.repetitionStartIndex)); } @Override public String toString() { return base + ".extendTo(" + following + ")"; } }; } /** * Splits {@code string} into two parts that are separated by this separator pattern. For * example: * * <pre>{@code * Optional<KeyValue> keyValue = first('=').split("name=joe").join(KeyValue::new); * }</pre> * * <p>If you need to trim the key-value pairs, use {@link #splitThenTrim}. * * <p>To split a string into multiple substrings delimited by a delimiter, use {@link #repeatedly}. * * @since 5.0 */ public final BiOptional<String, String> split(CharSequence string) { Match match = match(string.toString()); return match == null ? BiOptional.empty() : BiOptional.of(match.before(), match.after()); } /** * Splits {@code string} into two parts that are separated by this separator pattern, with * leading and trailing whitespaces trimmed. For example: * * <pre>{@code * Optional<KeyValue> keyValue = first('=').splitThenTrim("name = joe ").join(KeyValue::new); * }</pre> * * <p>If you are trying to parse a string to a key-value data structure ({@code Map}, {@code * Multimap} etc.), you can use {@code com.google.common.base.Splitter.MapSplitter} though it's * limited to {@code Map} and doesn't allow duplicate keys: * * <pre>{@code * String toSplit = " x -> y, z-> a "; * Map<String, String> result = Splitter.on(',') * .trimResults() * .withKeyValueSeparator(Splitter.on("->")) * .split(toSplit); * }</pre> * * Alternatively, you can use {@code Substring} to allow duplicate keys and to split into * multimaps or other types: * * <pre>{@code * import static com.google.mu.util.stream.MoreCollectors.mapping; * * String toSplit = " x -> y, z-> a, x -> t "; * ImmutableListMultimap<String, String> result = first(',') * .repeatedly() * .split(toSplit) * .map(first("->")::splitThenTrim) * .collect( * mapping( * kv -> kv.orElseThrow(...), * ImmutableListMultimap::toImmutableListMultimap)); * }</pre> * * <p>To split a string into multiple substrings delimited by a delimiter, use {@link #repeatedly}. * * @since 5.0 */ public final BiOptional<String, String> splitThenTrim(CharSequence string) { Match match = match(string.toString()); return match == null ? BiOptional.empty() : BiOptional.of(match.before().trim(), match.after().trim()); } /** * Returns a {@link RepeatingPattern} that applies this pattern repeatedly against the input * string. That is, after each iteration, the pattern is applied again over the substring after * the match, repeatedly until no match is found. * * @since 5.2 */ public final RepeatingPattern repeatedly() { Pattern repeatable = Pattern.this; return new RepeatingPattern() { @Override public Stream<Match> match(String input) { return MoreStreams.whileNotNull( new Supplier<Match>() { private final int end = input.length(); private int nextIndex = 0; @Override public Match get() { if (nextIndex > end) { return null; } Match match = repeatable.match(input, nextIndex); if (match == null) { return null; } if (match.endIndex == end) { // We've consumed the entire string. nextIndex = Integer.MAX_VALUE; } else if (match.repetitionStartIndex > nextIndex) { nextIndex = match.repetitionStartIndex; } else { throw new IllegalStateException( "Infinite loop detected at " + match.repetitionStartIndex); } return match; } }); } @Override public Stream<Match> split(String string) { if (repeatable.match("") != null) { throw new IllegalStateException("Pattern (" + repeatable + ") cannot be used as delimiter."); } return super.split(string); } @Override public String toString() { return repeatable + ".repeatedly()"; } }; } /** * Matches against {@code string} starting from {@code fromIndex}, and returns null if not * found. */ abstract Match match(String string, int fromIndex); private Match match(String string) { return match(string, 0); } /** * Do not depend on the string representation of Substring, except for subtypes {@link Prefix} * and {@link Suffix} that have an explicitly defined representation. */ @Override public String toString() { return super.toString(); } } /** * A substring pattern to be applied repeatedly on the input string, each time over the remaining * substring after the previous match. * * @since 5.2 */ public abstract static class RepeatingPattern { /** * Applies this pattern against {@code string} and returns a stream of each iteration. * * <p>Iterations happen in strict character encounter order, from the beginning of the input * string to the end, with no overlapping. When a match is found, the next iteration is * guaranteed to be in the substring after the current match. For example, {@code * between(first('/'), first('/')).repeatedly().match("/foo/bar/baz/")} will return {@code * ["foo", "bar", "baz"]}. On the other hand, {@code * after(last('/')).repeatedly().match("/foo/bar")} will only return "bar". * * <p>Pattern matching is lazy and doesn't start until the returned stream is consumed. * * <p>An empty stream is returned if this pattern has no matches in the {@code input} string. */ public abstract Stream<Match> match(String input); /** * Applies this pattern against {@code string} and returns a stream of each iteration. * * <p>Iterations happen in strict character encounter order, from the beginning of the input * string to the end, with no overlapping. When a match is found, the next iteration is * guaranteed to be in the substring after the current match. For example, {@code * between(first('/'), first('/')).repeatedly().from("/foo/bar/baz/")} will return {@code * ["foo", "bar", "baz"]}. On the other hand, {@code * after(last('/')).repeatedly().from("/foo/bar")} will only return "bar". * * <p>Pattern matching is lazy and doesn't start until the returned stream is consumed. * * <p>An empty stream is returned if this pattern has no matches in the {@code input} string. */ public Stream<String> from(CharSequence input) { return match(input.toString()).map(Match::toString); } /** * Returns a new string with all {@link #match matches} of this pattern removed. Returns {@code * string} as is if no match is found. */ public String removeAllFrom(String string) { return replaceAllFrom(string, m -> ""); } /** * Returns a new string with all {@link #match matches} of this pattern replaced by applying * {@code replacementFunction} for each match. * * <p>{@code replacementFunction} must not return null. Returns {@code string} as-is if no match * is found. */ public String replaceAllFrom( String string, Function<? super Match, ? extends CharSequence> replacementFunction) { requireNonNull(replacementFunction); Iterator<Match> matches = match(string).iterator(); if (!matches.hasNext()) { return string; } // Add the chars between the previous and current match. StringBuilder builder = new StringBuilder(string.length()); int index = 0; do { Match match = matches.next(); CharSequence replacement = replacementFunction.apply(match); if (replacement == null) { throw new NullPointerException("No replacement is returned for " + match); } builder .append(string, index, match.startIndex) .append(replacement); index = match.endIndex; } while (matches.hasNext()); // Add the remaining chars return builder.append(string, index, string.length()).toString(); } /** * Returns a stream of {@code Match} objects delimited by every match of this pattern. If this * pattern isn't found in {@code string}, the full string is matched. * * <p>The returned {@code Match} objects are cheap "views" of the matched substring sequences. * Because {@code Match} implements {@code CharSequence}, the returned {@code Match} objects can * be directly passed to {@code CharSequence}-accepting APIs such as {@code * com.google.common.base.CharMatcher.trimFrom()} and {@link Pattern#splitThenTrim} etc. */ public Stream<Match> split(String string) { return MoreStreams.whileNotNull( new Supplier<Match>() { int next = 0; Iterator<Match> it = match(string).iterator(); @Override public Match get() { if (it.hasNext()) { Match delim = it.next(); Match result = new Match(string, next, delim.index() - next); next = delim.endIndex; return result; } if (next >= 0) { Match result = new Match(string, next, string.length() - next); next = -1; return result; } else { return null; } } }); } /** * Returns a stream of {@code Match} objects delimited by every match of this pattern. with * whitespaces trimmed. * * <p>The returned {@code Match} objects are cheap "views" of the matched substring sequences. * Because {@code Match} implements {@code CharSequence}, the returned {@code Match} objects can * be directly passed to {@code CharSequence}-accepting APIs such as {@code * com.google.common.base.CharMatcher.trimFrom()} and {@link Pattern#split} etc. */ public Stream<Match> splitThenTrim(String string) { return split(string).map(Match::trim); } /** * Returns a {@link BiStream} of key value pairs from {@code input}. * * <p>The key-value pairs are delimited by this repeating pattern. * with the key and value separated by {@code keyValueSeparator}. * * <p>Empty parts (including leading and trailing separator) are ignored. * Although whitespaces are not trimmed. For example: * * <pre>{@code * first(',') * .repeatedly() * .splitKeyValuesAround(first('='), "k1=v1,,k2=v2,") * }</pre> * will result in a {@code BiStream} equivalent to {@code [(k1, v1), (k2, v2)]}, * but {@code "k1=v1, ,k2=v2"} will fail to be split due to the whitespace after the first * {@code ','}. * * <p>Non-empty parts where {@code keyValueSeparator} is absent will result in * {@link IllegalArgumentException}. * * <p>For alternative splitting strategies, like, if you want to reject instead of ignoring * empty parts. consider to use {@link #split} and {@link Pattern#split} directly, * such as: * * <pre>{@code * first(',') * .repeatedly() * .split("k1=v1,,k2=v2,") // the redundant ',' will throw IAE * .collect( * GuavaCollectors.toImmutableMap( * m -> first('=').split(m).orElseThrow(...))); * }</pre> * * Or, if you want to ignore unparsable parts: * * <pre>{@code * first(',') * .repeatedly() * .split("k1=v1,k2>v2") // Ignore the unknown "k2>v2" * .map(first('=')::split) * .collect( * MoreCollectors.flatMapping( * BiOptional::stream, * toImmutableMap())); * }</pre> * * @since 5.9 */ public final BiStream<String, String> splitKeyValuesAround( Pattern keyValueSeparator, String input) { requireNonNull(keyValueSeparator); return BiStream.from( split(input) .filter(m -> m.length() > 0) .map(m -> keyValueSeparator .split(m) .orElseThrow( () -> new IllegalArgumentException("Cannot split key values from '" + m + "'")))); } /** * Returns a {@link BiStream} of key value pairs from {@code input}. * * <p>The key-value pairs are delimited by this repeating pattern. * with the key and value separated by {@code keyValueSeparator}. * * <p>All keys and values are trimmed, with empty parts (including leading and trailing * separator) ignored. For example: * * <pre>{@code * first(',') * .repeatedly() * .splitThenTrimKeyValuesAround(first('='), "k1 = v1, , k2=v2,") * }</pre> * will result in a {@code BiStream} equivalent to {@code [(k1, v1), (k2, v2)]}. * * <p>Non-empty parts where {@code keyValueSeparator} is absent will result in * {@link IllegalArgumentException}. * * <p>For alternative splitting strategies, like, if you want to reject instead of ignoring * empty parts. consider to use {@link #split} and {@link Pattern#splitThenTrim} directly, * such as: * * <pre>{@code * first(',') * .repeatedly() * .split("k1 = v1, , k2=v2,") // the redundant ',' will throw IAE * .collect( * GuavaCollectors.toImmutableMap( * m -> first('=').splitThenTrim(m).orElseThrow(...))); * }</pre> * * Or, if you want to ignore unparsable parts: * * <pre>{@code * first(',') * .repeatedly() * .split("k1 = v1, k2 > v2") // Ignore the unknown "k2 > v2" * .map(first('=')::splitThenTrim) * .collect( * MoreCollectors.flatMapping( * BiOptional::stream, * toImmutableMap())); * }</pre> * * @since 5.9 */ public final BiStream<String, String> splitThenTrimKeyValuesAround( Pattern keyValueSeparator, String input) { requireNonNull(keyValueSeparator); return BiStream.from( splitThenTrim(input) .filter(m -> m.length() > 0) .map(m -> keyValueSeparator .splitThenTrim(m) .orElseThrow( () -> new IllegalArgumentException("Cannot split key values from '" + m + "'")))); } RepeatingPattern() {} } /** * An immutable string prefix {@code Pattern} with extra utilities such as {@link * #addToIfAbsent(String)}, {@link #removeFrom(StringBuilder)}, {@link #isIn(CharSequence)} etc. * * <p>Can usually be declared as a constant to save allocation cost. Because {@code Prefix} * implements {@link CharSequence}, it can be used almost interchangeably as a string. You can: * * <ul> * <li>directly prepend a prefix as in {@code HOME_PREFIX + path}; * <li>or prepend it into a {@code StringBuilder}: {@code builder.insert(0, HOME_PREFIX)}; * <li>pass it to any CharSequence-accepting APIs such as {@code * CharMatcher.anyOf(...).matchesAnyOf(MY_PREFIX)}, {@code * Substring.first(':').splitThenTrim(MY_PREFIX)} etc. * </ul> * * @since 4.6 */ public static final class Prefix extends Pattern implements CharSequence { private final String prefix; Prefix(String prefix) { this.prefix = prefix; } /** * Returns true if {@code source} starts with this prefix. * * @since 5.7 */ public boolean isIn(CharSequence source) { if (source instanceof String) { return ((String) source).startsWith(prefix); } int prefixChars = prefix.length(); int existingChars = source.length(); if (existingChars < prefixChars) { return false; } for (int i = 0; i < prefixChars; i++) { if (prefix.charAt(i) != source.charAt(i)) { return false; } } return true; } /** * If {@code string} has this prefix, return it as-is; otherwise, return it with this prefix * prepended. * * @since 4.8 */ public String addToIfAbsent(String string) { return string.startsWith(prefix) ? string : prefix + string; } /** * If {@code builder} does not already have this prefix, prepend this prefix to it. * * @return true if this prefix is prepended * @since 5.7 */ public boolean addToIfAbsent(StringBuilder builder) { boolean shouldAdd = !isIn(builder); if (shouldAdd) { builder.insert(0, prefix); } return shouldAdd; } /** * Removes this prefix from {@code builder} if it starts with the prefix. * * @return true if this prefix is removed * @since 5.7 */ public boolean removeFrom(StringBuilder builder) { boolean present = isIn(builder); if (present) { builder.delete(0, length()); } return present; } /** * Replaces this prefix from {@code builder} with {@code replacement} if it starts with the * prefix. * * @return true if this prefix is replaced * @since 5.7 */ public boolean replaceFrom(StringBuilder builder, CharSequence replacement) { requireNonNull(replacement); boolean present = isIn(builder); if (present) { builder.replace(0, length(), replacement.toString()); } return present; } /** @since 5.7 */ @Override public char charAt(int index) { return prefix.charAt(index); } /** @since 5.7 */ @Override public String subSequence(int start, int end) { return prefix.substring(start, end); } /** * Returns the length of this prefix. * * @since 5.7 */ @Override public int length() { return prefix.length(); } @Override public int hashCode() { return prefix.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof Prefix && prefix.equals(((Prefix) obj).prefix); } /** Returns this prefix string. */ @Override public String toString() { return prefix; } @Override Match match(String input, int fromIndex) { return input.startsWith(prefix, fromIndex) ? new Match(input, fromIndex, prefix.length()) : null; } } /** * An immutable string suffix {@code Pattern} with extra utilities such as {@link * #addToIfAbsent(String)}, {@link #removeFrom(StringBuilder)}, {@link #isIn(CharSequence)} etc. * * <p>Can usually be declared as a constant to save allocation cost. Because {@code Suffix} * implements {@link CharSequence}, it can be used almost interchangeably as a string. You can: * * <ul> * <li>directly append a suffix as in {@code path + SHARD_SUFFIX}; * <li>or append the suffix into a {@code StringBuilder}: {@code builder.append(SHARD_SUFFIX)}}; * <li>pass it to any CharSequence-accepting APIs such as {@code * CharMatcher.anyOf(...).matchesAnyOf(MY_PREFIX)}, {@code * Substring.first(':').splitThenTrim(MY_PREFIX)} etc. * </ul> * * @since 4.6 */ public static final class Suffix extends Pattern implements CharSequence { private final String suffix; Suffix(String suffix) { this.suffix = suffix; } /** * Returns true if {@code source} ends with this suffix. * * @since 5.7 */ public boolean isIn(CharSequence source) { if (source instanceof String) { return ((String) source).endsWith(suffix); } int suffixChars = suffix.length(); int existingChars = source.length(); if (existingChars < suffixChars) { return false; } for (int i = 1; i <= suffixChars; i++) { if (suffix.charAt(suffixChars - i) != source.charAt(existingChars - i)) { return false; } } return true; } /** * If {@code string} has this suffix, return it as-is; otherwise, return it with this suffix * appended. * * @since 4.8 */ public String addToIfAbsent(String string) { return string.endsWith(suffix) ? string : string + suffix; } /** * If {@code builder} does not already have this suffix, append this suffix to it. * * @return true if this suffix is appended * @since 5.7 */ public boolean addToIfAbsent(StringBuilder builder) { boolean shouldAdd = !isIn(builder); if (shouldAdd) { builder.append(suffix); } return shouldAdd; } /** * Removes this suffix from {@code builder} if it ends with the suffix. * * @return true if this suffix is removed * @since 5.7 */ public boolean removeFrom(StringBuilder builder) { boolean present = isIn(builder); if (present) { builder.delete(builder.length() - length(), builder.length()); } return present; } /** * Replaces this suffix from {@code builder} with {@code replacement} if it ends with the * suffix. * * @return true if this suffix is replaced * @since 5.7 */ public boolean replaceFrom(StringBuilder builder, CharSequence replacement) { requireNonNull(replacement); boolean present = isIn(builder); if (present) { builder.replace(builder.length() - length(), builder.length(), replacement.toString()); } return present; } /** @since 5.7 */ @Override public char charAt(int index) { return suffix.charAt(index); } /** @since 5.7 */ @Override public String subSequence(int start, int end) { return suffix.substring(start, end); } /** * Returns the length of this suffix. * * @since 5.7 */ @Override public int length() { return suffix.length(); } /** @since 5.7 */ @Override public int hashCode() { return suffix.hashCode(); } /** @since 5.7 */ @Override public boolean equals(Object obj) { return obj instanceof Suffix && suffix.equals(((Suffix) obj).suffix); } /** Returns this suffix string. */ @Override public String toString() { return suffix; } @Override Match match(String input, int fromIndex) { int index = input.length() - suffix.length(); return index >= fromIndex && input.endsWith(suffix) ? new Match(input, index, suffix.length()) : null; } } /** * The result of successfully matching a {@link Pattern} against a string, providing access to the * {@link #toString matched substring}, to the parts of the string {@link #before before} and * {@link #after after} it, and to copies with the matched substring {@link #remove removed} or * {@link #replaceWith replaced}. * * <p><em>Note:</em> a {@link Match} is a view of the original string and holds a strong reference * to the original string. It's advisable to construct and use a {@code Match} object within the * scope of a method; holding onto a {@code Match} object has the same risk of leaking memory as * holding onto the string it was produced from. */ public static final class Match implements CharSequence { private final String context; private final int startIndex; private final int endIndex; /** * While {@code endIndex} demarcates the matched substring, {@code repetitionStartIndex} points to * the starting point to scan for the succeeding {@link Pattern#iterateIn iteration} of the same * pattern. It's by default equal to {@code endIndex}, but for {@link Substring#before} and * {@link Substring#upToIncluding}, {@code repetitionStartIndex} starts after the delimiters. */ private final int repetitionStartIndex; private Match(String context, int startIndex, int length) { this(context, startIndex, length, startIndex + max(1, length)); } private Match(String context, int startIndex, int length, int repetitionStartIndex) { this.context = context; this.startIndex = startIndex; this.endIndex = startIndex + length; this.repetitionStartIndex = repetitionStartIndex; } /** * Returns the part of the original string before the matched substring. * * <p>{@link #before} and {@link #after} are almost always used together to split a string into * two parts. If you just need the substring before the match, you might want to use {@code * Substring.before(pattern)} instead, because the pattern logic is encoded entirely in the * {@link Pattern} object. For example: * * <pre> * private static final Substring.Pattern DIRECTORY = Substring.before(last("/")); * </pre> */ public String before() { return context.substring(0, startIndex); } /** * Returns the part of the original string before the matched substring. * * <p>{@link #before} and {@link #after} are almost always used together to split a string into * two parts. If you just need the substring after the match, you might want to use {@code * Substring.after(pattern)} instead, because the pattern logic is encoded entirely in the * {@link Pattern} object. For example: * * <pre> * private static final Substring.Pattern LINE_COMMENT = Substring.after(first("//")); * </pre> */ public String after() { return context.substring(endIndex); } /** Return the full string being matched against. */ public String fullString() { return context; } /** * Returns a copy of the original string with the matched substring removed. * * <p>This is equivalent to {@code match.before() + match.after()}. */ public String remove() { // Minimize string concatenation. if (endIndex == context.length()) { return before(); } else if (startIndex == 0) { return after(); } else { return before() + after(); } } /** * Returns a copy of the original string with the matched substring replaced with {@code * replacement}. * * <p>This is equivalent to {@code match.before() + replacement + match.after()}. */ public String replaceWith(CharSequence replacement) { requireNonNull(replacement); return before() + replacement + after(); } /** * Returns true if the match isn't empty. * * @since 6.0 */ public boolean isNotEmpty() { return length() > 0; } /** Return 0-based index of this match in {@link #fullString}. */ public int index() { return startIndex; } /** Returns the length of the matched substring. */ @Override public int length() { return endIndex - startIndex; } /** * {@inheritDoc} * @since 4.6 */ @Override public char charAt(int i) { if (i < 0) { throw new IndexOutOfBoundsException("Invalid index (" + i + ") < 0"); } if (i >= length()) { throw new IndexOutOfBoundsException( "Invalid index (" + i + ") >= length (" + length() + ")"); } return context.charAt(startIndex + i); } /** * Returns a {@link CharSequence} instance which is a sub-range of this {@code Match}. * * <p>For example, if this {@code Match} points to the range of {@code "wood"} from * the {@code "Holywood"} string, calling {@code subSequence(1, 3)} will point to the * range of {@code "oo"} from the original string. * * <p>Can be used to further reduce the matched range manually. * * @since 4.6 */ @Override public CharSequence subSequence(int begin, int end) { if (begin < 0) { throw new IndexOutOfBoundsException("Invalid index: begin (" + begin + ") < 0"); } if (end > length()) { throw new IndexOutOfBoundsException( "Invalid index: end (" + end + ") > length (" + length() + ")"); } if (begin > end) { throw new IndexOutOfBoundsException( "Invalid index: begin (" + begin + ") > end (" + end + ")"); } return new Match(context, startIndex + begin, end - begin); } /** Returns the matched substring. */ @Override public String toString() { return context.substring(startIndex, endIndex); } Match preceding() { return new Match(context, 0, startIndex); } Match following() { return new Match(context, endIndex, context.length() - endIndex); } Match trim() { int left = startIndex; int right = endIndex - 1; while (left <= right) { if (Character.isWhitespace(context.charAt(left))) { left++; continue; } if (Character.isWhitespace(context.charAt(right))) { right--; continue; } break; } int trimmedLength = right - left + 1; return trimmedLength == length() ? this : new Match(context, left, trimmedLength, repetitionStartIndex); } private Match toEnd() { return new Match(context, startIndex, context.length() - startIndex); } } private Substring() {} }
mug/src/main/java/com/google/mu/util/Substring.java
/***************************************************************************** * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package com.google.mu.util; import static com.google.mu.function.CharPredicate.ALPHA; import static com.google.mu.function.CharPredicate.ANY; import static com.google.mu.function.CharPredicate.ASCII; import static com.google.mu.function.CharPredicate.DIGIT; import static com.google.mu.function.CharPredicate.LOWER_CASE; import static java.lang.Math.max; import static java.util.Objects.requireNonNull; import java.util.Iterator; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.stream.Stream; import com.google.mu.function.CharPredicate; import com.google.mu.util.stream.BiStream; import com.google.mu.util.stream.MoreStreams; /** * Utilities for creating patterns that attempt to match a substring in an input string. The matched * substring can be {@link Pattern#from extracted}, {@link Pattern#removeFrom removed}, {@link * Pattern#replaceFrom replaced}, or used to divide the input string into parts. * * <p>For example, to strip off the "http://" prefix from a uri string if present: * * <pre> * static String stripHttp(String uri) { * return Substring.prefix("http://").removeFrom(uri); * } * </pre> * * To strip off either an "http://" or "https://" prefix if present: * * <pre> * static import com.google.util.Substring.prefix; * * static String stripHttpOrHttps(String uri) { * return prefix("http://").or(prefix("https://")).removeFrom(uri); * } * </pre> * * To strip off a suffix starting with a dash (-) character: * * <pre> * static String stripDashSuffix(String str) { * return last('-').toEnd().removeFrom(str); * } * </pre> * * To replace a trailing "//" with "/": * * <pre> * static String fixTrailingSlash(String str) { * return Substring.suffix("//").replaceFrom(str, '/'); * } * </pre> * * To extract the 'name' and 'value' from an input string in the format of "name:value": * * <pre> * Substring.first(':') * .split("name:joe") * .map(NameValue::new) * .orElseThrow(BadFormatException::new); * </pre> * * To parse key-value pairs: * * <pre>{@code * import static com.google.mu.util.stream.GuavaCollectors.toImmutableListMultimap; * * ImmutableListMultimap<String, String> tags = * first(',') * .repeatedly() * .splitThenTrimKeyValuesAround(first('='), "k1=v1, k2=v2") // => [(k1, v1), (k2, v2)] * .collect(toImmutableListMultimap()); * }</pre> * * @since 2.0 */ public final class Substring { /** {@code Pattern} that never matches any substring. */ public static final Pattern NONE = new Pattern() { @Override Match match(String s, int fromIndex) { requireNonNull(s); return null; } @Override public String toString() { return "NONE"; } }; /** * {@code Pattern} that matches the empty substring at the beginning of the input string. * Typically used to represent an optional delimiter. For example, the following pattern matches * the substring after optional "header_name=": * * <pre> * static final Substring.Pattern VALUE = Substring.after(first('=').or(BEGINNING)); * </pre> */ public static final Pattern BEGINNING = new Pattern() { @Override Match match(String str, int fromIndex) { return new Match(str, fromIndex, 0); } @Override public String toString() { return "BEGINNING"; } }; /** * {@code Pattern} that matches the empty substring at the end of the input string. Typically used * to represent an optional delimiter. For example, the following pattern matches the text between * the first occurrence of the string "id=" and the end of that line, or the end of the string: * * <pre> * static final Substring.Pattern ID = * Substring.between(substring("id="), substring("\n").or(END)); * </pre> */ public static final Pattern END = new Pattern() { @Override Match match(String str, int fromIndex) { return new Match(str, str.length(), 0); } @Override public String toString() { return "END"; } }; /** * Returns a {@code Prefix} pattern that matches strings starting with {@code prefix}. * * <p>Typically if you have a {@code String} constant representing a prefix, consider to declare a * {@link Prefix} constant instead. The type is more explicit, and utilitiy methods like {@link * Pattern#removeFrom}, {@link Pattern#from} are easier to discover and use. */ public static Prefix prefix(String prefix) { return new Prefix(requireNonNull(prefix)); } /** * Returns a {@code Prefix} pattern that matches strings starting with {@code prefix}. * * <p>Typically if you have a {@code char} constant representing a prefix, consider to declare a * {@link Prefix} constant instead. The type is more explicit, and utilitiy methods like {@link * Pattern#removeFrom}, {@link Pattern#from} are easier to discover and use. */ public static Prefix prefix(char prefix) { return new Prefix(Character.toString(prefix)); } /** * Returns a {@code Suffix} pattern that matches strings ending with {@code suffix}. * * <p>Typically if you have a {@code String} constant representing a suffix, consider to declare a * {@link Suffix} constant instead. The type is more explicit, and utilitiy methods like {@link * Pattern#removeFrom}, {@link Pattern#from} are easier to discover and use. */ public static Suffix suffix(String suffix) { return new Suffix(requireNonNull(suffix)); } /** * Returns a {@code Suffix} pattern that matches strings ending with {@code suffix}. * * <p>Typically if you have a {@code char} constant representing a suffix, consider to declare a * {@link Suffix} constant instead. The type is more explicit, and utilitiy methods like {@link * Pattern#removeFrom}, {@link Pattern#from} are easier to discover and use. */ public static Suffix suffix(char suffix) { return new Suffix(Character.toString(suffix)); } /** Returns a {@code Pattern} that matches the first occurrence of {@code str}. */ public static Pattern first(String str) { if (str.length() == 1) { return first(str.charAt(0)); } return new Pattern() { @Override Match match(String input, int fromIndex) { int index = input.indexOf(str, fromIndex); return index >= 0 ? new Match(input, index, str.length()) : null; } @Override public String toString() { return "first('" + str + "')"; } }; } /** Returns a {@code Pattern} that matches the first occurrence of {@code character}. */ public static Pattern first(char character) { return new Pattern() { @Override Match match(String input, int fromIndex) { int index = input.indexOf(character, fromIndex); return index >= 0 ? new Match(input, index, 1) : null; } @Override public String toString() { return "first(\'" + character + "\')"; } }; } /** * Returns a {@code Pattern} that matches the first character found by {@code charMatcher}. * * @since 6.0 */ public static Pattern first(CharPredicate charMatcher) { requireNonNull(charMatcher); return new Pattern() { @Override Match match(String input, int fromIndex) { for (int i = fromIndex; i < input.length(); i++) { if (charMatcher.matches(input.charAt(i))) { return new Match(input, i, 1); } } return null; } @Override public String toString() { return "first(" + charMatcher + ")"; } }; } /** * Returns a {@code Pattern} that matches the last character found by {@code charMatcher}. * * @since 6.0 */ public static Pattern last(CharPredicate charMatcher) { requireNonNull(charMatcher); return new Pattern() { @Override Match match(String input, int fromIndex) { for (int i = input.length() - 1; i >= fromIndex; i--) { if (charMatcher.matches(input.charAt(i))) { return new Match(input, i, 1); } } return null; } @Override public String toString() { return "last(" + charMatcher + ")"; } }; } /** * Returns a {@code Pattern} that matches the first occurrence of {@code regexPattern}. * * <p>Unlike {@code str.replaceFirst(regexPattern, replacement)}, * * <pre>first(regexPattern).replaceFrom(str, replacement)</pre> * * treats the {@code replacement} as a literal string, with no special handling of backslash (\) * and dollar sign ($) characters. */ public static Pattern first(java.util.regex.Pattern regexPattern) { return first(regexPattern, 0); } /** * Returns a {@code Pattern} that matches the first occurrence of a word composed of {@code * [a-zA-Z0-9_]} characters. * * @since 6.0 */ public static Pattern word() { return consecutive(CharPredicate.WORD); } /** * Returns a {@code Pattern} that matches the first occurrence of {@code word} that isn't * immediately preceded or followed by another "word" ({@code [a-zA-Z0-9_]}) character. * * <p>For example, if you are looking for an English word "cat" in the string "catchie has a cat", * {@code first("cat")} won't work because it'll match the first three letters of "cathie". * Instead, you should use {@code word("cat")} to skip over "cathie". * * <p>If your word boundary isn't equivalent to the regex {@code \W} character class, you can * define your own word boundary {@code CharMatcher} and then use {@link Pattern#withBoundary} * instead. Say, if your word is lower-case alpha with dash ('-'), then: * * <pre>{@code * CharMatcher boundary = CharMatcher.inRange('a', 'z').or(CharMatcher.is('-')).negate(); * Substring.Pattern petFriendly = first("pet-friendly").withBoundary(boundary); * }</pre> * * @since 6.0 */ public static Pattern word(String word) { return first(word).withBoundary(CharPredicate.WORD.not()); } /** * Returns a lazy stream of substrings split out from {@code text}, delimited by non-alphanumeric * ascii characters as punctuations, and word boundaries in lowerCamelCase or UpperCamelCase. * * <p>Examples: * * <pre>{@code * splitAsciiByCase("userId") => ["user", "ID"] * splitAsciiByCase("field_name") => ["field", "name"] * splitAsciiByCase("CONSTANT_NAME") => ["CONSTANT", "NAME"] * splitAsciiByCase("dash-case") => ["dash", "case"] * splitAsciiByCase("3 separate words") => ["3", "separate", "words"] * splitAsciiByCase("TheURLs") => ["The", "URLs"] * splitAsciiByCase("UpgradeIPv4ToIPv6") => ["Upgrade", "IPv4", "To", "IPv6"] * }</pre> * * <p>Besides used as word delimiters, non-alphanumeric ascii characters are filtered out from the * returned words. * * <p>Non-ascii characters are not split. Splitting with ascii and non-ascii mixed is best-effort. * * @since 6.0 */ public static Stream<String> splitAsciiByCase(CharSequence text) { CharPredicate punctuation = ASCII.and(ALPHA.or(DIGIT).not()); CharPredicate lowerOrDigit = LOWER_CASE.or(DIGIT); Pattern camelHump = upToIncluding( first(lowerOrDigit).withBoundary(ANY, lowerOrDigit.not()).or(END)); return consecutive(punctuation) .repeatedly() .split(text.toString()) .filter(Match::isNotEmpty) .flatMap(camelHump.repeatedly()::from); } /** * Returns a {@code Pattern} that matches from the beginning of the input string, a non-empty * sequence of leading characters identified by {@code matcher}. * * <p>For example: {@code leading(javaLetter()).from("System.err")} will result in {@code * "System"}. * * <p>It's related to and complements {@link com.google.common.base.CharMatcher#trimLeadingFrom}, * which removes the leading characters instead of extracting them. * * @since 6.0 */ public static Pattern leading(CharPredicate matcher) { requireNonNull(matcher); return new Pattern() { @Override Match match(String input, int fromIndex) { int len = 0; for (int i = fromIndex; i < input.length(); i++, len++) { if (!matcher.matches(input.charAt(i))) { break; } } return len == 0 ? null : new Match(input, fromIndex, len); } @Override public String toString() { return "leading(" + matcher + ")"; } }; } /** * Returns a {@code Pattern} that matches from the end of the input string, a non-empty sequence * of trailing characters identified by {@code matcher}. * * <p>For example: {@code trailing(digit()).from("60612-3588")} will result in {@code "3588"}. * * <p>It's related to and complements {@link CharMatcher#trimTrailingFrom}, which removes the * trailing characters instead of extracting them. * * @since 6.0 */ public static Pattern trailing(CharPredicate matcher) { requireNonNull(matcher); return new Pattern() { @Override Match match(String input, int fromIndex) { int len = 0; for (int i = input.length() - 1; i >= fromIndex; i--, len++) { if (!matcher.matches(input.charAt(i))) { break; } } return len == 0 ? null : new Match(input, input.length() - len, len); } @Override public String toString() { return "trailing(" + matcher + ")"; } }; } /** * Returns a {@code Pattern} that matches the first non-empty sequence of consecutive characters * identified by {@code matcher}. * * <p>For example: {@code consecutive(javaLetter()).from("(System.out)")} will find {@code * "System"}, and {@code consecutive(javaLetter()).repeatedly().from("(System.out)")} will produce * {@code ["System", "out"]}. * * <p>Equivalent to {@code matcher.collapseFrom(string, replacement)}, you can do {@code * consecutive(matcher).repeatedly().replaceAllFrom(string, replacement)}. But you can also do * things other than collapsing these consecutive groups, for example to inspect their values and * replace conditionally: {@code consecutive(matcher).repeatedly().replaceAllFrom(string, group -> * ...)}, or other more sophisticated use cases like building index maps of these sub sequences. * * @since 6.0 */ public static Pattern consecutive(CharPredicate matcher) { requireNonNull(matcher); return new Pattern() { @Override Match match(String input, int fromIndex) { int end = input.length(); for (int i = fromIndex; i < end; i++) { if (matcher.matches(input.charAt(i))) { int len = 1; for (int j = i + 1; j < end; j++, len++) { if (!matcher.matches(input.charAt(j))) { break; } } return new Match(input, i, len); } } return null; } @Override public String toString() { return "consecutive(" + matcher + ")"; } }; } /** * Returns a repeating pattern representing all the top-level groups from {@code regexPattern}. * If {@code regexPattern} has no capture group, the entire pattern is considered the only group. * * <p>For example, {@code topLevelGroups(compile("(g+)(o+)")).from("ggooo")} will return * {@code ["gg", "ooo"]}. * * <p>Nested capture groups are not taken into account. For example: {@code * topLevelGroups(compile("((foo)+(bar)*)(zoo)")).from("foofoobarzoo")} will return * {@code ["foofoobar", "zoo"]}. * * <p>Note that the top-level groups are statically determined by the {@code regexPattern}. * Particularly, quantifiers on a capture group do not increase or decrease the number of captured * groups. That is, when matching {@code "(foo)+"} against {@code "foofoofoo"}, there will only * be one top-level group, with {@code "foo"} as the value. * * @since 5.3 */ public static RepeatingPattern topLevelGroups(java.util.regex.Pattern regexPattern) { requireNonNull(regexPattern); return new RepeatingPattern() { @Override public Stream<Match> match(String string) { Matcher matcher = regexPattern.matcher(string); if (!matcher.find()) return Stream.empty(); int groups = matcher.groupCount(); if (groups == 0) { return Stream.of(new Match(string, matcher.start(), matcher.end() - matcher.start())); } else { return MoreStreams.whileNotNull(new Supplier<Match>() { private int next = 0; private int g = 1; @Override public Match get() { for (; g <= groups; g++) { int start = matcher.start(g); int end = matcher.end(g); if (start >= next) { next = end; return new Match(string, start, end - start); } } return null; } }); } } @Override public String toString() { return "topLevelGroups(" + regexPattern + ")"; } }; } /** * Returns a {@code Pattern} that matches the first occurrence of {@code regexPattern} and then * selects the capturing group identified by {@code group}. * * <p>For example, the following pattern finds the shard number (12) from a string like {@code * 12-of-99}: * * <pre> * import java.util.regex.Pattern; * * private static final Substring.Pattern SHARD_NUMBER = * Substring.first(Pattern.compile("(\\d+)-of-\\d+"), 1); * </pre> * * @throws IndexOutOfBoundsException if {@code group} is negative or exceeds the number of * capturing groups in {@code regexPattern}. */ public static Pattern first(java.util.regex.Pattern regexPattern, int group) { requireNonNull(regexPattern); if (group < 0 || (group > 0 && group > regexPattern.matcher("").groupCount())) { throw new IndexOutOfBoundsException("Capturing group " + group + " doesn't exist."); } return new Pattern() { @Override Match match(String input, int fromIndex) { Matcher matcher = regexPattern.matcher(input); if (matcher.find(fromIndex)) { int start = matcher.start(group); return new Match(input, start, matcher.end(group) - start); } return null; } @Override public String toString() { return "first(\"" + regexPattern + "\", " + group + ")"; } }; } /** * Returns a {@code Pattern} that matches the first occurrence of {@code stop1}, followed by an * occurrence of {@code stop2}, followed sequentially by occurrences of {@code moreStops} in * order, including any characters between consecutive stops. */ public static Pattern spanningInOrder(String stop1, String stop2, String... moreStops) { Pattern result = first(stop1).extendTo(first(stop2)); for (String stop : moreStops) { result = result.extendTo(first(stop)); } return result; } /** Returns a {@code Pattern} that matches the last occurrence of {@code str}. */ public static Pattern last(String str) { if (str.length() == 1) { return last(str.charAt(0)); } return new Pattern() { @Override Match match(String input, int fromIndex) { int index = input.lastIndexOf(str); return index >= fromIndex ? new Match(input, index, str.length()) : null; } @Override public String toString() { return "last('" + str + "')"; } }; } /** Returns a {@code Pattern} that matches the last occurrence of {@code character}. */ public static Pattern last(char character) { return new Pattern() { @Override Match match(String input, int fromIndex) { int index = input.lastIndexOf(character); return index >= fromIndex ? new Match(input, index, 1) : null; } @Override public String toString() { return "last('" + character + "')"; } }; } /** * Returns a {@code Pattern} that covers the substring before {@code delimiter}. For example: * * <pre> * String file = "/home/path/file.txt"; * String path = Substring.before(last('/')).from(file).orElseThrow(...); * assertThat(path).isEqualTo("/home/path"); * </pre> */ public static Pattern before(Pattern delimiter) { requireNonNull(delimiter); return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = delimiter.match(input, fromIndex); return match == null ? null // For example when matching before(first("//")) against "http://", there should be // only one iteration, which is "http:". If the next scan starts before //, we'd get // an empty string match. : new Match(input, fromIndex, match.startIndex - fromIndex, match.repetitionStartIndex); } @Override public String toString() { return "before(" + delimiter + ")"; } }; } /** * Returns a {@code Pattern} that covers the substring after {@code delimiter}. For example: * * <pre> * String file = "/home/path/file.txt"; * String ext = Substring.after(last('.')).from(file).orElseThrow(...); * assertThat(ext).isEqualTo("txt"); * </pre> */ public static Pattern after(Pattern delimiter) { requireNonNull(delimiter); return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = delimiter.match(input, fromIndex); return match == null ? null : match.following(); } @Override public String toString() { return "after(" + delimiter + ")"; } }; } /** * Returns a {@code Pattern} that will match from the beginning of the original string up to the * substring matched by {@code pattern} <em>inclusively</em>. For example: * * <pre> * String uri = "http://google.com"; * String schemeStripped = upToIncluding(first("://")).removeFrom(uri); * assertThat(schemeStripped).isEqualTo("google.com"); * </pre> * * <p>To match from the start of {@code pattern} to the end of the original string, use {@link * Pattern#toEnd} instead. */ public static Pattern upToIncluding(Pattern pattern) { requireNonNull(pattern); return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = pattern.match(input, fromIndex); return match == null ? null // Do not include the delimiter pattern in the next iteration. : new Match(input, fromIndex, match.endIndex - fromIndex, match.repetitionStartIndex); } @Override public String toString() { return "upToIncluding(" + pattern + ")"; } }; } /** * Returns a {@code Pattern} that will match the substring between the first {@code open} and the * first {@code close} after it. * * <p>If for example you need to find the substring between the first {@code "<-"} and the * <em>last</em> {@code "->"}, use {@code between(first("<-"), last("->"))} instead. * * @since 6.0 */ public static Pattern between(String open, String close) { return between(first(open), first(close)); } /** * Returns a {@code Pattern} that will match the substring between the first {@code open} and the * first {@code close} after it. * * <p>If for example you need to find the substring between the first and the <em>last</em> {@code * '/'}, use {@code between(first('/'), last('/'))} instead. * * @since 6.0 */ public static Pattern between(char open, char close) { return between(first(open), first(close)); } /** * Returns a {@code Pattern} that will match the substring between {@code open} and {@code close}. * For example the following pattern finds the link text in markdown syntax: * * <pre> * private static final Substring.Pattern DEPOT_PATH = * Substring.between(first("//depot/"), last('/')); * assertThat(DEPOT_PATH.from("//depot/google3/foo/bar/baz.txt")).hasValue("google3/foo/bar"); * </pre> */ public static Pattern between(Pattern open, Pattern close) { requireNonNull(open); requireNonNull(close); return new Pattern() { @Override Match match(String input, int fromIndex) { Match left = open.match(input, fromIndex); if (left == null) { return null; } Match right = close.match(input, left.endIndex); if (right == null) { return null; } return new Match( // Include the closing delimiter in the next iteration. This allows delimiters in // patterns like "/foo/bar/baz/" to be treated more intuitively. input, /*startIndex=*/ left.endIndex, /*length=*/ right.startIndex - left.endIndex); } @Override public String toString() { return "between(" + open + ", " + close + ")"; } }; } /** A pattern that can be matched against a string, finding a single substring from it. */ public abstract static class Pattern { /** * Matches this pattern against {@code string}, returning a {@code Match} if successful, or * {@code empty()} otherwise. * * <p>This is useful if you need to call {@link Match} methods, like {@link Match#remove} or * {@link Match#before}. If you just need the matched substring itself, prefer to use {@link * #from} instead. */ public final Optional<Match> in(String string) { return Optional.ofNullable(match(string)); } /** * Matches this pattern against {@code string}, returning the matched substring if successful, * or {@code empty()} otherwise. {@code pattern.from(str)} is equivalent to {@code * pattern.in(str).map(Object::toString)}. * * <p>This is useful if you only need the matched substring itself. Use {@link #in} if you need * to call {@link Match} methods, like {@link Match#remove} or {@link Match#before}. */ public final Optional<String> from(CharSequence string) { return Optional.ofNullable(Objects.toString(match(string.toString()), null)); } /** * Matches this pattern against {@code string}, and returns a copy with the matched substring * removed if successful. Otherwise, returns {@code string} unchanged. */ public final String removeFrom(String string) { Match match = match(string); return match == null ? string : match.remove(); } /** * Returns a new string with the substring matched by {@code this} replaced by {@code * replacement}. Returns {@code string} as-is if a substring is not found. */ public final String replaceFrom(String string, CharSequence replacement) { requireNonNull(replacement); Match match = match(string); return match == null ? string : match.replaceWith(replacement); } /** * Returns a {@code Pattern} that will match from the substring matched by {@code this} to the * end of the input string. For example: * * <pre> * String line = "return foo; // some comment..."; * String commentRemoved = first("//").toEnd().removeFrom(line).trim(); * assertThat(commentRemoved).isEqualTo("return foo;"); * </pre> * * <p>To match from the beginning of the input string to the end of a pattern, use {@link * Substring#upToIncluding} instead. */ public final Pattern toEnd() { Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = base.match(input, fromIndex); return match == null ? null : match.toEnd(); } @Override public String toString() { return base + ".toEnd()"; } }; } /** * Returns a {@code Pattern} that falls back to using {@code that} if {@code this} fails to * match. */ public final Pattern or(Pattern that) { requireNonNull(that); Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match match = base.match(input, fromIndex); return match == null ? that.match(input, fromIndex) : match; } @Override public String toString() { return base + ".or(" + that + ")"; } }; } /** * Similar to regex lookahead, returns a pattern that matches the {@code following} * pattern after it has matched this pattern. For example {@code first('/').then(first('/'))} * finds the second '/' character. * * @since 5.7 */ public final Pattern then(Pattern following) { requireNonNull(following); Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match preceding = base.match(input, fromIndex); if (preceding == null) { return null; } Match next = following.match(input, preceding.endIndex); if (next == null) { return null; } // Keep the repetitionStartIndex strictly increasing to avoid the next iteration // in repeatedly() to be stuck with no progress. return next.repetitionStartIndex < preceding.repetitionStartIndex ? new Match(input, next.startIndex, next.length(), preceding.repetitionStartIndex) : next; } @Override public String toString() { return base + ".then(" + following + ")"; } }; } /** * Return a {@code Pattern} equivalent to this {@code Pattern}, except it will fail to match * if it's not followed by the {@code following} string. * * <p>Useful in asserting that the current match is followed by the expected keyword. For example: * {@code SCHEME_NAME.peek(":")} returns the URI scheme name. * * <p>Note that unlike regex lookahead, no backtracking is attempted. So {@code * first("foo").peek("bar")} will match "bafoobar" but won't match "foofoobar". * * <p>If you are trying to define a boundary around or after your pattern, consider to use * {@link #withBoundary} if the boundary can be detected by a character. * * @since 6.0 */ public final Pattern peek(String following) { return peek(prefix(following)); } /** * Return a {@code Pattern} equivalent to this {@code Pattern}, except it will fail to match * if the {@code following} pattern can't find a match in the substring after the current match. * * <p>Useful in asserting that the current match is followed by the expected pattern. For example: * {@code SCHEME_NAME.peek(prefix(':'))} returns the URI scheme name. * * <p>Note that unlike regex lookahead, no backtracking is attempted. So {@code * first("foo").peek("bar")} will match "bafoobar" but won't match "foofoobar" because * the first "foo" isn't followed by "bar". * * <p>If you are trying to define a boundary around or after your pattern, consider to use * {@link #withBoundary} if the boundary can be detected by a character. * * @since 6.0 */ public final Pattern peek(Pattern following) { requireNonNull(following); Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match preceding = base.match(input, fromIndex); if (preceding == null) { return null; } return following.match(input, preceding.endIndex) == null ? null : preceding; } @Override public String toString() { return base + ".peek(" + following + ")"; } }; } /** * Returns a {@code Pattern} that matches the first occurrence of this pattern, where the * beginning of the match must either be the beginning of the input, or be preceded by a * boundary character as defined by {@code boundary}; and the end of the match must either be * the end of the input, or be followed by a boundary character as defined by {@code boundary}. * * <p>In other words, whatever {@code boundary} is, the beginning and the end of the input * string are always considered implicit boundary. * * <p>Useful if you are trying to find a word with custom boundaries. To search for words * composed of regex {@code \w} character class, consider using {@link Substring#word} instead. * * @since 6.0 */ public final Pattern withBoundary(CharPredicate boundary) { return withBoundary(boundary, boundary); } /** * Returns a {@code Pattern} that matches the first occurrence of this pattern, where the * beginning of the match must either be the beginning of the input, or be preceded by a * boundary character as defined by {@code boundaryBefore}; and the end of the match must either * be the end of the input, or be followed by a boundary character as defined by {@code * boundaryAfter}. * * <p>In other words, the beginning and the end of the input string are always considered * implicit boundaries. * * <p>Useful if you are trying to find a word with custom boundaries. To search for words * composed of regex {@code \w} character class, consider using {@link Substring#word} instead. * * @since 6.0 */ public final Pattern withBoundary(CharPredicate boundaryBefore, CharPredicate boundaryAfter) { requireNonNull(boundaryBefore); requireNonNull(boundaryAfter); Pattern target = this; return new Pattern() { @Override Match match(String input, int fromIndex) { while (fromIndex <= input.length()) { if (fromIndex > 0 && !boundaryBefore.matches(input.charAt(fromIndex - 1))) { fromIndex++; continue; // The current position cannot possibly be the beginning of match. } Match match = target.match(input, fromIndex); if (match == null) { return null; } if (match.startIndex == fromIndex // Already checked boundaryBefore || boundaryBefore.matches(input.charAt(match.startIndex - 1))) { int boundaryIndex = match.endIndex; if (boundaryIndex >= input.length() || boundaryAfter.matches(input.charAt(boundaryIndex))) { return match; } } // Boundary mismatch, skip the first matched char then try again. fromIndex = match.startIndex + 1; } return null; } @Override public String toString() { return target + ".withBoundary(" + boundaryBefore + ", " + boundaryAfter + ")"; } }; } /** * Returns a {@code Pattern} that asserts that this pattern must <em>not</em> match the input, * in which case an empty match starting at the beginning of the input is returned. * * <p>Useful when combined with {@link #peek} to support negative lookahead. * * <p>Note that {@code pattern.not().not()} isn't equivalent to {@code pattern} because the * result match is empty. * * @since 6.0 */ public final Pattern not() { Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { return base.match(input, fromIndex) == null ? BEGINNING.match(input, fromIndex) : null; } @Override public String toString() { return base + ".not()"; } }; } /** * Matches this pattern and then matches {@code following}. * The result matches from the beginning of this pattern to the end of {@code following}. */ final Pattern extendTo(Pattern following) { requireNonNull(following); Pattern base = this; return new Pattern() { @Override Match match(String input, int fromIndex) { Match preceding = base.match(input, fromIndex); if (preceding == null) { return null; } Match next = following.match(input, preceding.endIndex); if (next == null) { return null; } return new Match( input, preceding.startIndex, next.endIndex - preceding.startIndex, // Keep the repetitionStartIndex strictly increasing to avoid the next iteration // in repeatedly() to be stuck with no progress. Math.max(preceding.repetitionStartIndex, next.repetitionStartIndex)); } @Override public String toString() { return base + ".extendTo(" + following + ")"; } }; } /** * Splits {@code string} into two parts that are separated by this separator pattern. For * example: * * <pre>{@code * Optional<KeyValue> keyValue = first('=').split("name=joe").join(KeyValue::new); * }</pre> * * <p>If you need to trim the key-value pairs, use {@link #splitThenTrim}. * * <p>To split a string into multiple substrings delimited by a delimiter, use {@link #repeatedly}. * * @since 5.0 */ public final BiOptional<String, String> split(CharSequence string) { Match match = match(string.toString()); return match == null ? BiOptional.empty() : BiOptional.of(match.before(), match.after()); } /** * Splits {@code string} into two parts that are separated by this separator pattern, with * leading and trailing whitespaces trimmed. For example: * * <pre>{@code * Optional<KeyValue> keyValue = first('=').splitThenTrim("name = joe ").join(KeyValue::new); * }</pre> * * <p>If you are trying to parse a string to a key-value data structure ({@code Map}, {@code * Multimap} etc.), you can use {@code com.google.common.base.Splitter.MapSplitter} though it's * limited to {@code Map} and doesn't allow duplicate keys: * * <pre>{@code * String toSplit = " x -> y, z-> a "; * Map<String, String> result = Splitter.on(',') * .trimResults() * .withKeyValueSeparator(Splitter.on("->")) * .split(toSplit); * }</pre> * * Alternatively, you can use {@code Substring} to allow duplicate keys and to split into * multimaps or other types: * * <pre>{@code * import static com.google.mu.util.stream.MoreCollectors.mapping; * * String toSplit = " x -> y, z-> a, x -> t "; * ImmutableListMultimap<String, String> result = first(',') * .repeatedly() * .split(toSplit) * .map(first("->")::splitThenTrim) * .collect( * mapping( * kv -> kv.orElseThrow(...), * ImmutableListMultimap::toImmutableListMultimap)); * }</pre> * * <p>To split a string into multiple substrings delimited by a delimiter, use {@link #repeatedly}. * * @since 5.0 */ public final BiOptional<String, String> splitThenTrim(CharSequence string) { Match match = match(string.toString()); return match == null ? BiOptional.empty() : BiOptional.of(match.before().trim(), match.after().trim()); } /** * Returns a {@link RepeatingPattern} that applies this pattern repeatedly against the input * string. That is, after each iteration, the pattern is applied again over the substring after * the match, repeatedly until no match is found. * * @since 5.2 */ public final RepeatingPattern repeatedly() { Pattern repeatable = Pattern.this; return new RepeatingPattern() { @Override public Stream<Match> match(String input) { return MoreStreams.whileNotNull( new Supplier<Match>() { private final int end = input.length(); private int nextIndex = 0; @Override public Match get() { if (nextIndex > end) { return null; } Match match = repeatable.match(input, nextIndex); if (match == null) { return null; } if (match.endIndex == end) { // We've consumed the entire string. nextIndex = Integer.MAX_VALUE; } else if (match.repetitionStartIndex > nextIndex) { nextIndex = match.repetitionStartIndex; } else { throw new IllegalStateException( "Infinite loop detected at " + match.repetitionStartIndex); } return match; } }); } @Override public Stream<Match> split(String string) { if (repeatable.match("") != null) { throw new IllegalStateException("Pattern (" + repeatable + ") cannot be used as delimiter."); } return super.split(string); } @Override public String toString() { return repeatable + ".repeatedly()"; } }; } /** * Matches against {@code string} starting from {@code fromIndex}, and returns null if not * found. */ abstract Match match(String string, int fromIndex); private Match match(String string) { return match(string, 0); } /** * Do not depend on the string representation of Substring, except for subtypes {@link Prefix} * and {@link Suffix} that have an explicitly defined representation. */ @Override public String toString() { return super.toString(); } } /** * A substring pattern to be applied repeatedly on the input string, each time over the remaining * substring after the previous match. * * @since 5.2 */ public abstract static class RepeatingPattern { /** * Applies this pattern against {@code string} and returns a stream of each iteration. * * <p>Iterations happen in strict character encounter order, from the beginning of the input * string to the end, with no overlapping. When a match is found, the next iteration is * guaranteed to be in the substring after the current match. For example, {@code * between(first('/'), first('/')).repeatedly().match("/foo/bar/baz/")} will return {@code * ["foo", "bar", "baz"]}. On the other hand, {@code * after(last('/')).repeatedly().match("/foo/bar")} will only return "bar". * * <p>Pattern matching is lazy and doesn't start until the returned stream is consumed. * * <p>An empty stream is returned if this pattern has no matches in the {@code input} string. */ public abstract Stream<Match> match(String input); /** * Applies this pattern against {@code string} and returns a stream of each iteration. * * <p>Iterations happen in strict character encounter order, from the beginning of the input * string to the end, with no overlapping. When a match is found, the next iteration is * guaranteed to be in the substring after the current match. For example, {@code * between(first('/'), first('/')).repeatedly().from("/foo/bar/baz/")} will return {@code * ["foo", "bar", "baz"]}. On the other hand, {@code * after(last('/')).repeatedly().from("/foo/bar")} will only return "bar". * * <p>Pattern matching is lazy and doesn't start until the returned stream is consumed. * * <p>An empty stream is returned if this pattern has no matches in the {@code input} string. */ public Stream<String> from(CharSequence input) { return match(input.toString()).map(Match::toString); } /** * Returns a new string with all {@link #match matches} of this pattern removed. Returns {@code * string} as is if no match is found. */ public String removeAllFrom(String string) { return replaceAllFrom(string, m -> ""); } /** * Returns a new string with all {@link #match matches} of this pattern replaced by applying * {@code replacementFunction} for each match. * * <p>{@code replacementFunction} must not return null. Returns {@code string} as-is if no match * is found. */ public String replaceAllFrom( String string, Function<? super Match, ? extends CharSequence> replacementFunction) { requireNonNull(replacementFunction); Iterator<Match> matches = match(string).iterator(); if (!matches.hasNext()) { return string; } // Add the chars between the previous and current match. StringBuilder builder = new StringBuilder(string.length()); int index = 0; do { Match match = matches.next(); CharSequence replacement = replacementFunction.apply(match); if (replacement == null) { throw new NullPointerException("No replacement is returned for " + match); } builder .append(string, index, match.startIndex) .append(replacement); index = match.endIndex; } while (matches.hasNext()); // Add the remaining chars return builder.append(string, index, string.length()).toString(); } /** * Returns a stream of {@code Match} objects delimited by every match of this pattern. If this * pattern isn't found in {@code string}, the full string is matched. * * <p>The returned {@code Match} objects are cheap "views" of the matched substring sequences. * Because {@code Match} implements {@code CharSequence}, the returned {@code Match} objects can * be directly passed to {@code CharSequence}-accepting APIs such as {@code * com.google.common.base.CharMatcher.trimFrom()} and {@link Pattern#splitThenTrim} etc. */ public Stream<Match> split(String string) { return MoreStreams.whileNotNull( new Supplier<Match>() { int next = 0; Iterator<Match> it = match(string).iterator(); @Override public Match get() { if (it.hasNext()) { Match delim = it.next(); Match result = new Match(string, next, delim.index() - next); next = delim.endIndex; return result; } if (next >= 0) { Match result = new Match(string, next, string.length() - next); next = -1; return result; } else { return null; } } }); } /** * Returns a stream of {@code Match} objects delimited by every match of this pattern. with * whitespaces trimmed. * * <p>The returned {@code Match} objects are cheap "views" of the matched substring sequences. * Because {@code Match} implements {@code CharSequence}, the returned {@code Match} objects can * be directly passed to {@code CharSequence}-accepting APIs such as {@code * com.google.common.base.CharMatcher.trimFrom()} and {@link Pattern#split} etc. */ public Stream<Match> splitThenTrim(String string) { return split(string).map(Match::trim); } /** * Returns a {@link BiStream} of key value pairs from {@code input}. * * <p>The key-value pairs are delimited by this repeating pattern. * with the key and value separated by {@code keyValueSeparator}. * * <p>Empty parts (including leading and trailing separator) are ignored. * Although whitespaces are not trimmed. For example: * * <pre>{@code * first(',') * .repeatedly() * .splitKeyValuesAround(first('='), "k1=v1,,k2=v2,") * }</pre> * will result in a {@code BiStream} equivalent to {@code [(k1, v1), (k2, v2)]}, * but {@code "k1=v1, ,k2=v2"} will fail to be split due to the whitespace after the first * {@code ','}. * * <p>Non-empty parts where {@code keyValueSeparator} is absent will result in * {@link IllegalArgumentException}. * * <p>For alternative splitting strategies, like, if you want to reject instead of ignoring * empty parts. consider to use {@link #split} and {@link Pattern#split} directly, * such as: * * <pre>{@code * first(',') * .repeatedly() * .split("k1=v1,,k2=v2,") // the redundant ',' will throw IAE * .collect( * GuavaCollectors.toImmutableMap( * m -> first('=').split(m).orElseThrow(...))); * }</pre> * * Or, if you want to ignore unparsable parts: * * <pre>{@code * first(',') * .repeatedly() * .split("k1=v1,k2>v2") // Ignore the unknown "k2>v2" * .map(first('=')::split) * .collect( * MoreCollectors.flatMapping( * BiOptional::stream, * toImmutableMap())); * }</pre> * * @since 5.9 */ public final BiStream<String, String> splitKeyValuesAround( Pattern keyValueSeparator, String input) { requireNonNull(keyValueSeparator); return BiStream.from( split(input) .filter(m -> m.length() > 0) .map(m -> keyValueSeparator .split(m) .orElseThrow( () -> new IllegalArgumentException("Cannot split key values from '" + m + "'")))); } /** * Returns a {@link BiStream} of key value pairs from {@code input}. * * <p>The key-value pairs are delimited by this repeating pattern. * with the key and value separated by {@code keyValueSeparator}. * * <p>All keys and values are trimmed, with empty parts (including leading and trailing * separator) ignored. For example: * * <pre>{@code * first(',') * .repeatedly() * .splitThenTrimKeyValuesAround(first('='), "k1 = v1, , k2=v2,") * }</pre> * will result in a {@code BiStream} equivalent to {@code [(k1, v1), (k2, v2)]}. * * <p>Non-empty parts where {@code keyValueSeparator} is absent will result in * {@link IllegalArgumentException}. * * <p>For alternative splitting strategies, like, if you want to reject instead of ignoring * empty parts. consider to use {@link #split} and {@link Pattern#splitThenTrim} directly, * such as: * * <pre>{@code * first(',') * .repeatedly() * .split("k1 = v1, , k2=v2,") // the redundant ',' will throw IAE * .collect( * GuavaCollectors.toImmutableMap( * m -> first('=').splitThenTrim(m).orElseThrow(...))); * }</pre> * * Or, if you want to ignore unparsable parts: * * <pre>{@code * first(',') * .repeatedly() * .split("k1 = v1, k2 > v2") // Ignore the unknown "k2 > v2" * .map(first('=')::splitThenTrim) * .collect( * MoreCollectors.flatMapping( * BiOptional::stream, * toImmutableMap())); * }</pre> * * @since 5.9 */ public final BiStream<String, String> splitThenTrimKeyValuesAround( Pattern keyValueSeparator, String input) { requireNonNull(keyValueSeparator); return BiStream.from( splitThenTrim(input) .filter(m -> m.length() > 0) .map(m -> keyValueSeparator .splitThenTrim(m) .orElseThrow( () -> new IllegalArgumentException("Cannot split key values from '" + m + "'")))); } RepeatingPattern() {} } /** * An immutable string prefix {@code Pattern} with extra utilities such as {@link * #addToIfAbsent(String)}, {@link #removeFrom(StringBuilder)}, {@link #isIn(CharSequence)} etc. * * <p>Can usually be declared as a constant to save allocation cost. Because {@code Prefix} * implements {@link CharSequence}, it can be used almost interchangeably as a string. You can: * * <ul> * <li>directly prepend a prefix as in {@code HOME_PREFIX + path}; * <li>or prepend it into a {@code StringBuilder}: {@code builder.insert(0, HOME_PREFIX)}; * <li>pass it to any CharSequence-accepting APIs such as {@code * CharMatcher.anyOf(...).matchesAnyOf(MY_PREFIX)}, {@code * Substring.first(':').splitThenTrim(MY_PREFIX)} etc. * </ul> * * @since 4.6 */ public static final class Prefix extends Pattern implements CharSequence { private final String prefix; Prefix(String prefix) { this.prefix = prefix; } /** * Returns true if {@code source} starts with this prefix. * * @since 5.7 */ public boolean isIn(CharSequence source) { if (source instanceof String) { return ((String) source).startsWith(prefix); } int prefixChars = prefix.length(); int existingChars = source.length(); if (existingChars < prefixChars) { return false; } for (int i = 0; i < prefixChars; i++) { if (prefix.charAt(i) != source.charAt(i)) { return false; } } return true; } /** * If {@code string} has this prefix, return it as-is; otherwise, return it with this prefix * prepended. * * @since 4.8 */ public String addToIfAbsent(String string) { return string.startsWith(prefix) ? string : prefix + string; } /** * If {@code builder} does not already have this prefix, prepend this prefix to it. * * @return true if this prefix is prepended * @since 5.7 */ public boolean addToIfAbsent(StringBuilder builder) { boolean shouldAdd = !isIn(builder); if (shouldAdd) { builder.insert(0, prefix); } return shouldAdd; } /** * Removes this prefix from {@code builder} if it starts with the prefix. * * @return true if this prefix is removed * @since 5.7 */ public boolean removeFrom(StringBuilder builder) { boolean present = isIn(builder); if (present) { builder.delete(0, length()); } return present; } /** * Replaces this prefix from {@code builder} with {@code replacement} if it starts with the * prefix. * * @return true if this prefix is replaced * @since 5.7 */ public boolean replaceFrom(StringBuilder builder, CharSequence replacement) { requireNonNull(replacement); boolean present = isIn(builder); if (present) { builder.replace(0, length(), replacement.toString()); } return present; } /** @since 5.7 */ @Override public char charAt(int index) { return prefix.charAt(index); } /** @since 5.7 */ @Override public String subSequence(int start, int end) { return prefix.substring(start, end); } /** * Returns the length of this prefix. * * @since 5.7 */ @Override public int length() { return prefix.length(); } @Override public int hashCode() { return prefix.hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof Prefix && prefix.equals(((Prefix) obj).prefix); } /** Returns this prefix string. */ @Override public String toString() { return prefix; } @Override Match match(String input, int fromIndex) { return input.startsWith(prefix, fromIndex) ? new Match(input, fromIndex, prefix.length()) : null; } } /** * An immutable string suffix {@code Pattern} with extra utilities such as {@link * #addToIfAbsent(String)}, {@link #removeFrom(StringBuilder)}, {@link #isIn(CharSequence)} etc. * * <p>Can usually be declared as a constant to save allocation cost. Because {@code Suffix} * implements {@link CharSequence}, it can be used almost interchangeably as a string. You can: * * <ul> * <li>directly append a suffix as in {@code path + SHARD_SUFFIX}; * <li>or append the suffix into a {@code StringBuilder}: {@code builder.append(SHARD_SUFFIX)}}; * <li>pass it to any CharSequence-accepting APIs such as {@code * CharMatcher.anyOf(...).matchesAnyOf(MY_PREFIX)}, {@code * Substring.first(':').splitThenTrim(MY_PREFIX)} etc. * </ul> * * @since 4.6 */ public static final class Suffix extends Pattern implements CharSequence { private final String suffix; Suffix(String suffix) { this.suffix = suffix; } /** * Returns true if {@code source} ends with this suffix. * * @since 5.7 */ public boolean isIn(CharSequence source) { if (source instanceof String) { return ((String) source).endsWith(suffix); } int suffixChars = suffix.length(); int existingChars = source.length(); if (existingChars < suffixChars) { return false; } for (int i = 1; i <= suffixChars; i++) { if (suffix.charAt(suffixChars - i) != source.charAt(existingChars - i)) { return false; } } return true; } /** * If {@code string} has this suffix, return it as-is; otherwise, return it with this suffix * appended. * * @since 4.8 */ public String addToIfAbsent(String string) { return string.endsWith(suffix) ? string : string + suffix; } /** * If {@code builder} does not already have this suffix, append this suffix to it. * * @return true if this suffix is appended * @since 5.7 */ public boolean addToIfAbsent(StringBuilder builder) { boolean shouldAdd = !isIn(builder); if (shouldAdd) { builder.append(suffix); } return shouldAdd; } /** * Removes this suffix from {@code builder} if it ends with the suffix. * * @return true if this suffix is removed * @since 5.7 */ public boolean removeFrom(StringBuilder builder) { boolean present = isIn(builder); if (present) { builder.delete(builder.length() - length(), builder.length()); } return present; } /** * Replaces this suffix from {@code builder} with {@code replacement} if it ends with the * suffix. * * @return true if this suffix is replaced * @since 5.7 */ public boolean replaceFrom(StringBuilder builder, CharSequence replacement) { requireNonNull(replacement); boolean present = isIn(builder); if (present) { builder.replace(builder.length() - length(), builder.length(), replacement.toString()); } return present; } /** @since 5.7 */ @Override public char charAt(int index) { return suffix.charAt(index); } /** @since 5.7 */ @Override public String subSequence(int start, int end) { return suffix.substring(start, end); } /** * Returns the length of this suffix. * * @since 5.7 */ @Override public int length() { return suffix.length(); } /** @since 5.7 */ @Override public int hashCode() { return suffix.hashCode(); } /** @since 5.7 */ @Override public boolean equals(Object obj) { return obj instanceof Suffix && suffix.equals(((Suffix) obj).suffix); } /** Returns this suffix string. */ @Override public String toString() { return suffix; } @Override Match match(String input, int fromIndex) { int index = input.length() - suffix.length(); return index >= fromIndex && input.endsWith(suffix) ? new Match(input, index, suffix.length()) : null; } } /** * The result of successfully matching a {@link Pattern} against a string, providing access to the * {@link #toString matched substring}, to the parts of the string {@link #before before} and * {@link #after after} it, and to copies with the matched substring {@link #remove removed} or * {@link #replaceWith replaced}. * * <p><em>Note:</em> a {@link Match} is a view of the original string and holds a strong reference * to the original string. It's advisable to construct and use a {@code Match} object within the * scope of a method; holding onto a {@code Match} object has the same risk of leaking memory as * holding onto the string it was produced from. */ public static final class Match implements CharSequence { private final String context; private final int startIndex; private final int endIndex; /** * While {@code endIndex} demarcates the matched substring, {@code repetitionStartIndex} points to * the starting point to scan for the succeeding {@link Pattern#iterateIn iteration} of the same * pattern. It's by default equal to {@code endIndex}, but for {@link Substring#before} and * {@link Substring#upToIncluding}, {@code repetitionStartIndex} starts after the delimiters. */ private final int repetitionStartIndex; private Match(String context, int startIndex, int length) { this(context, startIndex, length, startIndex + max(1, length)); } private Match(String context, int startIndex, int length, int repetitionStartIndex) { this.context = context; this.startIndex = startIndex; this.endIndex = startIndex + length; this.repetitionStartIndex = repetitionStartIndex; } /** * Returns the part of the original string before the matched substring. * * <p>{@link #before} and {@link #after} are almost always used together to split a string into * two parts. If you just need the substring before the match, you might want to use {@code * Substring.before(pattern)} instead, because the pattern logic is encoded entirely in the * {@link Pattern} object. For example: * * <pre> * private static final Substring.Pattern DIRECTORY = Substring.before(last("/")); * </pre> */ public String before() { return context.substring(0, startIndex); } /** * Returns the part of the original string before the matched substring. * * <p>{@link #before} and {@link #after} are almost always used together to split a string into * two parts. If you just need the substring after the match, you might want to use {@code * Substring.after(pattern)} instead, because the pattern logic is encoded entirely in the * {@link Pattern} object. For example: * * <pre> * private static final Substring.Pattern LINE_COMMENT = Substring.after(first("//")); * </pre> */ public String after() { return context.substring(endIndex); } /** Return the full string being matched against. */ public String fullString() { return context; } /** * Returns a copy of the original string with the matched substring removed. * * <p>This is equivalent to {@code match.before() + match.after()}. */ public String remove() { // Minimize string concatenation. if (endIndex == context.length()) { return before(); } else if (startIndex == 0) { return after(); } else { return before() + after(); } } /** * Returns a copy of the original string with the matched substring replaced with {@code * replacement}. * * <p>This is equivalent to {@code match.before() + replacement + match.after()}. */ public String replaceWith(CharSequence replacement) { requireNonNull(replacement); return before() + replacement + after(); } /** * Returns true if the match isn't empty. * * @since 6.0 */ public boolean isNotEmpty() { return length() > 0; } /** Return 0-based index of this match in {@link #fullString}. */ public int index() { return startIndex; } /** Returns the length of the matched substring. */ @Override public int length() { return endIndex - startIndex; } /** * {@inheritDoc} * @since 4.6 */ @Override public char charAt(int i) { if (i < 0) { throw new IndexOutOfBoundsException("Invalid index (" + i + ") < 0"); } if (i >= length()) { throw new IndexOutOfBoundsException( "Invalid index (" + i + ") >= length (" + length() + ")"); } return context.charAt(startIndex + i); } /** * Returns a {@link CharSequence} instance which is a sub-range of this {@code Match}. * * <p>For example, if this {@code Match} points to the range of {@code "wood"} from * the {@code "Holywood"} string, calling {@code subSequence(1, 3)} will point to the * range of {@code "oo"} from the original string. * * <p>Can be used to further reduce the matched range manually. * * @since 4.6 */ @Override public CharSequence subSequence(int begin, int end) { if (begin < 0) { throw new IndexOutOfBoundsException("Invalid index: begin (" + begin + ") < 0"); } if (end > length()) { throw new IndexOutOfBoundsException( "Invalid index: end (" + end + ") > length (" + length() + ")"); } if (begin > end) { throw new IndexOutOfBoundsException( "Invalid index: begin (" + begin + ") > end (" + end + ")"); } return new Match(context, startIndex + begin, end - begin); } /** Returns the matched substring. */ @Override public String toString() { return context.substring(startIndex, endIndex); } Match preceding() { return new Match(context, 0, startIndex); } Match following() { return new Match(context, endIndex, context.length() - endIndex); } Match trim() { int left = startIndex; int right = endIndex - 1; while (left <= right) { if (Character.isWhitespace(context.charAt(left))) { left++; continue; } if (Character.isWhitespace(context.charAt(right))) { right--; continue; } break; } int trimmedLength = right - left + 1; return trimmedLength == length() ? this : new Match(context, left, trimmedLength, repetitionStartIndex); } private Match toEnd() { return new Match(context, startIndex, context.length() - startIndex); } } private Substring() {} }
Update splitAsciiByCase() examples
mug/src/main/java/com/google/mu/util/Substring.java
Update splitAsciiByCase() examples
Java
apache-2.0
7b42203b2510b326d26855466feecfc3501364a4
0
maboelhassan/alluxio,apc999/alluxio,maboelhassan/alluxio,jswudi/alluxio,riversand963/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,madanadit/alluxio,maobaolong/alluxio,aaudiber/alluxio,aaudiber/alluxio,wwjiang007/alluxio,jswudi/alluxio,maboelhassan/alluxio,Alluxio/alluxio,madanadit/alluxio,Reidddddd/alluxio,PasaLab/tachyon,PasaLab/tachyon,maobaolong/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,madanadit/alluxio,Alluxio/alluxio,Reidddddd/alluxio,Alluxio/alluxio,aaudiber/alluxio,apc999/alluxio,wwjiang007/alluxio,bf8086/alluxio,aaudiber/alluxio,apc999/alluxio,maobaolong/alluxio,calvinjia/tachyon,PasaLab/tachyon,madanadit/alluxio,aaudiber/alluxio,aaudiber/alluxio,jswudi/alluxio,riversand963/alluxio,wwjiang007/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,PasaLab/tachyon,Reidddddd/alluxio,jswudi/alluxio,maobaolong/alluxio,apc999/alluxio,madanadit/alluxio,calvinjia/tachyon,jswudi/alluxio,wwjiang007/alluxio,calvinjia/tachyon,PasaLab/tachyon,bf8086/alluxio,Reidddddd/alluxio,calvinjia/tachyon,maobaolong/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,wwjiang007/alluxio,maobaolong/alluxio,Alluxio/alluxio,bf8086/alluxio,madanadit/alluxio,Alluxio/alluxio,riversand963/alluxio,Alluxio/alluxio,maboelhassan/alluxio,riversand963/alluxio,wwjiang007/alluxio,jswudi/alluxio,calvinjia/tachyon,wwjiang007/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,maobaolong/alluxio,Alluxio/alluxio,calvinjia/tachyon,PasaLab/tachyon,EvilMcJerkface/alluxio,Alluxio/alluxio,apc999/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,calvinjia/tachyon,madanadit/alluxio,apc999/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,aaudiber/alluxio,Alluxio/alluxio,Reidddddd/alluxio,maobaolong/alluxio,riversand963/alluxio,Alluxio/alluxio,bf8086/alluxio,bf8086/alluxio,Reidddddd/alluxio,Reidddddd/alluxio,bf8086/alluxio,maobaolong/alluxio,maobaolong/alluxio,wwjiang007/alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.web; import alluxio.AlluxioURI; import alluxio.Configuration; import alluxio.PropertyKey; import com.google.common.base.Preconditions; //import com.google.common.base.Throwables; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.webapp.WebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import javax.annotation.concurrent.NotThreadSafe; /** * Class that bootstraps and starts a web server. */ @NotThreadSafe public abstract class WebServer { private static final Logger LOG = LoggerFactory.getLogger(WebServer.class); private final Server mServer; private final String mServiceName; private final InetSocketAddress mAddress; private final ServerConnector mServerConnector; protected final WebAppContext mWebAppContext; /** * Creates a new instance of {@link WebServer}. It pairs URLs with servlets and sets the webapp * folder. * * @param serviceName name of the web service * @param address address of the server */ public WebServer(String serviceName, InetSocketAddress address) { Preconditions.checkNotNull(serviceName, "Service name cannot be null"); Preconditions.checkNotNull(address, "Server address cannot be null"); mAddress = address; mServiceName = serviceName; QueuedThreadPool threadPool = new QueuedThreadPool(); int webThreadCount = Configuration.getInt(PropertyKey.WEB_THREADS); // Jetty needs at least (1 + selectors + acceptors) threads. threadPool.setMinThreads(webThreadCount * 2 + 1); threadPool.setMaxThreads(webThreadCount * 2 + 100); mServer = new Server(threadPool); mServerConnector = new ServerConnector(mServer); mServerConnector.setPort(mAddress.getPort()); mServerConnector.setHost(mAddress.getAddress().getHostAddress()); mServer.addConnector(mServerConnector); // Open the connector here so we can resolve the port if we are selecting a free port. try { mServerConnector.open(); } catch (IOException e) { // Throwables.propagate(e); throw new RuntimeException(e); } System.setProperty("org.apache.jasper.compiler.disablejsr199", "false"); mWebAppContext = new WebAppContext(); mWebAppContext.setContextPath(AlluxioURI.SEPARATOR); File warPath = new File(Configuration.get(PropertyKey.WEB_RESOURCES)); mWebAppContext.setWar(warPath.getAbsolutePath()); // Set the ContainerIncludeJarPattern so that jetty examines these // container-path jars for tlds, web-fragments etc. // If you omit the jar that contains the jstl .tlds, the jsp engine will // scan for them instead. mWebAppContext.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$" + "|.*/[^/]*taglibs.*\\.jar$"); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] {mWebAppContext, new DefaultHandler()}); mServer.setHandler(handlers); } /** * Adds a handler. * * @param handler the handler to add */ public void addHandler(AbstractHandler handler) { HandlerList handlers = new HandlerList(); handlers.addHandler(handler); for (Handler h : mServer.getHandlers()) { handlers.addHandler(h); } mServer.setHandler(handlers); } /** * @param handler to use */ public void setHandler(AbstractHandler handler) { mServer.setHandler(handler); } /** * @return the underlying Jetty server */ public Server getServer() { return mServer; } /** * Gets the actual bind hostname. * * @return the bind host */ public String getBindHost() { String bindHost = mServerConnector.getHost(); return bindHost == null ? "0.0.0.0" : bindHost; } /** * Gets the actual port that the web server is listening on. * * @return the local port */ public int getLocalPort() { return mServerConnector.getLocalPort(); } /** * Shuts down the web server. */ public void stop() throws Exception { // close all connectors and release all binding ports for (Connector connector : mServer.getConnectors()) { connector.stop(); } mServer.stop(); } /** * Starts the web server. */ public void start() { try { mServer.start(); LOG.info("{} started @ {}", mServiceName, mAddress); } catch (Exception e) { // throw Throwables.propagate(e); throw new RuntimeException(e); } } }
core/server/common/src/main/java/alluxio/web/WebServer.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.web; import alluxio.AlluxioURI; import alluxio.Configuration; import alluxio.PropertyKey; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.webapp.WebAppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import javax.annotation.concurrent.NotThreadSafe; /** * Class that bootstraps and starts a web server. */ @NotThreadSafe public abstract class WebServer { private static final Logger LOG = LoggerFactory.getLogger(WebServer.class); private final Server mServer; private final String mServiceName; private final InetSocketAddress mAddress; private final ServerConnector mServerConnector; protected final WebAppContext mWebAppContext; /** * Creates a new instance of {@link WebServer}. It pairs URLs with servlets and sets the webapp * folder. * * @param serviceName name of the web service * @param address address of the server */ public WebServer(String serviceName, InetSocketAddress address) { Preconditions.checkNotNull(serviceName, "Service name cannot be null"); Preconditions.checkNotNull(address, "Server address cannot be null"); mAddress = address; mServiceName = serviceName; QueuedThreadPool threadPool = new QueuedThreadPool(); int webThreadCount = Configuration.getInt(PropertyKey.WEB_THREADS); // Jetty needs at least (1 + selectors + acceptors) threads. threadPool.setMinThreads(webThreadCount * 2 + 1); threadPool.setMaxThreads(webThreadCount * 2 + 100); mServer = new Server(threadPool); mServerConnector = new ServerConnector(mServer); mServerConnector.setPort(mAddress.getPort()); mServerConnector.setHost(mAddress.getAddress().getHostAddress()); mServer.addConnector(mServerConnector); // Open the connector here so we can resolve the port if we are selecting a free port. try { mServerConnector.open(); } catch (IOException e) { Throwables.propagate(e); } System.setProperty("org.apache.jasper.compiler.disablejsr199", "false"); mWebAppContext = new WebAppContext(); mWebAppContext.setContextPath(AlluxioURI.SEPARATOR); File warPath = new File(Configuration.get(PropertyKey.WEB_RESOURCES)); mWebAppContext.setWar(warPath.getAbsolutePath()); // Set the ContainerIncludeJarPattern so that jetty examines these // container-path jars for tlds, web-fragments etc. // If you omit the jar that contains the jstl .tlds, the jsp engine will // scan for them instead. mWebAppContext.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$" + "|.*/[^/]*taglibs.*\\.jar$"); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] {mWebAppContext, new DefaultHandler()}); mServer.setHandler(handlers); } /** * Adds a handler. * * @param handler the handler to add */ public void addHandler(AbstractHandler handler) { HandlerList handlers = new HandlerList(); handlers.addHandler(handler); for (Handler h : mServer.getHandlers()) { handlers.addHandler(h); } mServer.setHandler(handlers); } /** * @param handler to use */ public void setHandler(AbstractHandler handler) { mServer.setHandler(handler); } /** * @return the underlying Jetty server */ public Server getServer() { return mServer; } /** * Gets the actual bind hostname. * * @return the bind host */ public String getBindHost() { String bindHost = mServerConnector.getHost(); return bindHost == null ? "0.0.0.0" : bindHost; } /** * Gets the actual port that the web server is listening on. * * @return the local port */ public int getLocalPort() { return mServerConnector.getLocalPort(); } /** * Shuts down the web server. */ public void stop() throws Exception { // close all connectors and release all binding ports for (Connector connector : mServer.getConnectors()) { connector.stop(); } mServer.stop(); } /** * Starts the web server. */ public void start() { try { mServer.start(); LOG.info("{} started @ {}", mServiceName, mAddress); } catch (Exception e) { throw Throwables.propagate(e); } } }
WebServer.java RuntimeException(e)
core/server/common/src/main/java/alluxio/web/WebServer.java
WebServer.java RuntimeException(e)
Java
apache-2.0
d37b47282a516fbb739d24933481e65d647de75d
0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.annotation.model; import java.time.LocalDate; import java.time.ZoneId; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeExtensionItem.OCCURS_IN_CL_1; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeExtensionItem.OCCURS_IN_CL_2; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeExtensionItem.OCCURS_IN_CL_3; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeWithFromItem.IPR_1; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeWithFromItem.IPR_2; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeWithFromItem.IPR_3; /** * A class for creating stubbed annotations, representing rows of data read from * annotation source files. * * Created 20/01/17 * @author Tony */ public class AnnotationMocker { public static final String WITH_FROM_AS_STRING = IPR_1 + "|" + IPR_2 + "," + IPR_3; public static final String EXTENSIONS_AS_STRING = OCCURS_IN_CL_1 + "|" + OCCURS_IN_CL_2 + "," + OCCURS_IN_CL_3; public static final String SYMBOL = "atf4-creb1_mouse"; public static final String QUALIFIER = "enables"; public static final String REFERENCE = "PMID:12871976"; public static final String ECO_ID = "ECO:0000353"; public static final String GO_EVIDENCE = "IPI"; public static final int TAXON_ID = 12345; public static final String TAXON_NAME = "Hipdedipdiflorous"; public static final int INTERACTING_TAXON_ID = 54321; public static final String DB = "IntAct"; public static final String ID = "EBI-10043081"; public static final String GO_ID = "GO:0003824"; public static final String GO_NAME = "catalytic activity"; public static final String DATE_AS_STRING = "20121002"; private static final String SLIMMED_FROM_GO_ID = "GO:0071840"; public static final List<String> SLIMMED_TO_IDS = Collections.singletonList(SLIMMED_FROM_GO_ID); private static final String COMMA = ","; private static final List<List<Supplier<Annotation.SimpleXRef>>> WITH_FROM = asList( singletonList(IPR_1), asList(IPR_2, IPR_3)); private static final List<List<Supplier<Annotation.QualifiedXref>>> EXTENSIONS = asList( singletonList(OCCURS_IN_CL_1), asList(OCCURS_IN_CL_2, OCCURS_IN_CL_3)); private static final String GENE_PRODUCT_ID = "IntAct:EBI-10043081"; private static final String ASSIGNED_BY = "IntAct"; private static final String GO_ASPECT = "molecular_function"; private static final Date DATE = Date.from( LocalDate.of(2012, 10, 2).atStartOfDay(ZoneId.systemDefault()).toInstant()); public static final String SYNONYMS = "A0A000_9ACTN,moeA5"; public static final String NAME = "MoeA5"; public static final String TYPE = "complex"; public static Annotation createValidAnnotation() { Annotation annotation = new Annotation(); annotation.id = DB + ":" + ID; annotation.extensions = connectedQualifiedXrefs(EXTENSIONS); annotation.taxonId = TAXON_ID; annotation.goAspect = GO_ASPECT; //todo is this populated annotation.goEvidence = GO_EVIDENCE; annotation.assignedBy = ASSIGNED_BY; annotation.date = DATE; annotation.evidenceCode = ECO_ID; annotation.geneProductId = GENE_PRODUCT_ID; annotation.qualifier = QUALIFIER; annotation.symbol = SYMBOL; annotation.reference = REFERENCE; annotation.withFrom = connectedSimpleXrefs(WITH_FROM); annotation.goId = GO_ID; annotation.interactingTaxonId = INTERACTING_TAXON_ID; annotation.goName = GO_NAME; annotation.taxonName = TAXON_NAME; annotation.name = NAME; annotation.synonyms = SYNONYMS; return annotation; } private static List<Annotation.ConnectedXRefs<Annotation.SimpleXRef>> connectedSimpleXrefs( List<List<Supplier<Annotation.SimpleXRef>>> items) { return items.stream().map(itemList -> { Annotation.ConnectedXRefs<Annotation.SimpleXRef> xrefs = new Annotation .ConnectedXRefs<>(); itemList.stream().map(Supplier::get).forEach(xrefs::addXref); return xrefs; } ).collect(Collectors.toList()); } private static List<Annotation.ConnectedXRefs<Annotation.QualifiedXref>> connectedQualifiedXrefs( List<List<Supplier<Annotation.QualifiedXref>>> items) { return items.stream().map(itemList -> { Annotation.ConnectedXRefs<Annotation.QualifiedXref> xrefs = new Annotation .ConnectedXRefs<>(); itemList.stream().map(Supplier::get).forEach(xrefs::addXref); return xrefs; } ).collect(Collectors.toList()); } private static <T extends Annotation.AbstractXref> List<String> stringsForConnectedXrefs( List<List<Supplier<T>>> items) { return items.stream() .map(itemList -> itemList.stream() .map(Supplier::toString).collect(Collectors.joining(COMMA)) ).collect(Collectors.toList()); } enum FakeWithFromItem implements Supplier<Annotation.SimpleXRef> { IPR_1("InterPro", "IPR015421"), IPR_2("InterPro", "IPR015422"), IPR_3("InterPro", "IPR015421"); private final String db; private final String id; FakeWithFromItem(String db, String id) { this.db = db; this.id = id; } @Override public Annotation.SimpleXRef get() { return new Annotation.SimpleXRef(db, id); } @Override public String toString() { return db + ":" + id; } } enum FakeExtensionItem implements Supplier<Annotation.QualifiedXref> { OCCURS_IN_CL_1("occurs_in", "CL", "0000001"), OCCURS_IN_CL_2("occurs_in", "CL", "0000002"), OCCURS_IN_CL_3("occurs_in", "CL", "0000003"); private final String qualifier; private final String db; private final String id; FakeExtensionItem(String qualifier, String db, String id) { this.qualifier = qualifier; this.db = db; this.id = id; } @Override public Annotation.QualifiedXref get() { return new Annotation.QualifiedXref(db, id, qualifier); } @Override public String toString() { return qualifier + "(" + db + ":" + id + ")"; } } }
annotation-rest/src/test/java/uk/ac/ebi/quickgo/annotation/model/AnnotationMocker.java
package uk.ac.ebi.quickgo.annotation.model; import java.time.LocalDate; import java.time.ZoneId; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeExtensionItem.OCCURS_IN_CL_1; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeExtensionItem.OCCURS_IN_CL_2; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeExtensionItem.OCCURS_IN_CL_3; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeWithFromItem.IPR_1; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeWithFromItem.IPR_2; import static uk.ac.ebi.quickgo.annotation.model.AnnotationMocker.FakeWithFromItem.IPR_3; /** * A class for creating stubbed annotations, representing rows of data read from * annotation source files. * * Created 20/01/17 * @author Tony */ public class AnnotationMocker { public static final String WITH_FROM_AS_STRING = IPR_1 + "|" + IPR_2 + "," + IPR_3; public static final String EXTENSIONS_AS_STRING = OCCURS_IN_CL_1 + "|" + OCCURS_IN_CL_2 + "," + OCCURS_IN_CL_3; public static final String SYMBOL = "atf4-creb1_mouse"; public static final String QUALIFIER = "enables"; public static final String REFERENCE = "PMID:12871976"; public static final String ECO_ID = "ECO:0000353"; public static final String GO_EVIDENCE = "IPI"; public static final int TAXON_ID = 12345; public static final String TAXON_NAME = "Hipdedipdiflorous"; public static final int INTERACTING_TAXON_ID = 54321; public static final String DB = "IntAct"; public static final String ID = "EBI-10043081"; public static final String GO_ID = "GO:0003824"; public static final String GO_NAME = "catalytic activity"; public static final String DATE_AS_STRING = "20121002"; private static final String SLIMMED_FROM_GO_ID = "GO:0071840"; public static final List<String> SLIMMED_TO_IDS = Collections.singletonList(SLIMMED_FROM_GO_ID); private static final String COMMA = ","; private static final List<List<Supplier<Annotation.SimpleXRef>>> WITH_FROM = asList( singletonList(IPR_1), asList(IPR_2, IPR_3)); private static final List<List<Supplier<Annotation.QualifiedXref>>> EXTENSIONS = asList( singletonList(OCCURS_IN_CL_1), asList(OCCURS_IN_CL_2, OCCURS_IN_CL_3)); private static final String GENE_PRODUCT_ID = "IntAct:EBI-10043081"; private static final String ASSIGNED_BY = "IntAct"; private static final String GO_ASPECT = "molecular_function"; private static final Date DATE = Date.from( LocalDate.of(2012, 10, 2).atStartOfDay(ZoneId.systemDefault()).toInstant()); public static final String SYNONYMS = "A0A000_9ACTN,moeA5"; public static final String NAME = "MoeA5"; public static final String TYPE = "complex"; public static Annotation createValidAnnotation() { Annotation annotation = new Annotation(); annotation.id = DB + ":" + ID; annotation.extensions = connectedQualifiedXrefs(EXTENSIONS); annotation.taxonId = TAXON_ID; annotation.goAspect = GO_ASPECT; //todo is this populated annotation.goEvidence = GO_EVIDENCE; annotation.assignedBy = ASSIGNED_BY; annotation.date = DATE; annotation.evidenceCode = ECO_ID; annotation.geneProductId = GENE_PRODUCT_ID; annotation.qualifier = QUALIFIER; annotation.symbol = SYMBOL; annotation.reference = REFERENCE; annotation.withFrom = connectedSimpleXrefs(WITH_FROM); annotation.goId = GO_ID; annotation.interactingTaxonId = INTERACTING_TAXON_ID; annotation.goName = GO_NAME; annotation.taxonName = TAXON_NAME; annotation.name = NAME; annotation.synonyms = SYNONYMS; annotation.type = TYPE; return annotation; } private static List<Annotation.ConnectedXRefs<Annotation.SimpleXRef>> connectedSimpleXrefs( List<List<Supplier<Annotation.SimpleXRef>>> items) { return items.stream().map(itemList -> { Annotation.ConnectedXRefs<Annotation.SimpleXRef> xrefs = new Annotation .ConnectedXRefs<>(); itemList.stream().map(Supplier::get).forEach(xrefs::addXref); return xrefs; } ).collect(Collectors.toList()); } private static List<Annotation.ConnectedXRefs<Annotation.QualifiedXref>> connectedQualifiedXrefs( List<List<Supplier<Annotation.QualifiedXref>>> items) { return items.stream().map(itemList -> { Annotation.ConnectedXRefs<Annotation.QualifiedXref> xrefs = new Annotation .ConnectedXRefs<>(); itemList.stream().map(Supplier::get).forEach(xrefs::addXref); return xrefs; } ).collect(Collectors.toList()); } private static <T extends Annotation.AbstractXref> List<String> stringsForConnectedXrefs( List<List<Supplier<T>>> items) { return items.stream() .map(itemList -> itemList.stream() .map(Supplier::toString).collect(Collectors.joining(COMMA)) ).collect(Collectors.toList()); } enum FakeWithFromItem implements Supplier<Annotation.SimpleXRef> { IPR_1("InterPro", "IPR015421"), IPR_2("InterPro", "IPR015422"), IPR_3("InterPro", "IPR015421"); private final String db; private final String id; FakeWithFromItem(String db, String id) { this.db = db; this.id = id; } @Override public Annotation.SimpleXRef get() { return new Annotation.SimpleXRef(db, id); } @Override public String toString() { return db + ":" + id; } } enum FakeExtensionItem implements Supplier<Annotation.QualifiedXref> { OCCURS_IN_CL_1("occurs_in", "CL", "0000001"), OCCURS_IN_CL_2("occurs_in", "CL", "0000002"), OCCURS_IN_CL_3("occurs_in", "CL", "0000003"); private final String qualifier; private final String db; private final String id; FakeExtensionItem(String qualifier, String db, String id) { this.qualifier = qualifier; this.db = db; this.id = id; } @Override public Annotation.QualifiedXref get() { return new Annotation.QualifiedXref(db, id, qualifier); } @Override public String toString() { return qualifier + "(" + db + ":" + id + ")"; } } }
Remove type.
annotation-rest/src/test/java/uk/ac/ebi/quickgo/annotation/model/AnnotationMocker.java
Remove type.
Java
apache-2.0
ee536330cafbed81f8300563b21225b0e64fc3d3
0
librato/metrics-librato
package com.librato.metrics; import com.codahale.metrics.*; import com.codahale.metrics.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.TimeUnit; /** * A reporter for publishing metrics to <a href="http://metrics.librato.com/">Librato Metrics</a> */ public class LibratoReporter extends ScheduledReporter implements MetricsLibratoBatch.RateConverter, MetricsLibratoBatch.DurationConverter { private static final Logger LOG = LoggerFactory.getLogger(LibratoReporter.class); private final DeltaTracker deltaTracker; private final String source; private final long timeout; private final TimeUnit timeoutUnit; private final Sanitizer sanitizer; private final HttpPoster httpPoster; private final String prefix; private final String prefixDelimiter; protected final MetricRegistry registry; protected final Clock clock; protected final MetricExpansionConfig expansionConfig; /** * Private. Use builder instead. */ private LibratoReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, Sanitizer customSanitizer, String source, long timeout, TimeUnit timeoutUnit, Clock clock, MetricExpansionConfig expansionConfig, HttpPoster httpPoster, String prefix, String prefixDelimiter) { super(registry, name, filter, rateUnit, durationUnit); this.registry = registry; this.sanitizer = customSanitizer; this.source = source; this.timeout = timeout; this.timeoutUnit = timeoutUnit; this.clock = clock; this.expansionConfig = expansionConfig; this.httpPoster = httpPoster; this.prefix = prefix; this.prefixDelimiter = prefixDelimiter; this.deltaTracker = new DeltaTracker(new DeltaMetricSupplier(registry, filter)); } public double convertMetricDuration(double duration) { return convertDuration(duration); } public double convertMetricRate(double rate) { return convertRate(rate); } /** * Used to supply metrics to the delta tracker on initialization. Uses the metric name conversion * to ensure that the correct names are supplied for the metric. */ class DeltaMetricSupplier implements DeltaTracker.MetricSupplier { final MetricRegistry registry; final MetricFilter filter; DeltaMetricSupplier(MetricRegistry registry, MetricFilter filter) { this.registry = registry; this.filter = filter; } public Map<String, Metric> getMetrics() { final Map<String, Metric> map = new HashMap<String, Metric>(); for (Map.Entry<String, Metric> entry : registry.getMetrics().entrySet()) { // todo: ensure the name here is what we expect final String name = entry.getKey(); map.put(name, entry.getValue()); } return map; } } /** * Starts the reporter polling at the given period. * * @param period the amount of time between polls * @param unit the unit for {@code period} */ @Override public void start(long period, TimeUnit unit) { LOG.debug("Reporter starting at fixed rate of every {} {}", period, unit); super.start(period, unit); } @Override public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) { final long epoch = TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); final MetricsLibratoBatch batch = new MetricsLibratoBatch( LibratoBatch.DEFAULT_BATCH_SIZE, sanitizer, timeout, timeoutUnit, expansionConfig, httpPoster, prefix, prefixDelimiter, deltaTracker, this, this); for (Map.Entry<String, Gauge> entry : gauges.entrySet()) { batch.addGauge(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Counter> entry : counters.entrySet()) { batch.addCounter(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Histogram> entry : histograms.entrySet()) { batch.addHistogram(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Meter> entry : meters.entrySet()) { batch.addMeter(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Timer> entry : timers.entrySet()) { batch.addTimer(entry.getKey(), entry.getValue()); } batch.post(source, epoch); } /** * A builder for the LibratoReporter class that requires things that cannot be inferred and uses * sane default values for everything else. */ public static class Builder { private final String source; private Sanitizer sanitizer = Sanitizer.NO_OP; private long timeout = 5; private TimeUnit timeoutUnit = TimeUnit.SECONDS; private TimeUnit rateUnit = TimeUnit.SECONDS; private TimeUnit durationUnit = TimeUnit.MILLISECONDS; private String name = "librato-reporter"; private final MetricRegistry registry; private MetricFilter filter = MetricFilter.ALL; private Clock clock = Clock.defaultClock(); private MetricExpansionConfig expansionConfig = MetricExpansionConfig.ALL; private HttpPoster httpPoster; private String prefix; private String prefixDelimiter = "."; public Builder(MetricRegistry registry, String username, String token, String source) { this.registry = registry; this.source = source; this.httpPoster = NingHttpPoster.newPoster(username, token, "https://metrics-api.librato.com/v1/metrics"); } /** * Sets the timeout for POSTs to Librato * * @param timeout the timeout * @return itself */ @SuppressWarnings("unused") public Builder setTimeout(long timeout) { this.timeout = timeout; return this; } /** * Sets the timeout time unit for POSTs to Librato * * @param timeoutUnit the timeout unit * @return itself */ @SuppressWarnings("unused") public Builder setTimeoutUnit(TimeUnit timeoutUnit) { this.timeoutUnit = timeoutUnit; return this; } /** * Sets the delimiter which will separate the prefix from the metric name. Defaults * to "." * * @param prefixDelimiter the delimiter * @return itself */ @SuppressWarnings("unused") public Builder setPrefixDelimiter(String prefixDelimiter) { this.prefixDelimiter = prefixDelimiter; return this; } /** * Sets a prefix that will be prepended to all metric names * * @param prefix the prefix * @return itself */ @SuppressWarnings("unused") public Builder setPrefix(String prefix) { this.prefix = prefix; return this; } /** * Sets the {@link HttpPoster} which will send the payload to Librato * * @param poster the HttpPoster * @return itself */ @SuppressWarnings("unused") public Builder setHttpPoster(HttpPoster poster) { this.httpPoster = poster; return this; } /** * Sets the time unit to which rates will be converted by the reporter. The default * value is TimeUnit.SECONDS * * @param rateUnit the rate * @return itself */ @SuppressWarnings("unused") public Builder setRateUnit(TimeUnit rateUnit) { this.rateUnit = rateUnit; return this; } /** * Sets the time unit to which durations will be converted by the reporter. The default * value is TimeUnit.MILLISECONDS * * @param durationUnit the time unit * @return itself */ @SuppressWarnings("unused") public Builder setDurationUnit(TimeUnit durationUnit) { this.durationUnit = durationUnit; return this; } /** * set the HTTP timeout for a publishing attempt * * @param timeout duration to expect a response * @param timeoutUnit unit for duration * @return itself */ @SuppressWarnings("unused") public Builder setTimeout(long timeout, TimeUnit timeoutUnit) { this.timeout = timeout; this.timeoutUnit = timeoutUnit; return this; } /** * Specify a custom name for this reporter * * @param name the name to be used * @return itself */ @SuppressWarnings("unused") public Builder setName(String name) { this.name = name; return this; } /** * Use a custom sanitizer. All metric names are run through a sanitizer to ensure validity before being sent * along. Librato places some restrictions on the characters allowed in keys, so all keys are ultimately run * through APIUtil.lastPassSanitizer. Specifying an additional sanitizer (that runs before lastPassSanitizer) * allows the user to customize what they want done about invalid characters and excessively long metric names. * * @param sanitizer the custom sanitizer to use (defaults to a noop sanitizer). * @return itself */ @SuppressWarnings("unused") public Builder setSanitizer(Sanitizer sanitizer) { this.sanitizer = sanitizer; return this; } /** * Filter the metrics that this particular reporter publishes * * @param filter the {@link MetricFilter} * @return itself */ @SuppressWarnings("unused") public Builder setFilter(MetricFilter filter) { this.filter = filter; return this; } /** * use a custom clock * * @param clock to be used * @return itself */ @SuppressWarnings("unused") public Builder setClock(Clock clock) { this.clock = clock; return this; } /** * Enables control over how the reporter generates 'expanded' metrics from meters and histograms, * such as percentiles and rates. * * @param expansionConfig the configuration * @return itself * @see {@link ExpandedMetric} */ @SuppressWarnings("unused") public Builder setExpansionConfig(MetricExpansionConfig expansionConfig) { this.expansionConfig = expansionConfig; return this; } /** * Build the LibratoReporter as configured by this Builder * * @return a fully configured LibratoReporter */ public LibratoReporter build() { return new LibratoReporter( registry, name, filter, rateUnit, durationUnit, sanitizer, source, timeout, timeoutUnit, clock, expansionConfig, httpPoster, prefix, prefixDelimiter); } } /** * convenience method for creating a Builder */ public static Builder builder(MetricRegistry metricRegistry, String username, String token, String source) { return new Builder(metricRegistry, username, token, source); } public static enum ExpandedMetric { // sampling MEDIAN("median"), PCT_75("75th"), PCT_95("95th"), PCT_98("98th"), PCT_99("99th"), PCT_999("999th"), // metered COUNT("count"), RATE_MEAN("meanRate"), RATE_1_MINUTE("1MinuteRate"), RATE_5_MINUTE("5MinuteRate"), RATE_15_MINUTE("15MinuteRate"); private final String displayName; public String buildMetricName(String metric) { return metric + "." + displayName; } private ExpandedMetric(String displayName) { this.displayName = displayName; } } /** * Configures how to report "expanded" metrics derived from meters and histograms (e.g. percentiles, * rates, etc). Default is to report everything. * * @see ExpandedMetric */ public static class MetricExpansionConfig { public static MetricExpansionConfig ALL = new MetricExpansionConfig(EnumSet.allOf(ExpandedMetric.class)); private final Set<ExpandedMetric> enabled; public MetricExpansionConfig(Set<ExpandedMetric> enabled) { this.enabled = EnumSet.copyOf(enabled); } public boolean isSet(ExpandedMetric metric) { return enabled.contains(metric); } } /** * @param builder a LibratoReporter.Builder * @param interval the interval at which the metrics are to be reporter * @param unit the timeunit for interval */ public static void enable(Builder builder, long interval, TimeUnit unit) { builder.build().start(interval, unit); } }
src/main/java/com/librato/metrics/LibratoReporter.java
package com.librato.metrics; import com.codahale.metrics.*; import com.codahale.metrics.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.TimeUnit; /** * A reporter for publishing metrics to <a href="http://metrics.librato.com/">Librato Metrics</a> */ public class LibratoReporter extends ScheduledReporter implements MetricsLibratoBatch.RateConverter, MetricsLibratoBatch.DurationConverter { private static final Logger LOG = LoggerFactory.getLogger(LibratoReporter.class); private final DeltaTracker deltaTracker; private final String source; private final long timeout; private final TimeUnit timeoutUnit; private final Sanitizer sanitizer; private final HttpPoster httpPoster; private final String prefix; private final String prefixDelimiter; protected final MetricRegistry registry; protected final Clock clock; protected final MetricExpansionConfig expansionConfig; /** * Private. Use builder instead. */ private LibratoReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, Sanitizer customSanitizer, String source, long timeout, TimeUnit timeoutUnit, Clock clock, MetricExpansionConfig expansionConfig, HttpPoster httpPoster, String prefix, String prefixDelimiter) { super(registry, name, filter, rateUnit, durationUnit); this.registry = registry; this.sanitizer = customSanitizer; this.source = source; this.timeout = timeout; this.timeoutUnit = timeoutUnit; this.clock = clock; this.expansionConfig = expansionConfig; this.httpPoster = httpPoster; this.prefix = prefix; this.prefixDelimiter = prefixDelimiter; this.deltaTracker = new DeltaTracker(new DeltaMetricSupplier(registry, filter)); } public double convertMetricDuration(double duration) { return convertDuration(duration); } public double convertMetricRate(double rate) { return convertRate(rate); } /** * Used to supply metrics to the delta tracker on initialization. Uses the metric name conversion * to ensure that the correct names are supplied for the metric. */ class DeltaMetricSupplier implements DeltaTracker.MetricSupplier { final MetricRegistry registry; final MetricFilter filter; DeltaMetricSupplier(MetricRegistry registry, MetricFilter filter) { this.registry = registry; this.filter = filter; } public Map<String, Metric> getMetrics() { final Map<String, Metric> map = new HashMap<String, Metric>(); for (Map.Entry<String, Metric> entry : registry.getMetrics().entrySet()) { // todo: ensure the name here is what we expect final String name = entry.getKey(); map.put(name, entry.getValue()); } return map; } } /** * Starts the reporter polling at the given period. * * @param period the amount of time between polls * @param unit the unit for {@code period} */ @Override public void start(long period, TimeUnit unit) { LOG.debug("Reporter starting at fixed rate of every {} {}", period, unit); super.start(period, unit); } @Override public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) { final long epoch = TimeUnit.MILLISECONDS.toSeconds(clock.getTime()); final MetricsLibratoBatch batch = new MetricsLibratoBatch( LibratoBatch.DEFAULT_BATCH_SIZE, sanitizer, timeout, timeoutUnit, expansionConfig, httpPoster, prefix, prefixDelimiter, deltaTracker, this, this); for (Map.Entry<String, Gauge> entry : gauges.entrySet()) { batch.addGauge(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Counter> entry : counters.entrySet()) { batch.addCounter(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Histogram> entry : histograms.entrySet()) { batch.addHistogram(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Meter> entry : meters.entrySet()) { batch.addMeter(entry.getKey(), entry.getValue()); } for (Map.Entry<String, Timer> entry : timers.entrySet()) { batch.addTimer(entry.getKey(), entry.getValue()); } batch.post(source, epoch); } /** * A builder for the LibratoReporter class that requires things that cannot be inferred and uses * sane default values for everything else. */ public static class Builder { private final String source; private Sanitizer sanitizer = Sanitizer.NO_OP; private long timeout = 5; private TimeUnit timeoutUnit = TimeUnit.SECONDS; private TimeUnit rateUnit = TimeUnit.SECONDS; private TimeUnit durationUnit = TimeUnit.MILLISECONDS; private String name = "librato-reporter"; private final MetricRegistry registry; private MetricFilter filter = MetricFilter.ALL; private Clock clock = Clock.defaultClock(); private MetricExpansionConfig expansionConfig = MetricExpansionConfig.ALL; private HttpPoster httpPoster; private String prefix; private String prefixDelimiter = "."; public Builder(MetricRegistry registry, String username, String token, String source) { this.registry = registry; this.source = source; this.httpPoster = NingHttpPoster.newPoster(username, token, "https://metrics-api.librato.com"); } /** * Sets the timeout for POSTs to Librato * * @param timeout the timeout * @return itself */ @SuppressWarnings("unused") public Builder setTimeout(long timeout) { this.timeout = timeout; return this; } /** * Sets the timeout time unit for POSTs to Librato * * @param timeoutUnit the timeout unit * @return itself */ @SuppressWarnings("unused") public Builder setTimeoutUnit(TimeUnit timeoutUnit) { this.timeoutUnit = timeoutUnit; return this; } /** * Sets the delimiter which will separate the prefix from the metric name. Defaults * to "." * * @param prefixDelimiter the delimiter * @return itself */ @SuppressWarnings("unused") public Builder setPrefixDelimiter(String prefixDelimiter) { this.prefixDelimiter = prefixDelimiter; return this; } /** * Sets a prefix that will be prepended to all metric names * * @param prefix the prefix * @return itself */ @SuppressWarnings("unused") public Builder setPrefix(String prefix) { this.prefix = prefix; return this; } /** * Sets the {@link HttpPoster} which will send the payload to Librato * * @param poster the HttpPoster * @return itself */ @SuppressWarnings("unused") public Builder setHttpPoster(HttpPoster poster) { this.httpPoster = poster; return this; } /** * Sets the time unit to which rates will be converted by the reporter. The default * value is TimeUnit.SECONDS * * @param rateUnit the rate * @return itself */ @SuppressWarnings("unused") public Builder setRateUnit(TimeUnit rateUnit) { this.rateUnit = rateUnit; return this; } /** * Sets the time unit to which durations will be converted by the reporter. The default * value is TimeUnit.MILLISECONDS * * @param durationUnit the time unit * @return itself */ @SuppressWarnings("unused") public Builder setDurationUnit(TimeUnit durationUnit) { this.durationUnit = durationUnit; return this; } /** * set the HTTP timeout for a publishing attempt * * @param timeout duration to expect a response * @param timeoutUnit unit for duration * @return itself */ @SuppressWarnings("unused") public Builder setTimeout(long timeout, TimeUnit timeoutUnit) { this.timeout = timeout; this.timeoutUnit = timeoutUnit; return this; } /** * Specify a custom name for this reporter * * @param name the name to be used * @return itself */ @SuppressWarnings("unused") public Builder setName(String name) { this.name = name; return this; } /** * Use a custom sanitizer. All metric names are run through a sanitizer to ensure validity before being sent * along. Librato places some restrictions on the characters allowed in keys, so all keys are ultimately run * through APIUtil.lastPassSanitizer. Specifying an additional sanitizer (that runs before lastPassSanitizer) * allows the user to customize what they want done about invalid characters and excessively long metric names. * * @param sanitizer the custom sanitizer to use (defaults to a noop sanitizer). * @return itself */ @SuppressWarnings("unused") public Builder setSanitizer(Sanitizer sanitizer) { this.sanitizer = sanitizer; return this; } /** * Filter the metrics that this particular reporter publishes * * @param filter the {@link MetricFilter} * @return itself */ @SuppressWarnings("unused") public Builder setFilter(MetricFilter filter) { this.filter = filter; return this; } /** * use a custom clock * * @param clock to be used * @return itself */ @SuppressWarnings("unused") public Builder setClock(Clock clock) { this.clock = clock; return this; } /** * Enables control over how the reporter generates 'expanded' metrics from meters and histograms, * such as percentiles and rates. * * @param expansionConfig the configuration * @return itself * @see {@link ExpandedMetric} */ @SuppressWarnings("unused") public Builder setExpansionConfig(MetricExpansionConfig expansionConfig) { this.expansionConfig = expansionConfig; return this; } /** * Build the LibratoReporter as configured by this Builder * * @return a fully configured LibratoReporter */ public LibratoReporter build() { return new LibratoReporter( registry, name, filter, rateUnit, durationUnit, sanitizer, source, timeout, timeoutUnit, clock, expansionConfig, httpPoster, prefix, prefixDelimiter); } } /** * convenience method for creating a Builder */ public static Builder builder(MetricRegistry metricRegistry, String username, String token, String source) { return new Builder(metricRegistry, username, token, source); } public static enum ExpandedMetric { // sampling MEDIAN("median"), PCT_75("75th"), PCT_95("95th"), PCT_98("98th"), PCT_99("99th"), PCT_999("999th"), // metered COUNT("count"), RATE_MEAN("meanRate"), RATE_1_MINUTE("1MinuteRate"), RATE_5_MINUTE("5MinuteRate"), RATE_15_MINUTE("15MinuteRate"); private final String displayName; public String buildMetricName(String metric) { return metric + "." + displayName; } private ExpandedMetric(String displayName) { this.displayName = displayName; } } /** * Configures how to report "expanded" metrics derived from meters and histograms (e.g. percentiles, * rates, etc). Default is to report everything. * * @see ExpandedMetric */ public static class MetricExpansionConfig { public static MetricExpansionConfig ALL = new MetricExpansionConfig(EnumSet.allOf(ExpandedMetric.class)); private final Set<ExpandedMetric> enabled; public MetricExpansionConfig(Set<ExpandedMetric> enabled) { this.enabled = EnumSet.copyOf(enabled); } public boolean isSet(ExpandedMetric metric) { return enabled.contains(metric); } } /** * @param builder a LibratoReporter.Builder * @param interval the interval at which the metrics are to be reporter * @param unit the timeunit for interval */ public static void enable(Builder builder, long interval, TimeUnit unit) { builder.build().start(interval, unit); } }
Use the /v1/metrics endpoint
src/main/java/com/librato/metrics/LibratoReporter.java
Use the /v1/metrics endpoint
Java
apache-2.0
4b1820d2d3129351026d88af708c2b4144104d05
0
oanc/org.anc.lapps.gate,oanc/org.anc.lapps.gate
package org.anc.lapps.gate; import gate.Document; import gate.Factory; import gate.FeatureMap; import org.lappsgrid.api.Data; import org.lappsgrid.core.DataFactory; import org.lappsgrid.discriminator.Types; import org.lappsgrid.vocabulary.Annotations; import org.lappsgrid.vocabulary.Contents; import org.lappsgrid.vocabulary.Metadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SentenceSplitter extends PooledGateService { protected static final Logger logger = LoggerFactory.getLogger(SentenceSplitter.class); public SentenceSplitter() { super(); createResource("gate.creole.splitter.SentenceSplitter"); logger.info("Sentence splitter created."); } public long[] requires() { logger.info("Called requires"); return new long[] { Types.GATE, Types.TOKEN }; } public long[] produces() { logger.info("Called produces."); return new long[] { Types.GATE, Types.SENTENCE }; } public Data execute(Data input) { Document document = null; try { document = doExecute(input); } catch (Exception e) { return DataFactory.error("Unable to execute the Sentence Splitter.", e); } if (document == null) { return DataFactory.error(BUSY); } String producer = this.getClass().getName() + "_" + Version.getVersion(); FeatureMap features = document.getFeatures(); Integer step = (Integer) features.get("lapps:step"); if (step == null) { step = 1; } features.put("lapps:step", step + 1); features.put("lapps:" + Annotations.SENTENCE, step + " " + producer + " " + Contents.Chunks.SENTENCES); Data result = DataFactory.gateDocument(document.toXml()); Factory.deleteResource(document); return result; } }
src/main/java/org/anc/lapps/gate/SentenceSplitter.java
package org.anc.lapps.gate; import gate.Document; import gate.Factory; import gate.FeatureMap; import org.lappsgrid.api.Data; import org.lappsgrid.core.DataFactory; import org.lappsgrid.discriminator.Types; import org.lappsgrid.vocabulary.Annotations; import org.lappsgrid.vocabulary.Contents; import org.lappsgrid.vocabulary.Metadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SentenceSplitter extends PooledGateService { protected static final Logger logger = LoggerFactory.getLogger(SentenceSplitter.class); public SentenceSplitter() { super(); createResource("gate.creole.splitter.SentenceSplitter"); logger.info("Sentence splitter created."); } public long[] requires() { logger.info("Called requires"); return new long[] { Types.GATE, Types.TOKEN }; } public long[] produces() { logger.info("Called produces."); return new long[] { Types.GATE, Types.SENTENCE }; } public Data execute(Data input) { Document document = null; try { document = doExecute(input); } catch (Exception e) { return DataFactory.error("Unable to execute the Sentence Splitter.", e); } if (document == null) { return DataFactory.error(BUSY); } String producer = this.getClass().getName() + "_" + Version.getVersion(); FeatureMap features = document.getFeatures(); Integer step = (Integer) features.get("lapps:step"); if (step == null) { step = 1; } features.put("lapps:step", step + 1); features.put("lapps:" + Annotations.SENTENCE, step + " " + producer + " chunk:annie"); Data result = DataFactory.gateDocument(document.toXml()); Factory.deleteResource(document); return result; } }
Fixed metadata added by the SentenceSplitter
src/main/java/org/anc/lapps/gate/SentenceSplitter.java
Fixed metadata added by the SentenceSplitter
Java
apache-2.0
67f9451c88385c3240acf46fa86a2e4e461d6f81
0
kwmt/GitHubSearch
package net.kwmt27.codesearch.entity.events; import android.content.Context; import android.view.View; import android.widget.TextView; import com.google.android.flexbox.FlexboxLayout; import com.google.gson.annotations.SerializedName; import net.kwmt27.codesearch.entity.EventEntity; import net.kwmt27.codesearch.entity.payloads.FollowEventEntity; import net.kwmt27.codesearch.view.events.EventListFragment; /** * https://developer.github.com/v3/activity/events/types/#followevent * * Events of this type are no longer created, but it's possible that they exist in timelines of some users. */ public class FollowEvent extends EventEntity { @SerializedName("payload") private FollowEventEntity mFollowEventEntity; @Override public View createView(Context context, EventListFragment.OnLinkClickListener listener) { if (mFollowEventEntity == null) { return newTextView(context, "data empty", false, null); } FlexboxLayout flexboxLayout = newFlexboxLayout(context); TextView actionTextView = newTextView(context, "downloaded ", true, null); flexboxLayout.addView(actionTextView); TextView repoTextView = newTextView(context, mFollowEventEntity.getTargetUser().getLogin(), false, newOnLinkClickClickableSpan(listener, mFollowEventEntity.getTargetUser().getLogin(), mFollowEventEntity.getTargetUser().getHtmlUrl(), getRepo())); flexboxLayout.addView(repoTextView); return flexboxLayout; } }
app/src/main/java/net/kwmt27/codesearch/entity/events/FollowEvent.java
package net.kwmt27.codesearch.entity.events; import android.content.Context; import android.view.View; import android.widget.TextView; import com.google.android.flexbox.FlexboxLayout; import com.google.gson.annotations.SerializedName; import net.kwmt27.codesearch.entity.EventEntity; import net.kwmt27.codesearch.entity.payloads.FollowEventEntity; import net.kwmt27.codesearch.view.events.EventListFragment; public class FollowEvent extends EventEntity { @SerializedName("payload") private FollowEventEntity mFollowEventEntity; @Override public View createView(Context context, EventListFragment.OnLinkClickListener listener) { if (mFollowEventEntity == null) { return newTextView(context, "data empty", false, null); } FlexboxLayout flexboxLayout = newFlexboxLayout(context); TextView actionTextView = newTextView(context, "downloaded ", true, null); flexboxLayout.addView(actionTextView); TextView repoTextView = newTextView(context, mFollowEventEntity.getTargetUser().getLogin(), false, newOnLinkClickClickableSpan(listener, mFollowEventEntity.getTargetUser().getLogin(), mFollowEventEntity.getTargetUser().getHtmlUrl(), getRepo())); flexboxLayout.addView(repoTextView); return flexboxLayout; } }
add comment
app/src/main/java/net/kwmt27/codesearch/entity/events/FollowEvent.java
add comment
Java
bsd-3-clause
90526d7795ddd73704c741fd936af495d3808f80
0
mdcao/japsa,mdcao/japsa
/***************************************************************************** * Copyright (c) Minh Duc Cao, Monash Uni & UQ, All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * 3. Neither the names of the institutions nor the names of the contributors* * may be used to endorse or promote products derived from this software * * without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /************************** REVISION HISTORY ************************** * 18/10/2013 - Minh Duc Cao: Created * ****************************************************************************/ package japsa.tools.bio.np; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.math3.ml.clustering.Cluster; import org.apache.commons.math3.ml.clustering.DBSCANClusterer; import org.apache.commons.math3.ml.clustering.DoublePoint; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMRecordIterator; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import japsa.seq.Alphabet; import japsa.seq.Sequence; import japsa.seq.SequenceReader; import japsa.util.CommandLine; import japsa.util.deploy.Deployable; import japsa.bio.hts.scaffold.AlignmentRecord; import japsa.bio.hts.scaffold.Contig; @Deployable( scriptName = "jsa.np.flankDetect", scriptDesc = "Detect flanking sequences from both ends of nanopore reads. Results will be printed to stdout while logs to stderr." ) public class FlankSeqsDetectorCmd extends CommandLine{ private static final Logger LOG = LoggerFactory.getLogger(FlankSeqsDetectorCmd.class); public FlankSeqsDetectorCmd(){ super(); Deployable annotation = getClass().getAnnotation(Deployable.class); setUsage(annotation.scriptName() + " [options]"); setDesc(annotation.scriptDesc()); addString("flankFile",null,"Flank sequences file, maximum 2 sequences. The first one determines the true flank (LTR)",true); addString("refFile","","Reference sequences (human genome)"); addString("bamFile",null,"SAM/BAM file generated by aligning ONT reads to the ref and flank sequences",true); addDouble("qual", 1, "Mininum quality"); addInt("insert", 10, "Minimum length of the integration site"); addInt("tips", 20, "Maximum percentage of the overhangs compared to the corresponding flanking sequence"); addInt("distance", 3, "Distance for DBSCAN clustering algorithm."); addDouble("cover", 80, "Mininum percentage of flank sequence coverage for a valid alignment"); addStdHelp(); } /** * @param args */ public static void main(String[] args) throws IOException{ /*********************** Setting up script ****************************/ /*********************** Setting up script ****************************/ CommandLine cmdLine = new FlankSeqsDetectorCmd(); args = cmdLine.stdParseLine(args); /**********************************************************************/ String flankSeqsFile= cmdLine.getStringVal("flankFile"), refSeqsFile= cmdLine.getStringVal("refFile"); String bamFile = cmdLine.getStringVal("bamFile"); double qual = cmdLine.getDoubleVal("qual"), flkCov = cmdLine.getDoubleVal("cover"); int insertLength = cmdLine.getIntVal("insert"), distance = cmdLine.getIntVal("distance"), tipsPercentage = cmdLine.getIntVal("tips"); SequenceReader seqReader = SequenceReader.getReader(flankSeqsFile); Sequence seq; HashMap<String, Contig> refSeqs = new HashMap<>(); ArrayList<Contig> flankSeqs=new ArrayList<>(); int index=0; while ((seq = seqReader.nextSequence(Alphabet.DNA())) != null) flankSeqs.add(new Contig(index++,seq)); seqReader.close(); if(!refSeqsFile.isEmpty()){ seqReader = SequenceReader.getReader(refSeqsFile); index=0; while ((seq = seqReader.nextSequence(Alphabet.DNA())) != null) refSeqs.put(seq.getName(), new Contig(index++,seq)); seqReader.close(); } if(flankSeqs.size() > 2){ LOG.error("More than 2 sequences!"); System.exit(1); } SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT); SamReader reader = SamReaderFactory.makeDefault().open(new File(bamFile)); SAMRecordIterator iter = reader.iterator(); SAMRecord curSAMRecord=null; AlignmentRecord curAlnRecord=null; FlankRecord fr=null; String readID = ""; List<FlankRecord> records=new ArrayList<>(); /********************************************************************** ********************** Junctions detection *************************** **********************************************************************/ while (iter.hasNext()) { try { curSAMRecord = iter.next(); }catch(Exception e) { // LOG.warn("Ignore one faulty SAM record: \n {}", e.getMessage()); continue; } if (curSAMRecord.getReadUnmappedFlag() || curSAMRecord.getMappingQuality() < qual || curSAMRecord.isSecondaryAlignment()){ // LOG.info("Ignore record! Unmapped, low-quality or secondary alignment from {}...", curSAMRecord.getReadName()); continue; } if (!readID.equals(curSAMRecord.getReadName())){ //output prev if(fr!=null) records.add(new FlankRecord(fr)); //update for next readID = curSAMRecord.getReadName(); fr=new FlankRecord(readID); } //adding info to current FlankRecord Contig ctg=null; String refName = curSAMRecord.getReferenceName(); if(refSeqs.containsKey(refName)){ ctg=refSeqs.get(refName); curAlnRecord=new AlignmentRecord(curSAMRecord, ctg); if(curAlnRecord.readAlignmentEnd()-curAlnRecord.readAlignmentStart() < insertLength){ // LOG.info("Ignore record! Integration size too short: {}", curAlnRecord.toString()); continue; } if(fr.refRec==null||fr.refRec.qual < curAlnRecord.qual) fr.refRec=curAlnRecord; else if(fr.refRec.qual == curAlnRecord.qual){ // LOG.info("Ignore record! Confusing alignment on {}:\n {} \n {}", refName, curAlnRecord.toString(), fr.refRec); fr.refRec=null; continue; } }else{ if(flankSeqs.get(0).getName().equals(refName)){ ctg=flankSeqs.get(0); curAlnRecord=new AlignmentRecord(curSAMRecord, ctg); if(curAlnRecord.refEnd-curAlnRecord.refStart < (double)flkCov*ctg.length()/100.0) continue; //not too far from the tip of read else if(Math.min(-curAlnRecord.readAlignmentEnd()+curAlnRecord.readLength, curAlnRecord.readAlignmentStart()) > (double)ctg.length()*tipsPercentage/100.0){ continue; } if(fr.f0Rec==null||fr.f0Rec.qual < curAlnRecord.qual) fr.f0Rec=curAlnRecord; else if(fr.f0Rec.qual == curAlnRecord.qual){ // LOG.info("Ignore record! Confusing alignment on {}:\n {} \n {}", refName, curAlnRecord.toString(), fr.refRec); fr.f0Rec=null; continue; } }else if(flankSeqs.size()>1 && flankSeqs.get(1).getName().equals(refName)){ ctg=flankSeqs.get(1); curAlnRecord=new AlignmentRecord(curSAMRecord, ctg); if(curAlnRecord.refEnd-curAlnRecord.refStart < (double)flkCov*ctg.length()/100.0) continue; //not too far from the tip of read else if(Math.min(-curAlnRecord.readAlignmentEnd()+curAlnRecord.readLength, curAlnRecord.readAlignmentStart()) > (double)ctg.length()*tipsPercentage/100.0){ continue; } if(fr.f1Rec==null||fr.f1Rec.qual < curAlnRecord.qual) fr.f1Rec=curAlnRecord; else if(fr.f1Rec.qual == curAlnRecord.qual){ // LOG.info("Ignore record! Confusing alignment on {}:\n {} \n {}", refName, curAlnRecord.toString(), fr.refRec); fr.f1Rec=null; continue; } } // else // LOG.error("Sequence {} not found, ignored!", refName); } }// while //last time adding if (fr!=null) records.add(new FlankRecord(fr)); iter.close(); /********************************************************************** ********************** DBSCAN clustering ***************************** **********************************************************************/ List<DoublePoint> points = new ArrayList<DoublePoint>(); HashMap<Integer, List<FlankRecord>> tf2record = new HashMap<>(); //map each unique TF value to a list of records int f1=0, f2=0, f12=0, f0=0; for(int i=0;i<records.size();i++){ FlankRecord frec = records.get(i); if(frec.refRec==null) continue; else if(frec.f0Rec!=null && frec.f1Rec!=null){ f12++; }else if(frec.f0Rec!=null){ f1++; }else if(frec.f1Rec!=null){ f2++; continue; }else{ f0++; continue; } frec.calculateTF(flankSeqs.size()==2); if(frec.trueFlank>=0){ if(!tf2record.containsKey(frec.trueFlank)){ tf2record.put(frec.trueFlank, new ArrayList<>()); points.add(new DoublePoint(new double[]{frec.trueFlank})); } tf2record.get(frec.trueFlank).add(frec); } // else // System.err.printf("Ignore clustering of: %s\n", frec.toString()); } System.err.println("===================================================="); System.err.printf("Number of aligned reads with both flank: %d\n", f12); System.err.printf("Number of aligned reads with only flank %s: %d\n", flankSeqs.get(0).getName(), f1); if(flankSeqs.size()>1) System.err.printf("Number of aligned reads with only flank %s: %d\n", flankSeqs.get(1).getName(), f2); System.err.printf("Number of aligned reads with no flank: %d\n", f0); System.err.println("===================================================="); //minPts=0 to report every clusters, even ones with only 1 point DBSCANClusterer dbscan = new DBSCANClusterer(distance, 0, (a,b)->Math.abs(a[0]- b[0])); List<Cluster<DoublePoint>> cluster = dbscan.cluster(points); for(int i=0;i<cluster.size();i++) { Cluster<DoublePoint> c=cluster.get(i); TFCluster tfCluster=new TFCluster(); for(DoublePoint p:c.getPoints()){ int tf=(int)p.getPoint()[0]; tfCluster.set(tf, tf2record.get(tf).size()); for(FlankRecord rec:tf2record.get(tf)) rec.setTFCluster(tfCluster); } } System.out.println("#ReadID\tTarget\tStart\tEnd\tStrand\tJunction\tClusterID\tCount\tMin\tMax\tMod\tR50(bp)\tR80(bp)"); for(FlankRecord rec:records) System.out.println(rec.print()); } } //To maintain distribution for each cluster detected. class TFCluster{ private static final AtomicInteger count = new AtomicInteger(0); private final int ID; private int size; HashMap<Integer, Integer> distribution; TFCluster(){ ID=count.incrementAndGet(); distribution=new HashMap<>(); size=0; } public int getId(){ return ID; } public void set(int value, int count){ if(distribution.containsKey(value)){ System.err.println("Warning: "+value+" already present!");; } else distribution.put(value, count); size+=count; } public String toString(){ // DescriptiveStatistics stats = new DescriptiveStatistics(values.stream().mapToDouble(i->i).toArray()); Set<Integer> keys=distribution.keySet(); int min=Collections.min(keys), max=Collections.max(keys); final int max_values=Collections.max(distribution.values()); //if there is more than 1 modes, take the average double rmode=keys.stream().filter(k->(distribution.get(k)==max_values)).mapToDouble(k->k).average().orElse(Double.NaN); int mod=(int) Math.round(rmode); //calculate rX = minimal range from the mode making up X% of cluster size. // E.g. r50=2 meaning values from [mod-2,mod+2] making up 50% of the cluster int r50=-1, r80=-1; int count=distribution.containsKey(mod)?distribution.get(mod):0; for(int i=0; i < max-min+1; i++){ if(r50<0 && count>=.5*size) r50=i; if(r80<0 && count>=.8*size){ r80=i; break; } count+=distribution.containsKey(mod+i)?distribution.get(mod+i):0; count+=distribution.containsKey(mod-i)?distribution.get(mod-i):0; } return getId()+"\t"+size+"\t"+min+"\t"+max+"\t"+(int)mod+"\t"+(r50<0?"NA":r50)+"\t"+(r80<0?"NA":r80); } } // A record contains alignments to Human reference and flank sequences // The 3'-LTR junction site (trueFlank) is induced here class FlankRecord{ String readID; AlignmentRecord f0Rec, f1Rec, refRec; int trueFlank; TFCluster cluster; FlankRecord(String readID){ this.readID=readID; f0Rec=f1Rec=refRec=null; trueFlank=-1; cluster=null; } FlankRecord(FlankRecord rec){ readID=rec.readID; f0Rec=rec.f0Rec; f1Rec=rec.f1Rec; refRec=rec.refRec; trueFlank=rec.trueFlank; cluster=rec.cluster; } public void setTFCluster(TFCluster cluster){ this.cluster=cluster; } public String toString(){ String retval = readID+"\t"; if(f0Rec!=null) retval+=f0Rec.readStart+"\t"+f0Rec.readEnd+"\t"; else retval+="NA\tNA\t"; if(refRec!=null) retval+=refRec.readStart+"\t"+refRec.readEnd+"\t"; else retval+="NA\tNA\t"; if(f1Rec!=null) retval+=f1Rec.readStart+"\t"+f1Rec.readEnd+"\t"; else retval+="NA\tNA\t"; return retval+trueFlank; } //call to calculate true flank public void calculateTF(boolean bothFlank){ if((bothFlank && f1Rec==null)) return; if(refRec!=null && f0Rec!=null){ int t0=(refRec.readStart-f0Rec.readStart)*(refRec.readStart-f0Rec.readEnd), t1=(refRec.readEnd-f0Rec.readStart)*(refRec.readEnd-f0Rec.readEnd); trueFlank=(t0<t1?refRec.refStart:refRec.refEnd); } } public String print(){ String retval = readID+"\t"; if(refRec!=null) retval+=refRec.contig.getName()+"\t"+refRec.refStart+"\t"+refRec.refEnd+"\t"+(refRec.strand?"+":"-")+"\t"; else retval+="NA\tNA\tNA\tNA\t"; return retval+""+(trueFlank<0?"NA":trueFlank)+"\t"+(cluster==null?"NA\tNA\tNA\tNA\tNA\tNA\tNA":cluster.toString()); } }
src/main/java/japsa/tools/bio/np/FlankSeqsDetectorCmd.java
/***************************************************************************** * Copyright (c) Minh Duc Cao, Monash Uni & UQ, All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * 3. Neither the names of the institutions nor the names of the contributors* * may be used to endorse or promote products derived from this software * * without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /************************** REVISION HISTORY ************************** * 18/10/2013 - Minh Duc Cao: Created * ****************************************************************************/ package japsa.tools.bio.np; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.math3.ml.clustering.Cluster; import org.apache.commons.math3.ml.clustering.DBSCANClusterer; import org.apache.commons.math3.ml.clustering.DoublePoint; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMRecordIterator; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import japsa.seq.Alphabet; import japsa.seq.Sequence; import japsa.seq.SequenceReader; import japsa.util.CommandLine; import japsa.util.deploy.Deployable; import japsa.bio.hts.scaffold.AlignmentRecord; import japsa.bio.hts.scaffold.Contig; @Deployable( scriptName = "jsa.np.flankDetect", scriptDesc = "Detect flanking sequences from both ends of nanopore reads. Results will be printed to stdout while logs to stderr." ) public class FlankSeqsDetectorCmd extends CommandLine{ private static final Logger LOG = LoggerFactory.getLogger(FlankSeqsDetectorCmd.class); public FlankSeqsDetectorCmd(){ super(); Deployable annotation = getClass().getAnnotation(Deployable.class); setUsage(annotation.scriptName() + " [options]"); setDesc(annotation.scriptDesc()); addString("flankFile",null,"Flank sequences file, maximum 2 sequences",true); addString("refFile","","Reference sequences"); addString("bamFile",null,"Bam file",true); addDouble("qual", 1, "Mininum quality"); addInt("insert", 10, "Minimum length of insert sequence in-between 2 flanking sequences"); addInt("tips", 20, "Maximum percentage of the overhangs compared to the corresponding flanking sequence"); addInt("distance", 3, "Distance for DBSCAN clustering algorithm."); addDouble("cover", 80, "Mininum percentage of flank sequence coverage for a valid alignment"); addStdHelp(); } /** * @param args */ public static void main(String[] args) throws IOException{ /*********************** Setting up script ****************************/ /*********************** Setting up script ****************************/ CommandLine cmdLine = new FlankSeqsDetectorCmd(); args = cmdLine.stdParseLine(args); /**********************************************************************/ String flankSeqsFile= cmdLine.getStringVal("flankFile"), refSeqsFile= cmdLine.getStringVal("refFile"); String bamFile = cmdLine.getStringVal("bamFile"); double qual = cmdLine.getDoubleVal("qual"), flkCov = cmdLine.getDoubleVal("cover"); int insertLength = cmdLine.getIntVal("insert"), distance = cmdLine.getIntVal("distance"), tipsPercentage = cmdLine.getIntVal("tips"); SequenceReader seqReader = SequenceReader.getReader(flankSeqsFile); Sequence seq; HashMap<String, Contig> refSeqs = new HashMap<>(); ArrayList<Contig> flankSeqs=new ArrayList<>(); int index=0; while ((seq = seqReader.nextSequence(Alphabet.DNA())) != null) flankSeqs.add(new Contig(index++,seq)); seqReader.close(); if(!refSeqsFile.isEmpty()){ seqReader = SequenceReader.getReader(refSeqsFile); index=0; while ((seq = seqReader.nextSequence(Alphabet.DNA())) != null) refSeqs.put(seq.getName(), new Contig(index++,seq)); seqReader.close(); } if(flankSeqs.size() > 2){ System.err.println("More than 2 sequences!"); System.exit(1); } SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT); SamReader reader = SamReaderFactory.makeDefault().open(new File(bamFile)); SAMRecordIterator iter = reader.iterator(); SAMRecord curSAMRecord=null; AlignmentRecord curAlnRecord=null; FlankRecord fr=null; String readID = ""; List<FlankRecord> records=new ArrayList<>(); /********************************************************************** ********************** Junctions detection *************************** **********************************************************************/ while (iter.hasNext()) { try { curSAMRecord = iter.next(); }catch(Exception e) { LOG.warn("Ignore one faulty SAM record: \n {}", e.getMessage()); continue; } if (curSAMRecord.getReadUnmappedFlag() || curSAMRecord.getMappingQuality() < qual || curSAMRecord.isSecondaryAlignment()){ LOG.info("Ignore record! Unmapped, low-quality or secondary alignment from {}...", curSAMRecord.getReadName()); continue; } if (!readID.equals(curSAMRecord.getReadName())){ //output prev if(fr!=null){ // System.out.println(fr.printJunctionOnRef()); records.add(new FlankRecord(fr)); } //update for next readID = curSAMRecord.getReadName(); fr=new FlankRecord(readID); } //adding info to current FlankRecord Contig ctg=null; String refName = curSAMRecord.getReferenceName(); if(refSeqs.containsKey(refName)){ ctg=refSeqs.get(refName); curAlnRecord=new AlignmentRecord(curSAMRecord, ctg); if(curAlnRecord.readAlignmentEnd()-curAlnRecord.readAlignmentStart() < insertLength){ LOG.info("Ignore record! Integration size too short: {}", curAlnRecord.toString()); continue; } if(fr.refRec==null||fr.refRec.qual < curAlnRecord.qual) fr.refRec=curAlnRecord; else if(fr.refRec.qual == curAlnRecord.qual){ LOG.info("Ignore record! Confusing alignment on {}:\n {} \n {}", refName, curAlnRecord.toString(), fr.refRec); fr.refRec=null; continue; } }else{ if(flankSeqs.get(0).getName().equals(refName)){ ctg=flankSeqs.get(0); curAlnRecord=new AlignmentRecord(curSAMRecord, ctg); if(curAlnRecord.refEnd-curAlnRecord.refStart < (double)flkCov*ctg.length()/100.0) continue; //not too far from the tip of read else if(Math.min(-curAlnRecord.readAlignmentEnd()+curAlnRecord.readLength, curAlnRecord.readAlignmentStart()) > (double)ctg.length()*tipsPercentage/100.0){ continue; } if(fr.f0Rec==null||fr.f0Rec.qual < curAlnRecord.qual) fr.f0Rec=curAlnRecord; else if(fr.f0Rec.qual == curAlnRecord.qual){ LOG.info("Ignore record! Confusing alignment on {}:\n {} \n {}", refName, curAlnRecord.toString(), fr.refRec); fr.f0Rec=null; continue; } }else if(flankSeqs.size()>1 && flankSeqs.get(1).getName().equals(refName)){ ctg=flankSeqs.get(1); curAlnRecord=new AlignmentRecord(curSAMRecord, ctg); if(curAlnRecord.refEnd-curAlnRecord.refStart < (double)flkCov*ctg.length()/100.0) continue; //not too far from the tip of read else if(Math.min(-curAlnRecord.readAlignmentEnd()+curAlnRecord.readLength, curAlnRecord.readAlignmentStart()) > (double)ctg.length()*tipsPercentage/100.0){ continue; } if(fr.f1Rec==null||fr.f1Rec.qual < curAlnRecord.qual) fr.f1Rec=curAlnRecord; else if(fr.f1Rec.qual == curAlnRecord.qual){ LOG.info("Ignore record! Confusing alignment on {}:\n {} \n {}", refName, curAlnRecord.toString(), fr.refRec); fr.f1Rec=null; continue; } }else{ LOG.info("Flank not found: {} != {}!", refName, flankSeqs.get(0).getName()); System.exit(1); } } }// while iter.close(); /********************************************************************** ********************** DBSCAN clustering ***************************** **********************************************************************/ List<DoublePoint> points = new ArrayList<DoublePoint>(); for(int i=0;i<records.size();i++){ FlankRecord frec = records.get(i); frec.calculateTF(); if(frec.trueFlank>0) points.add(new DoublePoint(new double[]{frec.trueFlank, new Double(i)})); } //minPts=0 to report every clusters, even ones with only 1 point DBSCANClusterer dbscan = new DBSCANClusterer(distance, 0, (a,b)->Math.abs(a[0]- b[0])); List<Cluster<DoublePoint>> cluster = dbscan.cluster(points); for(int i=0;i<cluster.size();i++) { Cluster<DoublePoint> c=cluster.get(i); TFCluster tfCluster=new TFCluster(); for(DoublePoint p:c.getPoints()){ records.get((int)p.getPoint()[1]).setTFCluster(tfCluster); tfCluster.add((int)p.getPoint()[0]); } } System.out.println("#ReadID\tTarget\tStart\tEnd\tStrand\tJunction\tClusterID\tCount\tMin\tMax\tMod\tR50(bp)\tR80(bp)"); for(FlankRecord rec:records) System.out.println(rec.print()); } } //To maintain distribution for each cluster detected. class TFCluster{ private static final AtomicInteger count = new AtomicInteger(0); private final int ID; private int size; HashMap<Integer, Integer> distribution; TFCluster(){ ID=count.incrementAndGet(); distribution=new HashMap<>(); size=0; } public int getId(){ return ID; } public void add(int value){ if(distribution.containsKey(value)) distribution.put(value, distribution.get(value)+1); else distribution.put(value, 1); size++; } public String toString(){ // DescriptiveStatistics stats = new DescriptiveStatistics(values.stream().mapToDouble(i->i).toArray()); Set<Integer> keys=distribution.keySet(); int min=Collections.min(keys), max=Collections.max(keys); final int max_values=Collections.max(distribution.values()); //if there is more than 1 modes, take the average double rmode=keys.stream().filter(k->(distribution.get(k)==max_values)).mapToDouble(k->k).average().orElse(Double.NaN); int mod=(int) Math.round(rmode); //calculate rX = minimal range from the mode making up X% of cluster size. // E.g. r50=2 meaning values from [mod-2,mod+2] making up 50% of the cluster int r50=-1, r80=-1; int count=distribution.containsKey(mod)?distribution.get(mod):0; for(int i=0; i < max-min+1; i++){ if(r50<0 && count>=.5*size) r50=i; if(r80<0 && count>=.8*size){ r80=i; break; } count+=distribution.containsKey(mod+i)?distribution.get(mod+i):0; count+=distribution.containsKey(mod-i)?distribution.get(mod-i):0; } return getId()+"\t"+size+"\t"+min+"\t"+max+"\t"+(int)mod+"\t"+(r50<0?"NA":r50)+"\t"+(r80<0?"NA":r80); } } // A record contains alignments to Human reference and flank sequences // The 3'-LTR junction site (trueFlank) is induced here class FlankRecord{ String readID; AlignmentRecord f0Rec, f1Rec, refRec; int trueFlank; TFCluster cluster; FlankRecord(String readID){ this.readID=readID; f0Rec=f1Rec=refRec=null; trueFlank=-1; cluster=null; } FlankRecord(FlankRecord rec){ readID=rec.readID; f0Rec=rec.f0Rec; f1Rec=rec.f1Rec; refRec=rec.refRec; trueFlank=rec.trueFlank; cluster=rec.cluster; } public void setTFCluster(TFCluster cluster){ this.cluster=cluster; } public String toString(){ String retval = readID+"\t"; if(f0Rec!=null) retval+=f0Rec.readStart+"\t"+f0Rec.readEnd+"\t"; else retval+="NA\tNA\t"; if(refRec!=null) retval+=refRec.readStart+"\t"+refRec.readEnd+"\t"; else retval+="NA\tNA\t"; if(f1Rec!=null) retval+=f1Rec.readStart+"\t"+f1Rec.readEnd+"\t"; else retval+="NA\tNA\t"; return retval+trueFlank; } //call to calculate true flank public void calculateTF(){ if(refRec!=null && f0Rec!=null){ int t0=(refRec.readStart-f0Rec.readStart)*(refRec.readStart-f0Rec.readEnd), t1=(refRec.readEnd-f0Rec.readStart)*(refRec.readEnd-f0Rec.readEnd); trueFlank=(t0<t1?refRec.refStart:refRec.refEnd); } } public String print(){ String retval = readID+"\t"; if(refRec!=null) retval+=refRec.contig.getName()+"\t"+refRec.refStart+"\t"+refRec.refEnd+"\t"+(refRec.strand?"+":"-")+"\t"; else retval+="NA\tNA\tNA\tNA\t"; return retval+""+(trueFlank<0?"NA":trueFlank)+"\t"+(cluster==null?"NA\tNA\tNA\tNA\tNA\tNA\tNA":cluster.toString()); } }
optimize DBSCAn
src/main/java/japsa/tools/bio/np/FlankSeqsDetectorCmd.java
optimize DBSCAn
Java
mit
3a2b1bcedf7d4aed554daba7dbc95f215ceaa39a
0
gitj-client/gitj,redpois0n/gitj
package com.redpois0n.gitj.ui.components; import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JPanel; import com.redpois0n.git.Chunk; import com.redpois0n.git.CodeLine; import com.redpois0n.git.Diff; @SuppressWarnings("serial") public class DiffPanel extends JPanel { private Diff diff; private int prefWidth; private int prefHeight; public DiffPanel(Diff diff) { this.diff = diff; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); FontMetrics metrics = g.getFontMetrics(g.getFont()); if (prefWidth == 0 || prefHeight == 0) { for (Chunk chunk : diff.getChunks()) { prefHeight += 10; for (CodeLine line : chunk.getLines()) { int sw = metrics.stringWidth(line.getLine()); if (sw > prefWidth) { prefWidth = sw; } prefHeight += metrics.getHeight() + 2; } } } int y = 0; for (Chunk chunk : diff.getChunks()) { y += 10; for (CodeLine line : chunk.getLines()) { if (line.getType() == CodeLine.Type.ADDED) { g.setColor(new Color(212, 234, 205)); } else if (line.getType() == CodeLine.Type.REMOVED) { g.setColor(new Color(240, 214, 214)); } else { g.setColor(Color.white); } g.fillRect(0, y, prefWidth, metrics.getHeight() + 2); g.setColor(Color.black); g.drawString(line.getLine(), 0, y + metrics.getHeight()); y += metrics.getHeight() + 2; } } g.drawRect(0, 0, getWidth(), getHeight()); super.setSize(getDimension()); super.setPreferredSize(getDimension()); } public Dimension getDimension() { return new Dimension(prefWidth, prefHeight); } public int getPrefWidth() { return prefWidth; } public int getPrefHeight() { return prefHeight; } }
src/com/redpois0n/gitj/ui/components/DiffPanel.java
package com.redpois0n.gitj.ui.components; import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JPanel; import com.redpois0n.git.Chunk; import com.redpois0n.git.CodeLine; import com.redpois0n.git.Diff; @SuppressWarnings("serial") public class DiffPanel extends JPanel { private Diff diff; private int prefWidth; private int prefHeight; public DiffPanel(Diff diff) { this.diff = diff; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); FontMetrics metrics = g.getFontMetrics(g.getFont()); if (prefWidth == 0 || prefHeight == 0) { for (Chunk chunk : diff.getChunks()) { prefHeight += 10; for (CodeLine line : chunk.getLines()) { int sw = metrics.stringWidth(line.getLine()); if (sw > prefWidth) { prefWidth = sw; } prefHeight += metrics.getHeight() + 2; } } } int y = 0; for (Chunk chunk : diff.getChunks()) { y += 10; for (CodeLine line : chunk.getLines()) { if (line.getType() == CodeLine.Type.ADDED) { g.setColor(Color.green); } else if (line.getType() == CodeLine.Type.REMOVED) { g.setColor(Color.red); } else { g.setColor(Color.white); } g.fillRect(0, y, prefWidth, metrics.getHeight() + 2); g.setColor(Color.black); g.drawString(line.getLine(), 0, y + metrics.getHeight()); y += metrics.getHeight() + 2; } } g.drawRect(0, 0, getWidth(), getHeight()); super.setSize(getDimension()); super.setPreferredSize(getDimension()); } public Dimension getDimension() { return new Dimension(prefWidth, prefHeight); } public int getPrefWidth() { return prefWidth; } public int getPrefHeight() { return prefHeight; } }
SourceTree colors
src/com/redpois0n/gitj/ui/components/DiffPanel.java
SourceTree colors
Java
mit
79cf67b65085495bf0191273755b04065a6a296b
0
conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5
package com.conveyal.r5.analyst.broker; /** * Describes the status of Job. */ public class JobStatus { /** number of complete tasks */ public int complete; /** number of tasks remaining */ public int remaining; /** number of tasks in flight (i.e. on workers now) */ public int inFlight; /** number of workers on this job */ public int nWorkers; /** The graph ID */ public String graphId; /** ID of this job */ public String jobId; public JobStatus (Job job) { this.complete = job.getCompletedTaskCount(); this.inFlight = job.invisibleUntil.size(); this.remaining = job.tasksAwaitingDelivery.size(); this.jobId = job.jobId; this.graphId = job.graphId; } /** default constructor for JSON deserialization */ public JobStatus () { /* nothing */ } }
src/main/java/com/conveyal/r5/analyst/broker/JobStatus.java
package com.conveyal.r5.analyst.broker; /** * Describes the status of Job. */ public class JobStatus { /** number of complete tasks */ public int complete; /** number of tasks remaining */ public int remaining; /** number of tasks in flight (i.e. on workers now) */ public int inFlight; /** number of workers on this job */ public int nWorkers; /** ID of this job */ public String jobId; public JobStatus (Job job) { this.complete = job.getCompletedTaskCount(); this.inFlight = job.invisibleUntil.size(); this.remaining = job.tasksAwaitingDelivery.size(); this.jobId = job.jobId; } /** default constructor for JSON deserialization */ public JobStatus () { /* nothing */ } }
add graph ID to job status, for debugging.
src/main/java/com/conveyal/r5/analyst/broker/JobStatus.java
add graph ID to job status, for debugging.
Java
mit
6fe612d19e97bcd2688791abb2be34d631e46bc2
0
wmaop/wm-aop-util
package org.wmaop.util.jexl; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.apache.commons.jexl2.Expression; import org.apache.commons.jexl2.MapContext; import org.junit.Test; public class FunctionsTest { @Test public void shouldPatternMatchWithinArray() { Expression expr = JexlExpressionFactory.getEngine().createExpression( "arrays:matches(values, '.*orld')"); MapContext mc = new MapContext(); mc.set("values", new String[] { "This", "is", "hello world" }); assertTrue((Boolean) expr.evaluate(mc)); } @Test public void shouldStringContainWithinArray() { Expression expr = JexlExpressionFactory.getEngine().createExpression( "arrays:contains(values, 'or')"); MapContext mc = new MapContext(); mc.set("values", new String[] { "This", "is", "hello world" }); assertTrue((Boolean) expr.evaluate(mc)); } @Test public void shouldHandleNullArrayInputForStringContain() { Expression expr = JexlExpressionFactory.getEngine().createExpression( "arrays:contains(values, 'or')"); MapContext mc = new MapContext(); mc.set("values", null); assertNull(expr.evaluate(mc)); } @Test public void shouldHandleNullArrayInputForStringMatch() { Expression expr = JexlExpressionFactory.getEngine().createExpression( "arrays:matches(values, '.*orld')"); MapContext mc = new MapContext(); mc.set("values", null); assertNull(expr.evaluate(mc)); } }
src/test/java/org/wmaop/util/jexl/FunctionsTest.java
package org.wmaop.util.jexl; import static org.junit.Assert.*; import org.apache.commons.jexl2.Expression; import org.apache.commons.jexl2.JexlContext; import org.apache.commons.jexl2.MapContext; import org.junit.Test; public class FunctionsTest { @Test public void shouldPatternMatchWithinArray() { Expression expr = JexlExpressionFactory.getEngine().createExpression( "arrays:matches(values, '.*orld')"); MapContext mc = new MapContext(); mc.set("values", new String[] { "This", "is", "hello world" }); assertTrue((Boolean) expr.evaluate(mc)); } @Test public void shouldStringContainWithinArray() { Expression expr = JexlExpressionFactory.getEngine().createExpression( "arrays:contains(values, 'or')"); MapContext mc = new MapContext(); mc.set("values", new String[] { "This", "is", "hello world" }); assertTrue((Boolean) expr.evaluate(mc)); } @Test public void shouldHandleNullArrayInputForStringContain() { Expression expr = JexlExpressionFactory.getEngine().createExpression( "arrays:contains(values, 'or')"); MapContext mc = new MapContext(); mc.set("values", null); assertNull(expr.evaluate(mc)); } @Test public void shouldHandleNullArrayInputForStringMatch() { Expression expr = JexlExpressionFactory.getEngine().createExpression( "arrays:matches(values, '.*orld')"); MapContext mc = new MapContext(); mc.set("values", null); assertNull(expr.evaluate(mc)); } }
Update markers
src/test/java/org/wmaop/util/jexl/FunctionsTest.java
Update markers
Java
mit
752e8e8fe9a453b4f30fe91baea929f02cc7067d
0
KWStudios/RageMode,KWStudios/RageMode
package org.kwstudios.play.ragemode.gameLogic; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.gmail.zahusek.tinyprotocolapi.api.tabapi.TabAPI; public class TabGuiUpdater { public static void setTabGui(List<String> playerUUIDs) { for (String playerUUID : playerUUIDs) { Player player = Bukkit.getPlayer(UUID.fromString(playerUUID)); setTitles(player); TabAPI.modifyTab(player); } } public static void setTabGui(String playerUUID) { Player player = Bukkit.getPlayer(UUID.fromString(playerUUID)); setTitles(player); TabAPI.modifyTab(player); } public static void updateTabGui(String gameName) { List<PlayerPoints> playersPoints = new ArrayList<PlayerPoints>(); String[] playersInGame = PlayerList.getPlayersInGame(gameName); if (playersInGame != null) { for (String playerInGame : playersInGame) { if (playerInGame != null) { PlayerPoints playerPoints = RageScores.getPlayerPoints(playerInGame); if (playerPoints != null) { playersPoints.add(playerPoints); } } } } for (PlayerPoints playerPoints : playersPoints) { Player player = Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID())); TabAPI.setTabSlot(player, 0, 1, ChatColor.BLUE + Integer.toString(playersPoints.size()), 0); } Collections.sort(playersPoints); for (int i = 0; i < playersPoints.size(); i++) { PlayerPoints playerPoints = playersPoints.get(i); Player player = Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID())); int points = playerPoints.getPoints(); int kills = playerPoints.getKills(); int deaths = playerPoints.getDeaths(); for (PlayerPoints innerPlayerPoints : playersPoints) { Player innerPlayer = Bukkit.getPlayer(UUID.fromString(innerPlayerPoints.getPlayerUUID())); TabAPI.setTabSlot(innerPlayer, 0, i + 5, ChatColor.YELLOW + Integer.toString(points), 0); TabAPI.setTabSlot(innerPlayer, 1, i + 5, ChatColor.YELLOW + player.getName(), 0); TabAPI.setTabSlot(innerPlayer, 2, i + 5, ChatColor.YELLOW + Integer.toString(kills) + " - " + Integer.toString(deaths), 0); } } for (PlayerPoints playerPoints : playersPoints) { TabAPI.modifyTab(Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID()))); } } private static void setTitles(Player player) { TabAPI.setTabHnF(player, ChatColor.DARK_RED + "RageMode", ChatColor.translateAlternateColorCodes('&', "&eKWStudios.org ") + ChatColor.translateAlternateColorCodes('&', "&3Network")); TabAPI.setTabSlot(player, 0, 0, ChatColor.translateAlternateColorCodes('&', "&9Player"), 100); TabAPI.setTabSlot(player, 1, 0, ChatColor.translateAlternateColorCodes('&', "&9Time"), 100); TabAPI.setTabSlot(player, 2, 0, ChatColor.translateAlternateColorCodes('&', "&9Map"), 100); TabAPI.setTabSlot(player, 0, 4, ChatColor.translateAlternateColorCodes('&', "&6&lPoints"), 100); TabAPI.setTabSlot(player, 1, 4, ChatColor.translateAlternateColorCodes('&', "&6&lPlayer"), 100); TabAPI.setTabSlot(player, 2, 4, ChatColor.translateAlternateColorCodes('&', "&6&lKills - Deaths"), 100); } }
src/org/kwstudios/play/ragemode/gameLogic/TabGuiUpdater.java
package org.kwstudios.play.ragemode.gameLogic; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import com.gmail.zahusek.tinyprotocolapi.api.tabapi.TabAPI; public class TabGuiUpdater { public static void setTabGui(List<String> playerUUIDs) { for (String playerUUID : playerUUIDs) { Player player = Bukkit.getPlayer(UUID.fromString(playerUUID)); setTitles(player); TabAPI.modifyTab(player); } } public static void setTabGui(String playerUUID) { Player player = Bukkit.getPlayer(UUID.fromString(playerUUID)); setTitles(player); TabAPI.modifyTab(player); } public static void updateTabGui(String gameName) { List<PlayerPoints> playersPoints = new ArrayList<PlayerPoints>(); String[] playersInGame = PlayerList.getPlayersInGame(gameName); for (String playerInGame : playersInGame) { PlayerPoints playerPoints = RageScores.getPlayerPoints(playerInGame); if (playerPoints != null) { playersPoints.add(playerPoints); } } for (PlayerPoints playerPoints : playersPoints) { Player player = Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID())); TabAPI.setTabSlot(player, 0, 1, ChatColor.BLUE + Integer.toString(playersPoints.size()), 0); } Collections.sort(playersPoints); for (int i = 0; i < playersPoints.size(); i++) { PlayerPoints playerPoints = playersPoints.get(i); Player player = Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID())); int points = playerPoints.getPoints(); int kills = playerPoints.getKills(); int deaths = playerPoints.getDeaths(); for (PlayerPoints innerPlayerPoints : playersPoints) { Player innerPlayer = Bukkit.getPlayer(UUID.fromString(innerPlayerPoints.getPlayerUUID())); TabAPI.setTabSlot(innerPlayer, 0, i + 5, ChatColor.YELLOW + Integer.toString(points), 0); TabAPI.setTabSlot(innerPlayer, 1, i + 5, ChatColor.YELLOW + player.getName(), 0); TabAPI.setTabSlot(innerPlayer, 2, i + 5, ChatColor.YELLOW + Integer.toString(kills) + " - " + Integer.toString(deaths), 0); } } for (PlayerPoints playerPoints : playersPoints) { TabAPI.modifyTab(Bukkit.getPlayer(UUID.fromString(playerPoints.getPlayerUUID()))); } } private static void setTitles(Player player) { TabAPI.setTabHnF(player, ChatColor.DARK_RED + "RageMode", ChatColor.translateAlternateColorCodes('&', "&eKWStudios.org ") + ChatColor.translateAlternateColorCodes('&', "&3Network")); TabAPI.setTabSlot(player, 0, 0, ChatColor.translateAlternateColorCodes('&', "&9Player"), 100); TabAPI.setTabSlot(player, 1, 0, ChatColor.translateAlternateColorCodes('&', "&9Time"), 100); TabAPI.setTabSlot(player, 2, 0, ChatColor.translateAlternateColorCodes('&', "&9Map"), 100); TabAPI.setTabSlot(player, 0, 4, ChatColor.translateAlternateColorCodes('&', "&6&lPoints"), 100); TabAPI.setTabSlot(player, 1, 4, ChatColor.translateAlternateColorCodes('&', "&6&lPlayer"), 100); TabAPI.setTabSlot(player, 2, 4, ChatColor.translateAlternateColorCodes('&', "&6&lKills - Deaths"), 100); } }
Removed NullPointerException in TabGuiUpdater.
src/org/kwstudios/play/ragemode/gameLogic/TabGuiUpdater.java
Removed NullPointerException in TabGuiUpdater.
Java
mpl-2.0
114f99b58e7345ebec28da69e7fa47e928225c48
0
kristopherschmidt/openmrs-core,rbtracker/openmrs-core,Bhamni/openmrs-core,aboutdata/openmrs-core,donaldgavis/openmrs-core,sadhanvejella/openmrs,sintjuri/openmrs-core,sravanthi17/openmrs-core,Winbobob/openmrs-core,hoquangtruong/TestMylyn,dlahn/openmrs-core,preethi29/openmrs-core,milankarunarathne/openmrs-core,MuhammadSafwan/Stop-Button-Ability,chethandeshpande/openmrs-core,vinayvenu/openmrs-core,sravanthi17/openmrs-core,spereverziev/openmrs-core,maekstr/openmrs-core,trsorsimoII/openmrs-core,jamesfeshner/openmrs-module,Winbobob/openmrs-core,Negatu/openmrs-core,foolchan2556/openmrs-core,MuhammadSafwan/Stop-Button-Ability,hoquangtruong/TestMylyn,rbtracker/openmrs-core,Openmrs-joel/openmrs-core,jvena1/openmrs-core,macorrales/openmrs-core,WANeves/openmrs-core,kabariyamilind/openMRSDEV,alexei-grigoriev/openmrs-core,shiangree/openmrs-core,jamesfeshner/openmrs-module,lilo2k/openmrs-core,jcantu1988/openmrs-core,dcmul/openmrs-core,lilo2k/openmrs-core,nilusi/Legacy-UI,trsorsimoII/openmrs-core,aj-jaswanth/openmrs-core,alexei-grigoriev/openmrs-core,iLoop2/openmrs-core,ern2/openmrs-core,Negatu/openmrs-core,vinayvenu/openmrs-core,sravanthi17/openmrs-core,joansmith/openmrs-core,jamesfeshner/openmrs-module,iLoop2/openmrs-core,trsorsimoII/openmrs-core,jembi/openmrs-core,iLoop2/openmrs-core,ssmusoke/openmrs-core,siddharthkhabia/openmrs-core,michaelhofer/openmrs-core,hoquangtruong/TestMylyn,macorrales/openmrs-core,WANeves/openmrs-core,sintjuri/openmrs-core,Openmrs-joel/openmrs-core,Winbobob/openmrs-core,joansmith/openmrs-core,koskedk/openmrs-core,foolchan2556/openmrs-core,macorrales/openmrs-core,kckc/openmrs-core,alexwind26/openmrs-core,shiangree/openmrs-core,andyvand/OpenMRS,MitchellBot/openmrs-core,chethandeshpande/openmrs-core,MitchellBot/openmrs-core,geoff-wasilwa/openmrs-core,kigsmtua/openmrs-core,donaldgavis/openmrs-core,foolchan2556/openmrs-core,kigsmtua/openmrs-core,spereverziev/openmrs-core,WANeves/openmrs-core,naraink/openmrs-core,siddharthkhabia/openmrs-core,MuhammadSafwan/Stop-Button-Ability,maekstr/openmrs-core,shiangree/openmrs-core,shiangree/openmrs-core,prisamuel/openmrs-core,kckc/openmrs-core,Winbobob/openmrs-core,iLoop2/openmrs-core,spereverziev/openmrs-core,siddharthkhabia/openmrs-core,maany/openmrs-core,pselle/openmrs-core,sadhanvejella/openmrs,dcmul/openmrs-core,sintjuri/openmrs-core,Bhamni/openmrs-core,kckc/openmrs-core,andyvand/OpenMRS,dlahn/openmrs-core,spereverziev/openmrs-core,lilo2k/openmrs-core,nilusi/Legacy-UI,pselle/openmrs-core,maany/openmrs-core,vinayvenu/openmrs-core,ldf92/openmrs-core,jvena1/openmrs-core,koskedk/openmrs-core,nilusi/Legacy-UI,AbhijitParate/openmrs-core,rbtracker/openmrs-core,milankarunarathne/openmrs-core,dlahn/openmrs-core,koskedk/openmrs-core,jembi/openmrs-core,nilusi/Legacy-UI,iLoop2/openmrs-core,jcantu1988/openmrs-core,naraink/openmrs-core,rbtracker/openmrs-core,maany/openmrs-core,dlahn/openmrs-core,asifur77/openmrs,nilusi/Legacy-UI,milankarunarathne/openmrs-core,geoff-wasilwa/openmrs-core,dcmul/openmrs-core,siddharthkhabia/openmrs-core,aboutdata/openmrs-core,vinayvenu/openmrs-core,macorrales/openmrs-core,WANeves/openmrs-core,ssmusoke/openmrs-core,spereverziev/openmrs-core,Ch3ck/openmrs-core,kabariyamilind/openMRSDEV,maekstr/openmrs-core,Negatu/openmrs-core,kristopherschmidt/openmrs-core,sadhanvejella/openmrs,WANeves/openmrs-core,ssmusoke/openmrs-core,macorrales/openmrs-core,maany/openmrs-core,ern2/openmrs-core,alexei-grigoriev/openmrs-core,koskedk/openmrs-core,sadhanvejella/openmrs,sintjuri/openmrs-core,joansmith/openmrs-core,kristopherschmidt/openmrs-core,andyvand/OpenMRS,lbl52001/openmrs-core,vinayvenu/openmrs-core,ldf92/openmrs-core,kristopherschmidt/openmrs-core,asifur77/openmrs,MuhammadSafwan/Stop-Button-Ability,iLoop2/openmrs-core,pselle/openmrs-core,dcmul/openmrs-core,spereverziev/openmrs-core,prisamuel/openmrs-core,Negatu/openmrs-core,donaldgavis/openmrs-core,Openmrs-joel/openmrs-core,Bhamni/openmrs-core,alexei-grigoriev/openmrs-core,naraink/openmrs-core,alexwind26/openmrs-core,lilo2k/openmrs-core,Negatu/openmrs-core,AbhijitParate/openmrs-core,preethi29/openmrs-core,kigsmtua/openmrs-core,ern2/openmrs-core,andyvand/OpenMRS,kigsmtua/openmrs-core,jvena1/openmrs-core,jamesfeshner/openmrs-module,maekstr/openmrs-core,preethi29/openmrs-core,preethi29/openmrs-core,andyvand/OpenMRS,alexwind26/openmrs-core,ldf92/openmrs-core,kigsmtua/openmrs-core,aboutdata/openmrs-core,donaldgavis/openmrs-core,WANeves/openmrs-core,maekstr/openmrs-core,kckc/openmrs-core,geoff-wasilwa/openmrs-core,koskedk/openmrs-core,geoff-wasilwa/openmrs-core,hoquangtruong/TestMylyn,AbhijitParate/openmrs-core,jembi/openmrs-core,ssmusoke/openmrs-core,MitchellBot/openmrs-core,lbl52001/openmrs-core,rbtracker/openmrs-core,preethi29/openmrs-core,MitchellBot/openmrs-core,milankarunarathne/openmrs-core,naraink/openmrs-core,pselle/openmrs-core,AbhijitParate/openmrs-core,aj-jaswanth/openmrs-core,Openmrs-joel/openmrs-core,Negatu/openmrs-core,pselle/openmrs-core,lilo2k/openmrs-core,kckc/openmrs-core,koskedk/openmrs-core,chethandeshpande/openmrs-core,trsorsimoII/openmrs-core,milankarunarathne/openmrs-core,prisamuel/openmrs-core,maekstr/openmrs-core,jvena1/openmrs-core,geoff-wasilwa/openmrs-core,jembi/openmrs-core,asifur77/openmrs,Bhamni/openmrs-core,shiangree/openmrs-core,kabariyamilind/openMRSDEV,foolchan2556/openmrs-core,michaelhofer/openmrs-core,prisamuel/openmrs-core,kabariyamilind/openMRSDEV,MitchellBot/openmrs-core,michaelhofer/openmrs-core,joansmith/openmrs-core,jcantu1988/openmrs-core,aj-jaswanth/openmrs-core,lbl52001/openmrs-core,ldf92/openmrs-core,MuhammadSafwan/Stop-Button-Ability,Ch3ck/openmrs-core,chethandeshpande/openmrs-core,ern2/openmrs-core,aj-jaswanth/openmrs-core,AbhijitParate/openmrs-core,sadhanvejella/openmrs,dcmul/openmrs-core,naraink/openmrs-core,hoquangtruong/TestMylyn,AbhijitParate/openmrs-core,aboutdata/openmrs-core,kigsmtua/openmrs-core,lbl52001/openmrs-core,naraink/openmrs-core,Bhamni/openmrs-core,chethandeshpande/openmrs-core,Ch3ck/openmrs-core,milankarunarathne/openmrs-core,sintjuri/openmrs-core,sintjuri/openmrs-core,alexwind26/openmrs-core,trsorsimoII/openmrs-core,siddharthkhabia/openmrs-core,kristopherschmidt/openmrs-core,alexei-grigoriev/openmrs-core,sadhanvejella/openmrs,jembi/openmrs-core,MuhammadSafwan/Stop-Button-Ability,nilusi/Legacy-UI,dlahn/openmrs-core,Openmrs-joel/openmrs-core,joansmith/openmrs-core,Ch3ck/openmrs-core,foolchan2556/openmrs-core,alexei-grigoriev/openmrs-core,siddharthkhabia/openmrs-core,prisamuel/openmrs-core,donaldgavis/openmrs-core,jvena1/openmrs-core,maany/openmrs-core,Winbobob/openmrs-core,sravanthi17/openmrs-core,foolchan2556/openmrs-core,ssmusoke/openmrs-core,pselle/openmrs-core,jembi/openmrs-core,Ch3ck/openmrs-core,ern2/openmrs-core,aboutdata/openmrs-core,shiangree/openmrs-core,aboutdata/openmrs-core,jcantu1988/openmrs-core,hoquangtruong/TestMylyn,lilo2k/openmrs-core,andyvand/OpenMRS,ldf92/openmrs-core,michaelhofer/openmrs-core,kckc/openmrs-core,lbl52001/openmrs-core,dcmul/openmrs-core,aj-jaswanth/openmrs-core,sravanthi17/openmrs-core,jcantu1988/openmrs-core,jamesfeshner/openmrs-module,michaelhofer/openmrs-core,prisamuel/openmrs-core,lbl52001/openmrs-core,alexwind26/openmrs-core,kabariyamilind/openMRSDEV,asifur77/openmrs,asifur77/openmrs,Winbobob/openmrs-core
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.util; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Scanner; import java.util.Set; import liquibase.Liquibase; import liquibase.changelog.ChangeLogIterator; import liquibase.changelog.ChangeLogParameters; import liquibase.changelog.ChangeSet; import liquibase.changelog.DatabaseChangeLog; import liquibase.changelog.filter.ContextChangeSetFilter; import liquibase.changelog.filter.DbmsChangeSetFilter; import liquibase.changelog.filter.ShouldRunChangeSetFilter; import liquibase.changelog.visitor.UpdateVisitor; import liquibase.database.Database; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.exception.LockException; import liquibase.lockservice.LockService; import liquibase.parser.core.xml.XMLChangeLogSAXParser; import liquibase.resource.CompositeResourceAccessor; import liquibase.resource.FileSystemResourceAccessor; import liquibase.resource.ResourceAccessor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.annotation.Authorized; import org.openmrs.api.context.Context; /** * This class uses Liquibase to update the database. <br/> * <br/> * See /metadata/model/liquibase-update-to-latest.xml for the changes. This class will also run * arbitrary liquibase xml files on the associated database as well. Details for the database are * taken from the openmrs runtime properties. * * @since 1.5 */ public class DatabaseUpdater { private static Log log = LogFactory.getLog(DatabaseUpdater.class); private static final String CHANGE_LOG_FILE = "liquibase-update-to-latest.xml"; private static final String CONTEXT = "core"; public static final String DATABASE_UPDATES_LOG_FILE = "liquibaseUpdateLogs.txt"; private static Integer authenticatedUserId; /** * Holds the update warnings generated by the custom liquibase changesets as they are executed */ private static List<String> updateWarnings = null; /** * Convenience method to run the changesets using Liquibase to bring the database up to a * version compatible with the code * * @throws InputRequiredException if the changelog file requirest some sort of user input. The * error object will list of the user prompts and type of data for each prompt * @see #update(Map) * @see #executeChangelog(String, Map) */ public static void executeChangelog() throws DatabaseUpdateException, InputRequiredException { executeChangelog(null, null); } /** * Run changesets on database using Liquibase to get the database up to the most recent version * * @param changelog the liquibase changelog file to use (or null to use the default file) * @param userInput nullable map from question to user answer. Used if a call to update(null) * threw an {@link InputRequiredException} * @throws DatabaseUpdateException * @throws InputRequiredException */ public static void executeChangelog(String changelog, Map<String, Object> userInput) throws DatabaseUpdateException, InputRequiredException { log.debug("Executing changelog: " + changelog); executeChangelog(changelog, userInput, null); } /** * Interface used for callbacks when updating the database. Implement this interface and pass it * to {@link DatabaseUpdater#executeChangelog(String, Map, ChangeSetExecutorCallback)} */ public interface ChangeSetExecutorCallback { /** * This method is called after each changeset is executed. * * @param changeSet the liquibase changeset that was just run * @param numChangeSetsToRun the total number of changesets in the current file */ public void executing(ChangeSet changeSet, int numChangeSetsToRun); } /** * Executes the given changelog file. This file is assumed to be on the classpath. If no file is * given, the default {@link #CHANGE_LOG_FILE} is ran. * * @param changelog The string filename of a liquibase changelog xml file to run * @param userInput nullable map from question to user answer. Used if a call to * executeChangelog(<String>, null) threw an {@link InputRequiredException} * @return A list of messages or warnings generated by the executed changesets * @throws InputRequiredException if the changelog file requirest some sort of user input. The * error object will list of the user prompts and type of data for each prompt */ public static List<String> executeChangelog(String changelog, Map<String, Object> userInput, ChangeSetExecutorCallback callback) throws DatabaseUpdateException, InputRequiredException { log.debug("installing the tables into the database"); if (changelog == null) changelog = CHANGE_LOG_FILE; try { return executeChangelog(changelog, CONTEXT, userInput, callback); } catch (Exception e) { throw new DatabaseUpdateException("There was an error while updating the database to the latest. file: " + changelog + ". Error: " + e.getMessage(), e); } } /** * @deprecated use * {@link #executeChangelog(String, String, Map, ChangeSetExecutorCallback, ClassLoader)} */ @Deprecated public static List<String> executeChangelog(String changeLogFile, String contexts, Map<String, Object> userInput, ChangeSetExecutorCallback callback) throws Exception { return executeChangelog(changeLogFile, contexts, userInput, callback, null); } /** * This code was borrowed from the liquibase jar so that we can call the given callback * function. * * @param changeLogFile the file to execute * @param contexts the liquibase changeset context * @param userInput answers given by the user * @param callback the function to call after every changeset * @param cl {@link ClassLoader} to use to find the changeLogFile (or null to use * {@link OpenmrsClassLoader}) * @return A list of messages or warnings generated by the executed changesets * @throws Exception */ public static List<String> executeChangelog(String changeLogFile, String contexts, Map<String, Object> userInput, ChangeSetExecutorCallback callback, ClassLoader cl) throws Exception { final class OpenmrsUpdateVisitor extends UpdateVisitor { private ChangeSetExecutorCallback callback; private int numChangeSetsToRun; public OpenmrsUpdateVisitor(Database database, ChangeSetExecutorCallback callback, int numChangeSetsToRun) { super(database); this.callback = callback; this.numChangeSetsToRun = numChangeSetsToRun; } @Override public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) throws LiquibaseException { if (callback != null) callback.executing(changeSet, numChangeSetsToRun); super.visit(changeSet, databaseChangeLog, database); } } if (cl == null) cl = OpenmrsClassLoader.getInstance(); log.debug("Setting up liquibase object to run changelog: " + changeLogFile); Liquibase liquibase = getLiquibase(changeLogFile, cl); int numChangeSetsToRun = liquibase.listUnrunChangeSets(contexts).size(); Database database = liquibase.getDatabase(); LockService lockHandler = LockService.getInstance(database); lockHandler.waitForLock(); try { ResourceAccessor openmrsFO = new ClassLoaderFileOpener(cl); ResourceAccessor fsFO = new FileSystemResourceAccessor(); DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse(changeLogFile, new ChangeLogParameters(), new CompositeResourceAccessor(openmrsFO, fsFO)); changeLog.validate(database); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database), new ContextChangeSetFilter(contexts), new DbmsChangeSetFilter(database)); database.checkDatabaseChangeLogTable(true, changeLog, new String[] { contexts }); logIterator.run(new OpenmrsUpdateVisitor(database, callback, numChangeSetsToRun), database); } catch (LiquibaseException e) { throw e; } finally { try { lockHandler.releaseLock(); } catch (LockException e) { log.error("Could not release lock", e); } try { database.getConnection().close(); } catch (Throwable t) { //pass } } return updateWarnings; } /** * Ask Liquibase if it needs to do any updates. Only looks at the {@link #CHANGE_LOG_FILE} * * @return true/false whether database updates are required * @should always have a valid update to latest file */ public static boolean updatesRequired() throws Exception { log.debug("checking for updates"); List<OpenMRSChangeSet> changesets = getUnrunDatabaseChanges(CHANGE_LOG_FILE); return changesets.size() > 0; } /** * Ask Liquibase if it needs to do any updates * * @param changeLogFilenames the filenames of all files to search for unrun changesets * @return true/false whether database updates are required * @should always have a valid update to latest file */ public static boolean updatesRequired(String... changeLogFilenames) throws Exception { log.debug("checking for updates"); List<OpenMRSChangeSet> changesets = getUnrunDatabaseChanges(changeLogFilenames); return changesets.size() > 0; } /** * Indicates whether automatic database updates are allowed by this server. Automatic updates * are disabled by default. In order to enable automatic updates, the admin needs to add * 'auto_update_database=true' to the runtime properties file. * * @return true/false whether the 'auto_update_database' has been enabled. */ public static Boolean allowAutoUpdate() { String allowAutoUpdate = Context.getRuntimeProperties().getProperty( OpenmrsConstants.AUTO_UPDATE_DATABASE_RUNTIME_PROPERTY, "false"); return "true".equals(allowAutoUpdate); } /** * Takes the default properties defined in /metadata/api/hibernate/hibernate.default.properties * and merges it into the user-defined runtime properties * * @see org.openmrs.api.db.ContextDAO#mergeDefaultRuntimeProperties(java.util.Properties) */ private static void mergeDefaultRuntimeProperties(Properties runtimeProperties) { // loop over runtime properties and precede each with "hibernate" if // it isn't already Set<Object> runtimePropertyKeys = new HashSet<Object>(); runtimePropertyKeys.addAll(runtimeProperties.keySet()); // must do it this way to prevent concurrent mod errors for (Object key : runtimePropertyKeys) { String prop = (String) key; String value = (String) runtimeProperties.get(key); log.trace("Setting property: " + prop + ":" + value); if (!prop.startsWith("hibernate") && !runtimeProperties.containsKey("hibernate." + prop)) runtimeProperties.setProperty("hibernate." + prop, value); } // load in the default hibernate properties from hibernate.default.properties InputStream propertyStream = null; try { Properties props = new Properties(); // TODO: This is a dumb requirement to have hibernate in here. Clean this up propertyStream = DatabaseUpdater.class.getClassLoader().getResourceAsStream("hibernate.default.properties"); OpenmrsUtil.loadProperties(props, propertyStream); // add in all default properties that don't exist in the runtime // properties yet for (Map.Entry<Object, Object> entry : props.entrySet()) { if (!runtimeProperties.containsKey(entry.getKey())) runtimeProperties.put(entry.getKey(), entry.getValue()); } } finally { try { propertyStream.close(); } catch (Throwable t) { // pass } } } /** * Get a connection to the database through Liquibase. The calling method /must/ close the * database connection when finished with this Liquibase object. * liquibase.getDatabase().getConnection().close() * * @param changeLogFile the name of the file to look for the on classpath or filesystem * @param cl the {@link ClassLoader} to use to find the file (or null to use * {@link OpenmrsClassLoader}) * @return Liquibase object based on the current connection settings * @throws Exception */ private static Liquibase getLiquibase(String changeLogFile, ClassLoader cl) throws Exception { Connection connection = null; try { connection = getConnection(); } catch (SQLException e) { throw new Exception( "Unable to get a connection to the database. Please check your openmrs runtime properties file and make sure you have the correct connection.username and connection.password set", e); } if (cl == null) cl = OpenmrsClassLoader.getInstance(); try { Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation( new JdbcConnection(connection)); database.setDatabaseChangeLogTableName("liquibasechangelog"); database.setDatabaseChangeLogLockTableName("liquibasechangeloglock"); if (connection.getMetaData().getDatabaseProductName().contains("HSQL Database Engine") || connection.getMetaData().getDatabaseProductName().contains("H2")) { // a hack because hsqldb and h2 seem to be checking table names in the metadata section case sensitively database.setDatabaseChangeLogTableName(database.getDatabaseChangeLogTableName().toUpperCase()); database.setDatabaseChangeLogLockTableName(database.getDatabaseChangeLogLockTableName().toUpperCase()); } ResourceAccessor openmrsFO = new ClassLoaderFileOpener(cl); ResourceAccessor fsFO = new FileSystemResourceAccessor(); if (changeLogFile == null) changeLogFile = CHANGE_LOG_FILE; database.checkDatabaseChangeLogTable(false, null, null); return new Liquibase(changeLogFile, new CompositeResourceAccessor(openmrsFO, fsFO), database); } catch (Exception e) { // if an error occurs, close the connection if (connection != null) connection.close(); throw e; } } /** * Gets a database connection for liquibase to do the updates * * @return a java.sql.connection based on the current runtime properties */ public static Connection getConnection() throws Exception { Properties props = Context.getRuntimeProperties(); mergeDefaultRuntimeProperties(props); String driver = props.getProperty("hibernate.connection.driver_class"); String username = props.getProperty("hibernate.connection.username"); String password = props.getProperty("hibernate.connection.password"); String url = props.getProperty("hibernate.connection.url"); // hack for mysql to make sure innodb tables are created if (url.contains("mysql") && !url.contains("InnoDB")) { url = url + "&sessionVariables=storage_engine=InnoDB"; } Class.forName(driver); return DriverManager.getConnection(url, username, password); } /** * Represents each change in the liquibase-update-to-latest */ public static class OpenMRSChangeSet { private String id; private String author; private String comments; private String description; private ChangeSet.RunStatus runStatus; private Date ranDate; /** * Create an OpenmrsChangeSet from the given changeset * * @param changeSet * @param database */ public OpenMRSChangeSet(ChangeSet changeSet, Database database) throws Exception { setId(changeSet.getId()); setAuthor(changeSet.getAuthor()); setComments(changeSet.getComments()); setDescription(changeSet.getDescription()); setRunStatus(database.getRunStatus(changeSet)); setRanDate(database.getRanDate(changeSet)); } /** * @return the author */ public String getAuthor() { return author; } /** * @param author the author to set */ public void setAuthor(String author) { this.author = author; } /** * @return the comments */ public String getComments() { return comments; } /** * @param comments the comments to set */ public void setComments(String comments) { this.comments = comments; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the runStatus */ public ChangeSet.RunStatus getRunStatus() { return runStatus; } /** * @param runStatus the runStatus to set */ public void setRunStatus(ChangeSet.RunStatus runStatus) { this.runStatus = runStatus; } /** * @return the ranDate */ public Date getRanDate() { return ranDate; } /** * @param ranDate the ranDate to set */ public void setRanDate(Date ranDate) { this.ranDate = ranDate; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } } /** * Looks at the current liquibase-update-to-latest.xml file and then checks the database to see * if they have been run. * * @return list of changesets that both have and haven't been run */ @Authorized(PrivilegeConstants.VIEW_DATABASE_CHANGES) public static List<OpenMRSChangeSet> getDatabaseChanges() throws Exception { Database database = null; try { Liquibase liquibase = getLiquibase(CHANGE_LOG_FILE, null); database = liquibase.getDatabase(); DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse(CHANGE_LOG_FILE, new ChangeLogParameters(), liquibase.getFileOpener()); List<ChangeSet> changeSets = changeLog.getChangeSets(); List<OpenMRSChangeSet> results = new ArrayList<OpenMRSChangeSet>(); for (ChangeSet changeSet : changeSets) { OpenMRSChangeSet omrschangeset = new OpenMRSChangeSet(changeSet, database); results.add(omrschangeset); } return results; } finally { try { if (database != null) { database.getConnection().close(); } } catch (Throwable t) { //pass } } } /** * Looks at the specified liquibase change log files and returns all changesets in the files * that have not been run on the database yet. If no argument is specified, then it looks at the * current liquibase-update-to-latest.xml file * * @param changeLogFilenames the filenames of all files to search for unrun changesets * @return * @throws Exception */ @Authorized(PrivilegeConstants.VIEW_DATABASE_CHANGES) public static List<OpenMRSChangeSet> getUnrunDatabaseChanges(String... changeLogFilenames) throws Exception { log.debug("Getting unrun changesets"); Database database = null; try { if (changeLogFilenames == null) throw new IllegalArgumentException("changeLogFilenames cannot be null"); //if no argument, look ONLY in liquibase-update-to-latest.xml if (changeLogFilenames.length == 0) changeLogFilenames = new String[] { CHANGE_LOG_FILE }; List<OpenMRSChangeSet> results = new ArrayList<OpenMRSChangeSet>(); for (String changelogFile : changeLogFilenames) { Liquibase liquibase = getLiquibase(changelogFile, null); database = liquibase.getDatabase(); List<ChangeSet> changeSets = liquibase.listUnrunChangeSets(CONTEXT); for (ChangeSet changeSet : changeSets) { OpenMRSChangeSet omrschangeset = new OpenMRSChangeSet(changeSet, database); results.add(omrschangeset); } } return results; } catch (Exception e) { throw new RuntimeException("Error occurred while trying to get the updates needed for the database. " + e.getMessage(), e); } finally { try { database.getConnection().close(); } catch (Throwable t) { //pass } } } /** * @return the authenticatedUserId */ public static Integer getAuthenticatedUserId() { return authenticatedUserId; } /** * @param authenticatedUserId the authenticatedUserId to set */ public static void setAuthenticatedUserId(Integer userId) { authenticatedUserId = userId; } /** * This method is called by an executing custom changeset to register warning messages. * * @param warnings list of warnings to append to the end of the current list */ public static void reportUpdateWarnings(List<String> warnings) { if (updateWarnings == null) updateWarnings = new LinkedList<String>(); updateWarnings.addAll(warnings); } /** * This method writes the given text to the database updates log file located in the application * data directory. * * @param the text to be written to the file */ public static void writeUpdateMessagesToFile(String text) { PrintWriter writer = null; Scanner scanner = null; File destFile = new File(OpenmrsUtil.getApplicationDataDirectory(), DatabaseUpdater.DATABASE_UPDATES_LOG_FILE); try { String lineSeparator = System.getProperty("line.separator"); Date date = Calendar.getInstance().getTime(); StringBuilder sb = new StringBuilder(); if (destFile.isFile()) { scanner = new Scanner(destFile); while (scanner.hasNextLine()) sb.append(scanner.nextLine()).append(lineSeparator); sb.append(lineSeparator); sb.append(lineSeparator); if (scanner.ioException() != null) log.warn("Some error(s) occured while reading messages from the database update log file", scanner .ioException()); } writer = new PrintWriter(destFile); sb.append("********** START OF DATABASE UPDATE LOGS AS AT " + date + " **********"); sb.append(lineSeparator); sb.append(lineSeparator); sb.append(text); sb.append(lineSeparator); sb.append(lineSeparator); sb.append("*********** END OF DATABASE UPDATE LOGS AS AT " + date + " ***********"); writer.write(sb.toString()); //check if there was an error while writing to the file if (writer.checkError()) log.warn("An Error occured while writing warnings to the database update log file'"); } catch (FileNotFoundException e) { log.warn("Generated error", e); } finally { if (writer != null) writer.close(); if (scanner != null) scanner.close(); } } }
api/src/main/java/org/openmrs/util/DatabaseUpdater.java
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.util; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Scanner; import java.util.Set; import liquibase.Liquibase; import liquibase.changelog.ChangeLogIterator; import liquibase.changelog.ChangeLogParameters; import liquibase.changelog.ChangeSet; import liquibase.changelog.DatabaseChangeLog; import liquibase.changelog.filter.ContextChangeSetFilter; import liquibase.changelog.filter.DbmsChangeSetFilter; import liquibase.changelog.filter.ShouldRunChangeSetFilter; import liquibase.changelog.visitor.UpdateVisitor; import liquibase.database.Database; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.LiquibaseException; import liquibase.exception.LockException; import liquibase.lockservice.LockService; import liquibase.parser.core.xml.XMLChangeLogSAXParser; import liquibase.resource.CompositeResourceAccessor; import liquibase.resource.FileSystemResourceAccessor; import liquibase.resource.ResourceAccessor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.annotation.Authorized; import org.openmrs.api.context.Context; /** * This class uses Liquibase to update the database. <br/> * <br/> * See /metadata/model/liquibase-update-to-latest.xml for the changes. This class will also run * arbitrary liquibase xml files on the associated database as well. Details for the database are * taken from the openmrs runtime properties. * * @since 1.5 */ public class DatabaseUpdater { private static Log log = LogFactory.getLog(DatabaseUpdater.class); private static final String CHANGE_LOG_FILE = "liquibase-update-to-latest.xml"; private static final String CONTEXT = "core"; public static final String DATABASE_UPDATES_LOG_FILE = "liquibaseUpdateLogs.txt"; private static Integer authenticatedUserId; /** * Holds the update warnings generated by the custom liquibase changesets as they are executed */ private static List<String> updateWarnings = null; /** * Convenience method to run the changesets using Liquibase to bring the database up to a * version compatible with the code * * @throws InputRequiredException if the changelog file requirest some sort of user input. The * error object will list of the user prompts and type of data for each prompt * @see #update(Map) * @see #executeChangelog(String, Map) */ public static void executeChangelog() throws DatabaseUpdateException, InputRequiredException { executeChangelog(null, null); } /** * Run changesets on database using Liquibase to get the database up to the most recent version * * @param changelog the liquibase changelog file to use (or null to use the default file) * @param userInput nullable map from question to user answer. Used if a call to update(null) * threw an {@link InputRequiredException} * @throws DatabaseUpdateException * @throws InputRequiredException */ public static void executeChangelog(String changelog, Map<String, Object> userInput) throws DatabaseUpdateException, InputRequiredException { log.debug("Executing changelog: " + changelog); executeChangelog(changelog, userInput, null); } /** * Interface used for callbacks when updating the database. Implement this interface and pass it * to {@link DatabaseUpdater#executeChangelog(String, Map, ChangeSetExecutorCallback)} */ public interface ChangeSetExecutorCallback { /** * This method is called after each changeset is executed. * * @param changeSet the liquibase changeset that was just run * @param numChangeSetsToRun the total number of changesets in the current file */ public void executing(ChangeSet changeSet, int numChangeSetsToRun); } /** * Executes the given changelog file. This file is assumed to be on the classpath. If no file is * given, the default {@link #CHANGE_LOG_FILE} is ran. * * @param changelog The string filename of a liquibase changelog xml file to run * @param userInput nullable map from question to user answer. Used if a call to * executeChangelog(<String>, null) threw an {@link InputRequiredException} * @return A list of messages or warnings generated by the executed changesets * @throws InputRequiredException if the changelog file requirest some sort of user input. The * error object will list of the user prompts and type of data for each prompt */ public static List<String> executeChangelog(String changelog, Map<String, Object> userInput, ChangeSetExecutorCallback callback) throws DatabaseUpdateException, InputRequiredException { log.debug("installing the tables into the database"); if (changelog == null) changelog = CHANGE_LOG_FILE; try { return executeChangelog(changelog, CONTEXT, userInput, callback); } catch (Exception e) { throw new DatabaseUpdateException("There was an error while updating the database to the latest. file: " + changelog + ". Error: " + e.getMessage(), e); } } /** * @deprecated use * {@link #executeChangelog(String, String, Map, ChangeSetExecutorCallback, ClassLoader)} */ @Deprecated public static List<String> executeChangelog(String changeLogFile, String contexts, Map<String, Object> userInput, ChangeSetExecutorCallback callback) throws Exception { return executeChangelog(changeLogFile, contexts, userInput, callback, null); } /** * This code was borrowed from the liquibase jar so that we can call the given callback * function. * * @param changeLogFile the file to execute * @param contexts the liquibase changeset context * @param userInput answers given by the user * @param callback the function to call after every changeset * @param cl {@link ClassLoader} to use to find the changeLogFile (or null to use * {@link OpenmrsClassLoader}) * @return A list of messages or warnings generated by the executed changesets * @throws Exception */ public static List<String> executeChangelog(String changeLogFile, String contexts, Map<String, Object> userInput, ChangeSetExecutorCallback callback, ClassLoader cl) throws Exception { final class OpenmrsUpdateVisitor extends UpdateVisitor { private ChangeSetExecutorCallback callback; private int numChangeSetsToRun; public OpenmrsUpdateVisitor(Database database, ChangeSetExecutorCallback callback, int numChangeSetsToRun) { super(database); this.callback = callback; this.numChangeSetsToRun = numChangeSetsToRun; } @Override public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) throws LiquibaseException { if (callback != null) callback.executing(changeSet, numChangeSetsToRun); super.visit(changeSet, databaseChangeLog, database); } } if (cl == null) cl = OpenmrsClassLoader.getInstance(); log.debug("Setting up liquibase object to run changelog: " + changeLogFile); Liquibase liquibase = getLiquibase(changeLogFile, cl); int numChangeSetsToRun = liquibase.listUnrunChangeSets(contexts).size(); Database database = liquibase.getDatabase(); LockService lockHandler = LockService.getInstance(database); lockHandler.waitForLock(); try { database.checkDatabaseChangeLogTable(true, null, new String[] { contexts }); ResourceAccessor openmrsFO = new ClassLoaderFileOpener(cl); ResourceAccessor fsFO = new FileSystemResourceAccessor(); DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse(changeLogFile, new ChangeLogParameters(), new CompositeResourceAccessor(openmrsFO, fsFO)); changeLog.validate(database); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database), new ContextChangeSetFilter(contexts), new DbmsChangeSetFilter(database)); logIterator.run(new OpenmrsUpdateVisitor(database, callback, numChangeSetsToRun), database); } catch (LiquibaseException e) { throw e; } finally { try { lockHandler.releaseLock(); } catch (LockException e) { log.error("Could not release lock", e); } try { database.getConnection().close(); } catch (Throwable t) { //pass } } return updateWarnings; } /** * Ask Liquibase if it needs to do any updates. Only looks at the {@link #CHANGE_LOG_FILE} * * @return true/false whether database updates are required * @should always have a valid update to latest file */ public static boolean updatesRequired() throws Exception { log.debug("checking for updates"); List<OpenMRSChangeSet> changesets = getUnrunDatabaseChanges(CHANGE_LOG_FILE); return changesets.size() > 0; } /** * Ask Liquibase if it needs to do any updates * * @param changeLogFilenames the filenames of all files to search for unrun changesets * @return true/false whether database updates are required * @should always have a valid update to latest file */ public static boolean updatesRequired(String... changeLogFilenames) throws Exception { log.debug("checking for updates"); List<OpenMRSChangeSet> changesets = getUnrunDatabaseChanges(changeLogFilenames); return changesets.size() > 0; } /** * Indicates whether automatic database updates are allowed by this server. Automatic updates * are disabled by default. In order to enable automatic updates, the admin needs to add * 'auto_update_database=true' to the runtime properties file. * * @return true/false whether the 'auto_update_database' has been enabled. */ public static Boolean allowAutoUpdate() { String allowAutoUpdate = Context.getRuntimeProperties().getProperty( OpenmrsConstants.AUTO_UPDATE_DATABASE_RUNTIME_PROPERTY, "false"); return "true".equals(allowAutoUpdate); } /** * Takes the default properties defined in /metadata/api/hibernate/hibernate.default.properties * and merges it into the user-defined runtime properties * * @see org.openmrs.api.db.ContextDAO#mergeDefaultRuntimeProperties(java.util.Properties) */ private static void mergeDefaultRuntimeProperties(Properties runtimeProperties) { // loop over runtime properties and precede each with "hibernate" if // it isn't already Set<Object> runtimePropertyKeys = new HashSet<Object>(); runtimePropertyKeys.addAll(runtimeProperties.keySet()); // must do it this way to prevent concurrent mod errors for (Object key : runtimePropertyKeys) { String prop = (String) key; String value = (String) runtimeProperties.get(key); log.trace("Setting property: " + prop + ":" + value); if (!prop.startsWith("hibernate") && !runtimeProperties.containsKey("hibernate." + prop)) runtimeProperties.setProperty("hibernate." + prop, value); } // load in the default hibernate properties from hibernate.default.properties InputStream propertyStream = null; try { Properties props = new Properties(); // TODO: This is a dumb requirement to have hibernate in here. Clean this up propertyStream = DatabaseUpdater.class.getClassLoader().getResourceAsStream("hibernate.default.properties"); OpenmrsUtil.loadProperties(props, propertyStream); // add in all default properties that don't exist in the runtime // properties yet for (Map.Entry<Object, Object> entry : props.entrySet()) { if (!runtimeProperties.containsKey(entry.getKey())) runtimeProperties.put(entry.getKey(), entry.getValue()); } } finally { try { propertyStream.close(); } catch (Throwable t) { // pass } } } /** * Get a connection to the database through Liquibase. The calling method /must/ close the * database connection when finished with this Liquibase object. * liquibase.getDatabase().getConnection().close() * * @param changeLogFile the name of the file to look for the on classpath or filesystem * @param cl the {@link ClassLoader} to use to find the file (or null to use * {@link OpenmrsClassLoader}) * @return Liquibase object based on the current connection settings * @throws Exception */ private static Liquibase getLiquibase(String changeLogFile, ClassLoader cl) throws Exception { Connection connection = null; try { connection = getConnection(); } catch (SQLException e) { throw new Exception( "Unable to get a connection to the database. Please check your openmrs runtime properties file and make sure you have the correct connection.username and connection.password set", e); } if (cl == null) cl = OpenmrsClassLoader.getInstance(); try { Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation( new JdbcConnection(connection)); database.setDatabaseChangeLogTableName("liquibasechangelog"); database.setDatabaseChangeLogLockTableName("liquibasechangeloglock"); if (connection.getMetaData().getDatabaseProductName().contains("HSQL Database Engine") || connection.getMetaData().getDatabaseProductName().contains("H2")) { // a hack because hsqldb and h2 seem to be checking table names in the metadata section case sensitively database.setDatabaseChangeLogTableName(database.getDatabaseChangeLogTableName().toUpperCase()); database.setDatabaseChangeLogLockTableName(database.getDatabaseChangeLogLockTableName().toUpperCase()); } ResourceAccessor openmrsFO = new ClassLoaderFileOpener(cl); ResourceAccessor fsFO = new FileSystemResourceAccessor(); if (changeLogFile == null) changeLogFile = CHANGE_LOG_FILE; return new Liquibase(changeLogFile, new CompositeResourceAccessor(openmrsFO, fsFO), database); } catch (Exception e) { // if an error occurs, close the connection if (connection != null) connection.close(); throw e; } } /** * Gets a database connection for liquibase to do the updates * * @return a java.sql.connection based on the current runtime properties */ public static Connection getConnection() throws Exception { Properties props = Context.getRuntimeProperties(); mergeDefaultRuntimeProperties(props); String driver = props.getProperty("hibernate.connection.driver_class"); String username = props.getProperty("hibernate.connection.username"); String password = props.getProperty("hibernate.connection.password"); String url = props.getProperty("hibernate.connection.url"); // hack for mysql to make sure innodb tables are created if (url.contains("mysql") && !url.contains("InnoDB")) { url = url + "&sessionVariables=storage_engine=InnoDB"; } Class.forName(driver); return DriverManager.getConnection(url, username, password); } /** * Represents each change in the liquibase-update-to-latest */ public static class OpenMRSChangeSet { private String id; private String author; private String comments; private String description; private ChangeSet.RunStatus runStatus; private Date ranDate; /** * Create an OpenmrsChangeSet from the given changeset * * @param changeSet * @param database */ public OpenMRSChangeSet(ChangeSet changeSet, Database database) throws Exception { setId(changeSet.getId()); setAuthor(changeSet.getAuthor()); setComments(changeSet.getComments()); setDescription(changeSet.getDescription()); setRunStatus(database.getRunStatus(changeSet)); setRanDate(database.getRanDate(changeSet)); } /** * @return the author */ public String getAuthor() { return author; } /** * @param author the author to set */ public void setAuthor(String author) { this.author = author; } /** * @return the comments */ public String getComments() { return comments; } /** * @param comments the comments to set */ public void setComments(String comments) { this.comments = comments; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the runStatus */ public ChangeSet.RunStatus getRunStatus() { return runStatus; } /** * @param runStatus the runStatus to set */ public void setRunStatus(ChangeSet.RunStatus runStatus) { this.runStatus = runStatus; } /** * @return the ranDate */ public Date getRanDate() { return ranDate; } /** * @param ranDate the ranDate to set */ public void setRanDate(Date ranDate) { this.ranDate = ranDate; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } } /** * Looks at the current liquibase-update-to-latest.xml file and then checks the database to see * if they have been run. * * @return list of changesets that both have and haven't been run */ @Authorized(PrivilegeConstants.VIEW_DATABASE_CHANGES) public static List<OpenMRSChangeSet> getDatabaseChanges() throws Exception { Database database = null; try { Liquibase liquibase = getLiquibase(CHANGE_LOG_FILE, null); database = liquibase.getDatabase(); DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse(CHANGE_LOG_FILE, new ChangeLogParameters(), liquibase.getFileOpener()); List<ChangeSet> changeSets = changeLog.getChangeSets(); List<OpenMRSChangeSet> results = new ArrayList<OpenMRSChangeSet>(); for (ChangeSet changeSet : changeSets) { OpenMRSChangeSet omrschangeset = new OpenMRSChangeSet(changeSet, database); results.add(omrschangeset); } return results; } finally { try { if (database != null) { database.getConnection().close(); } } catch (Throwable t) { //pass } } } /** * Looks at the specified liquibase change log files and returns all changesets in the files * that have not been run on the database yet. If no argument is specified, then it looks at the * current liquibase-update-to-latest.xml file * * @param changeLogFilenames the filenames of all files to search for unrun changesets * @return * @throws Exception */ @Authorized(PrivilegeConstants.VIEW_DATABASE_CHANGES) public static List<OpenMRSChangeSet> getUnrunDatabaseChanges(String... changeLogFilenames) throws Exception { log.debug("Getting unrun changesets"); Database database = null; try { if (changeLogFilenames == null) throw new IllegalArgumentException("changeLogFilenames cannot be null"); //if no argument, look ONLY in liquibase-update-to-latest.xml if (changeLogFilenames.length == 0) changeLogFilenames = new String[] { CHANGE_LOG_FILE }; List<OpenMRSChangeSet> results = new ArrayList<OpenMRSChangeSet>(); for (String changelogFile : changeLogFilenames) { Liquibase liquibase = getLiquibase(changelogFile, null); database = liquibase.getDatabase(); List<ChangeSet> changeSets = liquibase.listUnrunChangeSets(CONTEXT); for (ChangeSet changeSet : changeSets) { OpenMRSChangeSet omrschangeset = new OpenMRSChangeSet(changeSet, database); results.add(omrschangeset); } } return results; } catch (Exception e) { throw new RuntimeException("Error occurred while trying to get the updates needed for the database. " + e.getMessage(), e); } finally { try { database.getConnection().close(); } catch (Throwable t) { //pass } } } /** * @return the authenticatedUserId */ public static Integer getAuthenticatedUserId() { return authenticatedUserId; } /** * @param authenticatedUserId the authenticatedUserId to set */ public static void setAuthenticatedUserId(Integer userId) { authenticatedUserId = userId; } /** * This method is called by an executing custom changeset to register warning messages. * * @param warnings list of warnings to append to the end of the current list */ public static void reportUpdateWarnings(List<String> warnings) { if (updateWarnings == null) updateWarnings = new LinkedList<String>(); updateWarnings.addAll(warnings); } /** * This method writes the given text to the database updates log file located in the application * data directory. * * @param the text to be written to the file */ public static void writeUpdateMessagesToFile(String text) { PrintWriter writer = null; Scanner scanner = null; File destFile = new File(OpenmrsUtil.getApplicationDataDirectory(), DatabaseUpdater.DATABASE_UPDATES_LOG_FILE); try { String lineSeparator = System.getProperty("line.separator"); Date date = Calendar.getInstance().getTime(); StringBuilder sb = new StringBuilder(); if (destFile.isFile()) { scanner = new Scanner(destFile); while (scanner.hasNextLine()) sb.append(scanner.nextLine()).append(lineSeparator); sb.append(lineSeparator); sb.append(lineSeparator); if (scanner.ioException() != null) log.warn("Some error(s) occured while reading messages from the database update log file", scanner .ioException()); } writer = new PrintWriter(destFile); sb.append("********** START OF DATABASE UPDATE LOGS AS AT " + date + " **********"); sb.append(lineSeparator); sb.append(lineSeparator); sb.append(text); sb.append(lineSeparator); sb.append(lineSeparator); sb.append("*********** END OF DATABASE UPDATE LOGS AS AT " + date + " ***********"); writer.write(sb.toString()); //check if there was an error while writing to the file if (writer.checkError()) log.warn("An Error occured while writing warnings to the database update log file'"); } catch (FileNotFoundException e) { log.warn("Generated error", e); } finally { if (writer != null) writer.close(); if (scanner != null) scanner.close(); } } }
Add check for changelog table when initializing liquibase - TRUNK-1926 git-svn-id: ce3478dfdc990238714fcdf4fc6855b7489218cf@22631 5bac5841-c719-aa4e-b3fe-cce5062f897a
api/src/main/java/org/openmrs/util/DatabaseUpdater.java
Add check for changelog table when initializing liquibase - TRUNK-1926
Java
mpl-2.0
cd97ef722149a4893c86be10a7c956accea9e899
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.gl3d.camera; import java.awt.Point; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; import org.helioviewer.base.logging.Log; import org.helioviewer.base.physics.Constants; import org.helioviewer.gl3d.math.GL3DMat4d; import org.helioviewer.gl3d.math.GL3DQuatd; import org.helioviewer.gl3d.math.GL3DVec2d; import org.helioviewer.gl3d.math.GL3DVec3d; import org.helioviewer.gl3d.scenegraph.GL3DState; import org.helioviewer.jhv.display.Displayer; /** * * @author Simon Spoerri (simon.spoerri@fhnw.ch) * */ public abstract class GL3DCamera { protected GLU glu = new GLU(); public static final double MAX_DISTANCE = -Constants.SunMeanDistanceToEarth * 1.8; public static final double MIN_DISTANCE = -Constants.SunRadius * 1.2; public static final double INITFOV = (48. / 60.) * Math.PI / 180.; public static final double MIN_FOV = INITFOV * 0.05; public static final double MAX_FOV = INITFOV * 100; private final double clipNear = Constants.SunRadius * 3; private final double clipFar = Constants.SunRadius * 10000.; private double fov = INITFOV; private double aspect = 0.0; private double previousAspect = -1.0; private final RayTracer rayTracer; private GL3DMat4d cameraTransformation; protected GL3DQuatd rotation; protected GL3DVec3d translation; protected GL3DQuatd currentDragRotation; protected GL3DQuatd localRotation; private long timeDelay; private double translationz; private double ratio = 1.0; private long time; private boolean trackingMode; public GL3DMat4d orthoMatrixInverse = GL3DMat4d.identity(); private double cameraWidth = 1.; private double previousCameraWidth = -1; private double cameraWidthTimesAspect; public GL3DCamera() { this.cameraTransformation = GL3DMat4d.identity(); this.rotation = new GL3DQuatd(); this.currentDragRotation = new GL3DQuatd(); this.localRotation = new GL3DQuatd(); this.translation = new GL3DVec3d(); rayTracer = new RayTracer(this); } public void reset() { this.resetFOV(); this.translation = new GL3DVec3d(0, 0, this.translation.z); } private void resetFOV() { this.fov = INITFOV; } /** * This method is called when the camera changes and should copy the * required settings of the preceding camera objects. * * @param precedingCamera */ public void activate(GL3DCamera precedingCamera) { if (precedingCamera != null) { this.rotation = precedingCamera.getRotation().copy(); this.translation = precedingCamera.translation.copy(); this.updateCameraTransformation(); if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getRotateInteraction())) { this.setCurrentInteraction(this.getRotateInteraction()); } else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getPanInteraction())) { this.setCurrentInteraction(this.getPanInteraction()); } else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getZoomInteraction())) { this.setCurrentInteraction(this.getZoomInteraction()); } } else { Log.debug("GL3DCamera: No Preceding Camera, resetting Camera"); this.reset(); } } protected void setZTranslation(double z) { this.translationz = Math.min(MIN_DISTANCE, Math.max(MAX_DISTANCE, z)); this.translation.z = this.ratio * this.translationz; } public void setPanning(double x, double y) { this.translation.x = x; this.translation.y = y; } public GL3DVec3d getTranslation() { return this.translation; } public GL3DMat4d getCameraTransformation() { return this.cameraTransformation; } public double getZTranslation() { return this.translation.z; } public GL3DQuatd getLocalRotation() { return this.localRotation; } public GL3DQuatd getRotation() { this.updateCameraTransformation(); return this.rotation; } public GL3DQuatd getRotationInverse() { this.updateCameraTransformation(); return this.rotation; } public void resetCurrentDragRotation() { this.currentDragRotation.clear(); } public void setLocalRotation(GL3DQuatd localRotation) { this.localRotation = localRotation; this.rotation.clear(); this.updateCameraTransformation(); } public void setCurrentDragRotation(GL3DQuatd currentDragRotation) { this.currentDragRotation = currentDragRotation; this.rotation.clear(); this.updateCameraTransformation(); } public void rotateCurrentDragRotation(GL3DQuatd currentDragRotation) { this.currentDragRotation.rotate(currentDragRotation); this.rotation.clear(); this.updateCameraTransformation(); } public void activate() { } public void applyPerspective(GL3DState state) { GL2 gl = state.gl; gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPushMatrix(); this.aspect = state.getViewportWidth() / (double) state.getViewportHeight(); cameraWidth = -translation.z * Math.tan(fov / 2.); if (cameraWidth == 0.) cameraWidth = 1.; cameraWidthTimesAspect = cameraWidth * aspect; gl.glLoadIdentity(); gl.glOrtho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); gl.glMatrixMode(GL2.GL_MODELVIEW); if (cameraWidth == previousCameraWidth && aspect == previousAspect) { return; } previousCameraWidth = cameraWidth; previousAspect = aspect; //orthoMatrix = GL3DMat4d.ortho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); orthoMatrixInverse = GL3DMat4d.orthoInverse(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); } public void resumePerspective(GL3DState state) { GL2 gl = state.gl; gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL2.GL_MODELVIEW); } public GL3DVec3d getVectorFromSphereOrPlane(GL3DVec2d normalizedScreenpos, GL3DMat4d cameraDifferenceRotation) { //GL3DVec4d up1 = this.orthoMatrixInverse.multiply(normalizedScreenpos); double up1x = normalizedScreenpos.x * cameraWidthTimesAspect; double up1y = normalizedScreenpos.y * cameraWidth; GL3DVec3d hitPoint; GL3DVec3d rotatedHitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= 1) { hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2)); rotatedHitPoint = cameraDifferenceRotation.multiplyTranspose(hitPoint); if (rotatedHitPoint.z > 0.) { return rotatedHitPoint; } } GL3DVec3d altnormal = cameraDifferenceRotation.multiply(GL3DVec3d.ZAxis); double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z; hitPoint = new GL3DVec3d(up1x, up1y, zvalue); rotatedHitPoint = cameraDifferenceRotation.multiplyTranspose(hitPoint); return rotatedHitPoint; } public GL3DVec3d getVectorFromSphere(Point viewportCoordinates) { GL3DVec3d hp = rayTracer.cast(viewportCoordinates.getX(), viewportCoordinates.getY()).getHitpoint(); return hp; } public GL3DVec3d getVectorFromSphereAlt(Point viewportCoordinates) { GL3DVec3d hp = rayTracer.cast(viewportCoordinates.getX(), viewportCoordinates.getY()).getHitpoint(); return this.getLocalRotation().toMatrix().multiply(hp); } /** * Updates the camera transformation by applying the rotation and * translation information. */ public void updateCameraTransformation() { this.rotation = this.currentDragRotation.copy(); this.rotation.rotate(this.localRotation); cameraTransformation = this.rotation.toMatrix().translate(this.translation); } public GL3DMat4d getRotationMatrix() { return this.getRotation().toMatrix(); } public void applyCamera(GL3DState state) { state.gl.glMultMatrixd(cameraTransformation.m, 0); } public abstract GL3DInteraction getPanInteraction(); public abstract GL3DInteraction getRotateInteraction(); public abstract GL3DInteraction getZoomInteraction(); public abstract String getName(); public void drawCamera(GL3DState state) { getCurrentInteraction().drawInteractionFeedback(state, this); } public abstract GL3DInteraction getCurrentInteraction(); public abstract void setCurrentInteraction(GL3DInteraction currentInteraction); public double getCameraFOV() { return this.fov; } public double setCameraFOV(double fov) { if (fov < MIN_FOV) { this.fov = MIN_FOV; } else if (fov > MAX_FOV) { this.fov = MAX_FOV; } else { this.fov = fov; } return this.fov; } public final double getClipNear() { return clipNear; } public final double getClipFar() { return clipFar; } public double getAspect() { return aspect; } @Override public String toString() { return getName(); } public void setTimeDelay(long timeDelay) { this.timeDelay = timeDelay; } public long getTimeDelay() { return this.timeDelay; } public GL3DQuatd getCurrentDragRotation() { return this.currentDragRotation; } public void setRatio(double ratio) { this.ratio = ratio; this.translation.z = this.translationz * this.ratio; } public void setTime(long time) { this.time = time; } public long getTime() { return time; } public void setTrackingMode(boolean trackingMode) { this.trackingMode = trackingMode; } public boolean getTrackingMode() { return this.trackingMode; } public void deactivate() { } public void setDefaultFOV() { this.fov = INITFOV; } public double getCameraWidth() { return cameraWidth; } public void zoomIn(int wr) { double currentWidth = this.getCameraWidth(); double newWidth = currentWidth + wr * 0.1; double fov = 2. * Math.atan(-newWidth / this.getTranslation().z); this.setCameraFOV(fov); Displayer.display(); } }
src/jhv/src/org/helioviewer/gl3d/camera/GL3DCamera.java
package org.helioviewer.gl3d.camera; import java.awt.Point; import javax.media.opengl.GL2; import javax.media.opengl.glu.GLU; import org.helioviewer.base.logging.Log; import org.helioviewer.base.physics.Constants; import org.helioviewer.gl3d.math.GL3DMat4d; import org.helioviewer.gl3d.math.GL3DQuatd; import org.helioviewer.gl3d.math.GL3DVec2d; import org.helioviewer.gl3d.math.GL3DVec3d; import org.helioviewer.gl3d.scenegraph.GL3DState; import org.helioviewer.jhv.display.Displayer; /** * * @author Simon Spoerri (simon.spoerri@fhnw.ch) * */ public abstract class GL3DCamera { protected GLU glu = new GLU(); public static final double MAX_DISTANCE = -Constants.SunMeanDistanceToEarth * 1.8; public static final double MIN_DISTANCE = -Constants.SunRadius * 1.2; public static final double INITFOV = (48. / 60.) * Math.PI / 180.; public static final double MIN_FOV = INITFOV * 0.05; public static final double MAX_FOV = INITFOV * 100; private final double clipNear = Constants.SunRadius * 3; private final double clipFar = Constants.SunRadius * 10000.; private double fov = INITFOV; private double aspect = 0.0; private double previousAspect = -1.0; private final RayTracer rayTracer; private GL3DMat4d cameraTransformation; protected GL3DQuatd rotation; protected GL3DVec3d translation; protected GL3DQuatd currentDragRotation; protected GL3DQuatd localRotation; private long timeDelay; private double translationz; private double ratio = 1.0; private long time; private boolean trackingMode; public GL3DMat4d orthoMatrixInverse = GL3DMat4d.identity(); private double cameraWidth = 1.; private double previousCameraWidth = -1; private double cameraWidthTimesAspect; public GL3DCamera() { this.cameraTransformation = GL3DMat4d.identity(); this.rotation = new GL3DQuatd(); this.currentDragRotation = new GL3DQuatd(); this.localRotation = new GL3DQuatd(); this.translation = new GL3DVec3d(); rayTracer = new RayTracer(this); } public void reset() { this.resetFOV(); this.translation = new GL3DVec3d(0, 0, this.translation.z); } private void resetFOV() { this.fov = INITFOV; } /** * This method is called when the camera changes and should copy the * required settings of the preceding camera objects. * * @param precedingCamera */ public void activate(GL3DCamera precedingCamera) { if (precedingCamera != null) { this.rotation = precedingCamera.getRotation().copy(); this.translation = precedingCamera.translation.copy(); this.updateCameraTransformation(); if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getRotateInteraction())) { this.setCurrentInteraction(this.getRotateInteraction()); } else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getPanInteraction())) { this.setCurrentInteraction(this.getPanInteraction()); } else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getZoomInteraction())) { this.setCurrentInteraction(this.getZoomInteraction()); } } else { Log.debug("GL3DCamera: No Preceding Camera, resetting Camera"); this.reset(); } } protected void setZTranslation(double z) { this.translationz = Math.min(MIN_DISTANCE, Math.max(MAX_DISTANCE, z)); this.translation.z = this.ratio * this.translationz; } public void setPanning(double x, double y) { this.translation.x = x; this.translation.y = y; } public GL3DVec3d getTranslation() { return this.translation; } public GL3DMat4d getCameraTransformation() { return this.cameraTransformation; } public double getZTranslation() { return this.translation.z; } public GL3DQuatd getLocalRotation() { return this.localRotation; } public GL3DQuatd getRotation() { this.updateCameraTransformation(); return this.rotation; } public GL3DQuatd getRotationInverse() { this.updateCameraTransformation(); return this.rotation; } public void resetCurrentDragRotation() { this.currentDragRotation.clear(); } public void setLocalRotation(GL3DQuatd localRotation) { this.localRotation = localRotation; this.rotation.clear(); this.updateCameraTransformation(); } public void setCurrentDragRotation(GL3DQuatd currentDragRotation) { this.currentDragRotation = currentDragRotation; this.rotation.clear(); this.updateCameraTransformation(); } public void rotateCurrentDragRotation(GL3DQuatd currentDragRotation) { this.currentDragRotation.rotate(currentDragRotation); this.rotation.clear(); this.updateCameraTransformation(); } public void activate() { } public void applyPerspective(GL3DState state) { GL2 gl = state.gl; gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPushMatrix(); this.aspect = state.getViewportWidth() / (double) state.getViewportHeight(); cameraWidth = -translation.z * Math.tan(fov / 2.); if (cameraWidth == 0.) cameraWidth = 1.; cameraWidthTimesAspect = cameraWidth * aspect; gl.glLoadIdentity(); gl.glOrtho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); gl.glMatrixMode(GL2.GL_MODELVIEW); if (cameraWidth == previousCameraWidth && aspect == previousAspect) { return; } previousCameraWidth = cameraWidth; previousAspect = aspect; //orthoMatrix = GL3DMat4d.ortho(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); orthoMatrixInverse = GL3DMat4d.orthoInverse(-cameraWidthTimesAspect, cameraWidthTimesAspect, -cameraWidth, cameraWidth, clipNear, clipFar); } public void resumePerspective(GL3DState state) { GL2 gl = state.gl; gl.glMatrixMode(GL2.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL2.GL_MODELVIEW); } public GL3DVec3d getVectorFromSphereOrPlane(GL3DVec2d normalizedScreenpos, GL3DMat4d cameraDifferenceRotation) { //GL3DVec4d up1 = this.orthoMatrixInverse.multiply(normalizedScreenpos); double up1x = normalizedScreenpos.x * cameraWidthTimesAspect; double up1y = normalizedScreenpos.y * cameraWidth; GL3DVec3d hitPoint; GL3DVec3d rotatedHitPoint; double radius2 = up1x * up1x + up1y * up1y; if (radius2 <= 1) { hitPoint = new GL3DVec3d(up1x, up1y, Math.sqrt(1. - radius2)); rotatedHitPoint = cameraDifferenceRotation.multiplyTranspose(hitPoint); if (rotatedHitPoint.z > 0.) { return rotatedHitPoint; } } GL3DVec3d altnormal = cameraDifferenceRotation.multiply(new GL3DVec3d(0., 0., 1.)); double zvalue = -(altnormal.x * up1x + altnormal.y * up1y) / altnormal.z; hitPoint = new GL3DVec3d(up1x, up1y, zvalue); rotatedHitPoint = cameraDifferenceRotation.multiplyTranspose(hitPoint); return rotatedHitPoint; } public GL3DVec3d getVectorFromSphere(Point viewportCoordinates) { GL3DVec3d hp = rayTracer.cast(viewportCoordinates.getX(), viewportCoordinates.getY()).getHitpoint(); return hp; } public GL3DVec3d getVectorFromSphereAlt(Point viewportCoordinates) { GL3DVec3d hp = rayTracer.cast(viewportCoordinates.getX(), viewportCoordinates.getY()).getHitpoint(); return this.getLocalRotation().toMatrix().multiply(hp); } /** * Updates the camera transformation by applying the rotation and * translation information. */ public void updateCameraTransformation() { this.rotation = this.currentDragRotation.copy(); this.rotation.rotate(this.localRotation); cameraTransformation = this.rotation.toMatrix().translate(this.translation); } public GL3DMat4d getRotationMatrix() { return this.getRotation().toMatrix(); } public void applyCamera(GL3DState state) { state.gl.glMultMatrixd(cameraTransformation.m, 0); } public abstract GL3DInteraction getPanInteraction(); public abstract GL3DInteraction getRotateInteraction(); public abstract GL3DInteraction getZoomInteraction(); public abstract String getName(); public void drawCamera(GL3DState state) { getCurrentInteraction().drawInteractionFeedback(state, this); } public abstract GL3DInteraction getCurrentInteraction(); public abstract void setCurrentInteraction(GL3DInteraction currentInteraction); public double getCameraFOV() { return this.fov; } public double setCameraFOV(double fov) { if (fov < MIN_FOV) { this.fov = MIN_FOV; } else if (fov > MAX_FOV) { this.fov = MAX_FOV; } else { this.fov = fov; } return this.fov; } public final double getClipNear() { return clipNear; } public final double getClipFar() { return clipFar; } public double getAspect() { return aspect; } @Override public String toString() { return getName(); } public void setTimeDelay(long timeDelay) { this.timeDelay = timeDelay; } public long getTimeDelay() { return this.timeDelay; } public GL3DQuatd getCurrentDragRotation() { return this.currentDragRotation; } public void setRatio(double ratio) { this.ratio = ratio; this.translation.z = this.translationz * this.ratio; } public void setTime(long time) { this.time = time; } public long getTime() { return time; } public void setTrackingMode(boolean trackingMode) { this.trackingMode = trackingMode; } public boolean getTrackingMode() { return this.trackingMode; } public void deactivate() { } public void setDefaultFOV() { this.fov = INITFOV; } public double getCameraWidth() { return cameraWidth; } public void zoomIn(int wr) { double currentWidth = this.getCameraWidth(); double newWidth = currentWidth + wr * 0.1; double fov = 2. * Math.atan(-newWidth / this.getTranslation().z); this.setCameraFOV(fov); Displayer.display(); } }
Reduce GL3DVec3d allocations git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@4109 b4e469a2-07ce-4b26-9273-4d7d95a670c7
src/jhv/src/org/helioviewer/gl3d/camera/GL3DCamera.java
Reduce GL3DVec3d allocations
Java
agpl-3.0
344282b9f519f2bc3c6495064ddf0017091521fc
0
hobrasoft-cz/PDFMU,hobrasoft-cz/PDFMU
package cz.hobrasoft.pdfmu.error; import cz.hobrasoft.pdfmu.IntProperties; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Logger; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.functors.StringValueTransformer; /** * Lists all the types of errors (failing conditions) that can happen in PDFMU. * Every error type has a code and a message associated. The codes are loaded * from the properties file {@link #errorCodesResourceName} and the messages are * loaded from the resource bundle {@link #errorMessagesResourceBundleBaseName}. * The messages are templated. The keys in the {@code .properties} files must * match the strings returned by {@link ErrorType#toString()} (which returns the * enum constant name by default). * * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> */ public enum ErrorType { PARSER_UNKNOWN, PARSER_UNRECOGNIZED_ARGUMENT, PARSER_INVALID_CHOICE, INPUT_NOT_VALID_PDF, INPUT_NOT_FOUND, INPUT_CLOSE, OUTPUT_NOT_SPECIFIED, OUTPUT_EXISTS_FORCE_NOT_SET, OUTPUT_OPEN, OUTPUT_STAMPER_OPEN, OUTPUT_STAMPER_CLOSE, OUTPUT_CLOSE, SIGNATURE_ADD_KEYSTORE_TYPE_UNSUPPORTED, SIGNATURE_ADD_KEYSTORE_FILE_NOT_SPECIFIED, SIGNATURE_ADD_KEYSTORE_FILE_OPEN, SIGNATURE_ADD_KEYSTORE_LOAD, SIGNATURE_ADD_KEYSTORE_FILE_CLOSE, SIGNATURE_ADD_KEYSTORE_ALIASES, SIGNATURE_ADD_KEYSTORE_EMPTY, SIGNATURE_ADD_KEYSTORE_ALIAS_MISSING, SIGNATURE_ADD_KEYSTORE_ALIAS_EXCEPTION, SIGNATURE_ADD_KEYSTORE_ALIAS_NOT_KEY, SIGNATURE_ADD_KEYSTORE_ALIAS_KEY_EXCEPTION, SIGNATURE_ADD_KEYSTORE_PRIVATE_KEY, SIGNATURE_ADD_KEYSTORE_CERTIFICATE_CHAIN, SIGNATURE_ADD_UNSUPPORTED_DIGEST_ALGORITHM, SIGNATURE_ADD_FAIL, ATTACH_FAIL, ATTACH_ATTACHMENT_EQUALS_OUTPUT; // Configuration /** * The default error code. It is used for error types that have no code * associated in {@link #errorCodesResourceName}. */ public static final int defaultErrorCode = -1; // Used if no matching code is found in `errorCodes` public static final String errorCodesResourceName = "cz/hobrasoft/pdfmu/error/ErrorCodes.properties"; public static final String errorMessagesResourceBundleBaseName = "cz.hobrasoft.pdfmu.error.ErrorMessages"; private static final Logger logger = Logger.getLogger(ErrorType.class.getName()); private static final IntProperties errorCodes = new IntProperties(defaultErrorCode); private static ResourceBundle errorMessages = null; /** * @return true iff each of the constants of this enum is a key in both * {@link #errorCodes} and {@link #errorMessages}. */ private static boolean codesAndMessagesAvailable() { ErrorType[] enumKeyArray = ErrorType.values(); List<ErrorType> enumKeyList = Arrays.asList(enumKeyArray); Collection<String> enumKeyStrings = CollectionUtils.collect(enumKeyList, StringValueTransformer.stringValueTransformer()); Set<String> codeKeySet = errorCodes.stringPropertyNames(); assert errorMessages != null; Set<String> messageKeySet = errorMessages.keySet(); return codeKeySet.containsAll(enumKeyStrings) && messageKeySet.containsAll(enumKeyStrings); } /** * @return true iff the codes stored in {@link #errorCodes} are pairwise * different. */ private static boolean codesUnique() { Collection<Integer> codes = errorCodes.intPropertyValues(); Set<Integer> codesUnique = new HashSet<>(codes); assert codes.size() >= codesUnique.size(); return codes.size() == codesUnique.size(); } /** * Loads error codes from the properties resource * {@link #errorCodesResourceName} and stores them in {@link #errorCodes}. */ private static void loadErrorCodes() { ClassLoader classLoader = ErrorType.class.getClassLoader(); InputStream in = classLoader.getResourceAsStream(errorCodesResourceName); if (in != null) { try { errorCodes.load(in); } catch (IOException ex) { logger.severe(String.format("Could not load the error codes properties file: %s", ex)); } try { in.close(); } catch (IOException ex) { logger.severe(String.format("Could not close the error codes properties file: %s", ex)); } } else { logger.severe("Could not open the error codes properties file."); } } /** * Loads error messages from the resource bundle * {@link #errorMessagesResourceBundleBaseName} and stores them in * {@link #errorMessages}. */ private static void loadErrorMessages() { try { errorMessages = ResourceBundle.getBundle(errorMessagesResourceBundleBaseName); } catch (MissingResourceException ex) { logger.severe(String.format("Could not load the error messages resource bundle: %s", ex)); } } static { // Load error codes and messages before OperationException is instantiated loadErrorCodes(); loadErrorMessages(); assert errorMessages != null; // Assert that a code and a message is available for every enum constant assert codesAndMessagesAvailable(); // Assert that the codes are pairwise different assert codesUnique(); } /** * Returns the error code associated with this error type. The code should * uniquely identify the error. The default value {@link #defaultErrorCode} * is returned in case no code is associated with this error type. The error * codes are loaded from {@code ErrorCodes.properties} when the first * {@link ErrorType} is instantiated. * * @return the error code associated with this error type, or -1 if none is * associated */ public int getCode() { return errorCodes.getIntProperty(toString()); } /** * Returns the message pattern associated with this error type. The message * patterns are loaded from {@code ErrorMessages.properties} when the first * {@link ErrorType} is instantiated. * * @return the message pattern associated with this error type, or null if * none is associated */ public String getMessagePattern() { String key = toString(); assert errorMessages != null; if (errorMessages != null && errorMessages.containsKey(key)) { return errorMessages.getString(key); } else { return null; } } }
pdfmu/src/main/java/cz/hobrasoft/pdfmu/error/ErrorType.java
package cz.hobrasoft.pdfmu.error; import cz.hobrasoft.pdfmu.IntProperties; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Logger; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.functors.StringValueTransformer; /** * Lists all the types of errors (failing conditions) that can happen in PDFMU. * Every error type has a code and a message associated. The codes are loaded * from the properties file {@link #errorCodesResourceName} and the messages are * loaded from the resource bundle {@link #errorMessagesResourceBundleBaseName}. * The messages are templated. The keys in the {@code .properties} files must * match the strings returned by {@link ErrorType#toString()} (which returns the * enum constant name by default). * * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> */ public enum ErrorType { PARSER_UNKNOWN, PARSER_UNRECOGNIZED_ARGUMENT, PARSER_INVALID_CHOICE, INPUT_NOT_VALID_PDF, INPUT_NOT_FOUND, INPUT_CLOSE, OUTPUT_NOT_SPECIFIED, OUTPUT_EXISTS_FORCE_NOT_SET, OUTPUT_OPEN, OUTPUT_STAMPER_OPEN, OUTPUT_STAMPER_CLOSE, OUTPUT_CLOSE, SIGNATURE_ADD_KEYSTORE_TYPE_UNSUPPORTED, SIGNATURE_ADD_KEYSTORE_FILE_NOT_SPECIFIED, SIGNATURE_ADD_KEYSTORE_FILE_OPEN, SIGNATURE_ADD_KEYSTORE_LOAD, SIGNATURE_ADD_KEYSTORE_FILE_CLOSE, SIGNATURE_ADD_KEYSTORE_ALIASES, SIGNATURE_ADD_KEYSTORE_EMPTY, SIGNATURE_ADD_KEYSTORE_ALIAS_MISSING, SIGNATURE_ADD_KEYSTORE_ALIAS_EXCEPTION, SIGNATURE_ADD_KEYSTORE_ALIAS_NOT_KEY, SIGNATURE_ADD_KEYSTORE_ALIAS_KEY_EXCEPTION, SIGNATURE_ADD_KEYSTORE_PRIVATE_KEY, SIGNATURE_ADD_KEYSTORE_CERTIFICATE_CHAIN, SIGNATURE_ADD_UNSUPPORTED_DIGEST_ALGORITHM, SIGNATURE_ADD_FAIL, ATTACH_FAIL, ATTACH_ATTACHMENT_EQUALS_OUTPUT; // Configuration /** * The default error code. It is used for error types that have no code * associated in {@link #errorCodesResourceName}. */ public static final int defaultErrorCode = -1; // Used if no matching code is found in `errorCodes` public static final String errorCodesResourceName = "cz/hobrasoft/pdfmu/error/ErrorCodes.properties"; public static final String errorMessagesResourceBundleBaseName = "cz.hobrasoft.pdfmu.error.ErrorMessages"; private static final Logger logger = Logger.getLogger(ErrorType.class.getName()); private static final IntProperties errorCodes = new IntProperties(defaultErrorCode); private static ResourceBundle errorMessages = null; /** * @return true iff each of the constants of this enum is a key in both * {@link #errorCodes} and {@link #errorMessages}. */ private static boolean codesAndMessagesAvailable() { ErrorType[] enumKeyArray = ErrorType.values(); List<ErrorType> enumKeyList = Arrays.asList(enumKeyArray); Collection<String> enumKeyStrings = CollectionUtils.collect(enumKeyList, StringValueTransformer.stringValueTransformer()); Set<String> codeKeySet = errorCodes.stringPropertyNames(); assert errorMessages != null; Set<String> messageKeySet = errorMessages.keySet(); return codeKeySet.containsAll(enumKeyStrings) && messageKeySet.containsAll(enumKeyStrings); } /** * @return true iff the codes stored in {@link #errorCodes} are pairwise * different. */ private static boolean codesUnique() { Collection<Integer> codes = errorCodes.intPropertyValues(); Set<Integer> codesUnique = new HashSet<>(codes); assert codes.size() >= codesUnique.size(); return codes.size() == codesUnique.size(); } /** * Loads error codes from the properties resource * {@link #errorCodesResourceName} and stores them in {@link #errorCodes}. */ private static void loadErrorCodes() { ClassLoader classLoader = ErrorType.class.getClassLoader(); InputStream in = classLoader.getResourceAsStream(errorCodesResourceName); if (in != null) { try { errorCodes.load(in); } catch (IOException ex) { logger.severe(String.format("Could not load the error codes properties file: %s", ex)); } try { in.close(); } catch (IOException ex) { logger.severe(String.format("Could not close the error codes properties file: %s", ex)); } } else { logger.severe("Could not open the error codes properties file."); } } /** * Loads error messages from the resource bundle * {@link #errorMessagesResourceBundleBaseName} and stores them in * {@link #errorMessages}. */ private static void loadErrorMessages() { try { errorMessages = ResourceBundle.getBundle(errorMessagesResourceBundleBaseName); } catch (MissingResourceException ex) { logger.severe(String.format("Could not load the error messages resource bundle: %s", ex)); } } static { // Load error codes before OperationException is instantiated loadErrorCodes(); loadErrorMessages(); assert errorMessages != null; // Make sure all a code and a message is available for every enum value assert codesAndMessagesAvailable(); assert codesUnique(); } /** * Returns the error code associated with this error type. The code should * uniquely identify the error. The default value {@link #defaultErrorCode} * is returned in case no code is associated with this error type. The error * codes are loaded from {@code ErrorCodes.properties} when the first * {@link ErrorType} is instantiated. * * @return the error code associated with this error type, or -1 if none is * associated */ public int getCode() { return errorCodes.getIntProperty(toString()); } /** * Returns the message pattern associated with this error type. The message * patterns are loaded from {@code ErrorMessages.properties} when the first * {@link ErrorType} is instantiated. * * @return the message pattern associated with this error type, or null if * none is associated */ public String getMessagePattern() { String key = toString(); assert errorMessages != null; if (errorMessages != null && errorMessages.containsKey(key)) { return errorMessages.getString(key); } else { return null; } } }
ErrorType: Update comments
pdfmu/src/main/java/cz/hobrasoft/pdfmu/error/ErrorType.java
ErrorType: Update comments
Java
agpl-3.0
766b1e2e1e8bf86c9e8df104a3b56807d0a73e40
0
bitsquare/bitsquare,bitsquare/bitsquare,bisq-network/exchange,bisq-network/exchange
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.btc.model; import bisq.common.config.Config; import bisq.common.proto.persistable.PersistedDataHost; import bisq.common.proto.persistable.UserThreadMappedPersistableEnvelope; import bisq.common.storage.Storage; import com.google.protobuf.Message; import org.bitcoinj.core.Address; import org.bitcoinj.core.LegacyAddress; import org.bitcoinj.core.Transaction; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.script.Script; import org.bitcoinj.wallet.Wallet; import com.google.inject.Inject; import com.google.common.collect.ImmutableList; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collectors; import lombok.ToString; import lombok.extern.slf4j.Slf4j; /** * The AddressEntries was previously stored as list, now as hashSet. We still keep the old name to reflect the * associated protobuf message. */ @ToString @Slf4j public final class AddressEntryList implements UserThreadMappedPersistableEnvelope, PersistedDataHost { transient private Storage<AddressEntryList> storage; transient private Wallet wallet; private final Set<AddressEntry> entrySet = new CopyOnWriteArraySet<>(); @Inject public AddressEntryList(Storage<AddressEntryList> storage) { this.storage = storage; } @Override public void readPersisted() { AddressEntryList persisted = storage.initAndGetPersisted(this, 50); if (persisted != null) { entrySet.clear(); entrySet.addAll(persisted.entrySet); } } /////////////////////////////////////////////////////////////////////////////////////////// // PROTO BUFFER /////////////////////////////////////////////////////////////////////////////////////////// private AddressEntryList(Set<AddressEntry> entrySet) { this.entrySet.addAll(entrySet); } public static AddressEntryList fromProto(protobuf.AddressEntryList proto) { Set<AddressEntry> entrySet = proto.getAddressEntryList().stream() .map(AddressEntry::fromProto) .collect(Collectors.toSet()); return new AddressEntryList(entrySet); } @Override public Message toProtoMessage() { Set<protobuf.AddressEntry> addressEntries = entrySet.stream() .map(AddressEntry::toProtoMessage) .collect(Collectors.toSet()); return protobuf.PersistableEnvelope.newBuilder() .setAddressEntryList(protobuf.AddressEntryList.newBuilder() .addAllAddressEntry(addressEntries)) .build(); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// public void onWalletReady(Wallet wallet) { this.wallet = wallet; if (!entrySet.isEmpty()) { Set<AddressEntry> toBeRemoved = new HashSet<>(); entrySet.forEach(addressEntry -> { DeterministicKey keyFromPubHash = (DeterministicKey) wallet.findKeyFromPubKeyHash( addressEntry.getPubKeyHash(), Script.ScriptType.P2PKH); if (keyFromPubHash != null) { Address addressFromKey = LegacyAddress.fromKey(Config.baseCurrencyNetworkParameters(), keyFromPubHash); // We want to ensure key and address matches in case we have address in entry available already if (addressEntry.getAddress() == null || addressFromKey.equals(addressEntry.getAddress())) { addressEntry.setDeterministicKey(keyFromPubHash); } else { log.error("We found an address entry without key but cannot apply the key as the address " + "is not matching. " + "We remove that entry as it seems it is not compatible with our wallet. " + "addressFromKey={}, addressEntry.getAddress()={}", addressFromKey, addressEntry.getAddress()); toBeRemoved.add(addressEntry); } } else { log.error("Key from addressEntry {} not found in that wallet. We remove that entry. " + "This is expected at restore from seeds.", addressEntry.toString()); toBeRemoved.add(addressEntry); } }); toBeRemoved.forEach(entrySet::remove); } else { // As long the old arbitration domain is not removed from the code base we still support it here. entrySet.add(new AddressEntry(wallet.freshReceiveKey(), AddressEntry.Context.ARBITRATOR)); } // In case we restore from seed words and have balance we need to add the relevant addresses to our list. // IssuedReceiveAddresses does not contain all addresses where we expect balance so we need to listen to // incoming txs at blockchain sync to add the rest. if (wallet.getBalance().isPositive()) { wallet.getIssuedReceiveAddresses().stream() .filter(this::isAddressNotInEntries) .forEach(address -> { log.info("Create AddressEntry for IssuedReceiveAddress. address={}", address.toString()); DeterministicKey key = (DeterministicKey) wallet.findKeyFromAddress(address); if (key != null) { // Address will be derived from key in getAddress method entrySet.add(new AddressEntry(key, AddressEntry.Context.AVAILABLE)); } }); } // We add those listeners to get notified about potential new transactions and // add an address entry list in case it does not exist yet. This is mainly needed for restore from seed words // but can help as well in case the addressEntry list would miss an address where the wallet was received // funds (e.g. if the user sends funds to an address which has not been provided in the main UI - like from the // wallet details window). wallet.addCoinsReceivedEventListener((wallet1, tx, prevBalance, newBalance) -> { maybeAddNewAddressEntry(tx); }); wallet.addCoinsSentEventListener((wallet1, tx, prevBalance, newBalance) -> { maybeAddNewAddressEntry(tx); }); persist(); } public ImmutableList<AddressEntry> getAddressEntriesAsListImmutable() { return ImmutableList.copyOf(entrySet); } public void addAddressEntry(AddressEntry addressEntry) { boolean entryWithSameOfferIdAndContextAlreadyExist = entrySet.stream().anyMatch(e -> { if (addressEntry.getOfferId() != null) { return addressEntry.getOfferId().equals(e.getOfferId()) && addressEntry.getContext() == e.getContext(); } return false; }); if (entryWithSameOfferIdAndContextAlreadyExist) { log.error("We have an address entry with the same offer ID and context. We do not add the new one. " + "addressEntry={}, entrySet={}", addressEntry, entrySet); return; } boolean setChangedByAdd = entrySet.add(addressEntry); if (setChangedByAdd) persist(); } public void swapToAvailable(AddressEntry addressEntry) { boolean setChangedByRemove = entrySet.remove(addressEntry); boolean setChangedByAdd = entrySet.add(new AddressEntry(addressEntry.getKeyPair(), AddressEntry.Context.AVAILABLE)); if (setChangedByRemove || setChangedByAdd) { persist(); } } public AddressEntry swapAvailableToAddressEntryWithOfferId(AddressEntry addressEntry, AddressEntry.Context context, String offerId) { boolean setChangedByRemove = entrySet.remove(addressEntry); final AddressEntry newAddressEntry = new AddressEntry(addressEntry.getKeyPair(), context, offerId); boolean setChangedByAdd = entrySet.add(newAddressEntry); if (setChangedByRemove || setChangedByAdd) persist(); return newAddressEntry; } public void persist() { storage.queueUpForSave(50); } /////////////////////////////////////////////////////////////////////////////////////////// // Private /////////////////////////////////////////////////////////////////////////////////////////// private void maybeAddNewAddressEntry(Transaction tx) { tx.getOutputs().stream() .filter(output -> output.isMine(wallet)) .map(output -> output.getScriptPubKey().getToAddress(wallet.getNetworkParameters())) .filter(Objects::nonNull) .filter(this::isAddressNotInEntries) .map(address -> (DeterministicKey) wallet.findKeyFromPubKeyHash(address.getHash(), Script.ScriptType.P2PKH)) .filter(Objects::nonNull) .map(deterministicKey -> new AddressEntry(deterministicKey, AddressEntry.Context.AVAILABLE)) .forEach(this::addAddressEntry); } private boolean isAddressNotInEntries(Address address) { return entrySet.stream().noneMatch(e -> address.equals(e.getAddress())); } }
core/src/main/java/bisq/core/btc/model/AddressEntryList.java
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.btc.model; import bisq.common.config.Config; import bisq.common.proto.persistable.PersistedDataHost; import bisq.common.proto.persistable.UserThreadMappedPersistableEnvelope; import bisq.common.storage.Storage; import com.google.protobuf.Message; import org.bitcoinj.core.Address; import org.bitcoinj.core.LegacyAddress; import org.bitcoinj.core.Transaction; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.script.Script; import org.bitcoinj.wallet.Wallet; import com.google.inject.Inject; import com.google.common.collect.ImmutableList; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collectors; import lombok.ToString; import lombok.extern.slf4j.Slf4j; /** * The AddressEntries was previously stored as list, now as hashSet. We still keep the old name to reflect the * associated protobuf message. */ @ToString @Slf4j public final class AddressEntryList implements UserThreadMappedPersistableEnvelope, PersistedDataHost { transient private Storage<AddressEntryList> storage; transient private Wallet wallet; private final Set<AddressEntry> entrySet = new CopyOnWriteArraySet<>(); @Inject public AddressEntryList(Storage<AddressEntryList> storage) { this.storage = storage; } @Override public void readPersisted() { AddressEntryList persisted = storage.initAndGetPersisted(this, 50); if (persisted != null) { entrySet.clear(); entrySet.addAll(persisted.entrySet); } } /////////////////////////////////////////////////////////////////////////////////////////// // PROTO BUFFER /////////////////////////////////////////////////////////////////////////////////////////// private AddressEntryList(Set<AddressEntry> entrySet) { this.entrySet.addAll(entrySet); } public static AddressEntryList fromProto(protobuf.AddressEntryList proto) { Set<AddressEntry> entrySet = proto.getAddressEntryList().stream() .map(AddressEntry::fromProto) .collect(Collectors.toSet()); return new AddressEntryList(entrySet); } @Override public Message toProtoMessage() { Set<protobuf.AddressEntry> addressEntries = entrySet.stream() .map(AddressEntry::toProtoMessage) .collect(Collectors.toSet()); return protobuf.PersistableEnvelope.newBuilder() .setAddressEntryList(protobuf.AddressEntryList.newBuilder() .addAllAddressEntry(addressEntries)) .build(); } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// public void onWalletReady(Wallet wallet) { this.wallet = wallet; if (!entrySet.isEmpty()) { Set<AddressEntry> toBeRemoved = new HashSet<>(); entrySet.forEach(addressEntry -> { DeterministicKey keyFromPubHash = (DeterministicKey) wallet.findKeyFromPubKeyHash( addressEntry.getPubKeyHash(), Script.ScriptType.P2PKH); if (keyFromPubHash != null) { Address addressFromKey = LegacyAddress.fromKey(Config.baseCurrencyNetworkParameters(), keyFromPubHash); // We want to ensure key and address matches in case we have address in entry available already if (addressEntry.getAddress() == null || addressFromKey.equals(addressEntry.getAddress())) { addressEntry.setDeterministicKey(keyFromPubHash); } else { log.error("We found an address entry without key but cannot apply the key as the address " + "is not matching. " + "We remove that entry as it seems it is not compatible with our wallet. " + "addressFromKey={}, addressEntry.getAddress()={}", addressFromKey, addressEntry.getAddress()); toBeRemoved.add(addressEntry); } } else { log.error("Key from addressEntry {} not found in that wallet. We remove that entry. " + "This is expected at restore from seeds.", addressEntry.toString()); toBeRemoved.add(addressEntry); } }); toBeRemoved.forEach(entrySet::remove); } else { // As long the old arbitration domain is not removed from the code base we still support it here. entrySet.add(new AddressEntry(wallet.freshReceiveKey(), AddressEntry.Context.ARBITRATOR)); } // In case we restore from seed words and have balance we need to add the relevant addresses to our list. // IssuedReceiveAddresses does not contain all addresses where we expect balance so we need to listen to // incoming txs at blockchain sync to add the rest. if (wallet.getBalance().isPositive()) { wallet.getIssuedReceiveAddresses().stream() .filter(this::isAddressNotInEntries) .forEach(address -> { log.info("Create AddressEntry for IssuedReceiveAddress. address={}", address.toString()); DeterministicKey key = (DeterministicKey) wallet.findKeyFromAddress(address); if (key != null) { // Address will be derived from key in getAddress method entrySet.add(new AddressEntry(key, AddressEntry.Context.AVAILABLE)); } }); } // We add those listeners to get notified about potential new transactions and // add an address entry list in case it does not exist yet. This is mainly needed for restore from seed words // but can help as well in case the addressEntry list would miss an address where the wallet was received // funds (e.g. if the user sends funds to an address which has not been provided in the main UI - like from the // wallet details window). wallet.addCoinsReceivedEventListener((wallet1, tx, prevBalance, newBalance) -> { maybeAddNewAddressEntry(tx); }); wallet.addCoinsSentEventListener((wallet1, tx, prevBalance, newBalance) -> { maybeAddNewAddressEntry(tx); }); persist(); } public ImmutableList<AddressEntry> getAddressEntriesAsListImmutable() { return ImmutableList.copyOf(entrySet); } public void addAddressEntry(AddressEntry addressEntry) { boolean setChangedByAdd = entrySet.add(addressEntry); if (setChangedByAdd) persist(); } public void swapToAvailable(AddressEntry addressEntry) { boolean setChangedByRemove = entrySet.remove(addressEntry); boolean setChangedByAdd = entrySet.add(new AddressEntry(addressEntry.getKeyPair(), AddressEntry.Context.AVAILABLE)); if (setChangedByRemove || setChangedByAdd) { persist(); } } public AddressEntry swapAvailableToAddressEntryWithOfferId(AddressEntry addressEntry, AddressEntry.Context context, String offerId) { boolean setChangedByRemove = entrySet.remove(addressEntry); final AddressEntry newAddressEntry = new AddressEntry(addressEntry.getKeyPair(), context, offerId); boolean setChangedByAdd = entrySet.add(newAddressEntry); if (setChangedByRemove || setChangedByAdd) persist(); return newAddressEntry; } public void persist() { storage.queueUpForSave(50); } /////////////////////////////////////////////////////////////////////////////////////////// // Private /////////////////////////////////////////////////////////////////////////////////////////// private void maybeAddNewAddressEntry(Transaction tx) { tx.getOutputs().stream() .filter(output -> output.isMine(wallet)) .map(output -> output.getScriptPubKey().getToAddress(wallet.getNetworkParameters())) .filter(Objects::nonNull) .filter(this::isAddressNotInEntries) .map(address -> (DeterministicKey) wallet.findKeyFromPubKeyHash(address.getHash(), Script.ScriptType.P2PKH)) .filter(Objects::nonNull) .map(deterministicKey -> new AddressEntry(deterministicKey, AddressEntry.Context.AVAILABLE)) .forEach(this::addAddressEntry); } private boolean isAddressNotInEntries(Address address) { return entrySet.stream().noneMatch(e -> address.equals(e.getAddress())); } }
Add check to not add a duplicate address entry with same offer ID and context. In debugging trade protocol and taking same offer I could generate problems where the multisig entry was twice but with diff. keys, so take offer failed. I remember the error log to have seen in the past and I assume this was a rare bug we encountered when users took again the same offer which failed with an uncritical state earlier.
core/src/main/java/bisq/core/btc/model/AddressEntryList.java
Add check to not add a duplicate address entry with same offer ID and context. In debugging trade protocol and taking same offer I could generate problems where the multisig entry was twice but with diff. keys, so take offer failed. I remember the error log to have seen in the past and I assume this was a rare bug we encountered when users took again the same offer which failed with an uncritical state earlier.
Java
lgpl-2.1
a65e293c439173643b15b8940bc4a7ded3ea84a9
0
sbliven/biojava,sbliven/biojava,sbliven/biojava
package seq; import org.biojavax.RichObjectFactory; import org.biojavax.bio.db.ncbi.GenbankRichSequenceDB; import org.biojavax.bio.seq.RichSequence; /** * Fetch sequences by accession from the NCBI efetch server and dump them as genbank. * Updated to use RichSequence and BioJavaX. * * Messages go to stderr and all data output goes to stdout. * * @author Matthew Pocock * @author Mark Schreiber */ public class FetchSeq { /** * Run the program * @param args one or more genbank accessions */ public static void main(String[] args) { GenbankRichSequenceDB genbank = new GenbankRichSequenceDB(); for(int i = 0; i < args.length; i++) { try { System.err.println("Fetching: " + args[i]); RichSequence seq = genbank.getRichSequence(args[i]); RichSequence.IOTools.writeGenbank(System.out, seq, RichObjectFactory.getDefaultNamespace()); System.err.println("Done."); } catch (Throwable t) { t.printStackTrace(System.err); } } } }
demos/seq/FetchSeq.java
package seq; import org.biojava.utils.*; import org.biojava.bio.*; import org.biojava.bio.seq.*; import org.biojava.bio.seq.db.*; import org.biojava.bio.seq.io.*; /** * Fetch sequences by accession from the NCBI efetch server and dump them as genbank. * * Messages go to stderr and all data output goes to stdout. * * @author Matthew Pocock */ public class FetchSeq { public static void main(String[] args) { GenbankSequenceDB genbank = new GenbankSequenceDB(); for(int i = 0; i < args.length; i++) { try { System.err.println("Fetching: " + args[i]); Sequence seq = genbank.getSequence(args[i]); SeqIOTools.writeGenbank(System.out, seq); System.err.println("Done."); } catch (Throwable t) { t.printStackTrace(System.err); } } } }
updated for biojavax git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@3754 7c6358e6-4a41-0410-a743-a5b2a554c398
demos/seq/FetchSeq.java
updated for biojavax
Java
lgpl-2.1
8bc79acc551ae32ebb79dc8bf1a6fd271cb2c5e2
0
shabanovd/exist,hungerburg/exist,eXist-db/exist,wolfgangmm/exist,opax/exist,jessealama/exist,MjAbuz/exist,lcahlander/exist,wshager/exist,ambs/exist,jensopetersen/exist,ambs/exist,kohsah/exist,patczar/exist,eXist-db/exist,ljo/exist,eXist-db/exist,wolfgangmm/exist,jensopetersen/exist,RemiKoutcherawy/exist,joewiz/exist,ljo/exist,zwobit/exist,dizzzz/exist,windauer/exist,patczar/exist,opax/exist,ljo/exist,adamretter/exist,kohsah/exist,jessealama/exist,joewiz/exist,adamretter/exist,jensopetersen/exist,ambs/exist,kohsah/exist,patczar/exist,jessealama/exist,adamretter/exist,MjAbuz/exist,adamretter/exist,wshager/exist,kohsah/exist,jensopetersen/exist,joewiz/exist,olvidalo/exist,patczar/exist,ambs/exist,wshager/exist,zwobit/exist,lcahlander/exist,olvidalo/exist,joewiz/exist,hungerburg/exist,lcahlander/exist,adamretter/exist,zwobit/exist,zwobit/exist,ljo/exist,windauer/exist,hungerburg/exist,adamretter/exist,opax/exist,dizzzz/exist,lcahlander/exist,dizzzz/exist,hungerburg/exist,patczar/exist,wolfgangmm/exist,shabanovd/exist,MjAbuz/exist,ambs/exist,RemiKoutcherawy/exist,opax/exist,wolfgangmm/exist,jessealama/exist,jensopetersen/exist,olvidalo/exist,shabanovd/exist,eXist-db/exist,lcahlander/exist,shabanovd/exist,dizzzz/exist,MjAbuz/exist,wolfgangmm/exist,wshager/exist,shabanovd/exist,windauer/exist,RemiKoutcherawy/exist,jessealama/exist,kohsah/exist,MjAbuz/exist,zwobit/exist,jensopetersen/exist,ljo/exist,wshager/exist,windauer/exist,shabanovd/exist,patczar/exist,windauer/exist,joewiz/exist,olvidalo/exist,lcahlander/exist,dizzzz/exist,jessealama/exist,MjAbuz/exist,hungerburg/exist,eXist-db/exist,ambs/exist,kohsah/exist,ljo/exist,joewiz/exist,RemiKoutcherawy/exist,opax/exist,wolfgangmm/exist,dizzzz/exist,RemiKoutcherawy/exist,olvidalo/exist,windauer/exist,wshager/exist,zwobit/exist,eXist-db/exist,RemiKoutcherawy/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2011 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.debuggee; import java.util.Observable; import java.util.Observer; import org.exist.Database; import org.exist.debuggee.dbgp.packets.Stop; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.xquery.CompiledXQuery; import org.exist.xquery.XQuery; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class ScriptRunner implements Runnable, Observer { private SessionImpl session; private CompiledXQuery expression; private Thread thread; protected Exception exception = null; public ScriptRunner(SessionImpl session, CompiledXQuery compiled) { this.session = session; expression = compiled; thread = new Thread(this); thread.setDaemon(true); thread.setName("Debug session "+compiled.getContext().hashCode()); } public void start() { thread.start(); } public void stop() { thread.interrupt(); } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { Database db = null; DBBroker broker = null; try { db = BrokerPool.getInstance(); BrokerPool.registerStatusObserver(this); broker = db.get(null); XQuery xquery = broker.getXQueryService(); xquery.execute(expression, null); // XQueryContext context = expression.getContext(); // // expression.reset(); // // context.setBroker(broker); // context.getWatchDog().reset(); // // //do any preparation before execution // context.prepare(); // // context.getProfiler().traceQueryStart(); // broker.getBrokerPool().getProcessMonitor().queryStarted(context.getWatchDog()); // try { // Sequence result = expression.eval(null); // // if(outputProperties != null) // context.checkOptions(outputProperties); //must be done before context.reset! // // //return result; // } finally { // context.getProfiler().traceQueryEnd(context); // expression.reset(); // context.reset(); // broker.getBrokerPool().getProcessMonitor().queryCompleted(context.getWatchDog()); // } } catch (Exception e) { e.printStackTrace(); exception = e; } finally { if (db != null) db.release(broker); } } @Override public void update(Observable o, Object arg) { if (arg.equals(BrokerPool.SIGNAL_SHUTDOWN)) { Stop command = new Stop(session, ""); command.exec(); //TODO: make sure that session is closed? what can be done if not? } } }
extensions/debuggee/src/org/exist/debuggee/ScriptRunner.java
/* * eXist Open Source Native XML Database * Copyright (C) 2011 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.debuggee; import java.util.Observable; import java.util.Observer; import org.exist.Database; import org.exist.debuggee.dbgp.packets.Stop; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.xquery.CompiledXQuery; import org.exist.xquery.XQuery; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class ScriptRunner implements Runnable, Observer { private SessionImpl session; private CompiledXQuery expression; private Thread thread; protected Exception exception = null; public ScriptRunner(SessionImpl session, CompiledXQuery compiled) { this.session = session; expression = compiled; thread = new Thread(this); thread.setDaemon(true); thread.setName("Debug session "+compiled.getContext().hashCode()); } public void start() { thread.start(); } public void stop() { thread.interrupt(); } /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { Database db = null; DBBroker broker = null; try { db = BrokerPool.getInstance(); db.addObserver(this); broker = db.get(null); XQuery xquery = broker.getXQueryService(); xquery.execute(expression, null); // XQueryContext context = expression.getContext(); // // expression.reset(); // // context.setBroker(broker); // context.getWatchDog().reset(); // // //do any preparation before execution // context.prepare(); // // context.getProfiler().traceQueryStart(); // broker.getBrokerPool().getProcessMonitor().queryStarted(context.getWatchDog()); // try { // Sequence result = expression.eval(null); // // if(outputProperties != null) // context.checkOptions(outputProperties); //must be done before context.reset! // // //return result; // } finally { // context.getProfiler().traceQueryEnd(context); // expression.reset(); // context.reset(); // broker.getBrokerPool().getProcessMonitor().queryCompleted(context.getWatchDog()); // } } catch (Exception e) { e.printStackTrace(); exception = e; } finally { if (db != null) db.release(broker); } } @Override public void update(Observable o, Object arg) { if (arg.equals(BrokerPool.SIGNAL_SHUTDOWN)) { Stop command = new Stop(session, ""); command.exec(); //TODO: make sure that session is closed? what can be done if not? } } }
[bugfix] make debugger extension compile again
extensions/debuggee/src/org/exist/debuggee/ScriptRunner.java
[bugfix] make debugger extension compile again
Java
lgpl-2.1
8909b11c318018908bd0ad61817558bbef3ee0cb
0
levants/lightmare
package org.lightmare.rest.providers; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.MessageBodyReader; import org.glassfish.jersey.internal.util.collection.MultivaluedStringMap; import org.glassfish.jersey.message.MessageBodyWorkers; import org.glassfish.jersey.server.model.Parameter; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.reflect.MetaUtils; import org.lightmare.utils.rest.RequestUtils; /** * Translates REST request parameters to java objects * * @author levan * @since 0.0.75-SNAPSHOT */ public class ParamBuilder { private MediaType mediaType; private List<Parameter> parameters; private MessageBodyWorkers workers; private ContainerRequestContext request; private MultivaluedMap<String, String> httpHeaders; private MultivaluedMap<String, String> uriParams; private MessageBodyReader<?> reader; private boolean check; private List<Object> paramsList; // Default length of parameters list (used for MultivaluedMap) private static final int PARAM_VALIES_LENGTH = 1; private ParamBuilder() { } public ParamBuilder(MediaType mediaType, List<Parameter> parameters, MessageBodyWorkers workers, ContainerRequestContext request) { this.mediaType = mediaType; this.parameters = parameters; this.workers = workers; this.request = request; } /** * Creates error message if one of the necessary fields in null * * @return String * @throws IOException */ private String errorOnBuild() throws IOException { String errorMessage; String errorPrefix = "Could not initialize "; String errorClass = this.getClass().getName(); String errorReasonPrefix = " caouse"; String errorReasonSuffix = "is null"; String errorMessageBody; if (mediaType == null) { errorMessageBody = "mediaType"; } else if (parameters == null) { errorMessageBody = "parameters"; } else if (workers == null) { errorMessageBody = "workers"; } else if (request == null) { errorMessageBody = "request"; } else { throw new IOException("Could not find null value"); } errorMessage = new StringBuilder().append(errorPrefix) .append(errorClass).append(errorReasonPrefix) .append(errorMessageBody).append(errorReasonSuffix).toString(); return errorMessage; } /** * Check if one of the necessary fields in null and if it is throws * {@link IOException} with generated error message * * @return <code>boolean</code> * @throws IOException */ private boolean checkOnBuild() throws IOException { boolean valid = ObjectUtils.notNullAll(mediaType, parameters, workers, request); if (ObjectUtils.notTrue(valid)) { String errorMessage = errorOnBuild(); throw new IOException(errorMessage); } return valid; } private boolean check() throws IOException { return ObjectUtils.notTrue(request.hasEntity()) && IOUtils.notAvailable(request.getEntityStream()); } private void copyAll(MultivaluedMap<String, String> from, MultivaluedMap<String, String> to) { for (Map.Entry<String, List<String>> entry : from.entrySet()) { to.addAll(entry.getKey(), entry.getValue()); } } private void addAll(MultivaluedMap<String, String> from, MultivaluedMap<String, String> to) { if (CollectionUtils.valid(from)) { copyAll(from, to); } } /** * Extracts all parameters from {@link ContainerRequestContext} object * * @param request * @return {@link MultivaluedMap}<String, String> */ private MultivaluedMap<String, String> extractParameters( ContainerRequestContext request) { MultivaluedMap<String, String> params = new MultivaluedStringMap(); MultivaluedMap<String, String> exts; boolean decode = Boolean.TRUE; UriInfo uriInfo = request.getUriInfo(); exts = request.getHeaders(); addAll(exts, params); exts = uriInfo.getPathParameters(decode); addAll(exts, params); exts = uriInfo.getQueryParameters(decode); addAll(exts, params); Map<String, Cookie> cookies = request.getCookies(); if (CollectionUtils.valid(cookies)) { for (Map.Entry<String, Cookie> entry : cookies.entrySet()) { params.putSingle(entry.getKey(), entry.getValue().toString()); } } return params; } /** * Converts {@link Parameter} to {@link InputStream} or {@link List} of * {@link InputStream} by {@link Parameter} nature * * @param parameter * @return {@link Object} */ private Object getEntityStream(Parameter parameter) { Object stream; List<String> paramValues = uriParams.get(parameter.getSourceName()); String value; if (CollectionUtils.valid(paramValues)) { if (paramValues.size() == PARAM_VALIES_LENGTH) { value = CollectionUtils.getFirst(paramValues); stream = RequestUtils.textToStream(value); } else { stream = RequestUtils.textsToStreams(paramValues); } } else { stream = null; } return stream; } /** * Reads {@link InputStream} from passed {@link ContainerRequestContext} for * associated {@link Parameter} instance * * @param request * @param parameter * @return {@link Object} */ private Object getEntityStream(ContainerRequestContext request, Parameter parameter) { Object entityStream; if (check) { entityStream = getEntityStream(parameter); } else { entityStream = request.getEntityStream(); } return entityStream; } private boolean available(InputStream entityStream, Parameter parameter) { return ObjectUtils.notNullAll(reader, entityStream) && reader.isReadable(parameter.getRawType(), parameter.getType(), parameter.getAnnotations(), mediaType); } private void close(InputStream entityStream) throws IOException { if (check) { IOUtils.close(entityStream); } } /** * Extracts parameter from passed {@link InputStream} (writes appropriate * value to {@link Object} instance) * * @param parameter * @param entityStream * @return {@link Object} * @throws IOException */ @SuppressWarnings({ "unchecked", "rawtypes" }) private Object extractParam(Parameter parameter, InputStream entityStream) throws IOException { Object param; try { param = reader.readFrom((Class) parameter.getRawType(), parameter.getType(), parameter.getAnnotations(), mediaType, httpHeaders, entityStream); } finally { close(entityStream); } return param; } private void addParam(Object param) { if (ObjectUtils.notNull(param)) { paramsList.add(param); } } /** * Initializes and adds null parameter to {@link List} of parameters * * @param parameter */ private void addNullParam(Parameter parameter) { Class<?> paramType = parameter.getRawType(); Object nullParam; if (paramType.isPrimitive()) { nullParam = MetaUtils.getDefault(paramType); } else { nullParam = null; } paramsList.add(nullParam); } /** * Reads from {@link InputStream} to java {@link Object} instance * * @param entityStream * @param parameter * @throws IOException */ private void readFromStream(InputStream entityStream, Parameter parameter) throws IOException { boolean valid = available(entityStream, parameter); if (valid) { Object param = extractParam(parameter, entityStream); addParam(param); } } /** * Reads from {@link InputStream} or {@link List} of {@link InputStream} in * case that parameters are multi valued * * @param stream * @param parameter * @throws IOException */ private void fillParamList(Object stream, Parameter parameter) throws IOException { InputStream entityStream; if (stream instanceof InputStream) { entityStream = (InputStream) stream; readFromStream(entityStream, parameter); } else if (stream instanceof List) { List<InputStream> streamsList = ObjectUtils.cast(stream); Iterator<InputStream> streams = streamsList.iterator(); while (streams.hasNext()) { entityStream = streams.next(); readFromStream(entityStream, parameter); } } } /** * Extracts parameters from {@link ContainerRequestContext} instance * * @return {@link List}<Object> * @throws IOException */ public List<Object> extractParams() throws IOException { paramsList = new ArrayList<Object>(); check = check(); httpHeaders = request.getHeaders(); uriParams = extractParameters(request); Object stream; for (Parameter parameter : parameters) { reader = RequestUtils.getReader(workers, parameter, mediaType); stream = getEntityStream(request, parameter); if (ObjectUtils.notNull(stream)) { fillParamList(stream, parameter); } else { addNullParam(parameter); } } return paramsList; } /** * Builder class to configure and initialize {@link ParamBuilder} instance * * @author Levan * */ public static final class Builder { private ParamBuilder target; public Builder() { target = new ParamBuilder(); } /** * Adds {@link MediaType} necessary parameter * * @param mediaType * @return {@link Builder} */ public ParamBuilder.Builder setMediaType(MediaType mediaType) { target.mediaType = mediaType; return this; } /** * Adds {@link List}<Parameter> necessary parameter * * @param parameters * @return {@link Builder} */ public ParamBuilder.Builder setParameters(List<Parameter> parameters) { target.parameters = parameters; return this; } /** * Adds {@link MessageBodyWorkers} necessary parameter * * @param workers * @return {@link Builder} */ public ParamBuilder.Builder setWorkers(MessageBodyWorkers workers) { target.workers = workers; return this; } /** * Adds {@link ContainerRequestContext} necessary parameter * * @param request * @return {@link Builder} */ public ParamBuilder.Builder setRequest(ContainerRequestContext request) { target.request = request; return this; } public ParamBuilder build() throws IOException { // TODO Check if there is a another way to create ParamBuilder // instance or // checks all parameters not to be null target.checkOnBuild(); return target; } } }
src/main/java/org/lightmare/rest/providers/ParamBuilder.java
package org.lightmare.rest.providers; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.MessageBodyReader; import org.glassfish.jersey.internal.util.collection.MultivaluedStringMap; import org.glassfish.jersey.message.MessageBodyWorkers; import org.glassfish.jersey.server.model.Parameter; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.reflect.MetaUtils; import org.lightmare.utils.rest.RequestUtils; /** * Translates REST request parameters to java objects * * @author levan * @since 0.0.75-SNAPSHOT */ public class ParamBuilder { private MediaType mediaType; private List<Parameter> parameters; private MessageBodyWorkers workers; private ContainerRequestContext request; private MultivaluedMap<String, String> httpHeaders; private MultivaluedMap<String, String> uriParams; private MessageBodyReader<?> reader; private boolean check; private List<Object> paramsList; // Default length of parameters list (used for MultivaluedMap) private static final int PARAM_VALIES_LENGTH = 1; private ParamBuilder() { } public ParamBuilder(MediaType mediaType, List<Parameter> parameters, MessageBodyWorkers workers, ContainerRequestContext request) { this.mediaType = mediaType; this.parameters = parameters; this.workers = workers; this.request = request; } /** * Creates error message if one of the necessary fields in null * * @return String * @throws IOException */ private String errorOnBuild() throws IOException { String errorMessage; String errorPrefix = "Could not initialize "; String errorClass = this.getClass().getName(); String errorReasonPrefix = " caouse"; String errorReasonSuffix = "is null"; String errorMessageBody; if (mediaType == null) { errorMessageBody = "mediaType"; } else if (parameters == null) { errorMessageBody = "parameters"; } else if (workers == null) { errorMessageBody = "workers"; } else if (request == null) { errorMessageBody = "request"; } else { throw new IOException("Could not find null value"); } errorMessage = new StringBuilder().append(errorPrefix) .append(errorClass).append(errorReasonPrefix) .append(errorMessageBody).append(errorReasonSuffix).toString(); return errorMessage; } /** * Check if one of the necessary fields in null and if it is throws * {@link IOException} with generated error message * * @return <code>boolean</code> * @throws IOException */ private boolean checkOnBuild() throws IOException { boolean valid = ObjectUtils.notNullAll(mediaType, parameters, workers, request); if (ObjectUtils.notTrue(valid)) { String errorMessage = errorOnBuild(); throw new IOException(errorMessage); } return valid; } private boolean check() throws IOException { return ObjectUtils.notTrue(request.hasEntity()) && IOUtils.notAvailable(request.getEntityStream()); } private void copyAll(MultivaluedMap<String, String> from, MultivaluedMap<String, String> to) { for (Map.Entry<String, List<String>> entry : from.entrySet()) { to.addAll(entry.getKey(), entry.getValue()); } } private void addAll(MultivaluedMap<String, String> from, MultivaluedMap<String, String> to) { if (CollectionUtils.valid(from)) { copyAll(from, to); } } /** * Extracts all parameters from {@link ContainerRequestContext} object * * @param request * @return {@link MultivaluedMap}<String, String> */ private MultivaluedMap<String, String> extractParameters( ContainerRequestContext request) { MultivaluedMap<String, String> params = new MultivaluedStringMap(); MultivaluedMap<String, String> exts; boolean decode = Boolean.TRUE; UriInfo uriInfo = request.getUriInfo(); exts = request.getHeaders(); addAll(exts, params); exts = uriInfo.getPathParameters(decode); addAll(exts, params); exts = uriInfo.getQueryParameters(decode); addAll(exts, params); Map<String, Cookie> cookies = request.getCookies(); if (CollectionUtils.valid(cookies)) { for (Map.Entry<String, Cookie> entry : cookies.entrySet()) { params.putSingle(entry.getKey(), entry.getValue().toString()); } } return params; } /** * Converts {@link Parameter} to {@link InputStream} or {@link List} of * {@link InputStream} by {@link Parameter} nature * * @param parameter * @return {@link Object} */ private Object getEntityStream(Parameter parameter) { Object stream; List<String> paramValues = uriParams.get(parameter.getSourceName()); String value; if (CollectionUtils.valid(paramValues)) { if (paramValues.size() == PARAM_VALIES_LENGTH) { value = CollectionUtils.getFirst(paramValues); stream = RequestUtils.textToStream(value); } else { stream = RequestUtils.textsToStreams(paramValues); } } else { stream = null; } return stream; } /** * Reads {@link InputStream} from passed {@link ContainerRequestContext} for * associated {@link Parameter} instance * * @param request * @param parameter * @return {@link Object} */ private Object getEntityStream(ContainerRequestContext request, Parameter parameter) { Object entityStream; if (check) { entityStream = getEntityStream(parameter); } else { entityStream = request.getEntityStream(); } return entityStream; } private boolean available(InputStream entityStream, Parameter parameter) { return ObjectUtils.notNullAll(reader, entityStream) && reader.isReadable(parameter.getRawType(), parameter.getType(), parameter.getAnnotations(), mediaType); } private void close(InputStream entityStream) throws IOException { if (check) { IOUtils.close(entityStream); } } /** * Extracts parameter from passed {@link InputStream} (writes appropriate * value to {@link Object} instance) * * @param parameter * @param entityStream * @return {@link Object} * @throws IOException */ @SuppressWarnings({ "unchecked", "rawtypes" }) private Object extractParam(Parameter parameter, InputStream entityStream) throws IOException { Object param; try { param = reader.readFrom((Class) parameter.getRawType(), parameter.getType(), parameter.getAnnotations(), mediaType, httpHeaders, entityStream); } finally { close(entityStream); } return param; } private void addParam(Object param) { if (ObjectUtils.notNull(param)) { paramsList.add(param); } } /** * Initializes and adds null parameter to {@link List} of parameters * * @param parameter */ private void addNullParam(Parameter parameter) { Class<?> paramType = parameter.getRawType(); Object nullParam; if (paramType.isPrimitive()) { nullParam = MetaUtils.getDefault(paramType); } else { nullParam = null; } paramsList.add(nullParam); } /** * Reads from {@link InputStream} to java {@link Object} instance * * @param entityStream * @param parameter * @throws IOException */ private void readFromStream(InputStream entityStream, Parameter parameter) throws IOException { boolean valid = available(entityStream, parameter); if (valid) { Object param = extractParam(parameter, entityStream); addParam(param); } } /** * Reads from {@link InputStream} or {@link List} of {@link InputStream} in * case that parameters are multi valued * * @param stream * @param parameter * @throws IOException */ private void fillParamList(Object stream, Parameter parameter) throws IOException { InputStream entityStream; if (stream instanceof InputStream) { entityStream = (InputStream) stream; readFromStream(entityStream, parameter); } else if (stream instanceof List) { List<InputStream> streamsList = ObjectUtils.cast(stream); Iterator<InputStream> streams = streamsList.iterator(); while (streams.hasNext()) { entityStream = streams.next(); readFromStream(entityStream, parameter); } } } /** * Extracts parameters from {@link ContainerRequestContext} instance * * @return {@link List}<Object> * @throws IOException */ public List<Object> extractParams() throws IOException { paramsList = new ArrayList<Object>(); check = check(); httpHeaders = request.getHeaders(); uriParams = extractParameters(request); Object stream; for (Parameter parameter : parameters) { reader = RequestUtils.getReader(workers, parameter, mediaType); stream = getEntityStream(request, parameter); if (ObjectUtils.notNull(stream)) { fillParamList(stream, parameter); } else { addNullParam(parameter); } } return paramsList; } /** * Builder class to configure and initialize {@link ParamBuilder} instance * * @author Levan * */ public static final class Builder { private ParamBuilder target; public Builder() { target = new ParamBuilder(); } /** * Adds {@link MediaType} necessary parameter * * @param mediaType * @return {@link Builder} */ public ParamBuilder.Builder setMediaType(MediaType mediaType) { target.mediaType = mediaType; return this; } /** * Adds {@link List}<Parameter> necessary parameter * * @param parameters * @return {@link Builder} */ public ParamBuilder.Builder setParameters(List<Parameter> parameters) { target.parameters = parameters; return this; } /** * Adds {@link MessageBodyWorkers} necessary parameter * * @param workers * @return {@link Builder} */ public ParamBuilder.Builder setWorkers(MessageBodyWorkers workers) { target.workers = workers; return this; } /** * Adds {@link ContainerRequestContext} necessary parameter * * @param request * @return {@link Builder} */ public ParamBuilder.Builder setRequest(ContainerRequestContext request) { target.request = request; return this; } public ParamBuilder build() throws IOException { // TODO Check if there is a another way to create ParamBuilder // instance or // checks all parameters not to be null target.checkOnBuild(); return target; } } }
improved / commented code utiliti classes
src/main/java/org/lightmare/rest/providers/ParamBuilder.java
improved / commented code utiliti classes
Java
unlicense
98759407c33a90b4880c96c86a2ab238277afe0e
0
vpadegaonkar/VinayMaven
package com.example.javamavenjunithelloworld; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.StandardOutputStreamLog; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.io.File; /** * Integration test for the HelloApp program. * <p/> * An integration test verifies the workings of a complete program, a module, or a set of dependant classes. * <p/> * This integration test uses system-rules, an extension for JUnit that lets you test System.out and System.exit() * etc.: * <p/> * http://www.stefan-birkner.de/system-rules */ public class HelloWithTestsIT { @Rule public final StandardOutputStreamLog out = new StandardOutputStreamLog(); @Test public void doesItSayHelloTest() { String[] args = {"1"}; HelloApp.main(args); assertThat(out.getLog(), is(equalTo(Hello.HELLO + "\n"))); } @Test public void doesItSayHelloTest3() { String[] args = {"4"}; HelloApp.main(args); String thrice = Hello.HELLO + "\n" + Hello.HELLO + "\n" + Hello.HELLO + "\n" + Hello.HELLO + "\n"; //File file = new File("C:\\Selenium\\IEDriverServer_x64_2.53.1\\geckodriver.exe"); //System.setProperty("webdriver.gecko.driver", file.getAbsolutePath()); WebDriver driver = new FirefoxDriver(); driver.get("http://www.guru99.com/selenium-tutorial.html"); assertThat(out.getLog(), is(equalTo(thrice))); } }
src/test/java/com/example/javamavenjunithelloworld/HelloWithTestsIT.java
package com.example.javamavenjunithelloworld; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.StandardOutputStreamLog; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.io.File; /** * Integration test for the HelloApp program. * <p/> * An integration test verifies the workings of a complete program, a module, or a set of dependant classes. * <p/> * This integration test uses system-rules, an extension for JUnit that lets you test System.out and System.exit() * etc.: * <p/> * http://www.stefan-birkner.de/system-rules */ public class HelloWithTestsIT { @Rule public final StandardOutputStreamLog out = new StandardOutputStreamLog(); @Test public void doesItSayHelloTest() { String[] args = {"1"}; HelloApp.main(args); assertThat(out.getLog(), is(equalTo(Hello.HELLO + "\n"))); } @Test public void doesItSayHelloTest3() { String[] args = {"4"}; HelloApp.main(args); String thrice = Hello.HELLO + "\n" + Hello.HELLO + "\n" + Hello.HELLO + "\n" + Hello.HELLO + "\n"; File file = new File("C:\\Selenium\\IEDriverServer_x64_2.53.1\\geckodriver.exe"); System.setProperty("webdriver.gecko.driver", file.getAbsolutePath()); WebDriver driver = new FirefoxDriver(); driver.get("http://www.guru99.com/selenium-tutorial.html"); assertThat(out.getLog(), is(equalTo(thrice))); } }
Installed Firefox on Jenkins to see error
src/test/java/com/example/javamavenjunithelloworld/HelloWithTestsIT.java
Installed Firefox on Jenkins to see error
Java
unlicense
1749a48ca7259425988a896c1e39219c9fd32d90
0
svenkaestle/PrApp
package de.svenkaestle.prapp; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; public class AddDrugsActivity extends AppCompatActivity { EditText medicationAmount; Button decreaseMedicationAmount; Button increaseMedicationAmount; String medicationAmountOldValue; String medicationAmountNewValue; Integer newValue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_drugs); medicationAmount = (EditText) findViewById(R.id.medicationNumberEditView); medicationAmount.setText("0"); decreaseMedicationAmount = (Button) findViewById(R.id.decreaseMedicationNumberButton); increaseMedicationAmount = (Button) findViewById(R.id.increaseMedicationNumberButton); decreaseMedicationAmount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { medicationAmountOldValue = medicationAmount.getText().toString(); newValue = Integer.valueOf(medicationAmountOldValue) - 1; if (newValue <= 0) { newValue = 0; } medicationAmountNewValue = newValue.toString(); medicationAmount.setText(medicationAmountNewValue); } }); increaseMedicationAmount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { medicationAmountOldValue = medicationAmount.getText().toString(); newValue = Integer.valueOf(medicationAmountOldValue) + 1; medicationAmountNewValue = newValue.toString(); medicationAmount.setText(medicationAmountNewValue); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.top_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_links: startActivity(new Intent(getApplicationContext(), LinksActivity.class)); return true; case R.id.menu_contact: startActivity(new Intent(getApplicationContext(), ContactActivity.class)); return true; default: finish(); return true; } } }
app/src/main/java/de/svenkaestle/prapp/AddDrugsActivity.java
package de.svenkaestle.prapp; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; public class AddDrugsActivity extends AppCompatActivity { EditText medicationAmount; Button decreaseMedicationAmount; Button increaseMedicationAmount; String medicationAmountOldValue; String medicationAmountNewValue; Integer newValue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_drugs); medicationAmount = (EditText) findViewById(R.id.medicationNumberEditView); medicationAmount.setText("0"); decreaseMedicationAmount = (Button) findViewById(R.id.decreaseMedicationNumberButton); increaseMedicationAmount = (Button) findViewById(R.id.increaseMedicationNumberButton); decreaseMedicationAmount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { medicationAmountOldValue = medicationAmount.getText().toString(); newValue = Integer.valueOf(medicationAmountOldValue) - 1; if (newValue <= 0) { newValue = 0; } medicationAmountNewValue = newValue.toString(); medicationAmount.setText(medicationAmountNewValue); } }); increaseMedicationAmount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { medicationAmountOldValue = medicationAmount.getText().toString(); newValue = Integer.valueOf(medicationAmountOldValue) + 1; medicationAmountNewValue = newValue.toString(); medicationAmount.setText(medicationAmountNewValue); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.top_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_links: startActivity(new Intent(getApplicationContext(), LinksActivity.class)); this.finish(); return true; case R.id.menu_contact: startActivity(new Intent(getApplicationContext(), ContactActivity.class)); this.finish(); return true; default: finish(); return true; } } }
delete finish in menu
app/src/main/java/de/svenkaestle/prapp/AddDrugsActivity.java
delete finish in menu
Java
apache-2.0
46a5a8926eafb3bf30e7ff997a3801fc68b75ada
0
Nanoware/Terasology,MovingBlocks/Terasology,Malanius/Terasology,Nanoware/Terasology,Malanius/Terasology,MovingBlocks/Terasology,Nanoware/Terasology,MovingBlocks/Terasology
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.world.propagation.light; import org.terasology.math.Side; import org.terasology.math.geom.Vector3i; import org.terasology.world.block.Block; import org.terasology.world.chunks.ChunkConstants; import org.terasology.world.chunks.LitChunk; /** * Rules for how standard light should propagate. * Also provides implementation for setting and getting values */ public class LightPropagationRules extends CommonLightPropagationRules { /** * Any luminance from the block is a constant * <p> * {@inheritDoc} */ @Override public byte getFixedValue(Block block, Vector3i pos) { return block.getLuminance(); } /** * When the light propagates it's light level reduces by one * <p> * {@inheritDoc} */ @Override public byte propagateValue(byte existingValue, Side side, Block from) { return (byte) (existingValue - 1); } /** * The maximum light level is a full byte of 15 * <p> * {@inheritDoc} */ @Override public byte getMaxValue() { return ChunkConstants.MAX_LIGHT; // 15 } @Override public byte getValue(LitChunk chunk, Vector3i pos) { return getValue(chunk, pos.x, pos.y, pos.z); } @Override public byte getValue(LitChunk chunk, int x, int y, int z) { return chunk.getLight(x, y, z); } @Override public void setValue(LitChunk chunk, Vector3i pos, byte value) { chunk.setLight(pos, value); } }
engine/src/main/java/org/terasology/world/propagation/light/LightPropagationRules.java
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.world.propagation.light; import org.terasology.math.Side; import org.terasology.math.geom.Vector3i; import org.terasology.world.block.Block; import org.terasology.world.chunks.LitChunk; /** * Rules for how standard light should propagate. * Also provides implementation for setting and getting values */ public class LightPropagationRules extends CommonLightPropagationRules { /** * Any luminance from the block is a constant * <p> * {@inheritDoc} */ @Override public byte getFixedValue(Block block, Vector3i pos) { return block.getLuminance(); } /** * When the light propagates it's light level reduces by one * <p> * {@inheritDoc} */ @Override public byte propagateValue(byte existingValue, Side side, Block from) { return (byte) (existingValue - 1); } /** * The maximum light level is a full byte of 15 * <p> * {@inheritDoc} */ @Override public byte getMaxValue() { return 0xF; // 15 } @Override public byte getValue(LitChunk chunk, Vector3i pos) { return getValue(chunk, pos.x, pos.y, pos.z); } @Override public byte getValue(LitChunk chunk, int x, int y, int z) { return chunk.getLight(x, y, z); } @Override public void setValue(LitChunk chunk, Vector3i pos, byte value) { chunk.setLight(pos, value); } }
Tweak light propgation rules to use the chunk constants
engine/src/main/java/org/terasology/world/propagation/light/LightPropagationRules.java
Tweak light propgation rules to use the chunk constants
Java
apache-2.0
d318ca174154f54dcdaf8b6d097221e267a1810f
0
ndimiduk/hbase,francisliu/hbase,Apache9/hbase,apurtell/hbase,Apache9/hbase,mahak/hbase,ndimiduk/hbase,francisliu/hbase,ndimiduk/hbase,francisliu/hbase,francisliu/hbase,apurtell/hbase,apurtell/hbase,mahak/hbase,mahak/hbase,ndimiduk/hbase,francisliu/hbase,apurtell/hbase,Apache9/hbase,francisliu/hbase,Apache9/hbase,mahak/hbase,apurtell/hbase,francisliu/hbase,Apache9/hbase,mahak/hbase,francisliu/hbase,mahak/hbase,apurtell/hbase,mahak/hbase,apurtell/hbase,ndimiduk/hbase,francisliu/hbase,Apache9/hbase,ndimiduk/hbase,francisliu/hbase,Apache9/hbase,ndimiduk/hbase,mahak/hbase,apurtell/hbase,mahak/hbase,apurtell/hbase,mahak/hbase,ndimiduk/hbase,Apache9/hbase,ndimiduk/hbase,Apache9/hbase,ndimiduk/hbase,apurtell/hbase,Apache9/hbase
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.master.HMaster; import org.apache.hadoop.hbase.master.RegionState; import org.apache.hadoop.hbase.master.ServerManager; import org.apache.hadoop.hbase.master.assignment.AssignmentManager; import org.apache.hadoop.hbase.master.assignment.RegionStates; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.regionserver.Region; import org.apache.hadoop.hbase.testclassification.ClientTests; import org.apache.hadoop.hbase.testclassification.LargeTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.JVMClusterUtil; import org.apache.hadoop.hbase.util.Threads; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * Class to test asynchronous region admin operations. * @see TestAsyncRegionAdminApi2 This test and it used to be joined it was taking longer than our * ten minute timeout so they were split. */ @RunWith(Parameterized.class) @Category({ LargeTests.class, ClientTests.class }) public class TestAsyncRegionAdminApi extends TestAsyncAdminBase { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestAsyncRegionAdminApi.class); @Test public void testAssignRegionAndUnassignRegion() throws Exception { createTableWithDefaultConf(tableName); // assign region. HMaster master = TEST_UTIL.getHBaseCluster().getMaster(); AssignmentManager am = master.getAssignmentManager(); RegionInfo hri = am.getRegionStates().getRegionsOfTable(tableName).get(0); // assert region on server RegionStates regionStates = am.getRegionStates(); ServerName serverName = regionStates.getRegionServerOfRegion(hri); TEST_UTIL.assertRegionOnServer(hri, serverName, 200); assertTrue(regionStates.getRegionState(hri).isOpened()); // Region is assigned now. Let's assign it again. // Master should not abort, and region should stay assigned. try { admin.assign(hri.getRegionName()).get(); fail("Should fail when assigning an already onlined region"); } catch (ExecutionException e) { // Expected assertThat(e.getCause(), instanceOf(DoNotRetryRegionException.class)); } assertFalse(am.getRegionStates().getRegionStateNode(hri).isInTransition()); assertTrue(regionStates.getRegionState(hri).isOpened()); // unassign region admin.unassign(hri.getRegionName(), true).get(); assertFalse(am.getRegionStates().getRegionStateNode(hri).isInTransition()); assertTrue(regionStates.getRegionState(hri).isClosed()); } RegionInfo createTableAndGetOneRegion(final TableName tableName) throws IOException, InterruptedException, ExecutionException { TableDescriptor desc = TableDescriptorBuilder.newBuilder(tableName) .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILY)).build(); admin.createTable(desc, Bytes.toBytes("A"), Bytes.toBytes("Z"), 5).get(); // wait till the table is assigned HMaster master = TEST_UTIL.getHBaseCluster().getMaster(); long timeoutTime = System.currentTimeMillis() + 3000; while (true) { List<RegionInfo> regions = master.getAssignmentManager().getRegionStates().getRegionsOfTable(tableName); if (regions.size() > 3) { return regions.get(2); } long now = System.currentTimeMillis(); if (now > timeoutTime) { fail("Could not find an online region"); } Thread.sleep(10); } } @Test public void testGetRegionByStateOfTable() throws Exception { RegionInfo hri = createTableAndGetOneRegion(tableName); RegionStates regionStates = TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().getRegionStates(); assertTrue(regionStates.getRegionByStateOfTable(tableName).get(RegionState.State.OPEN) .stream().anyMatch(r -> RegionInfo.COMPARATOR.compare(r, hri) == 0)); assertFalse(regionStates.getRegionByStateOfTable(TableName.valueOf("I_am_the_phantom")) .get(RegionState.State.OPEN).stream().anyMatch(r -> RegionInfo.COMPARATOR.compare(r, hri) == 0)); } @Test public void testMoveRegion() throws Exception { admin.balancerSwitch(false).join(); RegionInfo hri = createTableAndGetOneRegion(tableName); RawAsyncHBaseAdmin rawAdmin = (RawAsyncHBaseAdmin) ASYNC_CONN.getAdmin(); ServerName serverName = rawAdmin.getRegionLocation(hri.getRegionName()).get().getServerName(); HMaster master = TEST_UTIL.getHBaseCluster().getMaster(); ServerManager serverManager = master.getServerManager(); ServerName destServerName = null; List<JVMClusterUtil.RegionServerThread> regionServers = TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads(); for (JVMClusterUtil.RegionServerThread regionServer : regionServers) { HRegionServer destServer = regionServer.getRegionServer(); destServerName = destServer.getServerName(); if (!destServerName.equals(serverName) && serverManager.isServerOnline(destServerName)) { break; } } assertTrue(destServerName != null && !destServerName.equals(serverName)); admin.move(hri.getRegionName(), destServerName).get(); long timeoutTime = System.currentTimeMillis() + 30000; while (true) { ServerName sn = rawAdmin.getRegionLocation(hri.getRegionName()).get().getServerName(); if (sn != null && sn.equals(destServerName)) { break; } long now = System.currentTimeMillis(); if (now > timeoutTime) { fail("Failed to move the region in time: " + hri); } Thread.sleep(100); } admin.balancerSwitch(true).join(); } @Test public void testGetOnlineRegions() throws Exception { createTableAndGetOneRegion(tableName); AtomicInteger regionServerCount = new AtomicInteger(0); TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads().stream() .map(rsThread -> rsThread.getRegionServer()).forEach(rs -> { ServerName serverName = rs.getServerName(); try { assertEquals(admin.getRegions(serverName).get().size(), rs.getRegions().size()); } catch (Exception e) { fail("admin.getOnlineRegions() method throws a exception: " + e.getMessage()); } regionServerCount.incrementAndGet(); }); assertEquals(TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads().size(), regionServerCount.get()); } @Test public void testFlushTableAndRegion() throws Exception { RegionInfo hri = createTableAndGetOneRegion(tableName); ServerName serverName = TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(hri); HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads().stream() .map(rsThread -> rsThread.getRegionServer()) .filter(rs -> rs.getServerName().equals(serverName)).findFirst().get(); // write a put into the specific region ASYNC_CONN.getTable(tableName) .put(new Put(hri.getStartKey()).addColumn(FAMILY, FAMILY_0, Bytes.toBytes("value-1"))) .join(); assertTrue(regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize() > 0); // flush region and wait flush operation finished. LOG.info("flushing region: " + Bytes.toStringBinary(hri.getRegionName())); admin.flushRegion(hri.getRegionName()).get(); LOG.info("blocking until flush is complete: " + Bytes.toStringBinary(hri.getRegionName())); Threads.sleepWithoutInterrupt(500); while (regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize() > 0) { Threads.sleep(50); } // check the memstore. assertEquals(regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize(), 0); // write another put into the specific region ASYNC_CONN.getTable(tableName) .put(new Put(hri.getStartKey()).addColumn(FAMILY, FAMILY_0, Bytes.toBytes("value-2"))) .join(); assertTrue(regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize() > 0); admin.flush(tableName).get(); Threads.sleepWithoutInterrupt(500); while (regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize() > 0) { Threads.sleep(50); } // check the memstore. assertEquals(regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize(), 0); } private void waitUntilMobCompactionFinished(TableName tableName) throws ExecutionException, InterruptedException { long finished = EnvironmentEdgeManager.currentTime() + 60000; CompactionState state = admin.getCompactionState(tableName, CompactType.MOB).get(); while (EnvironmentEdgeManager.currentTime() < finished) { if (state == CompactionState.NONE) { break; } Thread.sleep(10); state = admin.getCompactionState(tableName, CompactType.MOB).get(); } assertEquals(CompactionState.NONE, state); } @Test public void testCompactMob() throws Exception { ColumnFamilyDescriptor columnDescriptor = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("mob")) .setMobEnabled(true).setMobThreshold(0).build(); TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName) .setColumnFamily(columnDescriptor).build(); admin.createTable(tableDescriptor).get(); byte[][] families = { Bytes.toBytes("mob") }; loadData(tableName, families, 3000, 8); admin.majorCompact(tableName).get(); CompactionState state = admin.getCompactionState(tableName).get(); assertNotEquals(CompactionState.NONE, state); waitUntilMobCompactionFinished(tableName); } @Test public void testCompactRegionServer() throws Exception { byte[][] families = { Bytes.toBytes("f1"), Bytes.toBytes("f2"), Bytes.toBytes("f3") }; createTableWithDefaultConf(tableName, null, families); loadData(tableName, families, 3000, 8); List<HRegionServer> rsList = TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads().stream() .map(rsThread -> rsThread.getRegionServer()).collect(Collectors.toList()); List<Region> regions = new ArrayList<>(); rsList.forEach(rs -> regions.addAll(rs.getRegions(tableName))); assertEquals(1, regions.size()); int countBefore = countStoreFilesInFamilies(regions, families); assertTrue(countBefore > 0); // Minor compaction for all region servers. for (HRegionServer rs : rsList) admin.compactRegionServer(rs.getServerName()).get(); Thread.sleep(5000); int countAfterMinorCompaction = countStoreFilesInFamilies(regions, families); assertTrue(countAfterMinorCompaction < countBefore); // Major compaction for all region servers. for (HRegionServer rs : rsList) admin.majorCompactRegionServer(rs.getServerName()).get(); Thread.sleep(5000); int countAfterMajorCompaction = countStoreFilesInFamilies(regions, families); assertEquals(3, countAfterMajorCompaction); } @Test public void testCompactionSwitchStates() throws Exception { // Create a table with regions byte[] family = Bytes.toBytes("family"); byte[][] families = {family, Bytes.add(family, Bytes.toBytes("2")), Bytes.add(family, Bytes.toBytes("3"))}; createTableWithDefaultConf(tableName, null, families); loadData(tableName, families, 3000, 8); List<Region> regions = new ArrayList<>(); TEST_UTIL .getHBaseCluster() .getLiveRegionServerThreads() .forEach(rsThread -> regions.addAll(rsThread.getRegionServer().getRegions(tableName))); CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture = admin.compactionSwitch(true, new ArrayList<>()); Map<ServerName, Boolean> pairs = listCompletableFuture.get(); for (Map.Entry<ServerName, Boolean> p : pairs.entrySet()) { assertEquals("Default compaction state, expected=enabled actual=disabled", true, p.getValue()); } CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture1 = admin.compactionSwitch(false, new ArrayList<>()); Map<ServerName, Boolean> pairs1 = listCompletableFuture1.get(); for (Map.Entry<ServerName, Boolean> p : pairs1.entrySet()) { assertEquals("Last compaction state, expected=enabled actual=disabled", true, p.getValue()); } CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture2 = admin.compactionSwitch(true, new ArrayList<>()); Map<ServerName, Boolean> pairs2 = listCompletableFuture2.get(); for (Map.Entry<ServerName, Boolean> p : pairs2.entrySet()) { assertEquals("Last compaction state, expected=disabled actual=enabled", false, p.getValue()); } ServerName serverName = TEST_UTIL.getHBaseCluster().getRegionServer(0) .getServerName(); List<String> serverNameList = new ArrayList<String>(); serverNameList.add(serverName.getServerName()); CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture3 = admin.compactionSwitch(false, serverNameList); Map<ServerName, Boolean> pairs3 = listCompletableFuture3.get(); assertEquals(pairs3.entrySet().size(), 1); for (Map.Entry<ServerName, Boolean> p : pairs3.entrySet()) { assertEquals("Last compaction state, expected=enabled actual=disabled", true, p.getValue()); } CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture4 = admin.compactionSwitch(true, serverNameList); Map<ServerName, Boolean> pairs4 = listCompletableFuture4.get(); assertEquals(pairs4.entrySet().size(), 1); for (Map.Entry<ServerName, Boolean> p : pairs4.entrySet()) { assertEquals("Last compaction state, expected=disabled actual=enabled", false, p.getValue()); } } @Test public void testCompact() throws Exception { compactionTest(TableName.valueOf("testCompact1"), 8, CompactionState.MAJOR, false); compactionTest(TableName.valueOf("testCompact2"), 15, CompactionState.MINOR, false); compactionTest(TableName.valueOf("testCompact3"), 8, CompactionState.MAJOR, true); compactionTest(TableName.valueOf("testCompact4"), 15, CompactionState.MINOR, true); } private void compactionTest(final TableName tableName, final int flushes, final CompactionState expectedState, boolean singleFamily) throws Exception { // Create a table with regions byte[] family = Bytes.toBytes("family"); byte[][] families = { family, Bytes.add(family, Bytes.toBytes("2")), Bytes.add(family, Bytes.toBytes("3")) }; createTableWithDefaultConf(tableName, null, families); byte[][] singleFamilyArray = { family }; // When singleFamily is true, only load data for the family being tested. This is to avoid // the case that while major compaction is going on for the family, minor compaction could // happen for other families at the same time (Two compaction threads long/short), thus // pollute the compaction and store file numbers for the region. if (singleFamily) { loadData(tableName, singleFamilyArray, 3000, flushes); } else { loadData(tableName, families, 3000, flushes); } List<Region> regions = new ArrayList<>(); TEST_UTIL .getHBaseCluster() .getLiveRegionServerThreads() .forEach(rsThread -> regions.addAll(rsThread.getRegionServer().getRegions(tableName))); assertEquals(1, regions.size()); int countBefore = countStoreFilesInFamilies(regions, families); int countBeforeSingleFamily = countStoreFilesInFamily(regions, family); assertTrue(countBefore > 0); // there should be some data files if (expectedState == CompactionState.MINOR) { if (singleFamily) { admin.compact(tableName, family).get(); } else { admin.compact(tableName).get(); } } else { if (singleFamily) { admin.majorCompact(tableName, family).get(); } else { admin.majorCompact(tableName).get(); } } long curt = System.currentTimeMillis(); long waitTime = 5000; long endt = curt + waitTime; CompactionState state = admin.getCompactionState(tableName).get(); while (state == CompactionState.NONE && curt < endt) { Thread.sleep(10); state = admin.getCompactionState(tableName).get(); curt = System.currentTimeMillis(); } // Now, should have the right compaction state, // otherwise, the compaction should have already been done if (expectedState != state) { for (Region region : regions) { state = CompactionState.valueOf(region.getCompactionState().toString()); assertEquals(CompactionState.NONE, state); } } else { // Wait until the compaction is done state = admin.getCompactionState(tableName).get(); while (state != CompactionState.NONE && curt < endt) { Thread.sleep(10); state = admin.getCompactionState(tableName).get(); } // Now, compaction should be done. assertEquals(CompactionState.NONE, state); } int countAfter = countStoreFilesInFamilies(regions, families); int countAfterSingleFamily = countStoreFilesInFamily(regions, family); assertTrue(countAfter < countBefore); if (!singleFamily) { if (expectedState == CompactionState.MAJOR) { assertEquals(families.length, countAfter); } else { assertTrue(families.length <= countAfter); } } else { int singleFamDiff = countBeforeSingleFamily - countAfterSingleFamily; // assert only change was to single column family assertEquals(singleFamDiff, (countBefore - countAfter)); if (expectedState == CompactionState.MAJOR) { assertEquals(1, countAfterSingleFamily); } else { assertTrue("" + countAfterSingleFamily, 1 <= countAfterSingleFamily); } } } @Test public void testNonExistentTableCompaction() { testNonExistentTableCompaction(CompactionState.MINOR); testNonExistentTableCompaction(CompactionState.MAJOR); } private void testNonExistentTableCompaction(CompactionState compactionState) { try { if (compactionState == CompactionState.MINOR) { admin.compact(TableName.valueOf("NonExistentTable")).get(); } else { admin.majorCompact(TableName.valueOf("NonExistentTable")).get(); } fail("Expected TableNotFoundException when table doesn't exist"); } catch (Exception e) { // expected. assertTrue(e.getCause() instanceof TableNotFoundException); } } private static int countStoreFilesInFamily(List<Region> regions, final byte[] family) { return countStoreFilesInFamilies(regions, new byte[][] { family }); } private static int countStoreFilesInFamilies(List<Region> regions, final byte[][] families) { int count = 0; for (Region region : regions) { count += region.getStoreFileList(families).size(); } return count; } static void loadData(final TableName tableName, final byte[][] families, final int rows) throws IOException { loadData(tableName, families, rows, 1); } static void loadData(final TableName tableName, final byte[][] families, final int rows, final int flushes) throws IOException { AsyncTable<?> table = ASYNC_CONN.getTable(tableName); List<Put> puts = new ArrayList<>(rows); byte[] qualifier = Bytes.toBytes("val"); for (int i = 0; i < flushes; i++) { for (int k = 0; k < rows; k++) { byte[] row = Bytes.add(Bytes.toBytes(k), Bytes.toBytes(i)); Put p = new Put(row); for (int j = 0; j < families.length; ++j) { p.addColumn(families[j], qualifier, row); } puts.add(p); } table.putAll(puts).join(); TEST_UTIL.flush(); puts.clear(); } } }
hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAsyncRegionAdminApi.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.master.HMaster; import org.apache.hadoop.hbase.master.RegionState; import org.apache.hadoop.hbase.master.ServerManager; import org.apache.hadoop.hbase.master.assignment.AssignmentManager; import org.apache.hadoop.hbase.master.assignment.RegionStates; import org.apache.hadoop.hbase.regionserver.HRegionServer; import org.apache.hadoop.hbase.regionserver.Region; import org.apache.hadoop.hbase.testclassification.ClientTests; import org.apache.hadoop.hbase.testclassification.LargeTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.JVMClusterUtil; import org.apache.hadoop.hbase.util.Threads; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * Class to test asynchronous region admin operations. * @see TestAsyncRegionAdminApi2 This test and it used to be joined it was taking longer than our * ten minute timeout so they were split. */ @RunWith(Parameterized.class) @Category({ LargeTests.class, ClientTests.class }) public class TestAsyncRegionAdminApi extends TestAsyncAdminBase { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestAsyncRegionAdminApi.class); @Test public void testAssignRegionAndUnassignRegion() throws Exception { createTableWithDefaultConf(tableName); // assign region. HMaster master = TEST_UTIL.getHBaseCluster().getMaster(); AssignmentManager am = master.getAssignmentManager(); RegionInfo hri = am.getRegionStates().getRegionsOfTable(tableName).get(0); // assert region on server RegionStates regionStates = am.getRegionStates(); ServerName serverName = regionStates.getRegionServerOfRegion(hri); TEST_UTIL.assertRegionOnServer(hri, serverName, 200); assertTrue(regionStates.getRegionState(hri).isOpened()); // Region is assigned now. Let's assign it again. // Master should not abort, and region should stay assigned. try { admin.assign(hri.getRegionName()).get(); fail("Should fail when assigning an already onlined region"); } catch (ExecutionException e) { // Expected assertThat(e.getCause(), instanceOf(DoNotRetryRegionException.class)); } assertFalse(am.getRegionStates().getRegionStateNode(hri).isInTransition()); assertTrue(regionStates.getRegionState(hri).isOpened()); // unassign region admin.unassign(hri.getRegionName(), true).get(); assertFalse(am.getRegionStates().getRegionStateNode(hri).isInTransition()); assertTrue(regionStates.getRegionState(hri).isClosed()); } RegionInfo createTableAndGetOneRegion(final TableName tableName) throws IOException, InterruptedException, ExecutionException { TableDescriptor desc = TableDescriptorBuilder.newBuilder(tableName) .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILY)).build(); admin.createTable(desc, Bytes.toBytes("A"), Bytes.toBytes("Z"), 5).get(); // wait till the table is assigned HMaster master = TEST_UTIL.getHBaseCluster().getMaster(); long timeoutTime = System.currentTimeMillis() + 3000; while (true) { List<RegionInfo> regions = master.getAssignmentManager().getRegionStates().getRegionsOfTable(tableName); if (regions.size() > 3) { return regions.get(2); } long now = System.currentTimeMillis(); if (now > timeoutTime) { fail("Could not find an online region"); } Thread.sleep(10); } } @Test public void testGetRegionByStateOfTable() throws Exception { RegionInfo hri = createTableAndGetOneRegion(tableName); RegionStates regionStates = TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().getRegionStates(); assertTrue(regionStates.getRegionByStateOfTable(tableName).get(RegionState.State.OPEN) .stream().anyMatch(r -> RegionInfo.COMPARATOR.compare(r, hri) == 0)); assertFalse(regionStates.getRegionByStateOfTable(TableName.valueOf("I_am_the_phantom")) .get(RegionState.State.OPEN).stream().anyMatch(r -> RegionInfo.COMPARATOR.compare(r, hri) == 0)); } @Test public void testMoveRegion() throws Exception { admin.balancerSwitch(false).join(); RegionInfo hri = createTableAndGetOneRegion(tableName); RawAsyncHBaseAdmin rawAdmin = (RawAsyncHBaseAdmin) ASYNC_CONN.getAdmin(); ServerName serverName = rawAdmin.getRegionLocation(hri.getRegionName()).get().getServerName(); HMaster master = TEST_UTIL.getHBaseCluster().getMaster(); ServerManager serverManager = master.getServerManager(); ServerName destServerName = null; List<JVMClusterUtil.RegionServerThread> regionServers = TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads(); for (JVMClusterUtil.RegionServerThread regionServer : regionServers) { HRegionServer destServer = regionServer.getRegionServer(); destServerName = destServer.getServerName(); if (!destServerName.equals(serverName) && serverManager.isServerOnline(destServerName)) { break; } } assertTrue(destServerName != null && !destServerName.equals(serverName)); admin.move(hri.getRegionName(), destServerName).get(); long timeoutTime = System.currentTimeMillis() + 30000; while (true) { ServerName sn = rawAdmin.getRegionLocation(hri.getRegionName()).get().getServerName(); if (sn != null && sn.equals(destServerName)) { break; } long now = System.currentTimeMillis(); if (now > timeoutTime) { fail("Failed to move the region in time: " + hri); } Thread.sleep(100); } admin.balancerSwitch(true).join(); } @Test public void testGetOnlineRegions() throws Exception { createTableAndGetOneRegion(tableName); AtomicInteger regionServerCount = new AtomicInteger(0); TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads().stream() .map(rsThread -> rsThread.getRegionServer()).forEach(rs -> { ServerName serverName = rs.getServerName(); try { assertEquals(admin.getRegions(serverName).get().size(), rs.getRegions().size()); } catch (Exception e) { fail("admin.getOnlineRegions() method throws a exception: " + e.getMessage()); } regionServerCount.incrementAndGet(); }); assertEquals(TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads().size(), regionServerCount.get()); } @Test public void testFlushTableAndRegion() throws Exception { RegionInfo hri = createTableAndGetOneRegion(tableName); ServerName serverName = TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().getRegionStates() .getRegionServerOfRegion(hri); HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads().stream() .map(rsThread -> rsThread.getRegionServer()) .filter(rs -> rs.getServerName().equals(serverName)).findFirst().get(); // write a put into the specific region ASYNC_CONN.getTable(tableName) .put(new Put(hri.getStartKey()).addColumn(FAMILY, FAMILY_0, Bytes.toBytes("value-1"))) .join(); assertTrue(regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize() > 0); // flush region and wait flush operation finished. LOG.info("flushing region: " + Bytes.toStringBinary(hri.getRegionName())); admin.flushRegion(hri.getRegionName()).get(); LOG.info("blocking until flush is complete: " + Bytes.toStringBinary(hri.getRegionName())); Threads.sleepWithoutInterrupt(500); while (regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize() > 0) { Threads.sleep(50); } // check the memstore. assertEquals(regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize(), 0); // write another put into the specific region ASYNC_CONN.getTable(tableName) .put(new Put(hri.getStartKey()).addColumn(FAMILY, FAMILY_0, Bytes.toBytes("value-2"))) .join(); assertTrue(regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize() > 0); admin.flush(tableName).get(); Threads.sleepWithoutInterrupt(500); while (regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize() > 0) { Threads.sleep(50); } // check the memstore. assertEquals(regionServer.getOnlineRegion(hri.getRegionName()).getMemStoreDataSize(), 0); } private void waitUntilMobCompactionFinished(TableName tableName) throws ExecutionException, InterruptedException { long finished = EnvironmentEdgeManager.currentTime() + 60000; CompactionState state = admin.getCompactionState(tableName, CompactType.MOB).get(); while (EnvironmentEdgeManager.currentTime() < finished) { if (state == CompactionState.NONE) { break; } Thread.sleep(10); state = admin.getCompactionState(tableName, CompactType.MOB).get(); } assertEquals(CompactionState.NONE, state); } @Test public void testCompactMob() throws Exception { ColumnFamilyDescriptor columnDescriptor = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("mob")) .setMobEnabled(true).setMobThreshold(0).build(); TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName) .setColumnFamily(columnDescriptor).build(); admin.createTable(tableDescriptor).get(); byte[][] families = { Bytes.toBytes("mob") }; loadData(tableName, families, 3000, 8); admin.majorCompact(tableName).get(); CompactionState state = admin.getCompactionState(tableName).get(); assertNotEquals(CompactionState.NONE, state); waitUntilMobCompactionFinished(tableName); } @Test public void testCompactRegionServer() throws Exception { byte[][] families = { Bytes.toBytes("f1"), Bytes.toBytes("f2"), Bytes.toBytes("f3") }; createTableWithDefaultConf(tableName, null, families); loadData(tableName, families, 3000, 8); List<HRegionServer> rsList = TEST_UTIL.getHBaseCluster().getLiveRegionServerThreads().stream() .map(rsThread -> rsThread.getRegionServer()).collect(Collectors.toList()); List<Region> regions = new ArrayList<>(); rsList.forEach(rs -> regions.addAll(rs.getRegions(tableName))); assertEquals(1, regions.size()); int countBefore = countStoreFilesInFamilies(regions, families); assertTrue(countBefore > 0); // Minor compaction for all region servers. for (HRegionServer rs : rsList) admin.compactRegionServer(rs.getServerName()).get(); Thread.sleep(5000); int countAfterMinorCompaction = countStoreFilesInFamilies(regions, families); assertTrue(countAfterMinorCompaction < countBefore); // Major compaction for all region servers. for (HRegionServer rs : rsList) admin.majorCompactRegionServer(rs.getServerName()).get(); Thread.sleep(5000); int countAfterMajorCompaction = countStoreFilesInFamilies(regions, families); assertEquals(3, countAfterMajorCompaction); } @Test public void testCompactionSwitchStates() throws Exception { // Create a table with regions byte[] family = Bytes.toBytes("family"); byte[][] families = {family, Bytes.add(family, Bytes.toBytes("2")), Bytes.add(family, Bytes.toBytes("3"))}; createTableWithDefaultConf(tableName, null, families); loadData(tableName, families, 3000, 8); List<Region> regions = new ArrayList<>(); TEST_UTIL .getHBaseCluster() .getLiveRegionServerThreads() .forEach(rsThread -> regions.addAll(rsThread.getRegionServer().getRegions(tableName))); CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture = admin.compactionSwitch(true, new ArrayList<>()); Map<ServerName, Boolean> pairs = listCompletableFuture.get(); for (Map.Entry<ServerName, Boolean> p : pairs.entrySet()) { assertEquals("Default compaction state, expected=enabled actual=disabled", true, p.getValue()); } CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture1 = admin.compactionSwitch(false, new ArrayList<>()); Map<ServerName, Boolean> pairs1 = listCompletableFuture1.get(); for (Map.Entry<ServerName, Boolean> p : pairs1.entrySet()) { assertEquals("Last compaction state, expected=enabled actual=disabled", true, p.getValue()); } CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture2 = admin.compactionSwitch(true, new ArrayList<>()); Map<ServerName, Boolean> pairs2 = listCompletableFuture2.get(); for (Map.Entry<ServerName, Boolean> p : pairs2.entrySet()) { assertEquals("Last compaction state, expected=disabled actual=enabled", false, p.getValue()); } ServerName serverName = TEST_UTIL.getHBaseCluster().getRegionServer(0) .getServerName(); List<String> serverNameList = new ArrayList<String>(); serverNameList.add(serverName.getServerName()); CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture3 = admin.compactionSwitch(false, serverNameList); Map<ServerName, Boolean> pairs3 = listCompletableFuture3.get(); assertEquals(pairs3.entrySet().size(), 1); for (Map.Entry<ServerName, Boolean> p : pairs3.entrySet()) { assertEquals("Last compaction state, expected=enabled actual=disabled", true, p.getValue()); } CompletableFuture<Map<ServerName, Boolean>> listCompletableFuture4 = admin.compactionSwitch(true, serverNameList); Map<ServerName, Boolean> pairs4 = listCompletableFuture4.get(); assertEquals(pairs4.entrySet().size(), 1); for (Map.Entry<ServerName, Boolean> p : pairs4.entrySet()) { assertEquals("Last compaction state, expected=disabled actual=enabled", false, p.getValue()); } } @Test public void testCompact() throws Exception { compactionTest(TableName.valueOf("testCompact1"), 8, CompactionState.MAJOR, false); compactionTest(TableName.valueOf("testCompact2"), 15, CompactionState.MINOR, false); compactionTest(TableName.valueOf("testCompact3"), 8, CompactionState.MAJOR, true); compactionTest(TableName.valueOf("testCompact4"), 15, CompactionState.MINOR, true); } private void compactionTest(final TableName tableName, final int flushes, final CompactionState expectedState, boolean singleFamily) throws Exception { // Create a table with regions byte[] family = Bytes.toBytes("family"); byte[][] families = { family, Bytes.add(family, Bytes.toBytes("2")), Bytes.add(family, Bytes.toBytes("3")) }; createTableWithDefaultConf(tableName, null, families); loadData(tableName, families, 3000, flushes); List<Region> regions = new ArrayList<>(); TEST_UTIL .getHBaseCluster() .getLiveRegionServerThreads() .forEach(rsThread -> regions.addAll(rsThread.getRegionServer().getRegions(tableName))); assertEquals(1, regions.size()); int countBefore = countStoreFilesInFamilies(regions, families); int countBeforeSingleFamily = countStoreFilesInFamily(regions, family); assertTrue(countBefore > 0); // there should be some data files if (expectedState == CompactionState.MINOR) { if (singleFamily) { admin.compact(tableName, family).get(); } else { admin.compact(tableName).get(); } } else { if (singleFamily) { admin.majorCompact(tableName, family).get(); } else { admin.majorCompact(tableName).get(); } } long curt = System.currentTimeMillis(); long waitTime = 5000; long endt = curt + waitTime; CompactionState state = admin.getCompactionState(tableName).get(); while (state == CompactionState.NONE && curt < endt) { Thread.sleep(10); state = admin.getCompactionState(tableName).get(); curt = System.currentTimeMillis(); } // Now, should have the right compaction state, // otherwise, the compaction should have already been done if (expectedState != state) { for (Region region : regions) { state = CompactionState.valueOf(region.getCompactionState().toString()); assertEquals(CompactionState.NONE, state); } } else { // Wait until the compaction is done state = admin.getCompactionState(tableName).get(); while (state != CompactionState.NONE && curt < endt) { Thread.sleep(10); state = admin.getCompactionState(tableName).get(); } // Now, compaction should be done. assertEquals(CompactionState.NONE, state); } int countAfter = countStoreFilesInFamilies(regions, families); int countAfterSingleFamily = countStoreFilesInFamily(regions, family); assertTrue(countAfter < countBefore); if (!singleFamily) { if (expectedState == CompactionState.MAJOR) { assertEquals(families.length, countAfter); } else { assertTrue(families.length <= countAfter); } } else { int singleFamDiff = countBeforeSingleFamily - countAfterSingleFamily; // assert only change was to single column family assertEquals(singleFamDiff, (countBefore - countAfter)); if (expectedState == CompactionState.MAJOR) { assertEquals(1, countAfterSingleFamily); } else { assertTrue("" + countAfterSingleFamily, 1 <= countAfterSingleFamily); } } } @Test public void testNonExistentTableCompaction() { testNonExistentTableCompaction(CompactionState.MINOR); testNonExistentTableCompaction(CompactionState.MAJOR); } private void testNonExistentTableCompaction(CompactionState compactionState) { try { if (compactionState == CompactionState.MINOR) { admin.compact(TableName.valueOf("NonExistentTable")).get(); } else { admin.majorCompact(TableName.valueOf("NonExistentTable")).get(); } fail("Expected TableNotFoundException when table doesn't exist"); } catch (Exception e) { // expected. assertTrue(e.getCause() instanceof TableNotFoundException); } } private static int countStoreFilesInFamily(List<Region> regions, final byte[] family) { return countStoreFilesInFamilies(regions, new byte[][] { family }); } private static int countStoreFilesInFamilies(List<Region> regions, final byte[][] families) { int count = 0; for (Region region : regions) { count += region.getStoreFileList(families).size(); } return count; } static void loadData(final TableName tableName, final byte[][] families, final int rows) throws IOException { loadData(tableName, families, rows, 1); } static void loadData(final TableName tableName, final byte[][] families, final int rows, final int flushes) throws IOException { AsyncTable<?> table = ASYNC_CONN.getTable(tableName); List<Put> puts = new ArrayList<>(rows); byte[] qualifier = Bytes.toBytes("val"); for (int i = 0; i < flushes; i++) { for (int k = 0; k < rows; k++) { byte[] row = Bytes.add(Bytes.toBytes(k), Bytes.toBytes(i)); Put p = new Put(row); for (int j = 0; j < families.length; ++j) { p.addColumn(families[j], qualifier, row); } puts.add(p); } table.putAll(puts).join(); TEST_UTIL.flush(); puts.clear(); } } }
HBASE-24073 [flakey test] client.TestAsyncRegionAdminApi messed up compaction state. (#1387) Signed-off-by: Viraj Jasani <0f008b677517e222a5b140e7cfedb6aed7df6c3b@apache.org>
hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAsyncRegionAdminApi.java
HBASE-24073 [flakey test] client.TestAsyncRegionAdminApi messed up compaction state. (#1387)
Java
apache-2.0
c34b6df7b7528efca92ca0c71a596b7020a9d720
0
IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service
/* * Copyright 2015 West Coast Informatics, LLC */ package org.ihtsdo.otf.mapping.jpa.services; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import org.apache.log4j.Logger; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.util.ReaderUtil; import org.apache.lucene.util.Version; import org.hibernate.CacheMode; import org.hibernate.search.SearchFactory; import org.hibernate.search.indexes.IndexReaderAccessor; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.Search; import org.ihtsdo.otf.mapping.helpers.FeedbackConversationList; import org.ihtsdo.otf.mapping.helpers.FeedbackConversationListJpa; import org.ihtsdo.otf.mapping.helpers.FeedbackList; import org.ihtsdo.otf.mapping.helpers.FeedbackListJpa; import org.ihtsdo.otf.mapping.helpers.LocalException; import org.ihtsdo.otf.mapping.helpers.MapRecordList; import org.ihtsdo.otf.mapping.helpers.MapUserList; import org.ihtsdo.otf.mapping.helpers.MapUserListJpa; import org.ihtsdo.otf.mapping.helpers.PfsParameter; import org.ihtsdo.otf.mapping.helpers.PfsParameterJpa; import org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler; import org.ihtsdo.otf.mapping.helpers.SearchResult; import org.ihtsdo.otf.mapping.helpers.SearchResultJpa; import org.ihtsdo.otf.mapping.helpers.SearchResultList; import org.ihtsdo.otf.mapping.helpers.SearchResultListJpa; import org.ihtsdo.otf.mapping.helpers.TrackingRecordList; import org.ihtsdo.otf.mapping.helpers.TrackingRecordListJpa; import org.ihtsdo.otf.mapping.helpers.TreePositionList; import org.ihtsdo.otf.mapping.helpers.ValidationResult; import org.ihtsdo.otf.mapping.helpers.WorkflowAction; import org.ihtsdo.otf.mapping.helpers.WorkflowPath; import org.ihtsdo.otf.mapping.helpers.WorkflowStatus; import org.ihtsdo.otf.mapping.helpers.WorkflowType; import org.ihtsdo.otf.mapping.jpa.FeedbackConversationJpa; import org.ihtsdo.otf.mapping.jpa.MapRecordJpa; import org.ihtsdo.otf.mapping.jpa.handlers.AbstractWorkflowPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowFixErrorPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowNonLegacyPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowQaPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowReviewProjectPathHandler; import org.ihtsdo.otf.mapping.model.Feedback; import org.ihtsdo.otf.mapping.model.FeedbackConversation; import org.ihtsdo.otf.mapping.model.MapProject; import org.ihtsdo.otf.mapping.model.MapRecord; import org.ihtsdo.otf.mapping.model.MapUser; import org.ihtsdo.otf.mapping.reports.Report; import org.ihtsdo.otf.mapping.reports.ReportResultItem; import org.ihtsdo.otf.mapping.rf2.Concept; import org.ihtsdo.otf.mapping.services.ContentService; import org.ihtsdo.otf.mapping.services.MappingService; import org.ihtsdo.otf.mapping.services.WorkflowService; import org.ihtsdo.otf.mapping.services.helpers.ConfigUtility; import org.ihtsdo.otf.mapping.services.helpers.OtfEmailHandler; import org.ihtsdo.otf.mapping.workflow.TrackingRecord; import org.ihtsdo.otf.mapping.workflow.TrackingRecordJpa; import org.ihtsdo.otf.mapping.workflow.WorkflowException; import org.ihtsdo.otf.mapping.workflow.WorkflowExceptionJpa; /** * Default workflow service implementation. */ public class WorkflowServiceJpa extends RootServiceJpa implements WorkflowService { /** The map record indexed field names. */ protected static Set<String> trackingRecordFieldNames; /** * Instantiates an empty {@link WorkflowServiceJpa}. * * @throws Exception the exception */ public WorkflowServiceJpa() throws Exception { super(); if (trackingRecordFieldNames == null) { initializeFieldNames(); } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.RootService#initializeFieldNames() */ @Override public synchronized void initializeFieldNames() throws Exception { trackingRecordFieldNames = new HashSet<>(); EntityManager manager = factory.createEntityManager(); FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(manager); IndexReaderAccessor indexReaderAccessor = fullTextEntityManager.getSearchFactory().getIndexReaderAccessor(); Set<String> indexedClassNames = fullTextEntityManager.getSearchFactory().getStatistics() .getIndexedClassNames(); for (String indexClass : indexedClassNames) { if (indexClass.indexOf("TrackingRecordJpa") != -1) { Logger.getLogger(ContentServiceJpa.class).info( "FOUND TrackingRecordJpa index"); IndexReader indexReader = indexReaderAccessor.open(indexClass); try { for (FieldInfo info : ReaderUtil.getMergedFieldInfos(indexReader)) { trackingRecordFieldNames.add(info.name); } } finally { indexReaderAccessor.close(indexReader); } } } fullTextEntityManager.close(); } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#addTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public TrackingRecord addTrackingRecord(TrackingRecord trackingRecord) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(trackingRecord); tx.commit(); } else { manager.persist(trackingRecord); } return trackingRecord; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#removeTrackingRecord * (java.lang.Long) */ @Override public void removeTrackingRecord(Long trackingRecordId) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); TrackingRecord ma = manager.find(TrackingRecordJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } tx.commit(); } else { TrackingRecord ma = manager.find(TrackingRecordJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#updateTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public void updateTrackingRecord(TrackingRecord record) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(record); tx.commit(); } else { manager.merge(record); } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getTrackingRecords () */ @SuppressWarnings("unchecked") @Override public TrackingRecordList getTrackingRecords() throws Exception { TrackingRecordListJpa trackingRecordList = new TrackingRecordListJpa(); trackingRecordList.setTrackingRecords(manager.createQuery( "select tr from TrackingRecordJpa tr").getResultList()); return trackingRecordList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getTrackingRecordForMapProjectAndConcept * (org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.rf2.Concept) */ @Override public TrackingRecord getTrackingRecordForMapProjectAndConcept( MapProject mapProject, Concept concept) { try { return (TrackingRecord) manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", concept.getTerminology()) .setParameter("terminologyVersion", concept.getTerminologyVersion()) .setParameter("terminologyId", concept.getTerminologyId()) .getSingleResult(); } catch (Exception e) { return null; } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getTrackingRecordForMapProjectAndConcept * (org.ihtsdo.otf.mapping.model.MapProject, java.lang.String) */ @Override public TrackingRecord getTrackingRecordForMapProjectAndConcept( MapProject mapProject, String terminologyId) { try { return (TrackingRecord) manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId).getSingleResult(); } catch (Exception e) { return null; } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getTrackingRecordsForMapProject (org.ihtsdo.otf.mapping.model.MapProject) */ @SuppressWarnings("unchecked") @Override public TrackingRecordList getTrackingRecordsForMapProject( MapProject mapProject) throws Exception { TrackingRecordListJpa trackingRecordList = new TrackingRecordListJpa(); javax.persistence.Query query = manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId") .setParameter("mapProjectId", mapProject.getId()); trackingRecordList.setTrackingRecords(query.getResultList()); return trackingRecordList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getTrackingRecord * (org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.rf2.Concept) */ @Override public TrackingRecord getTrackingRecord(MapProject mapProject, Concept concept) throws Exception { javax.persistence.Query query = manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminologyId", concept.getTerminologyId()); return (TrackingRecord) query.getSingleResult(); } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#addWorkflowException * (org.ihtsdo.otf.mapping.workflow.WorkflowException) */ @Override public WorkflowException addWorkflowException(WorkflowException trackingRecord) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(trackingRecord); tx.commit(); } else { manager.persist(trackingRecord); } return trackingRecord; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#removeWorkflowException * (java.lang.Long) */ @Override public void removeWorkflowException(Long trackingRecordId) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); WorkflowException ma = manager.find(WorkflowExceptionJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } tx.commit(); } else { WorkflowException ma = manager.find(WorkflowExceptionJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } } } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#updateWorkflowException * (org.ihtsdo.otf.mapping.workflow.WorkflowException) */ @Override public void updateWorkflowException(WorkflowException workflowException) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(workflowException); tx.commit(); } else { manager.merge(workflowException); } } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#getWorkflowException(org * .ihtsdo.otf.mapping.model.MapProject, java.lang.String) */ @Override public WorkflowException getWorkflowException(MapProject mapProject, String terminologyId) { javax.persistence.Query query = manager .createQuery( "select we from WorkflowExceptionJpa we where mapProjectId = :mapProjectId" + " and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId); // try to get the expected single result try { return (WorkflowException) query.getSingleResult(); } catch (NoResultException e) { return null; } } /** * Construct map project id query. * * @param mapProjectId the map project id * @param query the query * @return the string */ private static String constructMapProjectIdQuery(Long mapProjectId, String query) { String fullQuery; // if no filter supplied, return query based on map project id only if (query == null || query.equals("") || query.equals("null") || query.equals("undefined")) { fullQuery = "mapProjectId:" + mapProjectId; return fullQuery; } // Pre-treatment: Find any lower-case boolean operators and set to // uppercase // ////////////////// // Basic algorithm: // // 1) add whitespace breaks to operators // 2) split query on whitespace // 3) cycle over terms in split query to find quoted material, add each // term/quoted term to parsed terms\ // a) special case: quoted term after a : // 3) cycle over terms in parsed terms // a) if an operator/parantheses, pass through unchanged (send to upper // case // for boolean) // b) if a fielded query (i.e. field:value), pass through unchanged // c) if not, construct query on all fields with this term // list of escape terms (i.e. quotes, operators) to be fed into query // untouched String escapeTerms = "\\+|\\-|\"|\\(|\\)"; String booleanTerms = "and|AND|or|OR|not|NOT"; // first cycle over the string to add artificial breaks before and after // control characters String queryStrMod = query; queryStrMod = queryStrMod.replace("(", " ( "); queryStrMod = queryStrMod.replace(")", " ) "); queryStrMod = queryStrMod.replace("\"", " \" "); queryStrMod = queryStrMod.replace("+", " + "); queryStrMod = queryStrMod.replace("-", " - "); // remove any leading or trailing whitespace (otherwise first/last null // term // bug) queryStrMod = queryStrMod.trim(); // split the string by white space and single-character operators String[] terms = queryStrMod.split("\\s+"); // merge items between quotation marks boolean exprInQuotes = false; List<String> parsedTerms = new ArrayList<>(); String currentTerm = ""; // cycle over terms to identify quoted (i.e. non-parsed) terms for (int i = 0; i < terms.length; i++) { // if an open quote is detected if (terms[i].equals("\"")) { if (exprInQuotes) { // special case check: fielded term. Impossible for first // term to be // fielded. if (parsedTerms.size() == 0) { parsedTerms.add("\"" + currentTerm + "\""); } else { String lastParsedTerm = parsedTerms.get(parsedTerms.size() - 1); // if last parsed term ended with a colon, append this // term to the // last parsed term if (lastParsedTerm.endsWith(":")) { parsedTerms.set(parsedTerms.size() - 1, lastParsedTerm + "\"" + currentTerm + "\""); } else { parsedTerms.add("\"" + currentTerm + "\""); } } // reset current term currentTerm = ""; exprInQuotes = false; } else { exprInQuotes = true; } // if no quote detected } else { // if inside quotes, continue building term if (exprInQuotes) { currentTerm = currentTerm == "" ? terms[i] : currentTerm + " " + terms[i]; // otherwise, add to parsed list } else { parsedTerms.add(terms[i]); } } } for (String s : parsedTerms) { Logger.getLogger(MappingServiceJpa.class).debug(" " + s); } // cycle over terms to construct query fullQuery = ""; for (int i = 0; i < parsedTerms.size(); i++) { // if not the first term AND the last term was not an escape term // add whitespace separator if (i != 0 && !parsedTerms.get(i - 1).matches(escapeTerms)) { fullQuery += " "; } /* * fullQuery += (i == 0 ? // check for first term "" : // -> if first * character, add nothing parsedTerms.get(i-1).matches(escapeTerms) ? // * check if last term was an escape character "": // -> if last term was * an escape character, add nothing " "); // -> otherwise, add a * separating space */ // if an escape character/sequence, add this term unmodified if (parsedTerms.get(i).matches(escapeTerms)) { fullQuery += parsedTerms.get(i); // else if a boolean character, add this term in upper-case form // (i.e. // lucene format) } else if (parsedTerms.get(i).matches(booleanTerms)) { fullQuery += parsedTerms.get(i).toUpperCase(); // else if already a field-specific query term, add this term // unmodified } else if (parsedTerms.get(i).contains(":")) { fullQuery += parsedTerms.get(i); // otherwise, treat as unfielded query term } else { // open parenthetical term fullQuery += "("; // add fielded query for each indexed term, separated by OR Iterator<String> namesIter = trackingRecordFieldNames.iterator(); while (namesIter.hasNext()) { fullQuery += namesIter.next() + ":" + parsedTerms.get(i); if (namesIter.hasNext()) fullQuery += " OR "; } // close parenthetical term fullQuery += ")"; } // if further terms remain in the sequence if (!(i == parsedTerms.size() - 1)) { // Add a separating OR iff: // - this term is not an escape character // - this term is not a boolean term // - next term is not a boolean term if (!parsedTerms.get(i).matches(escapeTerms) && !parsedTerms.get(i).matches(booleanTerms) && !parsedTerms.get(i + 1).matches(booleanTerms)) { fullQuery += " OR"; } } } // add parantheses and map project constraint fullQuery = "(" + fullQuery + ")" + " AND mapProjectId:" + mapProjectId; Logger.getLogger(MappingServiceJpa.class).debug("Full query: " + fullQuery); return fullQuery; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAvailableWork(org.ihtsdo * .otf.mapping.model.MapProject, org.ihtsdo.otf.mapping.model.MapUser, * java.lang.String, org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAvailableWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList availableWork = new SearchResultListJpa(); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAvailableWork // - must be NON_LEGACY PATH // - any tracking record with no assigned users is by definition // available // - any tracking record with one assigned user on NON_LEGACY_PATH with // workflowstatus NEW, EDITING_IN_PROGRESS, or EDITING_DONE. Assigned // user must not be this user switch (mapProject.getWorkflowType()) { case CONFLICT_PROJECT: fullQuery += " AND workflowPath:NON_LEGACY_PATH"; // Handle "team" based assignment if (mapProject.isTeamBased() && mapUser.getTeam() != null && !mapUser.getTeam().isEmpty()) { // Use "AND NOT" clauses for all members matching my user's team. MappingService service = new MappingServiceJpa(); fullQuery += " AND (assignedUserCount:0 OR (assignedUserCount:1 "; for (MapUser user : service.getMapUsersForTeam(mapUser.getTeam()) .getMapUsers()) { fullQuery += " AND NOT assignedUserNames:" + user.getUserName(); } fullQuery += ") )"; service.close(); } else { fullQuery += " AND (assignedUserCount:0 OR " + "(assignedUserCount:1 AND NOT assignedUserNames:" + mapUser.getUserName() + "))"; } break; case REVIEW_PROJECT: fullQuery += " AND workflowPath:REVIEW_PROJECT_PATH"; fullQuery += " AND assignedUserCount:0"; break; default: throw new Exception("Invalid workflow type specified for project " + mapProject.getWorkflowType()); } QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); availableWork.setTotalCount(ftquery.getResultSize()); if (pfsParameter.getStartIndex() != -1 && pfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(pfsParameter.getStartIndex()); ftquery.setMaxResults(pfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (pfsParameter.getSortField() != null && !pfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()) .getType().equals(String.class)) { ftquery.setSort(new Sort(new SortField(pfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); result.setTerminologyId(tr.getTerminologyId()); result.setValue(tr.getDefaultPreferredName()); result.setId(tr.getId()); availableWork.addSearchResult(result); } return availableWork; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getAvailableConflicts * (org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.model.MapUser) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAvailableConflicts(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList availableConflicts = new SearchResultListJpa(); // if not a conflict project, return empty list if (!mapProject.getWorkflowType().equals(WorkflowType.CONFLICT_PROJECT)) { return availableConflicts; } FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAvailableConflicts // - user and workflowStatus pair of CONFLICT_DETECTED_userName exists // - user and workflowStatus pairs of // CONFLICT_NEW/CONFLICT_IN_PROGRESS_userName does not exist fullQuery += " AND userAndWorkflowStatusPairs:CONFLICT_DETECTED_*"; fullQuery += " AND NOT (userAndWorkflowStatusPairs:CONFLICT_NEW_* OR userAndWorkflowStatusPairs:CONFLICT_IN_PROGRESS_* OR userAndWorkflowStatusPairs:CONFLICT_RESOLVED_*)"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); availableConflicts.setTotalCount(ftquery.getResultSize()); if (pfsParameter.getStartIndex() != -1 && pfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(pfsParameter.getStartIndex()); ftquery.setMaxResults(pfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (pfsParameter.getSortField() != null && !pfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()) .getType().equals(String.class)) { ftquery.setSort(new Sort(new SortField(pfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); result.setTerminologyId(tr.getTerminologyId()); result.setValue(tr.getDefaultPreferredName()); result.setId(tr.getId()); availableConflicts.addSearchResult(result); } return availableConflicts; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAvailableQAWork(org * .ihtsdo.otf.mapping.model.MapProject, org.ihtsdo.otf.mapping.model.MapUser, * java.lang.String, org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAvailableQAWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList availableQAWork = new SearchResultListJpa(); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = "mapProjectId:" + mapProject.getId(); // add the query terms specific to findAvailableReviewWork // - a user (any) and workflowStatus pair of QA_NEEDED_userName // exists // - the QA_NEEDED pair is not for this user (i.e. user can't review // their own work, UNLESS there is only one lead on the project // - user and workflowStatus pairs of // CONFLICT_NEW/CONFLICT_IN_PROGRESS_userName does not exist // must have a QA_NEEDED tag with any user fullQuery += " AND userAndWorkflowStatusPairs:QA_NEEDED_*"; fullQuery += " AND workflowPath:QA_PATH"; // there must not be an already claimed review record fullQuery += " AND NOT (userAndWorkflowStatusPairs:QA_NEW_*" + " OR userAndWorkflowStatusPairs:QA_IN_PROGRESS_*" + " OR userAndWorkflowStatusPairs:QA_RESOLVED_*" + ")"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); List<TrackingRecord> allResults = ftquery.getResultList(); List<TrackingRecord> results = new ArrayList<>(); if (query == null || query.equals("") || query.equals("null") || query.equals("undefined")) { results = allResults; } else { // remove tracking records that don't have a map record with a label // matching the query for (TrackingRecord tr : allResults) { boolean labelFound = false; // OPTIMIZATION: Bypass the "get map records for tr" mechanism to avoid // full lazy initialization of the record Set<MapRecord> mapRecords = new HashSet<>(); if (tr != null && tr.getMapRecordIds() != null) { for (Long id : tr.getMapRecordIds()) { // go directly, we just need record label info mapRecords.add(manager.find(MapRecordJpa.class, id)); } } for (MapRecord record : mapRecords) { for (String label : record.getLabels()) { if (label.equals(query)) { labelFound = true; } } } if (labelFound) { results.add(tr); } } } // set the total count matching this label availableQAWork.setTotalCount(results.size()); // apply paging, and sorting if appropriate if (pfsParameter != null && (pfsParameter.getSortField() != null && !pfsParameter.getSortField() .isEmpty())) { // check that specified sort field exists on Concept and is // a string final Field sortField = TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()); if (!sortField.getType().equals(String.class)) { throw new Exception( "findAvailableQAWork error: Referenced sort field is not of type String"); } // allow the field to access the Concept values sortField.setAccessible(true); // sort the list - UNTESTED Collections.sort(results, new Comparator<TrackingRecord>() { @Override public int compare(TrackingRecord c1, TrackingRecord c2) { // if an exception is returned, simply pass equality try { return ((String) sortField.get(c1)).compareTo((String) sortField .get(c2)); } catch (Exception e) { return 0; } } }); } // get the start and end indexes based on paging parameters int startIndex = 0; int toIndex = results.size(); if (pfsParameter != null) { startIndex = pfsParameter.getStartIndex() == -1 ? 0 : Math.min(results.size(), pfsParameter.getStartIndex()); // ensure start index not negative if (startIndex < 0) startIndex = 0; toIndex = pfsParameter.getMaxResults() == -1 ? results.size() : Math.min( results.size(), startIndex + pfsParameter.getMaxResults()); } for (TrackingRecord tr : results.subList(startIndex, toIndex)) { SearchResult result = new SearchResultJpa(); result.setTerminologyId(tr.getTerminologyId()); result.setId(tr.getId()); result.setValue(tr.getDefaultPreferredName()); StringBuffer labelBuffer = new StringBuffer(); for (MapRecord record : getMapRecordsForTrackingRecord(tr)) { for (String label : record.getLabels()) { if (labelBuffer.indexOf(label) == -1) labelBuffer.append(";").append(label); } } result.setValue2(labelBuffer.toString()); availableQAWork.addSearchResult(result); } return availableQAWork; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getAvailableReviewWork * (org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.model.MapUser) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAvailableReviewWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList availableReviewWork = new SearchResultListJpa(); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAvailableReviewWork // - a user (any) and workflowStatus pair of REVIEW_NEEDED_userName // exists // - the REVIEW_NEEDED pair is not for this user (i.e. user can't review // their own work, UNLESS there is only one lead on the project // - user and workflowStatus pairs of // CONFLICT_NEW/CONFLICT_IN_PROGRESS_userName does not exist // must have a REVIEW_NEEDED tag with any user fullQuery += " AND userAndWorkflowStatusPairs:REVIEW_NEEDED_*"; // there must not be an already claimed review record fullQuery += " AND NOT (userAndWorkflowStatusPairs:REVIEW_NEW_*" + " OR userAndWorkflowStatusPairs:REVIEW_IN_PROGRESS_*" + " OR userAndWorkflowStatusPairs:REVIEW_RESOLVED_*" + ")"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); availableReviewWork.setTotalCount(ftquery.getResultSize()); if (pfsParameter.getStartIndex() != -1 && pfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(pfsParameter.getStartIndex()); ftquery.setMaxResults(pfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (pfsParameter.getSortField() != null && !pfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()) .getType().equals(String.class)) { ftquery.setSort(new Sort(new SortField(pfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); result.setTerminologyId(tr.getTerminologyId()); result.setValue(tr.getDefaultPreferredName()); result.setId(tr.getId()); availableReviewWork.addSearchResult(result); } return availableReviewWork; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAssignedWork(org.ihtsdo * .otf.mapping.model.MapProject, org.ihtsdo.otf.mapping.model.MapUser, * java.lang.String, org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAssignedWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { PfsParameter localPfsParameter = pfsParameter; SearchResultList assignedWork = new SearchResultListJpa(); // create a blank pfs parameter object if one not passed in if (localPfsParameter == null) localPfsParameter = new PfsParameterJpa(); // create a blank query restriction if none provided if (localPfsParameter.getQueryRestriction() == null) localPfsParameter.setQueryRestriction(""); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAssignedWork // - user and workflowStatus must exist in a pair of form: // workflowStatus_userName, e.g. NEW_dmo or EDITING_IN_PROGRESS_kli // - modify search term based on pfs parameter query restriction field // * default: NEW, EDITING_IN_PROGRESS, EDITING_DONE/CONFLICT_DETECTED // * NEW: NEW // * EDITED: EDITING_IN_PROGRESS, EDITING_DONE/CONFLICT_DETECTED // add terms based on query restriction switch (localPfsParameter.getQueryRestriction()) { case "NEW": fullQuery += " AND userAndWorkflowStatusPairs:NEW_" + mapUser.getUserName(); break; case "EDITING_IN_PROGRESS": fullQuery += " AND (userAndWorkflowStatusPairs:EDITING_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_IN_PROGRESS_" + mapUser.getUserName() + ")"; break; case "EDITING_DONE": fullQuery += " AND (userAndWorkflowStatusPairs:EDITING_DONE_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:CONFLICT_DETECTED_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_NEEDED_" + mapUser.getUserName() + ")"; break; default: fullQuery += " AND (userAndWorkflowStatusPairs:NEW_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:EDITING_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:EDITING_DONE_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:CONFLICT_DETECTED_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_NEEDED_" + mapUser.getUserName() + ")"; break; } // add terms to exclude concepts that a lead has claimed fullQuery += " AND NOT (userAndWorkflowStatusPairs:CONFLICT_NEW_*" + " OR userAndWorkflowStatusPairs:CONFLICT_IN_PROGRESS_*" + " OR userAndWorkflowStatusPairs:CONFLICT_RESOLVED_*" + " OR userAndWorkflowStatusPairs:REVIEW_NEW_*" + " OR userAndWorkflowStatusPairs:REVIEW_NEEDED_*" + " OR userAndWorkflowStatusPairs:REVIEW_RESOLVED_*)"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); assignedWork.setTotalCount(ftquery.getResultSize()); if (localPfsParameter.getStartIndex() != -1 && localPfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(localPfsParameter.getStartIndex()); ftquery.setMaxResults(localPfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (localPfsParameter.getSortField() != null && !localPfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class .getDeclaredField(localPfsParameter.getSortField()).getType() .equals(String.class)) { ftquery.setSort(new Sort(new SortField( localPfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } // otherwise, sort by ancestor path } else { ftquery.setSort(new Sort(new SortField("sortKey", SortField.STRING))); } List<TrackingRecord> results = ftquery.getResultList(); MappingService mappingService = new MappingServiceJpa(); for (TrackingRecord tr : results) { // instantiate the result list SearchResult result = new SearchResultJpa(); // get the map records associated with this tracking record Set<MapRecord> mapRecords = this.getMapRecordsForTrackingRecord(tr); // get the map record assigned to this user MapRecord mapRecord = null; // SEE BELOW/MAP-617 WorkflowStatus mapLeadAlternateRecordStatus = null; for (MapRecord mr : mapRecords) { if (mr.getOwner().equals(mapUser)) { // if this lead has review or conflict work, set the flag if (mr.getWorkflowStatus().equals(WorkflowStatus.CONFLICT_NEW) || mr.getWorkflowStatus().equals( WorkflowStatus.CONFLICT_IN_PROGRESS) || mr.getWorkflowStatus().equals(WorkflowStatus.REVIEW_NEW) || mr.getWorkflowStatus().equals( WorkflowStatus.REVIEW_IN_PROGRESS)) { mapLeadAlternateRecordStatus = mr.getWorkflowStatus(); // added to prevent user from getting REVISION record // back on FIX_ERROR_PATH // yet another problem related to leads being able to // serve as dual roles } else if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { // do nothing // otherwise, this is the specialist/concept-level work } else { mapRecord = mr; } } } // if no record and no review or conflict work was found, throw // error if (mapRecord == null) { throw new Exception( "Failed to retrieve assigned work: no map record found for user " + mapUser.getUserName() + " and concept " + tr.getTerminologyId()); } else { // alter the workflow status if a higher-level record exists for // this user if (mapLeadAlternateRecordStatus != null) { Logger.getLogger(WorkflowServiceJpa.class).info( "Setting alternate record status: " + mapLeadAlternateRecordStatus); mapRecord.setWorkflowStatus(mapLeadAlternateRecordStatus); } // create the search result result.setTerminologyId(mapRecord.getConceptId()); result.setValue(mapRecord.getConceptName()); result.setTerminology(mapRecord.getLastModified().toString()); result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString()); result.setId(mapRecord.getId()); assignedWork.addSearchResult(result); } } mappingService.close(); return assignedWork; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getAssignedConflicts( * org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.model.MapUser) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAssignedConflicts(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList assignedConflicts = new SearchResultListJpa(); if (mapProject.getWorkflowType().toString().equals("REVIEW_PROJECT_PATH")) return assignedConflicts; PfsParameter localPfsParameter = pfsParameter; if (localPfsParameter == null) localPfsParameter = new PfsParameterJpa(); // create a blank query restriction if none provided if (localPfsParameter.getQueryRestriction() == null) localPfsParameter.setQueryRestriction(""); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAssignedConflicts // - workflow status CONFLICT_NEW or CONFLICT_IN_PROGRESS with this user // name in pair // add terms based on query restriction switch (localPfsParameter.getQueryRestriction()) { case "CONFLICT_NEW": fullQuery += " AND userAndWorkflowStatusPairs:CONFLICT_NEW_" + mapUser.getUserName(); break; case "CONFLICT_IN_PROGRESS": fullQuery += " AND userAndWorkflowStatusPairs:CONFLICT_IN_PROGRESS_" + mapUser.getUserName(); break; case "CONFLICT_RESOLVED": fullQuery += " AND userAndWorkflowStatusPairs:CONFLICT_RESOLVED_" + mapUser.getUserName(); break; default: fullQuery += " AND (userAndWorkflowStatusPairs:CONFLICT_NEW_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:CONFLICT_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:CONFLICT_RESOLVED_" + mapUser.getUserName() + ")"; break; } QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); assignedConflicts.setTotalCount(ftquery.getResultSize()); if (localPfsParameter.getStartIndex() != -1 && localPfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(localPfsParameter.getStartIndex()); ftquery.setMaxResults(localPfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (localPfsParameter.getSortField() != null && !localPfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class .getDeclaredField(localPfsParameter.getSortField()).getType() .equals(String.class)) { ftquery.setSort(new Sort(new SortField( localPfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); MappingService mappingService = new MappingServiceJpa(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); Set<MapRecord> mapRecords = this.getMapRecordsForTrackingRecord(tr); // get the map record assigned to this user MapRecord mapRecord = null; for (MapRecord mr : mapRecords) { try { if (mr.getOwner().equals(mapUser)) // SEE MAP-617: // Lower level record may exist with same owner, only // add if actually a conflict if (mr.getWorkflowStatus().compareTo( WorkflowStatus.CONFLICT_DETECTED) < 0) { // do nothing, this is the specialist level work } else { mapRecord = mr; } } catch (Exception e) { e.printStackTrace(); } } if (mapRecord == null) { throw new Exception( "Failed to retrieve assigned conflicts: no map record found for user " + mapUser.getUserName() + " and concept " + tr.getTerminologyId()); } else { result.setTerminologyId(mapRecord.getConceptId()); result.setValue(mapRecord.getConceptName()); result.setTerminology(mapRecord.getLastModified().toString()); result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString()); result.setId(mapRecord.getId()); assignedConflicts.addSearchResult(result); } } mappingService.close(); return assignedConflicts; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAssignedReviewWork( * org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.model.MapUser, java.lang.String, * org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAssignedReviewWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList assignedReviewWork = new SearchResultListJpa(); PfsParameter localPfsParameter = pfsParameter; // create a blank pfs parameter object if one not passed in if (localPfsParameter == null) localPfsParameter = new PfsParameterJpa(); // create a blank query restriction if none provided if (localPfsParameter.getQueryRestriction() == null) localPfsParameter.setQueryRestriction(""); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAssignedReviewWork // - user and workflow status must exist in the form REVIEW_NEW_userName // or REVIEW_IN_PROGRESS_userName // add terms based on query restriction switch (localPfsParameter.getQueryRestriction()) { case "REVIEW_NEW": fullQuery += " AND userAndWorkflowStatusPairs:REVIEW_NEW_" + mapUser.getUserName(); break; case "REVIEW_IN_PROGRESS": fullQuery += " AND userAndWorkflowStatusPairs:REVIEW_IN_PROGRESS_" + mapUser.getUserName(); break; case "REVIEW_RESOLVED": fullQuery += " AND userAndWorkflowStatusPairs:REVIEW_RESOLVED_" + mapUser.getUserName(); break; default: fullQuery += " AND (userAndWorkflowStatusPairs:REVIEW_NEW_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_RESOLVED_" + mapUser.getUserName() + ")"; break; } QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); assignedReviewWork.setTotalCount(ftquery.getResultSize()); if (localPfsParameter.getStartIndex() != -1 && localPfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(localPfsParameter.getStartIndex()); ftquery.setMaxResults(localPfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (localPfsParameter.getSortField() != null && !localPfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class .getDeclaredField(localPfsParameter.getSortField()).getType() .equals(String.class)) { ftquery.setSort(new Sort(new SortField( localPfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); MappingService mappingService = new MappingServiceJpa(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); Set<MapRecord> mapRecords = this.getMapRecordsForTrackingRecord(tr); // get the map record assigned to this user MapRecord mapRecord = null; for (MapRecord mr : mapRecords) { if (mr.getOwner().equals(mapUser)) { // check for the case where REVIEW work is both specialist // and // lead level for same user if (mr.getWorkflowStatus().compareTo(WorkflowStatus.REVIEW_NEW) < 0) { // do nothing, this is the specialist level work } else if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { // do nothing } else { // add the record mapRecord = mr; } } } if (mapRecord == null) { mappingService.close(); throw new Exception( "Failed to retrieve assigned work: no map record found for user " + mapUser.getUserName() + " and concept " + tr.getTerminologyId()); } result.setTerminologyId(mapRecord.getConceptId()); result.setValue(mapRecord.getConceptName()); result.setTerminology(mapRecord.getLastModified().toString()); result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString()); result.setId(mapRecord.getId()); assignedReviewWork.addSearchResult(result); } mappingService.close(); return assignedReviewWork; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAssignedQAWork(org. * ihtsdo.otf.mapping.model.MapProject, org.ihtsdo.otf.mapping.model.MapUser, * java.lang.String, org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAssignedQAWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList assignedReviewWork = new SearchResultListJpa(); PfsParameter localPfsParameter = pfsParameter; // create a blank pfs parameter object if one not passed in if (localPfsParameter == null) localPfsParameter = new PfsParameterJpa(); // create a blank query restriction if none provided if (localPfsParameter.getQueryRestriction() == null) localPfsParameter.setQueryRestriction(""); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = "mapProjectId:" + mapProject.getId(); // add the query terms specific to findAssignedReviewWork // - user and workflow status must exist in the form QA_NEW_userName // or QA_IN_PROGRESS_userName // add terms based on query restriction switch (localPfsParameter.getQueryRestriction()) { case "QA_NEW": fullQuery += " AND userAndWorkflowStatusPairs:QA_NEW_" + mapUser.getUserName(); break; case "QA_IN_PROGRESS": fullQuery += " AND userAndWorkflowStatusPairs:QA_IN_PROGRESS_" + mapUser.getUserName(); break; case "QA_RESOLVED": fullQuery += " AND userAndWorkflowStatusPairs:QA_RESOLVED_" + mapUser.getUserName(); break; default: fullQuery += " AND (userAndWorkflowStatusPairs:QA_NEW_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:QA_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:QA_RESOLVED_" + mapUser.getUserName() + ")"; break; } // don't get path fullQuery += " AND workflowPath:QA_PATH"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); List<TrackingRecord> allResults = ftquery.getResultList(); List<TrackingRecord> results = new ArrayList<>(); if (query == null || query.equals("") || query.equals("null") || query.equals("undefined")) { results = allResults; } else { // remove tracking records that don't have a map record with a label // matching the query for (TrackingRecord tr : allResults) { boolean labelFound = false; for (MapRecord record : getMapRecordsForTrackingRecord(tr)) { for (String label : record.getLabels()) { if (label.equals(query)) { labelFound = true; } } } if (labelFound) { results.add(tr); } } } assignedReviewWork.setTotalCount(results.size()); // apply paging, and sorting if appropriate if (pfsParameter != null && (pfsParameter.getSortField() != null && !pfsParameter.getSortField() .isEmpty())) { // check that specified sort field exists on Concept and is // a string final Field sortField = TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()); if (!sortField.getType().equals(String.class)) { throw new Exception( "findAssignedQAWork error: Referenced sort field is not of type String"); } // allow the field to access the Concept values sortField.setAccessible(true); // sort the list - UNTESTED Collections.sort(results, new Comparator<TrackingRecord>() { @Override public int compare(TrackingRecord c1, TrackingRecord c2) { // if an exception is returned, simply pass equality try { return ((String) sortField.get(c1)).compareTo((String) sortField .get(c2)); } catch (Exception e) { return 0; } } }); } // get the start and end indexes based on paging parameters int startIndex = 0; int toIndex = results.size(); if (pfsParameter != null) { if (pfsParameter.getStartIndex() != -1) { // ensure that start index is within array boundaries startIndex = Math.min(results.size(), pfsParameter.getStartIndex()); // ensure startIndex not less than zero if (startIndex < 0) startIndex = 0; } if (pfsParameter.getMaxResults() != -1) { toIndex = Math.min(results.size(), startIndex + pfsParameter.getMaxResults()); } } for (TrackingRecord tr : results.subList(startIndex, toIndex)) { SearchResult result = new SearchResultJpa(); Set<MapRecord> mapRecords = this.getMapRecordsForTrackingRecord(tr); // get the map record assigned to this user MapRecord mapRecord = null; for (MapRecord mr : mapRecords) { if (mr.getOwner().equals(mapUser)) { if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEEDED)) { // do nothing, this is the specialist level QA work } else if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { // do nothing } else { // this is the user's record mapRecord = mr; } } } if (mapRecord == null) { throw new Exception( "Failed to retrieve assigned work: no map record found for user " + mapUser.getUserName() + " and concept " + tr.getTerminologyId()); } result.setTerminologyId(mapRecord.getConceptId()); result.setValue(mapRecord.getConceptName()); StringBuffer labelBuffer = new StringBuffer(); for (MapRecord record : getMapRecordsForTrackingRecord(tr)) { for (String label : record.getLabels()) { if (labelBuffer.indexOf(label) == -1) labelBuffer.append(";").append(label); } } result.setValue2(labelBuffer.toString()); result.setTerminology(mapRecord.getLastModified().toString()); result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString()); result.setId(mapRecord.getId()); assignedReviewWork.addSearchResult(result); } return assignedReviewWork; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#createQAWork(org.ihtsdo * .otf.mapping.reports.Report) */ @Override public void createQAWork(Report report) throws Exception { if (report.getResults() == null || report.getResults().size() != 1) { throw new Exception("Failed to provide a report with one result set " + report.getId()); } Set<String> conceptIds = new HashSet<>(); for (ReportResultItem resultItem : report.getResults().get(0) .getReportResultItems()) { conceptIds.add(resultItem.getItemId()); } // open the services ContentService contentService = new ContentServiceJpa(); MappingService mappingService = new MappingServiceJpa(); // get the map project and concept MapProject mapProject = mappingService.getMapProject(report.getMapProjectId()); // find the qa user MapUser mapUser = null; for (MapUser user : mappingService.getMapUsers().getMapUsers()) { if (user.getUserName().equals("qa")) mapUser = user; } mappingService.close(); for (String conceptId : conceptIds) { Concept concept = contentService.getConcept(conceptId, mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); mappingService = new MappingServiceJpa(); MapRecordList recordList = mappingService.getMapRecordsForProjectAndConcept(mapProject.getId(), conceptId); // lazy initialize recordList.getMapRecords().size(); mappingService.close(); for (MapRecord mapRecord : recordList.getMapRecords()) { // set the label on the record mapRecord.addLabel(report.getReportDefinition().getName()); // process the workflow action processWorkflowAction(mapProject, concept, mapUser, mapRecord, WorkflowAction.CREATE_QA_RECORD); } } contentService.close(); } /** * Perform workflow actions based on a specified action. * ASSIGN_FROM_INITIAL_RECORD is the only routine that requires a map record * to be passed in All other cases that all required mapping information (e.g. * map records) be current in the database (i.e. updateMapRecord has been * called) * * @param mapProject the map project * @param concept the concept * @param mapUser the map user * @param mapRecord the map record * @param workflowAction the workflow action * @throws Exception the exception */ @Override public void processWorkflowAction(MapProject mapProject, Concept concept, MapUser mapUser, MapRecord mapRecord, WorkflowAction workflowAction) throws Exception { Logger.getLogger(WorkflowServiceJpa.class).info( "Processing workflow action by " + mapUser.getName() + ": " + workflowAction.toString()); if (mapRecord != null) { Logger.getLogger(WorkflowServiceJpa.class).info( " Record attached: " + mapRecord.toString()); } setTransactionPerOperation(true); // instantiate the algorithm handler for this project\ ProjectSpecificAlgorithmHandler algorithmHandler = (ProjectSpecificAlgorithmHandler) Class.forName( mapProject.getProjectSpecificAlgorithmHandlerClass()).newInstance(); algorithmHandler.setMapProject(mapProject); // locate any existing workflow tracking records for this project and // concept // NOTE: Exception handling deliberate, since tracking record may or may // not exist // depending on workflow path TrackingRecord trackingRecord = null; try { trackingRecord = getTrackingRecord(mapProject, concept); } catch (NoResultException e) { trackingRecord = null; } // Validate tracking record if (trackingRecord != null) { // instantiate the handler based on tracking record workflow type AbstractWorkflowPathHandler handler = null; switch (trackingRecord.getWorkflowPath()) { case CONSENSUS_PATH: break; case DRIP_FEED_REVIEW_PATH: break; case FIX_ERROR_PATH: handler = new WorkflowFixErrorPathHandler(); break; case LEGACY_PATH: break; case NON_LEGACY_PATH: handler = new WorkflowNonLegacyPathHandler(); break; case QA_PATH: handler = new WorkflowQaPathHandler(); break; case REVIEW_PROJECT_PATH: handler = new WorkflowReviewProjectPathHandler(); break; default: throw new Exception( "Could not determine workflow handler from tracking record for path: " + trackingRecord.getWorkflowPath().toString()); } ValidationResult result = handler.validateTrackingRecordForActionAndUser(trackingRecord, workflowAction, mapUser); if (!result.isValid()) { Logger.getLogger(WorkflowServiceJpa.class).info(result.toString()); StringBuffer message = new StringBuffer(); message.append("Errors were detected in the workflow for:\n"); message.append(" Project\t: " + mapProject.getName() + "\n"); message.append(" Concept\t: " + concept.getTerminologyId() + "\n"); message.append(" Path:\t " + trackingRecord.getWorkflowPath().toString() + "\n"); message.append(" User\t: " + mapUser.getUserName() + "\n"); message.append(" Action\t: " + workflowAction.toString() + "\n"); message.append("\n"); // record information message.append("Records involved:\n"); message.append(" " + "id\tUser\tWorkflowStatus\n"); for (MapRecord mr : getMapRecordsForTrackingRecord(trackingRecord)) { message.append(" " + mr.getId().toString() + "\t" + mr.getOwner().getUserName() + "\t" + mr.getWorkflowStatus().toString() + "\n"); } message.append("\n"); message.append("Errors reported:\n"); for (String error : result.getErrors()) { message.append(" " + error + "\n"); } message.append("\n"); // log the message Logger.getLogger(WorkflowServiceJpa.class).error( "Workflow error detected\n" + message.toString()); // send email if indicated Properties config = ConfigUtility.getConfigProperties(); String notificationRecipients = config.getProperty("send.notification.recipients"); if (!notificationRecipients.isEmpty()) { OtfEmailHandler emailHandler = new OtfEmailHandler(); emailHandler.sendSimpleEmail(notificationRecipients, config.getProperty("mail.smtp.user"), mapProject.getName() + " Workflow Error Alert, Concept " + concept.getTerminologyId(), message.toString()); } throw new LocalException("Workflow action " + workflowAction.toString() + " could not be performed on concept " + trackingRecord.getTerminologyId()); } } Set<MapRecord> mapRecords = getMapRecordsForTrackingRecord(trackingRecord); // if the record passed in updates an existing record, replace it in the // set if (mapRecord != null && mapRecord.getId() != null) { for (MapRecord mr : mapRecords) { if (mr.getId().equals(mapRecord.getId())) { Logger.getLogger(WorkflowService.class).info( "Replacing record " + mr.toString() + "\n with" + mapRecord.toString()); mapRecords.remove(mr); mapRecords.add(mapRecord); break; } } } // switch on workflow action switch (workflowAction) { case CREATE_QA_RECORD: Logger.getLogger(WorkflowServiceJpa.class).info("CREATE_QA_RECORD"); // if a tracking record is found, perform no action (this record is // already assigned) if (trackingRecord == null) { // expect a map record to be passed in if (mapRecord == null) { throw new Exception( "ProcessWorkflowAction: CREATE_QA_RECORD - Call to assign from intial record must include an existing map record"); } // create a new tracking record for QA_PATH trackingRecord = new TrackingRecordJpa(); trackingRecord.setMapProjectId(mapProject.getId()); trackingRecord.setTerminology(concept.getTerminology()); trackingRecord.setTerminologyVersion(concept.getTerminologyVersion()); trackingRecord.setTerminologyId(concept.getTerminologyId()); trackingRecord.setDefaultPreferredName(concept .getDefaultPreferredName()); trackingRecord.addMapRecordId(mapRecord.getId()); // get the tree positions for this concept and set the sort key // to // the first retrieved ContentService contentService = new ContentServiceJpa(); TreePositionList treePositionsList = contentService.getTreePositionsWithDescendants( concept.getTerminologyId(), concept.getTerminology(), concept.getTerminologyVersion()); // handle inactive concepts - which don't have tree positions if (treePositionsList.getCount() == 0) { trackingRecord.setSortKey(""); } else { trackingRecord.setSortKey(treePositionsList.getTreePositions() .get(0).getAncestorPath()); } trackingRecord.setWorkflowPath(WorkflowPath.QA_PATH); // perform the assign action via the algorithm handler mapRecords = algorithmHandler.assignFromInitialRecord(trackingRecord, mapRecords, mapRecord, mapUser); contentService.close(); // otherwise, this concept is already in the workflow, do nothing } else { // do nothing (label will be added in synchronize) } break; case ASSIGN_FROM_INITIAL_RECORD: Logger.getLogger(WorkflowServiceJpa.class).info( "ASSIGN_FROM_INITIAL_RECORD"); // if a tracking record is found, perform no action (this record is // already assigned) if (trackingRecord == null) { // expect a map record to be passed in if (mapRecord == null) { throw new Exception( "ProcessWorkflowAction: ASSIGN_FROM_INITIAL_RECORD - Call to assign from intial record must include an existing map record"); } // create a new tracking record for FIX_ERROR_PATH or QA_PATH trackingRecord = new TrackingRecordJpa(); trackingRecord.setMapProjectId(mapProject.getId()); trackingRecord.setTerminology(concept.getTerminology()); trackingRecord.setTerminologyVersion(concept.getTerminologyVersion()); trackingRecord.setTerminologyId(concept.getTerminologyId()); trackingRecord.setDefaultPreferredName(concept .getDefaultPreferredName()); trackingRecord.addMapRecordId(mapRecord.getId()); // get the tree positions for this concept and set the sort key // to // the first retrieved ContentService contentService = new ContentServiceJpa(); TreePositionList treePositionsList = contentService.getTreePositionsWithDescendants( concept.getTerminologyId(), concept.getTerminology(), concept.getTerminologyVersion()); // handle inactive concepts - which don't have tree positions if (treePositionsList.getCount() == 0) { trackingRecord.setSortKey(""); } else { trackingRecord.setSortKey(treePositionsList.getTreePositions() .get(0).getAncestorPath()); } trackingRecord.setWorkflowPath(WorkflowPath.FIX_ERROR_PATH); // perform the assign action via the algorithm handler mapRecords = algorithmHandler.assignFromInitialRecord(trackingRecord, mapRecords, mapRecord, mapUser); contentService.close(); } else { throw new LocalException( "Assignment from published record failed -- concept already in workflow"); } break; case ASSIGN_FROM_SCRATCH: // Logger.getLogger(WorkflowServiceJpa.class).info( // "ASSIGN_FROM_SCRATCH"); // expect existing (pre-computed) workflow tracking record if (trackingRecord == null) { throw new Exception("Could not find tracking record for assignment."); } // Team based assignment only matters on NON_LEGACY_PATH and not for // conflict cases // If "concepts" assignment is being done on NON_LEGACY PATH and another // team // member claimed the other role, then leave alone if (trackingRecord.getWorkflowPath() == WorkflowPath.NON_LEGACY_PATH && mapProject.isTeamBased() && trackingRecord.getAssignedUserCount() > 0 && !trackingRecord.getUserAndWorkflowStatusPairs().contains( WorkflowStatus.CONFLICT_DETECTED.toString())) { MappingService service = new MappingServiceJpa(); for (MapUser user : service.getMapUsersForTeam(mapUser.getTeam()) .getMapUsers()) { if (trackingRecord.getAssignedUserNames().contains( user.getUserName())) { service.close(); throw new LocalException( "This concept is already assigned to another member of " + "the same team. Reload the dashboard and try again"); } } service.close(); } // perform the assignment via the algorithm handler mapRecords = algorithmHandler.assignFromScratch(trackingRecord, mapRecords, concept, mapUser); break; case UNASSIGN: Logger.getLogger(WorkflowServiceJpa.class).info("UNASSIGN"); // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: UNASSIGN - Could not find tracking record for unassignment."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: UNASSIGN - User not assigned to record for unassignment request"); // perform the unassign action via the algorithm handler mapRecords = algorithmHandler.unassign(trackingRecord, mapRecords, mapUser); break; case SAVE_FOR_LATER: // Logger.getLogger(WorkflowServiceJpa.class).info("SAVE_FOR_LATER"); // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: SAVE_FOR_LATER - Could not find tracking record."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: SAVE_FOR_LATER - SAVE_FOR_LATER - User not assigned to record"); // Logger.getLogger(WorkflowServiceJpa.class).info( // "Performing action..."); mapRecords = algorithmHandler.saveForLater(trackingRecord, mapRecords, mapUser); break; case FINISH_EDITING: // Logger.getLogger(WorkflowServiceJpa.class).info("FINISH_EDITING"); // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: FINISH_EDITING - Could not find tracking record to be finished."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: FINISH_EDITING - User not assigned to record for finishing request"); // // Logger.getLogger(WorkflowServiceJpa.class).info( // "Performing action..."); // // // perform the action mapRecords = algorithmHandler.finishEditing(trackingRecord, mapRecords, mapUser); break; case PUBLISH: // Logger.getLogger(WorkflowServiceJpa.class).info("FINISH_EDITING"); // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: PUBLISH - Could not find tracking record to be published."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: PUBLISH - User not assigned to tracking record for publish request"); // // Logger.getLogger(WorkflowServiceJpa.class).info( // "Performing action..."); // // // perform the action mapRecords = algorithmHandler.publish(trackingRecord, mapRecords, mapUser); break; case CANCEL: // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: CANCEL - Could not find tracking record to be finished."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: CANCEL - User not assigned to record for cancel request"); mapRecords = algorithmHandler.cancelWork(trackingRecord, mapRecords, mapUser); break; default: throw new Exception("Unknown action requested."); } Logger.getLogger(WorkflowServiceJpa.class).info("Synchronizing..."); // synchronize the map records via helper function Set<MapRecord> syncedRecords = synchronizeMapRecords(trackingRecord, mapRecords); // clear the pointer fields (i.e. ids and names of mapping // objects) trackingRecord.setMapRecordIds(null); trackingRecord.setAssignedUserNames(null); trackingRecord.setUserAndWorkflowStatusPairs(null); // recalculate the pointer fields for (MapRecord mr : syncedRecords) { trackingRecord.addMapRecordId(mr.getId()); trackingRecord.addAssignedUserName(mr.getOwner().getUserName()); trackingRecord.addUserAndWorkflowStatusPair(mr.getOwner().getUserName(), mr.getWorkflowStatus().toString()); } Logger.getLogger(WorkflowServiceJpa.class).info( "Revised tracking record: " + trackingRecord.toString()); // if the tracking record is ready for removal, delete it if ((getWorkflowStatusForTrackingRecord(trackingRecord).equals( WorkflowStatus.READY_FOR_PUBLICATION) || getWorkflowStatusForTrackingRecord( trackingRecord).equals(WorkflowStatus.PUBLISHED)) && trackingRecord.getMapRecordIds().size() == 1) { Logger.getLogger(WorkflowServiceJpa.class).info( " Publication ready, removing tracking record."); removeTrackingRecord(trackingRecord.getId()); // else add the tracking record if new } else if (trackingRecord.getId() == null) { Logger.getLogger(WorkflowServiceJpa.class).info( " New workflow concept, adding tracking record."); addTrackingRecord(trackingRecord); // otherwise update the tracking record } else { Logger.getLogger(WorkflowServiceJpa.class).info( " Still in workflow, updating tracking record."); updateTrackingRecord(trackingRecord); } } /** * Algorithm has gotten needlessly complex due to conflicting service changes * and algorithm handler changes. However, the basic process is this: * * 1) Function takes a set of map records returned from the algorithm handler * These map records may have a hibernate id (updated/unchanged) or not * (added) 2) The passed map records are detached from the persistence * environment. 3) The existing (in database) records are re-retrieved from * the database. Note that this is why the passed map records are detached -- * otherwise they are overwritten. 4) Each record in the detached set is * checked against the 'refreshed' database record set - if the detached * record is not in the set, then it has been added - if the detached record * is in the set, check it for updates - if it has been changed, update it - * if no change, disregard 5) Each record in the 'refreshed' databased record * set is checked against the new set - if the refreshed record is not in the * new set, delete it from the database 6) Return the detached set as * re-synchronized with the database * * Note on naming conventions used in this method: - mapRecords: the set of * records passed in as argument - newRecords: The set of records to be * returned after synchronization - oldRecords: The set of records retrieved * by id from the database for comparison - syncedRecords: The synchronized * set of records for return from this routine * * @param trackingRecord the tracking record * @param mapRecords the map records * @return the sets the * @throws Exception the exception */ @Override public Set<MapRecord> synchronizeMapRecords(TrackingRecord trackingRecord, Set<MapRecord> mapRecords) throws Exception { Set<MapRecord> newRecords = new HashSet<>(); Set<MapRecord> oldRecords = new HashSet<>(); Set<MapRecord> syncedRecords = new HashSet<>(); // detach the currently persisted map records from the workflow service // to avoid overwrite by retrieval of existing records for (MapRecord mr : mapRecords) { manager.detach(mr); newRecords.add(mr); } // Instantiate the mapping service MappingService mappingService = new MappingServiceJpa(); // retrieve the old (existing) records if (trackingRecord.getMapRecordIds() != null) { for (Long id : trackingRecord.getMapRecordIds()) { oldRecords.add(mappingService.getMapRecord(id)); } } // cycle over new records to check for additions or updates for (MapRecord mr : newRecords) { if (getMapRecordInSet(oldRecords, mr.getId()) == null) { // deep copy the detached record into a new // persistence-environment record // this routine also duplicates child collections to avoid // detached object errors MapRecord newRecord = new MapRecordJpa(mr, false); /* * Logger.getLogger(WorkflowServiceJpa.class).info( "Adding record: " + * newRecord.toString()); */ // add the record to the database mappingService.addMapRecord(newRecord); // add the record to the return list syncedRecords.add(newRecord); } // otherwise, check for update else { // if the old map record is changed, update it /* * Logger.getLogger(WorkflowServiceJpa.class).info( "New record: " + * mr.toString()); Logger.getLogger(WorkflowServiceJpa.class).info( * "Old record: " + getMapRecordInSet(oldRecords, * mr.getId()).toString()); */ if (!mr.isEquivalent(getMapRecordInSet(oldRecords, mr.getId()))) { Logger.getLogger(WorkflowServiceJpa.class) .info(" Changed: UPDATING"); mappingService.updateMapRecord(mr); } else { Logger.getLogger(WorkflowServiceJpa.class).info( " No change: NOT UPDATING"); } syncedRecords.add(mr); } } // cycle over old records to check for deletions for (MapRecord mr : oldRecords) { // if old record is not in the new record set, delete it if (getMapRecordInSet(syncedRecords, mr.getId()) == null) { Logger.getLogger(WorkflowServiceJpa.class).info( "Deleting record " + mr.getId()); mappingService.removeMapRecord(mr.getId()); } } // close the service mappingService.close(); return syncedRecords; } /** * Gets the map record in set. * * @param mapRecords the map records * @param mapRecordId the map record id * @return the map record in set */ private MapRecord getMapRecordInSet(Set<MapRecord> mapRecords, Long mapRecordId) { if (mapRecordId == null) return null; for (MapRecord mr : mapRecords) { if (mapRecordId.equals(mr.getId())) return mr; } return null; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#computeWorkflow(org.ihtsdo * .otf.mapping.model.MapProject) */ @Override public void computeWorkflow(MapProject mapProject) throws Exception { Logger.getLogger(WorkflowServiceJpa.class).info( "Start computing workflow for " + mapProject.getName()); // set the transaction parameter and tracking variables setTransactionPerOperation(false); int commitCt = 1000; int trackingRecordCt = 0; // Clear the workflow for this project Logger.getLogger(WorkflowServiceJpa.class).info(" Clear old workflow"); clearWorkflowForMapProject(mapProject); // open the services ContentService contentService = new ContentServiceJpa(); MappingService mappingService = new MappingServiceJpa(); // get the concepts in scope SearchResultList conceptsInScope = mappingService.findConceptsInScope(mapProject.getId(), null); // construct a hashset of concepts in scope Set<String> conceptIds = new HashSet<>(); for (SearchResult sr : conceptsInScope.getIterable()) { conceptIds.add(sr.getTerminologyId()); } Logger.getLogger(WorkflowServiceJpa.class).info( " Concept ids put into hash set: " + conceptIds.size()); // get the current records MapRecordList mapRecords = mappingService.getMapRecordsForMapProject(mapProject.getId()); Logger.getLogger(WorkflowServiceJpa.class).info( "Processing existing records (" + mapRecords.getCount() + " found)"); // instantiate a mapped set of non-published records Map<String, List<MapRecord>> unpublishedRecords = new HashMap<>(); // cycle over the map records, and remove concept ids if a map record is // publication-ready for (MapRecord mapRecord : mapRecords.getIterable()) { // if this map record is published, skip and remove this concept if (mapRecord.getWorkflowStatus().equals( WorkflowStatus.READY_FOR_PUBLICATION) || mapRecord.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED)) { conceptIds.remove(mapRecord.getConceptId()); } // if this concept is in scope, add to workflow else if (conceptIds.contains(mapRecord.getConceptId())) { List<MapRecord> originIds; // if this key does not yet have a constructed list, make one, // otherwise get the existing list if (unpublishedRecords.containsKey(mapRecord.getConceptId())) { originIds = unpublishedRecords.get(mapRecord.getConceptId()); } else { originIds = new ArrayList<>(); } originIds.add(mapRecord); unpublishedRecords.put(mapRecord.getConceptId(), originIds); } } Logger.getLogger(WorkflowServiceJpa.class) .info( " Concepts with no publication-ready map record: " + conceptIds.size()); Logger.getLogger(WorkflowServiceJpa.class).info( " Concepts with unpublished map record content: " + unpublishedRecords.size()); beginTransaction(); // construct the tracking records for unmapped concepts for (String terminologyId : conceptIds) { // retrieve the concept for this result Concept concept = contentService.getConcept(terminologyId, mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); // if concept could not be retrieved, throw exception if (concept == null) { throw new Exception("Failed to retrieve concept " + terminologyId); } // skip inactive concepts if (!concept.isActive()) { Logger.getLogger(WorkflowServiceJpa.class).warn( "Skipped inactive concept " + terminologyId); continue; } // get the tree positions for this concept and set the sort key to // the first retrieved TreePositionList treePositionsList = contentService.getTreePositions(concept.getTerminologyId(), concept.getTerminology(), concept.getTerminologyVersion()); // if no tree position, throw exception if (treePositionsList.getCount() == 0) { throw new Exception("Active concept " + terminologyId + " has no tree positions"); } // create a workflow tracking record for this concept TrackingRecord trackingRecord = new TrackingRecordJpa(); // populate the fields from project and concept trackingRecord.setMapProjectId(mapProject.getId()); trackingRecord.setTerminology(concept.getTerminology()); trackingRecord.setTerminologyId(concept.getTerminologyId()); trackingRecord.setTerminologyVersion(concept.getTerminologyVersion()); trackingRecord.setDefaultPreferredName(concept.getDefaultPreferredName()); trackingRecord.setSortKey(treePositionsList.getTreePositions().get(0) .getAncestorPath()); // add any existing map records to this tracking record Set<MapRecord> mapRecordsForTrackingRecord = new HashSet<>(); if (unpublishedRecords.containsKey(trackingRecord.getTerminologyId())) { for (MapRecord mr : unpublishedRecords.get(trackingRecord .getTerminologyId())) { Logger.getLogger(WorkflowServiceJpa.class).info( " Adding existing map record " + mr.getId() + ", owned by " + mr.getOwner().getUserName() + " to tracking record for " + trackingRecord.getTerminologyId()); trackingRecord.addMapRecordId(mr.getId()); trackingRecord.addAssignedUserName(mr.getOwner().getUserName()); trackingRecord.addUserAndWorkflowStatusPair(mr.getOwner() .getUserName(), mr.getWorkflowStatus().toString()); // add to the local set for workflow calculation mapRecordsForTrackingRecord.add(mr); } } // check if REVISION record is present // check if QA record is present boolean revisionRecordPresent = false; boolean qaRecordPresent = false; for (MapRecord mr : mapRecordsForTrackingRecord) { if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) revisionRecordPresent = true; if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEEDED) || mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEW) || mr.getWorkflowStatus().equals(WorkflowStatus.QA_IN_PROGRESS) || mr.getWorkflowStatus().equals(WorkflowStatus.QA_RESOLVED)) { qaRecordPresent = true; } } // if REVISION found and no qa records, set to FIX_ERROR_PATH if (revisionRecordPresent && !qaRecordPresent) { trackingRecord.setWorkflowPath(WorkflowPath.FIX_ERROR_PATH); // if REVISION found and qa records, set to QA_PATH } else if (revisionRecordPresent && qaRecordPresent) { trackingRecord.setWorkflowPath(WorkflowPath.QA_PATH); // otherwise, set to the WorkflowPath corresponding to the // project WorkflowType } else { if (mapProject.getWorkflowType().equals(WorkflowType.CONFLICT_PROJECT)) trackingRecord.setWorkflowPath(WorkflowPath.NON_LEGACY_PATH); else if (mapProject.getWorkflowType().equals( WorkflowType.REVIEW_PROJECT)) trackingRecord.setWorkflowPath(WorkflowPath.REVIEW_PROJECT_PATH); else { throw new Exception("Could not set workflow path from workflow type " + mapProject.getWorkflowType() + " for records " + trackingRecord.getMapRecordIds().toString()); } } addTrackingRecord(trackingRecord); if (++trackingRecordCt % commitCt == 0) { Logger.getLogger(WorkflowServiceJpa.class).info( " " + trackingRecordCt + " tracking records created"); commit(); beginTransaction(); // close and re-instantiate the content service to prevent // memory buildup from Concept and TreePosition objects contentService.close(); contentService = new ContentServiceJpa(); } } // commit any remaining transactions commit(); // instantiate the full text eneity manager and set version FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); fullTextEntityManager.setProperty("Version", Version.LUCENE_36); // create the indexes Logger.getLogger(WorkflowServiceJpa.class).info( " Creating indexes for TrackingRecordJpa"); fullTextEntityManager.purgeAll(TrackingRecordJpa.class); fullTextEntityManager.flushToIndexes(); fullTextEntityManager.createIndexer(TrackingRecordJpa.class) .batchSizeToLoadObjects(100).cacheMode(CacheMode.NORMAL) .threadsToLoadObjects(4).threadsForSubsequentFetching(8).startAndWait(); Logger.getLogger(WorkflowServiceJpa.class).info("Done."); } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#clearWorkflowForMapProject * (org.ihtsdo.otf.mapping.model.MapProject) */ @Override public void clearWorkflowForMapProject(MapProject mapProject) throws Exception { int commitCt = 0; int commitInterval = 1000; // begin transaction not in transaction-per-operation mode if (!getTransactionPerOperation()) { beginTransaction(); } for (TrackingRecord tr : getTrackingRecordsForMapProject(mapProject) .getTrackingRecords()) { removeTrackingRecord(tr.getId()); if (++commitCt % commitInterval == 0) { // if not a transaction for every operation, commit at intervals if (!getTransactionPerOperation()) { commit(); beginTransaction(); } Logger.getLogger(WorkflowServiceJpa.class).info( " Removed " + commitCt + " tracking records"); } } // commit any last deletions if not in transaction-per-operation mode if (!getTransactionPerOperation()) { commit(); } } // ////////////////////////// // Utility functions // ////////////////////////// /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getMapRecordsForTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public Set<MapRecord> getMapRecordsForTrackingRecord( TrackingRecord trackingRecord) throws Exception { Set<MapRecord> mapRecords = new HashSet<>(); MappingService mappingService = new MappingServiceJpa(); if (trackingRecord != null && trackingRecord.getMapRecordIds() != null) { for (Long id : trackingRecord.getMapRecordIds()) { mapRecords.add(mappingService.getMapRecord(id)); } } mappingService.close(); return mapRecords; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getMapUsersForTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public MapUserList getMapUsersForTrackingRecord(TrackingRecord trackingRecord) throws Exception { return getMapUsersFromMapRecords(getMapRecordsForTrackingRecord(trackingRecord)); } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getWorkflowStatusForTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public WorkflowStatus getWorkflowStatusForTrackingRecord( TrackingRecord trackingRecord) throws Exception { return getWorkflowStatusFromMapRecords(getMapRecordsForTrackingRecord(trackingRecord)); } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getLowestWorkflowStatusForTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public WorkflowStatus getLowestWorkflowStatusForTrackingRecord( TrackingRecord trackingRecord) throws Exception { return getLowestWorkflowStatusFromMapRecords(getMapRecordsForTrackingRecord(trackingRecord)); } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#getMapUsersFromMapRecords * (java.util.Set) */ @Override public MapUserList getMapUsersFromMapRecords(Set<MapRecord> mapRecords) { MapUserList mapUserList = new MapUserListJpa(); for (MapRecord mr : mapRecords) { mapUserList.addMapUser(mr.getOwner()); } return mapUserList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getWorkflowStatusFromMapRecords(java.util.Set) */ @Override public WorkflowStatus getWorkflowStatusFromMapRecords( Set<MapRecord> mapRecords) { WorkflowStatus workflowStatus = WorkflowStatus.NEW; for (MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().compareTo(workflowStatus) > 0) workflowStatus = mr.getWorkflowStatus(); } return workflowStatus; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getLowestWorkflowStatusFromMapRecords(java.util.Set) */ @Override public WorkflowStatus getLowestWorkflowStatusFromMapRecords( Set<MapRecord> mapRecords) { WorkflowStatus workflowStatus = WorkflowStatus.REVISION; for (MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().compareTo(workflowStatus) < 0) workflowStatus = mr.getWorkflowStatus(); } return workflowStatus; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#computeWorkflowStatusErrors * (org.ihtsdo.otf.mapping.model.MapProject) */ @Override public List<String> computeWorkflowStatusErrors(MapProject mapProject) throws Exception { List<String> results = new ArrayList<>(); // instantiate the mapping service MappingService mappingService = new MappingServiceJpa(); Logger.getLogger(WorkflowServiceJpa.class).info( "Retrieving tracking records for project " + mapProject.getId() + ", " + mapProject.getName()); // instantiate a copy of all workflow handlers WorkflowNonLegacyPathHandler nonLegacyHandler = new WorkflowNonLegacyPathHandler(); WorkflowFixErrorPathHandler fixErrorHandler = new WorkflowFixErrorPathHandler(); WorkflowQaPathHandler qaHandler = new WorkflowQaPathHandler(); WorkflowReviewProjectPathHandler reviewHandler = new WorkflowReviewProjectPathHandler(); // get all the tracking records for this project TrackingRecordList trackingRecords = this.getTrackingRecordsForMapProject(mapProject); // construct a set of terminology ids for which a tracking record exists Set<String> terminologyIdsWithTrackingRecord = new HashSet<>(); for (TrackingRecord trackingRecord : trackingRecords.getTrackingRecords()) { terminologyIdsWithTrackingRecord.add(trackingRecord.getTerminologyId()); // instantiate the handler based on tracking record workflow type AbstractWorkflowPathHandler handler = null; switch (trackingRecord.getWorkflowPath()) { case CONSENSUS_PATH: break; case DRIP_FEED_REVIEW_PATH: break; case FIX_ERROR_PATH: handler = fixErrorHandler; break; case LEGACY_PATH: break; case NON_LEGACY_PATH: handler = nonLegacyHandler; break; case QA_PATH: handler = qaHandler; break; case REVIEW_PROJECT_PATH: handler = reviewHandler; break; default: results .add("ERROR: Could not determine workflow handler from tracking record for concept " + trackingRecord.getTerminologyId() + " for path: " + trackingRecord.getWorkflowPath().toString()); } ValidationResult result = handler.validateTrackingRecord(trackingRecord); if (!result.isValid()) { results .add(constructErrorMessageStringForTrackingRecordAndValidationResult( trackingRecord, result)); } } Logger.getLogger(WorkflowServiceJpa.class).info( " Checking map records for " + mapProject.getId() + ", " + mapProject.getName()); // second, check all records for non-publication ready content without // tracking record, skip inactive concepts ContentService contentService = new ContentServiceJpa(); for (MapRecord mapRecord : mappingService.getMapRecordsForMapProject( mapProject.getId()).getMapRecords()) { // if not publication ready if (!mapRecord.getWorkflowStatus().equals( WorkflowStatus.READY_FOR_PUBLICATION) && !mapRecord.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED)) { Concept concept = contentService.getConcept(mapRecord.getConceptId(), mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); // if no tracking record found for this concept // and the concept is active, then report an error if (!terminologyIdsWithTrackingRecord .contains(mapRecord.getConceptId()) && concept != null && concept.isActive()) { results.add("Map Record " + mapRecord.getId() + ": " + mapRecord.getWorkflowStatus() + " but no tracking record exists (Concept " + mapRecord.getConceptId() + " " + mapRecord.getConceptName()); } } } mappingService.close(); contentService.close(); return results; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#computeUntrackedMapRecords * (org.ihtsdo.otf.mapping.model.MapProject) */ @Override public void computeUntrackedMapRecords(MapProject mapProject) throws Exception { MappingService mappingService = new MappingServiceJpa(); Logger.getLogger(WorkflowServiceJpa.class).info( "Retrieving map records for project " + mapProject.getId() + ", " + mapProject.getName()); MapRecordList mapRecordsInProject = mappingService.getMapRecordsForMapProject(mapProject.getId()); Logger.getLogger(WorkflowServiceJpa.class).info( " " + mapRecordsInProject.getCount() + " retrieved"); // set the reporting interval based on number of tracking records int nObjects = 0; int nMessageInterval = (int) Math.floor(mapRecordsInProject.getCount() / 10); Set<MapRecord> recordsUntracked = new HashSet<>(); for (MapRecord mr : mapRecordsInProject.getIterable()) { TrackingRecord tr = this.getTrackingRecordForMapProjectAndConcept(mapProject, mr.getConceptId()); // if no tracking record, check that this is a publication ready map // record if (tr == null) { if (!mr.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED) && !mr.getWorkflowStatus().equals( WorkflowStatus.READY_FOR_PUBLICATION)) { recordsUntracked.add(mr); } } if (++nObjects % nMessageInterval == 0) { Logger.getLogger(WorkflowServiceJpa.class).info( " " + nObjects + " records processed, " + recordsUntracked.size() + " unpublished map records without tracking record"); } } mappingService.close(); } // ///////////////////////////////////// // FEEDBACK FUNCTIONS // ///////////////////////////////////// /** * Adds the feedback. * * @param feedback the feedback * @return the feedback */ @Override public Feedback addFeedback(Feedback feedback) { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(feedback); tx.commit(); } else { manager.persist(feedback); } return feedback; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getFeedbacks() */ @Override @SuppressWarnings("unchecked") public FeedbackList getFeedbacks() { List<Feedback> feedbacks = null; // construct query javax.persistence.Query query = manager.createQuery("select m from FeedbackJpa m"); // Try query feedbacks = query.getResultList(); FeedbackListJpa feedbackList = new FeedbackListJpa(); feedbackList.setFeedbacks(feedbacks); feedbackList.setTotalCount(feedbacks.size()); return feedbackList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.MappingService#addFeedbackConversation * (org.ihtsdo.otf.mapping.model.FeedbackConversation) */ @Override public FeedbackConversation addFeedbackConversation( FeedbackConversation conversation) { // set the conversation of all elements of this conversation conversation.assignToChildren(); if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(conversation); tx.commit(); } else { manager.persist(conversation); } return conversation; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#updateFeedbackConversation * (org.ihtsdo.otf.mapping.model.FeedbackConversation) */ @Override public void updateFeedbackConversation(FeedbackConversation conversation) { // set the conversation of all elements of this conversation conversation.assignToChildren(); if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(conversation); tx.commit(); // manager.close(); } else { manager.merge(conversation); } } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#getFeedbackConversation * (java.lang.Long) */ @SuppressWarnings("unchecked") @Override public FeedbackConversation getFeedbackConversation(Long id) throws Exception { // construct query javax.persistence.Query query = manager .createQuery("select m from FeedbackConversationJpa m where mapRecordId = :recordId"); // Try query query.setParameter("recordId", id); List<FeedbackConversation> feedbackConversations = query.getResultList(); if (feedbackConversations != null && feedbackConversations.size() > 0) handleFeedbackConversationLazyInitialization(feedbackConversations.get(0)); Logger.getLogger(this.getClass()).debug( "Returning feedback conversation id... " + ((feedbackConversations != null) ? id.toString() : "null")); return feedbackConversations != null && feedbackConversations.size() > 0 ? feedbackConversations.get(0) : null; } /** * Handle feedback conversation lazy initialization. * * @param feedbackConversation the feedback conversation */ private void handleFeedbackConversationLazyInitialization( FeedbackConversation feedbackConversation) { // handle all lazy initializations for (Feedback feedback : feedbackConversation.getFeedbacks()) { feedback.getSender().getName(); for (MapUser recipient : feedback.getRecipients()) recipient.getName(); for (MapUser viewedBy : feedback.getViewedBy()) viewedBy.getName(); } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getFeedbackConversationsForConcept(java.lang.Long, java.lang.String) */ @SuppressWarnings("unchecked") @Override public FeedbackConversationList getFeedbackConversationsForConcept( Long mapProjectId, String terminologyId) throws Exception { MappingService mappingService = new MappingServiceJpa(); MapProject mapProject = mappingService.getMapProject(mapProjectId); mappingService.close(); javax.persistence.Query query = manager .createQuery( "select m from FeedbackConversationJpa m where terminology = :terminology and" + " terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId); List<FeedbackConversation> feedbackConversations = query.getResultList(); for (FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(feedbackConversations.size()); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * findFeedbackConversationsForProject(java.lang.Long, java.lang.String, * org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings({ "unchecked" }) @Override public FeedbackConversationList findFeedbackConversationsForProject( Long mapProjectId, String userName, String query, PfsParameter pfsParameter) throws Exception { MappingService mappingService = new MappingServiceJpa(); MapProject mapProject = mappingService.getMapProject(mapProjectId); mappingService.close(); // remove from the query the viewed parameter, if it exists // viewed will be handled later because it is on the Feedback object, // not the FeedbackConversation object String modifiedQuery = ""; if (query.contains(" AND viewed:false")) modifiedQuery = query.replace(" AND viewed:false", ""); else if (query.contains(" AND viewed:true")) modifiedQuery = query.replace(" AND viewed:true", ""); else modifiedQuery = query; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), modifiedQuery); fullQuery += " AND terminology:" + mapProject.getSourceTerminology() + " AND terminologyVersion:" + mapProject.getSourceTerminologyVersion() + " AND " + "( feedbacks.sender.userName:" + userName + " OR " + "feedbacks.recipients.userName:" + userName + ")"; Logger.getLogger(MappingServiceJpa.class).info(fullQuery); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct luceneQuery based on URL format QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(FeedbackConversationJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, FeedbackConversationJpa.class); // Sort Options -- in order of priority // (1) if a sort field is specified by pfs parameter, use it // (2) if a query has been specified, use nothing (lucene relevance // default) // (3) if a query has not been specified, sort by conceptId String sortField = "lastModified"; if (pfsParameter != null && pfsParameter.getSortField() != null && !pfsParameter.getSortField().isEmpty()) { ftquery.setSort(new Sort(new SortField(pfsParameter.getSortField(), SortField.STRING, true))); } else if (pfsParameter != null && pfsParameter.getQueryRestriction() != null && !pfsParameter.getQueryRestriction().isEmpty()) { // do nothing } else { ftquery .setSort(new Sort(new SortField(sortField, SortField.STRING, true))); } // get the results int totalCount = ftquery.getResultSize(); if (pfsParameter != null && !query.contains("viewed")) { ftquery.setFirstResult(pfsParameter.getStartIndex()); ftquery.setMaxResults(pfsParameter.getMaxResults()); } List<FeedbackConversation> feedbackConversations = ftquery.getResultList(); if (pfsParameter != null && query.contains("viewed")) { List<FeedbackConversation> conversationsToKeep = new ArrayList<>(); for (FeedbackConversation fc : feedbackConversations) { if (query.contains("viewed:false")) { for (Feedback feedback : fc.getFeedbacks()) { Set<MapUser> alreadyViewedBy = feedback.getViewedBy(); boolean found = false; for (MapUser user : alreadyViewedBy) { if (user.getUserName().equals(userName)) found = true; } if (!found) conversationsToKeep.add(fc); } } if (query.contains("viewed:true")) { boolean found = false; for (Feedback feedback : fc.getFeedbacks()) { Set<MapUser> alreadyViewedBy = feedback.getViewedBy(); for (MapUser user : alreadyViewedBy) { if (user.getUserName().equals(userName)) { found = true; break; } } if (!found) break; } if (found) conversationsToKeep.add(fc); } } totalCount = conversationsToKeep.size(); feedbackConversations.clear(); for (int i = pfsParameter.getStartIndex(); i < pfsParameter .getStartIndex() + pfsParameter.getMaxResults() && i < conversationsToKeep.size(); i++) { feedbackConversations.add(conversationsToKeep.get(i)); } } Logger.getLogger(this.getClass()).debug( Integer.toString(feedbackConversations.size()) + " feedbackConversations retrieved"); for (FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(totalCount); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getFeedbackConversationsForRecord(java.lang.Long) */ @SuppressWarnings("unchecked") @Override public FeedbackConversationList getFeedbackConversationsForRecord( Long mapRecordId) throws Exception { javax.persistence.Query query = manager .createQuery( "select m from FeedbackConversationJpa m where mapRecordId=:mapRecordId") .setParameter("mapRecordId", mapRecordId); List<FeedbackConversation> feedbackConversations = query.getResultList(); for (FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(feedbackConversations.size()); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#getFeedbackErrorsForRecord * (org.ihtsdo.otf.mapping.model.MapRecord) */ @Override public FeedbackList getFeedbackErrorsForRecord(MapRecord mapRecord) throws Exception { List<Feedback> feedbacksWithError = new ArrayList<>(); // find any feedback conersations for this record FeedbackConversationList conversations = this.getFeedbackConversationsForRecord(mapRecord.getId()); // cycle over feedbacks for (FeedbackConversation conversation : conversations.getIterable()) { for (Feedback feedback : conversation.getFeedbacks()) { if (feedback.getIsError()) { feedbacksWithError.add(feedback); } } } FeedbackList feedbackList = new FeedbackListJpa(); feedbackList.setFeedbacks(feedbacksWithError); return feedbackList; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#sendFeedbackEmail(java. * lang.String, java.lang.String, java.lang.String, java.lang.String, * java.lang.String, java.lang.String) */ @Override public void sendFeedbackEmail(String name, String email, String conceptId, String conceptName, String refSetId, String message) throws Exception { OtfEmailHandler emailHandler = new OtfEmailHandler(); // get to address from config.properties Properties config = ConfigUtility.getConfigProperties(); String feedbackUserRecipient = config.getProperty("mail.smtp.to.feedback.user"); String baseUrlWebapp = config.getProperty("base.url.webapp"); String conceptUrl = baseUrlWebapp + "/#/record/conceptId/" + conceptId + "/autologin?refSetId=" + refSetId; emailHandler.sendSimpleEmail(feedbackUserRecipient, email, "Mapping Tool User Feedback: " + conceptId + "-" + conceptName, "User: " + name + "<br>" + "Email: " + email + "<br>" + "Concept: <a href=" + conceptUrl + ">" + conceptId + "- " + conceptName + "</a><br><br>" + message); } /** * Construct error message string for tracking record and validation result. * * @param trackingRecord the tracking record * @param result the result * @return the string * @throws Exception the exception */ private String constructErrorMessageStringForTrackingRecordAndValidationResult( TrackingRecord trackingRecord, ValidationResult result) throws Exception { StringBuffer message = new StringBuffer(); message.append("ERROR for Concept " + trackingRecord.getTerminologyId() + ", Path " + trackingRecord.getWorkflowPath().toString() + "\n"); // record information message.append(" Records involved:\n"); message.append(" " + "id\tUser\tWorkflowStatus\n"); for (MapRecord mr : getMapRecordsForTrackingRecord(trackingRecord)) { message.append(" " + mr.getId().toString() + "\t" + mr.getOwner().getUserName() + "\t" + mr.getWorkflowStatus().toString() + "\n"); } message.append(" Errors reported:\n"); for (String error : result.getErrors()) { message.append(" " + error + "\n"); } return message.toString(); } }
jpa-services/src/main/java/org/ihtsdo/otf/mapping/jpa/services/WorkflowServiceJpa.java
/* * Copyright 2015 West Coast Informatics, LLC */ package org.ihtsdo.otf.mapping.jpa.services; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import org.apache.log4j.Logger; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.util.ReaderUtil; import org.apache.lucene.util.Version; import org.hibernate.CacheMode; import org.hibernate.search.SearchFactory; import org.hibernate.search.indexes.IndexReaderAccessor; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.Search; import org.ihtsdo.otf.mapping.helpers.FeedbackConversationList; import org.ihtsdo.otf.mapping.helpers.FeedbackConversationListJpa; import org.ihtsdo.otf.mapping.helpers.FeedbackList; import org.ihtsdo.otf.mapping.helpers.FeedbackListJpa; import org.ihtsdo.otf.mapping.helpers.LocalException; import org.ihtsdo.otf.mapping.helpers.MapRecordList; import org.ihtsdo.otf.mapping.helpers.MapUserList; import org.ihtsdo.otf.mapping.helpers.MapUserListJpa; import org.ihtsdo.otf.mapping.helpers.PfsParameter; import org.ihtsdo.otf.mapping.helpers.PfsParameterJpa; import org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler; import org.ihtsdo.otf.mapping.helpers.SearchResult; import org.ihtsdo.otf.mapping.helpers.SearchResultJpa; import org.ihtsdo.otf.mapping.helpers.SearchResultList; import org.ihtsdo.otf.mapping.helpers.SearchResultListJpa; import org.ihtsdo.otf.mapping.helpers.TrackingRecordList; import org.ihtsdo.otf.mapping.helpers.TrackingRecordListJpa; import org.ihtsdo.otf.mapping.helpers.TreePositionList; import org.ihtsdo.otf.mapping.helpers.ValidationResult; import org.ihtsdo.otf.mapping.helpers.WorkflowAction; import org.ihtsdo.otf.mapping.helpers.WorkflowPath; import org.ihtsdo.otf.mapping.helpers.WorkflowStatus; import org.ihtsdo.otf.mapping.helpers.WorkflowType; import org.ihtsdo.otf.mapping.jpa.FeedbackConversationJpa; import org.ihtsdo.otf.mapping.jpa.MapRecordJpa; import org.ihtsdo.otf.mapping.jpa.handlers.AbstractWorkflowPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowFixErrorPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowNonLegacyPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowQaPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowReviewProjectPathHandler; import org.ihtsdo.otf.mapping.model.Feedback; import org.ihtsdo.otf.mapping.model.FeedbackConversation; import org.ihtsdo.otf.mapping.model.MapProject; import org.ihtsdo.otf.mapping.model.MapRecord; import org.ihtsdo.otf.mapping.model.MapUser; import org.ihtsdo.otf.mapping.reports.Report; import org.ihtsdo.otf.mapping.reports.ReportResultItem; import org.ihtsdo.otf.mapping.rf2.Concept; import org.ihtsdo.otf.mapping.services.ContentService; import org.ihtsdo.otf.mapping.services.MappingService; import org.ihtsdo.otf.mapping.services.WorkflowService; import org.ihtsdo.otf.mapping.services.helpers.ConfigUtility; import org.ihtsdo.otf.mapping.services.helpers.OtfEmailHandler; import org.ihtsdo.otf.mapping.workflow.TrackingRecord; import org.ihtsdo.otf.mapping.workflow.TrackingRecordJpa; import org.ihtsdo.otf.mapping.workflow.WorkflowException; import org.ihtsdo.otf.mapping.workflow.WorkflowExceptionJpa; /** * Default workflow service implementation. */ public class WorkflowServiceJpa extends RootServiceJpa implements WorkflowService { /** The map record indexed field names. */ protected static Set<String> trackingRecordFieldNames; /** * Instantiates an empty {@link WorkflowServiceJpa}. * * @throws Exception the exception */ public WorkflowServiceJpa() throws Exception { super(); if (trackingRecordFieldNames == null) { initializeFieldNames(); } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.RootService#initializeFieldNames() */ @Override public synchronized void initializeFieldNames() throws Exception { trackingRecordFieldNames = new HashSet<>(); EntityManager manager = factory.createEntityManager(); FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(manager); IndexReaderAccessor indexReaderAccessor = fullTextEntityManager.getSearchFactory().getIndexReaderAccessor(); Set<String> indexedClassNames = fullTextEntityManager.getSearchFactory().getStatistics() .getIndexedClassNames(); for (String indexClass : indexedClassNames) { if (indexClass.indexOf("TrackingRecordJpa") != -1) { Logger.getLogger(ContentServiceJpa.class).info( "FOUND TrackingRecordJpa index"); IndexReader indexReader = indexReaderAccessor.open(indexClass); try { for (FieldInfo info : ReaderUtil.getMergedFieldInfos(indexReader)) { trackingRecordFieldNames.add(info.name); } } finally { indexReaderAccessor.close(indexReader); } } } fullTextEntityManager.close(); } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#addTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public TrackingRecord addTrackingRecord(TrackingRecord trackingRecord) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(trackingRecord); tx.commit(); } else { manager.persist(trackingRecord); } return trackingRecord; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#removeTrackingRecord * (java.lang.Long) */ @Override public void removeTrackingRecord(Long trackingRecordId) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); TrackingRecord ma = manager.find(TrackingRecordJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } tx.commit(); } else { TrackingRecord ma = manager.find(TrackingRecordJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#updateTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public void updateTrackingRecord(TrackingRecord record) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(record); tx.commit(); } else { manager.merge(record); } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getTrackingRecords () */ @SuppressWarnings("unchecked") @Override public TrackingRecordList getTrackingRecords() throws Exception { TrackingRecordListJpa trackingRecordList = new TrackingRecordListJpa(); trackingRecordList.setTrackingRecords(manager.createQuery( "select tr from TrackingRecordJpa tr").getResultList()); return trackingRecordList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getTrackingRecordForMapProjectAndConcept * (org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.rf2.Concept) */ @Override public TrackingRecord getTrackingRecordForMapProjectAndConcept( MapProject mapProject, Concept concept) { try { return (TrackingRecord) manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", concept.getTerminology()) .setParameter("terminologyVersion", concept.getTerminologyVersion()) .setParameter("terminologyId", concept.getTerminologyId()) .getSingleResult(); } catch (Exception e) { return null; } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getTrackingRecordForMapProjectAndConcept * (org.ihtsdo.otf.mapping.model.MapProject, java.lang.String) */ @Override public TrackingRecord getTrackingRecordForMapProjectAndConcept( MapProject mapProject, String terminologyId) { try { return (TrackingRecord) manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId).getSingleResult(); } catch (Exception e) { return null; } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getTrackingRecordsForMapProject (org.ihtsdo.otf.mapping.model.MapProject) */ @SuppressWarnings("unchecked") @Override public TrackingRecordList getTrackingRecordsForMapProject( MapProject mapProject) throws Exception { TrackingRecordListJpa trackingRecordList = new TrackingRecordListJpa(); javax.persistence.Query query = manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId") .setParameter("mapProjectId", mapProject.getId()); trackingRecordList.setTrackingRecords(query.getResultList()); return trackingRecordList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getTrackingRecord * (org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.rf2.Concept) */ @Override public TrackingRecord getTrackingRecord(MapProject mapProject, Concept concept) throws Exception { javax.persistence.Query query = manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminologyId", concept.getTerminologyId()); return (TrackingRecord) query.getSingleResult(); } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#addWorkflowException * (org.ihtsdo.otf.mapping.workflow.WorkflowException) */ @Override public WorkflowException addWorkflowException(WorkflowException trackingRecord) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(trackingRecord); tx.commit(); } else { manager.persist(trackingRecord); } return trackingRecord; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#removeWorkflowException * (java.lang.Long) */ @Override public void removeWorkflowException(Long trackingRecordId) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); WorkflowException ma = manager.find(WorkflowExceptionJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } tx.commit(); } else { WorkflowException ma = manager.find(WorkflowExceptionJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } } } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#updateWorkflowException * (org.ihtsdo.otf.mapping.workflow.WorkflowException) */ @Override public void updateWorkflowException(WorkflowException workflowException) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(workflowException); tx.commit(); } else { manager.merge(workflowException); } } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#getWorkflowException(org * .ihtsdo.otf.mapping.model.MapProject, java.lang.String) */ @Override public WorkflowException getWorkflowException(MapProject mapProject, String terminologyId) { javax.persistence.Query query = manager .createQuery( "select we from WorkflowExceptionJpa we where mapProjectId = :mapProjectId" + " and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId); // try to get the expected single result try { return (WorkflowException) query.getSingleResult(); } catch (NoResultException e) { return null; } } /** * Construct map project id query. * * @param mapProjectId the map project id * @param query the query * @return the string */ private static String constructMapProjectIdQuery(Long mapProjectId, String query) { String fullQuery; // if no filter supplied, return query based on map project id only if (query == null || query.equals("") || query.equals("null") || query.equals("undefined")) { fullQuery = "mapProjectId:" + mapProjectId; return fullQuery; } // Pre-treatment: Find any lower-case boolean operators and set to // uppercase // ////////////////// // Basic algorithm: // // 1) add whitespace breaks to operators // 2) split query on whitespace // 3) cycle over terms in split query to find quoted material, add each // term/quoted term to parsed terms\ // a) special case: quoted term after a : // 3) cycle over terms in parsed terms // a) if an operator/parantheses, pass through unchanged (send to upper // case // for boolean) // b) if a fielded query (i.e. field:value), pass through unchanged // c) if not, construct query on all fields with this term // list of escape terms (i.e. quotes, operators) to be fed into query // untouched String escapeTerms = "\\+|\\-|\"|\\(|\\)"; String booleanTerms = "and|AND|or|OR|not|NOT"; // first cycle over the string to add artificial breaks before and after // control characters String queryStrMod = query; queryStrMod = queryStrMod.replace("(", " ( "); queryStrMod = queryStrMod.replace(")", " ) "); queryStrMod = queryStrMod.replace("\"", " \" "); queryStrMod = queryStrMod.replace("+", " + "); queryStrMod = queryStrMod.replace("-", " - "); // remove any leading or trailing whitespace (otherwise first/last null // term // bug) queryStrMod = queryStrMod.trim(); // split the string by white space and single-character operators String[] terms = queryStrMod.split("\\s+"); // merge items between quotation marks boolean exprInQuotes = false; List<String> parsedTerms = new ArrayList<>(); String currentTerm = ""; // cycle over terms to identify quoted (i.e. non-parsed) terms for (int i = 0; i < terms.length; i++) { // if an open quote is detected if (terms[i].equals("\"")) { if (exprInQuotes) { // special case check: fielded term. Impossible for first // term to be // fielded. if (parsedTerms.size() == 0) { parsedTerms.add("\"" + currentTerm + "\""); } else { String lastParsedTerm = parsedTerms.get(parsedTerms.size() - 1); // if last parsed term ended with a colon, append this // term to the // last parsed term if (lastParsedTerm.endsWith(":")) { parsedTerms.set(parsedTerms.size() - 1, lastParsedTerm + "\"" + currentTerm + "\""); } else { parsedTerms.add("\"" + currentTerm + "\""); } } // reset current term currentTerm = ""; exprInQuotes = false; } else { exprInQuotes = true; } // if no quote detected } else { // if inside quotes, continue building term if (exprInQuotes) { currentTerm = currentTerm == "" ? terms[i] : currentTerm + " " + terms[i]; // otherwise, add to parsed list } else { parsedTerms.add(terms[i]); } } } for (String s : parsedTerms) { Logger.getLogger(MappingServiceJpa.class).debug(" " + s); } // cycle over terms to construct query fullQuery = ""; for (int i = 0; i < parsedTerms.size(); i++) { // if not the first term AND the last term was not an escape term // add whitespace separator if (i != 0 && !parsedTerms.get(i - 1).matches(escapeTerms)) { fullQuery += " "; } /* * fullQuery += (i == 0 ? // check for first term "" : // -> if first * character, add nothing parsedTerms.get(i-1).matches(escapeTerms) ? // * check if last term was an escape character "": // -> if last term was * an escape character, add nothing " "); // -> otherwise, add a * separating space */ // if an escape character/sequence, add this term unmodified if (parsedTerms.get(i).matches(escapeTerms)) { fullQuery += parsedTerms.get(i); // else if a boolean character, add this term in upper-case form // (i.e. // lucene format) } else if (parsedTerms.get(i).matches(booleanTerms)) { fullQuery += parsedTerms.get(i).toUpperCase(); // else if already a field-specific query term, add this term // unmodified } else if (parsedTerms.get(i).contains(":")) { fullQuery += parsedTerms.get(i); // otherwise, treat as unfielded query term } else { // open parenthetical term fullQuery += "("; // add fielded query for each indexed term, separated by OR Iterator<String> namesIter = trackingRecordFieldNames.iterator(); while (namesIter.hasNext()) { fullQuery += namesIter.next() + ":" + parsedTerms.get(i); if (namesIter.hasNext()) fullQuery += " OR "; } // close parenthetical term fullQuery += ")"; } // if further terms remain in the sequence if (!(i == parsedTerms.size() - 1)) { // Add a separating OR iff: // - this term is not an escape character // - this term is not a boolean term // - next term is not a boolean term if (!parsedTerms.get(i).matches(escapeTerms) && !parsedTerms.get(i).matches(booleanTerms) && !parsedTerms.get(i + 1).matches(booleanTerms)) { fullQuery += " OR"; } } } // add parantheses and map project constraint fullQuery = "(" + fullQuery + ")" + " AND mapProjectId:" + mapProjectId; Logger.getLogger(MappingServiceJpa.class).debug("Full query: " + fullQuery); return fullQuery; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAvailableWork(org.ihtsdo * .otf.mapping.model.MapProject, org.ihtsdo.otf.mapping.model.MapUser, * java.lang.String, org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAvailableWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList availableWork = new SearchResultListJpa(); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAvailableWork // - must be NON_LEGACY PATH // - any tracking record with no assigned users is by definition // available // - any tracking record with one assigned user on NON_LEGACY_PATH with // workflowstatus NEW, EDITING_IN_PROGRESS, or EDITING_DONE. Assigned // user must not be this user switch (mapProject.getWorkflowType()) { case CONFLICT_PROJECT: fullQuery += " AND workflowPath:NON_LEGACY_PATH"; // Handle "team" based assignment if (mapProject.isTeamBased() && mapUser.getTeam() != null && !mapUser.getTeam().isEmpty()) { // Use "AND NOT" clauses for all members matching my user's team. MappingService service = new MappingServiceJpa(); fullQuery += " AND (assignedUserCount:0 OR (assignedUserCount:1 "; for (MapUser user : service.getMapUsersForTeam(mapUser.getTeam()) .getMapUsers()) { fullQuery += " AND NOT assignedUserNames:" + user.getUserName(); } fullQuery += ") )"; service.close(); } else { fullQuery += " AND (assignedUserCount:0 OR " + "(assignedUserCount:1 AND NOT assignedUserNames:" + mapUser.getUserName() + "))"; } break; case REVIEW_PROJECT: fullQuery += " AND workflowPath:REVIEW_PROJECT_PATH"; fullQuery += " AND assignedUserCount:0"; break; default: throw new Exception("Invalid workflow type specified for project " + mapProject.getWorkflowType()); } QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); availableWork.setTotalCount(ftquery.getResultSize()); if (pfsParameter.getStartIndex() != -1 && pfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(pfsParameter.getStartIndex()); ftquery.setMaxResults(pfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (pfsParameter.getSortField() != null && !pfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()) .getType().equals(String.class)) { ftquery.setSort(new Sort(new SortField(pfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); result.setTerminologyId(tr.getTerminologyId()); result.setValue(tr.getDefaultPreferredName()); result.setId(tr.getId()); availableWork.addSearchResult(result); } return availableWork; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getAvailableConflicts * (org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.model.MapUser) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAvailableConflicts(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList availableConflicts = new SearchResultListJpa(); // if not a conflict project, return empty list if (!mapProject.getWorkflowType().equals(WorkflowType.CONFLICT_PROJECT)) { return availableConflicts; } FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAvailableConflicts // - user and workflowStatus pair of CONFLICT_DETECTED_userName exists // - user and workflowStatus pairs of // CONFLICT_NEW/CONFLICT_IN_PROGRESS_userName does not exist fullQuery += " AND userAndWorkflowStatusPairs:CONFLICT_DETECTED_*"; fullQuery += " AND NOT (userAndWorkflowStatusPairs:CONFLICT_NEW_* OR userAndWorkflowStatusPairs:CONFLICT_IN_PROGRESS_* OR userAndWorkflowStatusPairs:CONFLICT_RESOLVED_*)"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); availableConflicts.setTotalCount(ftquery.getResultSize()); if (pfsParameter.getStartIndex() != -1 && pfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(pfsParameter.getStartIndex()); ftquery.setMaxResults(pfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (pfsParameter.getSortField() != null && !pfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()) .getType().equals(String.class)) { ftquery.setSort(new Sort(new SortField(pfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); result.setTerminologyId(tr.getTerminologyId()); result.setValue(tr.getDefaultPreferredName()); result.setId(tr.getId()); availableConflicts.addSearchResult(result); } return availableConflicts; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAvailableQAWork(org * .ihtsdo.otf.mapping.model.MapProject, org.ihtsdo.otf.mapping.model.MapUser, * java.lang.String, org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAvailableQAWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList availableQAWork = new SearchResultListJpa(); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = "mapProjectId:" + mapProject.getId(); // add the query terms specific to findAvailableReviewWork // - a user (any) and workflowStatus pair of QA_NEEDED_userName // exists // - the QA_NEEDED pair is not for this user (i.e. user can't review // their own work, UNLESS there is only one lead on the project // - user and workflowStatus pairs of // CONFLICT_NEW/CONFLICT_IN_PROGRESS_userName does not exist // must have a QA_NEEDED tag with any user fullQuery += " AND userAndWorkflowStatusPairs:QA_NEEDED_*"; fullQuery += " AND workflowPath:QA_PATH"; // there must not be an already claimed review record fullQuery += " AND NOT (userAndWorkflowStatusPairs:QA_NEW_*" + " OR userAndWorkflowStatusPairs:QA_IN_PROGRESS_*" + " OR userAndWorkflowStatusPairs:QA_RESOLVED_*" + ")"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); List<TrackingRecord> allResults = ftquery.getResultList(); List<TrackingRecord> results = new ArrayList<>(); if (query == null || query.equals("") || query.equals("null") || query.equals("undefined")) { results = allResults; } else { // remove tracking records that don't have a map record with a label // matching the query for (TrackingRecord tr : allResults) { boolean labelFound = false; // OPTIMIZATION: Bypass the "get map records for tr" mechanism to avoid // full lazy initialization of the record Set<MapRecord> mapRecords = new HashSet<>(); if (tr != null && tr.getMapRecordIds() != null) { for (Long id : tr.getMapRecordIds()) { // go directly, we just need record label info mapRecords.add(manager.find(MapRecordJpa.class, id)); } } for (MapRecord record : mapRecords) { for (String label : record.getLabels()) { if (label.equals(query)) { labelFound = true; } } } if (labelFound) { results.add(tr); } } } // set the total count matching this label availableQAWork.setTotalCount(results.size()); // apply paging, and sorting if appropriate if (pfsParameter != null && (pfsParameter.getSortField() != null && !pfsParameter.getSortField() .isEmpty())) { // check that specified sort field exists on Concept and is // a string final Field sortField = TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()); if (!sortField.getType().equals(String.class)) { throw new Exception( "findAvailableQAWork error: Referenced sort field is not of type String"); } // allow the field to access the Concept values sortField.setAccessible(true); // sort the list - UNTESTED Collections.sort(results, new Comparator<TrackingRecord>() { @Override public int compare(TrackingRecord c1, TrackingRecord c2) { // if an exception is returned, simply pass equality try { return ((String) sortField.get(c1)).compareTo((String) sortField .get(c2)); } catch (Exception e) { return 0; } } }); } // get the start and end indexes based on paging parameters int startIndex = 0; int toIndex = results.size(); if (pfsParameter != null) { startIndex = pfsParameter.getStartIndex() == -1 ? 0 : Math.min(results.size(), pfsParameter.getStartIndex()); // ensure start index not negative if (startIndex < 0) startIndex = 0; toIndex = pfsParameter.getMaxResults() == -1 ? results.size() : Math.min( results.size(), startIndex + pfsParameter.getMaxResults()); } for (TrackingRecord tr : results.subList(startIndex, toIndex)) { SearchResult result = new SearchResultJpa(); result.setTerminologyId(tr.getTerminologyId()); result.setId(tr.getId()); result.setValue(tr.getDefaultPreferredName()); StringBuffer labelBuffer = new StringBuffer(); for (MapRecord record : getMapRecordsForTrackingRecord(tr)) { for (String label : record.getLabels()) { if (labelBuffer.indexOf(label) == -1) labelBuffer.append(";").append(label); } } result.setValue2(labelBuffer.toString()); availableQAWork.addSearchResult(result); } return availableQAWork; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getAvailableReviewWork * (org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.model.MapUser) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAvailableReviewWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList availableReviewWork = new SearchResultListJpa(); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAvailableReviewWork // - a user (any) and workflowStatus pair of REVIEW_NEEDED_userName // exists // - the REVIEW_NEEDED pair is not for this user (i.e. user can't review // their own work, UNLESS there is only one lead on the project // - user and workflowStatus pairs of // CONFLICT_NEW/CONFLICT_IN_PROGRESS_userName does not exist // must have a REVIEW_NEEDED tag with any user fullQuery += " AND userAndWorkflowStatusPairs:REVIEW_NEEDED_*"; // there must not be an already claimed review record fullQuery += " AND NOT (userAndWorkflowStatusPairs:REVIEW_NEW_*" + " OR userAndWorkflowStatusPairs:REVIEW_IN_PROGRESS_*" + " OR userAndWorkflowStatusPairs:REVIEW_RESOLVED_*" + ")"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); availableReviewWork.setTotalCount(ftquery.getResultSize()); if (pfsParameter.getStartIndex() != -1 && pfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(pfsParameter.getStartIndex()); ftquery.setMaxResults(pfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (pfsParameter.getSortField() != null && !pfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()) .getType().equals(String.class)) { ftquery.setSort(new Sort(new SortField(pfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); result.setTerminologyId(tr.getTerminologyId()); result.setValue(tr.getDefaultPreferredName()); result.setId(tr.getId()); availableReviewWork.addSearchResult(result); } return availableReviewWork; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAssignedWork(org.ihtsdo * .otf.mapping.model.MapProject, org.ihtsdo.otf.mapping.model.MapUser, * java.lang.String, org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAssignedWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { PfsParameter localPfsParameter = pfsParameter; SearchResultList assignedWork = new SearchResultListJpa(); // create a blank pfs parameter object if one not passed in if (localPfsParameter == null) localPfsParameter = new PfsParameterJpa(); // create a blank query restriction if none provided if (localPfsParameter.getQueryRestriction() == null) localPfsParameter.setQueryRestriction(""); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAssignedWork // - user and workflowStatus must exist in a pair of form: // workflowStatus_userName, e.g. NEW_dmo or EDITING_IN_PROGRESS_kli // - modify search term based on pfs parameter query restriction field // * default: NEW, EDITING_IN_PROGRESS, EDITING_DONE/CONFLICT_DETECTED // * NEW: NEW // * EDITED: EDITING_IN_PROGRESS, EDITING_DONE/CONFLICT_DETECTED // add terms based on query restriction switch (localPfsParameter.getQueryRestriction()) { case "NEW": fullQuery += " AND userAndWorkflowStatusPairs:NEW_" + mapUser.getUserName(); break; case "EDITING_IN_PROGRESS": fullQuery += " AND (userAndWorkflowStatusPairs:EDITING_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_IN_PROGRESS_" + mapUser.getUserName() + ")"; break; case "EDITING_DONE": fullQuery += " AND (userAndWorkflowStatusPairs:EDITING_DONE_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:CONFLICT_DETECTED_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_NEEDED_" + mapUser.getUserName() + ")"; break; default: fullQuery += " AND (userAndWorkflowStatusPairs:NEW_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:EDITING_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:EDITING_DONE_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:CONFLICT_DETECTED_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_NEEDED_" + mapUser.getUserName() + ")"; break; } // add terms to exclude concepts that a lead has claimed fullQuery += " AND NOT (userAndWorkflowStatusPairs:CONFLICT_NEW_*" + " OR userAndWorkflowStatusPairs:CONFLICT_IN_PROGRESS_*" + " OR userAndWorkflowStatusPairs:CONFLICT_RESOLVED_*" + " OR userAndWorkflowStatusPairs:REVIEW_NEW_*" + " OR userAndWorkflowStatusPairs:REVIEW_NEEDED_*" + " OR userAndWorkflowStatusPairs:REVIEW_RESOLVED_*)"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); assignedWork.setTotalCount(ftquery.getResultSize()); if (localPfsParameter.getStartIndex() != -1 && localPfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(localPfsParameter.getStartIndex()); ftquery.setMaxResults(localPfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (localPfsParameter.getSortField() != null && !localPfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class .getDeclaredField(localPfsParameter.getSortField()).getType() .equals(String.class)) { ftquery.setSort(new Sort(new SortField( localPfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } // otherwise, sort by ancestor path } else { ftquery.setSort(new Sort(new SortField("sortKey", SortField.STRING))); } List<TrackingRecord> results = ftquery.getResultList(); MappingService mappingService = new MappingServiceJpa(); for (TrackingRecord tr : results) { // instantiate the result list SearchResult result = new SearchResultJpa(); // get the map records associated with this tracking record Set<MapRecord> mapRecords = this.getMapRecordsForTrackingRecord(tr); // get the map record assigned to this user MapRecord mapRecord = null; // SEE BELOW/MAP-617 WorkflowStatus mapLeadAlternateRecordStatus = null; for (MapRecord mr : mapRecords) { if (mr.getOwner().equals(mapUser)) { // if this lead has review or conflict work, set the flag if (mr.getWorkflowStatus().equals(WorkflowStatus.CONFLICT_NEW) || mr.getWorkflowStatus().equals( WorkflowStatus.CONFLICT_IN_PROGRESS) || mr.getWorkflowStatus().equals(WorkflowStatus.REVIEW_NEW) || mr.getWorkflowStatus().equals( WorkflowStatus.REVIEW_IN_PROGRESS)) { mapLeadAlternateRecordStatus = mr.getWorkflowStatus(); // added to prevent user from getting REVISION record // back on FIX_ERROR_PATH // yet another problem related to leads being able to // serve as dual roles } else if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { // do nothing // otherwise, this is the specialist/concept-level work } else { mapRecord = mr; } } } // if no record and no review or conflict work was found, throw // error if (mapRecord == null) { throw new Exception( "Failed to retrieve assigned work: no map record found for user " + mapUser.getUserName() + " and concept " + tr.getTerminologyId()); } else { // alter the workflow status if a higher-level record exists for // this user if (mapLeadAlternateRecordStatus != null) { Logger.getLogger(WorkflowServiceJpa.class).info( "Setting alternate record status: " + mapLeadAlternateRecordStatus); mapRecord.setWorkflowStatus(mapLeadAlternateRecordStatus); } // create the search result result.setTerminologyId(mapRecord.getConceptId()); result.setValue(mapRecord.getConceptName()); result.setTerminology(mapRecord.getLastModified().toString()); result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString()); result.setId(mapRecord.getId()); assignedWork.addSearchResult(result); } } mappingService.close(); return assignedWork; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getAssignedConflicts( * org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.model.MapUser) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAssignedConflicts(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList assignedConflicts = new SearchResultListJpa(); if (mapProject.getWorkflowType().toString().equals("REVIEW_PROJECT_PATH")) return assignedConflicts; PfsParameter localPfsParameter = pfsParameter; if (localPfsParameter == null) localPfsParameter = new PfsParameterJpa(); // create a blank query restriction if none provided if (localPfsParameter.getQueryRestriction() == null) localPfsParameter.setQueryRestriction(""); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAssignedConflicts // - workflow status CONFLICT_NEW or CONFLICT_IN_PROGRESS with this user // name in pair // add terms based on query restriction switch (localPfsParameter.getQueryRestriction()) { case "CONFLICT_NEW": fullQuery += " AND userAndWorkflowStatusPairs:CONFLICT_NEW_" + mapUser.getUserName(); break; case "CONFLICT_IN_PROGRESS": fullQuery += " AND userAndWorkflowStatusPairs:CONFLICT_IN_PROGRESS_" + mapUser.getUserName(); break; case "CONFLICT_RESOLVED": fullQuery += " AND userAndWorkflowStatusPairs:CONFLICT_RESOLVED_" + mapUser.getUserName(); break; default: fullQuery += " AND (userAndWorkflowStatusPairs:CONFLICT_NEW_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:CONFLICT_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:CONFLICT_RESOLVED_" + mapUser.getUserName() + ")"; break; } QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); assignedConflicts.setTotalCount(ftquery.getResultSize()); if (localPfsParameter.getStartIndex() != -1 && localPfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(localPfsParameter.getStartIndex()); ftquery.setMaxResults(localPfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (localPfsParameter.getSortField() != null && !localPfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class .getDeclaredField(localPfsParameter.getSortField()).getType() .equals(String.class)) { ftquery.setSort(new Sort(new SortField( localPfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); MappingService mappingService = new MappingServiceJpa(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); Set<MapRecord> mapRecords = this.getMapRecordsForTrackingRecord(tr); // get the map record assigned to this user MapRecord mapRecord = null; for (MapRecord mr : mapRecords) { try { if (mr.getOwner().equals(mapUser)) // SEE MAP-617: // Lower level record may exist with same owner, only // add if actually a conflict if (mr.getWorkflowStatus().compareTo( WorkflowStatus.CONFLICT_DETECTED) < 0) { // do nothing, this is the specialist level work } else { mapRecord = mr; } } catch (Exception e) { e.printStackTrace(); } } if (mapRecord == null) { throw new Exception( "Failed to retrieve assigned conflicts: no map record found for user " + mapUser.getUserName() + " and concept " + tr.getTerminologyId()); } else { result.setTerminologyId(mapRecord.getConceptId()); result.setValue(mapRecord.getConceptName()); result.setTerminology(mapRecord.getLastModified().toString()); result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString()); result.setId(mapRecord.getId()); assignedConflicts.addSearchResult(result); } } mappingService.close(); return assignedConflicts; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAssignedReviewWork( * org.ihtsdo.otf.mapping.model.MapProject, * org.ihtsdo.otf.mapping.model.MapUser, java.lang.String, * org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAssignedReviewWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList assignedReviewWork = new SearchResultListJpa(); PfsParameter localPfsParameter = pfsParameter; // create a blank pfs parameter object if one not passed in if (localPfsParameter == null) localPfsParameter = new PfsParameterJpa(); // create a blank query restriction if none provided if (localPfsParameter.getQueryRestriction() == null) localPfsParameter.setQueryRestriction(""); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), query); // add the query terms specific to findAssignedReviewWork // - user and workflow status must exist in the form REVIEW_NEW_userName // or REVIEW_IN_PROGRESS_userName // add terms based on query restriction switch (localPfsParameter.getQueryRestriction()) { case "REVIEW_NEW": fullQuery += " AND userAndWorkflowStatusPairs:REVIEW_NEW_" + mapUser.getUserName(); break; case "REVIEW_IN_PROGRESS": fullQuery += " AND userAndWorkflowStatusPairs:REVIEW_IN_PROGRESS_" + mapUser.getUserName(); break; case "REVIEW_RESOLVED": fullQuery += " AND userAndWorkflowStatusPairs:REVIEW_RESOLVED_" + mapUser.getUserName(); break; default: fullQuery += " AND (userAndWorkflowStatusPairs:REVIEW_NEW_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:REVIEW_RESOLVED_" + mapUser.getUserName() + ")"; break; } QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); assignedReviewWork.setTotalCount(ftquery.getResultSize()); if (localPfsParameter.getStartIndex() != -1 && localPfsParameter.getMaxResults() != -1) { ftquery.setFirstResult(localPfsParameter.getStartIndex()); ftquery.setMaxResults(localPfsParameter.getMaxResults()); } // if sort field is specified, set sort key if (localPfsParameter.getSortField() != null && !localPfsParameter.getSortField().isEmpty()) { // check that specified sort field exists on Concept and is // a string if (TrackingRecordJpa.class .getDeclaredField(localPfsParameter.getSortField()).getType() .equals(String.class)) { ftquery.setSort(new Sort(new SortField( localPfsParameter.getSortField(), SortField.STRING))); } else { throw new Exception( "Concept query specified a field that does not exist or is not a string"); } } List<TrackingRecord> results = ftquery.getResultList(); MappingService mappingService = new MappingServiceJpa(); for (TrackingRecord tr : results) { SearchResult result = new SearchResultJpa(); Set<MapRecord> mapRecords = this.getMapRecordsForTrackingRecord(tr); // get the map record assigned to this user MapRecord mapRecord = null; for (MapRecord mr : mapRecords) { if (mr.getOwner().equals(mapUser)) { // check for the case where REVIEW work is both specialist // and // lead level for same user if (mr.getWorkflowStatus().compareTo(WorkflowStatus.REVIEW_NEW) < 0) { // do nothing, this is the specialist level work } else if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { // do nothing } else { // add the record mapRecord = mr; } } } if (mapRecord == null) { mappingService.close(); throw new Exception( "Failed to retrieve assigned work: no map record found for user " + mapUser.getUserName() + " and concept " + tr.getTerminologyId()); } result.setTerminologyId(mapRecord.getConceptId()); result.setValue(mapRecord.getConceptName()); result.setTerminology(mapRecord.getLastModified().toString()); result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString()); result.setId(mapRecord.getId()); assignedReviewWork.addSearchResult(result); } mappingService.close(); return assignedReviewWork; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#findAssignedQAWork(org. * ihtsdo.otf.mapping.model.MapProject, org.ihtsdo.otf.mapping.model.MapUser, * java.lang.String, org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings("unchecked") @Override public SearchResultList findAssignedQAWork(MapProject mapProject, MapUser mapUser, String query, PfsParameter pfsParameter) throws Exception { SearchResultList assignedReviewWork = new SearchResultListJpa(); PfsParameter localPfsParameter = pfsParameter; // create a blank pfs parameter object if one not passed in if (localPfsParameter == null) localPfsParameter = new PfsParameterJpa(); // create a blank query restriction if none provided if (localPfsParameter.getQueryRestriction() == null) localPfsParameter.setQueryRestriction(""); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct basic query String fullQuery = "mapProjectId:" + mapProject.getId(); // add the query terms specific to findAssignedReviewWork // - user and workflow status must exist in the form QA_NEW_userName // or QA_IN_PROGRESS_userName // add terms based on query restriction switch (localPfsParameter.getQueryRestriction()) { case "QA_NEW": fullQuery += " AND userAndWorkflowStatusPairs:QA_NEW_" + mapUser.getUserName(); break; case "QA_IN_PROGRESS": fullQuery += " AND userAndWorkflowStatusPairs:QA_IN_PROGRESS_" + mapUser.getUserName(); break; case "QA_RESOLVED": fullQuery += " AND userAndWorkflowStatusPairs:QA_RESOLVED_" + mapUser.getUserName(); break; default: fullQuery += " AND (userAndWorkflowStatusPairs:QA_NEW_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:QA_IN_PROGRESS_" + mapUser.getUserName() + " OR userAndWorkflowStatusPairs:QA_RESOLVED_" + mapUser.getUserName() + ")"; break; } // don't get path fullQuery += " AND workflowPath:QA_PATH"; QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(TrackingRecordJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, TrackingRecordJpa.class); List<TrackingRecord> allResults = ftquery.getResultList(); List<TrackingRecord> results = new ArrayList<>(); if (query == null || query.equals("") || query.equals("null") || query.equals("undefined")) { results = allResults; } else { // remove tracking records that don't have a map record with a label // matching the query for (TrackingRecord tr : allResults) { boolean labelFound = false; for (MapRecord record : getMapRecordsForTrackingRecord(tr)) { for (String label : record.getLabels()) { if (label.equals(query)) { labelFound = true; } } } if (labelFound) { results.add(tr); } } } assignedReviewWork.setTotalCount(results.size()); // apply paging, and sorting if appropriate if (pfsParameter != null && (pfsParameter.getSortField() != null && !pfsParameter.getSortField() .isEmpty())) { // check that specified sort field exists on Concept and is // a string final Field sortField = TrackingRecordJpa.class.getDeclaredField(pfsParameter.getSortField()); if (!sortField.getType().equals(String.class)) { throw new Exception( "findAssignedQAWork error: Referenced sort field is not of type String"); } // allow the field to access the Concept values sortField.setAccessible(true); // sort the list - UNTESTED Collections.sort(results, new Comparator<TrackingRecord>() { @Override public int compare(TrackingRecord c1, TrackingRecord c2) { // if an exception is returned, simply pass equality try { return ((String) sortField.get(c1)).compareTo((String) sortField .get(c2)); } catch (Exception e) { return 0; } } }); } // get the start and end indexes based on paging parameters int startIndex = 0; int toIndex = results.size(); if (pfsParameter != null) { if (pfsParameter.getStartIndex() != -1) { // ensure that start index is within array boundaries startIndex = Math.min(results.size(), pfsParameter.getStartIndex()); // ensure startIndex not less than zero if (startIndex < 0) startIndex = 0; } if (pfsParameter.getMaxResults() != -1) { toIndex = Math.min(results.size(), startIndex + pfsParameter.getMaxResults()); } } for (TrackingRecord tr : results.subList(startIndex, toIndex)) { SearchResult result = new SearchResultJpa(); Set<MapRecord> mapRecords = this.getMapRecordsForTrackingRecord(tr); // get the map record assigned to this user MapRecord mapRecord = null; for (MapRecord mr : mapRecords) { if (mr.getOwner().equals(mapUser)) { if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEEDED)) { // do nothing, this is the specialist level QA work } else if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) { // do nothing } else { // this is the user's record mapRecord = mr; } } } if (mapRecord == null) { throw new Exception( "Failed to retrieve assigned work: no map record found for user " + mapUser.getUserName() + " and concept " + tr.getTerminologyId()); } result.setTerminologyId(mapRecord.getConceptId()); result.setValue(mapRecord.getConceptName()); StringBuffer labelBuffer = new StringBuffer(); for (MapRecord record : getMapRecordsForTrackingRecord(tr)) { for (String label : record.getLabels()) { if (labelBuffer.indexOf(label) == -1) labelBuffer.append(";").append(label); } } result.setValue2(labelBuffer.toString()); result.setTerminology(mapRecord.getLastModified().toString()); result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString()); result.setId(mapRecord.getId()); assignedReviewWork.addSearchResult(result); } return assignedReviewWork; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#createQAWork(org.ihtsdo * .otf.mapping.reports.Report) */ @Override public void createQAWork(Report report) throws Exception { if (report.getResults() == null || report.getResults().size() != 1) { throw new Exception("Failed to provide a report with one result set " + report.getId()); } Set<String> conceptIds = new HashSet<>(); for (ReportResultItem resultItem : report.getResults().get(0) .getReportResultItems()) { conceptIds.add(resultItem.getItemId()); } // open the services ContentService contentService = new ContentServiceJpa(); MappingService mappingService = new MappingServiceJpa(); // get the map project and concept MapProject mapProject = mappingService.getMapProject(report.getMapProjectId()); // find the qa user MapUser mapUser = null; for (MapUser user : mappingService.getMapUsers().getMapUsers()) { if (user.getUserName().equals("qa")) mapUser = user; } for (String conceptId : conceptIds) { Concept concept = contentService.getConcept(conceptId, mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); MapRecordList recordList = mappingService.getMapRecordsForProjectAndConcept(mapProject.getId(), conceptId); // lazy initialize recordList.getMapRecords().size(); mappingService.close(); for (MapRecord mapRecord : recordList.getMapRecords()) { // set the label on the record mapRecord.addLabel(report.getReportDefinition().getName()); // process the workflow action processWorkflowAction(mapProject, concept, mapUser, mapRecord, WorkflowAction.CREATE_QA_RECORD); } } contentService.close(); } /** * Perform workflow actions based on a specified action. * ASSIGN_FROM_INITIAL_RECORD is the only routine that requires a map record * to be passed in All other cases that all required mapping information (e.g. * map records) be current in the database (i.e. updateMapRecord has been * called) * * @param mapProject the map project * @param concept the concept * @param mapUser the map user * @param mapRecord the map record * @param workflowAction the workflow action * @throws Exception the exception */ @Override public void processWorkflowAction(MapProject mapProject, Concept concept, MapUser mapUser, MapRecord mapRecord, WorkflowAction workflowAction) throws Exception { Logger.getLogger(WorkflowServiceJpa.class).info( "Processing workflow action by " + mapUser.getName() + ": " + workflowAction.toString()); if (mapRecord != null) { Logger.getLogger(WorkflowServiceJpa.class).info( " Record attached: " + mapRecord.toString()); } setTransactionPerOperation(true); // instantiate the algorithm handler for this project\ ProjectSpecificAlgorithmHandler algorithmHandler = (ProjectSpecificAlgorithmHandler) Class.forName( mapProject.getProjectSpecificAlgorithmHandlerClass()).newInstance(); algorithmHandler.setMapProject(mapProject); // locate any existing workflow tracking records for this project and // concept // NOTE: Exception handling deliberate, since tracking record may or may // not exist // depending on workflow path TrackingRecord trackingRecord = null; try { trackingRecord = getTrackingRecord(mapProject, concept); } catch (NoResultException e) { trackingRecord = null; } // Validate tracking record if (trackingRecord != null) { // instantiate the handler based on tracking record workflow type AbstractWorkflowPathHandler handler = null; switch (trackingRecord.getWorkflowPath()) { case CONSENSUS_PATH: break; case DRIP_FEED_REVIEW_PATH: break; case FIX_ERROR_PATH: handler = new WorkflowFixErrorPathHandler(); break; case LEGACY_PATH: break; case NON_LEGACY_PATH: handler = new WorkflowNonLegacyPathHandler(); break; case QA_PATH: handler = new WorkflowQaPathHandler(); break; case REVIEW_PROJECT_PATH: handler = new WorkflowReviewProjectPathHandler(); break; default: throw new Exception( "Could not determine workflow handler from tracking record for path: " + trackingRecord.getWorkflowPath().toString()); } ValidationResult result = handler.validateTrackingRecordForActionAndUser(trackingRecord, workflowAction, mapUser); if (!result.isValid()) { Logger.getLogger(WorkflowServiceJpa.class).info(result.toString()); StringBuffer message = new StringBuffer(); message.append("Errors were detected in the workflow for:\n"); message.append(" Project\t: " + mapProject.getName() + "\n"); message.append(" Concept\t: " + concept.getTerminologyId() + "\n"); message.append(" Path:\t " + trackingRecord.getWorkflowPath().toString() + "\n"); message.append(" User\t: " + mapUser.getUserName() + "\n"); message.append(" Action\t: " + workflowAction.toString() + "\n"); message.append("\n"); // record information message.append("Records involved:\n"); message.append(" " + "id\tUser\tWorkflowStatus\n"); for (MapRecord mr : getMapRecordsForTrackingRecord(trackingRecord)) { message.append(" " + mr.getId().toString() + "\t" + mr.getOwner().getUserName() + "\t" + mr.getWorkflowStatus().toString() + "\n"); } message.append("\n"); message.append("Errors reported:\n"); for (String error : result.getErrors()) { message.append(" " + error + "\n"); } message.append("\n"); // log the message Logger.getLogger(WorkflowServiceJpa.class).error( "Workflow error detected\n" + message.toString()); // send email if indicated Properties config = ConfigUtility.getConfigProperties(); String notificationRecipients = config.getProperty("send.notification.recipients"); if (!notificationRecipients.isEmpty()) { OtfEmailHandler emailHandler = new OtfEmailHandler(); emailHandler.sendSimpleEmail(notificationRecipients, config.getProperty("mail.smtp.user"), mapProject.getName() + " Workflow Error Alert, Concept " + concept.getTerminologyId(), message.toString()); } throw new LocalException("Workflow action " + workflowAction.toString() + " could not be performed on concept " + trackingRecord.getTerminologyId()); } } Set<MapRecord> mapRecords = getMapRecordsForTrackingRecord(trackingRecord); // if the record passed in updates an existing record, replace it in the // set if (mapRecord != null && mapRecord.getId() != null) { for (MapRecord mr : mapRecords) { if (mr.getId().equals(mapRecord.getId())) { Logger.getLogger(WorkflowService.class).info( "Replacing record " + mr.toString() + "\n with" + mapRecord.toString()); mapRecords.remove(mr); mapRecords.add(mapRecord); break; } } } // switch on workflow action switch (workflowAction) { case CREATE_QA_RECORD: Logger.getLogger(WorkflowServiceJpa.class).info("CREATE_QA_RECORD"); // if a tracking record is found, perform no action (this record is // already assigned) if (trackingRecord == null) { // expect a map record to be passed in if (mapRecord == null) { throw new Exception( "ProcessWorkflowAction: CREATE_QA_RECORD - Call to assign from intial record must include an existing map record"); } // create a new tracking record for QA_PATH trackingRecord = new TrackingRecordJpa(); trackingRecord.setMapProjectId(mapProject.getId()); trackingRecord.setTerminology(concept.getTerminology()); trackingRecord.setTerminologyVersion(concept.getTerminologyVersion()); trackingRecord.setTerminologyId(concept.getTerminologyId()); trackingRecord.setDefaultPreferredName(concept .getDefaultPreferredName()); trackingRecord.addMapRecordId(mapRecord.getId()); // get the tree positions for this concept and set the sort key // to // the first retrieved ContentService contentService = new ContentServiceJpa(); TreePositionList treePositionsList = contentService.getTreePositionsWithDescendants( concept.getTerminologyId(), concept.getTerminology(), concept.getTerminologyVersion()); // handle inactive concepts - which don't have tree positions if (treePositionsList.getCount() == 0) { trackingRecord.setSortKey(""); } else { trackingRecord.setSortKey(treePositionsList.getTreePositions() .get(0).getAncestorPath()); } trackingRecord.setWorkflowPath(WorkflowPath.QA_PATH); // perform the assign action via the algorithm handler mapRecords = algorithmHandler.assignFromInitialRecord(trackingRecord, mapRecords, mapRecord, mapUser); contentService.close(); // otherwise, this concept is already in the workflow, do nothing } else { // do nothing (label will be added in synchronize) } break; case ASSIGN_FROM_INITIAL_RECORD: Logger.getLogger(WorkflowServiceJpa.class).info( "ASSIGN_FROM_INITIAL_RECORD"); // if a tracking record is found, perform no action (this record is // already assigned) if (trackingRecord == null) { // expect a map record to be passed in if (mapRecord == null) { throw new Exception( "ProcessWorkflowAction: ASSIGN_FROM_INITIAL_RECORD - Call to assign from intial record must include an existing map record"); } // create a new tracking record for FIX_ERROR_PATH or QA_PATH trackingRecord = new TrackingRecordJpa(); trackingRecord.setMapProjectId(mapProject.getId()); trackingRecord.setTerminology(concept.getTerminology()); trackingRecord.setTerminologyVersion(concept.getTerminologyVersion()); trackingRecord.setTerminologyId(concept.getTerminologyId()); trackingRecord.setDefaultPreferredName(concept .getDefaultPreferredName()); trackingRecord.addMapRecordId(mapRecord.getId()); // get the tree positions for this concept and set the sort key // to // the first retrieved ContentService contentService = new ContentServiceJpa(); TreePositionList treePositionsList = contentService.getTreePositionsWithDescendants( concept.getTerminologyId(), concept.getTerminology(), concept.getTerminologyVersion()); // handle inactive concepts - which don't have tree positions if (treePositionsList.getCount() == 0) { trackingRecord.setSortKey(""); } else { trackingRecord.setSortKey(treePositionsList.getTreePositions() .get(0).getAncestorPath()); } trackingRecord.setWorkflowPath(WorkflowPath.FIX_ERROR_PATH); // perform the assign action via the algorithm handler mapRecords = algorithmHandler.assignFromInitialRecord(trackingRecord, mapRecords, mapRecord, mapUser); contentService.close(); } else { throw new LocalException( "Assignment from published record failed -- concept already in workflow"); } break; case ASSIGN_FROM_SCRATCH: // Logger.getLogger(WorkflowServiceJpa.class).info( // "ASSIGN_FROM_SCRATCH"); // expect existing (pre-computed) workflow tracking record if (trackingRecord == null) { throw new Exception("Could not find tracking record for assignment."); } // Team based assignment only matters on NON_LEGACY_PATH and not for // conflict cases // If "concepts" assignment is being done on NON_LEGACY PATH and another // team // member claimed the other role, then leave alone if (trackingRecord.getWorkflowPath() == WorkflowPath.NON_LEGACY_PATH && mapProject.isTeamBased() && trackingRecord.getAssignedUserCount() > 0 && !trackingRecord.getUserAndWorkflowStatusPairs().contains( WorkflowStatus.CONFLICT_DETECTED.toString())) { MappingService service = new MappingServiceJpa(); for (MapUser user : service.getMapUsersForTeam(mapUser.getTeam()) .getMapUsers()) { if (trackingRecord.getAssignedUserNames().contains( user.getUserName())) { service.close(); throw new LocalException( "This concept is already assigned to another member of " + "the same team. Reload the dashboard and try again"); } } service.close(); } // perform the assignment via the algorithm handler mapRecords = algorithmHandler.assignFromScratch(trackingRecord, mapRecords, concept, mapUser); break; case UNASSIGN: Logger.getLogger(WorkflowServiceJpa.class).info("UNASSIGN"); // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: UNASSIGN - Could not find tracking record for unassignment."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: UNASSIGN - User not assigned to record for unassignment request"); // perform the unassign action via the algorithm handler mapRecords = algorithmHandler.unassign(trackingRecord, mapRecords, mapUser); break; case SAVE_FOR_LATER: // Logger.getLogger(WorkflowServiceJpa.class).info("SAVE_FOR_LATER"); // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: SAVE_FOR_LATER - Could not find tracking record."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: SAVE_FOR_LATER - SAVE_FOR_LATER - User not assigned to record"); // Logger.getLogger(WorkflowServiceJpa.class).info( // "Performing action..."); mapRecords = algorithmHandler.saveForLater(trackingRecord, mapRecords, mapUser); break; case FINISH_EDITING: // Logger.getLogger(WorkflowServiceJpa.class).info("FINISH_EDITING"); // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: FINISH_EDITING - Could not find tracking record to be finished."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: FINISH_EDITING - User not assigned to record for finishing request"); // // Logger.getLogger(WorkflowServiceJpa.class).info( // "Performing action..."); // // // perform the action mapRecords = algorithmHandler.finishEditing(trackingRecord, mapRecords, mapUser); break; case PUBLISH: // Logger.getLogger(WorkflowServiceJpa.class).info("FINISH_EDITING"); // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: PUBLISH - Could not find tracking record to be published."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: PUBLISH - User not assigned to tracking record for publish request"); // // Logger.getLogger(WorkflowServiceJpa.class).info( // "Performing action..."); // // // perform the action mapRecords = algorithmHandler.publish(trackingRecord, mapRecords, mapUser); break; case CANCEL: // expect existing (pre-computed) workflow tracking record to exist // with this user assigned if (trackingRecord == null) throw new Exception( "ProcessWorkflowAction: CANCEL - Could not find tracking record to be finished."); // expect this user to be assigned to a map record in this tracking // record if (!getMapUsersForTrackingRecord(trackingRecord).contains(mapUser)) throw new Exception( "ProcessWorkflowAction: CANCEL - User not assigned to record for cancel request"); mapRecords = algorithmHandler.cancelWork(trackingRecord, mapRecords, mapUser); break; default: throw new Exception("Unknown action requested."); } Logger.getLogger(WorkflowServiceJpa.class).info("Synchronizing..."); // synchronize the map records via helper function Set<MapRecord> syncedRecords = synchronizeMapRecords(trackingRecord, mapRecords); // clear the pointer fields (i.e. ids and names of mapping // objects) trackingRecord.setMapRecordIds(null); trackingRecord.setAssignedUserNames(null); trackingRecord.setUserAndWorkflowStatusPairs(null); // recalculate the pointer fields for (MapRecord mr : syncedRecords) { trackingRecord.addMapRecordId(mr.getId()); trackingRecord.addAssignedUserName(mr.getOwner().getUserName()); trackingRecord.addUserAndWorkflowStatusPair(mr.getOwner().getUserName(), mr.getWorkflowStatus().toString()); } Logger.getLogger(WorkflowServiceJpa.class).info( "Revised tracking record: " + trackingRecord.toString()); // if the tracking record is ready for removal, delete it if ((getWorkflowStatusForTrackingRecord(trackingRecord).equals( WorkflowStatus.READY_FOR_PUBLICATION) || getWorkflowStatusForTrackingRecord( trackingRecord).equals(WorkflowStatus.PUBLISHED)) && trackingRecord.getMapRecordIds().size() == 1) { Logger.getLogger(WorkflowServiceJpa.class).info( " Publication ready, removing tracking record."); removeTrackingRecord(trackingRecord.getId()); // else add the tracking record if new } else if (trackingRecord.getId() == null) { Logger.getLogger(WorkflowServiceJpa.class).info( " New workflow concept, adding tracking record."); addTrackingRecord(trackingRecord); // otherwise update the tracking record } else { Logger.getLogger(WorkflowServiceJpa.class).info( " Still in workflow, updating tracking record."); updateTrackingRecord(trackingRecord); } } /** * Algorithm has gotten needlessly complex due to conflicting service changes * and algorithm handler changes. However, the basic process is this: * * 1) Function takes a set of map records returned from the algorithm handler * These map records may have a hibernate id (updated/unchanged) or not * (added) 2) The passed map records are detached from the persistence * environment. 3) The existing (in database) records are re-retrieved from * the database. Note that this is why the passed map records are detached -- * otherwise they are overwritten. 4) Each record in the detached set is * checked against the 'refreshed' database record set - if the detached * record is not in the set, then it has been added - if the detached record * is in the set, check it for updates - if it has been changed, update it - * if no change, disregard 5) Each record in the 'refreshed' databased record * set is checked against the new set - if the refreshed record is not in the * new set, delete it from the database 6) Return the detached set as * re-synchronized with the database * * Note on naming conventions used in this method: - mapRecords: the set of * records passed in as argument - newRecords: The set of records to be * returned after synchronization - oldRecords: The set of records retrieved * by id from the database for comparison - syncedRecords: The synchronized * set of records for return from this routine * * @param trackingRecord the tracking record * @param mapRecords the map records * @return the sets the * @throws Exception the exception */ @Override public Set<MapRecord> synchronizeMapRecords(TrackingRecord trackingRecord, Set<MapRecord> mapRecords) throws Exception { Set<MapRecord> newRecords = new HashSet<>(); Set<MapRecord> oldRecords = new HashSet<>(); Set<MapRecord> syncedRecords = new HashSet<>(); // detach the currently persisted map records from the workflow service // to avoid overwrite by retrieval of existing records for (MapRecord mr : mapRecords) { manager.detach(mr); newRecords.add(mr); } // Instantiate the mapping service MappingService mappingService = new MappingServiceJpa(); // retrieve the old (existing) records if (trackingRecord.getMapRecordIds() != null) { for (Long id : trackingRecord.getMapRecordIds()) { oldRecords.add(mappingService.getMapRecord(id)); } } // cycle over new records to check for additions or updates for (MapRecord mr : newRecords) { if (getMapRecordInSet(oldRecords, mr.getId()) == null) { // deep copy the detached record into a new // persistence-environment record // this routine also duplicates child collections to avoid // detached object errors MapRecord newRecord = new MapRecordJpa(mr, false); /* * Logger.getLogger(WorkflowServiceJpa.class).info( "Adding record: " + * newRecord.toString()); */ // add the record to the database mappingService.addMapRecord(newRecord); // add the record to the return list syncedRecords.add(newRecord); } // otherwise, check for update else { // if the old map record is changed, update it /* * Logger.getLogger(WorkflowServiceJpa.class).info( "New record: " + * mr.toString()); Logger.getLogger(WorkflowServiceJpa.class).info( * "Old record: " + getMapRecordInSet(oldRecords, * mr.getId()).toString()); */ if (!mr.isEquivalent(getMapRecordInSet(oldRecords, mr.getId()))) { Logger.getLogger(WorkflowServiceJpa.class) .info(" Changed: UPDATING"); mappingService.updateMapRecord(mr); } else { Logger.getLogger(WorkflowServiceJpa.class).info( " No change: NOT UPDATING"); } syncedRecords.add(mr); } } // cycle over old records to check for deletions for (MapRecord mr : oldRecords) { // if old record is not in the new record set, delete it if (getMapRecordInSet(syncedRecords, mr.getId()) == null) { Logger.getLogger(WorkflowServiceJpa.class).info( "Deleting record " + mr.getId()); mappingService.removeMapRecord(mr.getId()); } } // close the service mappingService.close(); return syncedRecords; } /** * Gets the map record in set. * * @param mapRecords the map records * @param mapRecordId the map record id * @return the map record in set */ private MapRecord getMapRecordInSet(Set<MapRecord> mapRecords, Long mapRecordId) { if (mapRecordId == null) return null; for (MapRecord mr : mapRecords) { if (mapRecordId.equals(mr.getId())) return mr; } return null; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#computeWorkflow(org.ihtsdo * .otf.mapping.model.MapProject) */ @Override public void computeWorkflow(MapProject mapProject) throws Exception { Logger.getLogger(WorkflowServiceJpa.class).info( "Start computing workflow for " + mapProject.getName()); // set the transaction parameter and tracking variables setTransactionPerOperation(false); int commitCt = 1000; int trackingRecordCt = 0; // Clear the workflow for this project Logger.getLogger(WorkflowServiceJpa.class).info(" Clear old workflow"); clearWorkflowForMapProject(mapProject); // open the services ContentService contentService = new ContentServiceJpa(); MappingService mappingService = new MappingServiceJpa(); // get the concepts in scope SearchResultList conceptsInScope = mappingService.findConceptsInScope(mapProject.getId(), null); // construct a hashset of concepts in scope Set<String> conceptIds = new HashSet<>(); for (SearchResult sr : conceptsInScope.getIterable()) { conceptIds.add(sr.getTerminologyId()); } Logger.getLogger(WorkflowServiceJpa.class).info( " Concept ids put into hash set: " + conceptIds.size()); // get the current records MapRecordList mapRecords = mappingService.getMapRecordsForMapProject(mapProject.getId()); Logger.getLogger(WorkflowServiceJpa.class).info( "Processing existing records (" + mapRecords.getCount() + " found)"); // instantiate a mapped set of non-published records Map<String, List<MapRecord>> unpublishedRecords = new HashMap<>(); // cycle over the map records, and remove concept ids if a map record is // publication-ready for (MapRecord mapRecord : mapRecords.getIterable()) { // if this map record is published, skip and remove this concept if (mapRecord.getWorkflowStatus().equals( WorkflowStatus.READY_FOR_PUBLICATION) || mapRecord.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED)) { conceptIds.remove(mapRecord.getConceptId()); } // if this concept is in scope, add to workflow else if (conceptIds.contains(mapRecord.getConceptId())) { List<MapRecord> originIds; // if this key does not yet have a constructed list, make one, // otherwise get the existing list if (unpublishedRecords.containsKey(mapRecord.getConceptId())) { originIds = unpublishedRecords.get(mapRecord.getConceptId()); } else { originIds = new ArrayList<>(); } originIds.add(mapRecord); unpublishedRecords.put(mapRecord.getConceptId(), originIds); } } Logger.getLogger(WorkflowServiceJpa.class) .info( " Concepts with no publication-ready map record: " + conceptIds.size()); Logger.getLogger(WorkflowServiceJpa.class).info( " Concepts with unpublished map record content: " + unpublishedRecords.size()); beginTransaction(); // construct the tracking records for unmapped concepts for (String terminologyId : conceptIds) { // retrieve the concept for this result Concept concept = contentService.getConcept(terminologyId, mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); // if concept could not be retrieved, throw exception if (concept == null) { throw new Exception("Failed to retrieve concept " + terminologyId); } // skip inactive concepts if (!concept.isActive()) { Logger.getLogger(WorkflowServiceJpa.class).warn( "Skipped inactive concept " + terminologyId); continue; } // get the tree positions for this concept and set the sort key to // the first retrieved TreePositionList treePositionsList = contentService.getTreePositions(concept.getTerminologyId(), concept.getTerminology(), concept.getTerminologyVersion()); // if no tree position, throw exception if (treePositionsList.getCount() == 0) { throw new Exception("Active concept " + terminologyId + " has no tree positions"); } // create a workflow tracking record for this concept TrackingRecord trackingRecord = new TrackingRecordJpa(); // populate the fields from project and concept trackingRecord.setMapProjectId(mapProject.getId()); trackingRecord.setTerminology(concept.getTerminology()); trackingRecord.setTerminologyId(concept.getTerminologyId()); trackingRecord.setTerminologyVersion(concept.getTerminologyVersion()); trackingRecord.setDefaultPreferredName(concept.getDefaultPreferredName()); trackingRecord.setSortKey(treePositionsList.getTreePositions().get(0) .getAncestorPath()); // add any existing map records to this tracking record Set<MapRecord> mapRecordsForTrackingRecord = new HashSet<>(); if (unpublishedRecords.containsKey(trackingRecord.getTerminologyId())) { for (MapRecord mr : unpublishedRecords.get(trackingRecord .getTerminologyId())) { Logger.getLogger(WorkflowServiceJpa.class).info( " Adding existing map record " + mr.getId() + ", owned by " + mr.getOwner().getUserName() + " to tracking record for " + trackingRecord.getTerminologyId()); trackingRecord.addMapRecordId(mr.getId()); trackingRecord.addAssignedUserName(mr.getOwner().getUserName()); trackingRecord.addUserAndWorkflowStatusPair(mr.getOwner() .getUserName(), mr.getWorkflowStatus().toString()); // add to the local set for workflow calculation mapRecordsForTrackingRecord.add(mr); } } // check if REVISION record is present // check if QA record is present boolean revisionRecordPresent = false; boolean qaRecordPresent = false; for (MapRecord mr : mapRecordsForTrackingRecord) { if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION)) revisionRecordPresent = true; if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEEDED) || mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEW) || mr.getWorkflowStatus().equals(WorkflowStatus.QA_IN_PROGRESS) || mr.getWorkflowStatus().equals(WorkflowStatus.QA_RESOLVED)) { qaRecordPresent = true; } } // if REVISION found and no qa records, set to FIX_ERROR_PATH if (revisionRecordPresent && !qaRecordPresent) { trackingRecord.setWorkflowPath(WorkflowPath.FIX_ERROR_PATH); // if REVISION found and qa records, set to QA_PATH } else if (revisionRecordPresent && qaRecordPresent) { trackingRecord.setWorkflowPath(WorkflowPath.QA_PATH); // otherwise, set to the WorkflowPath corresponding to the // project WorkflowType } else { if (mapProject.getWorkflowType().equals(WorkflowType.CONFLICT_PROJECT)) trackingRecord.setWorkflowPath(WorkflowPath.NON_LEGACY_PATH); else if (mapProject.getWorkflowType().equals( WorkflowType.REVIEW_PROJECT)) trackingRecord.setWorkflowPath(WorkflowPath.REVIEW_PROJECT_PATH); else { throw new Exception("Could not set workflow path from workflow type " + mapProject.getWorkflowType() + " for records " + trackingRecord.getMapRecordIds().toString()); } } addTrackingRecord(trackingRecord); if (++trackingRecordCt % commitCt == 0) { Logger.getLogger(WorkflowServiceJpa.class).info( " " + trackingRecordCt + " tracking records created"); commit(); beginTransaction(); // close and re-instantiate the content service to prevent // memory buildup from Concept and TreePosition objects contentService.close(); contentService = new ContentServiceJpa(); } } // commit any remaining transactions commit(); // instantiate the full text eneity manager and set version FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); fullTextEntityManager.setProperty("Version", Version.LUCENE_36); // create the indexes Logger.getLogger(WorkflowServiceJpa.class).info( " Creating indexes for TrackingRecordJpa"); fullTextEntityManager.purgeAll(TrackingRecordJpa.class); fullTextEntityManager.flushToIndexes(); fullTextEntityManager.createIndexer(TrackingRecordJpa.class) .batchSizeToLoadObjects(100).cacheMode(CacheMode.NORMAL) .threadsToLoadObjects(4).threadsForSubsequentFetching(8).startAndWait(); Logger.getLogger(WorkflowServiceJpa.class).info("Done."); } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#clearWorkflowForMapProject * (org.ihtsdo.otf.mapping.model.MapProject) */ @Override public void clearWorkflowForMapProject(MapProject mapProject) throws Exception { int commitCt = 0; int commitInterval = 1000; // begin transaction not in transaction-per-operation mode if (!getTransactionPerOperation()) { beginTransaction(); } for (TrackingRecord tr : getTrackingRecordsForMapProject(mapProject) .getTrackingRecords()) { removeTrackingRecord(tr.getId()); if (++commitCt % commitInterval == 0) { // if not a transaction for every operation, commit at intervals if (!getTransactionPerOperation()) { commit(); beginTransaction(); } Logger.getLogger(WorkflowServiceJpa.class).info( " Removed " + commitCt + " tracking records"); } } // commit any last deletions if not in transaction-per-operation mode if (!getTransactionPerOperation()) { commit(); } } // ////////////////////////// // Utility functions // ////////////////////////// /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getMapRecordsForTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public Set<MapRecord> getMapRecordsForTrackingRecord( TrackingRecord trackingRecord) throws Exception { Set<MapRecord> mapRecords = new HashSet<>(); MappingService mappingService = new MappingServiceJpa(); if (trackingRecord != null && trackingRecord.getMapRecordIds() != null) { for (Long id : trackingRecord.getMapRecordIds()) { mapRecords.add(mappingService.getMapRecord(id)); } } mappingService.close(); return mapRecords; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getMapUsersForTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public MapUserList getMapUsersForTrackingRecord(TrackingRecord trackingRecord) throws Exception { return getMapUsersFromMapRecords(getMapRecordsForTrackingRecord(trackingRecord)); } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getWorkflowStatusForTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public WorkflowStatus getWorkflowStatusForTrackingRecord( TrackingRecord trackingRecord) throws Exception { return getWorkflowStatusFromMapRecords(getMapRecordsForTrackingRecord(trackingRecord)); } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getLowestWorkflowStatusForTrackingRecord * (org.ihtsdo.otf.mapping.workflow.TrackingRecord) */ @Override public WorkflowStatus getLowestWorkflowStatusForTrackingRecord( TrackingRecord trackingRecord) throws Exception { return getLowestWorkflowStatusFromMapRecords(getMapRecordsForTrackingRecord(trackingRecord)); } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#getMapUsersFromMapRecords * (java.util.Set) */ @Override public MapUserList getMapUsersFromMapRecords(Set<MapRecord> mapRecords) { MapUserList mapUserList = new MapUserListJpa(); for (MapRecord mr : mapRecords) { mapUserList.addMapUser(mr.getOwner()); } return mapUserList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getWorkflowStatusFromMapRecords(java.util.Set) */ @Override public WorkflowStatus getWorkflowStatusFromMapRecords( Set<MapRecord> mapRecords) { WorkflowStatus workflowStatus = WorkflowStatus.NEW; for (MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().compareTo(workflowStatus) > 0) workflowStatus = mr.getWorkflowStatus(); } return workflowStatus; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getLowestWorkflowStatusFromMapRecords(java.util.Set) */ @Override public WorkflowStatus getLowestWorkflowStatusFromMapRecords( Set<MapRecord> mapRecords) { WorkflowStatus workflowStatus = WorkflowStatus.REVISION; for (MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().compareTo(workflowStatus) < 0) workflowStatus = mr.getWorkflowStatus(); } return workflowStatus; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#computeWorkflowStatusErrors * (org.ihtsdo.otf.mapping.model.MapProject) */ @Override public List<String> computeWorkflowStatusErrors(MapProject mapProject) throws Exception { List<String> results = new ArrayList<>(); // instantiate the mapping service MappingService mappingService = new MappingServiceJpa(); Logger.getLogger(WorkflowServiceJpa.class).info( "Retrieving tracking records for project " + mapProject.getId() + ", " + mapProject.getName()); // instantiate a copy of all workflow handlers WorkflowNonLegacyPathHandler nonLegacyHandler = new WorkflowNonLegacyPathHandler(); WorkflowFixErrorPathHandler fixErrorHandler = new WorkflowFixErrorPathHandler(); WorkflowQaPathHandler qaHandler = new WorkflowQaPathHandler(); WorkflowReviewProjectPathHandler reviewHandler = new WorkflowReviewProjectPathHandler(); // get all the tracking records for this project TrackingRecordList trackingRecords = this.getTrackingRecordsForMapProject(mapProject); // construct a set of terminology ids for which a tracking record exists Set<String> terminologyIdsWithTrackingRecord = new HashSet<>(); for (TrackingRecord trackingRecord : trackingRecords.getTrackingRecords()) { terminologyIdsWithTrackingRecord.add(trackingRecord.getTerminologyId()); // instantiate the handler based on tracking record workflow type AbstractWorkflowPathHandler handler = null; switch (trackingRecord.getWorkflowPath()) { case CONSENSUS_PATH: break; case DRIP_FEED_REVIEW_PATH: break; case FIX_ERROR_PATH: handler = fixErrorHandler; break; case LEGACY_PATH: break; case NON_LEGACY_PATH: handler = nonLegacyHandler; break; case QA_PATH: handler = qaHandler; break; case REVIEW_PROJECT_PATH: handler = reviewHandler; break; default: results .add("ERROR: Could not determine workflow handler from tracking record for concept " + trackingRecord.getTerminologyId() + " for path: " + trackingRecord.getWorkflowPath().toString()); } ValidationResult result = handler.validateTrackingRecord(trackingRecord); if (!result.isValid()) { results .add(constructErrorMessageStringForTrackingRecordAndValidationResult( trackingRecord, result)); } } Logger.getLogger(WorkflowServiceJpa.class).info( " Checking map records for " + mapProject.getId() + ", " + mapProject.getName()); // second, check all records for non-publication ready content without // tracking record, skip inactive concepts ContentService contentService = new ContentServiceJpa(); for (MapRecord mapRecord : mappingService.getMapRecordsForMapProject( mapProject.getId()).getMapRecords()) { // if not publication ready if (!mapRecord.getWorkflowStatus().equals( WorkflowStatus.READY_FOR_PUBLICATION) && !mapRecord.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED)) { Concept concept = contentService.getConcept(mapRecord.getConceptId(), mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); // if no tracking record found for this concept // and the concept is active, then report an error if (!terminologyIdsWithTrackingRecord .contains(mapRecord.getConceptId()) && concept != null && concept.isActive()) { results.add("Map Record " + mapRecord.getId() + ": " + mapRecord.getWorkflowStatus() + " but no tracking record exists (Concept " + mapRecord.getConceptId() + " " + mapRecord.getConceptName()); } } } mappingService.close(); contentService.close(); return results; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#computeUntrackedMapRecords * (org.ihtsdo.otf.mapping.model.MapProject) */ @Override public void computeUntrackedMapRecords(MapProject mapProject) throws Exception { MappingService mappingService = new MappingServiceJpa(); Logger.getLogger(WorkflowServiceJpa.class).info( "Retrieving map records for project " + mapProject.getId() + ", " + mapProject.getName()); MapRecordList mapRecordsInProject = mappingService.getMapRecordsForMapProject(mapProject.getId()); Logger.getLogger(WorkflowServiceJpa.class).info( " " + mapRecordsInProject.getCount() + " retrieved"); // set the reporting interval based on number of tracking records int nObjects = 0; int nMessageInterval = (int) Math.floor(mapRecordsInProject.getCount() / 10); Set<MapRecord> recordsUntracked = new HashSet<>(); for (MapRecord mr : mapRecordsInProject.getIterable()) { TrackingRecord tr = this.getTrackingRecordForMapProjectAndConcept(mapProject, mr.getConceptId()); // if no tracking record, check that this is a publication ready map // record if (tr == null) { if (!mr.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED) && !mr.getWorkflowStatus().equals( WorkflowStatus.READY_FOR_PUBLICATION)) { recordsUntracked.add(mr); } } if (++nObjects % nMessageInterval == 0) { Logger.getLogger(WorkflowServiceJpa.class).info( " " + nObjects + " records processed, " + recordsUntracked.size() + " unpublished map records without tracking record"); } } mappingService.close(); } // ///////////////////////////////////// // FEEDBACK FUNCTIONS // ///////////////////////////////////// /** * Adds the feedback. * * @param feedback the feedback * @return the feedback */ @Override public Feedback addFeedback(Feedback feedback) { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(feedback); tx.commit(); } else { manager.persist(feedback); } return feedback; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService#getFeedbacks() */ @Override @SuppressWarnings("unchecked") public FeedbackList getFeedbacks() { List<Feedback> feedbacks = null; // construct query javax.persistence.Query query = manager.createQuery("select m from FeedbackJpa m"); // Try query feedbacks = query.getResultList(); FeedbackListJpa feedbackList = new FeedbackListJpa(); feedbackList.setFeedbacks(feedbacks); feedbackList.setTotalCount(feedbacks.size()); return feedbackList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.MappingService#addFeedbackConversation * (org.ihtsdo.otf.mapping.model.FeedbackConversation) */ @Override public FeedbackConversation addFeedbackConversation( FeedbackConversation conversation) { // set the conversation of all elements of this conversation conversation.assignToChildren(); if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(conversation); tx.commit(); } else { manager.persist(conversation); } return conversation; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#updateFeedbackConversation * (org.ihtsdo.otf.mapping.model.FeedbackConversation) */ @Override public void updateFeedbackConversation(FeedbackConversation conversation) { // set the conversation of all elements of this conversation conversation.assignToChildren(); if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(conversation); tx.commit(); // manager.close(); } else { manager.merge(conversation); } } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#getFeedbackConversation * (java.lang.Long) */ @SuppressWarnings("unchecked") @Override public FeedbackConversation getFeedbackConversation(Long id) throws Exception { // construct query javax.persistence.Query query = manager .createQuery("select m from FeedbackConversationJpa m where mapRecordId = :recordId"); // Try query query.setParameter("recordId", id); List<FeedbackConversation> feedbackConversations = query.getResultList(); if (feedbackConversations != null && feedbackConversations.size() > 0) handleFeedbackConversationLazyInitialization(feedbackConversations.get(0)); Logger.getLogger(this.getClass()).debug( "Returning feedback conversation id... " + ((feedbackConversations != null) ? id.toString() : "null")); return feedbackConversations != null && feedbackConversations.size() > 0 ? feedbackConversations.get(0) : null; } /** * Handle feedback conversation lazy initialization. * * @param feedbackConversation the feedback conversation */ private void handleFeedbackConversationLazyInitialization( FeedbackConversation feedbackConversation) { // handle all lazy initializations for (Feedback feedback : feedbackConversation.getFeedbacks()) { feedback.getSender().getName(); for (MapUser recipient : feedback.getRecipients()) recipient.getName(); for (MapUser viewedBy : feedback.getViewedBy()) viewedBy.getName(); } } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getFeedbackConversationsForConcept(java.lang.Long, java.lang.String) */ @SuppressWarnings("unchecked") @Override public FeedbackConversationList getFeedbackConversationsForConcept( Long mapProjectId, String terminologyId) throws Exception { MappingService mappingService = new MappingServiceJpa(); MapProject mapProject = mappingService.getMapProject(mapProjectId); mappingService.close(); javax.persistence.Query query = manager .createQuery( "select m from FeedbackConversationJpa m where terminology = :terminology and" + " terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId); List<FeedbackConversation> feedbackConversations = query.getResultList(); for (FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(feedbackConversations.size()); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * findFeedbackConversationsForProject(java.lang.Long, java.lang.String, * org.ihtsdo.otf.mapping.helpers.PfsParameter) */ @SuppressWarnings({ "unchecked" }) @Override public FeedbackConversationList findFeedbackConversationsForProject( Long mapProjectId, String userName, String query, PfsParameter pfsParameter) throws Exception { MappingService mappingService = new MappingServiceJpa(); MapProject mapProject = mappingService.getMapProject(mapProjectId); mappingService.close(); // remove from the query the viewed parameter, if it exists // viewed will be handled later because it is on the Feedback object, // not the FeedbackConversation object String modifiedQuery = ""; if (query.contains(" AND viewed:false")) modifiedQuery = query.replace(" AND viewed:false", ""); else if (query.contains(" AND viewed:true")) modifiedQuery = query.replace(" AND viewed:true", ""); else modifiedQuery = query; // construct basic query String fullQuery = constructMapProjectIdQuery(mapProject.getId(), modifiedQuery); fullQuery += " AND terminology:" + mapProject.getSourceTerminology() + " AND terminologyVersion:" + mapProject.getSourceTerminologyVersion() + " AND " + "( feedbacks.sender.userName:" + userName + " OR " + "feedbacks.recipients.userName:" + userName + ")"; Logger.getLogger(MappingServiceJpa.class).info(fullQuery); FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); SearchFactory searchFactory = fullTextEntityManager.getSearchFactory(); Query luceneQuery; // construct luceneQuery based on URL format QueryParser queryParser = new QueryParser(Version.LUCENE_36, "summary", searchFactory.getAnalyzer(FeedbackConversationJpa.class)); try { luceneQuery = queryParser.parse(fullQuery); } catch (ParseException e) { throw new LocalException( "The specified search terms cannot be parsed. Please check syntax and try again."); } org.hibernate.search.jpa.FullTextQuery ftquery = fullTextEntityManager.createFullTextQuery(luceneQuery, FeedbackConversationJpa.class); // Sort Options -- in order of priority // (1) if a sort field is specified by pfs parameter, use it // (2) if a query has been specified, use nothing (lucene relevance // default) // (3) if a query has not been specified, sort by conceptId String sortField = "lastModified"; if (pfsParameter != null && pfsParameter.getSortField() != null && !pfsParameter.getSortField().isEmpty()) { ftquery.setSort(new Sort(new SortField(pfsParameter.getSortField(), SortField.STRING, true))); } else if (pfsParameter != null && pfsParameter.getQueryRestriction() != null && !pfsParameter.getQueryRestriction().isEmpty()) { // do nothing } else { ftquery .setSort(new Sort(new SortField(sortField, SortField.STRING, true))); } // get the results int totalCount = ftquery.getResultSize(); if (pfsParameter != null && !query.contains("viewed")) { ftquery.setFirstResult(pfsParameter.getStartIndex()); ftquery.setMaxResults(pfsParameter.getMaxResults()); } List<FeedbackConversation> feedbackConversations = ftquery.getResultList(); if (pfsParameter != null && query.contains("viewed")) { List<FeedbackConversation> conversationsToKeep = new ArrayList<>(); for (FeedbackConversation fc : feedbackConversations) { if (query.contains("viewed:false")) { for (Feedback feedback : fc.getFeedbacks()) { Set<MapUser> alreadyViewedBy = feedback.getViewedBy(); boolean found = false; for (MapUser user : alreadyViewedBy) { if (user.getUserName().equals(userName)) found = true; } if (!found) conversationsToKeep.add(fc); } } if (query.contains("viewed:true")) { boolean found = false; for (Feedback feedback : fc.getFeedbacks()) { Set<MapUser> alreadyViewedBy = feedback.getViewedBy(); for (MapUser user : alreadyViewedBy) { if (user.getUserName().equals(userName)) { found = true; break; } } if (!found) break; } if (found) conversationsToKeep.add(fc); } } totalCount = conversationsToKeep.size(); feedbackConversations.clear(); for (int i = pfsParameter.getStartIndex(); i < pfsParameter .getStartIndex() + pfsParameter.getMaxResults() && i < conversationsToKeep.size(); i++) { feedbackConversations.add(conversationsToKeep.get(i)); } } Logger.getLogger(this.getClass()).debug( Integer.toString(feedbackConversations.size()) + " feedbackConversations retrieved"); for (FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(totalCount); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* * (non-Javadoc) * * @see org.ihtsdo.otf.mapping.services.WorkflowService# * getFeedbackConversationsForRecord(java.lang.Long) */ @SuppressWarnings("unchecked") @Override public FeedbackConversationList getFeedbackConversationsForRecord( Long mapRecordId) throws Exception { javax.persistence.Query query = manager .createQuery( "select m from FeedbackConversationJpa m where mapRecordId=:mapRecordId") .setParameter("mapRecordId", mapRecordId); List<FeedbackConversation> feedbackConversations = query.getResultList(); for (FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(feedbackConversations.size()); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#getFeedbackErrorsForRecord * (org.ihtsdo.otf.mapping.model.MapRecord) */ @Override public FeedbackList getFeedbackErrorsForRecord(MapRecord mapRecord) throws Exception { List<Feedback> feedbacksWithError = new ArrayList<>(); // find any feedback conersations for this record FeedbackConversationList conversations = this.getFeedbackConversationsForRecord(mapRecord.getId()); // cycle over feedbacks for (FeedbackConversation conversation : conversations.getIterable()) { for (Feedback feedback : conversation.getFeedbacks()) { if (feedback.getIsError()) { feedbacksWithError.add(feedback); } } } FeedbackList feedbackList = new FeedbackListJpa(); feedbackList.setFeedbacks(feedbacksWithError); return feedbackList; } /* * (non-Javadoc) * * @see * org.ihtsdo.otf.mapping.services.WorkflowService#sendFeedbackEmail(java. * lang.String, java.lang.String, java.lang.String, java.lang.String, * java.lang.String, java.lang.String) */ @Override public void sendFeedbackEmail(String name, String email, String conceptId, String conceptName, String refSetId, String message) throws Exception { OtfEmailHandler emailHandler = new OtfEmailHandler(); // get to address from config.properties Properties config = ConfigUtility.getConfigProperties(); String feedbackUserRecipient = config.getProperty("mail.smtp.to.feedback.user"); String baseUrlWebapp = config.getProperty("base.url.webapp"); String conceptUrl = baseUrlWebapp + "/#/record/conceptId/" + conceptId + "/autologin?refSetId=" + refSetId; emailHandler.sendSimpleEmail(feedbackUserRecipient, email, "Mapping Tool User Feedback: " + conceptId + "-" + conceptName, "User: " + name + "<br>" + "Email: " + email + "<br>" + "Concept: <a href=" + conceptUrl + ">" + conceptId + "- " + conceptName + "</a><br><br>" + message); } /** * Construct error message string for tracking record and validation result. * * @param trackingRecord the tracking record * @param result the result * @return the string * @throws Exception the exception */ private String constructErrorMessageStringForTrackingRecordAndValidationResult( TrackingRecord trackingRecord, ValidationResult result) throws Exception { StringBuffer message = new StringBuffer(); message.append("ERROR for Concept " + trackingRecord.getTerminologyId() + ", Path " + trackingRecord.getWorkflowPath().toString() + "\n"); // record information message.append(" Records involved:\n"); message.append(" " + "id\tUser\tWorkflowStatus\n"); for (MapRecord mr : getMapRecordsForTrackingRecord(trackingRecord)) { message.append(" " + mr.getId().toString() + "\t" + mr.getOwner().getUserName() + "\t" + mr.getWorkflowStatus().toString() + "\n"); } message.append(" Errors reported:\n"); for (String error : result.getErrors()) { message.append(" " + error + "\n"); } return message.toString(); } }
MAP-1191: another tweak.
jpa-services/src/main/java/org/ihtsdo/otf/mapping/jpa/services/WorkflowServiceJpa.java
MAP-1191: another tweak.
Java
apache-2.0
837be65646eb459df16bfd351c3a642d5c668e4b
0
xizhououyang/elephant-bird,twitter/elephant-bird,InMobi/elephant-bird,saurfang/elephant-bird,wicknicks/elephant-bird,twitter/elephant-bird,qubole/elephant-bird,RainyWang103/elephant-bird,laurentgo/elephant-bird,airbnb/elephant-bird,canojim/elephant-bird,rubanm/elephant-bird,rubanm/elephant-bird,skinzer/elephant-bird,rangadi/elephant-bird,EugenCepoi/elephant-bird,nvoron23/elephant-bird,EugenCepoi/elephant-bird
package com.twitter.elephantbird.pig.util; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.pig.LoadFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; import org.apache.thrift.TBase; import org.apache.thrift.protocol.TType; import com.google.common.collect.Lists; import com.twitter.elephantbird.pig.load.ThriftPigLoader; import com.twitter.elephantbird.thrift.TStructDescriptor; import com.twitter.elephantbird.thrift.TStructDescriptor.Field; import com.twitter.elephantbird.util.ThriftUtils; import com.twitter.elephantbird.util.TypeRef; /** * <li> converts a Thrift struct to a Pig tuple * <li> utilities to provide schema for Pig loaders and Pig scripts */ public class ThriftToPig<M extends TBase<?, ?>> { public static final Logger LOG = LogManager.getLogger(ThriftToPig.class); private static BagFactory bagFactory = BagFactory.getInstance(); private static TupleFactory tupleFactory = TupleFactory.getInstance(); private TStructDescriptor structDesc; public static <M extends TBase<?, ?>> ThriftToPig<M> newInstance(Class<M> tClass) { return new ThriftToPig<M>(tClass); } public static <M extends TBase<?, ?>> ThriftToPig<M> newInstance(TypeRef<M> typeRef) { return new ThriftToPig<M>(typeRef.getRawClass()); } public ThriftToPig(Class<M> tClass) { structDesc = TStructDescriptor.getInstance(tClass); } public TStructDescriptor getTStructDescriptor() { return structDesc; } /** * Converts a thrift object to Pig tuple. * All the fields are deserialized. * It might be better to use getLazyTuple() if not all fields * are required. */ public Tuple getPigTuple(M thriftObj) { return toTuple(structDesc, thriftObj); } /** * Similar to {@link #getPigTuple(TBase)}. This delays * serialization of tuple contents until they are requested. * @param thriftObj * @return */ public Tuple getLazyTuple(M thriftObj) { return new LazyTuple(structDesc, thriftObj); } @SuppressWarnings("rawtypes") private static <T extends TBase>Tuple toTuple(TStructDescriptor tDesc, T tObj) { int size = tDesc.getFields().size(); Tuple tuple = tupleFactory.newTuple(size); for (int i=0; i<size; i++) { Field field = tDesc.getFieldAt(i); Object value = tDesc.getFieldValue(i, tObj); try { tuple.set(i, toPigObject(field, value, false)); } catch (ExecException e) { // not expected throw new RuntimeException(e); } } return tuple; } @SuppressWarnings("unchecked") public static Object toPigObject(Field field, Object value, boolean lazy) { if (value == null) { return null; } switch (field.getType()) { case TType.BOOL: return Integer.valueOf((Boolean)value ? 1 : 0); case TType.BYTE : return Integer.valueOf((Byte)value); case TType.I16 : return Integer.valueOf((Short)value); case TType.STRING: return stringTypeToPig(value); case TType.STRUCT: if (lazy) { return new LazyTuple(field.gettStructDescriptor(), (TBase<?, ?>)value); } else { return toTuple(field.gettStructDescriptor(), (TBase<?, ?>)value); } case TType.MAP: return toPigMap(field, (Map<Object, Object>)value, lazy); case TType.SET: return toPigBag(field.getSetElemField(), (Collection<Object>)value, lazy); case TType.LIST: return toPigBag(field.getListElemField(), (Collection<Object>)value, lazy); case TType.ENUM: return value.toString(); default: // standard types : I32, I64, DOUBLE, etc. return value; } } /** * TType.STRING is a mess in Thrift. It could be byte[], ByteBuffer, * or even a String!. */ private static Object stringTypeToPig(Object value) { if (value instanceof String) { return value; } if (value instanceof byte[]) { byte[] buf = (byte[])value; return new DataByteArray(Arrays.copyOf(buf, buf.length)); } if (value instanceof ByteBuffer) { ByteBuffer bin = (ByteBuffer)value; byte[] buf = new byte[bin.remaining()]; bin.mark(); bin.get(buf); bin.reset(); return new DataByteArray(buf); } return null; } private static Map<String, Object> toPigMap(Field field, Map<Object, Object> map, boolean lazy) { // PIG map's key always a String. just use toString() and hope // things would work out ok. HashMap<String, Object> out = new HashMap<String, Object>(map.size()); Field valueField = field.getMapValueField(); for(Entry<Object, Object> e : map.entrySet()) { Object prev = out.put(e.getKey().toString(), toPigObject(valueField, e.getValue(), lazy)); if (prev != null) { String msg = "Duplicate keys while converting to String while " + " processing map " + field.getName() + " (key type : " + field.getMapKeyField().getType() + " value type : " + field.getMapValueField().getType() + ")"; LOG.warn(msg); throw new RuntimeException(msg); } } return out; } private static DataBag toPigBag(Field field, Collection<Object> values, boolean lazy) { List<Tuple> tuples = Lists.newArrayListWithExpectedSize(values.size()); for(Object value : values) { Object pValue = toPigObject(field, value, lazy); if (pValue instanceof Tuple) { // DataBag should contain Tuples tuples.add((Tuple)pValue); } else { tuples.add(tupleFactory.newTuple(pValue)); } } return bagFactory.newDefaultBag(tuples); } @SuppressWarnings("serial") /** * Delays serialization of Thrift fields until they are requested. */ private static class LazyTuple extends AbstractLazyTuple { /* NOTE : This is only a partial optimization. The other part * is to avoid deserialization of the Thrift fields from the * binary buffer. * * Currently TDeserializer allows deserializing just one field, * psuedo-skipping over the fields before it. * But if we are going deserialize 5 fields out of 20, we will be * skipping over same set of fields multiple times. OTOH this might * still be better than a full deserialization. * * We need to write our own version of TBinaryProtocol that truly skips. * Even TDeserializer 'skips'/ignores only after deserializing fields. * (e.g. Strings, Integers, buffers etc). */ private TBase<?, ?> tObject; private TStructDescriptor desc; LazyTuple(TStructDescriptor desc, TBase<?, ?> tObject) { initRealTuple(desc.getFields().size()); this.tObject = tObject; this.desc = desc; } @Override protected Object getObjectAt(int index) { Field field = desc.getFieldAt(index); return toPigObject(field, desc.getFieldValue(index, tObject), true); } } /** * Returns Pig schema for the Thrift struct. */ public static Schema toSchema(Class<? extends TBase<?, ?>> tClass) { return toSchema(TStructDescriptor.getInstance(tClass)); } public Schema toSchema() { return toSchema(structDesc); } public static Schema toSchema(TStructDescriptor tDesc ) { Schema schema = new Schema(); try { for(Field field : tDesc.getFields()) { schema.add(singleFieldToFieldSchema(field.getName(), field)); } } catch (FrontendException t) { throw new RuntimeException(t); } return schema; } /** * return {@link FieldSchema} for a given field. */ private static FieldSchema singleFieldToFieldSchema(String fieldName, Field field) throws FrontendException { //TODO we should probably implement better naming, the current system is pretty nonsensical now switch (field.getType()) { case TType.STRUCT: return new FieldSchema(fieldName, toSchema(field.gettStructDescriptor()), DataType.TUPLE); case TType.LIST: return new FieldSchema(fieldName, singleFieldToTupleSchema(fieldName + "_tuple", field.getListElemField()), DataType.BAG); case TType.SET: return new FieldSchema(fieldName, singleFieldToTupleSchema(fieldName + "_tuple", field.getSetElemField()), DataType.BAG); case TType.MAP: if (field.getMapKeyField().getType() != TType.STRING && field.getMapKeyField().getType() != TType.ENUM) { LOG.warn("Using a map with non-string key for field " + field.getName() + ". while converting to PIG Tuple, toString() is used for the key." + " It could result in incorrect maps."); } return new FieldSchema(fieldName, new Schema(singleFieldToFieldSchema(null, field.getMapValueField())), DataType.MAP); default: return new FieldSchema(fieldName, null, getPigDataType(field)); } } /** * A helper function which wraps a Schema in a tuple (for Pig bags) if our version of pig makes it necessary */ private static Schema wrapInTupleIfPig9(Schema schema) throws FrontendException { if (PigUtil.Pig9orNewer) { return new Schema(new FieldSchema("t",schema,DataType.TUPLE)); } else { return schema; } } /** * Returns a schema with single tuple (for Pig bags). */ private static Schema singleFieldToTupleSchema(String fieldName, Field field) throws FrontendException { switch (field.getType()) { case TType.STRUCT: return wrapInTupleIfPig9(toSchema(field.gettStructDescriptor())); case TType.LIST: case TType.SET: case TType.MAP: return wrapInTupleIfPig9(new Schema(singleFieldToFieldSchema(fieldName, field))); default: return wrapInTupleIfPig9(new Schema(new FieldSchema(fieldName, null, getPigDataType(field)))); } } private static byte getPigDataType(Field field) { switch (field.getType()) { case TType.BOOL: case TType.BYTE: case TType.I16: case TType.I32: return DataType.INTEGER; case TType.ENUM: return DataType.CHARARRAY; case TType.I64: return DataType.LONG; case TType.DOUBLE: return DataType.DOUBLE; case TType.STRING: return field.isBuffer() ? DataType.BYTEARRAY : DataType.CHARARRAY; default: throw new IllegalArgumentException("Unexpected type where a simple type is expected : " + field.getType()); } } /** * Turn a Thrift Struct into a loading schema for a pig script. */ public static String toPigScript(Class<? extends TBase<?, ?>> thriftClass, Class<? extends LoadFunc> pigLoader) { StringBuilder sb = new StringBuilder(); /* we are commenting out explicit schema specification. The schema is * included mainly to help the readers of the pig script. Pig learns the * schema directly from the loader. * If explicit schema is not commented, we might have surprising results * when a Thrift class (possibly in control of another team) changes, * but the Pig script is not updated. Commenting it out avoids this. */ StringBuilder prefix = new StringBuilder(" -- "); sb.append("raw_data = load '$INPUT_FILES' using ") .append(pigLoader.getName()) .append("('") .append(thriftClass.getName()) .append("');\n") .append(prefix) .append("as "); prefix.append(" "); try { stringifySchema(sb, toSchema(thriftClass), DataType.TUPLE, prefix); } catch (FrontendException e) { throw new RuntimeException(e); } sb.append("\n"); return sb.toString(); } /** * Print formatted schema. This is a modified version of * {@link Schema#stringifySchema(StringBuilder, Schema, byte)} * with support for (indented) pretty printing. */ // This is used for building up output string // type can only be BAG or TUPLE public static void stringifySchema(StringBuilder sb, Schema schema, byte type, StringBuilder prefix) throws FrontendException{ // this is a modified version of {@link Schema#stringifySchema(StringBuilder, Schema, byte)} if (type == DataType.TUPLE) { sb.append("(") ; } else if (type == DataType.BAG) { sb.append("{") ; } prefix.append(" "); sb.append("\n").append(prefix); if (schema == null) { sb.append("null") ; } else { boolean isFirst = true ; for (int i=0; i< schema.size() ;i++) { if (!isFirst) { sb.append(",\n").append(prefix); } else { isFirst = false ; } FieldSchema fs = schema.getField(i) ; if(fs == null) { sb.append("null"); continue; } if (fs.alias != null) { sb.append(fs.alias); sb.append(": "); } if (DataType.isAtomic(fs.type)) { sb.append(DataType.findTypeName(fs.type)) ; } else if ( (fs.type == DataType.TUPLE) || (fs.type == DataType.BAG) ) { // safety net if (schema != fs.schema) { stringifySchema(sb, fs.schema, fs.type, prefix) ; } else { throw new AssertionError("Schema refers to itself " + "as inner schema") ; } } else if (fs.type == DataType.MAP) { sb.append(DataType.findTypeName(fs.type) + "["); if (fs.schema!=null) stringifySchema(sb, fs.schema, fs.type, prefix); sb.append("]"); } else { sb.append(DataType.findTypeName(fs.type)) ; } } } prefix.setLength(prefix.length()-2); sb.append("\n").append(prefix); if (type == DataType.TUPLE) { sb.append(")") ; } else if (type == DataType.BAG) { sb.append("}") ; } } public static void main(String[] args) throws Exception { if (args.length > 0) { Class<? extends TBase<?, ?>> tClass = ThriftUtils.getTypeRef(args[0]).getRawClass(); System.out.println(args[0] + " : " + toSchema(tClass).toString()); System.out.println(toPigScript(tClass, ThriftPigLoader.class)); } } }
src/java/com/twitter/elephantbird/pig/util/ThriftToPig.java
package com.twitter.elephantbird.pig.util; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.pig.LoadFunc; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; import org.apache.thrift.TBase; import org.apache.thrift.protocol.TType; import com.google.common.collect.Lists; import com.twitter.elephantbird.pig.load.ThriftPigLoader; import com.twitter.elephantbird.thrift.TStructDescriptor; import com.twitter.elephantbird.thrift.TStructDescriptor.Field; import com.twitter.elephantbird.util.ThriftUtils; import com.twitter.elephantbird.util.TypeRef; /** * <li> converts a Thrift struct to a Pig tuple * <li> utilities to provide schema for Pig loaders and Pig scripts */ public class ThriftToPig<M extends TBase<?, ?>> { public static final Logger LOG = LogManager.getLogger(ThriftToPig.class); private static BagFactory bagFactory = BagFactory.getInstance(); private static TupleFactory tupleFactory = TupleFactory.getInstance(); private TStructDescriptor structDesc; public static <M extends TBase<?, ?>> ThriftToPig<M> newInstance(Class<M> tClass) { return new ThriftToPig<M>(tClass); } public static <M extends TBase<?, ?>> ThriftToPig<M> newInstance(TypeRef<M> typeRef) { return new ThriftToPig<M>(typeRef.getRawClass()); } public ThriftToPig(Class<M> tClass) { structDesc = TStructDescriptor.getInstance(tClass); } public TStructDescriptor getTStructDescriptor() { return structDesc; } /** * Converts a thrift object to Pig tuple. * All the fields are deserialized. * It might be better to use getLazyTuple() if not all fields * are required. */ public Tuple getPigTuple(M thriftObj) { return toTuple(structDesc, thriftObj); } /** * Similar to {@link #getPigTuple(TBase)}. This delays * serialization of tuple contents until they are requested. * @param thriftObj * @return */ public Tuple getLazyTuple(M thriftObj) { return new LazyTuple(structDesc, thriftObj); } @SuppressWarnings("unchecked") private static <T extends TBase>Tuple toTuple(TStructDescriptor tDesc, T tObj) { int size = tDesc.getFields().size(); Tuple tuple = tupleFactory.newTuple(size); for (int i=0; i<size; i++) { Field field = tDesc.getFieldAt(i); Object value = tDesc.getFieldValue(i, tObj); try { tuple.set(i, toPigObject(field, value, false)); } catch (ExecException e) { // not expected throw new RuntimeException(e); } } return tuple; } @SuppressWarnings("unchecked") public static Object toPigObject(Field field, Object value, boolean lazy) { if (value == null) { return null; } switch (field.getType()) { case TType.BOOL: return Integer.valueOf((Boolean)value ? 1 : 0); case TType.BYTE : return Integer.valueOf((Byte)value); case TType.I16 : return Integer.valueOf((Short)value); case TType.STRING: return stringTypeToPig(value); case TType.STRUCT: if (lazy) { return new LazyTuple(field.gettStructDescriptor(), (TBase<?, ?>)value); } else { return toTuple(field.gettStructDescriptor(), (TBase<?, ?>)value); } case TType.MAP: return toPigMap(field, (Map<Object, Object>)value, lazy); case TType.SET: return toPigBag(field.getSetElemField(), (Collection<Object>)value, lazy); case TType.LIST: return toPigBag(field.getListElemField(), (Collection<Object>)value, lazy); case TType.ENUM: return value.toString(); default: // standard types : I32, I64, DOUBLE, etc. return value; } } /** * TType.STRING is a mess in Thrift. It could be byte[], ByteBuffer, * or even a String!. */ private static Object stringTypeToPig(Object value) { if (value instanceof String) { return value; } if (value instanceof byte[]) { byte[] buf = (byte[])value; return new DataByteArray(Arrays.copyOf(buf, buf.length)); } if (value instanceof ByteBuffer) { ByteBuffer bin = (ByteBuffer)value; byte[] buf = new byte[bin.remaining()]; bin.mark(); bin.get(buf); bin.reset(); return new DataByteArray(buf); } return null; } private static Map<String, Object> toPigMap(Field field, Map<Object, Object> map, boolean lazy) { // PIG map's key always a String. just use toString() and hope // things would work out ok. HashMap<String, Object> out = new HashMap<String, Object>(map.size()); Field valueField = field.getMapValueField(); for(Entry<Object, Object> e : map.entrySet()) { Object prev = out.put(e.getKey().toString(), toPigObject(valueField, e.getValue(), lazy)); if (prev != null) { String msg = "Duplicate keys while converting to String while " + " processing map " + field.getName() + " (key type : " + field.getMapKeyField().getType() + " value type : " + field.getMapValueField().getType() + ")"; LOG.warn(msg); throw new RuntimeException(msg); } } return out; } private static DataBag toPigBag(Field field, Collection<Object> values, boolean lazy) { List<Tuple> tuples = Lists.newArrayListWithExpectedSize(values.size()); for(Object value : values) { Object pValue = toPigObject(field, value, lazy); if (pValue instanceof Tuple) { // DataBag should contain Tuples tuples.add((Tuple)pValue); } else { tuples.add(tupleFactory.newTuple(pValue)); } } return bagFactory.newDefaultBag(tuples); } @SuppressWarnings("serial") /** * Delays serialization of Thrift fields until they are requested. */ private static class LazyTuple extends AbstractLazyTuple { /* NOTE : This is only a partial optimization. The other part * is to avoid deserialization of the Thrift fields from the * binary buffer. * * Currently TDeserializer allows deserializing just one field, * psuedo-skipping over the fields before it. * But if we are going deserialize 5 fields out of 20, we will be * skipping over same set of fields multiple times. OTOH this might * still be better than a full deserialization. * * We need to write our own version of TBinaryProtocol that truly skips. * Even TDeserializer 'skips'/ignores only after deserializing fields. * (e.g. Strings, Integers, buffers etc). */ private TBase<?, ?> tObject; private TStructDescriptor desc; LazyTuple(TStructDescriptor desc, TBase<?, ?> tObject) { initRealTuple(desc.getFields().size()); this.tObject = tObject; this.desc = desc; } @Override protected Object getObjectAt(int index) { Field field = desc.getFieldAt(index); return toPigObject(field, desc.getFieldValue(index, tObject), true); } } /** * Returns Pig schema for the Thrift struct. */ public static Schema toSchema(Class<? extends TBase<?, ?>> tClass) { return toSchema(TStructDescriptor.getInstance(tClass)); } public Schema toSchema() { return toSchema(structDesc); } public static Schema toSchema(TStructDescriptor tDesc ) { Schema schema = new Schema(); try { for(Field field : tDesc.getFields()) { schema.add(singleFieldToFieldSchema(field.getName(), field)); } } catch (FrontendException t) { throw new RuntimeException(t); } return schema; } /** * return {@link FieldSchema} for a given field. */ private static FieldSchema singleFieldToFieldSchema(String fieldName, Field field) throws FrontendException { //TODO we should probably implement better naming, the current system is pretty nonsensical now switch (field.getType()) { case TType.STRUCT: return new FieldSchema(fieldName, toSchema(field.gettStructDescriptor()), DataType.TUPLE); case TType.LIST: return new FieldSchema(fieldName, singleFieldToTupleSchema(fieldName + "_tuple", field.getListElemField()), DataType.BAG); case TType.SET: return new FieldSchema(fieldName, singleFieldToTupleSchema(fieldName + "_tuple", field.getSetElemField()), DataType.BAG); case TType.MAP: if (field.getMapKeyField().getType() != TType.STRING && field.getMapKeyField().getType() != TType.ENUM) { LOG.warn("Using a map with non-string key for field " + field.getName() + ". while converting to PIG Tuple, toString() is used for the key." + " It could result in incorrect maps."); } return new FieldSchema(fieldName, new Schema(singleFieldToFieldSchema(null, field.getMapValueField())), DataType.MAP); default: return new FieldSchema(fieldName, null, getPigDataType(field)); } } /** * A helper function which wraps a Schema in a tuple (for Pig bags) if our version of pig makes it necessary */ private static Schema wrapInTupleIfPig9(Schema schema) throws FrontendException { if (PigUtil.Pig9orNewer) { return new Schema(new FieldSchema("t",schema,DataType.TUPLE)); } else { return schema; } } /** * Returns a schema with single tuple (for Pig bags). */ private static Schema singleFieldToTupleSchema(String fieldName, Field field) throws FrontendException { switch (field.getType()) { case TType.STRUCT: return wrapInTupleIfPig9(toSchema(field.gettStructDescriptor())); case TType.LIST: case TType.SET: case TType.MAP: return wrapInTupleIfPig9(new Schema(singleFieldToFieldSchema(fieldName, field))); default: return wrapInTupleIfPig9(new Schema(new FieldSchema(fieldName, null, getPigDataType(field)))); } } private static byte getPigDataType(Field field) { switch (field.getType()) { case TType.BOOL: case TType.BYTE: case TType.I16: case TType.I32: return DataType.INTEGER; case TType.ENUM: return DataType.CHARARRAY; case TType.I64: return DataType.LONG; case TType.DOUBLE: return DataType.DOUBLE; case TType.STRING: return field.isBuffer() ? DataType.BYTEARRAY : DataType.CHARARRAY; default: throw new IllegalArgumentException("Unexpected type where a simple type is expected : " + field.getType()); } } /** * Turn a Thrift Struct into a loading schema for a pig script. */ public static String toPigScript(Class<? extends TBase<?, ?>> thriftClass, Class<? extends LoadFunc> pigLoader) { StringBuilder sb = new StringBuilder(); /* we are commenting out explicit schema specification. The schema is * included mainly to help the readers of the pig script. Pig learns the * schema directly from the loader. * If explicit schema is not commented, we might have surprising results * when a Thrift class (possibly in control of another team) changes, * but the Pig script is not updated. Commenting it out avoids this. */ StringBuilder prefix = new StringBuilder(" -- "); sb.append("raw_data = load '$INPUT_FILES' using ") .append(pigLoader.getName()) .append("('") .append(thriftClass.getName()) .append("');\n") .append(prefix) .append("as "); prefix.append(" "); try { stringifySchema(sb, toSchema(thriftClass), DataType.TUPLE, prefix); } catch (FrontendException e) { throw new RuntimeException(e); } sb.append("\n"); return sb.toString(); } /** * Print formatted schema. This is a modified version of * {@link Schema#stringifySchema(StringBuilder, Schema, byte)} * with support for (indented) pretty printing. */ // This is used for building up output string // type can only be BAG or TUPLE public static void stringifySchema(StringBuilder sb, Schema schema, byte type, StringBuilder prefix) throws FrontendException{ // this is a modified version of {@link Schema#stringifySchema(StringBuilder, Schema, byte)} if (type == DataType.TUPLE) { sb.append("(") ; } else if (type == DataType.BAG) { sb.append("{") ; } prefix.append(" "); sb.append("\n").append(prefix); if (schema == null) { sb.append("null") ; } else { boolean isFirst = true ; for (int i=0; i< schema.size() ;i++) { if (!isFirst) { sb.append(",\n").append(prefix); } else { isFirst = false ; } FieldSchema fs = schema.getField(i) ; if(fs == null) { sb.append("null"); continue; } if (fs.alias != null) { sb.append(fs.alias); sb.append(": "); } if (DataType.isAtomic(fs.type)) { sb.append(DataType.findTypeName(fs.type)) ; } else if ( (fs.type == DataType.TUPLE) || (fs.type == DataType.BAG) ) { // safety net if (schema != fs.schema) { stringifySchema(sb, fs.schema, fs.type, prefix) ; } else { throw new AssertionError("Schema refers to itself " + "as inner schema") ; } } else if (fs.type == DataType.MAP) { sb.append(DataType.findTypeName(fs.type) + "["); if (fs.schema!=null) stringifySchema(sb, fs.schema, fs.type, prefix); sb.append("]"); } else { sb.append(DataType.findTypeName(fs.type)) ; } } } prefix.setLength(prefix.length()-2); sb.append("\n").append(prefix); if (type == DataType.TUPLE) { sb.append(")") ; } else if (type == DataType.BAG) { sb.append("}") ; } } public static void main(String[] args) throws Exception { if (args.length > 0) { Class<? extends TBase<?, ?>> tClass = ThriftUtils.getTypeRef(args[0]).getRawClass(); System.out.println(args[0] + " : " + toSchema(tClass).toString()); System.out.println(toPigScript(tClass, ThriftPigLoader.class)); } } }
Fixes compile warning in ThriftToPig
src/java/com/twitter/elephantbird/pig/util/ThriftToPig.java
Fixes compile warning in ThriftToPig
Java
apache-2.0
379602b25ab0e4128fd1ce7b91499548ab48991d
0
nawawi/closure-compiler,google/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,nawawi/closure-compiler,monetate/closure-compiler,google/closure-compiler,google/closure-compiler,google/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.jscomp.InlineAndCollapseProperties.PARTIAL_NAMESPACE_WARNING; import static com.google.javascript.jscomp.InlineAndCollapseProperties.RECEIVER_AFFECTED_BY_COLLAPSE; import com.google.javascript.jscomp.CompilerOptions.ChunkOutputType; import com.google.javascript.jscomp.CompilerOptions.PropertyCollapseLevel; import com.google.javascript.jscomp.deps.ModuleLoader.ResolutionMode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link InlineAndCollapseProperties}. */ @RunWith(JUnit4.class) public final class InlineAndCollapsePropertiesTest extends CompilerTestCase { private static final String EXTERNS = lines( "var window;", // "function alert(s) {}", "function parseInt(s) {}", "/** @constructor */ function String() {};", "var arguments"); public InlineAndCollapsePropertiesTest() { super(EXTERNS); } @Override protected CompilerPass getProcessor(final Compiler compiler) { return InlineAndCollapseProperties.builder(compiler) .setPropertyCollapseLevel(PropertyCollapseLevel.ALL) .setChunkOutputType(ChunkOutputType.GLOBAL_NAMESPACE) .setHaveModulesBeenRewritten(false) .setModuleResolutionMode(ResolutionMode.BROWSER) .build(); } @Override @Before public void setUp() throws Exception { super.setUp(); enableNormalize(); disableCompareJsDoc(); } @Test public void testConstObjRefInTemplateLiteralComputedPropKey() { test( srcs( lines( "var module$name = {}", // "module$name.cssClasses = {", " CLASS_A: 'class-a',", "};", "", "module$name.oldCssClassesMap = {", " [`${module$name.cssClasses.CLASS_A}`]: 'old-class-a',", "};", "")), // TODO(bradfordcsmith): Shouldn't we be leaving the computed property in place? expected("var module$name$cssClasses$CLASS_A = 'class-a';")); } @Test public void testObjLitSpread() { test( lines( "const other = {bar: 'some' };", "let ns = {}", "ns.foo = { ...other };", "use(ns.foo.bar);"), lines("const other = {bar: 'some' };", "var ns$foo = { ...other };", "use(ns$foo.bar);")); } // same behavior with transpiled version of above test @Test public void testObjAssign() { test( lines( "const other = {bar: 'some' };", "let ns = {}", "ns.foo = Object.assign({}, other);", "use(ns.foo.bar);"), lines( "const other = {bar: 'some' };", "var ns$foo = Object.assign({}, other);", "use(ns$foo.bar);")); } @Test public void testObjLitSpread_twoSpreads() { test( lines( "const other = {bar: 'bar' };", "const another = {baz: 'baz' };", "let ns = {};", "ns.foo = { ...other, ...another };", "use(ns.foo.bar, ns.foo.baz);"), lines( "const other = {bar: 'bar' };", "const another = {baz : 'baz'};", "var ns$foo = { ...other, ...another };", "use(ns$foo.bar, ns$foo.baz);")); } // same behavior with transpiled version of above test @Test public void testObjAssign_twoSpreads() { test( lines( "const other = {bar: 'bar'};", "const another = {baz: 'baz'};", "let ns = {};", "ns.foo = Object.assign({}, other, another);", "use(ns.foo.bar, ns.foo.baz);"), lines( "const other = {bar: 'bar'};", "const another = {baz : 'baz'};", "var ns$foo = Object.assign({}, other, another);", "use(ns$foo.bar, ns$foo.baz);")); } @Test public void testObjLitSpread_withNormalPropAfter() { test( lines( "const other = {bar: 'some' };", "let ns = {}", "ns.foo = { ...other, prop : 0};", "use(ns.foo.bar, ns.foo.prop);"), lines( "const other = {bar: 'some' };", // "var ns$foo$prop = 0;", "var ns$foo = { ...other};", "use(ns$foo.bar, ns$foo$prop);")); } @Test public void testObjAssign_withNormalPropAfter() { test( lines( "const other = {bar: 'some' };", "let ns = {}", "ns.foo = Object.assign({}, other, {prop : 0});", "use(ns.foo.bar, ns.foo.prop);"), lines( "const other = {bar: 'some' };", // "var ns$foo = Object.assign({}, other, {prop:0});", "use(ns$foo.bar, ns$foo.prop);")); // both properties not collapsed. } @Test public void testObjLitSpread_chained() { test( lines( "const other = {bar: 'some' };", "let ns = {...other}", "let ns2 = { ...ns };", "use(ns2.bar);"), lines( "const other = {bar: 'some' };", "let ns = { ...other };", "let ns2 = { ...ns };", "use(ns2.bar);")); } // same behavior with transpiled version of above test @Test public void testObjAssign_chained() { test( lines( "const other = {bar: 'some' };", "let ns = Object.assign({}, other);", "let ns2 = Object.assign({}, ns);", "use(ns2.bar);"), lines( "const other = {bar: 'some' };", "let ns = Object.assign({}, other);", "let ns2 = Object.assign({}, ns);", "use(ns2.bar);")); } @Test public void testObjLitSpread_chainedWithGetProp() { test( lines( "const other = {bar: 'some' };", "let ns = {...other};", "let ns2 = {};", "ns2.foo = { ...ns };", "use(ns2.foo.bar);"), lines( "const other = {bar: 'some' };", "let ns = { ...other };", "var ns2$foo = { ...ns };", "use(ns2$foo.bar);")); } // same behavior with transpiled version of above test @Test public void testObjAssign_chainedWithGetProp() { test( lines( "const other = {bar: 'some' };", "let ns = Object.assign({}, other);", "let ns2 = {};", "ns2.foo = Object.assign({}, ns);", "use(ns2.foo.bar);"), lines( "const other = {bar: 'some' };", "let ns = Object.assign({}, other);", "var ns2$foo = Object.assign({}, ns);", "use(ns2$foo.bar);")); } @Test public void testGitHubIssue3733() { testSame( srcs( lines( "const X = {Y: 1};", "", "function fn(a) {", " if (a) {", // Before issue #3733 was fixed GlobalNamespace failed to see this reference // as creating an alias for X due to a switch statement that failed to check // for the RETURN node type, so X.Y was incorrectly collapsed. " return a ? X : {};", " }", "}", "", "console.log(fn(true).Y);"))); } @Test public void testCollapse() { test( "var a = {}; a.b = {}; var c = a.b;", // "var c = null"); test( "var a = {}; a.b = {}; var c = a.b; use(c);", // "var a$b = {}; var c = null; use(a$b);"); testSame("var a = {}; /** @nocollapse */ a.b;"); } @Test public void testOptChainPreventsInlineAndCollapse() { testSame( lines( "var a = {};", "a.b = {};", // c is not really an alias due to optional chain, // and optional chain prevents collapse of a.b. "var c = a?.b;", "use(c);")); test( lines( "var a = {};", // "a.b = {};", "var b = a.b;", // can be inlined and collapsed "b.c = {};", "var c = b?.c;", // opt chain prevents both "use(c);"), lines( "var a$b = {};", // "var b = null;", "a$b.c = {};", "var c = a$b?.c;", "use(c);")); test( lines( "const a = {};", // "a.b = {};", "a.b.c = {};", "const {b} = a;", // can be inlined and collapsed "const c = b?.c;", // opt chain prevents both "use(c);"), lines( "var a$b = {};", // "a$b.c = {};", "const b = null;", "const c = a$b?.c;", "use(c);")); test( lines( "const ns = {};", // "ns.Y = {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y);"), lines( "var ns$Y = {};", // "ns$Y.prop = 3;", "const Y = null;", "use(ns$Y);")); test( lines( "var a = {};", // "a.b = {};", "a.b.c = {};", "var c = a.b?.c;", "use(c);"), lines( "var a$b = {};", // "a$b.c = {};", "var c = a$b?.c;", "use(c);")); test( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y);"), lines( "/** @constructor */", // "var ns$Y = function() {};", "var ns$Y$prop = 3;", "const Y = null;", "use(ns$Y);")); test( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y?.prop);"), lines( "/** @constructor */", // "var ns$Y = function() {};", "var ns$Y$prop = 3;", "const Y = null;", "use(ns$Y?.prop);")); } @Test public void testObjLitDeclaration() { test( "var a = {b: {}, c: {}}; var d = a.b; var e = a.c", // "var d = null; var e = null;"); test( "var a = {b: {}, c: {}}; var d = a.b; var e = a.c; use(d, e);", // "var a$b = {}; var a$c = {}; var d = null; var e = null; use(a$b, a$c);"); test( "var a = {b: {}, /** @nocollapse */ c: {}}; var d = a.b; var e = a.c", // "var a = {/** @nocollapse */ c: {}}; var d = null; var e = null;"); test( "var a = {b: {}, /** @nocollapse */ c: {}}; var d = a.b; var e = a.c; use(d, e);", // "var a$b = {};var a = {/** @nocollapse */ c: {}};var d = null;var e = null;use(a$b, a.c);"); } @Test public void testObjLitDeclarationWithGet1() { testSame("var a = {get b(){}};"); } @Test public void testObjLitDeclarationWithGet2() { test( "var a = {b: {}, get c(){}}; var d = a.b; var e = a.c;", // "var a = {get c() {}}; var d=null; var e = a.c"); test( "var a = {b: {}, get c(){}}; var d = a.b; var e = a.c; use(d);", // "var a$b = {};var a = {get c(){}};var d = null; var e = a.c; use(a$b)"); } @Test public void testObjLitDeclarationWithGet3() { test( "var a = {b: {get c() { return 3; }}};", // "var a$b = {get c() { return 3; }};"); } @Test public void testObjLitDeclarationWithSet1() { testSame("var a = {set b(a){}};"); } @Test public void testObjLitDeclarationWithSet2() { test( "var a = {b: {}, set c(a){}}; var d = a.b; var e = a.c", // "var a = {set c(a$jscomp$1){}}; var d=null; var e = a.c"); test( "var a = {b: {}, set c(a){}}; var d = a.b; var e = a.c; use(d);", // "var a$b = {}; var a = {set c(a$jscomp$1){}}; var d=null; var e = a.c; use(a$b);"); } @Test public void testObjLitDeclarationWithSet3() { test( "var a = {b: {set c(d) {}}};", // "var a$b = {set c(d) {}};"); } @Test public void testObjLitDeclarationWithGetAndSet1() { test( "var a = {b: {get c() { return 3; },set c(d) {}}};", // "var a$b = {get c() { return 3; },set c(d) {}};"); } @Test public void testObjLitAssignmentDepth3() { test( "var a = {}; a.b = {}; a.b.c = {d: 1, e: 2}; var f = a.b.c.d", // "var a$b$c$d = 1; var a$b$c$e = 2; var f = null"); test( "var a = {}; a.b = {}; a.b.c = {d: 1, e: 2}; var f = a.b.c.d; use(f);", // "var a$b$c$d = 1; var a$b$c$e = 2; var f = null; use(a$b$c$d);"); test( lines( "var a = {}; a.b = {}; a.b.c = {d: 1, /** @nocollapse */ e: 2}; ", // "var f = a.b.c.d; var g = a.b.c.e"), "var a$b$c$d = 1; var a$b$c = {/** @nocollapse */ e: 2}; var f = null; var g = null;"); test( lines( "var a = {}; a.b = {}; a.b.c = {d: 1, /** @nocollapse */ e: 2}; ", // "var f = a.b.c.d; var g = a.b.c.e; use(f, g);"), lines( "var a$b$c$d = 1; var a$b$c = { /** @nocollapse */ e: 2};", // "var f = null; var g = null; use(a$b$c$d, a$b$c.e);")); testSame( lines( "var a = {}; /** @nocollapse*/ a.b = {}; ", // "a.b.c = {d: 1, e: 2}; ", "var f = null; var g = null;")); } @Test public void testObjLitAssignmentDepth4() { test( "var a = {}; a.b = {}; a.b.c = {}; a.b.c.d = {e: 1, f: 2}; var g = a.b.c.d.e;", // "var a$b$c$d$e = 1; var a$b$c$d$f = 2; var g = null;"); test( "var a = {}; a.b = {}; a.b.c = {}; a.b.c.d = {e: 1, f: 2}; var g = a.b.c.d.e; use(g);", // "var a$b$c$d$e = 1; var a$b$c$d$f = 2; var g = null; use(a$b$c$d$e);"); } @Test public void testHasOwnProperty() { test( "var a = {'b': 1, 'c': 1}; var alias = a; alert(alias.hasOwnProperty('c'));", // "var a = {'b': 1, 'c': 1}; var alias = null; alert(a.hasOwnProperty('c'));"); } @Test public void testAliasCreatedForObjectDepth1_1() { // An object's properties are not collapsed if the object is referenced // in a such a way that an alias is created for it, if that alias is used. test( "var a = {b: 0}; var c = a; c.b = 1; a.b == c.b;", // "var a$b = 0; var c = null; a$b = 1; a$b == a$b;"); test( "var a = {b: 0}; var c = a; c.b = 1; a?.b == c?.b;", "var a = {b: 0}; var c = null; a.b = 1; a?.b == a?.b;"); test( "var a = {b: 0}; var c = a; c.b = 1; a.b == c.b; use(c);", // "var a={b:0}; var c=null; a.b=1; a.b == a.b; use(a);"); } @Test public void testAliasCreatedForObjectDepth1_2() { testSame("var a = {b: 0}; f(a); a.b;"); } @Test public void testAliasCreatedForObjectDepth1_3() { testSame("var a = {b: 0}; new f(a); a.b;"); } @Test public void testMisusedConstructorTag() { test( lines( "var a = {}; var d = a; a.b = function() {};", // "/** @constructor */ a.b.c = 0; a.b.c;"), "var d=null; var a$b=function(){}; /** @constructor */ var a$b$c=0; a$b$c;"); } @Test public void testAliasCreatedForCtorDepth1_1() { // A constructor's properties *are* collapsed even if the function is // referenced in a such a way that an alias is created for it, // since a function with custom properties is considered a class and its // non-prototype properties are considered static methods and variables. // People don't typically iterate through static members of a class or // refer to them using an alias for the class name. test( lines( "/** @constructor */ var a = function(){}; a.b = 1; ", // "var c = a; c.b = 2; a.b == c.b;"), lines( "/** @constructor */ var a = function(){}; var a$b = 1;", // "var c = null; a$b = 2; a$b == a$b;")); test( lines( "/** @constructor */ var a = function(){}; a.b = 1; ", // "var c = a; c.b = 2; a?.b == c?.b;"), lines( "/** @constructor */ var a = function(){}; var a$b = 1;", // "var c = null; a$b = 2; a?.b == a?.b;")); // Sometimes we want to prevent static members of a constructor from // being collapsed. test( lines( "/** @constructor */ var a = function(){};", // "/** @nocollapse */ a.b = 1; var c = a; c.b = 2; a.b == c.b;"), lines( "/** @constructor */ var a = function(){};", // "/** @nocollapse */ a.b = 1; var c = null; a.b = 2; a.b == a.b;")); test( lines( "/** @constructor */ var a = function(){};", // "/** @nocollapse */ a.b = 1; var c = a; c.b = 2; a?.b == c?.b;"), lines( "/** @constructor */ var a = function(){};", // "/** @nocollapse */ a.b = 1; var c = null; a.b = 2; a?.b == a?.b;")); } @Test public void testAliasCreatedForFunctionDepth2() { test( "var a = {}; a.b = function() {}; a.b.c = 1; var d = a.b; a.b.c != d.c;", // "var a$b = function() {}; var a$b$c = 1; var d = null; a$b$c != a$b$c;"); testSame("var a = {}; a.b = function() {}; a.b.c = 1; var d = a?.b; a.b?.c != d?.c;"); test( lines( "var a = {}; a.b = function() {}; /** @nocollapse */ a.b.c = 1;", // "var d = a.b; a.b.c == d.c;"), "var a$b = function() {}; /** @nocollapse */ a$b.c = 1; var d = null; a$b.c == a$b.c;"); } @Test public void testAliasCreatedForCtorDepth2() { test( lines( "var a = {}; /** @constructor */ a.b = function() {}; a.b.c = 1; var d = a.b;", // "a.b.c == d.c;"), lines( "/** @constructor */ var a$b = function() {}; var a$b$c = 1; var d = null;", // "a$b$c == a$b$c;")); testSame( srcs( lines( "var a = {}; /** @constructor */ a.b = function() {}; a.b.c = 1; var d = a?.b;", // "a.b?.c == d?.c;")), warning(PARTIAL_NAMESPACE_WARNING)); test( lines( "var a = {}; /** @constructor */ a.b = function() {}; ", // "/** @nocollapse */ a.b.c = 1; var d = a.b;", "a.b.c == d.c;"), lines( "/** @constructor */ var a$b = function() {};", "/** @nocollapse */ a$b.c = 1; var d = null;", "a$b.c == a$b.c;")); } @Test public void testAliasCreatedForClassDepth1_1() { test( lines( "var a = {}; /** @constructor */ a.b = function(){};", // "var c = a; c.b = 0; a.b == c.b;"), lines( "/** @constructor */ var a$b = function(){};", // "var c = null; a$b = 0; a$b == a$b;")); test( srcs( lines( "var a = {}; /** @constructor */ a.b = function(){};", // // `a?.b` and `c?.b` are aliasing gets "var c = a; c.b = 0; a?.b == c?.b;")), expected( lines( "var a = {}; /** @constructor */ a.b = function(){};", // // `a?.b` and `c?.b` are aliasing gets "var c = null; a.b = 0; a?.b == a?.b;")), warning(PARTIAL_NAMESPACE_WARNING)); testSame( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = 1; c = a; c.b = 0; a.b == c.b;"), PARTIAL_NAMESPACE_WARNING); testSame( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = 1; c = a; c.b = 0; a?.b == c?.b;"), PARTIAL_NAMESPACE_WARNING); test( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = a; c.b = 0; a.b == c.b;"), lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = null; a.b = 0; a.b == a.b;")); test( srcs( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = a; c.b = 0; a?.b == c?.b;")), expected( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = null; a.b = 0; a?.b == a?.b;")), warning(PARTIAL_NAMESPACE_WARNING)); test( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = a; c.b = 0; a.b == c.b; use(c);"), lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = null; a.b = 0; a.b == a.b; use(a);"), warning(PARTIAL_NAMESPACE_WARNING)); test( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = a; c.b = 0; a?.b == c?.b; use(c);"), lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = null; a.b = 0; a?.b == a?.b; use(a);"), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testObjLitDeclarationUsedInSameVarList() { // The collapsed properties must be defined in the same place in the var list // where they were originally defined (and not, for example, at the end). test( "var a = {b: {}, c: {}}; var d = a.b; var e = a.c; use(d, e);", // "var a$b = {}; var a$c = {}; var d = null; var e = null; use(a$b, a$c);"); test( "var a = {b: {}, /** @nocollapse */ c: {}}; var d = a.b; var e = a.c; use(d, e);", // "var a$b = {};var a = {/** @nocollapse */ c: {}};var d = null;var e = null;use(a$b, a.c);"); } @Test public void testAddPropertyToUncollapsibleObjectInLocalScopeDepth1() { test( "var a = {}; var c = a; use(c); (function() {a.b = 0;})(); a.b;", // "var a={}; var c=null; use(a); (function(){ a.b = 0; })(); a.b;"); test( "var a = {}; var c = 1; c = a; (function() {a.b = 0;})(); a.b;", // "var a = {}; var c=1; c = a; (function(){a.b = 0;})(); a.b;"); } @Test public void testAddPropertyToUncollapsibleNamedCtorInLocalScopeDepth1() { test( lines( "/** @constructor */ function a() {} var a$b; var c = a; ", // "(function() {a$b = 0;})(); a$b;"), lines( "/** @constructor */ function a() {} var a$b; var c = null; ", // "(function() {a$b = 0;})(); a$b;")); } @Test public void testAddPropertyToUncollapsibleCtorInLocalScopeDepth1() { test( lines( "/** @constructor */ var a = function() {}; var c = a; ", // "(function() {a.b = 0;})(); a.b;"), lines( "/** @constructor */ var a = function() {}; var a$b; ", // "var c = null; (function() {a$b = 0;})(); a$b;")); } @Test public void testAddPropertyToUncollapsibleObjectInLocalScopeDepth2() { test( lines( "var a = {}; a.b = {}; var d = a.b; use(d);", // "(function() {a.b.c = 0;})(); a.b.c;"), lines( "var a$b = {}; var d = null; use(a$b);", // "(function() {a$b.c = 0;})(); a$b.c;")); } @Test public void testAddPropertyToUncollapsibleCtorInLocalScopeDepth2() { test( lines( "var a = {}; /** @constructor */ a.b = function (){}; var d = a.b;", // "(function() {a.b.c = 0;})(); a.b.c;"), lines( "/** @constructor */ var a$b = function (){}; var a$b$c; var d = null;", // "(function() {a$b$c = 0;})(); a$b$c;")); } @Test public void testPropertyOfChildFuncOfUncollapsibleObjectDepth1() { test( "var a = {}; var c = a; a.b = function (){}; a.b.x = 0; a.b.x;", // "var c = null; var a$b=function() {}; var a$b$x = 0; a$b$x;"); test( "var a = {}; var c = a; a.b = function (){}; a.b.x = 0; a.b.x; use(c);", // "var a = {}; var c = null; a.b=function() {}; a.b.x = 0; a.b.x; use(a);"); } @Test public void testPropertyOfChildFuncOfUncollapsibleObjectDepth2() { test( "var a = {}; a.b = {}; var c = a.b; a.b.c = function (){}; a.b.c.x = 0; a.b.c.x;", // "var c=null; var a$b$c = function(){}; var a$b$c$x = 0; a$b$c$x"); test( "var a = {}; a.b = {}; var c = a.b; a.b.c = function (){}; a.b.c.x = 0; a.b.c.x;" + " use(c);", // "var a$b = {}; var c=null; a$b.c = function(){}; a$b.c.x=0; a$b.c.x; use(a$b);"); } @Test public void testAddPropertyToChildFuncOfUncollapsibleObjectInLocalScope() { test( lines( "var a = {}; a.b = function (){}; a.b.x = 0;", // "var c = a; (function() {a.b.y = 1;})(); a.b.x; a.b.y;"), lines( "var a$b=function() {}; var a$b$y; var a$b$x = 0; var c=null;", // "(function() { a$b$y=1; })(); a$b$x; a$b$y")); } @Test public void testAddPropertyToChildTypeOfUncollapsibleObjectInLocalScope() { test( lines( "var a = {};", // "/** @constructor */", "a.b = function (){};", "a.b.x = 0;", "var c = a;", "(function() {a.b.y = 1;})();", "a.b.x;", "a.b.y;"), lines( "/** @constructor */", // "var a$b = function (){};", "var a$b$y;", "var a$b$x = 0;", "var c = null;", "(function() {a$b$y = 1;})();", "a$b$x;", "a$b$y;")); test( lines( "var a = {};", // "/** @constructor */", "a.b = function (){};", "a.b.x = 0;", "var c = a;", "(function() {a.b.y = 1;})();", "a.b.x;", "a.b.y;", "use(c);"), lines( "var a = {};", // "/** @constructor */", "a.b = function (){};", "a.b.x = 0;", "var c = null;", "(function() {a.b.y = 1;})();", "a.b.x;", "a.b.y;", "use(a);"), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testAddPropertyToChildOfUncollapsibleFunctionInLocalScope() { test( "function a() {} a.b = {x: 0}; var c = a; (function() {a.b.y = 0;})(); a.b.y;", // "function a() {} var a$b$x=0; var a$b$y; var c=null; (function(){a$b$y=0})(); a$b$y"); } @Test public void testAddPropertyToChildOfUncollapsibleCtorInLocalScope() { test( lines( "/** @constructor */ var a = function() {}; a.b = {x: 0}; var c = a;", // "(function() {a.b.y = 0;})(); a.b.y;"), lines( "/** @constructor */ var a = function() {}; var a$b$x = 0; var a$b$y; var c = null;", // "(function() {a$b$y = 0;})(); a$b$y;")); } @Test public void testLocalAliasCreatedAfterVarDeclaration1() { test( lines( "var a = {b: 3};", // "function f() {", " var tmp;", " tmp = a;", " use(tmp.b);", "}"), lines( "var a$b = 3", // "function f() {", " var tmp;", " tmp = null;", " use(a$b);", "}")); test( lines( "var a = {b: 3};", // "function f() {", " var tmp;", " tmp = a;", " use?.(tmp?.b);", "}"), lines( "var a = {b: 3};", // "function f() {", " var tmp;", " tmp = null;", " use?.(a?.b);", "}")); } @Test public void testLocalAliasCreatedAfterVarDeclaration2() { test( lines( "var a = {b: 3}", // "function f() {", " var tmp;", " if (true) {", " tmp = a;", " use(tmp.b);", " }", "}"), lines( "var a$b = 3;", // "function f() {", " var tmp;", " if (true) {", " tmp = null;", " use(a$b);", " }", "}")); test( lines( "var a = {b: 3}", // "function f() {", " var tmp;", " if (true) {", " tmp = a;", " use?.(tmp?.b);", " }", "}"), lines( "var a = {b: 3}", // "function f() {", " var tmp;", " if (true) {", " tmp = null;", " use?.(a?.b);", " }", "}")); } @Test public void testLocalAliasCreatedAfterVarDeclaration3() { testSame( lines( "var a = { b : 3 };", // "function f() {", " var tmp;", " if (true) {", " tmp = a;", " }", " use(tmp);", "}")); } @Test public void testPartialLocalCtorAlias() { testWarning( lines( "/** @constructor */ var Main = function() {};", // "Main.doSomething = function(i) {}", "function f() {", " var tmp;", " if (g()) {", " use(tmp.doSomething);", " tmp = Main;", " tmp.doSomething(5);", " }", " use(tmp.doSomething);", // can't inline this use of tmp. "}"), InlineAndCollapseProperties.UNSAFE_CTOR_ALIASING); } @Test public void testFunctionAlias2() { test( "var a = {}; a.b = {}; a.b.c = function(){}; a.b.d = a.b.c;use(a.b.d)", // "var a$b$c = function(){}; var a$b$d = null;use(a$b$c);"); test( "var a = {}; a.b = {}; a.b.c = function(){}; a.b.d = a.b?.c; use?.(a.b?.d);", // "var a$b = {}; a$b.c = function(){}; a$b.d = a$b?.c; use?.(a$b?.d);"); } @Test public void testLocalAlias1() { test( "var a = {b: 3}; function f() { var x = a; f(x.b); }", // "var a$b = 3 ; function f() { var x = null; f(a$b); }"); test( "var a = {b: 3}; function f() { var x = a; f(x?.b); }", "var a = {b: 3}; function f() { var x = null; f(a?.b); }"); } @Test public void testLocalAlias2() { test( "var a = {b: 3, c : 4}; function f() { var x = a; f(x.b); f(x.c);}", "var a$b = 3; var a$c = 4 ; function f() { var x = null; f(a$b); f(a$c);}"); test( "var a = {b: 3, c: 4}; function f() { var x = a; f?.(x?.b); f?.(x?.c);}", "var a = {b: 3, c: 4}; function f() { var x = null; f?.(a?.b); f?.(a?.c);}"); } @Test public void testLocalAlias3() { test( lines( "var a = {b: 3, c: {d: 5}}; ", // "function f() { var x = a; f(x.b); f(x.c); f(x.c.d); }"), lines( "var a$b = 3; var a$c = {d: 5}; ", // "function f() { var x = null; f(a$b); f(a$c); f(a$c.d);}")); test( lines( "var a = {b: 3, c: {d: 5}};", // "function f() { var x = a; f?.(x?.b); f?.(x?.c); f?.(x.c?.d);}"), lines( "var a = {b: 3, c: {d:5}};", // "function f() { var x = null; f?.(a?.b); f?.(a?.c); f?.(a.c?.d);}")); } @Test public void testLocalAlias4() { test( lines( "var a = {b: 3}; var c = {d: 5}; ", // "function f() { var x = a; var y = c; f(x.b); f(y.d); }"), lines( "var a$b = 3; var c$d = 5; ", // "function f() { var x = null; var y = null; f(a$b); f(c$d);}")); test( lines( "var a = {b: 3}; var c = {d: 5};", // "function f() { var x = a; var y = c; f?.(x?.b); f?.(y?.d); }"), lines( "var a = {b: 3}; var c = {d: 5};", // "function f() { var x = null; var y = null; f?.(a?.b); f?.(c?.d); }")); } @Test public void testLocalAlias5() { test( lines( "var a = {b: {c: 5}}; ", // "function f() { var x = a; var y = x.b; f(a.b.c); f(y.c); }"), lines( "var a$b$c = 5; ", // "function f() { var x = null; var y = null; f(a$b$c); f(a$b$c);}")); test( lines( "var a = {b: {c: 5}};", // "function f() { var x = a; var y = x?.b; f?.(a.b?.c); f?.(y?.c); }"), lines( "var a = {b: {c: 5}};", // "function f() { var x = null; var y = a?.b; f?.(a.b?.c); f?.(y?.c); }")); } @Test public void testLocalAlias6() { test( "var a = {b: 3}; function f() { var x = a; if (x.b) { f(x.b); } }", // "var a$b = 3; function f() { var x = null; if (a$b) { f(a$b); } }"); test( "var a = {b: 3}; function f() { var x = a; if (x?.b) { f?.(x?.b); } }", // "var a = {b: 3}; function f() { var x = null; if (a?.b) { f?.(a?.b); } }"); } @Test public void testLocalAlias7() { test( "var a = {b: {c: 5}}; function f() { var x = a.b; f(x.c); }", // "var a$b$c = 5; function f() { var x = null; f(a$b$c); }"); testSame("var a = {b: {c: 5}}; function f() { var x = a?.b; f?.(x?.c); }"); } @Test public void testLocalAlias8() { testSame("var a = { b: 3 }; function f() { if (true) { var x = a; f(x.b); } x = { b : 4}; }"); } @Test public void testGlobalWriteToAncestor() { testSame("var a = {b: 3}; function f() { var x = a; f(a.b); } a = 5;"); } @Test public void testGlobalWriteToNonAncestor() { test( "var a = {b: 3}; function f() { var x = a; f(a.b); } a.b = 5;", // "var a$b = 3; function f() { var x = null; f(a$b); } a$b = 5;"); test( "var a = {b: 3}; function f() { var x = a; f(a?.b); } a.b = 5;", "var a = {b: 3}; function f() { var x = null; f(a?.b); } a.b = 5;"); } @Test public void testLocalWriteToAncestor() { testSame("var a = {b: 3}; function f() { a = 5; var x = a; f(a.b); } "); } @Test public void testLocalWriteToNonAncestor() { test( lines( "var a = {b: 3}; ", // "function f() { a.b = 5; var x = a; f(a.b); }"), "var a$b = 3; function f() { a$b = 5; var x = null; f(a$b); } "); test( lines( "var a = {b: 3}; ", // "function f() { a.b = 5; var x = a; f?.(a?.b); }"), lines( "var a = {b: 3}; ", // "function f() { a.b = 5; var x = null; f?.(a?.b); }")); } @Test public void testLocalAliasOfAncestor() { testSame( lines( "var a = {b: {c: 5}}; function g() { f(a); } ", // "function f() { var x = a.b; f(x.c); }")); } @Test public void testGlobalAliasOfAncestor() { test( "var a = {b: {c: 5}}; function f() { var x = a.b; f(x.c); }", // "var a$b$c=5; function f() {var x=null; f(a$b$c); }"); testSame("var a = {b: {c: 5}}; function f() { var x = a?.b; f?.(x?.c); }"); } @Test public void testLocalAliasOfOtherName() { testSame( lines( "var foo = function() { return {b: 3}; };", // "var a = foo(); a.b = 5; ", "function f() { var x = a.b; f(x); }")); } @Test public void testLocalAliasOfFunction() { test( lines( "var a = function() {}; a.b = 5; ", // "function f() { var x = a.b; f(x); }"), lines( "var a = function() {}; var a$b = 5; ", // "function f() { var x = null; f(a$b); }")); } @Test public void testNoInlineGetpropIntoCall() { test( "var b = x; function f() { var a = b; a(); }", // "var b = x; function f() { var a = null; b(); }"); test( "var b = {}; b.c = x; function f() { var a = b.c; a(); }", // "var b$c = x; function f() { var a = null; b$c(); }"); } @Test public void testCommaOperator() { test( "var a = {}; a.b = function() {}, a.b();", // "var a$b; a$b=function() {}, a$b();"); test( lines( "var ns = {};", // "ns.Foo = {};", "var Baz = {};", "Baz.Foo = ns.Foo;", "(Baz.Foo.bar = 10, 123);"), lines( "var Baz$Foo=null;", // "var ns$Foo$bar;", "(ns$Foo$bar = 10, 123);")); test( lines( "var ns = {};", // "ns.Foo = {};", "var Baz = {};", "Baz.Foo = ns?.Foo;", "(Baz.Foo.bar = 10, 123);"), lines( "var ns = {};", // "ns.Foo = {};", "var Baz$Foo = ns?.Foo;", "(Baz$Foo.bar = 10, 123);")); test( lines( "var ns = {};", // "ns.Foo = {};", "var Baz = {};", "Baz.Foo = ns.Foo;", "function f() { (Baz.Foo.bar = 10, 123); }"), lines( "var ns$Foo$bar;", // "var Baz$Foo=null;", "function f() { (ns$Foo$bar = 10, 123); }")); test( lines( "var ns = {};", // "ns.Foo = {};", "var Baz = {};", "Baz.Foo = ns?.Foo;", "function f() { (Baz.Foo.bar = 10, 123); }"), lines( "var ns = {};", // "ns.Foo = {};", "var Baz$Foo = ns?.Foo;", "function f() { (Baz$Foo.bar = 10, 123); }")); } @Test public void testTypeDefAlias1() { test( lines( "/** @constructor */ var D = function() {};", // "/** @constructor */ D.L = function() {};", "/** @type {D.L} */ D.L.A = new D.L();", "", "/** @const */ var M = {};", "/** @typedef {D.L} */ M.L = D.L;", "", "use(M.L.A);"), lines( "/** @constructor */ var D = function() {};", // "/** @constructor */ var D$L = function() {};", "/** @type {D.L} */ var D$L$A = new D$L();", "/** @typedef {D.L} */ var M$L = null", "use(D$L$A);")); test( lines( "/** @constructor */ var D = function() {};", // "/** @constructor */ D.L = function() {};", "/** @type {D.L} */ D.L.A = new D.L();", "", "/** @const */ var M = {};", "/** @typedef {D.L} */ M.L = D.L;", "", "use?.(M.L?.A);"), lines( "/** @constructor */ var D = function() {};", // "/** @constructor */ var D$L = function() {};", "/** @type {D.L} */ var D$L$A = new D$L();", "/** @typedef {D.L} */ var M$L = null", // TODO(b/148237949): collapse above breaks this reference "use?.(D$L?.A);")); } @Test public void testGlobalAliasWithProperties1() { test( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns.Foo;", "var x = function() {use(ns.Bar.EventType.A)};", "use(x);"), lines( "/** @constructor */ var ns$Foo = function(){};", // "var ns$Foo$EventType$A = 1;", "var ns$Foo$EventType$B = 2;", "/** @constructor */ var ns$Bar = null;", "var x = function(){use(ns$Foo$EventType$A)};", "use(x);")); testSame( srcs( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns?.Foo;", "var x = function() {use?.(ns.Bar.EventType?.A)};", "use?.(x);")), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testGlobalAliasWithProperties2() { // Reassignment of properties was necessary to prevent invalid code in // previous iterations of this optimization. Verify we don't break // code like this. Now it causes a back-off of the collapsing because // the value is assigned more than once. test( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns.Foo;", "/** @enum {number} */ ns.Bar.EventType = ns.Foo.EventType;", "var x = function() {use(ns.Bar.EventType.A)};", "use(x)"), lines( "/** @constructor */ var ns$Foo = function(){};", // "/** @enum {number} */ var ns$Foo$EventType = {A:1, B:2};", "/** @constructor */ var ns$Bar = null;", "/** @enum {number} */ ns$Foo$EventType = ns$Foo$EventType;", "var x = function(){use(ns$Foo$EventType.A)};", "use(x);")); testSame( srcs( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns?.Foo;", "/** @enum {number} */ ns.Bar.EventType = ns.Foo?.EventType;", "var x = function() {use?.(ns.Bar.EventType?.A)};", "use?.(x)")), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testGlobalAliasWithProperties3() { test( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns.Foo;", "/** @enum {number} */ ns.Bar.Other = {X:1, Y:2};", "var x = function() {use(ns.Bar.Other.X)};", "use(x)"), lines( "/** @constructor */ var ns$Foo=function(){};", // "var ns$Foo$EventType$A=1;", "var ns$Foo$EventType$B=2;", "/** @constructor */ var ns$Bar=null;", "var ns$Foo$Other$X=1;", "var ns$Foo$Other$Y=2;", "var x=function(){use(ns$Foo$Other$X)};", "use(x)\n")); testSame( srcs( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns?.Foo;", "/** @enum {number} */ ns.Bar.Other = {X:1, Y:2};", "var x = function() {use?.(ns.Bar.Other?.X)};", "use?.(x)")), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testGlobalAliasWithProperties4() { testSame( lines( "", // "var nullFunction = function(){};", "var blob = {};", "blob.init = nullFunction;", "use(blob)")); } @Test public void testGlobalAlias_propertyOnExternedConstructor_isNotChanged() { testSame( externs("/** @constructor */ var blob = function() {}"), srcs( lines( "var nullFunction = function(){};", // "blob.init = nullFunction;", "use(blob.init)"))); } @Test public void testLocalAliasOfEnumWithInstanceofCheck() { test( lines( "/** @constructor */", // "var Enums = function() {", "};", "", "/** @enum {number} */", "Enums.Fruit = {", " APPLE: 1,", " BANANA: 2,", "};", "", "function foo(f) {", " if (f instanceof Enums) { alert('what?'); return; }", "", " var Fruit = Enums.Fruit;", " if (f == Fruit.APPLE) alert('apple');", " if (f == Fruit.BANANA) alert('banana');", "}"), lines( "/** @constructor */", // "var Enums = function() {};", "var Enums$Fruit$APPLE = 1;", "var Enums$Fruit$BANANA = 2;", "function foo(f) {", " if (f instanceof Enums) { alert('what?'); return; }", " var Fruit = null;", " if (f == Enums$Fruit$APPLE) alert('apple');", " if (f == Enums$Fruit$BANANA) alert('banana');", "}")); } @Test public void testCollapsePropertiesOfClass1() { test( lines( "/** @constructor */", // "var namespace = function() {};", "goog.inherits(namespace, Object);", "", "namespace.includeExtraParam = true;", "", "/** @enum {number} */", "namespace.Param = {", " param1: 1,", " param2: 2", "};", "", "if (namespace.includeExtraParam) {", " namespace.Param.optParam = 3;", "}", "", "function f() {", " var Param = namespace.Param;", " log(namespace.Param.optParam);", " log(Param.optParam);", "}"), lines( "/** @constructor */", // "var namespace = function() {};", "goog.inherits(namespace, Object);", "var namespace$includeExtraParam = true;", "var namespace$Param$param1 = 1;", "var namespace$Param$param2 = 2;", "if (namespace$includeExtraParam) {", " var namespace$Param$optParam = 3;", "}", "function f() {", " var Param = null;", " log(namespace$Param$optParam);", " log(namespace$Param$optParam);", "}")); // TODO(b/148237949): CollapseProperties breaks several optional chain references here test( lines( "/** @constructor */", // "var namespace = function() {};", "goog.inherits(namespace, Object);", "", "namespace.includeExtraParam = true;", "", "/** @enum {number} */", "namespace.Param = {", " param1: 1,", " param2: 2", "};", "", "if (namespace?.includeExtraParam) {", " namespace.Param.optParam = 3;", "}", "", "function f() {", " var Param = namespace?.Param;", " log(namespace.Param?.optParam);", " log(Param?.optParam);", "}"), lines( "/** @constructor */", // "var namespace = function() {};", "goog.inherits(namespace, Object);", "var namespace$includeExtraParam = true;", "var namespace$Param$param1 = 1;", "var namespace$Param$param2 = 2;", "/** @enum {number} */", "var namespace$Param = {", " param1: namespace$Param$param1,", " param2: namespace$Param$param2", "};", "if (namespace?.includeExtraParam) {", // broken " var namespace$Param$optParam = 3;", "}", "function f() {", " var Param = namespace?.Param;", // broken " log(namespace$Param?.optParam);", // broken " log(Param?.optParam);", // broken "}")); } @Test public void testCollapsePropertiesOfClass2() { test( lines( "var goog = goog || {};", // "goog.addSingletonGetter = function(cls) {};", "", "var a = {};", "", "/** @constructor */", "a.b = function() {};", "goog.addSingletonGetter(a.b);", "a.b.prototype.get = function(key) {};", "", "/** @constructor */", "a.b.c = function() {};", "a.b.c.XXX = new a.b.c();", "", "function f() {", " var x = a.b.getInstance();", " var Key = a.b.c;", " x.get(Key.XXX);", "}"), lines( "var goog = goog || {};", // "var goog$addSingletonGetter = function(cls) {};", "/** @constructor */", "var a$b = function() {};", "goog$addSingletonGetter(a$b);", "a$b.prototype.get = function(key) {};", "/** @constructor */", "var a$b$c = function() {};", "var a$b$c$XXX = new a$b$c();", "", "function f() {", " var x = a$b.getInstance();", " var Key = null;", " x.get(a$b$c$XXX);", "}")); } @Test public void test_b19179602() { // Note that this only collapses a.b.staticProp because a.b is a constructor. // Normally AggressiveInlineAliases would not inline "b" inside the loop. test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f() {", " while (true) {", // b is declared inside a loop, so it is reassigned multiple times " var b = a.b;", " alert(b.staticProp);", " }", "}"), lines( "/** @constructor */ var a$b = function() {};", // "var a$b$staticProp = 5;", "function f() {", " while (true) {", " var b = null;", " alert(a$b$staticProp);", " }", "}")); test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f() {", " while (true) {", // b is declared inside a loop, so it is reassigned multiple times " var b = a.b;", " alert(b?.staticProp);", " }", "}"), lines( "/** @constructor */ var a$b = function() {};", // "var a$b$staticProp = 5;", "function f() {", " while (true) {", " var b = null;", // TODO(bradfordcsmith): This reference is broken by collapsing above. " alert(a$b?.staticProp);", " }", "}")); } @Test public void test_b19179602_declareOutsideLoop() { test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f() {", // b is declared outside the loop " var b = a.b;", " while (true) {", " alert(b.staticProp);", " }", "}"), lines( "/** @constructor */", // "var a$b = function() {};", "var a$b$staticProp = 5;", "", "function f() {", " var b = null;", " while (true) {", " alert(a$b$staticProp);", " }", "}")); test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f() {", // b is declared outside the loop " var b = a.b;", " while (true) {", " alert(b?.staticProp);", " }", "}"), lines( "/** @constructor */", // "var a$b = function() {};", // TODO(b/148237949): Collapsing this breaks the optional chain reference below. "var a$b$staticProp = 5;", "", "function f() {", " var b = null;", " while (true) {", " alert(a$b?.staticProp);", " }", "}")); } @Test public void testCtorManyAssignmentsDontInlineWarn() { test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f(y, z) {", " var x = a.b;", " if (y) {", " x = z;", " }", " return x.staticProp;", "}"), lines( "/** @constructor */ var a$b = function() {};", // "var a$b$staticProp = 5;", "function f(y, z) {", " var x = a$b;", " if (y) {", " x = z;", " }", " return x.staticProp;", "}"), warning(InlineAndCollapseProperties.UNSAFE_CTOR_ALIASING)); } @Test public void testCodeGeneratedByGoogModule() { // The static property is added to the exports object test( lines( "var $jscomp = {};", // "$jscomp.scope = {};", "/** @constructor */", "$jscomp.scope.Foo = function() {};", "var exports = $jscomp.scope.Foo;", "exports.staticprop = {A:1};", "var y = exports.staticprop.A;"), lines( "/** @constructor */", // "var $jscomp$scope$Foo = function() {}", "var exports = null;", "var $jscomp$scope$Foo$staticprop$A = 1;", "var y = null;")); // The static property is added to the constructor test( lines( "var $jscomp = {};", // "$jscomp.scope = {};", "/** @constructor */", "$jscomp.scope.Foo = function() {};", "$jscomp.scope.Foo.staticprop = {A:1};", "var exports = $jscomp.scope.Foo;", "var y = exports.staticprop.A;"), lines( "/** @constructor */", // "var $jscomp$scope$Foo = function() {}", "var $jscomp$scope$Foo$staticprop$A = 1;", "var exports = null;", "var y = null;")); } @Test public void testInlineCtorInObjLit() { test( lines( "/** @constructor */", // "function Foo() {}", "", "/** @constructor */", "var Bar = Foo;", "", "var objlit = {", " 'prop' : Bar", "};"), lines( "/** @constructor */", // "function Foo() {}", "/** @constructor */", "var Bar = null;", "var objlit$prop = Foo;")); } @Test public void testNoCollapseExportedNode() { test( "var x = {}; x.y = {}; var dontExportMe = x.y; use(dontExportMe);", // "var x$y = {}; var dontExportMe = null; use(x$y);"); test( "var x = {}; x.y = {}; var _exportMe = x.y;", // "var x$y = {}; var _exportMe = x$y;"); } @Test public void testDontCrashCtorAliasWithEnum() { test( lines( "var ns = {};", // "/** @constructor */", "ns.Foo = function () {};", "var Bar = ns.Foo;", "/** @const @enum */", "Bar.prop = { A: 1 };"), lines( "/** @constructor */", // "var ns$Foo = function(){};", "var Bar = null;", "var ns$Foo$prop$A = 1")); } @Test public void testDontCrashNamespaceAliasAcrossScopes() { test( lines( "var ns = {};", // "ns.VALUE = 0.01;", "function f() {", " var constants = ns;", " (function() {", " var x = constants.VALUE;", " })();", "}"), null); } @Test public void testGlobalAliasWithLet() { test( "let ns = {}; ns.foo = 'bar'; let ns2 = ns; use(ns2.foo);", // "var ns$foo = 'bar'; let ns2 = null; use(ns$foo);"); test( "let ns = {}; ns.foo = 'bar'; let ns2 = ns; use?.(ns2?.foo);", // "let ns = {}; ns.foo = 'bar'; let ns2 = null; use?.( ns?.foo);"); } @Test public void testGlobalAliasForLet2() { // We don't do any sort of branch prediction, so can't collapse here. testSame( lines( "let ns = {};", // "ns.foo = 'bar';", "let ns2;", "if (true) {", " ns2 = ns;", "}", "use(ns2.foo);")); } @Test public void testGlobalAliasWithLet3() { // Back off since in general we don't check that ns2 is only ever accessed within the if block. testSame( lines( "let ns = {};", // "ns.foo = 'bar';", "let ns2;", "if (true) {", " ns2 = ns;", " use(ns2.foo);", "}")); } @Test public void testLocalAliasWithLet1() { test( "let ns = {}; ns.foo = 'bar'; function f() { let ns2 = ns; use(ns2.foo); }", "var ns$foo = 'bar'; function f() { let ns2 = null; use( ns$foo); }"); test( "let ns = {}; ns.foo = 'bar'; function f() { let ns2 = ns; use?.(ns2?.foo); }", "let ns = {}; ns.foo = 'bar'; function f() { let ns2 = null; use?.( ns?.foo); }"); } @Test public void testLocalAliasWithLet2() { test( lines( "let ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " let ns2 = ns;", " use(ns2.foo);", " }", "}"), lines( "var ns$foo = 'bar';", // "function f() {", " if (true) {", " let ns2 = null;", " use(ns$foo);", " }", "}")); test( lines( "let ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " let ns2 = ns;", " use?.(ns2?.foo);", " }", "}"), lines( "let ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " let ns2 = null;", " use?.(ns?.foo);", " }", "}")); } @Test public void testLocalAliasWithLet3() { test( lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let ns2 = ns;", " use(ns2.foo);", "}"), lines( "var ns$foo = 'bar';", // "if (true) {", " let ns2 = null;", " use(ns$foo);", "}")); test( lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let ns2 = ns;", " use?.(ns2?.foo);", "}"), lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let ns2 = null;", " use?.(ns?.foo);", "}")); } @Test public void testLocalAliasWithLet4() { test( lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let baz = ns.foo;", " use(baz);", "}"), lines( "var ns$foo = 'bar';", // "if (true) {", " let baz = null;", " use(ns$foo);", "}")); } @Test public void testLocalAliasWithLet5() { // For local variables (VAR, CONST, or LET) we only handle cases where the alias is a variable, // not a property. testSame( lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let ns2 = {};", " ns2.baz = ns;", " use(ns2.baz.foo);", "}")); } @Test public void testGlobalAliasWithConst() { test( "const ns = {}; ns.foo = 'bar'; const ns2 = ns; use(ns2.foo);", // "var ns$foo = 'bar'; const ns2 = null; use(ns$foo);"); test( "const ns = {}; ns.foo = 'bar'; const ns2 = ns; use?.(ns2?.foo);", // "const ns = {}; ns.foo = 'bar'; const ns2 = null; use?.( ns?.foo);"); } @Test public void testLocalAliasWithConst1() { test( lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " const ns2 = ns;", " use(ns2.foo);", "}"), lines( "var ns$foo = 'bar';", // "function f() {", " const ns2 = null;", " use(ns$foo);", "}")); test( lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " const ns2 = ns;", " use?.(ns2?.foo);", "}"), lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " const ns2 = null;", " use?.(ns?.foo);", "}")); } @Test public void testLocalAliasWithConst2() { test( lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " const ns2 = ns;", " use(ns2.foo);", " }", "}"), lines( "var ns$foo = 'bar';", // "function f() {", " if (true) {", " const ns2 = null;", " use(ns$foo);", " }", "}")); test( lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " const ns2 = ns;", " use?.(ns2?.foo);", " }", "}"), lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " const ns2 = null;", " use?.(ns?.foo);", " }", "}")); } @Test public void testLocalAliasWithConst3() { test( lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const ns2 = ns;", " use(ns2.foo);", "}"), lines( "var ns$foo = 'bar';", // "if (true) {", " const ns2 = null;", " use(ns$foo);", "}")); test( lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const ns2 = ns;", " use?.(ns2?.foo);", "}"), lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const ns2 = null;", " use?.(ns?.foo);", "}")); } @Test public void testLocalAliasWithConst4() { test( lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const baz = ns.foo;", " use(baz);", "}"), lines( "var ns$foo = 'bar';", // "if (true) {", " const baz = null;", " use(ns$foo);", "}")); } @Test public void testLocalAliasWithConst5() { // For local variables (VAR, CONST, or LET) we only handle cases where the alias is a variable, // not a property. testSame( lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const ns2 = {};", " ns2.baz = ns;", " use(ns2.baz.foo);", "}")); } @Test public void testLocalAliasInsideClass() { test( "var a = {b: 5}; class A { fn() { var c = a; use(a.b); } }", // "var a$b = 5; class A { fn() { var c = null; use(a$b); } }"); test( "var a = {b: 5}; class A { fn() { var c = a; use?.(a?.b); } }", // "var a = {b: 5}; class A { fn() { var c = null; use?.(a?.b); } }"); } @Test public void testEs6ClassStaticProperties() { // Collapsing static properties (A.foo and A.useFoo in this case) is known to be unsafe. test( srcs( lines( "class A {", // " static useFoo() {", " alert(this.foo);", " }", "}", "A.foo = 'bar';", "const B = A;", "B.foo = 'baz';", "B.useFoo();")), expected( lines( "var A$useFoo = function() { alert(this.foo); };", // "class A {}", "var A$foo = 'bar';", "const B = null;", "A$foo = 'baz';", "A$useFoo();")), warning(RECEIVER_AFFECTED_BY_COLLAPSE)); // Adding @nocollapse makes this safe. test( lines( "class A {", // " /** @nocollapse */", " static useFoo() {", " alert(this.foo);", " }", "}", "/** @nocollapse */", "A.foo = 'bar';", "const B = A;", "B.foo = 'baz';", "B.useFoo();"), lines( "class A {", // " /** @nocollapse */", " static useFoo() {", " alert(this.foo);", " }", "}", "/** @nocollapse */", "A.foo = 'bar';", "const B = null;", "A.foo = 'baz';", "A.useFoo();")); } @Test public void testClassStaticInheritance_method() { test( "class A { static s() {} } class B extends A {} const C = B; C.s();", // "var A$s = function() {}; class A {} class B extends A {} const C = null; A$s();"); test( "class A { static s() {} } class B extends A {} B.s();", // "var A$s = function() {}; class A {} class B extends A {} A$s();"); test( "class A {} A.s = function() {}; class B extends A {} B.s();", // "class A {} var A$s = function() {}; class B extends A {} A$s();"); } @Test public void testClassStaticInheritance_propertyAlias() { test( "class A {} A.staticProp = 6; class B extends A {} let b = new B;", // "class A {} var A$staticProp = 6; class B extends A {} let b = new B;"); test( "class A {} A.staticProp = 6; class B extends A {} use(B.staticProp);", // "class A {} var A$staticProp = 6; class B extends A {} use(A$staticProp);"); test( "class A {} A.staticProp = 6; class B extends A {} use(B?.staticProp);", // TODO(b/148237949): collapse breaks `B?.staticProp` reference "class A {} var A$staticProp = 6; class B extends A {} use(B?.staticProp);"); } @Test public void testClassStaticInheritance_propertyWithSubproperty() { test( "class A {} A.ns = {foo: 'bar'}; class B extends A {} use(B.ns.foo);", // "class A {} var A$ns$foo = 'bar'; class B extends A {} use(A$ns$foo);"); test( "class A {} A.ns = {foo: 'bar'}; class B extends A {} use(B.ns?.foo);", // "class A {} var A$ns = {foo: 'bar'}; class B extends A {} use(A$ns?.foo);"); test( "class A {} A.ns = {}; class B extends A {} B.ns.foo = 'baz'; use(B.ns.foo);", "class A {} class B extends A {} var A$ns$foo = 'baz'; use(A$ns$foo);"); test( "class A {} A.ns = {}; class B extends A {} B.ns.foo = 'baz'; use(B.ns?.foo);", "class A {} var A$ns = {}; class B extends A {} A$ns.foo = 'baz'; use(A$ns?.foo);"); } @Test public void testClassStaticInheritance_propertyWithShadowing() { test( "class A {} A.staticProp = 6; class B extends A {} B.staticProp = 7;", // "class A {} var A$staticProp = 6; class B extends A {} var B$staticProp = 7;"); // At the time use() is called, B.staticProp is still the same as A.staticProp, but we back off // rewriting it because of the shadowing afterwards. This makes CollapseProperties unsafely // collapse in this case - the same issue occurs when transpiling down to ES5. test( "class A {} A.foo = 6; class B extends A {} use(B.foo); B.foo = 7;", // "class A {} var A$foo = 6; class B extends A {} use(B$foo); var B$foo = 7;"); test( "class A {} A.foo = 6; class B extends A {} use(B?.foo); B.foo = 7;", // TODO(b/148237949): collapse properties breaks `B?.foo` reference "class A {} var A$foo = 6; class B extends A {} use(B?.foo); var B$foo = 7;"); } @Test public void testClassStaticInheritance_cantDetermineSuperclass() { // Here A.foo and B.foo are unsafely collapsed because getSuperclass() creates an alias for them test( lines( "class A {}", // "A.foo = 5;", "class B {}", "B.foo = 6;", "function getSuperclass() { return 1 < 2 ? A : B; }", "class C extends getSuperclass() {}", "use(C.foo);"), lines( "class A {}", // "var A$foo = 5;", "class B {}", "var B$foo = 6;", "function getSuperclass() { return 1 < 2 ? A : B; }", "class C extends getSuperclass() {}", "use(C.foo);")); } @Test public void testAliasForSuperclassNamespace() { test( lines( "var ns = {};", // "class Foo {}", "ns.clazz = Foo;", "var Bar = class extends ns.clazz.Baz {}"), lines( "class Foo {}", // "var ns$clazz = null;", "var Bar = class extends Foo.Baz {}")); test( lines( "var ns = {};", // "class Foo {}", "Foo.Builder = class {}", "ns.clazz = Foo;", "var Bar = class extends ns.clazz.Builder {}"), lines( "class Foo {}", // "var Foo$Builder = class {}", "var ns$clazz = null;", "var Bar = class extends Foo$Builder {}")); } @Test public void testAliasForSuperclassNamespace_withStaticInheritance() { test( lines( "var ns = {};", // "class Foo {}", "Foo.Builder = class {}", "Foo.Builder.baz = 3;", "ns.clazz = Foo;", "var Bar = class extends ns.clazz.Builder {}", "use(Bar.baz);"), lines( "class Foo {}", // "var Foo$Builder = class {}", "var Foo$Builder$baz = 3;", "var ns$clazz = null;", "var Bar = class extends Foo$Builder {}", "use(Foo$Builder$baz);")); test( lines( "var ns = {};", // "class Foo {}", "Foo.Builder = class {}", "Foo.Builder.baz = 3;", "ns.clazz = Foo;", "var Bar = class extends ns.clazz?.Builder {}", "use(Bar?.baz);"), lines( "class Foo {}", // "var Foo$Builder = class {}", "var Foo$Builder$baz = 3;", "var ns$clazz = null;", // TODO(b/148237979): Collapse above breaks this reference. "var Bar = class extends Foo?.Builder {}", // TODO(b/148237979): Collapse above breaks this reference. "use(Bar?.baz);")); } @Test public void testDestructuringAlias1() { testSame("var a = { x: 5 }; var [b] = [a]; use(b.x);"); } @Test public void testDestructuringAlias2() { testSame("var a = { x: 5 }; var {b} = {b: a}; use(b.x);"); } @Test public void testDestructingAliasWithConstructor() { test( lines( "var ns = {};", // "/** @constructor */", "ns.ctor = function() {}", "const {ctor} = ns;", "let c = new ctor;"), lines( "/** @constructor */", // "var ns$ctor = function() {}", "const ctor = null;", "let c = new ns$ctor;")); } @Test public void namespaceInDestructuringPattern() { testSame( lines( "const ns = {};", // "ns.x = 1;", "ns.y = 2;", "let {x, y} = ns;", "x = 4;", // enforce that we can't inline x -> ns.x because it's set multiple times "use(x + y);")); } @Test public void inlineDestructuringPatternConstructorWithProperty() { test( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y.prop);"), lines( "/** @constructor */", // "var ns$Y = function() {};", "var ns$Y$prop = 3;", "const Y = null;", "use(ns$Y$prop);")); test( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y?.prop);"), lines( "/** @constructor */", // "var ns$Y = function() {};", // TODO(bradfordcsmith): This collapse breaks the optional chain // reference below. "var ns$Y$prop = 3;", "const Y = null;", "use(ns$Y?.prop);")); // Only `const` destructuring aliases have special handling by AggressiveInlineAliases testSame( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "let {Y} = ns;", "use(Y.prop);"), PARTIAL_NAMESPACE_WARNING); } @Test public void testDefaultParamAlias1() { test( "var a = {b: 5}; var b = a; function f(x=b) { alert(x.b); }", // "var a = {b: 5}; var b = null; function f(x=a) { alert(x.b); }"); } @Test public void testDefaultParamAlias2() { test( "var a = {b: {c: 5}}; var b = a; function f(x=b.b) { alert(x.c); }", // "var a$b = {c: 5}; var b = null; function f(x=a$b) { alert(x.c); }"); test( "var a = {b: {c: 5}}; var b = a; function f(x=b?.b) { alert(x?.c); }", // "var a = {b: {c: 5}}; var b = null; function f(x=a?.b) { alert(x?.c); }"); } @Test public void testAliasPropertyOnUnsafelyRedefinedNamespace() { testSame("var obj = {foo: 3}; var foo = obj.foo; obj = {}; alert(foo);"); } @Test public void testAliasPropertyOnSafelyRedefinedNamespace() { // non-constructor property doesn't get collapsed test( "var obj = {foo: 3}; var foo = obj.foo; obj = obj || {}; alert(foo);", // "var obj = {foo: 3}; var foo = null ; obj = obj || {}; alert(obj.foo);"); // constructor property does get collapsed test( lines( "var ns = {};", // "/** @constructor */ ns.ctor = function() {};", "ns.ctor.foo = 3;", "var foo = ns.ctor.foo;", "ns = ns || {};", "alert(foo);"), lines( "var ns = {};", // "/** @constructor */ var ns$ctor = function() {};", "var ns$ctor$foo = 3;", "var foo = null;", "ns = ns || {};", "alert(ns$ctor$foo);")); // NOTE(lharker): this mirrors current code in Closure library test( lines( "var goog = {};", // "goog.module = function() {};", "/** @constructor */ goog.module.ModuleManager = function() {};", "goog.module.ModuleManager.getInstance = function() {};", "goog.module = goog.module || {};", "var ModuleManager = goog.module.ModuleManager;", "alert(ModuleManager.getInstance());"), lines( "var goog$module = function() {};", // "/** @constructor */ var goog$module$ModuleManager = function() {};", "var goog$module$ModuleManager$getInstance = function() {};", "goog$module = goog$module || {};", "var ModuleManager = null;", "alert(goog$module$ModuleManager$getInstance());")); } @Test public void testClassInObjectLiteral() { test( "var obj = {foo: class {}};", // "var obj$foo = class {};"); // TODO(lharker): this is unsafe, obj$foo.foo is undefined now that A$foo is collapsed test( "class A {} A.foo = 3; var obj = {foo: class extends A {}}; use(obj.foo.foo);", // "class A {} var A$foo = 3; var obj$foo = class extends A{}; use(obj$foo.foo)"); } @Test public void testToStringValueOfInObjectLiteral() { test( lines( "let z = {", " toString() { return 'toString';},", " valueOf() { return 'valueOf';},", "};", "var zAsString = z + \"\";"), lines( "var z$toString = function() {", " return \"toString\";", "};", "var z$valueOf = function() {", " return \"valueOf\";", "};", // TODO(b/223896059): CollapseProperties breaks references to toString/valueOf "let z = {}", "var zAsString = z + \"\";")); } @Test public void testLoopInAliasChainOfTypedefConstructorProperty() { test( lines( "/** @constructor */ var Item = function() {};", // "/** @typedef {number} */ Item.Models;", "Item.Models = Item.Models;"), lines( "/** @constructor */ var Item = function() {};", // "Item$Models;", "var Item$Models = Item$Models;")); test( lines( "/** @constructor */ var Item = function() {};", // "/** @typedef {number} */ Item.Models;", "Item.Models = Item?.Models;"), lines( "/** @constructor */ var Item = function() {};", // "Item$Models;", // TODO(b/148237949): Collapsing breaks this reference. "var Item$Models = Item?.Models;")); } @Test public void testDontInlinePropertiesOnEscapedNamespace() { testSame( externs("function use(obj) {}"), srcs( lines( "function Foo() {}", // "Foo.Bar = {};", "Foo.Bar.baz = {A: 1, B: 2};", "", "var $jscomp$destructuring$var1 = Foo.Bar;", // This call could potentially have changed the value of Foo.Bar, so don't // collapse Foo.Bar.baz.A/Foo.Bar.baz.B "use(Foo);", "var baz = $jscomp$destructuring$var1.baz;", "use(baz.A);"))); } @Test public void testInliningPropertiesOnEscapedNamespace_withDeclaredType() { test( externs("function use(obj) {}"), srcs( lines( "/** @constructor */", // "function Foo() {}", "/** @constructor */", "Foo.Bar = function() {};", "/** @enum {number} */", "Foo.Bar.baz = {A: 1, B: 2};", "", "var $jscomp$destructuring$var1 = Foo.Bar;", "use(Foo);", "var baz = $jscomp$destructuring$var1.baz;", "use(baz.A);")), expected( lines( "/** @constructor */", // "function Foo() {}", "/** @constructor */", "var Foo$Bar = function() {};", "var Foo$Bar$baz$A = 1;", "var Foo$Bar$baz$B = 2;", "", "var $jscomp$destructuring$var1 = null;", // This call could potentially read Foo.Bar, which will now be broken. // AggressiveInlineAliases/CollapseProperties intentionally generate unsafe code // in this case. The main motivation is to collapse long namespaces generated by // goog.provide or goog.module.declareLegacyNamespace() // https://developers.google.com/closure/compiler/docs/limitations#implications-of-object-property-flattening "use(Foo);", "var baz = null;", "use(Foo$Bar$baz$A);"))); } @Test public void testDontInlinePropertiesOnNamespace_withNoCollapse() { testSame( externs("function use(obj) {}"), srcs( lines( "/** @constructor */", // "function Foo() {}", "/** @constructor @nocollapse */", "Foo.Bar = function() {};", "/** @enum {number} @nocollapse */", "Foo.Bar.baz = {A: 1, B: 2};", "", "var $jscomp$destructuring$var1 = Foo.Bar;", // This call could potentially have changed the value of Foo.Bar, and without // @nocollapse on Foo.Bar and Foo.Bar.baz the compiler would generate unsafe code. "use(Foo);", "var baz = $jscomp$destructuring$var1.baz;", "use(baz.A);"))); } @Test public void testInlinePropertyOnAliasedConstructor() { // TODO(b/117905881): as long as we unsafely collapse Foo.prop -> Foo$prop, there's no way to // safely rewrite the "use(ns.alias.prop)" call in the compiler // Either // a) we replace "ns.alias.prop" with "Foo$prop" or // b) we leave "ns.alias.prop" as is. // Option a) can break code if the "use(ns)" call actually reassigns ns.alias (which is not // declared const). // Option b) breaks code if "use(ns)" does NOT reassign ns.alias, since now // ns.alias.prop is Foo.prop, which is undefined. // but we might want to consider movign to (b) instead of (a), since CollapseProperties will // also break case (a) test( externs("function use(ctor) {}"), srcs( lines( "/** @constructor */", // "function Foo() {}", "Foo.prop = 2;", "var ns = {};", "ns.alias = Foo;", "use(ns);", "use(ns.alias.prop);")), expected( lines( "/** @constructor */", // "function Foo() {}", "var Foo$prop = 2;", "var ns = {};", "ns.alias = Foo;", "use(ns);", "use(ns.alias.prop);"))); } @Test public void testClassStaticMemberAccessedWithSuper() { test( lines( "class Bar {", // " static double(n) {", " return n*2", " }", "}", "class Baz extends Bar {", " static quadruple(n) {", " return 2 * super.double(n);", " }", "}"), lines( "var Bar$double = function(n) { return n * 2; }", // "class Bar {}", "var Baz$quadruple = function(n) { return 2 * Bar$double(n); }", "class Baz extends Bar {}")); } @Test public void testCommaCallAliasing1() { test( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", "(0,xid)('abc');"), lines( "var xid = function(a) {};", // // The indirect call below does not prevent this property collapse "var xid$internal_ = function() {};", "(0,xid)('abc');")); } @Test public void testCommaCallAliasing2() { test( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", "fn((0,xid)('abc'));"), lines( "var xid = function(a) {};", // // The indirect call below does not prevent this property collapse "var xid$internal_ = function() {};", "fn((0,xid)('abc'));")); } @Test public void testCommaCallAliasing3() { test( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", "throw ((0, xid), 0);"), lines( "var xid = function(a) {};", // // The indirect call below does not prevent this property collapse "var xid$internal_ = function() {};", "throw ((0, xid), 0);")); } @Test public void testHookNewAliasing1() { testSame( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", // The indirect call prevents this property collapse "var xx = new Thing(x ? xid : abc).method();")); } @Test public void testHookGetProp1() { testSame( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", // The indirect call prevents this property collapse "var xx = (x ? xid : abc).method();")); } @Test public void testHookGetProp2() { test( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", "var xx = ((x ? xid : abc) - def).toExponential(5);"), lines( "var xid = function(a) {};", // // The indirect call below does not prevent this property collapse "var xid$internal_ = function() {};", "var xx = ((x ? xid : abc) - def).toExponential(5);")); } }
test/com/google/javascript/jscomp/InlineAndCollapsePropertiesTest.java
/* * Copyright 2006 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.javascript.jscomp.InlineAndCollapseProperties.PARTIAL_NAMESPACE_WARNING; import static com.google.javascript.jscomp.InlineAndCollapseProperties.RECEIVER_AFFECTED_BY_COLLAPSE; import com.google.javascript.jscomp.CompilerOptions.ChunkOutputType; import com.google.javascript.jscomp.CompilerOptions.PropertyCollapseLevel; import com.google.javascript.jscomp.deps.ModuleLoader.ResolutionMode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@link InlineAndCollapseProperties}. */ @RunWith(JUnit4.class) public final class InlineAndCollapsePropertiesTest extends CompilerTestCase { private static final String EXTERNS = lines( "var window;", // "function alert(s) {}", "function parseInt(s) {}", "/** @constructor */ function String() {};", "var arguments"); public InlineAndCollapsePropertiesTest() { super(EXTERNS); } @Override protected CompilerPass getProcessor(final Compiler compiler) { return InlineAndCollapseProperties.builder(compiler) .setPropertyCollapseLevel(PropertyCollapseLevel.ALL) .setChunkOutputType(ChunkOutputType.GLOBAL_NAMESPACE) .setHaveModulesBeenRewritten(false) .setModuleResolutionMode(ResolutionMode.BROWSER) .build(); } @Override @Before public void setUp() throws Exception { super.setUp(); enableNormalize(); disableCompareJsDoc(); } @Test public void testConstObjRefInTemplateLiteralComputedPropKey() { test( srcs( lines( "var module$name = {}", // "module$name.cssClasses = {", " CLASS_A: 'class-a',", "};", "", "module$name.oldCssClassesMap = {", " [`${module$name.cssClasses.CLASS_A}`]: 'old-class-a',", "};", "")), // TODO(bradfordcsmith): Shouldn't we be leaving the computed property in place? expected("var module$name$cssClasses$CLASS_A = 'class-a';")); } @Test public void testObjLitSpread() { test( lines( "const other = {bar: 'some' };", "let ns = {}", "ns.foo = { ...other };", "use(ns.foo.bar);"), lines("const other = {bar: 'some' };", "var ns$foo = { ...other };", "use(ns$foo.bar);")); } // same behavior with transpiled version of above test @Test public void testObjAssign() { test( lines( "const other = {bar: 'some' };", "let ns = {}", "ns.foo = Object.assign({}, other);", "use(ns.foo.bar);"), lines( "const other = {bar: 'some' };", "var ns$foo = Object.assign({}, other);", "use(ns$foo.bar);")); } @Test public void testObjLitSpread_twoSpreads() { test( lines( "const other = {bar: 'bar' };", "const another = {baz: 'baz' };", "let ns = {};", "ns.foo = { ...other, ...another };", "use(ns.foo.bar, ns.foo.baz);"), lines( "const other = {bar: 'bar' };", "const another = {baz : 'baz'};", "var ns$foo = { ...other, ...another };", "use(ns$foo.bar, ns$foo.baz);")); } // same behavior with transpiled version of above test @Test public void testObjAssign_twoSpreads() { test( lines( "const other = {bar: 'bar'};", "const another = {baz: 'baz'};", "let ns = {};", "ns.foo = Object.assign({}, other, another);", "use(ns.foo.bar, ns.foo.baz);"), lines( "const other = {bar: 'bar'};", "const another = {baz : 'baz'};", "var ns$foo = Object.assign({}, other, another);", "use(ns$foo.bar, ns$foo.baz);")); } @Test public void testObjLitSpread_withNormalPropAfter() { test( lines( "const other = {bar: 'some' };", "let ns = {}", "ns.foo = { ...other, prop : 0};", "use(ns.foo.bar, ns.foo.prop);"), lines( "const other = {bar: 'some' };", // "var ns$foo$prop = 0;", "var ns$foo = { ...other};", "use(ns$foo.bar, ns$foo$prop);")); } @Test public void testObjAssign_withNormalPropAfter() { test( lines( "const other = {bar: 'some' };", "let ns = {}", "ns.foo = Object.assign({}, other, {prop : 0});", "use(ns.foo.bar, ns.foo.prop);"), lines( "const other = {bar: 'some' };", // "var ns$foo = Object.assign({}, other, {prop:0});", "use(ns$foo.bar, ns$foo.prop);")); // both properties not collapsed. } @Test public void testObjLitSpread_chained() { test( lines( "const other = {bar: 'some' };", "let ns = {...other}", "let ns2 = { ...ns };", "use(ns2.bar);"), lines( "const other = {bar: 'some' };", "let ns = { ...other };", "let ns2 = { ...ns };", "use(ns2.bar);")); } // same behavior with transpiled version of above test @Test public void testObjAssign_chained() { test( lines( "const other = {bar: 'some' };", "let ns = Object.assign({}, other);", "let ns2 = Object.assign({}, ns);", "use(ns2.bar);"), lines( "const other = {bar: 'some' };", "let ns = Object.assign({}, other);", "let ns2 = Object.assign({}, ns);", "use(ns2.bar);")); } @Test public void testObjLitSpread_chainedWithGetProp() { test( lines( "const other = {bar: 'some' };", "let ns = {...other};", "let ns2 = {};", "ns2.foo = { ...ns };", "use(ns2.foo.bar);"), lines( "const other = {bar: 'some' };", "let ns = { ...other };", "var ns2$foo = { ...ns };", "use(ns2$foo.bar);")); } // same behavior with transpiled version of above test @Test public void testObjAssign_chainedWithGetProp() { test( lines( "const other = {bar: 'some' };", "let ns = Object.assign({}, other);", "let ns2 = {};", "ns2.foo = Object.assign({}, ns);", "use(ns2.foo.bar);"), lines( "const other = {bar: 'some' };", "let ns = Object.assign({}, other);", "var ns2$foo = Object.assign({}, ns);", "use(ns2$foo.bar);")); } @Test public void testGitHubIssue3733() { testSame( srcs( lines( "const X = {Y: 1};", "", "function fn(a) {", " if (a) {", // Before issue #3733 was fixed GlobalNamespace failed to see this reference // as creating an alias for X due to a switch statement that failed to check // for the RETURN node type, so X.Y was incorrectly collapsed. " return a ? X : {};", " }", "}", "", "console.log(fn(true).Y);"))); } @Test public void testCollapse() { test( "var a = {}; a.b = {}; var c = a.b;", // "var c = null"); test( "var a = {}; a.b = {}; var c = a.b; use(c);", // "var a$b = {}; var c = null; use(a$b);"); testSame("var a = {}; /** @nocollapse */ a.b;"); } @Test public void testOptChainPreventsInlineAndCollapse() { testSame( lines( "var a = {};", "a.b = {};", // c is not really an alias due to optional chain, // and optional chain prevents collapse of a.b. "var c = a?.b;", "use(c);")); test( lines( "var a = {};", // "a.b = {};", "var b = a.b;", // can be inlined and collapsed "b.c = {};", "var c = b?.c;", // opt chain prevents both "use(c);"), lines( "var a$b = {};", // "var b = null;", "a$b.c = {};", "var c = a$b?.c;", "use(c);")); test( lines( "const a = {};", // "a.b = {};", "a.b.c = {};", "const {b} = a;", // can be inlined and collapsed "const c = b?.c;", // opt chain prevents both "use(c);"), lines( "var a$b = {};", // "a$b.c = {};", "const b = null;", "const c = a$b?.c;", "use(c);")); test( lines( "const ns = {};", // "ns.Y = {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y);"), lines( "var ns$Y = {};", // "ns$Y.prop = 3;", "const Y = null;", "use(ns$Y);")); test( lines( "var a = {};", // "a.b = {};", "a.b.c = {};", "var c = a.b?.c;", "use(c);"), lines( "var a$b = {};", // "a$b.c = {};", "var c = a$b?.c;", "use(c);")); test( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y);"), lines( "/** @constructor */", // "var ns$Y = function() {};", "var ns$Y$prop = 3;", "const Y = null;", "use(ns$Y);")); test( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y?.prop);"), lines( "/** @constructor */", // "var ns$Y = function() {};", "var ns$Y$prop = 3;", "const Y = null;", "use(ns$Y?.prop);")); } @Test public void testObjLitDeclaration() { test( "var a = {b: {}, c: {}}; var d = a.b; var e = a.c", // "var d = null; var e = null;"); test( "var a = {b: {}, c: {}}; var d = a.b; var e = a.c; use(d, e);", // "var a$b = {}; var a$c = {}; var d = null; var e = null; use(a$b, a$c);"); test( "var a = {b: {}, /** @nocollapse */ c: {}}; var d = a.b; var e = a.c", // "var a = {/** @nocollapse */ c: {}}; var d = null; var e = null;"); test( "var a = {b: {}, /** @nocollapse */ c: {}}; var d = a.b; var e = a.c; use(d, e);", // "var a$b = {};var a = {/** @nocollapse */ c: {}};var d = null;var e = null;use(a$b, a.c);"); } @Test public void testObjLitDeclarationWithGet1() { testSame("var a = {get b(){}};"); } @Test public void testObjLitDeclarationWithGet2() { test( "var a = {b: {}, get c(){}}; var d = a.b; var e = a.c;", // "var a = {get c() {}}; var d=null; var e = a.c"); test( "var a = {b: {}, get c(){}}; var d = a.b; var e = a.c; use(d);", // "var a$b = {};var a = {get c(){}};var d = null; var e = a.c; use(a$b)"); } @Test public void testObjLitDeclarationWithGet3() { test( "var a = {b: {get c() { return 3; }}};", // "var a$b = {get c() { return 3; }};"); } @Test public void testObjLitDeclarationWithSet1() { testSame("var a = {set b(a){}};"); } @Test public void testObjLitDeclarationWithSet2() { test( "var a = {b: {}, set c(a){}}; var d = a.b; var e = a.c", // "var a = {set c(a$jscomp$1){}}; var d=null; var e = a.c"); test( "var a = {b: {}, set c(a){}}; var d = a.b; var e = a.c; use(d);", // "var a$b = {}; var a = {set c(a$jscomp$1){}}; var d=null; var e = a.c; use(a$b);"); } @Test public void testObjLitDeclarationWithSet3() { test( "var a = {b: {set c(d) {}}};", // "var a$b = {set c(d) {}};"); } @Test public void testObjLitDeclarationWithGetAndSet1() { test( "var a = {b: {get c() { return 3; },set c(d) {}}};", // "var a$b = {get c() { return 3; },set c(d) {}};"); } @Test public void testObjLitAssignmentDepth3() { test( "var a = {}; a.b = {}; a.b.c = {d: 1, e: 2}; var f = a.b.c.d", // "var a$b$c$d = 1; var a$b$c$e = 2; var f = null"); test( "var a = {}; a.b = {}; a.b.c = {d: 1, e: 2}; var f = a.b.c.d; use(f);", // "var a$b$c$d = 1; var a$b$c$e = 2; var f = null; use(a$b$c$d);"); test( lines( "var a = {}; a.b = {}; a.b.c = {d: 1, /** @nocollapse */ e: 2}; ", // "var f = a.b.c.d; var g = a.b.c.e"), "var a$b$c$d = 1; var a$b$c = {/** @nocollapse */ e: 2}; var f = null; var g = null;"); test( lines( "var a = {}; a.b = {}; a.b.c = {d: 1, /** @nocollapse */ e: 2}; ", // "var f = a.b.c.d; var g = a.b.c.e; use(f, g);"), lines( "var a$b$c$d = 1; var a$b$c = { /** @nocollapse */ e: 2};", // "var f = null; var g = null; use(a$b$c$d, a$b$c.e);")); testSame( lines( "var a = {}; /** @nocollapse*/ a.b = {}; ", // "a.b.c = {d: 1, e: 2}; ", "var f = null; var g = null;")); } @Test public void testObjLitAssignmentDepth4() { test( "var a = {}; a.b = {}; a.b.c = {}; a.b.c.d = {e: 1, f: 2}; var g = a.b.c.d.e;", // "var a$b$c$d$e = 1; var a$b$c$d$f = 2; var g = null;"); test( "var a = {}; a.b = {}; a.b.c = {}; a.b.c.d = {e: 1, f: 2}; var g = a.b.c.d.e; use(g);", // "var a$b$c$d$e = 1; var a$b$c$d$f = 2; var g = null; use(a$b$c$d$e);"); } @Test public void testHasOwnProperty() { test( "var a = {'b': 1, 'c': 1}; var alias = a; alert(alias.hasOwnProperty('c'));", // "var a = {'b': 1, 'c': 1}; var alias = null; alert(a.hasOwnProperty('c'));"); } @Test public void testAliasCreatedForObjectDepth1_1() { // An object's properties are not collapsed if the object is referenced // in a such a way that an alias is created for it, if that alias is used. test( "var a = {b: 0}; var c = a; c.b = 1; a.b == c.b;", // "var a$b = 0; var c = null; a$b = 1; a$b == a$b;"); test( "var a = {b: 0}; var c = a; c.b = 1; a?.b == c?.b;", "var a = {b: 0}; var c = null; a.b = 1; a?.b == a?.b;"); test( "var a = {b: 0}; var c = a; c.b = 1; a.b == c.b; use(c);", // "var a={b:0}; var c=null; a.b=1; a.b == a.b; use(a);"); } @Test public void testAliasCreatedForObjectDepth1_2() { testSame("var a = {b: 0}; f(a); a.b;"); } @Test public void testAliasCreatedForObjectDepth1_3() { testSame("var a = {b: 0}; new f(a); a.b;"); } @Test public void testMisusedConstructorTag() { test( lines( "var a = {}; var d = a; a.b = function() {};", // "/** @constructor */ a.b.c = 0; a.b.c;"), "var d=null; var a$b=function(){}; /** @constructor */ var a$b$c=0; a$b$c;"); } @Test public void testAliasCreatedForCtorDepth1_1() { // A constructor's properties *are* collapsed even if the function is // referenced in a such a way that an alias is created for it, // since a function with custom properties is considered a class and its // non-prototype properties are considered static methods and variables. // People don't typically iterate through static members of a class or // refer to them using an alias for the class name. test( lines( "/** @constructor */ var a = function(){}; a.b = 1; ", // "var c = a; c.b = 2; a.b == c.b;"), lines( "/** @constructor */ var a = function(){}; var a$b = 1;", // "var c = null; a$b = 2; a$b == a$b;")); test( lines( "/** @constructor */ var a = function(){}; a.b = 1; ", // "var c = a; c.b = 2; a?.b == c?.b;"), lines( "/** @constructor */ var a = function(){}; var a$b = 1;", // "var c = null; a$b = 2; a?.b == a?.b;")); // Sometimes we want to prevent static members of a constructor from // being collapsed. test( lines( "/** @constructor */ var a = function(){};", // "/** @nocollapse */ a.b = 1; var c = a; c.b = 2; a.b == c.b;"), lines( "/** @constructor */ var a = function(){};", // "/** @nocollapse */ a.b = 1; var c = null; a.b = 2; a.b == a.b;")); test( lines( "/** @constructor */ var a = function(){};", // "/** @nocollapse */ a.b = 1; var c = a; c.b = 2; a?.b == c?.b;"), lines( "/** @constructor */ var a = function(){};", // "/** @nocollapse */ a.b = 1; var c = null; a.b = 2; a?.b == a?.b;")); } @Test public void testAliasCreatedForFunctionDepth2() { test( "var a = {}; a.b = function() {}; a.b.c = 1; var d = a.b; a.b.c != d.c;", // "var a$b = function() {}; var a$b$c = 1; var d = null; a$b$c != a$b$c;"); testSame("var a = {}; a.b = function() {}; a.b.c = 1; var d = a?.b; a.b?.c != d?.c;"); test( lines( "var a = {}; a.b = function() {}; /** @nocollapse */ a.b.c = 1;", // "var d = a.b; a.b.c == d.c;"), "var a$b = function() {}; /** @nocollapse */ a$b.c = 1; var d = null; a$b.c == a$b.c;"); } @Test public void testAliasCreatedForCtorDepth2() { test( lines( "var a = {}; /** @constructor */ a.b = function() {}; a.b.c = 1; var d = a.b;", // "a.b.c == d.c;"), lines( "/** @constructor */ var a$b = function() {}; var a$b$c = 1; var d = null;", // "a$b$c == a$b$c;")); testSame( srcs( lines( "var a = {}; /** @constructor */ a.b = function() {}; a.b.c = 1; var d = a?.b;", // "a.b?.c == d?.c;")), warning(PARTIAL_NAMESPACE_WARNING)); test( lines( "var a = {}; /** @constructor */ a.b = function() {}; ", // "/** @nocollapse */ a.b.c = 1; var d = a.b;", "a.b.c == d.c;"), lines( "/** @constructor */ var a$b = function() {};", "/** @nocollapse */ a$b.c = 1; var d = null;", "a$b.c == a$b.c;")); } @Test public void testAliasCreatedForClassDepth1_1() { test( lines( "var a = {}; /** @constructor */ a.b = function(){};", // "var c = a; c.b = 0; a.b == c.b;"), lines( "/** @constructor */ var a$b = function(){};", // "var c = null; a$b = 0; a$b == a$b;")); test( srcs( lines( "var a = {}; /** @constructor */ a.b = function(){};", // // `a?.b` and `c?.b` are aliasing gets "var c = a; c.b = 0; a?.b == c?.b;")), expected( lines( "var a = {}; /** @constructor */ a.b = function(){};", // // `a?.b` and `c?.b` are aliasing gets "var c = null; a.b = 0; a?.b == a?.b;")), warning(PARTIAL_NAMESPACE_WARNING)); testSame( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = 1; c = a; c.b = 0; a.b == c.b;"), PARTIAL_NAMESPACE_WARNING); testSame( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = 1; c = a; c.b = 0; a?.b == c?.b;"), PARTIAL_NAMESPACE_WARNING); test( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = a; c.b = 0; a.b == c.b;"), lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = null; a.b = 0; a.b == a.b;")); test( srcs( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = a; c.b = 0; a?.b == c?.b;")), expected( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = null; a.b = 0; a?.b == a?.b;")), warning(PARTIAL_NAMESPACE_WARNING)); test( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = a; c.b = 0; a.b == c.b; use(c);"), lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = null; a.b = 0; a.b == a.b; use(a);"), warning(PARTIAL_NAMESPACE_WARNING)); test( lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = a; c.b = 0; a?.b == c?.b; use(c);"), lines( "var a = {}; /** @constructor @nocollapse */ a.b = function(){};", // "var c = null; a.b = 0; a?.b == a?.b; use(a);"), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testObjLitDeclarationUsedInSameVarList() { // The collapsed properties must be defined in the same place in the var list // where they were originally defined (and not, for example, at the end). test( "var a = {b: {}, c: {}}; var d = a.b; var e = a.c; use(d, e);", // "var a$b = {}; var a$c = {}; var d = null; var e = null; use(a$b, a$c);"); test( "var a = {b: {}, /** @nocollapse */ c: {}}; var d = a.b; var e = a.c; use(d, e);", // "var a$b = {};var a = {/** @nocollapse */ c: {}};var d = null;var e = null;use(a$b, a.c);"); } @Test public void testAddPropertyToUncollapsibleObjectInLocalScopeDepth1() { test( "var a = {}; var c = a; use(c); (function() {a.b = 0;})(); a.b;", // "var a={}; var c=null; use(a); (function(){ a.b = 0; })(); a.b;"); test( "var a = {}; var c = 1; c = a; (function() {a.b = 0;})(); a.b;", // "var a = {}; var c=1; c = a; (function(){a.b = 0;})(); a.b;"); } @Test public void testAddPropertyToUncollapsibleNamedCtorInLocalScopeDepth1() { test( lines( "/** @constructor */ function a() {} var a$b; var c = a; ", // "(function() {a$b = 0;})(); a$b;"), lines( "/** @constructor */ function a() {} var a$b; var c = null; ", // "(function() {a$b = 0;})(); a$b;")); } @Test public void testAddPropertyToUncollapsibleCtorInLocalScopeDepth1() { test( lines( "/** @constructor */ var a = function() {}; var c = a; ", // "(function() {a.b = 0;})(); a.b;"), lines( "/** @constructor */ var a = function() {}; var a$b; ", // "var c = null; (function() {a$b = 0;})(); a$b;")); } @Test public void testAddPropertyToUncollapsibleObjectInLocalScopeDepth2() { test( lines( "var a = {}; a.b = {}; var d = a.b; use(d);", // "(function() {a.b.c = 0;})(); a.b.c;"), lines( "var a$b = {}; var d = null; use(a$b);", // "(function() {a$b.c = 0;})(); a$b.c;")); } @Test public void testAddPropertyToUncollapsibleCtorInLocalScopeDepth2() { test( lines( "var a = {}; /** @constructor */ a.b = function (){}; var d = a.b;", // "(function() {a.b.c = 0;})(); a.b.c;"), lines( "/** @constructor */ var a$b = function (){}; var a$b$c; var d = null;", // "(function() {a$b$c = 0;})(); a$b$c;")); } @Test public void testPropertyOfChildFuncOfUncollapsibleObjectDepth1() { test( "var a = {}; var c = a; a.b = function (){}; a.b.x = 0; a.b.x;", // "var c = null; var a$b=function() {}; var a$b$x = 0; a$b$x;"); test( "var a = {}; var c = a; a.b = function (){}; a.b.x = 0; a.b.x; use(c);", // "var a = {}; var c = null; a.b=function() {}; a.b.x = 0; a.b.x; use(a);"); } @Test public void testPropertyOfChildFuncOfUncollapsibleObjectDepth2() { test( "var a = {}; a.b = {}; var c = a.b; a.b.c = function (){}; a.b.c.x = 0; a.b.c.x;", // "var c=null; var a$b$c = function(){}; var a$b$c$x = 0; a$b$c$x"); test( "var a = {}; a.b = {}; var c = a.b; a.b.c = function (){}; a.b.c.x = 0; a.b.c.x;" + " use(c);", // "var a$b = {}; var c=null; a$b.c = function(){}; a$b.c.x=0; a$b.c.x; use(a$b);"); } @Test public void testAddPropertyToChildFuncOfUncollapsibleObjectInLocalScope() { test( lines( "var a = {}; a.b = function (){}; a.b.x = 0;", // "var c = a; (function() {a.b.y = 1;})(); a.b.x; a.b.y;"), lines( "var a$b=function() {}; var a$b$y; var a$b$x = 0; var c=null;", // "(function() { a$b$y=1; })(); a$b$x; a$b$y")); } @Test public void testAddPropertyToChildTypeOfUncollapsibleObjectInLocalScope() { test( lines( "var a = {};", // "/** @constructor */", "a.b = function (){};", "a.b.x = 0;", "var c = a;", "(function() {a.b.y = 1;})();", "a.b.x;", "a.b.y;"), lines( "/** @constructor */", // "var a$b = function (){};", "var a$b$y;", "var a$b$x = 0;", "var c = null;", "(function() {a$b$y = 1;})();", "a$b$x;", "a$b$y;")); test( lines( "var a = {};", // "/** @constructor */", "a.b = function (){};", "a.b.x = 0;", "var c = a;", "(function() {a.b.y = 1;})();", "a.b.x;", "a.b.y;", "use(c);"), lines( "var a = {};", // "/** @constructor */", "a.b = function (){};", "a.b.x = 0;", "var c = null;", "(function() {a.b.y = 1;})();", "a.b.x;", "a.b.y;", "use(a);"), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testAddPropertyToChildOfUncollapsibleFunctionInLocalScope() { test( "function a() {} a.b = {x: 0}; var c = a; (function() {a.b.y = 0;})(); a.b.y;", // "function a() {} var a$b$x=0; var a$b$y; var c=null; (function(){a$b$y=0})(); a$b$y"); } @Test public void testAddPropertyToChildOfUncollapsibleCtorInLocalScope() { test( lines( "/** @constructor */ var a = function() {}; a.b = {x: 0}; var c = a;", // "(function() {a.b.y = 0;})(); a.b.y;"), lines( "/** @constructor */ var a = function() {}; var a$b$x = 0; var a$b$y; var c = null;", // "(function() {a$b$y = 0;})(); a$b$y;")); } @Test public void testLocalAliasCreatedAfterVarDeclaration1() { test( lines( "var a = {b: 3};", // "function f() {", " var tmp;", " tmp = a;", " use(tmp.b);", "}"), lines( "var a$b = 3", // "function f() {", " var tmp;", " tmp = null;", " use(a$b);", "}")); test( lines( "var a = {b: 3};", // "function f() {", " var tmp;", " tmp = a;", " use?.(tmp?.b);", "}"), lines( "var a = {b: 3};", // "function f() {", " var tmp;", " tmp = null;", " use?.(a?.b);", "}")); } @Test public void testLocalAliasCreatedAfterVarDeclaration2() { test( lines( "var a = {b: 3}", // "function f() {", " var tmp;", " if (true) {", " tmp = a;", " use(tmp.b);", " }", "}"), lines( "var a$b = 3;", // "function f() {", " var tmp;", " if (true) {", " tmp = null;", " use(a$b);", " }", "}")); test( lines( "var a = {b: 3}", // "function f() {", " var tmp;", " if (true) {", " tmp = a;", " use?.(tmp?.b);", " }", "}"), lines( "var a = {b: 3}", // "function f() {", " var tmp;", " if (true) {", " tmp = null;", " use?.(a?.b);", " }", "}")); } @Test public void testLocalAliasCreatedAfterVarDeclaration3() { testSame( lines( "var a = { b : 3 };", // "function f() {", " var tmp;", " if (true) {", " tmp = a;", " }", " use(tmp);", "}")); } @Test public void testPartialLocalCtorAlias() { testWarning( lines( "/** @constructor */ var Main = function() {};", // "Main.doSomething = function(i) {}", "function f() {", " var tmp;", " if (g()) {", " use(tmp.doSomething);", " tmp = Main;", " tmp.doSomething(5);", " }", " use(tmp.doSomething);", // can't inline this use of tmp. "}"), InlineAndCollapseProperties.UNSAFE_CTOR_ALIASING); } @Test public void testFunctionAlias2() { test( "var a = {}; a.b = {}; a.b.c = function(){}; a.b.d = a.b.c;use(a.b.d)", // "var a$b$c = function(){}; var a$b$d = null;use(a$b$c);"); test( "var a = {}; a.b = {}; a.b.c = function(){}; a.b.d = a.b?.c; use?.(a.b?.d);", // "var a$b = {}; a$b.c = function(){}; a$b.d = a$b?.c; use?.(a$b?.d);"); } @Test public void testLocalAlias1() { test( "var a = {b: 3}; function f() { var x = a; f(x.b); }", // "var a$b = 3 ; function f() { var x = null; f(a$b); }"); test( "var a = {b: 3}; function f() { var x = a; f(x?.b); }", "var a = {b: 3}; function f() { var x = null; f(a?.b); }"); } @Test public void testLocalAlias2() { test( "var a = {b: 3, c : 4}; function f() { var x = a; f(x.b); f(x.c);}", "var a$b = 3; var a$c = 4 ; function f() { var x = null; f(a$b); f(a$c);}"); test( "var a = {b: 3, c: 4}; function f() { var x = a; f?.(x?.b); f?.(x?.c);}", "var a = {b: 3, c: 4}; function f() { var x = null; f?.(a?.b); f?.(a?.c);}"); } @Test public void testLocalAlias3() { test( lines( "var a = {b: 3, c: {d: 5}}; ", // "function f() { var x = a; f(x.b); f(x.c); f(x.c.d); }"), lines( "var a$b = 3; var a$c = {d: 5}; ", // "function f() { var x = null; f(a$b); f(a$c); f(a$c.d);}")); test( lines( "var a = {b: 3, c: {d: 5}};", // "function f() { var x = a; f?.(x?.b); f?.(x?.c); f?.(x.c?.d);}"), lines( "var a = {b: 3, c: {d:5}};", // "function f() { var x = null; f?.(a?.b); f?.(a?.c); f?.(a.c?.d);}")); } @Test public void testLocalAlias4() { test( lines( "var a = {b: 3}; var c = {d: 5}; ", // "function f() { var x = a; var y = c; f(x.b); f(y.d); }"), lines( "var a$b = 3; var c$d = 5; ", // "function f() { var x = null; var y = null; f(a$b); f(c$d);}")); test( lines( "var a = {b: 3}; var c = {d: 5};", // "function f() { var x = a; var y = c; f?.(x?.b); f?.(y?.d); }"), lines( "var a = {b: 3}; var c = {d: 5};", // "function f() { var x = null; var y = null; f?.(a?.b); f?.(c?.d); }")); } @Test public void testLocalAlias5() { test( lines( "var a = {b: {c: 5}}; ", // "function f() { var x = a; var y = x.b; f(a.b.c); f(y.c); }"), lines( "var a$b$c = 5; ", // "function f() { var x = null; var y = null; f(a$b$c); f(a$b$c);}")); test( lines( "var a = {b: {c: 5}};", // "function f() { var x = a; var y = x?.b; f?.(a.b?.c); f?.(y?.c); }"), lines( "var a = {b: {c: 5}};", // "function f() { var x = null; var y = a?.b; f?.(a.b?.c); f?.(y?.c); }")); } @Test public void testLocalAlias6() { test( "var a = {b: 3}; function f() { var x = a; if (x.b) { f(x.b); } }", // "var a$b = 3; function f() { var x = null; if (a$b) { f(a$b); } }"); test( "var a = {b: 3}; function f() { var x = a; if (x?.b) { f?.(x?.b); } }", // "var a = {b: 3}; function f() { var x = null; if (a?.b) { f?.(a?.b); } }"); } @Test public void testLocalAlias7() { test( "var a = {b: {c: 5}}; function f() { var x = a.b; f(x.c); }", // "var a$b$c = 5; function f() { var x = null; f(a$b$c); }"); testSame("var a = {b: {c: 5}}; function f() { var x = a?.b; f?.(x?.c); }"); } @Test public void testLocalAlias8() { testSame("var a = { b: 3 }; function f() { if (true) { var x = a; f(x.b); } x = { b : 4}; }"); } @Test public void testGlobalWriteToAncestor() { testSame("var a = {b: 3}; function f() { var x = a; f(a.b); } a = 5;"); } @Test public void testGlobalWriteToNonAncestor() { test( "var a = {b: 3}; function f() { var x = a; f(a.b); } a.b = 5;", // "var a$b = 3; function f() { var x = null; f(a$b); } a$b = 5;"); test( "var a = {b: 3}; function f() { var x = a; f(a?.b); } a.b = 5;", "var a = {b: 3}; function f() { var x = null; f(a?.b); } a.b = 5;"); } @Test public void testLocalWriteToAncestor() { testSame("var a = {b: 3}; function f() { a = 5; var x = a; f(a.b); } "); } @Test public void testLocalWriteToNonAncestor() { test( lines( "var a = {b: 3}; ", // "function f() { a.b = 5; var x = a; f(a.b); }"), "var a$b = 3; function f() { a$b = 5; var x = null; f(a$b); } "); test( lines( "var a = {b: 3}; ", // "function f() { a.b = 5; var x = a; f?.(a?.b); }"), lines( "var a = {b: 3}; ", // "function f() { a.b = 5; var x = null; f?.(a?.b); }")); } @Test public void testLocalAliasOfAncestor() { testSame( lines( "var a = {b: {c: 5}}; function g() { f(a); } ", // "function f() { var x = a.b; f(x.c); }")); } @Test public void testGlobalAliasOfAncestor() { test( "var a = {b: {c: 5}}; function f() { var x = a.b; f(x.c); }", // "var a$b$c=5; function f() {var x=null; f(a$b$c); }"); testSame("var a = {b: {c: 5}}; function f() { var x = a?.b; f?.(x?.c); }"); } @Test public void testLocalAliasOfOtherName() { testSame( lines( "var foo = function() { return {b: 3}; };", // "var a = foo(); a.b = 5; ", "function f() { var x = a.b; f(x); }")); } @Test public void testLocalAliasOfFunction() { test( lines( "var a = function() {}; a.b = 5; ", // "function f() { var x = a.b; f(x); }"), lines( "var a = function() {}; var a$b = 5; ", // "function f() { var x = null; f(a$b); }")); } @Test public void testNoInlineGetpropIntoCall() { test( "var b = x; function f() { var a = b; a(); }", // "var b = x; function f() { var a = null; b(); }"); test( "var b = {}; b.c = x; function f() { var a = b.c; a(); }", // "var b$c = x; function f() { var a = null; b$c(); }"); } @Test public void testCommaOperator() { test( "var a = {}; a.b = function() {}, a.b();", // "var a$b; a$b=function() {}, a$b();"); test( lines( "var ns = {};", // "ns.Foo = {};", "var Baz = {};", "Baz.Foo = ns.Foo;", "(Baz.Foo.bar = 10, 123);"), lines( "var Baz$Foo=null;", // "var ns$Foo$bar;", "(ns$Foo$bar = 10, 123);")); test( lines( "var ns = {};", // "ns.Foo = {};", "var Baz = {};", "Baz.Foo = ns?.Foo;", "(Baz.Foo.bar = 10, 123);"), lines( "var ns = {};", // "ns.Foo = {};", "var Baz$Foo = ns?.Foo;", "(Baz$Foo.bar = 10, 123);")); test( lines( "var ns = {};", // "ns.Foo = {};", "var Baz = {};", "Baz.Foo = ns.Foo;", "function f() { (Baz.Foo.bar = 10, 123); }"), lines( "var ns$Foo$bar;", // "var Baz$Foo=null;", "function f() { (ns$Foo$bar = 10, 123); }")); test( lines( "var ns = {};", // "ns.Foo = {};", "var Baz = {};", "Baz.Foo = ns?.Foo;", "function f() { (Baz.Foo.bar = 10, 123); }"), lines( "var ns = {};", // "ns.Foo = {};", "var Baz$Foo = ns?.Foo;", "function f() { (Baz$Foo.bar = 10, 123); }")); } @Test public void testTypeDefAlias1() { test( lines( "/** @constructor */ var D = function() {};", // "/** @constructor */ D.L = function() {};", "/** @type {D.L} */ D.L.A = new D.L();", "", "/** @const */ var M = {};", "/** @typedef {D.L} */ M.L = D.L;", "", "use(M.L.A);"), lines( "/** @constructor */ var D = function() {};", // "/** @constructor */ var D$L = function() {};", "/** @type {D.L} */ var D$L$A = new D$L();", "/** @typedef {D.L} */ var M$L = null", "use(D$L$A);")); test( lines( "/** @constructor */ var D = function() {};", // "/** @constructor */ D.L = function() {};", "/** @type {D.L} */ D.L.A = new D.L();", "", "/** @const */ var M = {};", "/** @typedef {D.L} */ M.L = D.L;", "", "use?.(M.L?.A);"), lines( "/** @constructor */ var D = function() {};", // "/** @constructor */ var D$L = function() {};", "/** @type {D.L} */ var D$L$A = new D$L();", "/** @typedef {D.L} */ var M$L = null", // TODO(b/148237949): collapse above breaks this reference "use?.(D$L?.A);")); } @Test public void testGlobalAliasWithProperties1() { test( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns.Foo;", "var x = function() {use(ns.Bar.EventType.A)};", "use(x);"), lines( "/** @constructor */ var ns$Foo = function(){};", // "var ns$Foo$EventType$A = 1;", "var ns$Foo$EventType$B = 2;", "/** @constructor */ var ns$Bar = null;", "var x = function(){use(ns$Foo$EventType$A)};", "use(x);")); testSame( srcs( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns?.Foo;", "var x = function() {use?.(ns.Bar.EventType?.A)};", "use?.(x);")), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testGlobalAliasWithProperties2() { // Reassignment of properties was necessary to prevent invalid code in // previous iterations of this optimization. Verify we don't break // code like this. Now it causes a back-off of the collapsing because // the value is assigned more than once. test( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns.Foo;", "/** @enum {number} */ ns.Bar.EventType = ns.Foo.EventType;", "var x = function() {use(ns.Bar.EventType.A)};", "use(x)"), lines( "/** @constructor */ var ns$Foo = function(){};", // "/** @enum {number} */ var ns$Foo$EventType = {A:1, B:2};", "/** @constructor */ var ns$Bar = null;", "/** @enum {number} */ ns$Foo$EventType = ns$Foo$EventType;", "var x = function(){use(ns$Foo$EventType.A)};", "use(x);")); testSame( srcs( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns?.Foo;", "/** @enum {number} */ ns.Bar.EventType = ns.Foo?.EventType;", "var x = function() {use?.(ns.Bar.EventType?.A)};", "use?.(x)")), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testGlobalAliasWithProperties3() { test( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns.Foo;", "/** @enum {number} */ ns.Bar.Other = {X:1, Y:2};", "var x = function() {use(ns.Bar.Other.X)};", "use(x)"), lines( "/** @constructor */ var ns$Foo=function(){};", // "var ns$Foo$EventType$A=1;", "var ns$Foo$EventType$B=2;", "/** @constructor */ var ns$Bar=null;", "var ns$Foo$Other$X=1;", "var ns$Foo$Other$Y=2;", "var x=function(){use(ns$Foo$Other$X)};", "use(x)\n")); testSame( srcs( lines( "var ns = {}; ", // "/** @constructor */ ns.Foo = function() {};", "/** @enum {number} */ ns.Foo.EventType = {A:1, B:2};", "/** @constructor */ ns.Bar = ns?.Foo;", "/** @enum {number} */ ns.Bar.Other = {X:1, Y:2};", "var x = function() {use?.(ns.Bar.Other?.X)};", "use?.(x)")), warning(PARTIAL_NAMESPACE_WARNING)); } @Test public void testGlobalAliasWithProperties4() { testSame( lines( "", // "var nullFunction = function(){};", "var blob = {};", "blob.init = nullFunction;", "use(blob)")); } @Test public void testGlobalAlias_propertyOnExternedConstructor_isNotChanged() { testSame( externs("/** @constructor */ var blob = function() {}"), srcs( lines( "var nullFunction = function(){};", // "blob.init = nullFunction;", "use(blob.init)"))); } @Test public void testLocalAliasOfEnumWithInstanceofCheck() { test( lines( "/** @constructor */", // "var Enums = function() {", "};", "", "/** @enum {number} */", "Enums.Fruit = {", " APPLE: 1,", " BANANA: 2,", "};", "", "function foo(f) {", " if (f instanceof Enums) { alert('what?'); return; }", "", " var Fruit = Enums.Fruit;", " if (f == Fruit.APPLE) alert('apple');", " if (f == Fruit.BANANA) alert('banana');", "}"), lines( "/** @constructor */", // "var Enums = function() {};", "var Enums$Fruit$APPLE = 1;", "var Enums$Fruit$BANANA = 2;", "function foo(f) {", " if (f instanceof Enums) { alert('what?'); return; }", " var Fruit = null;", " if (f == Enums$Fruit$APPLE) alert('apple');", " if (f == Enums$Fruit$BANANA) alert('banana');", "}")); } @Test public void testCollapsePropertiesOfClass1() { test( lines( "/** @constructor */", // "var namespace = function() {};", "goog.inherits(namespace, Object);", "", "namespace.includeExtraParam = true;", "", "/** @enum {number} */", "namespace.Param = {", " param1: 1,", " param2: 2", "};", "", "if (namespace.includeExtraParam) {", " namespace.Param.optParam = 3;", "}", "", "function f() {", " var Param = namespace.Param;", " log(namespace.Param.optParam);", " log(Param.optParam);", "}"), lines( "/** @constructor */", // "var namespace = function() {};", "goog.inherits(namespace, Object);", "var namespace$includeExtraParam = true;", "var namespace$Param$param1 = 1;", "var namespace$Param$param2 = 2;", "if (namespace$includeExtraParam) {", " var namespace$Param$optParam = 3;", "}", "function f() {", " var Param = null;", " log(namespace$Param$optParam);", " log(namespace$Param$optParam);", "}")); // TODO(b/148237949): CollapseProperties breaks several optional chain references here test( lines( "/** @constructor */", // "var namespace = function() {};", "goog.inherits(namespace, Object);", "", "namespace.includeExtraParam = true;", "", "/** @enum {number} */", "namespace.Param = {", " param1: 1,", " param2: 2", "};", "", "if (namespace?.includeExtraParam) {", " namespace.Param.optParam = 3;", "}", "", "function f() {", " var Param = namespace?.Param;", " log(namespace.Param?.optParam);", " log(Param?.optParam);", "}"), lines( "/** @constructor */", // "var namespace = function() {};", "goog.inherits(namespace, Object);", "var namespace$includeExtraParam = true;", "var namespace$Param$param1 = 1;", "var namespace$Param$param2 = 2;", "/** @enum {number} */", "var namespace$Param = {", " param1: namespace$Param$param1,", " param2: namespace$Param$param2", "};", "if (namespace?.includeExtraParam) {", // broken " var namespace$Param$optParam = 3;", "}", "function f() {", " var Param = namespace?.Param;", // broken " log(namespace$Param?.optParam);", // broken " log(Param?.optParam);", // broken "}")); } @Test public void testCollapsePropertiesOfClass2() { test( lines( "var goog = goog || {};", // "goog.addSingletonGetter = function(cls) {};", "", "var a = {};", "", "/** @constructor */", "a.b = function() {};", "goog.addSingletonGetter(a.b);", "a.b.prototype.get = function(key) {};", "", "/** @constructor */", "a.b.c = function() {};", "a.b.c.XXX = new a.b.c();", "", "function f() {", " var x = a.b.getInstance();", " var Key = a.b.c;", " x.get(Key.XXX);", "}"), lines( "var goog = goog || {};", // "var goog$addSingletonGetter = function(cls) {};", "/** @constructor */", "var a$b = function() {};", "goog$addSingletonGetter(a$b);", "a$b.prototype.get = function(key) {};", "/** @constructor */", "var a$b$c = function() {};", "var a$b$c$XXX = new a$b$c();", "", "function f() {", " var x = a$b.getInstance();", " var Key = null;", " x.get(a$b$c$XXX);", "}")); } @Test public void test_b19179602() { // Note that this only collapses a.b.staticProp because a.b is a constructor. // Normally AggressiveInlineAliases would not inline "b" inside the loop. test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f() {", " while (true) {", // b is declared inside a loop, so it is reassigned multiple times " var b = a.b;", " alert(b.staticProp);", " }", "}"), lines( "/** @constructor */ var a$b = function() {};", // "var a$b$staticProp = 5;", "function f() {", " while (true) {", " var b = null;", " alert(a$b$staticProp);", " }", "}")); test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f() {", " while (true) {", // b is declared inside a loop, so it is reassigned multiple times " var b = a.b;", " alert(b?.staticProp);", " }", "}"), lines( "/** @constructor */ var a$b = function() {};", // "var a$b$staticProp = 5;", "function f() {", " while (true) {", " var b = null;", // TODO(bradfordcsmith): This reference is broken by collapsing above. " alert(a$b?.staticProp);", " }", "}")); } @Test public void test_b19179602_declareOutsideLoop() { test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f() {", // b is declared outside the loop " var b = a.b;", " while (true) {", " alert(b.staticProp);", " }", "}"), lines( "/** @constructor */", // "var a$b = function() {};", "var a$b$staticProp = 5;", "", "function f() {", " var b = null;", " while (true) {", " alert(a$b$staticProp);", " }", "}")); test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f() {", // b is declared outside the loop " var b = a.b;", " while (true) {", " alert(b?.staticProp);", " }", "}"), lines( "/** @constructor */", // "var a$b = function() {};", // TODO(b/148237949): Collapsing this breaks the optional chain reference below. "var a$b$staticProp = 5;", "", "function f() {", " var b = null;", " while (true) {", " alert(a$b?.staticProp);", " }", "}")); } @Test public void testCtorManyAssignmentsDontInlineWarn() { test( lines( "var a = {};", // "/** @constructor */ a.b = function() {};", "a.b.staticProp = 5;", "function f(y, z) {", " var x = a.b;", " if (y) {", " x = z;", " }", " return x.staticProp;", "}"), lines( "/** @constructor */ var a$b = function() {};", // "var a$b$staticProp = 5;", "function f(y, z) {", " var x = a$b;", " if (y) {", " x = z;", " }", " return x.staticProp;", "}"), warning(InlineAndCollapseProperties.UNSAFE_CTOR_ALIASING)); } @Test public void testCodeGeneratedByGoogModule() { // The static property is added to the exports object test( lines( "var $jscomp = {};", // "$jscomp.scope = {};", "/** @constructor */", "$jscomp.scope.Foo = function() {};", "var exports = $jscomp.scope.Foo;", "exports.staticprop = {A:1};", "var y = exports.staticprop.A;"), lines( "/** @constructor */", // "var $jscomp$scope$Foo = function() {}", "var exports = null;", "var $jscomp$scope$Foo$staticprop$A = 1;", "var y = null;")); // The static property is added to the constructor test( lines( "var $jscomp = {};", // "$jscomp.scope = {};", "/** @constructor */", "$jscomp.scope.Foo = function() {};", "$jscomp.scope.Foo.staticprop = {A:1};", "var exports = $jscomp.scope.Foo;", "var y = exports.staticprop.A;"), lines( "/** @constructor */", // "var $jscomp$scope$Foo = function() {}", "var $jscomp$scope$Foo$staticprop$A = 1;", "var exports = null;", "var y = null;")); } @Test public void testInlineCtorInObjLit() { test( lines( "/** @constructor */", // "function Foo() {}", "", "/** @constructor */", "var Bar = Foo;", "", "var objlit = {", " 'prop' : Bar", "};"), lines( "/** @constructor */", // "function Foo() {}", "/** @constructor */", "var Bar = null;", "var objlit$prop = Foo;")); } @Test public void testNoCollapseExportedNode() { test( "var x = {}; x.y = {}; var dontExportMe = x.y; use(dontExportMe);", // "var x$y = {}; var dontExportMe = null; use(x$y);"); test( "var x = {}; x.y = {}; var _exportMe = x.y;", // "var x$y = {}; var _exportMe = x$y;"); } @Test public void testDontCrashCtorAliasWithEnum() { test( lines( "var ns = {};", // "/** @constructor */", "ns.Foo = function () {};", "var Bar = ns.Foo;", "/** @const @enum */", "Bar.prop = { A: 1 };"), lines( "/** @constructor */", // "var ns$Foo = function(){};", "var Bar = null;", "var ns$Foo$prop$A = 1")); } @Test public void testDontCrashNamespaceAliasAcrossScopes() { test( lines( "var ns = {};", // "ns.VALUE = 0.01;", "function f() {", " var constants = ns;", " (function() {", " var x = constants.VALUE;", " })();", "}"), null); } @Test public void testGlobalAliasWithLet() { test( "let ns = {}; ns.foo = 'bar'; let ns2 = ns; use(ns2.foo);", // "var ns$foo = 'bar'; let ns2 = null; use(ns$foo);"); test( "let ns = {}; ns.foo = 'bar'; let ns2 = ns; use?.(ns2?.foo);", // "let ns = {}; ns.foo = 'bar'; let ns2 = null; use?.( ns?.foo);"); } @Test public void testGlobalAliasForLet2() { // We don't do any sort of branch prediction, so can't collapse here. testSame( lines( "let ns = {};", // "ns.foo = 'bar';", "let ns2;", "if (true) {", " ns2 = ns;", "}", "use(ns2.foo);")); } @Test public void testGlobalAliasWithLet3() { // Back off since in general we don't check that ns2 is only ever accessed within the if block. testSame( lines( "let ns = {};", // "ns.foo = 'bar';", "let ns2;", "if (true) {", " ns2 = ns;", " use(ns2.foo);", "}")); } @Test public void testLocalAliasWithLet1() { test( "let ns = {}; ns.foo = 'bar'; function f() { let ns2 = ns; use(ns2.foo); }", "var ns$foo = 'bar'; function f() { let ns2 = null; use( ns$foo); }"); test( "let ns = {}; ns.foo = 'bar'; function f() { let ns2 = ns; use?.(ns2?.foo); }", "let ns = {}; ns.foo = 'bar'; function f() { let ns2 = null; use?.( ns?.foo); }"); } @Test public void testLocalAliasWithLet2() { test( lines( "let ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " let ns2 = ns;", " use(ns2.foo);", " }", "}"), lines( "var ns$foo = 'bar';", // "function f() {", " if (true) {", " let ns2 = null;", " use(ns$foo);", " }", "}")); test( lines( "let ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " let ns2 = ns;", " use?.(ns2?.foo);", " }", "}"), lines( "let ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " let ns2 = null;", " use?.(ns?.foo);", " }", "}")); } @Test public void testLocalAliasWithLet3() { test( lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let ns2 = ns;", " use(ns2.foo);", "}"), lines( "var ns$foo = 'bar';", // "if (true) {", " let ns2 = null;", " use(ns$foo);", "}")); test( lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let ns2 = ns;", " use?.(ns2?.foo);", "}"), lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let ns2 = null;", " use?.(ns?.foo);", "}")); } @Test public void testLocalAliasWithLet4() { test( lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let baz = ns.foo;", " use(baz);", "}"), lines( "var ns$foo = 'bar';", // "if (true) {", " let baz = null;", " use(ns$foo);", "}")); } @Test public void testLocalAliasWithLet5() { // For local variables (VAR, CONST, or LET) we only handle cases where the alias is a variable, // not a property. testSame( lines( "let ns = {};", // "ns.foo = 'bar';", "if (true) {", " let ns2 = {};", " ns2.baz = ns;", " use(ns2.baz.foo);", "}")); } @Test public void testGlobalAliasWithConst() { test( "const ns = {}; ns.foo = 'bar'; const ns2 = ns; use(ns2.foo);", // "var ns$foo = 'bar'; const ns2 = null; use(ns$foo);"); test( "const ns = {}; ns.foo = 'bar'; const ns2 = ns; use?.(ns2?.foo);", // "const ns = {}; ns.foo = 'bar'; const ns2 = null; use?.( ns?.foo);"); } @Test public void testLocalAliasWithConst1() { test( lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " const ns2 = ns;", " use(ns2.foo);", "}"), lines( "var ns$foo = 'bar';", // "function f() {", " const ns2 = null;", " use(ns$foo);", "}")); test( lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " const ns2 = ns;", " use?.(ns2?.foo);", "}"), lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " const ns2 = null;", " use?.(ns?.foo);", "}")); } @Test public void testLocalAliasWithConst2() { test( lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " const ns2 = ns;", " use(ns2.foo);", " }", "}"), lines( "var ns$foo = 'bar';", // "function f() {", " if (true) {", " const ns2 = null;", " use(ns$foo);", " }", "}")); test( lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " const ns2 = ns;", " use?.(ns2?.foo);", " }", "}"), lines( "const ns = {};", // "ns.foo = 'bar';", "function f() {", " if (true) {", " const ns2 = null;", " use?.(ns?.foo);", " }", "}")); } @Test public void testLocalAliasWithConst3() { test( lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const ns2 = ns;", " use(ns2.foo);", "}"), lines( "var ns$foo = 'bar';", // "if (true) {", " const ns2 = null;", " use(ns$foo);", "}")); test( lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const ns2 = ns;", " use?.(ns2?.foo);", "}"), lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const ns2 = null;", " use?.(ns?.foo);", "}")); } @Test public void testLocalAliasWithConst4() { test( lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const baz = ns.foo;", " use(baz);", "}"), lines( "var ns$foo = 'bar';", // "if (true) {", " const baz = null;", " use(ns$foo);", "}")); } @Test public void testLocalAliasWithConst5() { // For local variables (VAR, CONST, or LET) we only handle cases where the alias is a variable, // not a property. testSame( lines( "const ns = {};", // "ns.foo = 'bar';", "if (true) {", " const ns2 = {};", " ns2.baz = ns;", " use(ns2.baz.foo);", "}")); } @Test public void testLocalAliasInsideClass() { test( "var a = {b: 5}; class A { fn() { var c = a; use(a.b); } }", // "var a$b = 5; class A { fn() { var c = null; use(a$b); } }"); test( "var a = {b: 5}; class A { fn() { var c = a; use?.(a?.b); } }", // "var a = {b: 5}; class A { fn() { var c = null; use?.(a?.b); } }"); } @Test public void testEs6ClassStaticProperties() { // Collapsing static properties (A.foo and A.useFoo in this case) is known to be unsafe. test( srcs( lines( "class A {", // " static useFoo() {", " alert(this.foo);", " }", "}", "A.foo = 'bar';", "const B = A;", "B.foo = 'baz';", "B.useFoo();")), expected( lines( "var A$useFoo = function() { alert(this.foo); };", // "class A {}", "var A$foo = 'bar';", "const B = null;", "A$foo = 'baz';", "A$useFoo();")), warning(RECEIVER_AFFECTED_BY_COLLAPSE)); // Adding @nocollapse makes this safe. test( lines( "class A {", // " /** @nocollapse */", " static useFoo() {", " alert(this.foo);", " }", "}", "/** @nocollapse */", "A.foo = 'bar';", "const B = A;", "B.foo = 'baz';", "B.useFoo();"), lines( "class A {", // " /** @nocollapse */", " static useFoo() {", " alert(this.foo);", " }", "}", "/** @nocollapse */", "A.foo = 'bar';", "const B = null;", "A.foo = 'baz';", "A.useFoo();")); } @Test public void testClassStaticInheritance_method() { test( "class A { static s() {} } class B extends A {} const C = B; C.s();", // "var A$s = function() {}; class A {} class B extends A {} const C = null; A$s();"); test( "class A { static s() {} } class B extends A {} B.s();", // "var A$s = function() {}; class A {} class B extends A {} A$s();"); test( "class A {} A.s = function() {}; class B extends A {} B.s();", // "class A {} var A$s = function() {}; class B extends A {} A$s();"); } @Test public void testClassStaticInheritance_propertyAlias() { test( "class A {} A.staticProp = 6; class B extends A {} let b = new B;", // "class A {} var A$staticProp = 6; class B extends A {} let b = new B;"); test( "class A {} A.staticProp = 6; class B extends A {} use(B.staticProp);", // "class A {} var A$staticProp = 6; class B extends A {} use(A$staticProp);"); test( "class A {} A.staticProp = 6; class B extends A {} use(B?.staticProp);", // TODO(b/148237949): collapse breaks `B?.staticProp` reference "class A {} var A$staticProp = 6; class B extends A {} use(B?.staticProp);"); } @Test public void testClassStaticInheritance_propertyWithSubproperty() { test( "class A {} A.ns = {foo: 'bar'}; class B extends A {} use(B.ns.foo);", // "class A {} var A$ns$foo = 'bar'; class B extends A {} use(A$ns$foo);"); test( "class A {} A.ns = {foo: 'bar'}; class B extends A {} use(B.ns?.foo);", // "class A {} var A$ns = {foo: 'bar'}; class B extends A {} use(A$ns?.foo);"); test( "class A {} A.ns = {}; class B extends A {} B.ns.foo = 'baz'; use(B.ns.foo);", "class A {} class B extends A {} var A$ns$foo = 'baz'; use(A$ns$foo);"); test( "class A {} A.ns = {}; class B extends A {} B.ns.foo = 'baz'; use(B.ns?.foo);", "class A {} var A$ns = {}; class B extends A {} A$ns.foo = 'baz'; use(A$ns?.foo);"); } @Test public void testClassStaticInheritance_propertyWithShadowing() { test( "class A {} A.staticProp = 6; class B extends A {} B.staticProp = 7;", // "class A {} var A$staticProp = 6; class B extends A {} var B$staticProp = 7;"); // At the time use() is called, B.staticProp is still the same as A.staticProp, but we back off // rewriting it because of the shadowing afterwards. This makes CollapseProperties unsafely // collapse in this case - the same issue occurs when transpiling down to ES5. test( "class A {} A.foo = 6; class B extends A {} use(B.foo); B.foo = 7;", // "class A {} var A$foo = 6; class B extends A {} use(B$foo); var B$foo = 7;"); test( "class A {} A.foo = 6; class B extends A {} use(B?.foo); B.foo = 7;", // TODO(b/148237949): collapse properties breaks `B?.foo` reference "class A {} var A$foo = 6; class B extends A {} use(B?.foo); var B$foo = 7;"); } @Test public void testClassStaticInheritance_cantDetermineSuperclass() { // Here A.foo and B.foo are unsafely collapsed because getSuperclass() creates an alias for them test( lines( "class A {}", // "A.foo = 5;", "class B {}", "B.foo = 6;", "function getSuperclass() { return 1 < 2 ? A : B; }", "class C extends getSuperclass() {}", "use(C.foo);"), lines( "class A {}", // "var A$foo = 5;", "class B {}", "var B$foo = 6;", "function getSuperclass() { return 1 < 2 ? A : B; }", "class C extends getSuperclass() {}", "use(C.foo);")); } @Test public void testAliasForSuperclassNamespace() { test( lines( "var ns = {};", // "class Foo {}", "ns.clazz = Foo;", "var Bar = class extends ns.clazz.Baz {}"), lines( "class Foo {}", // "var ns$clazz = null;", "var Bar = class extends Foo.Baz {}")); test( lines( "var ns = {};", // "class Foo {}", "Foo.Builder = class {}", "ns.clazz = Foo;", "var Bar = class extends ns.clazz.Builder {}"), lines( "class Foo {}", // "var Foo$Builder = class {}", "var ns$clazz = null;", "var Bar = class extends Foo$Builder {}")); } @Test public void testAliasForSuperclassNamespace_withStaticInheritance() { test( lines( "var ns = {};", // "class Foo {}", "Foo.Builder = class {}", "Foo.Builder.baz = 3;", "ns.clazz = Foo;", "var Bar = class extends ns.clazz.Builder {}", "use(Bar.baz);"), lines( "class Foo {}", // "var Foo$Builder = class {}", "var Foo$Builder$baz = 3;", "var ns$clazz = null;", "var Bar = class extends Foo$Builder {}", "use(Foo$Builder$baz);")); test( lines( "var ns = {};", // "class Foo {}", "Foo.Builder = class {}", "Foo.Builder.baz = 3;", "ns.clazz = Foo;", "var Bar = class extends ns.clazz?.Builder {}", "use(Bar?.baz);"), lines( "class Foo {}", // "var Foo$Builder = class {}", "var Foo$Builder$baz = 3;", "var ns$clazz = null;", // TODO(b/148237979): Collapse above breaks this reference. "var Bar = class extends Foo?.Builder {}", // TODO(b/148237979): Collapse above breaks this reference. "use(Bar?.baz);")); } @Test public void testDestructuringAlias1() { testSame("var a = { x: 5 }; var [b] = [a]; use(b.x);"); } @Test public void testDestructuringAlias2() { testSame("var a = { x: 5 }; var {b} = {b: a}; use(b.x);"); } @Test public void testDestructingAliasWithConstructor() { test( lines( "var ns = {};", // "/** @constructor */", "ns.ctor = function() {}", "const {ctor} = ns;", "let c = new ctor;"), lines( "/** @constructor */", // "var ns$ctor = function() {}", "const ctor = null;", "let c = new ns$ctor;")); } @Test public void namespaceInDestructuringPattern() { testSame( lines( "const ns = {};", // "ns.x = 1;", "ns.y = 2;", "let {x, y} = ns;", "x = 4;", // enforce that we can't inline x -> ns.x because it's set multiple times "use(x + y);")); } @Test public void inlineDestructuringPatternConstructorWithProperty() { test( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y.prop);"), lines( "/** @constructor */", // "var ns$Y = function() {};", "var ns$Y$prop = 3;", "const Y = null;", "use(ns$Y$prop);")); test( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "const {Y} = ns;", "use(Y?.prop);"), lines( "/** @constructor */", // "var ns$Y = function() {};", // TODO(bradfordcsmith): This collapse breaks the optional chain // reference below. "var ns$Y$prop = 3;", "const Y = null;", "use(ns$Y?.prop);")); // Only `const` destructuring aliases have special handling by AggressiveInlineAliases testSame( lines( "const ns = {};", // "/** @constructor */", "ns.Y = function() {};", "ns.Y.prop = 3;", "let {Y} = ns;", "use(Y.prop);"), PARTIAL_NAMESPACE_WARNING); } @Test public void testDefaultParamAlias1() { test( "var a = {b: 5}; var b = a; function f(x=b) { alert(x.b); }", // "var a = {b: 5}; var b = null; function f(x=a) { alert(x.b); }"); } @Test public void testDefaultParamAlias2() { test( "var a = {b: {c: 5}}; var b = a; function f(x=b.b) { alert(x.c); }", // "var a$b = {c: 5}; var b = null; function f(x=a$b) { alert(x.c); }"); test( "var a = {b: {c: 5}}; var b = a; function f(x=b?.b) { alert(x?.c); }", // "var a = {b: {c: 5}}; var b = null; function f(x=a?.b) { alert(x?.c); }"); } @Test public void testAliasPropertyOnUnsafelyRedefinedNamespace() { testSame("var obj = {foo: 3}; var foo = obj.foo; obj = {}; alert(foo);"); } @Test public void testAliasPropertyOnSafelyRedefinedNamespace() { // non-constructor property doesn't get collapsed test( "var obj = {foo: 3}; var foo = obj.foo; obj = obj || {}; alert(foo);", // "var obj = {foo: 3}; var foo = null ; obj = obj || {}; alert(obj.foo);"); // constructor property does get collapsed test( lines( "var ns = {};", // "/** @constructor */ ns.ctor = function() {};", "ns.ctor.foo = 3;", "var foo = ns.ctor.foo;", "ns = ns || {};", "alert(foo);"), lines( "var ns = {};", // "/** @constructor */ var ns$ctor = function() {};", "var ns$ctor$foo = 3;", "var foo = null;", "ns = ns || {};", "alert(ns$ctor$foo);")); // NOTE(lharker): this mirrors current code in Closure library test( lines( "var goog = {};", // "goog.module = function() {};", "/** @constructor */ goog.module.ModuleManager = function() {};", "goog.module.ModuleManager.getInstance = function() {};", "goog.module = goog.module || {};", "var ModuleManager = goog.module.ModuleManager;", "alert(ModuleManager.getInstance());"), lines( "var goog$module = function() {};", // "/** @constructor */ var goog$module$ModuleManager = function() {};", "var goog$module$ModuleManager$getInstance = function() {};", "goog$module = goog$module || {};", "var ModuleManager = null;", "alert(goog$module$ModuleManager$getInstance());")); } @Test public void testClassInObjectLiteral() { test( "var obj = {foo: class {}};", // "var obj$foo = class {};"); // TODO(lharker): this is unsafe, obj$foo.foo is undefined now that A$foo is collapsed test( "class A {} A.foo = 3; var obj = {foo: class extends A {}}; use(obj.foo.foo);", // "class A {} var A$foo = 3; var obj$foo = class extends A{}; use(obj$foo.foo)"); } @Test public void testLoopInAliasChainOfTypedefConstructorProperty() { test( lines( "/** @constructor */ var Item = function() {};", // "/** @typedef {number} */ Item.Models;", "Item.Models = Item.Models;"), lines( "/** @constructor */ var Item = function() {};", // "Item$Models;", "var Item$Models = Item$Models;")); test( lines( "/** @constructor */ var Item = function() {};", // "/** @typedef {number} */ Item.Models;", "Item.Models = Item?.Models;"), lines( "/** @constructor */ var Item = function() {};", // "Item$Models;", // TODO(b/148237949): Collapsing breaks this reference. "var Item$Models = Item?.Models;")); } @Test public void testDontInlinePropertiesOnEscapedNamespace() { testSame( externs("function use(obj) {}"), srcs( lines( "function Foo() {}", // "Foo.Bar = {};", "Foo.Bar.baz = {A: 1, B: 2};", "", "var $jscomp$destructuring$var1 = Foo.Bar;", // This call could potentially have changed the value of Foo.Bar, so don't // collapse Foo.Bar.baz.A/Foo.Bar.baz.B "use(Foo);", "var baz = $jscomp$destructuring$var1.baz;", "use(baz.A);"))); } @Test public void testInliningPropertiesOnEscapedNamespace_withDeclaredType() { test( externs("function use(obj) {}"), srcs( lines( "/** @constructor */", // "function Foo() {}", "/** @constructor */", "Foo.Bar = function() {};", "/** @enum {number} */", "Foo.Bar.baz = {A: 1, B: 2};", "", "var $jscomp$destructuring$var1 = Foo.Bar;", "use(Foo);", "var baz = $jscomp$destructuring$var1.baz;", "use(baz.A);")), expected( lines( "/** @constructor */", // "function Foo() {}", "/** @constructor */", "var Foo$Bar = function() {};", "var Foo$Bar$baz$A = 1;", "var Foo$Bar$baz$B = 2;", "", "var $jscomp$destructuring$var1 = null;", // This call could potentially read Foo.Bar, which will now be broken. // AggressiveInlineAliases/CollapseProperties intentionally generate unsafe code // in this case. The main motivation is to collapse long namespaces generated by // goog.provide or goog.module.declareLegacyNamespace() // https://developers.google.com/closure/compiler/docs/limitations#implications-of-object-property-flattening "use(Foo);", "var baz = null;", "use(Foo$Bar$baz$A);"))); } @Test public void testDontInlinePropertiesOnNamespace_withNoCollapse() { testSame( externs("function use(obj) {}"), srcs( lines( "/** @constructor */", // "function Foo() {}", "/** @constructor @nocollapse */", "Foo.Bar = function() {};", "/** @enum {number} @nocollapse */", "Foo.Bar.baz = {A: 1, B: 2};", "", "var $jscomp$destructuring$var1 = Foo.Bar;", // This call could potentially have changed the value of Foo.Bar, and without // @nocollapse on Foo.Bar and Foo.Bar.baz the compiler would generate unsafe code. "use(Foo);", "var baz = $jscomp$destructuring$var1.baz;", "use(baz.A);"))); } @Test public void testInlinePropertyOnAliasedConstructor() { // TODO(b/117905881): as long as we unsafely collapse Foo.prop -> Foo$prop, there's no way to // safely rewrite the "use(ns.alias.prop)" call in the compiler // Either // a) we replace "ns.alias.prop" with "Foo$prop" or // b) we leave "ns.alias.prop" as is. // Option a) can break code if the "use(ns)" call actually reassigns ns.alias (which is not // declared const). // Option b) breaks code if "use(ns)" does NOT reassign ns.alias, since now // ns.alias.prop is Foo.prop, which is undefined. // but we might want to consider movign to (b) instead of (a), since CollapseProperties will // also break case (a) test( externs("function use(ctor) {}"), srcs( lines( "/** @constructor */", // "function Foo() {}", "Foo.prop = 2;", "var ns = {};", "ns.alias = Foo;", "use(ns);", "use(ns.alias.prop);")), expected( lines( "/** @constructor */", // "function Foo() {}", "var Foo$prop = 2;", "var ns = {};", "ns.alias = Foo;", "use(ns);", "use(ns.alias.prop);"))); } @Test public void testClassStaticMemberAccessedWithSuper() { test( lines( "class Bar {", // " static double(n) {", " return n*2", " }", "}", "class Baz extends Bar {", " static quadruple(n) {", " return 2 * super.double(n);", " }", "}"), lines( "var Bar$double = function(n) { return n * 2; }", // "class Bar {}", "var Baz$quadruple = function(n) { return 2 * Bar$double(n); }", "class Baz extends Bar {}")); } @Test public void testCommaCallAliasing1() { test( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", "(0,xid)('abc');"), lines( "var xid = function(a) {};", // // The indirect call below does not prevent this property collapse "var xid$internal_ = function() {};", "(0,xid)('abc');")); } @Test public void testCommaCallAliasing2() { test( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", "fn((0,xid)('abc'));"), lines( "var xid = function(a) {};", // // The indirect call below does not prevent this property collapse "var xid$internal_ = function() {};", "fn((0,xid)('abc'));")); } @Test public void testCommaCallAliasing3() { test( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", "throw ((0, xid), 0);"), lines( "var xid = function(a) {};", // // The indirect call below does not prevent this property collapse "var xid$internal_ = function() {};", "throw ((0, xid), 0);")); } @Test public void testHookNewAliasing1() { testSame( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", // The indirect call prevents this property collapse "var xx = new Thing(x ? xid : abc).method();")); } @Test public void testHookGetProp1() { testSame( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", // The indirect call prevents this property collapse "var xx = (x ? xid : abc).method();")); } @Test public void testHookGetProp2() { test( lines( "var xid = function(a) {};", // "xid.internal_ = function() {};", "var xx = ((x ? xid : abc) - def).toExponential(5);"), lines( "var xid = function(a) {};", // // The indirect call below does not prevent this property collapse "var xid$internal_ = function() {};", "var xx = ((x ? xid : abc) - def).toExponential(5);")); } }
`InlineAndCollapsePropertiesTest`: Add test for incorrectly collapsing toString/valueOf from object literals This test case shows that we're removing toString/valueOf functions explicitly defined in object literals, when we shouldn't be. I'm submitting this now to document the current incorrect behavior of InlineAndCollapseProperties. I'll start working on a fix for this next. PiperOrigin-RevId: 435645058
test/com/google/javascript/jscomp/InlineAndCollapsePropertiesTest.java
`InlineAndCollapsePropertiesTest`: Add test for incorrectly collapsing toString/valueOf from object literals
Java
apache-2.0
5a99ec7360884255c7d47a14641751a5bcf6a4fd
0
ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package org.ofbiz.entity.jdbc; import java.io.Serializable; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.ofbiz.base.concurrent.ExecutionPool; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilTimer; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericEntityConfException; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.config.model.Datasource; import org.ofbiz.entity.config.model.EntityConfig; import org.ofbiz.entity.datasource.GenericHelperInfo; import org.ofbiz.entity.model.ModelEntity; import org.ofbiz.entity.model.ModelField; import org.ofbiz.entity.model.ModelFieldType; import org.ofbiz.entity.model.ModelFieldTypeReader; import org.ofbiz.entity.model.ModelIndex; import org.ofbiz.entity.model.ModelKeyMap; import org.ofbiz.entity.model.ModelRelation; import org.ofbiz.entity.model.ModelViewEntity; import org.ofbiz.entity.transaction.TransactionFactoryLoader; import org.ofbiz.entity.transaction.TransactionUtil; /** * Utilities for Entity Database Maintenance * */ public class DatabaseUtil { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); // OFBiz Connections protected ModelFieldTypeReader modelFieldTypeReader = null; protected Datasource datasourceInfo = null; protected GenericHelperInfo helperInfo = null; // Legacy Connections protected String connectionUrl = null; protected String driverName = null; protected String userName = null; protected String password = null; boolean isLegacy = false; // OFBiz DatabaseUtil public DatabaseUtil(GenericHelperInfo helperInfo) { this.helperInfo = helperInfo; this.modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperInfo.getHelperBaseName()); this.datasourceInfo = EntityConfig.getDatasource(helperInfo.getHelperBaseName()); } protected Connection getConnection() throws SQLException, GenericEntityException { Connection connection = null; if (!isLegacy) { connection = TransactionFactoryLoader.getInstance().getConnection(helperInfo); } else { connection = getConnection(driverName, connectionUrl, null, userName, password); } if (connection == null) { if (!isLegacy) { throw new GenericEntityException("No connection available for helper named [" + helperInfo.getHelperFullName() + "]"); } else { throw new GenericEntityException("No connection avaialble for URL [" + connectionUrl + "]"); } } if (!TransactionUtil.isTransactionInPlace()) { connection.setAutoCommit(true); } return connection; } private Connection getConnection(String driverName, String connectionUrl, Properties props, String userName, String password) throws SQLException { // first register the JDBC driver with the DriverManager if (driverName != null) { if (DriverManager.getDriver(driverName) == null) { try { Driver driver = (Driver) Class.forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance(); DriverManager.registerDriver(driver); } catch (ClassNotFoundException e) { Debug.logWarning(e, "Unable to load driver [" + driverName + "]", module); } catch (InstantiationException e) { Debug.logWarning(e, "Unable to instantiate driver [" + driverName + "]", module); } catch (IllegalAccessException e) { Debug.logWarning(e, "Illegal access exception [" + driverName + "]", module); } } } try { if (UtilValidate.isNotEmpty(userName)) return DriverManager.getConnection(connectionUrl, userName, password); else if (props != null) return DriverManager.getConnection(connectionUrl, props); else return DriverManager.getConnection(connectionUrl); } catch (SQLException e) { Debug.logError(e, "SQL Error obtaining JDBC connection", module); throw e; } } protected Connection getConnectionLogged(Collection<String> messages) { try { return getConnection(); } catch (SQLException | GenericEntityException e) { String message = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); return null; } } public Datasource getDatasource() { return this.datasourceInfo; } /* ====================================================================== */ /* ====================================================================== */ public void checkDb(Map<String, ModelEntity> modelEntities, List<String> messages, boolean addMissing) { checkDb(modelEntities, null, messages, datasourceInfo.getCheckPksOnStart(), (datasourceInfo.getUseForeignKeys() && datasourceInfo.getCheckFksOnStart()), (datasourceInfo.getUseForeignKeyIndices() && datasourceInfo.getCheckFkIndicesOnStart()), addMissing); } public void checkDb(Map<String, ModelEntity> modelEntities, List<String> colWrongSize, List<String> messages, boolean checkPks, boolean checkFks, boolean checkFkIdx, boolean addMissing) { if (isLegacy) { throw new RuntimeException("Cannot run checkDb on a legacy database connection; configure a database helper (entityengine.xml)"); } ExecutorService executor = Executors.newFixedThreadPool(datasourceInfo.getMaxWorkerPoolSize()); UtilTimer timer = new UtilTimer(); timer.timerString("Start - Before Get Database Meta Data"); // get ALL tables from this database TreeSet<String> tableNames = this.getTableNames(messages); TreeSet<String> fkTableNames = tableNames == null ? null : new TreeSet<String>(tableNames); TreeSet<String> indexTableNames = tableNames == null ? null : new TreeSet<String>(tableNames); if (tableNames == null) { String message = "Could not get table name information from the database, aborting."; if (messages != null) messages.add(message); Debug.logError(message, module); return; } timer.timerString("After Get All Table Names"); // get ALL column info, put into hashmap by table name Map<String, Map<String, ColumnCheckInfo>> colInfo = getColumnInfo(tableNames, checkPks, messages, executor); if (colInfo == null) { String message = "Could not get column information from the database, aborting."; if (messages != null) messages.add(message); Debug.logError(message, module); return; } timer.timerString("After Get All Column Info"); // -make sure all entities have a corresponding table // -list all tables that do not have a corresponding entity // -display message if number of table columns does not match number of entity fields // -list all columns that do not have a corresponding field // -make sure each corresponding column is of the correct type // -list all fields that do not have a corresponding column timer.timerString("Before Individual Table/Column Check"); List<ModelEntity> modelEntityList = new ArrayList<ModelEntity>(modelEntities.values()); // sort using compareTo method on ModelEntity Collections.sort(modelEntityList); int curEnt = 0; int totalEnt = modelEntityList.size(); List<ModelEntity> entitiesAdded = new LinkedList<ModelEntity>(); String schemaName; try { schemaName = getSchemaName(messages); } catch (SQLException e) { String message = "Could not get schema name the database, aborting."; if (messages != null) messages.add(message); Debug.logError(message, module); return; } List<Future<CreateTableCallable>> tableFutures = new LinkedList<Future<CreateTableCallable>>(); for (ModelEntity entity: modelEntityList) { curEnt++; // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { String entMessage = "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " View Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, module); if (messages != null) messages.add(entMessage); continue; // if never-check is set then don't check it either } else if (entity.getNeverCheck()) { String entMessage = "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, module); if (messages != null) messages.add(entMessage); continue; } String plainTableName = entity.getPlainTableName(); String tableName; if (UtilValidate.isNotEmpty(schemaName)) { tableName = schemaName + "." + plainTableName; } else { tableName = plainTableName; } String entMessage = "(" + timer.timeSinceLast() + "ms) Checking #" + curEnt + "/" + totalEnt + " Entity " + entity.getEntityName() + " with table " + tableName; Debug.logVerbose(entMessage, module); if (messages != null) messages.add(entMessage); // -make sure all entities have a corresponding table if (tableNames.contains(tableName)) { tableNames.remove(tableName); if (colInfo != null) { Map<String, ModelField> fieldColNames = new HashMap<String, ModelField>(); Iterator<ModelField> fieldIter = entity.getFieldsIterator(); while (fieldIter.hasNext()) { ModelField field = fieldIter.next(); fieldColNames.put(field.getColName(), field); } Map<String, ColumnCheckInfo> colMap = colInfo.get(tableName); if (colMap != null) { for (ColumnCheckInfo ccInfo: colMap.values()) { // -list all columns that do not have a corresponding field if (fieldColNames.containsKey(ccInfo.columnName)) { ModelField field = null; field = fieldColNames.remove(ccInfo.columnName); ModelFieldType modelFieldType = modelFieldTypeReader.getModelFieldType(field.getType()); if (modelFieldType != null) { // make sure each corresponding column is of the correct type String fullTypeStr = modelFieldType.getSqlType(); String typeName; int columnSize = -1; int decimalDigits = -1; int openParen = fullTypeStr.indexOf('('); int closeParen = fullTypeStr.indexOf(')'); int comma = fullTypeStr.indexOf(','); if (openParen > 0 && closeParen > 0 && closeParen > openParen) { typeName = fullTypeStr.substring(0, openParen); if (comma > 0 && comma > openParen && comma < closeParen) { String csStr = fullTypeStr.substring(openParen + 1, comma); try { columnSize = Integer.parseInt(csStr); } catch (NumberFormatException e) { Debug.logError(e, module); } String ddStr = fullTypeStr.substring(comma + 1, closeParen); try { decimalDigits = Integer.parseInt(ddStr); } catch (NumberFormatException e) { Debug.logError(e, module); } } else { String csStr = fullTypeStr.substring(openParen + 1, closeParen); try { columnSize = Integer.parseInt(csStr); } catch (NumberFormatException e) { Debug.logError(e, module); } } } else { typeName = fullTypeStr; } // override the default typeName with the sqlTypeAlias if it is specified if (UtilValidate.isNotEmpty(modelFieldType.getSqlTypeAlias())) { typeName = modelFieldType.getSqlTypeAlias(); } // NOTE: this may need a toUpperCase in some cases, keep an eye on it, okay just compare with ignore case if (!ccInfo.typeName.equalsIgnoreCase(typeName)) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] is of type [" + ccInfo.typeName + "] in the database, but is defined as type [" + typeName + "] in the entity definition."; Debug.logError(message, module); if (messages != null) messages.add(message); } if (columnSize != -1 && ccInfo.columnSize != -1 && columnSize != ccInfo.columnSize && (columnSize * 3) != ccInfo.columnSize) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] has a column size of [" + ccInfo.columnSize + "] in the database, but is defined to have a column size of [" + columnSize + "] in the entity definition."; Debug.logWarning(message, module); if (messages != null) messages.add(message); if (columnSize > ccInfo.columnSize && colWrongSize != null) { // add item to list of wrong sized columns; only if the entity is larger colWrongSize.add(entity.getEntityName() + "." + field.getName()); } } if (decimalDigits != -1 && decimalDigits != ccInfo.decimalDigits) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] has a decimalDigits of [" + ccInfo.decimalDigits + "] in the database, but is defined to have a decimalDigits of [" + decimalDigits + "] in the entity definition."; Debug.logWarning(message, module); if (messages != null) messages.add(message); } // do primary key matching check if (checkPks && ccInfo.isPk && !field.getIsPk()) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] IS a primary key in the database, but IS NOT a primary key in the entity definition. The primary key for this table needs to be re-created or modified so that this column is NOT part of the primary key."; Debug.logError(message, module); if (messages != null) messages.add(message); } if (checkPks && !ccInfo.isPk && field.getIsPk()) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] IS NOT a primary key in the database, but IS a primary key in the entity definition. The primary key for this table needs to be re-created or modified to add this column to the primary key. Note that data may need to be added first as a primary key column cannot have an null values."; Debug.logError(message, module); if (messages != null) messages.add(message); } } else { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] has a field type name of [" + field.getType() + "] which is not found in the field type definitions"; Debug.logError(message, module); if (messages != null) messages.add(message); } } else { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] exists in the database but has no corresponding field" + ((checkPks && ccInfo.isPk) ? " (and it is a PRIMARY KEY COLUMN)" : ""); Debug.logWarning(message, module); if (messages != null) messages.add(message); } } // -display message if number of table columns does not match number of entity fields if (colMap.size() != entity.getFieldsSize()) { String message = "Entity [" + entity.getEntityName() + "] has " + entity.getFieldsSize() + " fields but table [" + tableName + "] has " + colMap.size() + " columns."; Debug.logWarning(message, module); if (messages != null) messages.add(message); } } // -list all fields that do not have a corresponding column for (ModelField field : fieldColNames.values()) { String message = "Field [" + field.getName() + "] of entity [" + entity.getEntityName() + "] is missing its corresponding column [" + field.getColName() + "]" + (field.getIsPk() ? " (and it is a PRIMARY KEY FIELD)" : ""); Debug.logWarning(message, module); if (messages != null) messages.add(message); if (addMissing) { // add the column String errMsg = addColumn(entity, field); if (UtilValidate.isNotEmpty(errMsg)) { message = "Could not add column [" + field.getColName() + "] to table [" + tableName + "]: " + errMsg; Debug.logError(message, module); if (messages != null) messages.add(message); } else { message = "Added column [" + field.getColName() + "] to table [" + tableName + "]" + (field.getIsPk() ? " (NOTE: this is a PRIMARY KEY FIELD, but the primary key was not updated automatically (not considered a safe operation), be sure to fill in any needed data and re-create the primary key)" : ""); Debug.logImportant(message, module); if (messages != null) messages.add(message); } } } } } else { String message = "Entity [" + entity.getEntityName() + "] has no table in the database"; Debug.logWarning(message, module); if (messages != null) messages.add(message); if (addMissing) { // create the table tableFutures.add(executor.submit(new CreateTableCallable(entity, modelEntities, tableName))); } } } for (CreateTableCallable tableCallable: ExecutionPool.getAllFutures(tableFutures)) { tableCallable.updateData(messages, entitiesAdded); } timer.timerString("After Individual Table/Column Check"); // -list all tables that do not have a corresponding entity for (String tableName: tableNames) { String message = "Table named [" + tableName + "] exists in the database but has no corresponding entity"; Debug.logWarning(message, module); if (messages != null) messages.add(message); } // for each newly added table, add fk indices if (datasourceInfo.getUseForeignKeyIndices()) { int totalFkIndices = 0; List<Future<AbstractCountingCallable>> fkIndicesFutures = new LinkedList<Future<AbstractCountingCallable>>(); for (ModelEntity curEntity: entitiesAdded) { if (curEntity.getRelationsOneSize() > 0) { fkIndicesFutures.add(executor.submit(new AbstractCountingCallable(curEntity, modelEntities) { public AbstractCountingCallable call() throws Exception { count = createForeignKeyIndices(entity, datasourceInfo.getConstraintNameClipLength(), messages); return this; } })); } } for (AbstractCountingCallable fkIndicesCallable: ExecutionPool.getAllFutures(fkIndicesFutures)) { totalFkIndices += fkIndicesCallable.updateData(messages); } if (totalFkIndices > 0) Debug.logImportant("==== TOTAL Foreign Key Indices Created: " + totalFkIndices, module); } // for each newly added table, add fks if (datasourceInfo.getUseForeignKeys()) { int totalFks = 0; for (ModelEntity curEntity: entitiesAdded) { totalFks += this.createForeignKeys(curEntity, modelEntities, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred(), messages); } if (totalFks > 0) Debug.logImportant("==== TOTAL Foreign Keys Created: " + totalFks, module); } // for each newly added table, add declared indexes if (datasourceInfo.getUseIndices()) { int totalDis = 0; List<Future<AbstractCountingCallable>> disFutures = new LinkedList<Future<AbstractCountingCallable>>(); for (ModelEntity curEntity: entitiesAdded) { if (curEntity.getIndexesSize() > 0) { disFutures.add(executor.submit(new AbstractCountingCallable(curEntity, modelEntities) { public AbstractCountingCallable call() throws Exception { count = createDeclaredIndices(entity, messages); return this; } })); } } for (AbstractCountingCallable disCallable: ExecutionPool.getAllFutures(disFutures)) { totalDis += disCallable.updateData(messages); } if (totalDis > 0) Debug.logImportant("==== TOTAL Declared Indices Created: " + totalDis, module); } // make sure each one-relation has an FK if (checkFks) { //if (!justColumns && datasourceInfo.getUseForeignKeys() && datasourceInfo.checkForeignKeysOnStart) { // NOTE: This ISN'T working for Postgres or MySQL, who knows about others, may be from JDBC driver bugs... int numFksCreated = 0; // TODO: check each key-map to make sure it exists in the FK, if any differences warn and then remove FK and recreate it // get ALL column info, put into hashmap by table name Map<String, Map<String, ReferenceCheckInfo>> refTableInfoMap = this.getReferenceInfo(fkTableNames, messages); // Debug.logVerbose("Ref Info Map: " + refTableInfoMap, module); if (refTableInfoMap == null) { // uh oh, something happened while getting info... if (Debug.verboseOn()) Debug.logVerbose("Ref Table Info Map is null", module); } else { for (ModelEntity entity: modelEntityList) { String entityName = entity.getEntityName(); // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { String entMessage = "NOT Checking View Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, module); if (messages != null) { messages.add(entMessage); } continue; } // get existing FK map for this table Map<String, ReferenceCheckInfo> rcInfoMap = refTableInfoMap.get(entity.getTableName(datasourceInfo)); // Debug.logVerbose("Got ref info for table " + entity.getTableName(datasourceInfo) + ": " + rcInfoMap, module); // go through each relation to see if an FK already exists Iterator<ModelRelation> relations = entity.getRelationsIterator(); boolean createdConstraints = false; while (relations.hasNext()) { ModelRelation modelRelation = relations.next(); if (!"one".equals(modelRelation.getType())) { continue; } ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { Debug.logError("No such relation: " + entity.getEntityName() + " -> " + modelRelation.getRelEntityName(), module); continue; } String relConstraintName = makeFkConstraintName(modelRelation, datasourceInfo.getConstraintNameClipLength()); ReferenceCheckInfo rcInfo = null; if (rcInfoMap != null) { rcInfo = rcInfoMap.get(relConstraintName); } if (rcInfo != null) { rcInfoMap.remove(relConstraintName); } else { // if not, create one String noFkMessage = "No Foreign Key Constraint [" + relConstraintName + "] found for entity [" + entityName + "]"; if (messages != null) messages.add(noFkMessage); if (Debug.infoOn()) Debug.logInfo(noFkMessage, module); if (addMissing) { String errMsg = createForeignKey(entity, modelRelation, relModelEntity, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred()); if (UtilValidate.isNotEmpty(errMsg)) { String message = "Could not create foreign key " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg; Debug.logError(message, module); if (messages != null) messages.add(message); } else { String message = "Created foreign key " + relConstraintName + " for entity [" + entity.getEntityName() + "]"; Debug.logVerbose(message, module); if (messages != null) messages.add(message); createdConstraints = true; numFksCreated++; } } } } if (createdConstraints) { String message = "Created foreign key(s) for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } // show foreign key references that exist but are unknown if (rcInfoMap != null) { for (String rcKeyLeft: rcInfoMap.keySet()) { String message = "Unknown Foreign Key Constraint " + rcKeyLeft + " found in table " + entity.getTableName(datasourceInfo); Debug.logImportant(message, module); if (messages != null) messages.add(message); } } } } if (Debug.infoOn()) Debug.logInfo("Created " + numFksCreated + " fk refs", module); } // make sure each one-relation has an index if (checkFkIdx || datasourceInfo.getCheckIndicesOnStart()) { //if (!justColumns && datasourceInfo.getUseForeignKeyIndices() && datasourceInfo.checkFkIndicesOnStart) { int numIndicesCreated = 0; // TODO: check each key-map to make sure it exists in the index, if any differences warn and then remove the index and recreate it // get ALL column info, put into hashmap by table name boolean needsUpperCase[] = new boolean[1]; Map<String, Set<String>> tableIndexListMap = this.getIndexInfo(indexTableNames, messages, needsUpperCase); // Debug.logVerbose("Ref Info Map: " + refTableInfoMap, module); if (tableIndexListMap == null) { // uh oh, something happened while getting info... if (Debug.verboseOn()) Debug.logVerbose("Ref Table Info Map is null", module); } else { for (ModelEntity entity: modelEntityList) { String entityName = entity.getEntityName(); // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { String entMessage = "NOT Checking View Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, module); if (messages != null) messages.add(entMessage); continue; } // get existing index list for this table Set<String> tableIndexList = tableIndexListMap.get(entity.getTableName(datasourceInfo)); // Debug.logVerbose("Got ind info for table " + entity.getTableName(datasourceInfo) + ": " + tableIndexList, module); if (tableIndexList == null) { // evidently no indexes in the database for this table, do the create all if (checkFkIdx) { this.createForeignKeyIndices(entity, datasourceInfo.getConstraintNameClipLength(), messages); } if (datasourceInfo.getCheckIndicesOnStart()) { this.createDeclaredIndices(entity, messages); } continue; } // go through each relation to see if an FK already exists boolean createdConstraints = false; Iterator<ModelRelation> relations = entity.getRelationsIterator(); while (relations.hasNext()) { ModelRelation modelRelation = relations.next(); if (!"one".equals(modelRelation.getType())) { continue; } String relConstraintName = makeFkConstraintName(modelRelation, datasourceInfo.getConstraintNameClipLength()); if (tableIndexList.contains(relConstraintName)) { tableIndexList.remove(relConstraintName); } else { if (checkFkIdx) { // if not, create one String noIdxMessage = "No Index [" + relConstraintName + "] found for entity [" + entityName + "]"; if (messages != null) messages.add(noIdxMessage); if (Debug.infoOn()) Debug.logInfo(noIdxMessage, module); if (addMissing) { String errMsg = createForeignKeyIndex(entity, modelRelation, datasourceInfo.getConstraintNameClipLength()); if (UtilValidate.isNotEmpty(errMsg)) { String message = "Could not create foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg; Debug.logError(message, module); if (messages != null) messages.add(message); } else { String message = "Created foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]"; Debug.logVerbose(message, module); if (messages != null) messages.add(message); createdConstraints = true; numIndicesCreated++; } } } } } if (createdConstraints) { String message = "Created foreign key index/indices for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } // go through each indice to see if an indice already exists boolean createdIndexes = false; Iterator<ModelIndex> indexes = entity.getIndexesIterator(); while (indexes.hasNext()) { ModelIndex modelIndex = indexes.next(); String relIndexName = makeIndexName(modelIndex, datasourceInfo.getConstraintNameClipLength()); String checkIndexName = needsUpperCase[0] ? relIndexName.toUpperCase() : relIndexName; if (tableIndexList.contains(checkIndexName)) { tableIndexList.remove(checkIndexName); } else { if (datasourceInfo.getCheckIndicesOnStart()) { // if not, create one String noIdxMessage = "No Index [" + relIndexName + "] found for entity [" + entityName + "]"; if (messages != null) messages.add(noIdxMessage); if (Debug.infoOn()) Debug.logInfo(noIdxMessage, module); if (addMissing) { String errMsg = createDeclaredIndex(entity, modelIndex); if (UtilValidate.isNotEmpty(errMsg)) { String message = "Could not create index " + relIndexName + " for entity [" + entity.getEntityName() + "]: " + errMsg; Debug.logError(message, module); if (messages != null) messages.add(message); } else { String message = "Created index " + relIndexName + " for entity [" + entity.getEntityName() + "]"; Debug.logVerbose(message, module); if (messages != null) messages.add(message); createdIndexes = true; numIndicesCreated++; } } } } } if (createdIndexes) { String message = "Created declared index/indices for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } // show index key references that exist but are unknown if (tableIndexList != null) { for (String indexLeft: tableIndexList) { String message = "Unknown Index " + indexLeft + " found in table " + entity.getTableName(datasourceInfo); Debug.logImportant(message, module); if (messages != null) messages.add(message); } } } } if (numIndicesCreated > 0 && Debug.infoOn()) Debug.logInfo("Created " + numIndicesCreated + " indices", module); } executor.shutdown(); timer.timerString("Finished Checking Entity Database"); } /** Creates a list of ModelEntity objects based on meta data from the database */ public List<ModelEntity> induceModelFromDb(Collection<String> messages) { ExecutorService executor = Executors.newFixedThreadPool(datasourceInfo.getMaxWorkerPoolSize()); // get ALL tables from this database TreeSet<String> tableNames = this.getTableNames(messages); // get ALL column info, put into hashmap by table name Map<String, Map<String, ColumnCheckInfo>> colInfo = getColumnInfo(tableNames, true, messages, executor); // go through each table and make a ModelEntity object, add to list // for each entity make corresponding ModelField objects // then print out XML for the entities/fields List<ModelEntity> newEntList = new LinkedList<ModelEntity>(); boolean isCaseSensitive = getIsCaseSensitive(messages); // iterate over the table names is alphabetical order for (String tableName: new TreeSet<String>(colInfo.keySet())) { Map<String, ColumnCheckInfo> colMap = colInfo.get(tableName); ModelEntity newEntity = new ModelEntity(tableName, colMap, modelFieldTypeReader, isCaseSensitive); newEntList.add(newEntity); } executor.shutdown(); return newEntList; } private String getSchemaName(Collection<String> messages) throws SQLException { String schemaName; try (Connection connection = getConnectionLogged(messages)) { DatabaseMetaData dbData = this.getDatabaseMetaData(connection, messages); schemaName = getSchemaName(dbData); return schemaName; } } private boolean getIsCaseSensitive(Collection<String> messages) { boolean isCaseSensitive = false; try (Connection connection = getConnectionLogged(messages)) { DatabaseMetaData dbData = this.getDatabaseMetaData(connection, messages); if (dbData != null) { isCaseSensitive = dbData.supportsMixedCaseIdentifiers(); } } catch (SQLException e) { Debug.logError(e, "Error getting db meta data about case sensitive", module); } return isCaseSensitive; } public DatabaseMetaData getDatabaseMetaData(Connection connection, Collection<String> messages) { DatabaseMetaData dbData = null; try { dbData = connection.getMetaData(); } catch (SQLException e) { String message = "Unable to get database meta data... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) { messages.add(message); } return null; } if (dbData == null) { Debug.logWarning("Unable to get database meta data; method returned null", module); } return dbData; } private static final List<Detection> detections = new ArrayList<Detection>(); private static final String goodFormatStr; private static final String badFormatStr; private static class Detection { protected final String name; protected final boolean required; protected final Method method; protected final Object[] params; protected Detection(String name, boolean required, String methodName, Object... params) throws NoSuchMethodException { this.name = name; this.required = required; Class<?>[] paramTypes = new Class<?>[params.length]; for (int i = 0; i < params.length; i++) { Class<?> paramType = params[i].getClass(); if (paramType == Integer.class) { paramType = Integer.TYPE; } paramTypes[i] = paramType; } method = DatabaseMetaData.class.getMethod(methodName, paramTypes); this.params = params; } } static { try { detections.add(new Detection("supports transactions", true, "supportsTransactions")); detections.add(new Detection("isolation None", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_NONE)); detections.add(new Detection("isolation ReadCommitted", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_READ_COMMITTED)); detections.add(new Detection("isolation ReadUncommitted", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_READ_UNCOMMITTED)); detections.add(new Detection("isolation RepeatableRead", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_REPEATABLE_READ)); detections.add(new Detection("isolation Serializable", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_SERIALIZABLE)); detections.add(new Detection("forward only type", false, "supportsResultSetType", ResultSet.TYPE_FORWARD_ONLY)); detections.add(new Detection("scroll sensitive type", false, "supportsResultSetType", ResultSet.TYPE_SCROLL_SENSITIVE)); detections.add(new Detection("scroll insensitive type", false, "supportsResultSetType", ResultSet.TYPE_SCROLL_INSENSITIVE)); detections.add(new Detection("is case sensitive", false, "supportsMixedCaseIdentifiers")); detections.add(new Detection("stores LowerCase", false, "storesLowerCaseIdentifiers")); detections.add(new Detection("stores MixedCase", false, "storesMixedCaseIdentifiers")); detections.add(new Detection("stores UpperCase", false, "storesUpperCaseIdentifiers")); detections.add(new Detection("max table name length", false, "getMaxTableNameLength")); detections.add(new Detection("max column name length", false, "getMaxColumnNameLength")); detections.add(new Detection("concurrent connections", false, "getMaxConnections")); detections.add(new Detection("concurrent statements", false, "getMaxStatements")); detections.add(new Detection("ANSI SQL92 Entry", false, "supportsANSI92EntryLevelSQL")); detections.add(new Detection("ANSI SQL92 Intermediate", false, "supportsANSI92IntermediateSQL")); detections.add(new Detection("ANSI SQL92 Full", false, "supportsANSI92FullSQL")); detections.add(new Detection("ODBC SQL Grammar Core", false, "supportsCoreSQLGrammar")); detections.add(new Detection("ODBC SQL Grammar Extended", false, "supportsExtendedSQLGrammar")); detections.add(new Detection("ODBC SQL Grammar Minimum", false, "supportsMinimumSQLGrammar")); detections.add(new Detection("outer joins", true, "supportsOuterJoins")); detections.add(new Detection("limited outer joins", false, "supportsLimitedOuterJoins")); detections.add(new Detection("full outer joins", false, "supportsFullOuterJoins")); detections.add(new Detection("group by", true, "supportsGroupBy")); detections.add(new Detection("group by not in select", false, "supportsGroupByUnrelated")); detections.add(new Detection("column aliasing", false, "supportsColumnAliasing")); detections.add(new Detection("order by not in select", false, "supportsOrderByUnrelated")); detections.add(new Detection("alter table add column", true, "supportsAlterTableWithAddColumn")); detections.add(new Detection("non-nullable column", true, "supportsNonNullableColumns")); //detections.add(new Detection("", false, "", )); } catch (NoSuchMethodException e) { throw (InternalError) new InternalError(e.getMessage()).initCause(e); } int maxWidth = 0; for (Detection detection: detections) { if (detection.name.length() > maxWidth) { maxWidth = detection.name.length(); } } goodFormatStr = "- %-" + maxWidth + "s [%s]%s"; badFormatStr = "- %-" + maxWidth + "s [ DETECTION FAILED ]%s"; } public void printDbMiscData(DatabaseMetaData dbData, Connection con) { if (dbData == null) { return; } if (Debug.infoOn()) { // Database Info try { Debug.logInfo("Database Product Name is " + dbData.getDatabaseProductName(), module); Debug.logInfo("Database Product Version is " + dbData.getDatabaseProductVersion(), module); } catch (SQLException e) { Debug.logWarning("Unable to get Database name & version information", module); } // JDBC Driver Info try { Debug.logInfo("Database Driver Name is " + dbData.getDriverName(), module); Debug.logInfo("Database Driver Version is " + dbData.getDriverVersion(), module); Debug.logInfo("Database Driver JDBC Version is " + dbData.getJDBCMajorVersion() + "." + dbData.getJDBCMinorVersion(), module); } catch (SQLException e) { Debug.logWarning("Unable to get Driver name & version information", module); } catch (AbstractMethodError ame) { Debug.logWarning("Unable to get Driver JDBC Version", module); } // Db/Driver support settings Debug.logInfo("Database Setting/Support Information (those with a * should be true):", module); for (Detection detection: detections) { String requiredFlag = detection.required ? "*" : ""; try { Object result = detection.method.invoke(dbData, detection.params); Debug.logInfo(String.format(goodFormatStr, detection.name, result, requiredFlag), module); } catch (Exception e) { Debug.logVerbose(e, module); Debug.logWarning(String.format(badFormatStr, detection.name, requiredFlag), module); } } try { Debug.logInfo("- default fetchsize [" + con.createStatement().getFetchSize() + "]", module); } catch (Exception e) { Debug.logVerbose(e, module); Debug.logWarning("- default fetchsize [ DETECTION FAILED ]", module); } try { //this doesn't work in HSQLDB, other databases? //crashed (vm-death) with MS SQL Server 2000, runs properly with MS SQL Server 2005 //Debug.logInfo("- named parameters [" + dbData.supportsNamedParameters() + "]", module); Debug.logInfo("- named parameters [ SKIPPED ]", module); } catch (Exception e) { Debug.logVerbose(e, module); Debug.logWarning("- named parameters JDBC-3 [ DETECTION FAILED ]", module); } } } public TreeSet<String> getTableNames(Collection<String> messages) { Connection connection = getConnectionLogged(messages); if (connection == null) { String message = "Unable to establish a connection with the database, no additional information available."; Debug.logError(message, module); if (messages != null) messages.add(message); return null; } DatabaseMetaData dbData = this.getDatabaseMetaData(connection, messages); if (dbData == null) { return null; } printDbMiscData(dbData, connection); if (Debug.infoOn()) Debug.logInfo("Getting Table Info From Database", module); // get ALL tables from this database TreeSet<String> tableNames = new TreeSet<String>(); ResultSet tableSet = null; String lookupSchemaName = null; try { String[] types = {"TABLE", "BASE TABLE", "VIEW", "ALIAS", "SYNONYM"}; lookupSchemaName = getSchemaName(dbData); tableSet = dbData.getTables(null, lookupSchemaName, null, types); if (tableSet == null) { Debug.logWarning("getTables returned null set", module); } } catch (SQLException e) { String message = "Unable to get list of table information, let's try the create anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); try { connection.close(); } catch (SQLException e2) { String message2 = "Unable to close database connection, continuing anyway... Error was:" + e2.toString(); Debug.logError(message2, module); if (messages != null) messages.add(message2); } // we are returning an empty set here because databases like SapDB throw an exception when there are no tables in the database return tableNames; } try { boolean needsUpperCase = false; try { needsUpperCase = dbData.storesLowerCaseIdentifiers() || dbData.storesMixedCaseIdentifiers(); } catch (SQLException e) { String message = "Error getting identifier case information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } while (tableSet.next()) { try { String tableName = tableSet.getString("TABLE_NAME"); // for those databases which do not return the schema name with the table name (pgsql 7.3) boolean appendSchemaName = false; if (tableName != null && lookupSchemaName != null && !tableName.startsWith(lookupSchemaName + "\\.")) { appendSchemaName = true; } if (needsUpperCase && tableName != null) { tableName = tableName.toUpperCase(); } if (appendSchemaName) { tableName = lookupSchemaName + "." + tableName; } // NOTE: this may need a toUpperCase in some cases, keep an eye on it, okay for now just do a compare with equalsIgnoreCase String tableType = tableSet.getString("TABLE_TYPE"); // only allow certain table types if (tableType != null && !"TABLE".equalsIgnoreCase(tableType) && !"VIEW".equalsIgnoreCase(tableType) && !"ALIAS".equalsIgnoreCase(tableType) && !"SYNONYM".equalsIgnoreCase(tableType) && !"BASE TABLE".equalsIgnoreCase(tableType)) { continue; } // String remarks = tableSet.getString("REMARKS"); tableNames.add(tableName); // if (Debug.infoOn()) Debug.logInfo("Found table named [" + tableName + "] of type [" + tableType + "] with remarks: " + remarks, module); } catch (SQLException e) { String message = "Error getting table information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } } catch (SQLException e) { String message = "Error getting next table information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } finally { try { tableSet.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for table list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } try { connection.close(); } catch (SQLException e) { String message = "Unable to close database connection, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } return tableNames; } private AbstractCountingCallable createPrimaryKeyFetcher(final DatabaseMetaData dbData, final String lookupSchemaName, final boolean needsUpperCase, final Map<String, Map<String, ColumnCheckInfo>> colInfo, final Collection<String> messages, final String curTable) { return new AbstractCountingCallable(null, null) { public AbstractCountingCallable call() throws Exception { if (Debug.verboseOn()) Debug.logVerbose("Fetching primary keys for " + curTable, module); ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, curTable); count = checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); return this; } }; } private Map<String, Map<String, ColumnCheckInfo>> getColumnInfo(Set<String> tableNames, boolean getPks, Collection<String> messages, ExecutorService executor) { // if there are no tableNames, don't even try to get the columns if (tableNames.size() == 0) { return new HashMap<String, Map<String, ColumnCheckInfo>>(); } Connection connection = null; try { connection = getConnectionLogged(messages); if (connection == null) { return null; } DatabaseMetaData dbData = null; try { dbData = connection.getMetaData(); } catch (SQLException e) { String message = "Unable to get database meta data... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); try { connection.close(); } catch (SQLException e2) { String message2 = "Unable to close database connection, continuing anyway... Error was:" + e2.toString(); Debug.logError(message2, module); if (messages != null) messages.add(message2); } return null; } if (Debug.infoOn()) Debug.logInfo("Getting Column Info From Database", module); Map<String, Map<String, ColumnCheckInfo>> colInfo = new HashMap<String, Map<String, ColumnCheckInfo>>(); try { String lookupSchemaName = getSchemaName(dbData); boolean needsUpperCase = false; try { needsUpperCase = dbData.storesLowerCaseIdentifiers() || dbData.storesMixedCaseIdentifiers(); } catch (SQLException e) { String message = "Error getting identifier case information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } boolean foundCols = false; ResultSet rsCols = dbData.getColumns(null, lookupSchemaName, null, null); if (!rsCols.next()) { try { rsCols.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for column list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } rsCols = dbData.getColumns(null, lookupSchemaName, "%", "%"); if (!rsCols.next()) { // TODO: now what to do? I guess try one table name at a time... } else { foundCols = true; } } else { foundCols = true; } if (foundCols) { do { try { ColumnCheckInfo ccInfo = new ColumnCheckInfo(); ccInfo.tableName = ColumnCheckInfo.fixupTableName(rsCols.getString("TABLE_NAME"), lookupSchemaName, needsUpperCase); // ignore the column info if the table name is not in the list we are concerned with if (!tableNames.contains(ccInfo.tableName)) { continue; } ccInfo.columnName = rsCols.getString("COLUMN_NAME"); if (needsUpperCase && ccInfo.columnName != null) { ccInfo.columnName = ccInfo.columnName.toUpperCase(); } // NOTE: this may need a toUpperCase in some cases, keep an eye on it ccInfo.typeName = rsCols.getString("TYPE_NAME"); ccInfo.columnSize = rsCols.getInt("COLUMN_SIZE"); ccInfo.decimalDigits = rsCols.getInt("DECIMAL_DIGITS"); // NOTE: this may need a toUpperCase in some cases, keep an eye on it ccInfo.isNullable = rsCols.getString("IS_NULLABLE"); Map<String, ColumnCheckInfo> tableColInfo = colInfo.get(ccInfo.tableName); if (tableColInfo == null) { tableColInfo = new HashMap<String, ColumnCheckInfo>(); colInfo.put(ccInfo.tableName, tableColInfo); } tableColInfo.put(ccInfo.columnName, ccInfo); } catch (SQLException e) { String message = "Error getting column info for column. Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } while (rsCols.next()); } try { rsCols.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for column list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } if (getPks) { int pkCount = 0; // first try getting all at once for databases that support that and can generally perform WAY better, if that fails get one at a time so it will at least work try (ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, null)) { pkCount += checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); } catch (Exception e1) { Debug.logInfo("Error getting primary key info from database with null tableName, will try other means: " + e1.toString(), module); } if (pkCount == 0) { try (ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, "%")) { pkCount += checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); } catch (Exception e1) { Debug.logInfo("Error getting primary key info from database with % tableName, will try other means: " + e1.toString(), module); } } if (pkCount == 0) { Debug.logInfo("Searching in " + tableNames.size() + " tables for primary key fields ...", module); List<Future<AbstractCountingCallable>> pkFetcherFutures = new LinkedList<Future<AbstractCountingCallable>>(); for (String curTable: tableNames) { curTable = curTable.substring(curTable.indexOf('.') + 1); //cut off schema name pkFetcherFutures.add(executor.submit(createPrimaryKeyFetcher(dbData, lookupSchemaName, needsUpperCase, colInfo, messages, curTable))); } for (AbstractCountingCallable pkFetcherCallable: ExecutionPool.getAllFutures(pkFetcherFutures)) { pkCount += pkFetcherCallable.updateData(messages); } } Debug.logInfo("Reviewed " + pkCount + " primary key fields from database.", module); } } catch (SQLException e) { String message = "Error getting column meta data for Error was: [" + e.toString() + "]. Not checking columns."; Debug.logError(e, message, module); if (messages != null) messages.add(message); // we are returning an empty set in this case because databases like SapDB throw an exception when there are no tables in the database // colInfo = null; } return colInfo; } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { String message = "Unable to close database connection, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } } } public int checkPrimaryKeyInfo(ResultSet rsPks, String lookupSchemaName, boolean needsUpperCase, Map<String, Map<String, ColumnCheckInfo>> colInfo, Collection<String> messages) throws SQLException { int pkCount = 0; while (rsPks.next()) { pkCount++; try { String tableName = ColumnCheckInfo.fixupTableName(rsPks.getString("TABLE_NAME"), lookupSchemaName, needsUpperCase); String columnName = rsPks.getString("COLUMN_NAME"); if (needsUpperCase && columnName != null) { columnName = columnName.toUpperCase(); } Map<String, ColumnCheckInfo> tableColInfo = colInfo.get(tableName); if (tableColInfo == null) { // not looking for info on this table continue; } ColumnCheckInfo ccInfo = tableColInfo.get(columnName); if (ccInfo == null) { // this isn't good, what to do? Debug.logWarning("Got primary key information for a column that we didn't get column information for: tableName=[" + tableName + "], columnName=[" + columnName + "]", module); continue; } // KEY_SEQ short => sequence number within primary key // PK_NAME String => primary key name (may be null) ccInfo.isPk = true; ccInfo.pkSeq = rsPks.getShort("KEY_SEQ"); ccInfo.pkName = rsPks.getString("PK_NAME"); } catch (SQLException e) { String message = "Error getting primary key info for column. Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } return pkCount; } public Map<String, Map<String, ReferenceCheckInfo>> getReferenceInfo(Set<String> tableNames, Collection<String> messages) { Connection connection = getConnectionLogged(messages); if (connection == null) { return null; } DatabaseMetaData dbData = null; try { dbData = connection.getMetaData(); } catch (SQLException e) { String message = "Unable to get database meta data... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); try { connection.close(); } catch (SQLException e2) { String message2 = "Unable to close database connection, continuing anyway... Error was:" + e2.toString(); Debug.logError(message2, module); if (messages != null) messages.add(message2); } return null; } /* try { if (Debug.infoOn()) Debug.logInfo("Database Product Name is " + dbData.getDatabaseProductName(), module); if (Debug.infoOn()) Debug.logInfo("Database Product Version is " + dbData.getDatabaseProductVersion(), module); } catch (SQLException e) { Debug.logWarning("Unable to get Database name & version information", module); } try { if (Debug.infoOn()) Debug.logInfo("Database Driver Name is " + dbData.getDriverName(), module); if (Debug.infoOn()) Debug.logInfo("Database Driver Version is " + dbData.getDriverVersion(), module); } catch (SQLException e) { Debug.logWarning("Unable to get Driver name & version information", module); } */ if (Debug.infoOn()) Debug.logInfo("Getting Foreign Key (Reference) Info From Database", module); Map<String, Map<String, ReferenceCheckInfo>> refInfo = new HashMap<String, Map<String, ReferenceCheckInfo>>(); try { // ResultSet rsCols = dbData.getCrossReference(null, null, null, null, null, null); String lookupSchemaName = getSchemaName(dbData); boolean needsUpperCase = false; try { needsUpperCase = dbData.storesLowerCaseIdentifiers() || dbData.storesMixedCaseIdentifiers(); } catch (SQLException e) { String message = "Error getting identifier case information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } ResultSet rsCols = dbData.getImportedKeys(null, lookupSchemaName, null); int totalFkRefs = 0; // Iterator tableNamesIter = tableNames.iterator(); // while (tableNamesIter.hasNext()) { // String tableName = (String) tableNamesIter.next(); // ResultSet rsCols = dbData.getImportedKeys(null, null, tableName); // Debug.logVerbose("Getting imported keys for table " + tableName, module); while (rsCols.next()) { try { ReferenceCheckInfo rcInfo = new ReferenceCheckInfo(); rcInfo.pkTableName = rsCols.getString("PKTABLE_NAME"); if (needsUpperCase && rcInfo.pkTableName != null) { rcInfo.pkTableName = rcInfo.pkTableName.toUpperCase(); } rcInfo.pkColumnName = rsCols.getString("PKCOLUMN_NAME"); if (needsUpperCase && rcInfo.pkColumnName != null) { rcInfo.pkColumnName = rcInfo.pkColumnName.toUpperCase(); } rcInfo.fkTableName = rsCols.getString("FKTABLE_NAME"); if (needsUpperCase && rcInfo.fkTableName != null) { rcInfo.fkTableName = rcInfo.fkTableName.toUpperCase(); } // ignore the column info if the FK table name is not in the list we are concerned with if (!tableNames.contains(rcInfo.fkTableName)) { continue; } rcInfo.fkColumnName = rsCols.getString("FKCOLUMN_NAME"); if (needsUpperCase && rcInfo.fkColumnName != null) { rcInfo.fkColumnName = rcInfo.fkColumnName.toUpperCase(); } rcInfo.fkName = rsCols.getString("FK_NAME"); if (needsUpperCase && rcInfo.fkName != null) { rcInfo.fkName = rcInfo.fkName.toUpperCase(); } if (Debug.verboseOn()) Debug.logVerbose("Got: " + rcInfo.toString(), module); Map<String, ReferenceCheckInfo> tableRefInfo = refInfo.get(rcInfo.fkTableName); if (tableRefInfo == null) { tableRefInfo = new HashMap<String, ReferenceCheckInfo>(); refInfo.put(rcInfo.fkTableName, tableRefInfo); if (Debug.verboseOn()) Debug.logVerbose("Adding new Map for table: " + rcInfo.fkTableName, module); } if (!tableRefInfo.containsKey(rcInfo.fkName)) totalFkRefs++; tableRefInfo.put(rcInfo.fkName, rcInfo); } catch (SQLException e) { String message = "Error getting fk reference info for table. Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } // if (Debug.infoOn()) Debug.logInfo("There are " + totalFkRefs + " in the database", module); try { rsCols.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for fk reference list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } // } if (Debug.infoOn()) Debug.logInfo("There are " + totalFkRefs + " foreign key refs in the database", module); } catch (SQLException e) { String message = "Error getting fk reference meta data Error was:" + e.toString() + ". Not checking fk refs."; Debug.logError(message, module); if (messages != null) messages.add(message); refInfo = null; } finally { try { connection.close(); } catch (SQLException e) { String message = "Unable to close database connection, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } return refInfo; } public Map<String, Set<String>> getIndexInfo(Set<String> tableNames, Collection<String> messages, boolean[] needsUpperCase) { Connection connection = getConnectionLogged(messages); if (connection == null) { return null; } DatabaseMetaData dbData = null; try { dbData = connection.getMetaData(); } catch (SQLException e) { String message = "Unable to get database meta data... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); try { connection.close(); } catch (SQLException e2) { String message2 = "Unable to close database connection, continuing anyway... Error was:" + e2.toString(); Debug.logError(message2, module); if (messages != null) messages.add(message2); } return null; } needsUpperCase[0] = false; try { needsUpperCase[0] = dbData.storesLowerCaseIdentifiers() || dbData.storesMixedCaseIdentifiers(); } catch (SQLException e) { String message = "Error getting identifier case information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } if (Debug.infoOn()) Debug.logInfo("Getting Index Info From Database", module); Map<String, Set<String>> indexInfo = new HashMap<String, Set<String>>(); try { int totalIndices = 0; String lookupSchemaName = getSchemaName(dbData); for (String curTableName: tableNames) { if (lookupSchemaName != null) { curTableName = curTableName.substring(lookupSchemaName.length() + 1); } ResultSet rsCols = null; try { // false for unique, we don't really use unique indexes // true for approximate, don't really care if stats are up-to-date rsCols = dbData.getIndexInfo(null, lookupSchemaName, needsUpperCase[0] ? curTableName.toLowerCase() : curTableName, false, true); } catch (Exception e) { Debug.logWarning(e, "Error getting index info for table: " + curTableName + " using lookupSchemaName " + lookupSchemaName, module); } while (rsCols != null && rsCols.next()) { // NOTE: The code in this block may look funny, but it is designed so that the wrapping loop can be removed try { // skip all index info for statistics if (rsCols.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic) continue; // HACK: for now skip all "unique" indexes since our foreign key indices are not unique, but the primary key ones are // not correct, declared indices can also be unique // if (!rsCols.getBoolean("NON_UNIQUE")) continue; String tableName = rsCols.getString("TABLE_NAME"); if (needsUpperCase[0] && tableName != null) { tableName = tableName.toUpperCase(); } if (lookupSchemaName != null) { tableName = lookupSchemaName + '.' + tableName; } if (!tableNames.contains(tableName)) continue; String indexName = rsCols.getString("INDEX_NAME"); if (needsUpperCase[0] && indexName != null) { indexName = indexName.toUpperCase(); } if (indexName.startsWith("PK_") || indexName.startsWith("pk_")) continue; Set<String> tableIndexList = indexInfo.get(tableName); if (tableIndexList == null) { tableIndexList = new TreeSet<String>(); indexInfo.put(tableName, tableIndexList); if (Debug.verboseOn()) Debug.logVerbose("Adding new Map for table: " + tableName, module); } // Need the check here, because an index can contain multiple columns, // and this is represented by having multiple rows in rsCols. if (!tableIndexList.contains(indexName)) totalIndices++; tableIndexList.add(indexName); } catch (SQLException e) { String message = "Error getting fk reference info for table. Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } // if (Debug.infoOn()) Debug.logInfo("There are " + totalIndices + " indices in the database", module); if (rsCols != null) { try { rsCols.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for fk reference list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } } if (Debug.infoOn()) Debug.logInfo("There are " + totalIndices + " indices in the database", module); } catch (SQLException e) { String message = "Error getting fk reference meta data Error was:" + e.toString() + ". Not checking fk refs."; Debug.logError(message, module); if (messages != null) messages.add(message); indexInfo = null; } finally { try { connection.close(); } catch (SQLException e) { String message = "Unable to close database connection, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } return indexInfo; } private class CreateTableCallable implements Callable<CreateTableCallable> { private final ModelEntity entity; private final Map<String, ModelEntity> modelEntities; private final String tableName; private String message; private boolean success; protected CreateTableCallable(ModelEntity entity, Map<String, ModelEntity> modelEntities, String tableName) { this.entity = entity; this.modelEntities = modelEntities; this.tableName = tableName; } public CreateTableCallable call() throws Exception { String errMsg = createTable(entity, modelEntities, false); if (UtilValidate.isNotEmpty(errMsg)) { this.success = false; this.message = "Could not create table [" + tableName + "]: " + errMsg; Debug.logError(this.message, module); } else { this.success = true; this.message = "Created table [" + tableName + "]"; Debug.logImportant(this.message, module); } return this; } protected void updateData(Collection<String> messages, List<ModelEntity> entitiesAdded) { if (this.success) { entitiesAdded.add(entity); if (messages != null) { messages.add(this.message); } } else { if (messages != null) { messages.add(this.message); } } } } private abstract class AbstractCountingCallable implements Callable<AbstractCountingCallable> { protected final ModelEntity entity; protected final Map<String, ModelEntity> modelEntities; protected final List<String> messages = new LinkedList<String>(); protected int count; protected AbstractCountingCallable(ModelEntity entity, Map<String, ModelEntity> modelEntities) { this.entity = entity; this.modelEntities = modelEntities; } protected int updateData(Collection<String> messages) { // SCIPIO: there were 2 errors here; only 1 was fixed by ofbiz 16 //if (messages != null && UtilValidate.isNotEmpty(this.messages)) { // messages.addAll(messages); //} if (UtilValidate.isNotEmpty(messages)) { this.messages.addAll(messages); } return count; } } /* ====================================================================== */ /* ====================================================================== */ public String createTable(ModelEntity entity, Map<String, ModelEntity> modelEntities, boolean addFks) { if (entity == null) { return "ModelEntity was null and is required to create a table"; } if (entity instanceof ModelViewEntity) { return "ERROR: Cannot create table for a view entity"; } StringBuilder sqlBuf = new StringBuilder("CREATE TABLE "); sqlBuf.append(entity.getTableName(this.datasourceInfo)); sqlBuf.append(" ("); Iterator<ModelField> fieldIter = entity.getFieldsIterator(); while (fieldIter.hasNext()) { ModelField field = fieldIter.next(); ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table."; } sqlBuf.append(field.getColName()); sqlBuf.append(" "); sqlBuf.append(type.getSqlType()); if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) { // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlBuf.append(" CHARACTER SET "); sqlBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlBuf.append(" COLLATE "); sqlBuf.append(this.datasourceInfo.getCollate()); } } if (field.getIsNotNull() || field.getIsPk()) { if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) { sqlBuf.append(" CONSTRAINT NOT NULL, "); } else { sqlBuf.append(" NOT NULL, "); } } else { sqlBuf.append(", "); } } String pkName = makePkConstraintName(entity, this.datasourceInfo.getConstraintNameClipLength()); if (this.datasourceInfo.getUsePkConstraintNames()) { sqlBuf.append("CONSTRAINT "); sqlBuf.append(pkName); } sqlBuf.append(" PRIMARY KEY ("); entity.colNameString(entity.getPkFieldsUnmodifiable(), sqlBuf, ""); sqlBuf.append(")"); if (addFks) { // NOTE: This is kind of a bad idea anyway since ordering table creations is crazy, if not impossible // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { Debug.logError("Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(), module); continue; } if (relModelEntity instanceof ModelViewEntity) { Debug.logError("Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(), module); continue; } String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, this.datasourceInfo.getConstraintNameClipLength(), this.datasourceInfo.getFkStyle(), this.datasourceInfo.getUseFkInitiallyDeferred()); if (UtilValidate.isNotEmpty(fkConstraintClause)) { sqlBuf.append(", "); sqlBuf.append(fkConstraintClause); } else { continue; } } } } sqlBuf.append(")"); // if there is a tableType, add the TYPE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getTableType())) { // jaz:20101229 - This appears to be only used by mysql and now mysql has // deprecated (and in 5.5.x removed) the use of the TYPE keyword. This is // changed to ENGINE which is supported starting at 4.1 sqlBuf.append(" ENGINE "); //sqlBuf.append(" TYPE "); sqlBuf.append(this.datasourceInfo.getTableType()); } // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlBuf.append(" CHARACTER SET "); sqlBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlBuf.append(" COLLATE "); sqlBuf.append(this.datasourceInfo.getCollate()); } // if there is a rowFormat, add the ROW_FORMAT arg here (only intended for MariaDB and MySQL) if (UtilValidate.isNotEmpty(this.datasourceInfo.getRowFormat()) && !this.datasourceInfo.getRowFormat().equals("none")) { sqlBuf.append(" ROW_FORMAT "); sqlBuf.append(this.datasourceInfo.getRowFormat()); } if (Debug.verboseOn()) Debug.logVerbose("[createTable] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public void deleteTable(ModelEntity entity, List<String> messages) { if (entity == null) { String errMsg = "ModelEntity was null and is required to delete a table"; Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); return; } if (entity instanceof ModelViewEntity) { //String errMsg = "ERROR: Cannot delete table for a view entity"; //Debug.logError(errMsg, module); //if (messages != null) messages.add(errMsg); return; } String message = "Deleting table for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); StringBuilder sqlBuf = new StringBuilder("DROP TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); if (Debug.verboseOn()) Debug.logVerbose("[deleteTable] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnectionLogged(messages); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); } } public String addColumn(ModelEntity entity, ModelField field) { if (entity == null || field == null) return "ModelEntity or ModelField where null, cannot add column"; if (entity instanceof ModelViewEntity) { return "ERROR: Cannot add column for a view entity"; } ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not adding column."; } StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" ADD "); sqlBuf.append(field.getColName()); sqlBuf.append(" "); sqlBuf.append(type.getSqlType()); if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) { // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlBuf.append(" CHARACTER SET "); sqlBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlBuf.append(" COLLATE "); sqlBuf.append(this.datasourceInfo.getCollate()); } } String sql = sqlBuf.toString(); if (Debug.infoOn()) Debug.logInfo("[addColumn] sql=" + sql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql); } catch (SQLException e) { // if that failed try the alternate syntax real quick StringBuilder sql2Buf = new StringBuilder("ALTER TABLE "); sql2Buf.append(entity.getTableName(datasourceInfo)); sql2Buf.append(" ADD COLUMN "); sql2Buf.append(field.getColName()); sql2Buf.append(" "); sql2Buf.append(type.getSqlType()); if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) { // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sql2Buf.append(" CHARACTER SET "); sql2Buf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sql2Buf.append(" COLLATE "); sql2Buf.append(this.datasourceInfo.getCollate()); } } String sql2 = sql2Buf.toString(); if (Debug.infoOn()) Debug.logInfo("[addColumn] sql failed, trying sql2=" + sql2, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql2); } catch (SQLException e2) { // if this also fails report original error, not this error... return "SQL Exception while executing the following:\n" + sql + "\nError was: " + e2.toString(); } catch (GenericEntityException e2) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e2.toString(); Debug.logError(e2, errMsg, module); return errMsg; } } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String renameColumn(ModelEntity entity, ModelField field, String newName) { if (entity == null || field == null) return "ModelEntity or ModelField where null, cannot rename column"; if (entity instanceof ModelViewEntity) { return "ERROR: Cannot rename column for a view entity"; } ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not renaming column."; } StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" RENAME "); sqlBuf.append(field.getColName()); sqlBuf.append(" TO "); sqlBuf.append(newName); String sql = sqlBuf.toString(); if (Debug.infoOn()) Debug.logInfo("[renameColumn] sql=" + sql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public void repairColumnSize(ModelEntity entity, ModelField field, List<String> messages) { // first rename the column String tempName = makeTempFieldName(field); String renamedErr = renameColumn(entity, field, tempName); if (UtilValidate.isNotEmpty(renamedErr)) { if (messages != null) messages.add(renamedErr); Debug.logError(renamedErr, module); return; } // next add back in the column String addedErr = addColumn(entity, field); if (UtilValidate.isNotEmpty(addedErr)) { if (messages != null) messages.add(addedErr); Debug.logError(addedErr, module); return; } // copy the data from old to new StringBuilder sqlBuf1 = new StringBuilder("UPDATE "); sqlBuf1.append(entity.getTableName(datasourceInfo)); sqlBuf1.append(" SET "); sqlBuf1.append(field.getColName()); sqlBuf1.append(" = "); sqlBuf1.append(tempName); String sql1 = sqlBuf1.toString(); if (Debug.infoOn()) Debug.logInfo("[moveData] sql=" + sql1, module); try (Connection connection = getConnectionLogged(messages); Statement stmt = connection.createStatement()) { int changed = stmt.executeUpdate(sql1); if (Debug.infoOn()) Debug.logInfo("[moveData] " + changed + " records updated", module); } catch (SQLException e) { String thisMsg = "SQL Exception while executing the following:\n" + sql1 + "\nError was: " + e.toString(); if (messages != null) messages.add(thisMsg); Debug.logError(thisMsg, module); return; } // remove the old column StringBuilder sqlBuf2 = new StringBuilder("ALTER TABLE "); sqlBuf2.append(entity.getTableName(datasourceInfo)); sqlBuf2.append(" DROP COLUMN "); sqlBuf2.append(tempName); String sql2 = sqlBuf2.toString(); if (Debug.infoOn()) Debug.logInfo("[dropColumn] sql=" + sql2, module); try (Connection connection = getConnectionLogged(messages); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql2); } catch (SQLException e) { String thisMsg = "SQL Exception while executing the following:\n" + sql2 + "\nError was: " + e.toString(); if (messages != null) messages.add(thisMsg); Debug.logError(thisMsg, module); return; } } public void repairColumnSizeChanges(Map<String, ModelEntity> modelEntities, List<String> fieldsWrongSize, List<String> messages) { if (modelEntities == null || UtilValidate.isEmpty(fieldsWrongSize)) { messages.add("No fields to repair"); return; } if (messages == null) messages = new ArrayList<String>(); for (String fieldInfo: fieldsWrongSize) { String entityName = fieldInfo.substring(0, fieldInfo.indexOf('.')); String fieldName = fieldInfo.substring(fieldInfo.indexOf('.') + 1); ModelEntity modelEntity = modelEntities.get(entityName); ModelField modelField = modelEntity.getField(fieldName); repairColumnSize(modelEntity, modelField, messages); } } private String makeTempFieldName(ModelField field) { String tempName = "tmp_" + field.getName(); if (tempName.length() > 30) { tempName = tempName.substring(0, 30); } return tempName.toUpperCase(); } /* ====================================================================== */ /* ====================================================================== */ public String makePkConstraintName(ModelEntity entity, int constraintNameClipLength) { String pkName = "PK_" + entity.getPlainTableName(); if (pkName.length() > constraintNameClipLength) { pkName = pkName.substring(0, constraintNameClipLength); } return pkName; } public String makeFkConstraintName(ModelRelation modelRelation, int constraintNameClipLength) { String relConstraintName = modelRelation.getFkName(); if (UtilValidate.isEmpty(relConstraintName)) { relConstraintName = modelRelation.getTitle() + modelRelation.getRelEntityName(); relConstraintName = relConstraintName.toUpperCase(); } if (relConstraintName.length() > constraintNameClipLength) { relConstraintName = relConstraintName.substring(0, constraintNameClipLength); } return relConstraintName; } /* ====================================================================== */ public String makeIndexName(ModelIndex modelIndex, int constraintNameClipLength) { String indexName = modelIndex.getName(); if (indexName.length() > constraintNameClipLength) { indexName = indexName.substring(0, constraintNameClipLength); } return indexName; } /* ====================================================================== */ public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, List<String> messages) { return this.createForeignKeys(entity, modelEntities, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred(), messages); } public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred, List<String> messages) { if (entity == null) { String errMsg = "ModelEntity was null and is required to create foreign keys for a table"; Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); return 0; } if (entity instanceof ModelViewEntity) { //String errMsg = "ERROR: Cannot create foreign keys for a view entity"; //Debug.logError(errMsg, module); //if (messages != null) messages.add(errMsg); return 0; } int fksCreated = 0; // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { String errMsg = "Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(); Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); continue; } if (relModelEntity instanceof ModelViewEntity) { String errMsg = "Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(); Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); continue; } String retMsg = createForeignKey(entity, modelRelation, relModelEntity, constraintNameClipLength, fkStyle, useFkInitiallyDeferred); if (UtilValidate.isNotEmpty(retMsg)) { Debug.logError(retMsg, module); if (messages != null) messages.add(retMsg); continue; } fksCreated++; } } if (fksCreated > 0) { String message = "Created " + fksCreated + " foreign keys for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } return fksCreated; } public String createForeignKey(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred) { // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" ADD "); String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, constraintNameClipLength, fkStyle, useFkInitiallyDeferred); if (UtilValidate.isEmpty(fkConstraintClause)) { return "Error creating foreign key constraint clause, see log for details"; } sqlBuf.append(fkConstraintClause); if (Debug.verboseOn()) Debug.logVerbose("[createForeignKey] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String makeFkConstraintClause(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred) { // make the two column lists StringBuilder mainCols = new StringBuilder(); StringBuilder relCols = new StringBuilder(); for (ModelKeyMap keyMap : modelRelation.getKeyMaps()) { ModelField mainField = entity.getField(keyMap.getFieldName()); if (mainField == null) { Debug.logError("Bad key-map in entity [" + entity.getEntityName() + "] relation to [" + modelRelation.getTitle() + modelRelation.getRelEntityName() + "] for field [" + keyMap.getFieldName() + "]", module); return null; } if (mainCols.length() > 0) { mainCols.append(", "); } mainCols.append(mainField.getColName()); ModelField relField = relModelEntity.getField(keyMap.getRelFieldName()); if (relField == null) { Debug.logError("The field '" + keyMap.getRelFieldName() + "' was not found at related entity - check relations at entity '" + entity.getEntityName() + "'!", module); } if (relCols.length() > 0) { relCols.append(", "); } relCols.append(relField.getColName()); } StringBuilder sqlBuf = new StringBuilder(""); if ("name_constraint".equals(fkStyle)) { sqlBuf.append("CONSTRAINT "); String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); sqlBuf.append(relConstraintName); sqlBuf.append(" FOREIGN KEY ("); sqlBuf.append(mainCols.toString()); sqlBuf.append(") REFERENCES "); sqlBuf.append(relModelEntity.getTableName(datasourceInfo)); sqlBuf.append(" ("); sqlBuf.append(relCols.toString()); sqlBuf.append(")"); if (useFkInitiallyDeferred) { sqlBuf.append(" INITIALLY DEFERRED"); } } else if ("name_fk".equals(fkStyle)) { sqlBuf.append(" FOREIGN KEY "); String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); sqlBuf.append(relConstraintName); sqlBuf.append(" ("); sqlBuf.append(mainCols.toString()); sqlBuf.append(") REFERENCES "); sqlBuf.append(relModelEntity.getTableName(datasourceInfo)); sqlBuf.append(" ("); sqlBuf.append(relCols.toString()); sqlBuf.append(")"); if (useFkInitiallyDeferred) { sqlBuf.append(" INITIALLY DEFERRED"); } } else { String emsg = "ERROR: fk-style specified for this data-source is not valid: " + fkStyle; Debug.logError(emsg, module); throw new IllegalArgumentException(emsg); } return sqlBuf.toString(); } public void deleteForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, List<String> messages) { this.deleteForeignKeys(entity, modelEntities, datasourceInfo.getConstraintNameClipLength(), messages); } public void deleteForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, int constraintNameClipLength, List<String> messages) { if (entity == null) { String errMsg = "ModelEntity was null and is required to delete foreign keys for a table"; if (messages != null) messages.add(errMsg); Debug.logError(errMsg, module); return; } if (entity instanceof ModelViewEntity) { //String errMsg = "ERROR: Cannot delete foreign keys for a view entity"; //if (messages != null) messages.add(errMsg); //Debug.logError(errMsg, module); return; } String message = "Deleting foreign keys for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { String errMsg = "Error removing foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(); if (messages != null) messages.add(errMsg); Debug.logError(errMsg, module); continue; } if (relModelEntity instanceof ModelViewEntity) { String errMsg = "Error removing foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(); if (messages != null) messages.add(errMsg); Debug.logError(errMsg, module); continue; } String retMsg = deleteForeignKey(entity, modelRelation, relModelEntity, constraintNameClipLength); if (UtilValidate.isNotEmpty(retMsg)) { if (messages != null) messages.add(retMsg); Debug.logError(retMsg, module); } } } } public String deleteForeignKey(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength) { String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); if (datasourceInfo.getDropFkUseForeignKeyKeyword()) { sqlBuf.append(" DROP FOREIGN KEY "); } else { sqlBuf.append(" DROP CONSTRAINT "); } sqlBuf.append(relConstraintName); if (Debug.verboseOn()) Debug.logVerbose("[deleteForeignKey] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } /* ====================================================================== */ /* ====================================================================== */ public void createPrimaryKey(ModelEntity entity, boolean usePkConstraintNames, int constraintNameClipLength, List<String> messages) { if (messages == null) messages = new ArrayList<String>(); String err = createPrimaryKey(entity, usePkConstraintNames, constraintNameClipLength); if (UtilValidate.isNotEmpty(err)) { messages.add(err); } } public void createPrimaryKey(ModelEntity entity, boolean usePkConstraintNames, List<String> messages) { createPrimaryKey(entity, usePkConstraintNames, datasourceInfo.getConstraintNameClipLength(), messages); } public void createPrimaryKey(ModelEntity entity, List<String> messages) { createPrimaryKey(entity, datasourceInfo.getUsePkConstraintNames(), messages); } public String createPrimaryKey(ModelEntity entity, boolean usePkConstraintNames, int constraintNameClipLength) { if (entity == null) { return "ModelEntity was null and is required to create the primary key for a table"; } if (entity instanceof ModelViewEntity) { return "Ignoring view entity [" + entity.getEntityName() + "]"; } String message; if (entity.getPksSize() > 0) { message = "Creating primary key for entity [" + entity.getEntityName() + "]"; // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" ADD "); String pkName = makePkConstraintName(entity, constraintNameClipLength); if (usePkConstraintNames) { sqlBuf.append("CONSTRAINT "); sqlBuf.append(pkName); } sqlBuf.append(" PRIMARY KEY ("); entity.colNameString(entity.getPkFieldsUnmodifiable(), sqlBuf, ""); sqlBuf.append(")"); if (Debug.verboseOn()) Debug.logVerbose("[createPrimaryKey] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { return "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); } catch (GenericEntityException e) { return "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); } } else { message = "No primary-key defined for table [" + entity.getEntityName() + "]"; } Debug.logImportant(message, module); return message; } public void deletePrimaryKey(ModelEntity entity, boolean usePkConstraintNames, int constraintNameClipLength, List<String> messages) { if (messages == null) messages = new ArrayList<String>(); String err = deletePrimaryKey(entity, usePkConstraintNames, constraintNameClipLength); if (UtilValidate.isNotEmpty(err)) { messages.add(err); } } public void deletePrimaryKey(ModelEntity entity, boolean usePkConstraintNames, List<String> messages) { deletePrimaryKey(entity, usePkConstraintNames, datasourceInfo.getConstraintNameClipLength(), messages); } public void deletePrimaryKey(ModelEntity entity, List<String> messages) { deletePrimaryKey(entity, datasourceInfo.getUsePkConstraintNames(), messages); } public String deletePrimaryKey(ModelEntity entity, boolean usePkConstraintNames, int constraintNameClipLength) { if (entity == null) { return "ModelEntity was null and is required to delete the primary key for a table"; } if (entity instanceof ModelViewEntity) { return "Ignoring view entity [" + entity.getEntityName() + "]"; } String message; if (entity.getPksSize() > 0) { message = "Deleting primary key for entity [" + entity.getEntityName() + "]"; // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" DROP "); String pkName = makePkConstraintName(entity, constraintNameClipLength); if (usePkConstraintNames) { sqlBuf.append("CONSTRAINT "); sqlBuf.append(pkName); sqlBuf.append(" CASCADE"); } else { sqlBuf.append(" PRIMARY KEY"); // DEJ20050502 not sure why this is here, shouldn't be needed and some dbs don't support like this, ie when used with PRIMARY KEY: sqlBuf.append(" CASCADE"); } if (Debug.verboseOn()) Debug.logVerbose("[deletePrimaryKey] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } } else { message = "No primary-key defined for table [" + entity.getEntityName() + "]"; } Debug.logImportant(message, module); return message; } /* ====================================================================== */ /* ====================================================================== */ public int createDeclaredIndices(ModelEntity entity, List<String> messages) { if (entity == null) { String message = "ModelEntity was null and is required to create declared indices for a table"; Debug.logError(message, module); if (messages != null) messages.add(message); return 0; } if (entity instanceof ModelViewEntity) { String message = "Cannot create declared indices for a view entity"; Debug.logWarning(message, module); if (messages != null) messages.add(message); return 0; } int dinsCreated = 0; // go through the indexes to see if any need to be added Iterator<ModelIndex> indexesIter = entity.getIndexesIterator(); while (indexesIter.hasNext()) { ModelIndex modelIndex = indexesIter.next(); String retMsg = createDeclaredIndex(entity, modelIndex); if (UtilValidate.isNotEmpty(retMsg)) { String message = "Could not create declared indices for entity [" + entity.getEntityName() + "]: " + retMsg; Debug.logError(message, module); if (messages != null) messages.add(message); continue; } dinsCreated++; } if (dinsCreated > 0) { String message = "Created " + dinsCreated + " declared indices for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } return dinsCreated; } public String createDeclaredIndex(ModelEntity entity, ModelIndex modelIndex) { String createIndexSql = null; try { createIndexSql = makeIndexClause(entity, modelIndex); } catch (Exception e) { // SCIPIO: Do this here so a single error doesn't ruin all indexes String errMsg = "Error while making index clause for index [" + modelIndex.getName() + "]: " + e.getMessage(); Debug.logError(e, errMsg, module); return errMsg; } if (Debug.verboseOn()) Debug.logVerbose("[createForeignKeyIndex] index sql=" + createIndexSql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(createIndexSql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + createIndexSql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String makeIndexClause(ModelEntity entity, ModelIndex modelIndex) throws GenericEntityConfException { // SCIPIO: May throw StringBuilder mainCols = new StringBuilder(); for (ModelIndex.Field field : modelIndex.getFields()) { ModelIndex.Function function = field.getFunction(); if (mainCols.length() > 0) { mainCols.append(", "); } if (function != null) { mainCols.append(function.toString()).append('('); } ModelField mainField = entity.getField(field.getFieldName()); if (mainField != null) { // SCIPIO: Missing check causing unexplainable NPE mainCols.append(mainField.getColName()); } else { throw new GenericEntityConfException("Field name [" + field.getFieldName() + "] not found in entity [" + entity.getEntityName() + "]"); } if (function != null) { mainCols.append(')'); } } StringBuilder indexSqlBuf = new StringBuilder("CREATE "); if (datasourceInfo.getUseIndicesUnique() && modelIndex.getUnique()) { indexSqlBuf.append("UNIQUE "); } indexSqlBuf.append("INDEX "); indexSqlBuf.append(makeIndexName(modelIndex, datasourceInfo.getConstraintNameClipLength())); indexSqlBuf.append(" ON "); indexSqlBuf.append(entity.getTableName(datasourceInfo)); indexSqlBuf.append(" ("); indexSqlBuf.append(mainCols.toString()); indexSqlBuf.append(")"); return indexSqlBuf.toString(); } public void deleteDeclaredIndices(ModelEntity entity, List<String> messages) { if (messages == null) messages = new ArrayList<String>(); String err = deleteDeclaredIndices(entity); if (UtilValidate.isNotEmpty(err)) { messages.add(err); } } public String deleteDeclaredIndices(ModelEntity entity) { if (entity == null) { return "ModelEntity was null and is required to delete declared indices for a table"; } if (entity instanceof ModelViewEntity) { return "ERROR: Cannot delete declared indices for a view entity"; } StringBuilder retMsgsBuffer = new StringBuilder(); // go through the relationships to see if any foreign keys need to be added Iterator<ModelIndex> indexesIter = entity.getIndexesIterator(); while (indexesIter.hasNext()) { ModelIndex modelIndex = indexesIter.next(); String retMsg = deleteDeclaredIndex(entity, modelIndex); if (UtilValidate.isNotEmpty(retMsg)) { if (retMsgsBuffer.length() > 0) { retMsgsBuffer.append("\n"); } retMsgsBuffer.append(retMsg); if (Debug.infoOn()) Debug.logInfo(retMsg, module); } } if (retMsgsBuffer.length() > 0) { return retMsgsBuffer.toString(); } else { return null; } } public String deleteDeclaredIndex(ModelEntity entity, ModelIndex modelIndex) { // TODO: also remove the constraing if this was a unique index, in most databases dropping the index does not drop the constraint StringBuilder indexSqlBuf = new StringBuilder("DROP INDEX "); String tableName = entity.getTableName(datasourceInfo); String schemaName = (UtilValidate.isEmpty(tableName) || tableName.indexOf('.') == -1) ? "" : tableName.substring(0, tableName.indexOf('.')); indexSqlBuf.append(schemaName); indexSqlBuf.append("."); indexSqlBuf.append(modelIndex.getName()); String deleteIndexSql = indexSqlBuf.toString(); if (Debug.verboseOn()) Debug.logVerbose("[deleteDeclaredIndex] index sql=" + deleteIndexSql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(deleteIndexSql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + deleteIndexSql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } /* ====================================================================== */ /* ====================================================================== */ public int createForeignKeyIndices(ModelEntity entity, List<String> messages) { return createForeignKeyIndices(entity, datasourceInfo.getConstraintNameClipLength(), messages); } public int createForeignKeyIndices(ModelEntity entity, int constraintNameClipLength, List<String> messages) { if (entity == null) { String message = "ModelEntity was null and is required to create foreign keys indices for a table"; Debug.logError(message, module); if (messages != null) messages.add(message); return 0; } if (entity instanceof ModelViewEntity) { String message = "Cannot create foreign keys indices for a view entity"; Debug.logWarning(message, module); if (messages != null) messages.add(message); return 0; } int fkisCreated = 0; // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { String retMsg = createForeignKeyIndex(entity, modelRelation, constraintNameClipLength); if (UtilValidate.isNotEmpty(retMsg)) { String message = "Could not create foreign key indices for entity [" + entity.getEntityName() + "]: " + retMsg; Debug.logError(message, module); if (messages != null) messages.add(message); continue; } fkisCreated++; } } if (fkisCreated > 0) { String message = "Created " + fkisCreated + " foreign key indices for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } return fkisCreated; } public String createForeignKeyIndex(ModelEntity entity, ModelRelation modelRelation, int constraintNameClipLength) { String createIndexSql = makeFkIndexClause(entity, modelRelation, constraintNameClipLength); if (UtilValidate.isEmpty(createIndexSql)) { return "Error creating foreign key index clause, see log for details"; } if (Debug.verboseOn()) Debug.logVerbose("[createForeignKeyIndex] index sql=" + createIndexSql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(createIndexSql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + createIndexSql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String makeFkIndexClause(ModelEntity entity, ModelRelation modelRelation, int constraintNameClipLength) { StringBuilder mainCols = new StringBuilder(); for (ModelKeyMap keyMap : modelRelation.getKeyMaps()) { ModelField mainField = entity.getField(keyMap.getFieldName()); if (mainField == null) { Debug.logError("Bad key-map in entity [" + entity.getEntityName() + "] relation to [" + modelRelation.getTitle() + modelRelation.getRelEntityName() + "] for field [" + keyMap.getFieldName() + "]", module); return null; } if (mainCols.length() > 0) { mainCols.append(", "); } mainCols.append(mainField.getColName()); } StringBuilder indexSqlBuf = new StringBuilder("CREATE INDEX "); String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); indexSqlBuf.append(relConstraintName); indexSqlBuf.append(" ON "); indexSqlBuf.append(entity.getTableName(datasourceInfo)); indexSqlBuf.append(" ("); indexSqlBuf.append(mainCols.toString()); indexSqlBuf.append(")"); return indexSqlBuf.toString(); } public void deleteForeignKeyIndices(ModelEntity entity, List<String> messages) { if (messages == null) messages = new ArrayList<String>(); String err = deleteForeignKeyIndices(entity, datasourceInfo.getConstraintNameClipLength()); if (UtilValidate.isNotEmpty(err)) { messages.add(err); } } public String deleteForeignKeyIndices(ModelEntity entity, int constraintNameClipLength) { if (entity == null) { return "ModelEntity was null and is required to delete foreign keys indices for a table"; } if (entity instanceof ModelViewEntity) { return "ERROR: Cannot delete foreign keys indices for a view entity"; } StringBuilder retMsgsBuffer = new StringBuilder(); // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { String retMsg = deleteForeignKeyIndex(entity, modelRelation, constraintNameClipLength); if (UtilValidate.isNotEmpty(retMsg)) { if (retMsgsBuffer.length() > 0) { retMsgsBuffer.append("\n"); } retMsgsBuffer.append(retMsg); } } } if (retMsgsBuffer.length() > 0) { return retMsgsBuffer.toString(); } else { return null; } } public String deleteForeignKeyIndex(ModelEntity entity, ModelRelation modelRelation, int constraintNameClipLength) { StringBuilder indexSqlBuf = new StringBuilder("DROP INDEX "); String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); String tableName = entity.getTableName(datasourceInfo); String schemaName = (UtilValidate.isEmpty(tableName) || tableName.indexOf('.') == -1) ? "" : tableName.substring(0, tableName.indexOf('.')); if (UtilValidate.isNotEmpty(schemaName)) { indexSqlBuf.append(schemaName); indexSqlBuf.append("."); } indexSqlBuf.append(relConstraintName); String deleteIndexSql = indexSqlBuf.toString(); if (Debug.verboseOn()) Debug.logVerbose("[deleteForeignKeyIndex] index sql=" + deleteIndexSql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(deleteIndexSql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + deleteIndexSql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String getSchemaName(DatabaseMetaData dbData) throws SQLException { if (!isLegacy && this.datasourceInfo.getUseSchemas() && dbData.supportsSchemasInTableDefinitions()) { if (UtilValidate.isNotEmpty(this.datasourceInfo.getSchemaName())) { if (dbData.storesLowerCaseIdentifiers()) { return this.datasourceInfo.getSchemaName().toLowerCase(); } else if (dbData.storesUpperCaseIdentifiers()) { return this.datasourceInfo.getSchemaName().toUpperCase(); } else { return this.datasourceInfo.getSchemaName(); } } else { return dbData.getUserName(); } } return null; } /* ====================================================================== */ /* ====================================================================== */ public void updateCharacterSetAndCollation(ModelEntity entity, List<String> messages) { if (entity instanceof ModelViewEntity) { return; } if (UtilValidate.isEmpty(this.datasourceInfo.getCharacterSet()) && UtilValidate.isEmpty(this.datasourceInfo.getCollate())) { messages.add("Not setting character-set and collate for entity [" + entity.getEntityName() + "], options not specified in the datasource definition in the entityengine.xml file."); return; } try (Connection connection = getConnectionLogged(messages)) { if (connection == null) { return; } StringBuilder sqlTableBuf = new StringBuilder("ALTER TABLE "); sqlTableBuf.append(entity.getTableName(this.datasourceInfo)); //sqlTableBuf.append(""); // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlTableBuf.append(" DEFAULT CHARACTER SET "); sqlTableBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlTableBuf.append(" COLLATE "); sqlTableBuf.append(this.datasourceInfo.getCollate()); } if (Debug.verboseOn()) Debug.logVerbose("[updateCharacterSetAndCollation] character-set and collate sql=" + sqlTableBuf, module); try (Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlTableBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlTableBuf + "\nError was: " + e.toString(); messages.add(errMsg); Debug.logError(errMsg, module); } Iterator<ModelField> fieldIter = entity.getFieldsIterator(); while (fieldIter.hasNext()) { ModelField field = fieldIter.next(); ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { messages.add("Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table."); continue; } if (!"String".equals(type.getJavaType()) && !"java.lang.String".equals(type.getJavaType())) { continue; } StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(this.datasourceInfo)); sqlBuf.append(" MODIFY COLUMN "); sqlBuf.append(field.getColName()); sqlBuf.append(" "); sqlBuf.append(type.getSqlType()); // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlBuf.append(" CHARACTER SET "); sqlBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlBuf.append(" COLLATE "); sqlBuf.append(this.datasourceInfo.getCollate()); } if (field.getIsPk() || field.getIsNotNull()) { if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) { sqlBuf.append(" CONSTRAINT NOT NULL"); } else { sqlBuf.append(" NOT NULL"); } } if (Debug.verboseOn()) Debug.logVerbose("[updateCharacterSetAndCollation] character-set and collate sql=" + sqlBuf, module); try (Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf + "\nError was: " + e.toString(); messages.add(errMsg); Debug.logError(errMsg, module); } } } catch (SQLException e) { Debug.logError(e, module); } } /* ====================================================================== */ /* ====================================================================== */ @SuppressWarnings("serial") public static class ColumnCheckInfo implements Serializable { public String tableName; public String columnName; public String typeName; public int columnSize; public int decimalDigits; public String isNullable; // YES/NO or "" = ie nobody knows public boolean isPk = false; public int pkSeq; public String pkName; public static String fixupTableName(String rawTableName, String lookupSchemaName, boolean needsUpperCase) { String tableName = rawTableName; // for those databases which do not return the schema name with the table name (pgsql 7.3) boolean appendSchemaName = false; if (tableName != null && lookupSchemaName != null && !tableName.startsWith(lookupSchemaName + "\\.")) { appendSchemaName = true; } if (needsUpperCase && tableName != null) { tableName = tableName.toUpperCase(); } if (appendSchemaName) { tableName = lookupSchemaName + "." + tableName; } return tableName; } } @SuppressWarnings("serial") public static class ReferenceCheckInfo implements Serializable { public String pkTableName; /** Comma separated list of column names in the related tables primary key */ public String pkColumnName; public String fkName; public String fkTableName; /** Comma separated list of column names in the primary tables foreign keys */ public String fkColumnName; @Override public String toString() { return "FK Reference from table " + fkTableName + " called " + fkName + " to PK in table " + pkTableName; } } }
framework/entity/src/org/ofbiz/entity/jdbc/DatabaseUtil.java
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package org.ofbiz.entity.jdbc; import java.io.Serializable; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.ofbiz.base.concurrent.ExecutionPool; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilTimer; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.config.model.Datasource; import org.ofbiz.entity.config.model.EntityConfig; import org.ofbiz.entity.datasource.GenericHelperInfo; import org.ofbiz.entity.model.ModelEntity; import org.ofbiz.entity.model.ModelField; import org.ofbiz.entity.model.ModelFieldType; import org.ofbiz.entity.model.ModelFieldTypeReader; import org.ofbiz.entity.model.ModelIndex; import org.ofbiz.entity.model.ModelKeyMap; import org.ofbiz.entity.model.ModelRelation; import org.ofbiz.entity.model.ModelViewEntity; import org.ofbiz.entity.transaction.TransactionFactoryLoader; import org.ofbiz.entity.transaction.TransactionUtil; /** * Utilities for Entity Database Maintenance * */ public class DatabaseUtil { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); // OFBiz Connections protected ModelFieldTypeReader modelFieldTypeReader = null; protected Datasource datasourceInfo = null; protected GenericHelperInfo helperInfo = null; // Legacy Connections protected String connectionUrl = null; protected String driverName = null; protected String userName = null; protected String password = null; boolean isLegacy = false; // OFBiz DatabaseUtil public DatabaseUtil(GenericHelperInfo helperInfo) { this.helperInfo = helperInfo; this.modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperInfo.getHelperBaseName()); this.datasourceInfo = EntityConfig.getDatasource(helperInfo.getHelperBaseName()); } protected Connection getConnection() throws SQLException, GenericEntityException { Connection connection = null; if (!isLegacy) { connection = TransactionFactoryLoader.getInstance().getConnection(helperInfo); } else { connection = getConnection(driverName, connectionUrl, null, userName, password); } if (connection == null) { if (!isLegacy) { throw new GenericEntityException("No connection available for helper named [" + helperInfo.getHelperFullName() + "]"); } else { throw new GenericEntityException("No connection avaialble for URL [" + connectionUrl + "]"); } } if (!TransactionUtil.isTransactionInPlace()) { connection.setAutoCommit(true); } return connection; } private Connection getConnection(String driverName, String connectionUrl, Properties props, String userName, String password) throws SQLException { // first register the JDBC driver with the DriverManager if (driverName != null) { if (DriverManager.getDriver(driverName) == null) { try { Driver driver = (Driver) Class.forName(driverName, true, Thread.currentThread().getContextClassLoader()).newInstance(); DriverManager.registerDriver(driver); } catch (ClassNotFoundException e) { Debug.logWarning(e, "Unable to load driver [" + driverName + "]", module); } catch (InstantiationException e) { Debug.logWarning(e, "Unable to instantiate driver [" + driverName + "]", module); } catch (IllegalAccessException e) { Debug.logWarning(e, "Illegal access exception [" + driverName + "]", module); } } } try { if (UtilValidate.isNotEmpty(userName)) return DriverManager.getConnection(connectionUrl, userName, password); else if (props != null) return DriverManager.getConnection(connectionUrl, props); else return DriverManager.getConnection(connectionUrl); } catch (SQLException e) { Debug.logError(e, "SQL Error obtaining JDBC connection", module); throw e; } } protected Connection getConnectionLogged(Collection<String> messages) { try { return getConnection(); } catch (SQLException | GenericEntityException e) { String message = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); return null; } } public Datasource getDatasource() { return this.datasourceInfo; } /* ====================================================================== */ /* ====================================================================== */ public void checkDb(Map<String, ModelEntity> modelEntities, List<String> messages, boolean addMissing) { checkDb(modelEntities, null, messages, datasourceInfo.getCheckPksOnStart(), (datasourceInfo.getUseForeignKeys() && datasourceInfo.getCheckFksOnStart()), (datasourceInfo.getUseForeignKeyIndices() && datasourceInfo.getCheckFkIndicesOnStart()), addMissing); } public void checkDb(Map<String, ModelEntity> modelEntities, List<String> colWrongSize, List<String> messages, boolean checkPks, boolean checkFks, boolean checkFkIdx, boolean addMissing) { if (isLegacy) { throw new RuntimeException("Cannot run checkDb on a legacy database connection; configure a database helper (entityengine.xml)"); } ExecutorService executor = Executors.newFixedThreadPool(datasourceInfo.getMaxWorkerPoolSize()); UtilTimer timer = new UtilTimer(); timer.timerString("Start - Before Get Database Meta Data"); // get ALL tables from this database TreeSet<String> tableNames = this.getTableNames(messages); TreeSet<String> fkTableNames = tableNames == null ? null : new TreeSet<String>(tableNames); TreeSet<String> indexTableNames = tableNames == null ? null : new TreeSet<String>(tableNames); if (tableNames == null) { String message = "Could not get table name information from the database, aborting."; if (messages != null) messages.add(message); Debug.logError(message, module); return; } timer.timerString("After Get All Table Names"); // get ALL column info, put into hashmap by table name Map<String, Map<String, ColumnCheckInfo>> colInfo = getColumnInfo(tableNames, checkPks, messages, executor); if (colInfo == null) { String message = "Could not get column information from the database, aborting."; if (messages != null) messages.add(message); Debug.logError(message, module); return; } timer.timerString("After Get All Column Info"); // -make sure all entities have a corresponding table // -list all tables that do not have a corresponding entity // -display message if number of table columns does not match number of entity fields // -list all columns that do not have a corresponding field // -make sure each corresponding column is of the correct type // -list all fields that do not have a corresponding column timer.timerString("Before Individual Table/Column Check"); List<ModelEntity> modelEntityList = new ArrayList<ModelEntity>(modelEntities.values()); // sort using compareTo method on ModelEntity Collections.sort(modelEntityList); int curEnt = 0; int totalEnt = modelEntityList.size(); List<ModelEntity> entitiesAdded = new LinkedList<ModelEntity>(); String schemaName; try { schemaName = getSchemaName(messages); } catch (SQLException e) { String message = "Could not get schema name the database, aborting."; if (messages != null) messages.add(message); Debug.logError(message, module); return; } List<Future<CreateTableCallable>> tableFutures = new LinkedList<Future<CreateTableCallable>>(); for (ModelEntity entity: modelEntityList) { curEnt++; // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { String entMessage = "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " View Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, module); if (messages != null) messages.add(entMessage); continue; // if never-check is set then don't check it either } else if (entity.getNeverCheck()) { String entMessage = "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, module); if (messages != null) messages.add(entMessage); continue; } String plainTableName = entity.getPlainTableName(); String tableName; if (UtilValidate.isNotEmpty(schemaName)) { tableName = schemaName + "." + plainTableName; } else { tableName = plainTableName; } String entMessage = "(" + timer.timeSinceLast() + "ms) Checking #" + curEnt + "/" + totalEnt + " Entity " + entity.getEntityName() + " with table " + tableName; Debug.logVerbose(entMessage, module); if (messages != null) messages.add(entMessage); // -make sure all entities have a corresponding table if (tableNames.contains(tableName)) { tableNames.remove(tableName); if (colInfo != null) { Map<String, ModelField> fieldColNames = new HashMap<String, ModelField>(); Iterator<ModelField> fieldIter = entity.getFieldsIterator(); while (fieldIter.hasNext()) { ModelField field = fieldIter.next(); fieldColNames.put(field.getColName(), field); } Map<String, ColumnCheckInfo> colMap = colInfo.get(tableName); if (colMap != null) { for (ColumnCheckInfo ccInfo: colMap.values()) { // -list all columns that do not have a corresponding field if (fieldColNames.containsKey(ccInfo.columnName)) { ModelField field = null; field = fieldColNames.remove(ccInfo.columnName); ModelFieldType modelFieldType = modelFieldTypeReader.getModelFieldType(field.getType()); if (modelFieldType != null) { // make sure each corresponding column is of the correct type String fullTypeStr = modelFieldType.getSqlType(); String typeName; int columnSize = -1; int decimalDigits = -1; int openParen = fullTypeStr.indexOf('('); int closeParen = fullTypeStr.indexOf(')'); int comma = fullTypeStr.indexOf(','); if (openParen > 0 && closeParen > 0 && closeParen > openParen) { typeName = fullTypeStr.substring(0, openParen); if (comma > 0 && comma > openParen && comma < closeParen) { String csStr = fullTypeStr.substring(openParen + 1, comma); try { columnSize = Integer.parseInt(csStr); } catch (NumberFormatException e) { Debug.logError(e, module); } String ddStr = fullTypeStr.substring(comma + 1, closeParen); try { decimalDigits = Integer.parseInt(ddStr); } catch (NumberFormatException e) { Debug.logError(e, module); } } else { String csStr = fullTypeStr.substring(openParen + 1, closeParen); try { columnSize = Integer.parseInt(csStr); } catch (NumberFormatException e) { Debug.logError(e, module); } } } else { typeName = fullTypeStr; } // override the default typeName with the sqlTypeAlias if it is specified if (UtilValidate.isNotEmpty(modelFieldType.getSqlTypeAlias())) { typeName = modelFieldType.getSqlTypeAlias(); } // NOTE: this may need a toUpperCase in some cases, keep an eye on it, okay just compare with ignore case if (!ccInfo.typeName.equalsIgnoreCase(typeName)) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] is of type [" + ccInfo.typeName + "] in the database, but is defined as type [" + typeName + "] in the entity definition."; Debug.logError(message, module); if (messages != null) messages.add(message); } if (columnSize != -1 && ccInfo.columnSize != -1 && columnSize != ccInfo.columnSize && (columnSize * 3) != ccInfo.columnSize) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] has a column size of [" + ccInfo.columnSize + "] in the database, but is defined to have a column size of [" + columnSize + "] in the entity definition."; Debug.logWarning(message, module); if (messages != null) messages.add(message); if (columnSize > ccInfo.columnSize && colWrongSize != null) { // add item to list of wrong sized columns; only if the entity is larger colWrongSize.add(entity.getEntityName() + "." + field.getName()); } } if (decimalDigits != -1 && decimalDigits != ccInfo.decimalDigits) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] has a decimalDigits of [" + ccInfo.decimalDigits + "] in the database, but is defined to have a decimalDigits of [" + decimalDigits + "] in the entity definition."; Debug.logWarning(message, module); if (messages != null) messages.add(message); } // do primary key matching check if (checkPks && ccInfo.isPk && !field.getIsPk()) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] IS a primary key in the database, but IS NOT a primary key in the entity definition. The primary key for this table needs to be re-created or modified so that this column is NOT part of the primary key."; Debug.logError(message, module); if (messages != null) messages.add(message); } if (checkPks && !ccInfo.isPk && field.getIsPk()) { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] IS NOT a primary key in the database, but IS a primary key in the entity definition. The primary key for this table needs to be re-created or modified to add this column to the primary key. Note that data may need to be added first as a primary key column cannot have an null values."; Debug.logError(message, module); if (messages != null) messages.add(message); } } else { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] has a field type name of [" + field.getType() + "] which is not found in the field type definitions"; Debug.logError(message, module); if (messages != null) messages.add(message); } } else { String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] exists in the database but has no corresponding field" + ((checkPks && ccInfo.isPk) ? " (and it is a PRIMARY KEY COLUMN)" : ""); Debug.logWarning(message, module); if (messages != null) messages.add(message); } } // -display message if number of table columns does not match number of entity fields if (colMap.size() != entity.getFieldsSize()) { String message = "Entity [" + entity.getEntityName() + "] has " + entity.getFieldsSize() + " fields but table [" + tableName + "] has " + colMap.size() + " columns."; Debug.logWarning(message, module); if (messages != null) messages.add(message); } } // -list all fields that do not have a corresponding column for (ModelField field : fieldColNames.values()) { String message = "Field [" + field.getName() + "] of entity [" + entity.getEntityName() + "] is missing its corresponding column [" + field.getColName() + "]" + (field.getIsPk() ? " (and it is a PRIMARY KEY FIELD)" : ""); Debug.logWarning(message, module); if (messages != null) messages.add(message); if (addMissing) { // add the column String errMsg = addColumn(entity, field); if (UtilValidate.isNotEmpty(errMsg)) { message = "Could not add column [" + field.getColName() + "] to table [" + tableName + "]: " + errMsg; Debug.logError(message, module); if (messages != null) messages.add(message); } else { message = "Added column [" + field.getColName() + "] to table [" + tableName + "]" + (field.getIsPk() ? " (NOTE: this is a PRIMARY KEY FIELD, but the primary key was not updated automatically (not considered a safe operation), be sure to fill in any needed data and re-create the primary key)" : ""); Debug.logImportant(message, module); if (messages != null) messages.add(message); } } } } } else { String message = "Entity [" + entity.getEntityName() + "] has no table in the database"; Debug.logWarning(message, module); if (messages != null) messages.add(message); if (addMissing) { // create the table tableFutures.add(executor.submit(new CreateTableCallable(entity, modelEntities, tableName))); } } } for (CreateTableCallable tableCallable: ExecutionPool.getAllFutures(tableFutures)) { tableCallable.updateData(messages, entitiesAdded); } timer.timerString("After Individual Table/Column Check"); // -list all tables that do not have a corresponding entity for (String tableName: tableNames) { String message = "Table named [" + tableName + "] exists in the database but has no corresponding entity"; Debug.logWarning(message, module); if (messages != null) messages.add(message); } // for each newly added table, add fk indices if (datasourceInfo.getUseForeignKeyIndices()) { int totalFkIndices = 0; List<Future<AbstractCountingCallable>> fkIndicesFutures = new LinkedList<Future<AbstractCountingCallable>>(); for (ModelEntity curEntity: entitiesAdded) { if (curEntity.getRelationsOneSize() > 0) { fkIndicesFutures.add(executor.submit(new AbstractCountingCallable(curEntity, modelEntities) { public AbstractCountingCallable call() throws Exception { count = createForeignKeyIndices(entity, datasourceInfo.getConstraintNameClipLength(), messages); return this; } })); } } for (AbstractCountingCallable fkIndicesCallable: ExecutionPool.getAllFutures(fkIndicesFutures)) { totalFkIndices += fkIndicesCallable.updateData(messages); } if (totalFkIndices > 0) Debug.logImportant("==== TOTAL Foreign Key Indices Created: " + totalFkIndices, module); } // for each newly added table, add fks if (datasourceInfo.getUseForeignKeys()) { int totalFks = 0; for (ModelEntity curEntity: entitiesAdded) { totalFks += this.createForeignKeys(curEntity, modelEntities, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred(), messages); } if (totalFks > 0) Debug.logImportant("==== TOTAL Foreign Keys Created: " + totalFks, module); } // for each newly added table, add declared indexes if (datasourceInfo.getUseIndices()) { int totalDis = 0; List<Future<AbstractCountingCallable>> disFutures = new LinkedList<Future<AbstractCountingCallable>>(); for (ModelEntity curEntity: entitiesAdded) { if (curEntity.getIndexesSize() > 0) { disFutures.add(executor.submit(new AbstractCountingCallable(curEntity, modelEntities) { public AbstractCountingCallable call() throws Exception { count = createDeclaredIndices(entity, messages); return this; } })); } } for (AbstractCountingCallable disCallable: ExecutionPool.getAllFutures(disFutures)) { totalDis += disCallable.updateData(messages); } if (totalDis > 0) Debug.logImportant("==== TOTAL Declared Indices Created: " + totalDis, module); } // make sure each one-relation has an FK if (checkFks) { //if (!justColumns && datasourceInfo.getUseForeignKeys() && datasourceInfo.checkForeignKeysOnStart) { // NOTE: This ISN'T working for Postgres or MySQL, who knows about others, may be from JDBC driver bugs... int numFksCreated = 0; // TODO: check each key-map to make sure it exists in the FK, if any differences warn and then remove FK and recreate it // get ALL column info, put into hashmap by table name Map<String, Map<String, ReferenceCheckInfo>> refTableInfoMap = this.getReferenceInfo(fkTableNames, messages); // Debug.logVerbose("Ref Info Map: " + refTableInfoMap, module); if (refTableInfoMap == null) { // uh oh, something happened while getting info... if (Debug.verboseOn()) Debug.logVerbose("Ref Table Info Map is null", module); } else { for (ModelEntity entity: modelEntityList) { String entityName = entity.getEntityName(); // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { String entMessage = "NOT Checking View Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, module); if (messages != null) { messages.add(entMessage); } continue; } // get existing FK map for this table Map<String, ReferenceCheckInfo> rcInfoMap = refTableInfoMap.get(entity.getTableName(datasourceInfo)); // Debug.logVerbose("Got ref info for table " + entity.getTableName(datasourceInfo) + ": " + rcInfoMap, module); // go through each relation to see if an FK already exists Iterator<ModelRelation> relations = entity.getRelationsIterator(); boolean createdConstraints = false; while (relations.hasNext()) { ModelRelation modelRelation = relations.next(); if (!"one".equals(modelRelation.getType())) { continue; } ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { Debug.logError("No such relation: " + entity.getEntityName() + " -> " + modelRelation.getRelEntityName(), module); continue; } String relConstraintName = makeFkConstraintName(modelRelation, datasourceInfo.getConstraintNameClipLength()); ReferenceCheckInfo rcInfo = null; if (rcInfoMap != null) { rcInfo = rcInfoMap.get(relConstraintName); } if (rcInfo != null) { rcInfoMap.remove(relConstraintName); } else { // if not, create one String noFkMessage = "No Foreign Key Constraint [" + relConstraintName + "] found for entity [" + entityName + "]"; if (messages != null) messages.add(noFkMessage); if (Debug.infoOn()) Debug.logInfo(noFkMessage, module); if (addMissing) { String errMsg = createForeignKey(entity, modelRelation, relModelEntity, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred()); if (UtilValidate.isNotEmpty(errMsg)) { String message = "Could not create foreign key " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg; Debug.logError(message, module); if (messages != null) messages.add(message); } else { String message = "Created foreign key " + relConstraintName + " for entity [" + entity.getEntityName() + "]"; Debug.logVerbose(message, module); if (messages != null) messages.add(message); createdConstraints = true; numFksCreated++; } } } } if (createdConstraints) { String message = "Created foreign key(s) for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } // show foreign key references that exist but are unknown if (rcInfoMap != null) { for (String rcKeyLeft: rcInfoMap.keySet()) { String message = "Unknown Foreign Key Constraint " + rcKeyLeft + " found in table " + entity.getTableName(datasourceInfo); Debug.logImportant(message, module); if (messages != null) messages.add(message); } } } } if (Debug.infoOn()) Debug.logInfo("Created " + numFksCreated + " fk refs", module); } // make sure each one-relation has an index if (checkFkIdx || datasourceInfo.getCheckIndicesOnStart()) { //if (!justColumns && datasourceInfo.getUseForeignKeyIndices() && datasourceInfo.checkFkIndicesOnStart) { int numIndicesCreated = 0; // TODO: check each key-map to make sure it exists in the index, if any differences warn and then remove the index and recreate it // get ALL column info, put into hashmap by table name boolean needsUpperCase[] = new boolean[1]; Map<String, Set<String>> tableIndexListMap = this.getIndexInfo(indexTableNames, messages, needsUpperCase); // Debug.logVerbose("Ref Info Map: " + refTableInfoMap, module); if (tableIndexListMap == null) { // uh oh, something happened while getting info... if (Debug.verboseOn()) Debug.logVerbose("Ref Table Info Map is null", module); } else { for (ModelEntity entity: modelEntityList) { String entityName = entity.getEntityName(); // if this is a view entity, do not check it... if (entity instanceof ModelViewEntity) { String entMessage = "NOT Checking View Entity " + entity.getEntityName(); Debug.logVerbose(entMessage, module); if (messages != null) messages.add(entMessage); continue; } // get existing index list for this table Set<String> tableIndexList = tableIndexListMap.get(entity.getTableName(datasourceInfo)); // Debug.logVerbose("Got ind info for table " + entity.getTableName(datasourceInfo) + ": " + tableIndexList, module); if (tableIndexList == null) { // evidently no indexes in the database for this table, do the create all if (checkFkIdx) { this.createForeignKeyIndices(entity, datasourceInfo.getConstraintNameClipLength(), messages); } if (datasourceInfo.getCheckIndicesOnStart()) { this.createDeclaredIndices(entity, messages); } continue; } // go through each relation to see if an FK already exists boolean createdConstraints = false; Iterator<ModelRelation> relations = entity.getRelationsIterator(); while (relations.hasNext()) { ModelRelation modelRelation = relations.next(); if (!"one".equals(modelRelation.getType())) { continue; } String relConstraintName = makeFkConstraintName(modelRelation, datasourceInfo.getConstraintNameClipLength()); if (tableIndexList.contains(relConstraintName)) { tableIndexList.remove(relConstraintName); } else { if (checkFkIdx) { // if not, create one String noIdxMessage = "No Index [" + relConstraintName + "] found for entity [" + entityName + "]"; if (messages != null) messages.add(noIdxMessage); if (Debug.infoOn()) Debug.logInfo(noIdxMessage, module); if (addMissing) { String errMsg = createForeignKeyIndex(entity, modelRelation, datasourceInfo.getConstraintNameClipLength()); if (UtilValidate.isNotEmpty(errMsg)) { String message = "Could not create foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg; Debug.logError(message, module); if (messages != null) messages.add(message); } else { String message = "Created foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]"; Debug.logVerbose(message, module); if (messages != null) messages.add(message); createdConstraints = true; numIndicesCreated++; } } } } } if (createdConstraints) { String message = "Created foreign key index/indices for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } // go through each indice to see if an indice already exists boolean createdIndexes = false; Iterator<ModelIndex> indexes = entity.getIndexesIterator(); while (indexes.hasNext()) { ModelIndex modelIndex = indexes.next(); String relIndexName = makeIndexName(modelIndex, datasourceInfo.getConstraintNameClipLength()); String checkIndexName = needsUpperCase[0] ? relIndexName.toUpperCase() : relIndexName; if (tableIndexList.contains(checkIndexName)) { tableIndexList.remove(checkIndexName); } else { if (datasourceInfo.getCheckIndicesOnStart()) { // if not, create one String noIdxMessage = "No Index [" + relIndexName + "] found for entity [" + entityName + "]"; if (messages != null) messages.add(noIdxMessage); if (Debug.infoOn()) Debug.logInfo(noIdxMessage, module); if (addMissing) { String errMsg = createDeclaredIndex(entity, modelIndex); if (UtilValidate.isNotEmpty(errMsg)) { String message = "Could not create index " + relIndexName + " for entity [" + entity.getEntityName() + "]: " + errMsg; Debug.logError(message, module); if (messages != null) messages.add(message); } else { String message = "Created index " + relIndexName + " for entity [" + entity.getEntityName() + "]"; Debug.logVerbose(message, module); if (messages != null) messages.add(message); createdIndexes = true; numIndicesCreated++; } } } } } if (createdIndexes) { String message = "Created declared index/indices for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } // show index key references that exist but are unknown if (tableIndexList != null) { for (String indexLeft: tableIndexList) { String message = "Unknown Index " + indexLeft + " found in table " + entity.getTableName(datasourceInfo); Debug.logImportant(message, module); if (messages != null) messages.add(message); } } } } if (numIndicesCreated > 0 && Debug.infoOn()) Debug.logInfo("Created " + numIndicesCreated + " indices", module); } executor.shutdown(); timer.timerString("Finished Checking Entity Database"); } /** Creates a list of ModelEntity objects based on meta data from the database */ public List<ModelEntity> induceModelFromDb(Collection<String> messages) { ExecutorService executor = Executors.newFixedThreadPool(datasourceInfo.getMaxWorkerPoolSize()); // get ALL tables from this database TreeSet<String> tableNames = this.getTableNames(messages); // get ALL column info, put into hashmap by table name Map<String, Map<String, ColumnCheckInfo>> colInfo = getColumnInfo(tableNames, true, messages, executor); // go through each table and make a ModelEntity object, add to list // for each entity make corresponding ModelField objects // then print out XML for the entities/fields List<ModelEntity> newEntList = new LinkedList<ModelEntity>(); boolean isCaseSensitive = getIsCaseSensitive(messages); // iterate over the table names is alphabetical order for (String tableName: new TreeSet<String>(colInfo.keySet())) { Map<String, ColumnCheckInfo> colMap = colInfo.get(tableName); ModelEntity newEntity = new ModelEntity(tableName, colMap, modelFieldTypeReader, isCaseSensitive); newEntList.add(newEntity); } executor.shutdown(); return newEntList; } private String getSchemaName(Collection<String> messages) throws SQLException { String schemaName; try (Connection connection = getConnectionLogged(messages)) { DatabaseMetaData dbData = this.getDatabaseMetaData(connection, messages); schemaName = getSchemaName(dbData); return schemaName; } } private boolean getIsCaseSensitive(Collection<String> messages) { boolean isCaseSensitive = false; try (Connection connection = getConnectionLogged(messages)) { DatabaseMetaData dbData = this.getDatabaseMetaData(connection, messages); if (dbData != null) { isCaseSensitive = dbData.supportsMixedCaseIdentifiers(); } } catch (SQLException e) { Debug.logError(e, "Error getting db meta data about case sensitive", module); } return isCaseSensitive; } public DatabaseMetaData getDatabaseMetaData(Connection connection, Collection<String> messages) { DatabaseMetaData dbData = null; try { dbData = connection.getMetaData(); } catch (SQLException e) { String message = "Unable to get database meta data... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) { messages.add(message); } return null; } if (dbData == null) { Debug.logWarning("Unable to get database meta data; method returned null", module); } return dbData; } private static final List<Detection> detections = new ArrayList<Detection>(); private static final String goodFormatStr; private static final String badFormatStr; private static class Detection { protected final String name; protected final boolean required; protected final Method method; protected final Object[] params; protected Detection(String name, boolean required, String methodName, Object... params) throws NoSuchMethodException { this.name = name; this.required = required; Class<?>[] paramTypes = new Class<?>[params.length]; for (int i = 0; i < params.length; i++) { Class<?> paramType = params[i].getClass(); if (paramType == Integer.class) { paramType = Integer.TYPE; } paramTypes[i] = paramType; } method = DatabaseMetaData.class.getMethod(methodName, paramTypes); this.params = params; } } static { try { detections.add(new Detection("supports transactions", true, "supportsTransactions")); detections.add(new Detection("isolation None", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_NONE)); detections.add(new Detection("isolation ReadCommitted", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_READ_COMMITTED)); detections.add(new Detection("isolation ReadUncommitted", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_READ_UNCOMMITTED)); detections.add(new Detection("isolation RepeatableRead", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_REPEATABLE_READ)); detections.add(new Detection("isolation Serializable", false, "supportsTransactionIsolationLevel", Connection.TRANSACTION_SERIALIZABLE)); detections.add(new Detection("forward only type", false, "supportsResultSetType", ResultSet.TYPE_FORWARD_ONLY)); detections.add(new Detection("scroll sensitive type", false, "supportsResultSetType", ResultSet.TYPE_SCROLL_SENSITIVE)); detections.add(new Detection("scroll insensitive type", false, "supportsResultSetType", ResultSet.TYPE_SCROLL_INSENSITIVE)); detections.add(new Detection("is case sensitive", false, "supportsMixedCaseIdentifiers")); detections.add(new Detection("stores LowerCase", false, "storesLowerCaseIdentifiers")); detections.add(new Detection("stores MixedCase", false, "storesMixedCaseIdentifiers")); detections.add(new Detection("stores UpperCase", false, "storesUpperCaseIdentifiers")); detections.add(new Detection("max table name length", false, "getMaxTableNameLength")); detections.add(new Detection("max column name length", false, "getMaxColumnNameLength")); detections.add(new Detection("concurrent connections", false, "getMaxConnections")); detections.add(new Detection("concurrent statements", false, "getMaxStatements")); detections.add(new Detection("ANSI SQL92 Entry", false, "supportsANSI92EntryLevelSQL")); detections.add(new Detection("ANSI SQL92 Intermediate", false, "supportsANSI92IntermediateSQL")); detections.add(new Detection("ANSI SQL92 Full", false, "supportsANSI92FullSQL")); detections.add(new Detection("ODBC SQL Grammar Core", false, "supportsCoreSQLGrammar")); detections.add(new Detection("ODBC SQL Grammar Extended", false, "supportsExtendedSQLGrammar")); detections.add(new Detection("ODBC SQL Grammar Minimum", false, "supportsMinimumSQLGrammar")); detections.add(new Detection("outer joins", true, "supportsOuterJoins")); detections.add(new Detection("limited outer joins", false, "supportsLimitedOuterJoins")); detections.add(new Detection("full outer joins", false, "supportsFullOuterJoins")); detections.add(new Detection("group by", true, "supportsGroupBy")); detections.add(new Detection("group by not in select", false, "supportsGroupByUnrelated")); detections.add(new Detection("column aliasing", false, "supportsColumnAliasing")); detections.add(new Detection("order by not in select", false, "supportsOrderByUnrelated")); detections.add(new Detection("alter table add column", true, "supportsAlterTableWithAddColumn")); detections.add(new Detection("non-nullable column", true, "supportsNonNullableColumns")); //detections.add(new Detection("", false, "", )); } catch (NoSuchMethodException e) { throw (InternalError) new InternalError(e.getMessage()).initCause(e); } int maxWidth = 0; for (Detection detection: detections) { if (detection.name.length() > maxWidth) { maxWidth = detection.name.length(); } } goodFormatStr = "- %-" + maxWidth + "s [%s]%s"; badFormatStr = "- %-" + maxWidth + "s [ DETECTION FAILED ]%s"; } public void printDbMiscData(DatabaseMetaData dbData, Connection con) { if (dbData == null) { return; } if (Debug.infoOn()) { // Database Info try { Debug.logInfo("Database Product Name is " + dbData.getDatabaseProductName(), module); Debug.logInfo("Database Product Version is " + dbData.getDatabaseProductVersion(), module); } catch (SQLException e) { Debug.logWarning("Unable to get Database name & version information", module); } // JDBC Driver Info try { Debug.logInfo("Database Driver Name is " + dbData.getDriverName(), module); Debug.logInfo("Database Driver Version is " + dbData.getDriverVersion(), module); Debug.logInfo("Database Driver JDBC Version is " + dbData.getJDBCMajorVersion() + "." + dbData.getJDBCMinorVersion(), module); } catch (SQLException e) { Debug.logWarning("Unable to get Driver name & version information", module); } catch (AbstractMethodError ame) { Debug.logWarning("Unable to get Driver JDBC Version", module); } // Db/Driver support settings Debug.logInfo("Database Setting/Support Information (those with a * should be true):", module); for (Detection detection: detections) { String requiredFlag = detection.required ? "*" : ""; try { Object result = detection.method.invoke(dbData, detection.params); Debug.logInfo(String.format(goodFormatStr, detection.name, result, requiredFlag), module); } catch (Exception e) { Debug.logVerbose(e, module); Debug.logWarning(String.format(badFormatStr, detection.name, requiredFlag), module); } } try { Debug.logInfo("- default fetchsize [" + con.createStatement().getFetchSize() + "]", module); } catch (Exception e) { Debug.logVerbose(e, module); Debug.logWarning("- default fetchsize [ DETECTION FAILED ]", module); } try { //this doesn't work in HSQLDB, other databases? //crashed (vm-death) with MS SQL Server 2000, runs properly with MS SQL Server 2005 //Debug.logInfo("- named parameters [" + dbData.supportsNamedParameters() + "]", module); Debug.logInfo("- named parameters [ SKIPPED ]", module); } catch (Exception e) { Debug.logVerbose(e, module); Debug.logWarning("- named parameters JDBC-3 [ DETECTION FAILED ]", module); } } } public TreeSet<String> getTableNames(Collection<String> messages) { Connection connection = getConnectionLogged(messages); if (connection == null) { String message = "Unable to establish a connection with the database, no additional information available."; Debug.logError(message, module); if (messages != null) messages.add(message); return null; } DatabaseMetaData dbData = this.getDatabaseMetaData(connection, messages); if (dbData == null) { return null; } printDbMiscData(dbData, connection); if (Debug.infoOn()) Debug.logInfo("Getting Table Info From Database", module); // get ALL tables from this database TreeSet<String> tableNames = new TreeSet<String>(); ResultSet tableSet = null; String lookupSchemaName = null; try { String[] types = {"TABLE", "BASE TABLE", "VIEW", "ALIAS", "SYNONYM"}; lookupSchemaName = getSchemaName(dbData); tableSet = dbData.getTables(null, lookupSchemaName, null, types); if (tableSet == null) { Debug.logWarning("getTables returned null set", module); } } catch (SQLException e) { String message = "Unable to get list of table information, let's try the create anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); try { connection.close(); } catch (SQLException e2) { String message2 = "Unable to close database connection, continuing anyway... Error was:" + e2.toString(); Debug.logError(message2, module); if (messages != null) messages.add(message2); } // we are returning an empty set here because databases like SapDB throw an exception when there are no tables in the database return tableNames; } try { boolean needsUpperCase = false; try { needsUpperCase = dbData.storesLowerCaseIdentifiers() || dbData.storesMixedCaseIdentifiers(); } catch (SQLException e) { String message = "Error getting identifier case information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } while (tableSet.next()) { try { String tableName = tableSet.getString("TABLE_NAME"); // for those databases which do not return the schema name with the table name (pgsql 7.3) boolean appendSchemaName = false; if (tableName != null && lookupSchemaName != null && !tableName.startsWith(lookupSchemaName + "\\.")) { appendSchemaName = true; } if (needsUpperCase && tableName != null) { tableName = tableName.toUpperCase(); } if (appendSchemaName) { tableName = lookupSchemaName + "." + tableName; } // NOTE: this may need a toUpperCase in some cases, keep an eye on it, okay for now just do a compare with equalsIgnoreCase String tableType = tableSet.getString("TABLE_TYPE"); // only allow certain table types if (tableType != null && !"TABLE".equalsIgnoreCase(tableType) && !"VIEW".equalsIgnoreCase(tableType) && !"ALIAS".equalsIgnoreCase(tableType) && !"SYNONYM".equalsIgnoreCase(tableType) && !"BASE TABLE".equalsIgnoreCase(tableType)) { continue; } // String remarks = tableSet.getString("REMARKS"); tableNames.add(tableName); // if (Debug.infoOn()) Debug.logInfo("Found table named [" + tableName + "] of type [" + tableType + "] with remarks: " + remarks, module); } catch (SQLException e) { String message = "Error getting table information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } } catch (SQLException e) { String message = "Error getting next table information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } finally { try { tableSet.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for table list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } try { connection.close(); } catch (SQLException e) { String message = "Unable to close database connection, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } return tableNames; } private AbstractCountingCallable createPrimaryKeyFetcher(final DatabaseMetaData dbData, final String lookupSchemaName, final boolean needsUpperCase, final Map<String, Map<String, ColumnCheckInfo>> colInfo, final Collection<String> messages, final String curTable) { return new AbstractCountingCallable(null, null) { public AbstractCountingCallable call() throws Exception { if (Debug.verboseOn()) Debug.logVerbose("Fetching primary keys for " + curTable, module); ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, curTable); count = checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); return this; } }; } private Map<String, Map<String, ColumnCheckInfo>> getColumnInfo(Set<String> tableNames, boolean getPks, Collection<String> messages, ExecutorService executor) { // if there are no tableNames, don't even try to get the columns if (tableNames.size() == 0) { return new HashMap<String, Map<String, ColumnCheckInfo>>(); } Connection connection = null; try { connection = getConnectionLogged(messages); if (connection == null) { return null; } DatabaseMetaData dbData = null; try { dbData = connection.getMetaData(); } catch (SQLException e) { String message = "Unable to get database meta data... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); try { connection.close(); } catch (SQLException e2) { String message2 = "Unable to close database connection, continuing anyway... Error was:" + e2.toString(); Debug.logError(message2, module); if (messages != null) messages.add(message2); } return null; } if (Debug.infoOn()) Debug.logInfo("Getting Column Info From Database", module); Map<String, Map<String, ColumnCheckInfo>> colInfo = new HashMap<String, Map<String, ColumnCheckInfo>>(); try { String lookupSchemaName = getSchemaName(dbData); boolean needsUpperCase = false; try { needsUpperCase = dbData.storesLowerCaseIdentifiers() || dbData.storesMixedCaseIdentifiers(); } catch (SQLException e) { String message = "Error getting identifier case information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } boolean foundCols = false; ResultSet rsCols = dbData.getColumns(null, lookupSchemaName, null, null); if (!rsCols.next()) { try { rsCols.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for column list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } rsCols = dbData.getColumns(null, lookupSchemaName, "%", "%"); if (!rsCols.next()) { // TODO: now what to do? I guess try one table name at a time... } else { foundCols = true; } } else { foundCols = true; } if (foundCols) { do { try { ColumnCheckInfo ccInfo = new ColumnCheckInfo(); ccInfo.tableName = ColumnCheckInfo.fixupTableName(rsCols.getString("TABLE_NAME"), lookupSchemaName, needsUpperCase); // ignore the column info if the table name is not in the list we are concerned with if (!tableNames.contains(ccInfo.tableName)) { continue; } ccInfo.columnName = rsCols.getString("COLUMN_NAME"); if (needsUpperCase && ccInfo.columnName != null) { ccInfo.columnName = ccInfo.columnName.toUpperCase(); } // NOTE: this may need a toUpperCase in some cases, keep an eye on it ccInfo.typeName = rsCols.getString("TYPE_NAME"); ccInfo.columnSize = rsCols.getInt("COLUMN_SIZE"); ccInfo.decimalDigits = rsCols.getInt("DECIMAL_DIGITS"); // NOTE: this may need a toUpperCase in some cases, keep an eye on it ccInfo.isNullable = rsCols.getString("IS_NULLABLE"); Map<String, ColumnCheckInfo> tableColInfo = colInfo.get(ccInfo.tableName); if (tableColInfo == null) { tableColInfo = new HashMap<String, ColumnCheckInfo>(); colInfo.put(ccInfo.tableName, tableColInfo); } tableColInfo.put(ccInfo.columnName, ccInfo); } catch (SQLException e) { String message = "Error getting column info for column. Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } while (rsCols.next()); } try { rsCols.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for column list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } if (getPks) { int pkCount = 0; // first try getting all at once for databases that support that and can generally perform WAY better, if that fails get one at a time so it will at least work try (ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, null)) { pkCount += checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); } catch (Exception e1) { Debug.logInfo("Error getting primary key info from database with null tableName, will try other means: " + e1.toString(), module); } if (pkCount == 0) { try (ResultSet rsPks = dbData.getPrimaryKeys(null, lookupSchemaName, "%")) { pkCount += checkPrimaryKeyInfo(rsPks, lookupSchemaName, needsUpperCase, colInfo, messages); } catch (Exception e1) { Debug.logInfo("Error getting primary key info from database with % tableName, will try other means: " + e1.toString(), module); } } if (pkCount == 0) { Debug.logInfo("Searching in " + tableNames.size() + " tables for primary key fields ...", module); List<Future<AbstractCountingCallable>> pkFetcherFutures = new LinkedList<Future<AbstractCountingCallable>>(); for (String curTable: tableNames) { curTable = curTable.substring(curTable.indexOf('.') + 1); //cut off schema name pkFetcherFutures.add(executor.submit(createPrimaryKeyFetcher(dbData, lookupSchemaName, needsUpperCase, colInfo, messages, curTable))); } for (AbstractCountingCallable pkFetcherCallable: ExecutionPool.getAllFutures(pkFetcherFutures)) { pkCount += pkFetcherCallable.updateData(messages); } } Debug.logInfo("Reviewed " + pkCount + " primary key fields from database.", module); } } catch (SQLException e) { String message = "Error getting column meta data for Error was: [" + e.toString() + "]. Not checking columns."; Debug.logError(e, message, module); if (messages != null) messages.add(message); // we are returning an empty set in this case because databases like SapDB throw an exception when there are no tables in the database // colInfo = null; } return colInfo; } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { String message = "Unable to close database connection, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } } } public int checkPrimaryKeyInfo(ResultSet rsPks, String lookupSchemaName, boolean needsUpperCase, Map<String, Map<String, ColumnCheckInfo>> colInfo, Collection<String> messages) throws SQLException { int pkCount = 0; while (rsPks.next()) { pkCount++; try { String tableName = ColumnCheckInfo.fixupTableName(rsPks.getString("TABLE_NAME"), lookupSchemaName, needsUpperCase); String columnName = rsPks.getString("COLUMN_NAME"); if (needsUpperCase && columnName != null) { columnName = columnName.toUpperCase(); } Map<String, ColumnCheckInfo> tableColInfo = colInfo.get(tableName); if (tableColInfo == null) { // not looking for info on this table continue; } ColumnCheckInfo ccInfo = tableColInfo.get(columnName); if (ccInfo == null) { // this isn't good, what to do? Debug.logWarning("Got primary key information for a column that we didn't get column information for: tableName=[" + tableName + "], columnName=[" + columnName + "]", module); continue; } // KEY_SEQ short => sequence number within primary key // PK_NAME String => primary key name (may be null) ccInfo.isPk = true; ccInfo.pkSeq = rsPks.getShort("KEY_SEQ"); ccInfo.pkName = rsPks.getString("PK_NAME"); } catch (SQLException e) { String message = "Error getting primary key info for column. Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } return pkCount; } public Map<String, Map<String, ReferenceCheckInfo>> getReferenceInfo(Set<String> tableNames, Collection<String> messages) { Connection connection = getConnectionLogged(messages); if (connection == null) { return null; } DatabaseMetaData dbData = null; try { dbData = connection.getMetaData(); } catch (SQLException e) { String message = "Unable to get database meta data... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); try { connection.close(); } catch (SQLException e2) { String message2 = "Unable to close database connection, continuing anyway... Error was:" + e2.toString(); Debug.logError(message2, module); if (messages != null) messages.add(message2); } return null; } /* try { if (Debug.infoOn()) Debug.logInfo("Database Product Name is " + dbData.getDatabaseProductName(), module); if (Debug.infoOn()) Debug.logInfo("Database Product Version is " + dbData.getDatabaseProductVersion(), module); } catch (SQLException e) { Debug.logWarning("Unable to get Database name & version information", module); } try { if (Debug.infoOn()) Debug.logInfo("Database Driver Name is " + dbData.getDriverName(), module); if (Debug.infoOn()) Debug.logInfo("Database Driver Version is " + dbData.getDriverVersion(), module); } catch (SQLException e) { Debug.logWarning("Unable to get Driver name & version information", module); } */ if (Debug.infoOn()) Debug.logInfo("Getting Foreign Key (Reference) Info From Database", module); Map<String, Map<String, ReferenceCheckInfo>> refInfo = new HashMap<String, Map<String, ReferenceCheckInfo>>(); try { // ResultSet rsCols = dbData.getCrossReference(null, null, null, null, null, null); String lookupSchemaName = getSchemaName(dbData); boolean needsUpperCase = false; try { needsUpperCase = dbData.storesLowerCaseIdentifiers() || dbData.storesMixedCaseIdentifiers(); } catch (SQLException e) { String message = "Error getting identifier case information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } ResultSet rsCols = dbData.getImportedKeys(null, lookupSchemaName, null); int totalFkRefs = 0; // Iterator tableNamesIter = tableNames.iterator(); // while (tableNamesIter.hasNext()) { // String tableName = (String) tableNamesIter.next(); // ResultSet rsCols = dbData.getImportedKeys(null, null, tableName); // Debug.logVerbose("Getting imported keys for table " + tableName, module); while (rsCols.next()) { try { ReferenceCheckInfo rcInfo = new ReferenceCheckInfo(); rcInfo.pkTableName = rsCols.getString("PKTABLE_NAME"); if (needsUpperCase && rcInfo.pkTableName != null) { rcInfo.pkTableName = rcInfo.pkTableName.toUpperCase(); } rcInfo.pkColumnName = rsCols.getString("PKCOLUMN_NAME"); if (needsUpperCase && rcInfo.pkColumnName != null) { rcInfo.pkColumnName = rcInfo.pkColumnName.toUpperCase(); } rcInfo.fkTableName = rsCols.getString("FKTABLE_NAME"); if (needsUpperCase && rcInfo.fkTableName != null) { rcInfo.fkTableName = rcInfo.fkTableName.toUpperCase(); } // ignore the column info if the FK table name is not in the list we are concerned with if (!tableNames.contains(rcInfo.fkTableName)) { continue; } rcInfo.fkColumnName = rsCols.getString("FKCOLUMN_NAME"); if (needsUpperCase && rcInfo.fkColumnName != null) { rcInfo.fkColumnName = rcInfo.fkColumnName.toUpperCase(); } rcInfo.fkName = rsCols.getString("FK_NAME"); if (needsUpperCase && rcInfo.fkName != null) { rcInfo.fkName = rcInfo.fkName.toUpperCase(); } if (Debug.verboseOn()) Debug.logVerbose("Got: " + rcInfo.toString(), module); Map<String, ReferenceCheckInfo> tableRefInfo = refInfo.get(rcInfo.fkTableName); if (tableRefInfo == null) { tableRefInfo = new HashMap<String, ReferenceCheckInfo>(); refInfo.put(rcInfo.fkTableName, tableRefInfo); if (Debug.verboseOn()) Debug.logVerbose("Adding new Map for table: " + rcInfo.fkTableName, module); } if (!tableRefInfo.containsKey(rcInfo.fkName)) totalFkRefs++; tableRefInfo.put(rcInfo.fkName, rcInfo); } catch (SQLException e) { String message = "Error getting fk reference info for table. Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } // if (Debug.infoOn()) Debug.logInfo("There are " + totalFkRefs + " in the database", module); try { rsCols.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for fk reference list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } // } if (Debug.infoOn()) Debug.logInfo("There are " + totalFkRefs + " foreign key refs in the database", module); } catch (SQLException e) { String message = "Error getting fk reference meta data Error was:" + e.toString() + ". Not checking fk refs."; Debug.logError(message, module); if (messages != null) messages.add(message); refInfo = null; } finally { try { connection.close(); } catch (SQLException e) { String message = "Unable to close database connection, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } return refInfo; } public Map<String, Set<String>> getIndexInfo(Set<String> tableNames, Collection<String> messages, boolean[] needsUpperCase) { Connection connection = getConnectionLogged(messages); if (connection == null) { return null; } DatabaseMetaData dbData = null; try { dbData = connection.getMetaData(); } catch (SQLException e) { String message = "Unable to get database meta data... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); try { connection.close(); } catch (SQLException e2) { String message2 = "Unable to close database connection, continuing anyway... Error was:" + e2.toString(); Debug.logError(message2, module); if (messages != null) messages.add(message2); } return null; } needsUpperCase[0] = false; try { needsUpperCase[0] = dbData.storesLowerCaseIdentifiers() || dbData.storesMixedCaseIdentifiers(); } catch (SQLException e) { String message = "Error getting identifier case information... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } if (Debug.infoOn()) Debug.logInfo("Getting Index Info From Database", module); Map<String, Set<String>> indexInfo = new HashMap<String, Set<String>>(); try { int totalIndices = 0; String lookupSchemaName = getSchemaName(dbData); for (String curTableName: tableNames) { if (lookupSchemaName != null) { curTableName = curTableName.substring(lookupSchemaName.length() + 1); } ResultSet rsCols = null; try { // false for unique, we don't really use unique indexes // true for approximate, don't really care if stats are up-to-date rsCols = dbData.getIndexInfo(null, lookupSchemaName, needsUpperCase[0] ? curTableName.toLowerCase() : curTableName, false, true); } catch (Exception e) { Debug.logWarning(e, "Error getting index info for table: " + curTableName + " using lookupSchemaName " + lookupSchemaName, module); } while (rsCols != null && rsCols.next()) { // NOTE: The code in this block may look funny, but it is designed so that the wrapping loop can be removed try { // skip all index info for statistics if (rsCols.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic) continue; // HACK: for now skip all "unique" indexes since our foreign key indices are not unique, but the primary key ones are // not correct, declared indices can also be unique // if (!rsCols.getBoolean("NON_UNIQUE")) continue; String tableName = rsCols.getString("TABLE_NAME"); if (needsUpperCase[0] && tableName != null) { tableName = tableName.toUpperCase(); } if (lookupSchemaName != null) { tableName = lookupSchemaName + '.' + tableName; } if (!tableNames.contains(tableName)) continue; String indexName = rsCols.getString("INDEX_NAME"); if (needsUpperCase[0] && indexName != null) { indexName = indexName.toUpperCase(); } if (indexName.startsWith("PK_") || indexName.startsWith("pk_")) continue; Set<String> tableIndexList = indexInfo.get(tableName); if (tableIndexList == null) { tableIndexList = new TreeSet<String>(); indexInfo.put(tableName, tableIndexList); if (Debug.verboseOn()) Debug.logVerbose("Adding new Map for table: " + tableName, module); } // Need the check here, because an index can contain multiple columns, // and this is represented by having multiple rows in rsCols. if (!tableIndexList.contains(indexName)) totalIndices++; tableIndexList.add(indexName); } catch (SQLException e) { String message = "Error getting fk reference info for table. Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); continue; } } // if (Debug.infoOn()) Debug.logInfo("There are " + totalIndices + " indices in the database", module); if (rsCols != null) { try { rsCols.close(); } catch (SQLException e) { String message = "Unable to close ResultSet for fk reference list, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } } if (Debug.infoOn()) Debug.logInfo("There are " + totalIndices + " indices in the database", module); } catch (SQLException e) { String message = "Error getting fk reference meta data Error was:" + e.toString() + ". Not checking fk refs."; Debug.logError(message, module); if (messages != null) messages.add(message); indexInfo = null; } finally { try { connection.close(); } catch (SQLException e) { String message = "Unable to close database connection, continuing anyway... Error was:" + e.toString(); Debug.logError(message, module); if (messages != null) messages.add(message); } } return indexInfo; } private class CreateTableCallable implements Callable<CreateTableCallable> { private final ModelEntity entity; private final Map<String, ModelEntity> modelEntities; private final String tableName; private String message; private boolean success; protected CreateTableCallable(ModelEntity entity, Map<String, ModelEntity> modelEntities, String tableName) { this.entity = entity; this.modelEntities = modelEntities; this.tableName = tableName; } public CreateTableCallable call() throws Exception { String errMsg = createTable(entity, modelEntities, false); if (UtilValidate.isNotEmpty(errMsg)) { this.success = false; this.message = "Could not create table [" + tableName + "]: " + errMsg; Debug.logError(this.message, module); } else { this.success = true; this.message = "Created table [" + tableName + "]"; Debug.logImportant(this.message, module); } return this; } protected void updateData(Collection<String> messages, List<ModelEntity> entitiesAdded) { if (this.success) { entitiesAdded.add(entity); if (messages != null) { messages.add(this.message); } } else { if (messages != null) { messages.add(this.message); } } } } private abstract class AbstractCountingCallable implements Callable<AbstractCountingCallable> { protected final ModelEntity entity; protected final Map<String, ModelEntity> modelEntities; protected final List<String> messages = new LinkedList<String>(); protected int count; protected AbstractCountingCallable(ModelEntity entity, Map<String, ModelEntity> modelEntities) { this.entity = entity; this.modelEntities = modelEntities; } protected int updateData(Collection<String> messages) { // SCIPIO: there were 2 errors here; only 1 was fixed by ofbiz 16 //if (messages != null && UtilValidate.isNotEmpty(this.messages)) { // messages.addAll(messages); //} if (UtilValidate.isNotEmpty(messages)) { this.messages.addAll(messages); } return count; } } /* ====================================================================== */ /* ====================================================================== */ public String createTable(ModelEntity entity, Map<String, ModelEntity> modelEntities, boolean addFks) { if (entity == null) { return "ModelEntity was null and is required to create a table"; } if (entity instanceof ModelViewEntity) { return "ERROR: Cannot create table for a view entity"; } StringBuilder sqlBuf = new StringBuilder("CREATE TABLE "); sqlBuf.append(entity.getTableName(this.datasourceInfo)); sqlBuf.append(" ("); Iterator<ModelField> fieldIter = entity.getFieldsIterator(); while (fieldIter.hasNext()) { ModelField field = fieldIter.next(); ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table."; } sqlBuf.append(field.getColName()); sqlBuf.append(" "); sqlBuf.append(type.getSqlType()); if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) { // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlBuf.append(" CHARACTER SET "); sqlBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlBuf.append(" COLLATE "); sqlBuf.append(this.datasourceInfo.getCollate()); } } if (field.getIsNotNull() || field.getIsPk()) { if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) { sqlBuf.append(" CONSTRAINT NOT NULL, "); } else { sqlBuf.append(" NOT NULL, "); } } else { sqlBuf.append(", "); } } String pkName = makePkConstraintName(entity, this.datasourceInfo.getConstraintNameClipLength()); if (this.datasourceInfo.getUsePkConstraintNames()) { sqlBuf.append("CONSTRAINT "); sqlBuf.append(pkName); } sqlBuf.append(" PRIMARY KEY ("); entity.colNameString(entity.getPkFieldsUnmodifiable(), sqlBuf, ""); sqlBuf.append(")"); if (addFks) { // NOTE: This is kind of a bad idea anyway since ordering table creations is crazy, if not impossible // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { Debug.logError("Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(), module); continue; } if (relModelEntity instanceof ModelViewEntity) { Debug.logError("Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(), module); continue; } String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, this.datasourceInfo.getConstraintNameClipLength(), this.datasourceInfo.getFkStyle(), this.datasourceInfo.getUseFkInitiallyDeferred()); if (UtilValidate.isNotEmpty(fkConstraintClause)) { sqlBuf.append(", "); sqlBuf.append(fkConstraintClause); } else { continue; } } } } sqlBuf.append(")"); // if there is a tableType, add the TYPE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getTableType())) { // jaz:20101229 - This appears to be only used by mysql and now mysql has // deprecated (and in 5.5.x removed) the use of the TYPE keyword. This is // changed to ENGINE which is supported starting at 4.1 sqlBuf.append(" ENGINE "); //sqlBuf.append(" TYPE "); sqlBuf.append(this.datasourceInfo.getTableType()); } // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlBuf.append(" CHARACTER SET "); sqlBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlBuf.append(" COLLATE "); sqlBuf.append(this.datasourceInfo.getCollate()); } // if there is a rowFormat, add the ROW_FORMAT arg here (only intended for MariaDB and MySQL) if (UtilValidate.isNotEmpty(this.datasourceInfo.getRowFormat()) && !this.datasourceInfo.getRowFormat().equals("none")) { sqlBuf.append(" ROW_FORMAT "); sqlBuf.append(this.datasourceInfo.getRowFormat()); } if (Debug.verboseOn()) Debug.logVerbose("[createTable] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public void deleteTable(ModelEntity entity, List<String> messages) { if (entity == null) { String errMsg = "ModelEntity was null and is required to delete a table"; Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); return; } if (entity instanceof ModelViewEntity) { //String errMsg = "ERROR: Cannot delete table for a view entity"; //Debug.logError(errMsg, module); //if (messages != null) messages.add(errMsg); return; } String message = "Deleting table for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); StringBuilder sqlBuf = new StringBuilder("DROP TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); if (Debug.verboseOn()) Debug.logVerbose("[deleteTable] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnectionLogged(messages); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); } } public String addColumn(ModelEntity entity, ModelField field) { if (entity == null || field == null) return "ModelEntity or ModelField where null, cannot add column"; if (entity instanceof ModelViewEntity) { return "ERROR: Cannot add column for a view entity"; } ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not adding column."; } StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" ADD "); sqlBuf.append(field.getColName()); sqlBuf.append(" "); sqlBuf.append(type.getSqlType()); if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) { // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlBuf.append(" CHARACTER SET "); sqlBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlBuf.append(" COLLATE "); sqlBuf.append(this.datasourceInfo.getCollate()); } } String sql = sqlBuf.toString(); if (Debug.infoOn()) Debug.logInfo("[addColumn] sql=" + sql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql); } catch (SQLException e) { // if that failed try the alternate syntax real quick StringBuilder sql2Buf = new StringBuilder("ALTER TABLE "); sql2Buf.append(entity.getTableName(datasourceInfo)); sql2Buf.append(" ADD COLUMN "); sql2Buf.append(field.getColName()); sql2Buf.append(" "); sql2Buf.append(type.getSqlType()); if ("String".equals(type.getJavaType()) || "java.lang.String".equals(type.getJavaType())) { // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sql2Buf.append(" CHARACTER SET "); sql2Buf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sql2Buf.append(" COLLATE "); sql2Buf.append(this.datasourceInfo.getCollate()); } } String sql2 = sql2Buf.toString(); if (Debug.infoOn()) Debug.logInfo("[addColumn] sql failed, trying sql2=" + sql2, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql2); } catch (SQLException e2) { // if this also fails report original error, not this error... return "SQL Exception while executing the following:\n" + sql + "\nError was: " + e2.toString(); } catch (GenericEntityException e2) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e2.toString(); Debug.logError(e2, errMsg, module); return errMsg; } } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String renameColumn(ModelEntity entity, ModelField field, String newName) { if (entity == null || field == null) return "ModelEntity or ModelField where null, cannot rename column"; if (entity instanceof ModelViewEntity) { return "ERROR: Cannot rename column for a view entity"; } ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { return "Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not renaming column."; } StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" RENAME "); sqlBuf.append(field.getColName()); sqlBuf.append(" TO "); sqlBuf.append(newName); String sql = sqlBuf.toString(); if (Debug.infoOn()) Debug.logInfo("[renameColumn] sql=" + sql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public void repairColumnSize(ModelEntity entity, ModelField field, List<String> messages) { // first rename the column String tempName = makeTempFieldName(field); String renamedErr = renameColumn(entity, field, tempName); if (UtilValidate.isNotEmpty(renamedErr)) { if (messages != null) messages.add(renamedErr); Debug.logError(renamedErr, module); return; } // next add back in the column String addedErr = addColumn(entity, field); if (UtilValidate.isNotEmpty(addedErr)) { if (messages != null) messages.add(addedErr); Debug.logError(addedErr, module); return; } // copy the data from old to new StringBuilder sqlBuf1 = new StringBuilder("UPDATE "); sqlBuf1.append(entity.getTableName(datasourceInfo)); sqlBuf1.append(" SET "); sqlBuf1.append(field.getColName()); sqlBuf1.append(" = "); sqlBuf1.append(tempName); String sql1 = sqlBuf1.toString(); if (Debug.infoOn()) Debug.logInfo("[moveData] sql=" + sql1, module); try (Connection connection = getConnectionLogged(messages); Statement stmt = connection.createStatement()) { int changed = stmt.executeUpdate(sql1); if (Debug.infoOn()) Debug.logInfo("[moveData] " + changed + " records updated", module); } catch (SQLException e) { String thisMsg = "SQL Exception while executing the following:\n" + sql1 + "\nError was: " + e.toString(); if (messages != null) messages.add(thisMsg); Debug.logError(thisMsg, module); return; } // remove the old column StringBuilder sqlBuf2 = new StringBuilder("ALTER TABLE "); sqlBuf2.append(entity.getTableName(datasourceInfo)); sqlBuf2.append(" DROP COLUMN "); sqlBuf2.append(tempName); String sql2 = sqlBuf2.toString(); if (Debug.infoOn()) Debug.logInfo("[dropColumn] sql=" + sql2, module); try (Connection connection = getConnectionLogged(messages); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sql2); } catch (SQLException e) { String thisMsg = "SQL Exception while executing the following:\n" + sql2 + "\nError was: " + e.toString(); if (messages != null) messages.add(thisMsg); Debug.logError(thisMsg, module); return; } } public void repairColumnSizeChanges(Map<String, ModelEntity> modelEntities, List<String> fieldsWrongSize, List<String> messages) { if (modelEntities == null || UtilValidate.isEmpty(fieldsWrongSize)) { messages.add("No fields to repair"); return; } if (messages == null) messages = new ArrayList<String>(); for (String fieldInfo: fieldsWrongSize) { String entityName = fieldInfo.substring(0, fieldInfo.indexOf('.')); String fieldName = fieldInfo.substring(fieldInfo.indexOf('.') + 1); ModelEntity modelEntity = modelEntities.get(entityName); ModelField modelField = modelEntity.getField(fieldName); repairColumnSize(modelEntity, modelField, messages); } } private String makeTempFieldName(ModelField field) { String tempName = "tmp_" + field.getName(); if (tempName.length() > 30) { tempName = tempName.substring(0, 30); } return tempName.toUpperCase(); } /* ====================================================================== */ /* ====================================================================== */ public String makePkConstraintName(ModelEntity entity, int constraintNameClipLength) { String pkName = "PK_" + entity.getPlainTableName(); if (pkName.length() > constraintNameClipLength) { pkName = pkName.substring(0, constraintNameClipLength); } return pkName; } public String makeFkConstraintName(ModelRelation modelRelation, int constraintNameClipLength) { String relConstraintName = modelRelation.getFkName(); if (UtilValidate.isEmpty(relConstraintName)) { relConstraintName = modelRelation.getTitle() + modelRelation.getRelEntityName(); relConstraintName = relConstraintName.toUpperCase(); } if (relConstraintName.length() > constraintNameClipLength) { relConstraintName = relConstraintName.substring(0, constraintNameClipLength); } return relConstraintName; } /* ====================================================================== */ public String makeIndexName(ModelIndex modelIndex, int constraintNameClipLength) { String indexName = modelIndex.getName(); if (indexName.length() > constraintNameClipLength) { indexName = indexName.substring(0, constraintNameClipLength); } return indexName; } /* ====================================================================== */ public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, List<String> messages) { return this.createForeignKeys(entity, modelEntities, datasourceInfo.getConstraintNameClipLength(), datasourceInfo.getFkStyle(), datasourceInfo.getUseFkInitiallyDeferred(), messages); } public int createForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred, List<String> messages) { if (entity == null) { String errMsg = "ModelEntity was null and is required to create foreign keys for a table"; Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); return 0; } if (entity instanceof ModelViewEntity) { //String errMsg = "ERROR: Cannot create foreign keys for a view entity"; //Debug.logError(errMsg, module); //if (messages != null) messages.add(errMsg); return 0; } int fksCreated = 0; // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { String errMsg = "Error adding foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(); Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); continue; } if (relModelEntity instanceof ModelViewEntity) { String errMsg = "Error adding foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(); Debug.logError(errMsg, module); if (messages != null) messages.add(errMsg); continue; } String retMsg = createForeignKey(entity, modelRelation, relModelEntity, constraintNameClipLength, fkStyle, useFkInitiallyDeferred); if (UtilValidate.isNotEmpty(retMsg)) { Debug.logError(retMsg, module); if (messages != null) messages.add(retMsg); continue; } fksCreated++; } } if (fksCreated > 0) { String message = "Created " + fksCreated + " foreign keys for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } return fksCreated; } public String createForeignKey(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred) { // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" ADD "); String fkConstraintClause = makeFkConstraintClause(entity, modelRelation, relModelEntity, constraintNameClipLength, fkStyle, useFkInitiallyDeferred); if (UtilValidate.isEmpty(fkConstraintClause)) { return "Error creating foreign key constraint clause, see log for details"; } sqlBuf.append(fkConstraintClause); if (Debug.verboseOn()) Debug.logVerbose("[createForeignKey] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String makeFkConstraintClause(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength, String fkStyle, boolean useFkInitiallyDeferred) { // make the two column lists StringBuilder mainCols = new StringBuilder(); StringBuilder relCols = new StringBuilder(); for (ModelKeyMap keyMap : modelRelation.getKeyMaps()) { ModelField mainField = entity.getField(keyMap.getFieldName()); if (mainField == null) { Debug.logError("Bad key-map in entity [" + entity.getEntityName() + "] relation to [" + modelRelation.getTitle() + modelRelation.getRelEntityName() + "] for field [" + keyMap.getFieldName() + "]", module); return null; } if (mainCols.length() > 0) { mainCols.append(", "); } mainCols.append(mainField.getColName()); ModelField relField = relModelEntity.getField(keyMap.getRelFieldName()); if (relField == null) { Debug.logError("The field '" + keyMap.getRelFieldName() + "' was not found at related entity - check relations at entity '" + entity.getEntityName() + "'!", module); } if (relCols.length() > 0) { relCols.append(", "); } relCols.append(relField.getColName()); } StringBuilder sqlBuf = new StringBuilder(""); if ("name_constraint".equals(fkStyle)) { sqlBuf.append("CONSTRAINT "); String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); sqlBuf.append(relConstraintName); sqlBuf.append(" FOREIGN KEY ("); sqlBuf.append(mainCols.toString()); sqlBuf.append(") REFERENCES "); sqlBuf.append(relModelEntity.getTableName(datasourceInfo)); sqlBuf.append(" ("); sqlBuf.append(relCols.toString()); sqlBuf.append(")"); if (useFkInitiallyDeferred) { sqlBuf.append(" INITIALLY DEFERRED"); } } else if ("name_fk".equals(fkStyle)) { sqlBuf.append(" FOREIGN KEY "); String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); sqlBuf.append(relConstraintName); sqlBuf.append(" ("); sqlBuf.append(mainCols.toString()); sqlBuf.append(") REFERENCES "); sqlBuf.append(relModelEntity.getTableName(datasourceInfo)); sqlBuf.append(" ("); sqlBuf.append(relCols.toString()); sqlBuf.append(")"); if (useFkInitiallyDeferred) { sqlBuf.append(" INITIALLY DEFERRED"); } } else { String emsg = "ERROR: fk-style specified for this data-source is not valid: " + fkStyle; Debug.logError(emsg, module); throw new IllegalArgumentException(emsg); } return sqlBuf.toString(); } public void deleteForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, List<String> messages) { this.deleteForeignKeys(entity, modelEntities, datasourceInfo.getConstraintNameClipLength(), messages); } public void deleteForeignKeys(ModelEntity entity, Map<String, ModelEntity> modelEntities, int constraintNameClipLength, List<String> messages) { if (entity == null) { String errMsg = "ModelEntity was null and is required to delete foreign keys for a table"; if (messages != null) messages.add(errMsg); Debug.logError(errMsg, module); return; } if (entity instanceof ModelViewEntity) { //String errMsg = "ERROR: Cannot delete foreign keys for a view entity"; //if (messages != null) messages.add(errMsg); //Debug.logError(errMsg, module); return; } String message = "Deleting foreign keys for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName()); if (relModelEntity == null) { String errMsg = "Error removing foreign key: ModelEntity was null for related entity name " + modelRelation.getRelEntityName(); if (messages != null) messages.add(errMsg); Debug.logError(errMsg, module); continue; } if (relModelEntity instanceof ModelViewEntity) { String errMsg = "Error removing foreign key: related entity is a view entity for related entity name " + modelRelation.getRelEntityName(); if (messages != null) messages.add(errMsg); Debug.logError(errMsg, module); continue; } String retMsg = deleteForeignKey(entity, modelRelation, relModelEntity, constraintNameClipLength); if (UtilValidate.isNotEmpty(retMsg)) { if (messages != null) messages.add(retMsg); Debug.logError(retMsg, module); } } } } public String deleteForeignKey(ModelEntity entity, ModelRelation modelRelation, ModelEntity relModelEntity, int constraintNameClipLength) { String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); if (datasourceInfo.getDropFkUseForeignKeyKeyword()) { sqlBuf.append(" DROP FOREIGN KEY "); } else { sqlBuf.append(" DROP CONSTRAINT "); } sqlBuf.append(relConstraintName); if (Debug.verboseOn()) Debug.logVerbose("[deleteForeignKey] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } /* ====================================================================== */ /* ====================================================================== */ public void createPrimaryKey(ModelEntity entity, boolean usePkConstraintNames, int constraintNameClipLength, List<String> messages) { if (messages == null) messages = new ArrayList<String>(); String err = createPrimaryKey(entity, usePkConstraintNames, constraintNameClipLength); if (UtilValidate.isNotEmpty(err)) { messages.add(err); } } public void createPrimaryKey(ModelEntity entity, boolean usePkConstraintNames, List<String> messages) { createPrimaryKey(entity, usePkConstraintNames, datasourceInfo.getConstraintNameClipLength(), messages); } public void createPrimaryKey(ModelEntity entity, List<String> messages) { createPrimaryKey(entity, datasourceInfo.getUsePkConstraintNames(), messages); } public String createPrimaryKey(ModelEntity entity, boolean usePkConstraintNames, int constraintNameClipLength) { if (entity == null) { return "ModelEntity was null and is required to create the primary key for a table"; } if (entity instanceof ModelViewEntity) { return "Ignoring view entity [" + entity.getEntityName() + "]"; } String message; if (entity.getPksSize() > 0) { message = "Creating primary key for entity [" + entity.getEntityName() + "]"; // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" ADD "); String pkName = makePkConstraintName(entity, constraintNameClipLength); if (usePkConstraintNames) { sqlBuf.append("CONSTRAINT "); sqlBuf.append(pkName); } sqlBuf.append(" PRIMARY KEY ("); entity.colNameString(entity.getPkFieldsUnmodifiable(), sqlBuf, ""); sqlBuf.append(")"); if (Debug.verboseOn()) Debug.logVerbose("[createPrimaryKey] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { return "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); } catch (GenericEntityException e) { return "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); } } else { message = "No primary-key defined for table [" + entity.getEntityName() + "]"; } Debug.logImportant(message, module); return message; } public void deletePrimaryKey(ModelEntity entity, boolean usePkConstraintNames, int constraintNameClipLength, List<String> messages) { if (messages == null) messages = new ArrayList<String>(); String err = deletePrimaryKey(entity, usePkConstraintNames, constraintNameClipLength); if (UtilValidate.isNotEmpty(err)) { messages.add(err); } } public void deletePrimaryKey(ModelEntity entity, boolean usePkConstraintNames, List<String> messages) { deletePrimaryKey(entity, usePkConstraintNames, datasourceInfo.getConstraintNameClipLength(), messages); } public void deletePrimaryKey(ModelEntity entity, List<String> messages) { deletePrimaryKey(entity, datasourceInfo.getUsePkConstraintNames(), messages); } public String deletePrimaryKey(ModelEntity entity, boolean usePkConstraintNames, int constraintNameClipLength) { if (entity == null) { return "ModelEntity was null and is required to delete the primary key for a table"; } if (entity instanceof ModelViewEntity) { return "Ignoring view entity [" + entity.getEntityName() + "]"; } String message; if (entity.getPksSize() > 0) { message = "Deleting primary key for entity [" + entity.getEntityName() + "]"; // now add constraint clause StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(datasourceInfo)); sqlBuf.append(" DROP "); String pkName = makePkConstraintName(entity, constraintNameClipLength); if (usePkConstraintNames) { sqlBuf.append("CONSTRAINT "); sqlBuf.append(pkName); sqlBuf.append(" CASCADE"); } else { sqlBuf.append(" PRIMARY KEY"); // DEJ20050502 not sure why this is here, shouldn't be needed and some dbs don't support like this, ie when used with PRIMARY KEY: sqlBuf.append(" CASCADE"); } if (Debug.verboseOn()) Debug.logVerbose("[deletePrimaryKey] sql=" + sqlBuf.toString(), module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf.toString() + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } } else { message = "No primary-key defined for table [" + entity.getEntityName() + "]"; } Debug.logImportant(message, module); return message; } /* ====================================================================== */ /* ====================================================================== */ public int createDeclaredIndices(ModelEntity entity, List<String> messages) { if (entity == null) { String message = "ModelEntity was null and is required to create declared indices for a table"; Debug.logError(message, module); if (messages != null) messages.add(message); return 0; } if (entity instanceof ModelViewEntity) { String message = "Cannot create declared indices for a view entity"; Debug.logWarning(message, module); if (messages != null) messages.add(message); return 0; } int dinsCreated = 0; // go through the indexes to see if any need to be added Iterator<ModelIndex> indexesIter = entity.getIndexesIterator(); while (indexesIter.hasNext()) { ModelIndex modelIndex = indexesIter.next(); String retMsg = createDeclaredIndex(entity, modelIndex); if (UtilValidate.isNotEmpty(retMsg)) { String message = "Could not create declared indices for entity [" + entity.getEntityName() + "]: " + retMsg; Debug.logError(message, module); if (messages != null) messages.add(message); continue; } dinsCreated++; } if (dinsCreated > 0) { String message = "Created " + dinsCreated + " declared indices for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } return dinsCreated; } public String createDeclaredIndex(ModelEntity entity, ModelIndex modelIndex) { String createIndexSql = makeIndexClause(entity, modelIndex); if (Debug.verboseOn()) Debug.logVerbose("[createForeignKeyIndex] index sql=" + createIndexSql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(createIndexSql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + createIndexSql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String makeIndexClause(ModelEntity entity, ModelIndex modelIndex) { StringBuilder mainCols = new StringBuilder(); for (ModelIndex.Field field : modelIndex.getFields()) { ModelIndex.Function function = field.getFunction(); if (mainCols.length() > 0) { mainCols.append(", "); } if (function != null) { mainCols.append(function.toString()).append('('); } ModelField mainField = entity.getField(field.getFieldName()); mainCols.append(mainField.getColName()); if (function != null) { mainCols.append(')'); } } StringBuilder indexSqlBuf = new StringBuilder("CREATE "); if (datasourceInfo.getUseIndicesUnique() && modelIndex.getUnique()) { indexSqlBuf.append("UNIQUE "); } indexSqlBuf.append("INDEX "); indexSqlBuf.append(makeIndexName(modelIndex, datasourceInfo.getConstraintNameClipLength())); indexSqlBuf.append(" ON "); indexSqlBuf.append(entity.getTableName(datasourceInfo)); indexSqlBuf.append(" ("); indexSqlBuf.append(mainCols.toString()); indexSqlBuf.append(")"); return indexSqlBuf.toString(); } public void deleteDeclaredIndices(ModelEntity entity, List<String> messages) { if (messages == null) messages = new ArrayList<String>(); String err = deleteDeclaredIndices(entity); if (UtilValidate.isNotEmpty(err)) { messages.add(err); } } public String deleteDeclaredIndices(ModelEntity entity) { if (entity == null) { return "ModelEntity was null and is required to delete declared indices for a table"; } if (entity instanceof ModelViewEntity) { return "ERROR: Cannot delete declared indices for a view entity"; } StringBuilder retMsgsBuffer = new StringBuilder(); // go through the relationships to see if any foreign keys need to be added Iterator<ModelIndex> indexesIter = entity.getIndexesIterator(); while (indexesIter.hasNext()) { ModelIndex modelIndex = indexesIter.next(); String retMsg = deleteDeclaredIndex(entity, modelIndex); if (UtilValidate.isNotEmpty(retMsg)) { if (retMsgsBuffer.length() > 0) { retMsgsBuffer.append("\n"); } retMsgsBuffer.append(retMsg); if (Debug.infoOn()) Debug.logInfo(retMsg, module); } } if (retMsgsBuffer.length() > 0) { return retMsgsBuffer.toString(); } else { return null; } } public String deleteDeclaredIndex(ModelEntity entity, ModelIndex modelIndex) { // TODO: also remove the constraing if this was a unique index, in most databases dropping the index does not drop the constraint StringBuilder indexSqlBuf = new StringBuilder("DROP INDEX "); String tableName = entity.getTableName(datasourceInfo); String schemaName = (UtilValidate.isEmpty(tableName) || tableName.indexOf('.') == -1) ? "" : tableName.substring(0, tableName.indexOf('.')); indexSqlBuf.append(schemaName); indexSqlBuf.append("."); indexSqlBuf.append(modelIndex.getName()); String deleteIndexSql = indexSqlBuf.toString(); if (Debug.verboseOn()) Debug.logVerbose("[deleteDeclaredIndex] index sql=" + deleteIndexSql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(deleteIndexSql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + deleteIndexSql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } /* ====================================================================== */ /* ====================================================================== */ public int createForeignKeyIndices(ModelEntity entity, List<String> messages) { return createForeignKeyIndices(entity, datasourceInfo.getConstraintNameClipLength(), messages); } public int createForeignKeyIndices(ModelEntity entity, int constraintNameClipLength, List<String> messages) { if (entity == null) { String message = "ModelEntity was null and is required to create foreign keys indices for a table"; Debug.logError(message, module); if (messages != null) messages.add(message); return 0; } if (entity instanceof ModelViewEntity) { String message = "Cannot create foreign keys indices for a view entity"; Debug.logWarning(message, module); if (messages != null) messages.add(message); return 0; } int fkisCreated = 0; // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { String retMsg = createForeignKeyIndex(entity, modelRelation, constraintNameClipLength); if (UtilValidate.isNotEmpty(retMsg)) { String message = "Could not create foreign key indices for entity [" + entity.getEntityName() + "]: " + retMsg; Debug.logError(message, module); if (messages != null) messages.add(message); continue; } fkisCreated++; } } if (fkisCreated > 0) { String message = "Created " + fkisCreated + " foreign key indices for entity [" + entity.getEntityName() + "]"; Debug.logImportant(message, module); if (messages != null) messages.add(message); } return fkisCreated; } public String createForeignKeyIndex(ModelEntity entity, ModelRelation modelRelation, int constraintNameClipLength) { String createIndexSql = makeFkIndexClause(entity, modelRelation, constraintNameClipLength); if (UtilValidate.isEmpty(createIndexSql)) { return "Error creating foreign key index clause, see log for details"; } if (Debug.verboseOn()) Debug.logVerbose("[createForeignKeyIndex] index sql=" + createIndexSql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(createIndexSql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + createIndexSql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String makeFkIndexClause(ModelEntity entity, ModelRelation modelRelation, int constraintNameClipLength) { StringBuilder mainCols = new StringBuilder(); for (ModelKeyMap keyMap : modelRelation.getKeyMaps()) { ModelField mainField = entity.getField(keyMap.getFieldName()); if (mainField == null) { Debug.logError("Bad key-map in entity [" + entity.getEntityName() + "] relation to [" + modelRelation.getTitle() + modelRelation.getRelEntityName() + "] for field [" + keyMap.getFieldName() + "]", module); return null; } if (mainCols.length() > 0) { mainCols.append(", "); } mainCols.append(mainField.getColName()); } StringBuilder indexSqlBuf = new StringBuilder("CREATE INDEX "); String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); indexSqlBuf.append(relConstraintName); indexSqlBuf.append(" ON "); indexSqlBuf.append(entity.getTableName(datasourceInfo)); indexSqlBuf.append(" ("); indexSqlBuf.append(mainCols.toString()); indexSqlBuf.append(")"); return indexSqlBuf.toString(); } public void deleteForeignKeyIndices(ModelEntity entity, List<String> messages) { if (messages == null) messages = new ArrayList<String>(); String err = deleteForeignKeyIndices(entity, datasourceInfo.getConstraintNameClipLength()); if (UtilValidate.isNotEmpty(err)) { messages.add(err); } } public String deleteForeignKeyIndices(ModelEntity entity, int constraintNameClipLength) { if (entity == null) { return "ModelEntity was null and is required to delete foreign keys indices for a table"; } if (entity instanceof ModelViewEntity) { return "ERROR: Cannot delete foreign keys indices for a view entity"; } StringBuilder retMsgsBuffer = new StringBuilder(); // go through the relationships to see if any foreign keys need to be added Iterator<ModelRelation> relationsIter = entity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); if ("one".equals(modelRelation.getType())) { String retMsg = deleteForeignKeyIndex(entity, modelRelation, constraintNameClipLength); if (UtilValidate.isNotEmpty(retMsg)) { if (retMsgsBuffer.length() > 0) { retMsgsBuffer.append("\n"); } retMsgsBuffer.append(retMsg); } } } if (retMsgsBuffer.length() > 0) { return retMsgsBuffer.toString(); } else { return null; } } public String deleteForeignKeyIndex(ModelEntity entity, ModelRelation modelRelation, int constraintNameClipLength) { StringBuilder indexSqlBuf = new StringBuilder("DROP INDEX "); String relConstraintName = makeFkConstraintName(modelRelation, constraintNameClipLength); String tableName = entity.getTableName(datasourceInfo); String schemaName = (UtilValidate.isEmpty(tableName) || tableName.indexOf('.') == -1) ? "" : tableName.substring(0, tableName.indexOf('.')); if (UtilValidate.isNotEmpty(schemaName)) { indexSqlBuf.append(schemaName); indexSqlBuf.append("."); } indexSqlBuf.append(relConstraintName); String deleteIndexSql = indexSqlBuf.toString(); if (Debug.verboseOn()) Debug.logVerbose("[deleteForeignKeyIndex] index sql=" + deleteIndexSql, module); try (Connection connection = getConnection(); Statement stmt = connection.createStatement()) { stmt.executeUpdate(deleteIndexSql); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + deleteIndexSql + "\nError was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } catch (GenericEntityException e) { String errMsg = "Unable to establish a connection with the database for helperName [" + this.helperInfo.getHelperFullName() + "]... Error was: " + e.toString(); Debug.logError(e, errMsg, module); return errMsg; } return null; } public String getSchemaName(DatabaseMetaData dbData) throws SQLException { if (!isLegacy && this.datasourceInfo.getUseSchemas() && dbData.supportsSchemasInTableDefinitions()) { if (UtilValidate.isNotEmpty(this.datasourceInfo.getSchemaName())) { if (dbData.storesLowerCaseIdentifiers()) { return this.datasourceInfo.getSchemaName().toLowerCase(); } else if (dbData.storesUpperCaseIdentifiers()) { return this.datasourceInfo.getSchemaName().toUpperCase(); } else { return this.datasourceInfo.getSchemaName(); } } else { return dbData.getUserName(); } } return null; } /* ====================================================================== */ /* ====================================================================== */ public void updateCharacterSetAndCollation(ModelEntity entity, List<String> messages) { if (entity instanceof ModelViewEntity) { return; } if (UtilValidate.isEmpty(this.datasourceInfo.getCharacterSet()) && UtilValidate.isEmpty(this.datasourceInfo.getCollate())) { messages.add("Not setting character-set and collate for entity [" + entity.getEntityName() + "], options not specified in the datasource definition in the entityengine.xml file."); return; } try (Connection connection = getConnectionLogged(messages)) { if (connection == null) { return; } StringBuilder sqlTableBuf = new StringBuilder("ALTER TABLE "); sqlTableBuf.append(entity.getTableName(this.datasourceInfo)); //sqlTableBuf.append(""); // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlTableBuf.append(" DEFAULT CHARACTER SET "); sqlTableBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlTableBuf.append(" COLLATE "); sqlTableBuf.append(this.datasourceInfo.getCollate()); } if (Debug.verboseOn()) Debug.logVerbose("[updateCharacterSetAndCollation] character-set and collate sql=" + sqlTableBuf, module); try (Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlTableBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlTableBuf + "\nError was: " + e.toString(); messages.add(errMsg); Debug.logError(errMsg, module); } Iterator<ModelField> fieldIter = entity.getFieldsIterator(); while (fieldIter.hasNext()) { ModelField field = fieldIter.next(); ModelFieldType type = modelFieldTypeReader.getModelFieldType(field.getType()); if (type == null) { messages.add("Field type [" + type + "] not found for field [" + field.getName() + "] of entity [" + entity.getEntityName() + "], not creating table."); continue; } if (!"String".equals(type.getJavaType()) && !"java.lang.String".equals(type.getJavaType())) { continue; } StringBuilder sqlBuf = new StringBuilder("ALTER TABLE "); sqlBuf.append(entity.getTableName(this.datasourceInfo)); sqlBuf.append(" MODIFY COLUMN "); sqlBuf.append(field.getColName()); sqlBuf.append(" "); sqlBuf.append(type.getSqlType()); // if there is a characterSet, add the CHARACTER SET arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCharacterSet())) { sqlBuf.append(" CHARACTER SET "); sqlBuf.append(this.datasourceInfo.getCharacterSet()); } // if there is a collate, add the COLLATE arg here if (UtilValidate.isNotEmpty(this.datasourceInfo.getCollate())) { sqlBuf.append(" COLLATE "); sqlBuf.append(this.datasourceInfo.getCollate()); } if (field.getIsPk() || field.getIsNotNull()) { if (this.datasourceInfo.getAlwaysUseConstraintKeyword()) { sqlBuf.append(" CONSTRAINT NOT NULL"); } else { sqlBuf.append(" NOT NULL"); } } if (Debug.verboseOn()) Debug.logVerbose("[updateCharacterSetAndCollation] character-set and collate sql=" + sqlBuf, module); try (Statement stmt = connection.createStatement()) { stmt.executeUpdate(sqlBuf.toString()); } catch (SQLException e) { String errMsg = "SQL Exception while executing the following:\n" + sqlBuf + "\nError was: " + e.toString(); messages.add(errMsg); Debug.logError(errMsg, module); } } } catch (SQLException e) { Debug.logError(e, module); } } /* ====================================================================== */ /* ====================================================================== */ @SuppressWarnings("serial") public static class ColumnCheckInfo implements Serializable { public String tableName; public String columnName; public String typeName; public int columnSize; public int decimalDigits; public String isNullable; // YES/NO or "" = ie nobody knows public boolean isPk = false; public int pkSeq; public String pkName; public static String fixupTableName(String rawTableName, String lookupSchemaName, boolean needsUpperCase) { String tableName = rawTableName; // for those databases which do not return the schema name with the table name (pgsql 7.3) boolean appendSchemaName = false; if (tableName != null && lookupSchemaName != null && !tableName.startsWith(lookupSchemaName + "\\.")) { appendSchemaName = true; } if (needsUpperCase && tableName != null) { tableName = tableName.toUpperCase(); } if (appendSchemaName) { tableName = lookupSchemaName + "." + tableName; } return tableName; } } @SuppressWarnings("serial") public static class ReferenceCheckInfo implements Serializable { public String pkTableName; /** Comma separated list of column names in the related tables primary key */ public String pkColumnName; public String fkName; public String fkTableName; /** Comma separated list of column names in the primary tables foreign keys */ public String fkColumnName; @Override public String toString() { return "FK Reference from table " + fkTableName + " called " + fkName + " to PK in table " + pkTableName; } } }
DatabaseUtil: fix entity index errors affecting unrelated indexes + improved logging https://gitlab.ilscipio.com/scipio-dev/dev/scipioce-dev/-/issues/1204
framework/entity/src/org/ofbiz/entity/jdbc/DatabaseUtil.java
DatabaseUtil: fix entity index errors affecting unrelated indexes + improved logging
Java
apache-2.0
f8e6cc58deb7c83bc3ea769e1a2282204c4157cf
0
MER-GROUP/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,supersven/intellij-community,holmes/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,clumsy/intellij-community,signed/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,semonte/intellij-community,petteyg/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,retomerz/intellij-community,kdwink/intellij-community,supersven/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,caot/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,robovm/robovm-studio,vladmm/intellij-community,adedayo/intellij-community,adedayo/intellij-community,slisson/intellij-community,supersven/intellij-community,petteyg/intellij-community,hurricup/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,izonder/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,holmes/intellij-community,tmpgit/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,dslomov/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,ryano144/intellij-community,asedunov/intellij-community,caot/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,izonder/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,signed/intellij-community,Distrotech/intellij-community,slisson/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,semonte/intellij-community,jagguli/intellij-community,da1z/intellij-community,signed/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,vladmm/intellij-community,signed/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,allotria/intellij-community,blademainer/intellij-community,holmes/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,allotria/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,signed/intellij-community,hurricup/intellij-community,blademainer/intellij-community,xfournet/intellij-community,izonder/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,adedayo/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ryano144/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,allotria/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,diorcety/intellij-community,semonte/intellij-community,allotria/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,petteyg/intellij-community,samthor/intellij-community,da1z/intellij-community,clumsy/intellij-community,izonder/intellij-community,semonte/intellij-community,allotria/intellij-community,allotria/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,kool79/intellij-community,blademainer/intellij-community,kool79/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,hurricup/intellij-community,fnouama/intellij-community,dslomov/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,kool79/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,supersven/intellij-community,slisson/intellij-community,kdwink/intellij-community,caot/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,da1z/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,semonte/intellij-community,tmpgit/intellij-community,signed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,semonte/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,semonte/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,holmes/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,allotria/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,da1z/intellij-community,caot/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,kool79/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,diorcety/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,da1z/intellij-community,samthor/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,petteyg/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,caot/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,holmes/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,supersven/intellij-community,ryano144/intellij-community,FHannes/intellij-community,izonder/intellij-community,ibinti/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,caot/intellij-community,apixandru/intellij-community,signed/intellij-community,diorcety/intellij-community,da1z/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,holmes/intellij-community,slisson/intellij-community,fitermay/intellij-community,samthor/intellij-community,fitermay/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,FHannes/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,caot/intellij-community,fitermay/intellij-community,allotria/intellij-community,xfournet/intellij-community,slisson/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,kool79/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,robovm/robovm-studio,apixandru/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,supersven/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,kool79/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,slisson/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,jagguli/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,signed/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,adedayo/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,apixandru/intellij-community,supersven/intellij-community,supersven/intellij-community,blademainer/intellij-community,ibinti/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,caot/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,FHannes/intellij-community,caot/intellij-community,Distrotech/intellij-community,kool79/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,signed/intellij-community,fnouama/intellij-community,retomerz/intellij-community,retomerz/intellij-community,diorcety/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,izonder/intellij-community,youdonghai/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,slisson/intellij-community,kool79/intellij-community,kool79/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,ryano144/intellij-community,vladmm/intellij-community,supersven/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,allotria/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,kool79/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,FHannes/intellij-community,amith01994/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,da1z/intellij-community,izonder/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,jagguli/intellij-community,allotria/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,da1z/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,amith01994/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,signed/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,caot/intellij-community,signed/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,FHannes/intellij-community,samthor/intellij-community,signed/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,vladmm/intellij-community
python/testSrc/com/jetbrains/python/testRunner/PyDocTestRunnerTest.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.testRunner; import com.intellij.execution.ExecutionException; import com.intellij.execution.process.ProcessOutput; import com.intellij.openapi.util.text.StringUtil; import com.intellij.testFramework.LightPlatformTestCase; import com.intellij.util.ArrayUtil; import com.jetbrains.python.PythonTestUtil; import com.jetbrains.python.fixtures.PyTestCase; import com.jetbrains.python.testing.JythonUnitTestUtil; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * User: catherine */ public class PyDocTestRunnerTest extends LightPlatformTestCase { @SuppressWarnings({"JUnitTestCaseWithNonTrivialConstructors"}) public PyDocTestRunnerTest() { PyTestCase.initPlatformPrefix(); } public void testEmptySuite() throws ExecutionException { final File testDir = getTestDataDir(); File testFile = new File(testDir, "test_empty.py"); String[] result = runUTRunner(testDir.getPath(), testFile.getPath()); assertEquals("##teamcity[enteredTheMatrix]", result [0]); assertEquals("##teamcity[testCount count='0']", result [1]); } public void testFile() throws ExecutionException { final File testDir = getTestDataDir(); File testFile = new File(testDir, "test_file.py"); String[] result = runUTRunner(testDir.getPath(), testFile.getPath()); assertEquals(StringUtil.join(result, "\n"), 14, result.length); assertEquals("##teamcity[testCount count='3']", result [1]); assertTrue(result[2].contains("name='test_file.FirstGoodTest'")); } private static File getTestDataDir() { return new File(PythonTestUtil.getTestDataPath(), "/testRunner/doctests"); } public void testClass() throws ExecutionException { final File testDir = getTestDataDir(); File testFile = new File(testDir, "test_file.py"); String[] result = runUTRunner(testDir.getPath(), testFile.getPath() + "::FirstGoodTest"); assertEquals(StringUtil.join(result, "\n"), 6, result.length); } public void testMethod() throws ExecutionException { final File testDir = getTestDataDir(); File testFile = new File(testDir, "test_file.py"); String[] result = runUTRunner(testDir.getPath(), testFile.getPath() + "::SecondGoodTest::test_passes"); assertEquals(StringUtil.join(result, "\n"), 6, result.length); } public void testFunction() throws ExecutionException { final File testDir = getTestDataDir(); File testFile = new File(testDir, "test_file.py"); String[] result = runUTRunner(testDir.getPath(), testFile.getPath() + "::factorial"); assertEquals(StringUtil.join(result, "\n"), 6, result.length); } private static String[] runUTRunner(String workDir, String... args) throws ExecutionException { String helpersPath = PyTestCase.getHelpersPath(); File utRunner = new File(helpersPath, "pycharm/docrunner.py"); List<String> allArgs = new ArrayList<String>(); allArgs.add(utRunner.getPath()); Collections.addAll(allArgs, args); final ProcessOutput output = JythonUnitTestUtil.runJython(workDir, helpersPath, ArrayUtil.toStringArray(allArgs)); assertEquals(output.getStderr(), 0, splitLines(output.getStderr()).length); return splitLines(output.getStdout()); } private static String[] splitLines(final String out) { List<String> result = new ArrayList<String>(); final String[] lines = StringUtil.convertLineSeparators(out).split("\n"); for (String line : lines) { if (line.length() > 0 && !line.contains("*sys-package-mgr*")) { result.add(line); } } return ArrayUtil.toStringArray(result); } }
moved doctest tests to env tests
python/testSrc/com/jetbrains/python/testRunner/PyDocTestRunnerTest.java
moved doctest tests to env tests
Java
apache-2.0
e7d08bd15b64dfb22ad8dae3f36faf683a49cbcd
0
bmatthews68/ldap-maven-plugin
/* * Copyright 2012 Brian Thomas Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.ldap.mojo; import java.io.File; import java.util.HashMap; import java.util.Map; import com.btmatthews.utils.monitor.mojo.AbstractRunMojo; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; /** * This Mojo implements the run goal which launches an embedded LDAP * server using Apache Directory Server. * * @author <a href="mailto:brian.matthews@btmatthews.com">Brian Matthews</a> * @since 1.1.0 */ @Mojo(name = "run", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST) public final class RunLDAPMojo extends AbstractRunMojo { /** * The server can be one of: * <ul> * <li>apacheds</li> * <li>opendj</li> * <li>unboundid</li> * </ul> */ @Parameter(property = "ldap.type", defaultValue = "apacheds") private String serverType; /** * The identity of the admin account for tbe directory server. */ @Parameter(property = "ldap.authDn", defaultValue = "uid=admin,ou=system") private String authDn; /** * The credentials for the admin account of the directory server. */ @Parameter(property = "ldap.passwd", defaultValue = "secret") private String passwd; /** * The root DN for the LDAP server. */ @Parameter(property = "ldap.root", required = true) private String rootDn; /** * An optional LDIF file that can be used to seed the embedded LDAP server. */ @Parameter(property = "ldap.ldif", required = false) private File ldifFile; /** * The port for the LDAP server. */ @Parameter(property = "ldap.port", defaultValue = "389") private int ldapPort; /** * The build target directory. */ @Parameter(defaultValue = "${project.build.directory}", required = true) private File outputDirectory; @Override public String getServerType() { return serverType; } @Override public Map<String, Object> getServerConfig() { final Map<String, Object> config = new HashMap<String, Object>(); config.put("root", rootDn); config.put("workingDirectory", new File(outputDirectory, "ldap")); config.put("ldifFile", ldifFile); config.put("ldapPort", Integer.valueOf(ldapPort)); config.put("authDn", authDn); config.put("passwd", passwd); return config; } }
src/main/java/com/btmatthews/maven/plugins/ldap/mojo/RunLDAPMojo.java
/* * Copyright 2012 Brian Thomas Matthews * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmatthews.maven.plugins.ldap.mojo; import java.io.File; import java.util.HashMap; import java.util.Map; import com.btmatthews.utils.monitor.mojo.AbstractRunMojo; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; /** * This Mojo implements the run goal which launches an embedded LDAP * server using Apache Directory Server. * * @author <a href="mailto:brian.matthews@btmatthews.com">Brian Matthews</a> * @since 1.1.0 */ @Mojo(name = "run", defaultPhase = LifecyclePhase.PRE_INTEGRATION_TEST) public final class RunLDAPMojo extends AbstractRunMojo { /** * The server can be one of: * <ul> * <li>apacheds</li> * <li>opendj</li> * <li>unboundid</li> * </ul> */ @Parameter(property = "ldap.type", defaultValue = "apacheds") private String serverType; /** * The root DN for the LDAP server. */ @Parameter(property = "ldap.root", required = true) private String rootDn; /** * An optional LDIF file that can be used to seed the embedded LDAP server. */ @Parameter(property = "ldap.ldif", required = false) private File ldifFile; /** * The port for the LDAP server. */ @Parameter(property = "ldap.port", defaultValue = "389") private int ldapPort; /** * The build target directory. */ @Parameter(defaultValue = "${project.build.directory}", required = true) private File outputDirectory; @Override public String getServerType() { return serverType; } @Override public Map<String, Object> getServerConfig() { final Map<String, Object> config = new HashMap<String, Object>(); config.put("root", rootDn); config.put("workingDirectory", new File(outputDirectory, "ldap")); config.put("ldifFile", ldifFile); config.put("ldapPort", Integer.valueOf(ldapPort)); return config; } }
Added server type and user name/password parameters
src/main/java/com/btmatthews/maven/plugins/ldap/mojo/RunLDAPMojo.java
Added server type and user name/password parameters
Java
apache-2.0
cb6215b2353e848cea054e52e37d1fe6c4756631
0
4treesCH/strolch,4treesCH/strolch,eitchnet/strolch,eitchnet/strolch,4treesCH/strolch,4treesCH/strolch,eitchnet/strolch,eitchnet/strolch
/* * Copyright (c) 2010, 2011 * * Robert von Burg <eitch@eitchnet.ch> * */ /* * This file is part of Privilege. * * Privilege is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Privilege is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Privilege. If not, see <http://www.gnu.org/licenses/>. * */ package ch.eitchnet.privilege.handler; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.dom4j.DocumentFactory; import org.dom4j.Element; import ch.eitchnet.privilege.helper.XmlConstants; import ch.eitchnet.privilege.helper.XmlHelper; import ch.eitchnet.privilege.i18n.PrivilegeException; import ch.eitchnet.privilege.model.UserState; import ch.eitchnet.privilege.model.internal.Privilege; import ch.eitchnet.privilege.model.internal.Role; import ch.eitchnet.privilege.model.internal.User; /** * {@link PersistenceHandler} implementation which reads the configuration from XML files. These configuration is passed * in {@link #initialize(Map)} * * @author Robert von Burg <eitch@eitchnet.ch> */ public class XmlPersistenceHandler implements PersistenceHandler { protected static final Logger logger = Logger.getLogger(XmlPersistenceHandler.class); private Map<String, User> userMap; private Map<String, Role> roleMap; private long modelsFileDate; private boolean userMapDirty; private boolean roleMapDirty; private Map<String, String> parameterMap; private String modelPath; /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#getAllUsers() */ @Override public List<User> getAllUsers() { synchronized (this.userMap) { return new LinkedList<User>(this.userMap.values()); } } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#getAllRoles() */ @Override public List<Role> getAllRoles() { synchronized (this.roleMap) { return new LinkedList<Role>(this.roleMap.values()); } } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#getUser(java.lang.String) */ @Override public User getUser(String username) { return this.userMap.get(username); } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#getRole(java.lang.String) */ @Override public Role getRole(String roleName) { return this.roleMap.get(roleName); } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#removeUser(java.lang.String) */ @Override public User removeUser(String username) { User user = this.userMap.remove(username); this.userMapDirty = user != null; return user; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#removeRole(java.lang.String) */ @Override public Role removeRole(String roleName) { Role role = this.roleMap.remove(roleName); this.roleMapDirty = role != null; return role; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#addOrReplaceUser(ch.eitchnet.privilege.model.internal.User) */ @Override public void addOrReplaceUser(User user) { this.userMap.put(user.getUsername(), user); this.userMapDirty = true; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#addOrReplaceRole(ch.eitchnet.privilege.model.internal.Role) */ @Override public void addOrReplaceRole(Role role) { this.roleMap.put(role.getName(), role); this.roleMapDirty = true; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#persist() */ @Override public boolean persist() { // get models file name String modelFileName = this.parameterMap.get(XmlConstants.XML_PARAM_MODEL_FILE); if (modelFileName == null || modelFileName.isEmpty()) { throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter " + XmlConstants.XML_PARAM_MODEL_FILE + " is invalid"); } // get model file File modelFile = new File(this.modelPath); boolean modelFileUnchanged = modelFile.exists() && modelFile.lastModified() == this.modelsFileDate; if (!(modelFileUnchanged && this.roleMapDirty && this.userMapDirty)) { logger.warn("Not persisting as current file is unchanged and model data is not dirty"); return false; } DocumentFactory docFactory = DocumentFactory.getInstance(); // create root element Element rootElement = docFactory.createElement(XmlConstants.XML_ROOT_PRIVILEGE_USERS_AND_ROLES); // USERS // build XML DOM of users List<Element> users = toDomUsers(this.userMap); Element usersElement = docFactory.createElement(XmlConstants.XML_USERS); for (Element userElement : users) { usersElement.add(userElement); } rootElement.add(usersElement); // ROLES // build XML DOM of roles List<Element> roles = toDomRoles(this.roleMap); Element rolesElement = docFactory.createElement(XmlConstants.XML_ROLES); for (Element roleElement : roles) { rolesElement.add(roleElement); } rootElement.add(rolesElement); // reset dirty states and return if something was dirty, false otherwise if (this.userMapDirty || this.roleMapDirty) { this.userMapDirty = false; this.roleMapDirty = false; return true; } this.userMapDirty = false; this.roleMapDirty = false; return false; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#reload() */ @Override public boolean reload() { // validate file exists File modelsFile = new File(this.modelPath); if (!modelsFile.exists()) { throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter " + XmlConstants.XML_PARAM_MODEL_FILE + " is invalid as models file does not exist at path " + modelsFile.getAbsolutePath()); } this.roleMap = Collections.synchronizedMap(new HashMap<String, Role>()); this.userMap = Collections.synchronizedMap(new HashMap<String, User>()); // parse models xml file to XML document Element modelsRootElement = XmlHelper.parseDocument(modelsFile).getRootElement(); this.modelsFileDate = modelsFile.lastModified(); // ROLES // get roles element Element rolesElement = modelsRootElement.element(XmlConstants.XML_ROLES); // read roles Map<String, Role> roles = readRoles(rolesElement); this.roleMap = roles; // USERS // get users element Element usersElement = modelsRootElement.element(XmlConstants.XML_USERS); // read users Map<String, User> users = readUsers(usersElement); this.userMap = users; this.userMapDirty = false; this.roleMapDirty = false; logger.info("Read " + this.userMap.size() + " Users"); logger.info("Read " + this.roleMap.size() + " Roles"); // validate we have a user with PrivilegeAdmin access boolean privilegeAdminExists = false; for (String username : this.userMap.keySet()) { User user = this.userMap.get(username); if (user.hasRole(PrivilegeHandler.PRIVILEGE_ADMIN_ROLE)) { privilegeAdminExists = true; break; } } if (!privilegeAdminExists) { logger.warn("No User with role '" + PrivilegeHandler.PRIVILEGE_ADMIN_ROLE + "' exists. Privilege modifications will not be possible!"); } return true; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#initialize(java.util.Map) */ @Override public void initialize(Map<String, String> parameterMap) { // get and validate base bath String basePath = parameterMap.get(XmlConstants.XML_PARAM_BASE_PATH); File basePathF = new File(basePath); if (!basePathF.exists() && !basePathF.isDirectory()) { throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter " + XmlConstants.XML_PARAM_BASE_PATH + " is invalid"); } // get model file name String modelFileName = parameterMap.get(XmlConstants.XML_PARAM_MODEL_FILE); if (modelFileName == null || modelFileName.isEmpty()) { throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter " + XmlConstants.XML_PARAM_MODEL_FILE + " is invalid"); } // save path to model this.modelPath = basePath + "/" + modelFileName; if (reload()) logger.info("Privilege Data loaded."); } /** * Parses {@link User} objects from their XML representations * * @param usersRootElement * the element containing suer elements * * @return the map of converted {@link User} objects */ protected static Map<String, User> readUsers(Element usersRootElement) { Map<String, User> userMap = new HashMap<String, User>(); @SuppressWarnings("unchecked") List<Element> userElements = usersRootElement.elements(XmlConstants.XML_USER); for (Element userElement : userElements) { String userId = userElement.attributeValue(XmlConstants.XML_ATTR_USER_ID); String username = userElement.attributeValue(XmlConstants.XML_ATTR_USERNAME); String password = userElement.attributeValue(XmlConstants.XML_ATTR_PASSWORD); String firstname = userElement.element(XmlConstants.XML_FIRSTNAME).getTextTrim(); String surname = userElement.element(XmlConstants.XML_SURNAME).getTextTrim(); UserState userState = UserState.valueOf(userElement.element(XmlConstants.XML_STATE).getTextTrim()); // TODO better parsing needed String localeName = userElement.element(XmlConstants.XML_LOCALE).getTextTrim(); Locale locale = new Locale(localeName); // read roles Element rolesElement = userElement.element(XmlConstants.XML_ROLES); @SuppressWarnings("unchecked") List<Element> rolesElementList = rolesElement.elements(XmlConstants.XML_ROLE); Set<String> roles = new HashSet<String>(); for (Element roleElement : rolesElementList) { String roleName = roleElement.getTextTrim(); if (roleName.isEmpty()) { logger.error("User " + username + " has a role defined with no name, Skipped."); } else { roles.add(roleName); } } // read properties Element propertiesElement = userElement.element(XmlConstants.XML_PROPERTIES); Map<String, String> propertyMap = convertToPropertyMap(propertiesElement); // create user User user = new User(userId, username, password, firstname, surname, userState, roles, locale, propertyMap); logger.info("Added user " + user); // put user in map userMap.put(username, user); } return userMap; } /** * Parses {@link Role} objects from their XML representations * * @param rolesRootElement * the element containing role elements * * @return the map of converted {@link Role} objects */ protected static Map<String, Role> readRoles(Element rolesRootElement) { Map<String, Role> roleMap = new HashMap<String, Role>(); @SuppressWarnings("unchecked") List<Element> roleElements = rolesRootElement.elements(XmlConstants.XML_ROLE); for (Element roleElement : roleElements) { String roleName = roleElement.attributeValue(XmlConstants.XML_ATTR_NAME); Map<String, Privilege> privilegeMap = readPrivileges(roleElement); Role role = new Role(roleName, privilegeMap); roleMap.put(roleName, role); } return roleMap; } /** * Converts {@link User} objects to their XML representations * * @param userMap * the map of users to convert * * @return the list of XML User elements */ protected static List<Element> toDomUsers(Map<String, User> userMap) { List<Element> usersAsElements = new ArrayList<Element>(userMap.size()); DocumentFactory documentFactory = DocumentFactory.getInstance(); synchronized (userMap) { for (String userName : userMap.keySet()) { // get the user object User user = userMap.get(userName); // create the user element Element userElement = documentFactory.createElement(XmlConstants.XML_USER); userElement.addAttribute(XmlConstants.XML_ATTR_USER_ID, user.getUserId()); userElement.addAttribute(XmlConstants.XML_ATTR_USERNAME, user.getUsername()); userElement.addAttribute(XmlConstants.XML_ATTR_PASSWORD, user.getPassword()); // add first name element Element firstnameElement = documentFactory.createElement(XmlConstants.XML_FIRSTNAME); firstnameElement.setText(user.getFirstname()); userElement.add(firstnameElement); // add surname element Element surnameElement = documentFactory.createElement(XmlConstants.XML_SURNAME); surnameElement.setText(user.getSurname()); userElement.add(surnameElement); // add state element Element stateElement = documentFactory.createElement(XmlConstants.XML_STATE); stateElement.setText(user.getUserState().toString()); userElement.add(stateElement); // add locale element Element localeElement = documentFactory.createElement(XmlConstants.XML_LOCALE); localeElement.setText(user.getLocale().toString()); userElement.add(localeElement); // add all the role elements Element rolesElement = documentFactory.createElement(XmlConstants.XML_ROLES); userElement.add(rolesElement); for (String roleName : user.getRoles()) { Element roleElement = documentFactory.createElement(XmlConstants.XML_ROLE); roleElement.setText(roleName); rolesElement.add(roleElement); } // add element to return list usersAsElements.add(userElement); } } return usersAsElements; } /** * Converts {@link Role} objects to their XML representations * * @param roleMap * the roles to convert * * @return the list of XML Role elements */ protected static List<Element> toDomRoles(Map<String, Role> roleMap) { List<Element> rolesAsElements = new ArrayList<Element>(roleMap.size()); DocumentFactory documentFactory = DocumentFactory.getInstance(); synchronized (roleMap) { for (String roleName : roleMap.keySet()) { // get the role object Role role = roleMap.get(roleName); // create the role element Element roleElement = documentFactory.createElement(XmlConstants.XML_ROLE); roleElement.addAttribute(XmlConstants.XML_ATTR_NAME, role.getName()); // add all the privileges toDomPrivileges(roleElement, role.getPrivilegeMap()); // add element to return list rolesAsElements.add(roleElement); } } return rolesAsElements; } /** * Parses {@link Privilege} objects from their XML representation to their objects * * @param roleParentElement * the parent on which the Privilege XML elements are * * @return the map of {@link Privilege} objects */ protected static Map<String, Privilege> readPrivileges(Element roleParentElement) { Map<String, Privilege> privilegeMap = new HashMap<String, Privilege>(); @SuppressWarnings("unchecked") List<Element> privilegeElements = roleParentElement.elements(XmlConstants.XML_PRIVILEGE); for (Element privilegeElement : privilegeElements) { String privilegeName = privilegeElement.attributeValue(XmlConstants.XML_ATTR_NAME); String privilegePolicy = privilegeElement.attributeValue(XmlConstants.XML_ATTR_POLICY); Element allAllowedE = privilegeElement.element(XmlConstants.XML_ALL_ALLOWED); boolean allAllowed = false; if (allAllowedE != null) { allAllowed = Boolean.valueOf(allAllowedE.getTextTrim()).booleanValue(); } @SuppressWarnings("unchecked") List<Element> denyElements = privilegeElement.elements(XmlConstants.XML_DENY); Set<String> denyList = new HashSet<String>(denyElements.size()); for (Element denyElement : denyElements) { String denyValue = denyElement.getTextTrim(); if (!denyValue.isEmpty()) denyList.add(denyValue); } @SuppressWarnings("unchecked") List<Element> allowElements = privilegeElement.elements(XmlConstants.XML_ALLOW); Set<String> allowList = new HashSet<String>(allowElements.size()); for (Element allowElement : allowElements) { String allowValue = allowElement.getTextTrim(); if (!allowValue.isEmpty()) allowList.add(allowValue); } Privilege privilege = new Privilege(privilegeName, privilegePolicy, allAllowed, denyList, allowList); privilegeMap.put(privilegeName, privilege); } return privilegeMap; } /** * Converts {@link Privilege} objects to their XML representation * * @param roleParentElement * the XML element of the parent {@link Role} * @param privilegeMap * the map of {@link Privilege}s to convert */ protected static void toDomPrivileges(Element roleParentElement, Map<String, Privilege> privilegeMap) { DocumentFactory documentFactory = DocumentFactory.getInstance(); for (Privilege privilege : privilegeMap.values()) { // create the privilege element Element privilegeElement = documentFactory.createElement(XmlConstants.XML_PRIVILEGE); privilegeElement.addAttribute(XmlConstants.XML_ATTR_NAME, privilege.getName()); privilegeElement.addAttribute(XmlConstants.XML_ATTR_POLICY, privilege.getPolicy()); // add the all allowed element Element allAllowedElement = documentFactory.createElement(XmlConstants.XML_ALL_ALLOWED); allAllowedElement.setText(Boolean.toString(privilege.isAllAllowed())); privilegeElement.add(allAllowedElement); // add all the deny values for (String denyValue : privilege.getDenyList()) { Element denyValueElement = documentFactory.createElement(XmlConstants.XML_DENY); denyValueElement.setText(denyValue); privilegeElement.add(denyValueElement); } // add all the allow values for (String allowValue : privilege.getAllowList()) { Element allowValueElement = documentFactory.createElement(XmlConstants.XML_ALLOW); allowValueElement.setText(allowValue); privilegeElement.add(allowValueElement); } // add element to parent roleParentElement.add(privilegeElement); } } /** * Converts an {@link XmlConstants#XML_PROPERTIES} element containing {@link XmlConstants#XML_PROPERTY} elements to * a {@link Map} of String key/value pairs * * @param element * the XML {@link Element} with name {@link XmlConstants#XML_PROPERTIES} containing * {@link XmlConstants#XML_PROPERTY} elements * * @return the {@link Map} of the property name/value combinations from the given {@link Element} */ @SuppressWarnings("unchecked") protected static Map<String, String> convertToPropertyMap(Element element) { // if element is null then there are no properties, so return empty map if (element == null) return Collections.emptyMap(); List<Element> elements = element.elements(XmlConstants.XML_PROPERTY); // if elements is null or empty then there are no properties, so return empty map if (elements == null || elements.isEmpty()) return Collections.emptyMap(); Map<String, String> propertyMap = new HashMap<String, String>(); for (Element property : elements) { String name = property.attributeValue(XmlConstants.XML_ATTR_NAME); String value = property.attributeValue(XmlConstants.XML_ATTR_VALUE); propertyMap.put(name, value); } return propertyMap; } }
src/ch/eitchnet/privilege/handler/XmlPersistenceHandler.java
/* * Copyright (c) 2010, 2011 * * Robert von Burg <eitch@eitchnet.ch> * */ /* * This file is part of Privilege. * * Privilege is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Privilege is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Privilege. If not, see <http://www.gnu.org/licenses/>. * */ package ch.eitchnet.privilege.handler; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.dom4j.DocumentFactory; import org.dom4j.Element; import ch.eitchnet.privilege.helper.XmlConstants; import ch.eitchnet.privilege.helper.XmlHelper; import ch.eitchnet.privilege.i18n.PrivilegeException; import ch.eitchnet.privilege.model.UserState; import ch.eitchnet.privilege.model.internal.Privilege; import ch.eitchnet.privilege.model.internal.Role; import ch.eitchnet.privilege.model.internal.User; /** * {@link PersistenceHandler} implementation which reads the configuration from XML files. These configuration is passed * in {@link #initialize(Map)} * * @author Robert von Burg <eitch@eitchnet.ch> */ public class XmlPersistenceHandler implements PersistenceHandler { protected static final Logger logger = Logger.getLogger(XmlPersistenceHandler.class); private Map<String, User> userMap; private Map<String, Role> roleMap; private long modelsFileDate; private boolean userMapDirty; private boolean roleMapDirty; private Map<String, String> parameterMap; private String modelPath; /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#getAllUsers() */ @Override public List<User> getAllUsers() { synchronized (this.userMap) { return new LinkedList<User>(this.userMap.values()); } } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#getAllRoles() */ @Override public List<Role> getAllRoles() { synchronized (this.roleMap) { return new LinkedList<Role>(this.roleMap.values()); } } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#getUser(java.lang.String) */ @Override public User getUser(String username) { return this.userMap.get(username); } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#getRole(java.lang.String) */ @Override public Role getRole(String roleName) { return this.roleMap.get(roleName); } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#removeUser(java.lang.String) */ @Override public User removeUser(String username) { User user = this.userMap.remove(username); this.userMapDirty = user != null; return user; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#removeRole(java.lang.String) */ @Override public Role removeRole(String roleName) { Role role = this.roleMap.remove(roleName); this.roleMapDirty = role != null; return role; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#addOrReplaceUser(ch.eitchnet.privilege.model.internal.User) */ @Override public void addOrReplaceUser(User user) { this.userMap.put(user.getUsername(), user); this.userMapDirty = true; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#addOrReplaceRole(ch.eitchnet.privilege.model.internal.Role) */ @Override public void addOrReplaceRole(Role role) { this.roleMap.put(role.getName(), role); this.roleMapDirty = true; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#persist() */ @Override public boolean persist() { // get models file name String modelFileName = this.parameterMap.get(XmlConstants.XML_PARAM_MODEL_FILE); if (modelFileName == null || modelFileName.isEmpty()) { throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter " + XmlConstants.XML_PARAM_MODEL_FILE + " is invalid"); } // get model file File modelFile = new File(this.modelPath); boolean modelFileUnchanged = modelFile.exists() && modelFile.lastModified() == this.modelsFileDate; if (!(modelFileUnchanged && this.roleMapDirty && this.userMapDirty)) { logger.warn("Not persisting as current file is unchanged and model data is not dirty"); return false; } DocumentFactory docFactory = DocumentFactory.getInstance(); // create root element Element rootElement = docFactory.createElement(XmlConstants.XML_ROOT_PRIVILEGE_USERS_AND_ROLES); // USERS // build XML DOM of users List<Element> users = toDomUsers(this.userMap); Element usersElement = docFactory.createElement(XmlConstants.XML_USERS); for (Element userElement : users) { usersElement.add(userElement); } rootElement.add(usersElement); // ROLES // build XML DOM of roles List<Element> roles = toDomRoles(this.roleMap); Element rolesElement = docFactory.createElement(XmlConstants.XML_ROLES); for (Element roleElement : roles) { rolesElement.add(roleElement); } rootElement.add(rolesElement); // reset dirty states and return if something was dirty, false otherwise if (this.userMapDirty || this.roleMapDirty) { this.userMapDirty = false; this.roleMapDirty = false; return true; } this.userMapDirty = false; this.roleMapDirty = false; return false; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#reload() */ @Override public boolean reload() { // validate file exists File modelsFile = new File(this.modelPath); if (!modelsFile.exists()) { throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter " + XmlConstants.XML_PARAM_MODEL_FILE + " is invalid as models file does not exist at path " + modelsFile.getAbsolutePath()); } this.roleMap = Collections.synchronizedMap(new HashMap<String, Role>()); this.userMap = Collections.synchronizedMap(new HashMap<String, User>()); // parse models xml file to XML document Element modelsRootElement = XmlHelper.parseDocument(modelsFile).getRootElement(); this.modelsFileDate = modelsFile.lastModified(); // ROLES // get roles element Element rolesElement = modelsRootElement.element(XmlConstants.XML_ROLES); // read roles Map<String, Role> roles = readRoles(rolesElement); this.roleMap = roles; // USERS // get users element Element usersElement = modelsRootElement.element(XmlConstants.XML_USERS); // read users Map<String, User> users = readUsers(usersElement); this.userMap = users; this.userMapDirty = false; this.roleMapDirty = false; logger.info("Read " + this.userMap.size() + " Users"); logger.info("Read " + this.roleMap.size() + " Roles"); // validate we have a user with PrivilegeAdmin access boolean privilegeAdminExists = false; for (String username : this.userMap.keySet()) { User user = this.userMap.get(username); if (user.hasRole(PrivilegeHandler.PRIVILEGE_ADMIN_ROLE)) { privilegeAdminExists = true; break; } } if (!privilegeAdminExists) { logger.warn("No User with role '" + PrivilegeHandler.PRIVILEGE_ADMIN_ROLE + "' exists. Privilege modifications will not be possible!"); } return true; } /** * @see ch.eitchnet.privilege.handler.PersistenceHandler#initialize(java.util.Map) */ @Override public void initialize(Map<String, String> parameterMap) { // get and validate base bath String basePath = parameterMap.get(XmlConstants.XML_PARAM_BASE_PATH); File basePathF = new File(basePath); if (!basePathF.exists() && !basePathF.isDirectory()) { throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter " + XmlConstants.XML_PARAM_BASE_PATH + " is invalid"); } // get model file name String modelFileName = parameterMap.get(XmlConstants.XML_PARAM_MODEL_FILE); if (modelFileName == null || modelFileName.isEmpty()) { throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter " + XmlConstants.XML_PARAM_MODEL_FILE + " is invalid"); } // save path to model this.modelPath = basePath + "/" + modelFileName; if (reload()) logger.info("Privilege Data loaded."); } /** * Parses {@link User} objects from their XML representations * * @param usersRootElement * the element containing suer elements * * @return the map of converted {@link User} objects */ protected static Map<String, User> readUsers(Element usersRootElement) { Map<String, User> userMap = new HashMap<String, User>(); @SuppressWarnings("unchecked") List<Element> userElements = usersRootElement.elements(XmlConstants.XML_USER); for (Element userElement : userElements) { String userId = userElement.attributeValue(XmlConstants.XML_ATTR_USER_ID); String username = userElement.attributeValue(XmlConstants.XML_ATTR_USERNAME); String password = userElement.attributeValue(XmlConstants.XML_ATTR_PASSWORD); String firstname = userElement.element(XmlConstants.XML_FIRSTNAME).getTextTrim(); String surname = userElement.element(XmlConstants.XML_SURNAME).getTextTrim(); UserState userState = UserState.valueOf(userElement.element(XmlConstants.XML_STATE).getTextTrim()); // TODO better parsing needed String localeName = userElement.element(XmlConstants.XML_LOCALE).getTextTrim(); Locale locale = new Locale(localeName); // read roles Element rolesElement = userElement.element(XmlConstants.XML_ROLES); @SuppressWarnings("unchecked") List<Element> rolesElementList = rolesElement.elements(XmlConstants.XML_ROLE); Set<String> roles = new HashSet<String>(); for (Element roleElement : rolesElementList) { String roleName = roleElement.getTextTrim(); if (roleName.isEmpty()) { logger.error("User " + username + " has a role defined with no name, Skipped."); } else { roles.add(roleName); } } // read properties Element propertiesElement = userElement.element(XmlConstants.XML_PROPERTIES); Map<String, String> propertyMap = convertToPropertyMap(propertiesElement); // create user User user = new User(userId, username, password, firstname, surname, userState, roles, locale, propertyMap); logger.info("Added user " + user); // put user in map userMap.put(username, user); } return userMap; } /** * Parses {@link Role} objects from their XML representations * * @param rolesRootElement * the element containing role elements * * @return the map of converted {@link Role} objects */ protected static Map<String, Role> readRoles(Element rolesRootElement) { Map<String, Role> roleMap = new HashMap<String, Role>(); @SuppressWarnings("unchecked") List<Element> roleElements = rolesRootElement.elements(XmlConstants.XML_ROLE); for (Element roleElement : roleElements) { String roleName = roleElement.attributeValue(XmlConstants.XML_ATTR_NAME); Map<String, Privilege> privilegeMap = readPrivileges(roleElement); Role role = new Role(roleName, privilegeMap); roleMap.put(roleName, role); } return roleMap; } /** * Converts {@link User} objects to their XML representations * * @param userMap * the map of users to convert * * @return the list of XML User elements */ protected static List<Element> toDomUsers(Map<String, User> userMap) { List<Element> usersAsElements = new ArrayList<Element>(userMap.size()); DocumentFactory documentFactory = DocumentFactory.getInstance(); synchronized (userMap) { for (String userName : userMap.keySet()) { // get the user object User user = userMap.get(userName); // create the user element Element userElement = documentFactory.createElement(XmlConstants.XML_USER); userElement.addAttribute(XmlConstants.XML_ATTR_USER_ID, user.getUserId()); userElement.addAttribute(XmlConstants.XML_ATTR_USERNAME, user.getUsername()); userElement.addAttribute(XmlConstants.XML_ATTR_PASSWORD, user.getPassword()); // add first name element Element firstnameElement = documentFactory.createElement(XmlConstants.XML_FIRSTNAME); firstnameElement.setText(user.getFirstname()); userElement.add(firstnameElement); // add surname element Element surnameElement = documentFactory.createElement(XmlConstants.XML_SURNAME); surnameElement.setText(user.getSurname()); userElement.add(surnameElement); // add state element Element stateElement = documentFactory.createElement(XmlConstants.XML_STATE); stateElement.setText(user.getUserState().toString()); userElement.add(stateElement); // add locale element Element localeElement = documentFactory.createElement(XmlConstants.XML_LOCALE); localeElement.setText(user.getLocale().toString()); userElement.add(localeElement); // add all the role elements Element rolesElement = documentFactory.createElement(XmlConstants.XML_ROLES); userElement.add(rolesElement); for (String roleName : user.getRoles()) { Element roleElement = documentFactory.createElement(XmlConstants.XML_ROLE); roleElement.setText(roleName); rolesElement.add(roleElement); } // add element to return list usersAsElements.add(userElement); } } return usersAsElements; } /** * Converts {@link Role} objects to their XML representations * * @param roleMap * the roles to convert * * @return the list of XML Role elements */ protected static List<Element> toDomRoles(Map<String, Role> roleMap) { List<Element> rolesAsElements = new ArrayList<Element>(roleMap.size()); DocumentFactory documentFactory = DocumentFactory.getInstance(); synchronized (roleMap) { for (String roleName : roleMap.keySet()) { // get the role object Role role = roleMap.get(roleName); // create the role element Element roleElement = documentFactory.createElement(XmlConstants.XML_ROLE); roleElement.addAttribute(XmlConstants.XML_ATTR_NAME, role.getName()); // add all the privileges toDomPrivileges(roleElement, role.getPrivilegeMap()); // add element to return list rolesAsElements.add(roleElement); } } return rolesAsElements; } /** * Parses {@link Privilege} objects from their XML representation to their objects * * @param roleParentElement * the parent on which the Privilege XML elements are * * @return the map of {@link Privilege} objects */ protected static Map<String, Privilege> readPrivileges(Element roleParentElement) { Map<String, Privilege> privilegeMap = new HashMap<String, Privilege>(); @SuppressWarnings("unchecked") List<Element> privilegeElements = roleParentElement.elements(XmlConstants.XML_PRIVILEGE); for (Element privilegeElement : privilegeElements) { String privilegeName = privilegeElement.attributeValue(XmlConstants.XML_ATTR_NAME); String privilegePolicy = privilegeElement.attributeValue(XmlConstants.XML_ATTR_POLICY); String allAllowedS = privilegeElement.element(XmlConstants.XML_ALL_ALLOWED).getTextTrim(); boolean allAllowed = Boolean.valueOf(allAllowedS).booleanValue(); @SuppressWarnings("unchecked") List<Element> denyElements = privilegeElement.elements(XmlConstants.XML_DENY); Set<String> denyList = new HashSet<String>(denyElements.size()); for (Element denyElement : denyElements) { String denyValue = denyElement.getTextTrim(); if (!denyValue.isEmpty()) denyList.add(denyValue); } @SuppressWarnings("unchecked") List<Element> allowElements = privilegeElement.elements(XmlConstants.XML_ALLOW); Set<String> allowList = new HashSet<String>(allowElements.size()); for (Element allowElement : allowElements) { String allowValue = allowElement.getTextTrim(); if (!allowValue.isEmpty()) allowList.add(allowValue); } Privilege privilege = new Privilege(privilegeName, privilegePolicy, allAllowed, denyList, allowList); privilegeMap.put(privilegeName, privilege); } return privilegeMap; } /** * Converts {@link Privilege} objects to their XML representation * * @param roleParentElement * the XML element of the parent {@link Role} * @param privilegeMap * the map of {@link Privilege}s to convert */ protected static void toDomPrivileges(Element roleParentElement, Map<String, Privilege> privilegeMap) { DocumentFactory documentFactory = DocumentFactory.getInstance(); for (Privilege privilege : privilegeMap.values()) { // create the privilege element Element privilegeElement = documentFactory.createElement(XmlConstants.XML_PRIVILEGE); privilegeElement.addAttribute(XmlConstants.XML_ATTR_NAME, privilege.getName()); privilegeElement.addAttribute(XmlConstants.XML_ATTR_POLICY, privilege.getPolicy()); // add the all allowed element Element allAllowedElement = documentFactory.createElement(XmlConstants.XML_ALL_ALLOWED); allAllowedElement.setText(Boolean.toString(privilege.isAllAllowed())); privilegeElement.add(allAllowedElement); // add all the deny values for (String denyValue : privilege.getDenyList()) { Element denyValueElement = documentFactory.createElement(XmlConstants.XML_DENY); denyValueElement.setText(denyValue); privilegeElement.add(denyValueElement); } // add all the allow values for (String allowValue : privilege.getAllowList()) { Element allowValueElement = documentFactory.createElement(XmlConstants.XML_ALLOW); allowValueElement.setText(allowValue); privilegeElement.add(allowValueElement); } // add element to parent roleParentElement.add(privilegeElement); } } /** * Converts an {@link XmlConstants#XML_PROPERTIES} element containing {@link XmlConstants#XML_PROPERTY} elements to * a {@link Map} of String key/value pairs * * @param element * the XML {@link Element} with name {@link XmlConstants#XML_PROPERTIES} containing * {@link XmlConstants#XML_PROPERTY} elements * * @return the {@link Map} of the property name/value combinations from the given {@link Element} */ @SuppressWarnings("unchecked") protected static Map<String, String> convertToPropertyMap(Element element) { // if element is null then there are no properties, so return empty map if (element == null) return Collections.emptyMap(); List<Element> elements = element.elements(XmlConstants.XML_PROPERTY); // if elements is null or empty then there are no properties, so return empty map if (elements == null || elements.isEmpty()) return Collections.emptyMap(); Map<String, String> propertyMap = new HashMap<String, String>(); for (Element property : elements) { String name = property.attributeValue(XmlConstants.XML_ATTR_NAME); String value = property.attributeValue(XmlConstants.XML_ATTR_VALUE); propertyMap.put(name, value); } return propertyMap; } }
[Bugfix] fixed a bug where if the <AllAllowed> tag was not defined in the PrivilegeModel.xml file then a NullPointer was thrown. It is now possible to leave out this tag, in which case false is assumed
src/ch/eitchnet/privilege/handler/XmlPersistenceHandler.java
[Bugfix] fixed a bug where if the <AllAllowed> tag was not defined in the PrivilegeModel.xml file then a NullPointer was thrown. It is now possible to leave out this tag, in which case false is assumed
Java
apache-2.0
7fa7f0e3172422d0115a1f638a968c9b881c8f07
0
ceylon/ceylon-model
package com.redhat.ceylon.model.typechecker.model; import static com.redhat.ceylon.model.typechecker.model.SiteVariance.IN; import static com.redhat.ceylon.model.typechecker.model.SiteVariance.OUT; import static java.lang.Character.charCount; import static java.lang.Character.isLowerCase; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.common.BackendSupport; /** * Model utilities. * * @author Stéphane Épardaud <stef@epardaud.fr> * @author Gavin King */ public class ModelUtil { static final List<Type> NO_TYPE_ARGS = Collections.<Type>emptyList(); static final Map<TypeParameter, Type> EMPTY_TYPE_ARG_MAP = Collections.<TypeParameter,Type>emptyMap(); static final Map<TypeParameter, SiteVariance> EMPTY_VARIANCE_MAP = emptyMap(); /** * Is the second scope contained by the first scope? */ public static boolean contains(Scope outer, Scope inner) { if (outer != null) { while (inner!=null) { if (inner.equals(outer)) { return true; } inner = inner.getScope(); } } return false; } /** * Get the nearest containing scope that is not a * ConditionScope. */ public static Scope getRealScope(Scope scope) { while (!(scope instanceof Package)) { if (!(scope instanceof ConditionScope)) { return scope; } scope = scope.getContainer(); } return null; } /** * Get the class or interface that "this" and "super" * refer to. */ public static ClassOrInterface getContainingClassOrInterface(Scope scope) { while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { return (ClassOrInterface) scope; } scope = scope.getContainer(); } return null; } /** * Get the declaration that contains the specified declaration, if any. */ public static Declaration getContainingDeclaration(Declaration d) { if (d.isToplevel()) return null; Scope scope = d.getContainer(); while (!(scope instanceof Package)) { if (scope instanceof Declaration) { return (Declaration) scope; } scope = scope.getContainer(); } return null; } /** * Get the declaration that contains the specified scope, if any. */ public static Declaration getContainingDeclarationOfScope(Scope scope) { while (!(scope instanceof Package)) { if (scope instanceof Declaration) { return (Declaration) scope; } scope = scope.getContainer(); } return null; } /** * Get the class or interface that "outer" refers to. */ public static Type getOuterClassOrInterface(Scope scope) { Boolean foundInner = false; while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { if (foundInner) { ClassOrInterface ci = (ClassOrInterface) scope; return ci.getType(); } else { foundInner = true; } } scope = scope.getContainer(); } return null; } /** * Convenience method to bind a single type argument * to a toplevel type declaration. */ public static Type appliedType( TypeDeclaration declaration, Type typeArgument) { if (declaration==null) return null; return declaration.appliedType(null, singletonList(typeArgument)); } /** * Convenience method to bind a list of type arguments * to a toplevel type declaration. */ public static Type appliedType( TypeDeclaration declaration, Type... typeArguments) { if (declaration==null) return null; return declaration.appliedType(null, asList(typeArguments)); } public static boolean isResolvable(Declaration declaration) { return declaration.getName()!=null && !declaration.isSetter() && //return getters, not setters !declaration.isAnonymous(); //don't return the type associated with an object dec } public static boolean isAbstraction(Declaration d) { return d!=null && d.isAbstraction(); } public static boolean notOverloaded(Declaration d) { if (d==null || !d.isFunctional()) { return true; } else { return !d.isOverloaded() || d.isAbstraction(); } } public static boolean isOverloadedVersion(Declaration decl) { return decl!=null && (decl.isOverloaded() && !decl.isAbstraction()) && !decl.isNative(); } static boolean hasMatchingSignature( Declaration dec, List<Type> signature, boolean ellipsis) { return hasMatchingSignature(dec, signature, ellipsis, true); } static boolean hasMatchingSignature( Declaration dec, List<Type> signature, boolean spread, boolean excludeAbstractClasses) { if (excludeAbstractClasses && dec instanceof Class && ((Class) dec).isAbstract()) { return false; } if (dec instanceof Functional) { if (dec.isAbstraction()) { return false; } Functional f = (Functional) dec; Unit unit = dec.getUnit(); List<ParameterList> pls = f.getParameterLists(); if (pls!=null && !pls.isEmpty()) { ParameterList pl = pls.get(0); List<Parameter> params = pl.getParameters(); int size = params.size(); boolean hasSeqParam = pl.hasSequencedParameter(); int sigSize = signature.size(); if (hasSeqParam) { size--; if (sigSize<size) { return false; } } else if (sigSize!=size) { return false; } for (int i=0; i<size; i++) { FunctionOrValue pm = params.get(i).getModel(); if (pm==null) { return false; } Type pdt = pm.appliedReference(null, NO_TYPE_ARGS) .getFullType(); if (pdt==null) { return false; } Type sdt = signature.get(i); if (!matches(sdt, pdt, unit)) { return false; } } if (hasSeqParam) { FunctionOrValue model = params.get(size).getModel(); Type pdt = model.appliedReference(null, NO_TYPE_ARGS) .getFullType(); if (pdt==null || pdt.getTypeArgumentList() .isEmpty()) { return false; } //Note: don't use Unit.getIterableType() // because this gets called from // model loader out-of-phase Type ipdt = pdt.getTypeArgumentList() .get(0); for (int i=size; i<sigSize; i++) { if (spread && i==sigSize-1) { Type sdt = signature.get(i); Type isdt = unit.getIteratedType(sdt); if (!matches(isdt, ipdt, unit)) { return false; } } else { Type sdt = signature.get(i); if (!matches(sdt, ipdt, unit)) { return false; } } } } else if (spread) { // if the method doesn't take sequenced // params and we have an ellipsis let's // not use it since we expect a variadic // method // TODO: this is basically wrong now that // we can spread tuples return false; } return true; } else { return false; } } else { return false; } } public static boolean matches( Type argType, Type paramType, Unit unit) { if (paramType==null || argType==null) { return false; } //Ignore optionality for resolving overloads, since //all Java parameters are treated as optional, //except primitive-typed parameters Type nvt = unit.getNullType(); if (nvt.isSubtypeOf(argType) && !nvt.isSubtypeOf(paramType)) { return false; //only for primitives } Type defParamType = unit.getDefiniteType(paramType); Type defArgType = unit.getDefiniteType(argType); Type nt = unit.getNullType(); if (defArgType.isSubtypeOf(nt)) { return true; } if (isTypeUnknown(defArgType) || isTypeUnknown(defParamType)) { return false; } if (!erase(defArgType, unit) .inherits(erase(defParamType, unit)) && notUnderlyingTypesEqual(defParamType, defArgType)) { return false; } return true; } private static boolean notUnderlyingTypesEqual( Type paramType, Type sigType) { String sut = sigType.getUnderlyingType(); String put = paramType.getUnderlyingType(); return sut==null || put==null || !sut.equals(put); } static boolean betterMatch(Declaration d, Declaration r, List<Type> signature) { if (d instanceof Functional && r instanceof Functional) { Functional df = (Functional) d; Functional rf = (Functional) r; List<ParameterList> dpls = df.getParameterLists(); List<ParameterList> rpls = rf.getParameterLists(); if (dpls!=null && !dpls.isEmpty() && rpls!=null && !rpls.isEmpty()) { ParameterList dpls0 = dpls.get(0); ParameterList rpls0 = rpls.get(0); List<Parameter> dpl = dpls0.getParameters(); List<Parameter> rpl = rpls0.getParameters(); int dplSize = dpl.size(); int rplSize = rpl.size(); //ignore sequenced parameters boolean dhsp = dpls0.hasSequencedParameter(); boolean rhsp = rpls0.hasSequencedParameter(); //always prefer a signature without varargs //over one with a varargs parameter if (!dhsp && rhsp) { return true; } if (dhsp && !rhsp) { return false; } //ignore sequenced parameters if (dhsp) dplSize--; if (rhsp) rplSize--; if (dplSize==rplSize) { //if all parameters are of more specific //or equal type, prefer it Unit unit = d.getUnit(); for (int i=0; i<dplSize; i++) { Type dplt = dpl.get(i).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type paramType = unit.getDefiniteType(dplt); Type rplt = rpl.get(i).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type otherType = unit.getDefiniteType(rplt); Type argumentType = signature != null && signature.size() >= i ? signature.get(i) : null; if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } TypeDeclaration ptd = erase(paramType, unit); TypeDeclaration otd = erase(otherType, unit); if(paramType.isExactly(otherType) && supportsCoercion(ptd) && // do we have different scores? hasWorseScore( getCoercionScore( argumentType, paramType), getCoercionScore( argumentType, otherType))) { return false; } if (!ptd.inherits(otd) && notUnderlyingTypesEqual( paramType, otherType)) { return false; } } // check sequenced parameters last if (dhsp && rhsp){ Type dplt = dpl.get(dplSize).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type paramType = unit.getDefiniteType(dplt); Type rplt = rpl.get(dplSize).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type otherType = unit.getDefiniteType(rplt); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } paramType = unit.getIteratedType(paramType); otherType = unit.getIteratedType(otherType); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } TypeDeclaration ptd = erase(paramType, unit); TypeDeclaration otd = erase(otherType, unit); if (paramType.isExactly(otherType) && supportsCoercion(ptd)) { Type widerArgumentType = getWiderArgumentType( paramType, signature, dplSize); // do we have different scores? int pscore = getCoercionScore( widerArgumentType, paramType); int oscore = getCoercionScore( widerArgumentType, otherType); if (hasWorseScore(pscore, oscore)) { return false; } } if (!ptd.inherits(otd) && notUnderlyingTypesEqual( paramType, otherType)) { return false; } } return true; } } } return false; } private static boolean supportsCoercion( TypeDeclaration decl) { return decl.isInteger() || decl.isFloat(); } private static boolean hasWorseScore( int underlyingTypeCoercionScoreA, int underlyingTypeCoercionScoreB) { if (underlyingTypeCoercionScoreA != underlyingTypeCoercionScoreB) { if (underlyingTypeCoercionScoreA > 0 && underlyingTypeCoercionScoreB > 0) { // both truncations, prefer the smaller // truncation if (underlyingTypeCoercionScoreA > underlyingTypeCoercionScoreB) { return true; } } else if(underlyingTypeCoercionScoreA > 0) { // A is a truncation, B is a widening, // prefer widening return true; } else if(underlyingTypeCoercionScoreA == 0) { // A is a perfect match, it's not worse return false; } else if(underlyingTypeCoercionScoreB == 0) { // B is a perfect match but A is not, // so it's worse return true; } else if(underlyingTypeCoercionScoreB > 0) { // A is a widening, B is a truncation, // so it's not worse return false; } else { // A is a widening and B is a widening too, // A is worse than B if it widens more than B return underlyingTypeCoercionScoreA < underlyingTypeCoercionScoreB; } } return false;// same score or we don't know } private static Type getWiderArgumentType( Type paramType, List<Type> signature, int startAt) { if (startAt >= signature.size()) { return null; } TypeDeclaration decl = paramType.getDeclaration(); Unit unit = decl.getUnit(); if (decl.isInteger()) { int bestScore = 0; Type ret = null; for(int i=startAt; i<signature.size(); i++){ Type argType = signature.get(i); String underlyingType = argType.getUnderlyingType(); int score = 0; if (underlyingType == null || underlyingType.equals("long")) { return argType; // found the wider sort } else if (underlyingType.equals("int")) { score = 2; } else if (underlyingType.equals("short")) { score = 1; } // keep the widest argument type if (score > bestScore) { bestScore = score; ret = argType; } } return ret; } else if (decl.equals(unit.getFloatDeclaration())) { int bestScore = 0; Type ret = null; for (int i=startAt; i<signature.size(); i++) { Type argType = signature.get(i); String underlyingType = argType.getUnderlyingType(); int score = 0; if (underlyingType == null || underlyingType.equals("double")) { return argType; // found the wider sort } else if (underlyingType.equals("float")) { score = 1; } // keep the widest argument type if (score > bestScore){ bestScore = score; ret = argType; } } return ret; } // not relevant return null; } /** * Returns 0 of there's no coercion, > 0 if we have to * truncate the argument type to fit the param type, * the higher for the worse truncation, or < 0 if we * have to widen the argument type to fit the param type, * the lower for the worse widening. */ private static int getCoercionScore( Type argumentType, Type paramType) { if (argumentType == null) { return 0; } // only consider types of Integer of Float if (paramType.isExactly(argumentType)) { String aType = argumentType.getUnderlyingType(); String pType = paramType.getUnderlyingType(); if (aType == null && pType == null) { return 0; } Unit unit = argumentType.getDeclaration().getUnit(); TypeDeclaration decl = paramType.getDeclaration(); if (decl.isInteger()) { if (aType == null) { aType = "long"; } if (pType == null) { pType = "long"; } int aScore = getPrimitiveScore(aType); int bScore = getPrimitiveScore(pType); /* * aType aTypeScore pType pTypeScore score * short 0 short 0 0 * short 0 int 1 -1 (widening) * short 0 long 2 -2 (widening) * int 1 short 0 1 (truncation) * int 1 int 1 0 * int 1 long 2 -1 (widening) * long 2 short 0 2 (truncation) * long 2 int 1 1 (truncation) * long 2 long 2 0 */ return aScore - bScore; } else if (decl.equals(unit.getFloatDeclaration())) { if (aType == null) { aType = "double"; } if (pType == null) { pType = "double"; } int aScore = getPrimitiveScore(aType); int bScore = getPrimitiveScore(pType); /* * aType aTypeScore pType pTypeScore score * float 0 float 0 0 * float 0 double 1 -1 (widening) * double 1 float 0 1 (truncation) * double 1 double 1 0 */ return aScore - bScore; } } // no truncation for the rest return 0; } private static int getPrimitiveScore(String underlyingType) { if (underlyingType.equals("long")) { return 2; } if (underlyingType.equals("int") || underlyingType.equals("double")) { return 1; } if (underlyingType.equals("short") || underlyingType.equals("float")) { return 0; } return 0; } static boolean strictlyBetterMatch(Declaration d, Declaration r) { if (d instanceof Functional && r instanceof Functional) { Functional fd = (Functional) d; Functional fr = (Functional) r; List<ParameterList> dpls = fd.getParameterLists(); List<ParameterList> rpls = fr.getParameterLists(); if (dpls!=null && !dpls.isEmpty() && rpls!=null && !rpls.isEmpty()) { ParameterList dpls0 = dpls.get(0); ParameterList rpls0 = rpls.get(0); List<Parameter> dpl = dpls0.getParameters(); List<Parameter> rpl = rpls0.getParameters(); int dplSize = dpl.size(); int rplSize = rpl.size(); //ignore sequenced parameters boolean dhsp = dpls0.hasSequencedParameter(); boolean rhsp = rpls0.hasSequencedParameter(); //always prefer a signature without varargs //over one with a varargs parameter if (!dhsp && rhsp) { return true; } if (dhsp && !rhsp) { return false; } //ignore sequenced parameters if (dhsp) dplSize--; if (rhsp) rplSize--; if (dplSize==rplSize) { //if all parameters are of more specific //or equal type, prefer it boolean atLeastOneBetter = false; Unit unit = d.getUnit(); for (int i=0; i<dplSize; i++) { Type dplt = dpl.get(i).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type paramType = unit.getDefiniteType(dplt); Type rplt = rpl.get(i).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type otherType = unit.getDefiniteType(rplt); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } TypeDeclaration ptd = erase(paramType, unit); TypeDeclaration otd = erase(otherType, unit); if (!ptd.inherits(otd) && notUnderlyingTypesEqual( paramType, otherType)) { return false; } if (ptd.inherits(otd) && !otd.inherits(ptd) && notUnderlyingTypesEqual( paramType, otherType)) { atLeastOneBetter = true; } } // check sequenced parameters last if (dhsp && rhsp) { Type dplt = dpl.get(dplSize).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type paramType = unit.getDefiniteType(dplt); Type rplt = rpl.get(dplSize).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type otherType = unit.getDefiniteType(rplt); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } paramType = unit.getIteratedType(paramType); otherType = unit.getIteratedType(otherType); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } TypeDeclaration ptd = erase(paramType, unit); TypeDeclaration otd = erase(otherType, unit); if (!ptd.inherits(otd) && notUnderlyingTypesEqual( paramType, otherType)) { return false; } if (ptd.inherits(otd) && !otd.inherits(ptd) && notUnderlyingTypesEqual( paramType, otherType)) { atLeastOneBetter = true; } } return atLeastOneBetter; } } } return false; } public static boolean isNamed(String name, Declaration d) { String dname = d.getName(); return dname!=null && dname.equals(name); } static TypeDeclaration erase(Type paramType, Unit unit) { if (paramType.isTypeParameter()) { if (paramType.getSatisfiedTypes().isEmpty()) { Type et = paramType.getExtendedType(); return et==null ? null : et.getDeclaration(); } else { //TODO: Is this actually correct? // What is Java's rule here? Type st = paramType.getSatisfiedTypes() .get(0); return st==null ? null : st.getDeclaration(); } } else if (paramType.isUnion()) { //TODO: this is very sucky, cos in theory a // union might be assignable to the // parameter type with a typecast return unit.getObjectDeclaration(); } else if (paramType.isIntersection()) { List<Type> sts = paramType.getSatisfiedTypes(); if (sts.size()==2) { //attempt to eliminate Basic from the //intersection - very useful for anonymous //classes, whose denotableType is often an //intersection with Basic Type first = sts.get(0); Type second = sts.get(1); if (first!=null && first.isBasic()) { return erase(second, unit); } else if (second!=null && second.isBasic()) { return erase(first, unit); } } //TODO: this is very sucky, cos in theory an // intersection might be assignable to the // parameter type with a typecast return unit.getObjectDeclaration(); } else { return paramType.getDeclaration(); } } /** * Match the name of the given declaration to the given * pattern. A name matches if: * * - it starts with the pattern, ignoring case, or * - the pattern consists of all uppercase after the * first character, and its uppercase "humps" match * the pattern. */ public static boolean isNameMatching( String startingWith, Declaration d) { return isNameMatching(startingWith, d.getName()); } public static boolean isNameMatching( String startingWith, Import i) { return isNameMatching(startingWith, i.getAlias()); } public static boolean isNameMatching( String startingWith, String name) { if (startingWith==null || startingWith.isEmpty()) { return true; } if (name==null || name.isEmpty()) { return false; } int nameLength = name.length(); int startingWithLength = startingWith.length(); if (nameLength<startingWithLength) { return false; } if (name.regionMatches(true,0,startingWith,0,startingWithLength)) { return true; } int c = startingWith.codePointAt(0); int d = name.codePointAt(0); if (c!=d) { return false; } //camel hump matching, starting from second character: int i=1, j=1; while (i<startingWithLength) { if (j>=nameLength) { return false; } while (i<startingWithLength && isLowerCase(c=startingWith.codePointAt(i))) { d = name.codePointAt(j); if (c==d) { i+=charCount(c); j+=charCount(d); if (i>=startingWithLength) { return true; } if (j>=nameLength) { return false; } } else { return false; } } while (j<nameLength && isLowerCase(d=name.codePointAt(j))) { j+=charCount(d); if (j>=nameLength) { return false; } } c = startingWith.codePointAt(i); d = name.codePointAt(j); i+=charCount(c); j+=charCount(d); if (d!=c) { return false; } } return true; } /** * Given a declaration, a list of type arguments to the * declaration, and a receiving type, collect together * all interesting type arguments. The resulting map * includes all type arguments from the receiving type * and all its qualifying types. That's useful, because * {@link Type.Substitution} works with a single * aggregated map, and so for performance * {@link Type#substitute(Type)} and * {@link Type#substitute(TypedReference)} * assume that the given type or reference holds such a * single aggregated map. * * @return a map of type parameter to type argument * * @param declaration a declaration * @param receivingType the receiving produced type * of which the declaration is a member * @param typeArguments all the explicit or inferred * type arguments of the declaration, including * those from qualifying types */ public static Map<TypeParameter,Type> getTypeArgumentMap(Declaration declaration, Type receivingType, List<Type> typeArguments) { List<TypeParameter> typeParameters = getTypeParameters(declaration); int count = countTypeParameters(receivingType, typeParameters); if (count==0) { return EMPTY_TYPE_ARG_MAP; } else { return aggregateTypeArguments(receivingType, typeArguments, typeParameters, count); } } private static Map<TypeParameter, Type> aggregateTypeArguments(Type receivingType, List<Type> typeArguments, List<TypeParameter> typeParameters, int count) { Map<TypeParameter,Type> map = new HashMap<TypeParameter,Type> (count); //make sure we collect all type arguments //from the whole qualified type! if (receivingType!=null) { if (receivingType.isIntersection()) { for (Type dt: receivingType.getSatisfiedTypes()) { while (dt!=null) { map.putAll(dt.getTypeArguments()); dt = dt.getQualifyingType(); } } } else { Type dt = receivingType; while (dt!=null) { map.putAll(dt.getTypeArguments()); dt = dt.getQualifyingType(); } } } if (typeArguments!=null) { //now turn the type argument tuple into a //map from type parameter to argument for (int i=0; i<typeParameters.size() && i<typeArguments.size(); i++) { map.put(typeParameters.get(i), typeArguments.get(i)); } } return map; } public static Map<TypeParameter,SiteVariance> getVarianceMap(Declaration declaration, Type receivingType, List<SiteVariance> variances) { if (variances==null) { return EMPTY_VARIANCE_MAP; } else { List<TypeParameter> typeParameters = getTypeParameters(declaration); int count = countTypeParameters(receivingType, typeParameters); if (count==0) { return EMPTY_VARIANCE_MAP; } else { return aggregateVariances(receivingType, variances, typeParameters); } } } private static Map<TypeParameter, SiteVariance> aggregateVariances(Type receivingType, List<SiteVariance> variances, List<TypeParameter> typeParameters) { Map<TypeParameter,SiteVariance> map = new HashMap<TypeParameter,SiteVariance>(); //make sure we collect all type arguments //from the whole qualified type! if (receivingType!=null) { if (receivingType.isIntersection()) { for (Type dt: receivingType.getSatisfiedTypes()) { while (dt!=null) { map.putAll(dt.getVarianceOverrides()); dt = dt.getQualifyingType(); } } } else { Type dt = receivingType; while (dt!=null) { map.putAll(dt.getVarianceOverrides()); dt = dt.getQualifyingType(); } } } for (int i=0; i<typeParameters.size() && i<variances.size(); i++) { SiteVariance var = variances.get(i); if (var!=null) { map.put(typeParameters.get(i), var); } } return map; } private static int countTypeParameters( Type receivingType, List<TypeParameter> typeParameters) { int count = typeParameters.size(); //make sure we count all type arguments //from the whole qualified type! if (receivingType!=null) { if (receivingType.isIntersection()) { for (Type dt: receivingType.getSatisfiedTypes()) { while (dt!=null) { count += dt.getTypeArguments().size(); dt = dt.getQualifyingType(); } } } else { Type dt = receivingType; while (dt!=null) { count += dt.getTypeArguments().size(); dt = dt.getQualifyingType(); } } } return count; } public static List<TypeParameter> getTypeParameters( Declaration declaration) { if (declaration instanceof Generic) { Generic g = (Generic) declaration; return g.getTypeParameters(); } else { return emptyList(); } } static <T> List<T> list(List<T> list, T element) { List<T> result = new ArrayList<T>(list.size()+1); result.addAll(list); result.add(element); return result; } /** * Helper method for eliminating duplicate types from * lists of types that form a union type, taking into * account that a subtype is a "duplicate" of its * supertype. */ public static void addToUnion(List<Type> list, Type pt) { if (pt==null || !list.isEmpty() && pt.isNothing()) { return; } else if (pt.isAnything()) { list.clear(); list.add(pt); } else if (pt.isUnion()) { List<Type> caseTypes = pt.getCaseTypes(); for ( int i=0, size=caseTypes.size(); i<size; i++ ) { Type t = caseTypes.get(i); addToUnion(list, t.substitute(pt)); } } else if (pt.isWellDefined()) { boolean add=true; for (int i=0; i<list.size(); i++) { Type t = list.get(i); if (pt.isSubtypeOf(t)) { add=false; break; } else if (pt.isSupertypeOf(t)) { list.remove(i); i--; // redo this index } } if (add) { list.add(pt); } } } /** * Helper method for eliminating duplicate types from * lists of types that form an intersection type, taking * into account that a supertype is a "duplicate" of its * subtype. */ public static void addToIntersection(List<Type> list, Type type, Unit unit) { if (type==null || !list.isEmpty() && type.isAnything()) { return; } else if (type.isNothing()) { list.clear(); list.add(type); } else if (type.isIntersection()) { List<Type> satisfiedTypes = type.getSatisfiedTypes(); for (int i=0, size=satisfiedTypes.size(); i<size; i++) { Type t = satisfiedTypes.get(i); addToIntersection(list, t, unit); } } else { if (type.isWellDefined()) { TypeDeclaration dec = type.getDeclaration(); for (int i=0; i<list.size(); i++) { Type t = list.get(i); if (t.isSubtypeOf(type)) { return; } else if (type.isSubtypeOf(t)) { list.remove(i); i--; // redo this index } else if (disjoint(type, t, unit)) { list.clear(); list.add(unit.getNothingType()); return; } else { if (type.isClassOrInterface() && t.isClassOrInterface() && t.getDeclaration().equals(dec) && !type.containsUnknowns() && !t.containsUnknowns()) { //canonicalize a type of form //T<InX,OutX>&T<InY,OutY> to //T<InX|InY,OutX&OutY> Type pi = principalInstantiation( dec, type, t, unit); if (!pi.containsUnknowns()) { list.remove(i); list.add(pi); return; } } } } if (list.size()>1) { //it is possible to have a type that is //a supertype of the intersection, even //though it is not a supertype of any of //the intersected types! Type t = canonicalIntersection(list, unit); if (type.isSupertypeOf(t)) { return; } } list.add(type); } } } /** * Are the given types disjoint? * * @param p the first type * @param q the second type * enumerated type are disjoint * @param unit * * @return true if the types are disjoint */ private static boolean disjoint(Type p, Type q, Unit unit) { if (q.getDeclaration() .isDisjoint(p.getDeclaration())) { return true; } else { //we have to resolve aliases here, or computing //supertype declarations gets incredibly slow //for the big stack of union type aliases in //ceylon.ast Type ps = p.resolveAliases(); Type qs = q.resolveAliases(); return emptyMeet(ps, qs, unit) || hasEmptyIntersectionOfInvariantInstantiations(ps, qs); } } /** * implement the rule that Foo&Bar==Nothing if * here exists some enumerated type Baz with * * Baz of Foo | Bar * * (the intersection of disjoint types is empty) * * @param type a type which might be disjoint from * a list of other given types * @param list the list of other types * @param unit * * @return true of the given type was disjoint from * the given list of types */ /*private static boolean reduceIfDisjoint(Type type, List<Type> list, Unit unit) { if (list.isEmpty()) { return false; } TypeDeclaration typeDec = type.getDeclaration(); List<TypeDeclaration> supertypes = typeDec.getSupertypeDeclarations(); for (int i=0, l=supertypes.size(); i<l; i++) { TypeDeclaration supertype = supertypes.get(i); List<Type> cts = supertype.getCaseTypes(); if (cts!=null) { TypeDeclaration ctd=null; for (int cti=0, ctl=cts.size(); cti<ctl; cti++) { TypeDeclaration ct = cts.get(cti) .getDeclaration(); if (typeDec.inherits(ct)) { ctd = ct; break; } } if (ctd!=null) { for (int cti=0, ctl=cts.size(); cti<ctl; cti++) { TypeDeclaration ct = cts.get(cti) .getDeclaration(); if (ct!=ctd) { for (int ti=0, tl=list.size(); ti<tl; ti++) { Type t = list.get(ti); if (t.getDeclaration() .inherits(ct)) { return true; } } } } } } } return false; }*/ /** * The meet of two classes unrelated by inheritance, * or of Null with an interface type is empty. The meet * of an anonymous class with a type to which it is not * assignable is empty. */ private static boolean emptyMeet( Type p, Type q, Unit unit) { if (p==null || q==null) { return false; } if (p.isNothing() || q.isNothing()) { return true; } TypeDeclaration pd = p.getDeclaration(); TypeDeclaration qd = q.getDeclaration(); if (p.isTypeParameter()) { p = canonicalIntersection( p.getSatisfiedTypes(), unit); pd = p.getDeclaration(); } if (q.isTypeParameter()) { q = canonicalIntersection( q.getSatisfiedTypes(), unit); qd = q.getDeclaration(); } if (q.isIntersection()) { for (Type t: q.getSatisfiedTypes()) { if (emptyMeet(p,t,unit)) { return true; } } return false; } if (p.isIntersection()) { for (Type t: p.getSatisfiedTypes()) { if (emptyMeet(q,t,unit)) { return true; } } return false; } if (q.isUnion()) { for (Type t: q.getCaseTypes()) { if (!emptyMeet(p,t,unit)) { return false; } } return true; } else if (qd.getCaseTypes()!=null) { boolean all = true; for (Type t: qd.getCaseTypes()) { if (t.getDeclaration().isSelfType() || !emptyMeet(p,t,unit)) { all = false; break; } } if (all) return true; } if (p.isUnion()) { for (Type t: p.getCaseTypes()) { if (!emptyMeet(q,t,unit)) { return false; } } return true; } else if (p.getCaseTypes()!=null) { boolean all = true; for (Type t: pd.getCaseTypes()) { if (t.getDeclaration().isSelfType() || !emptyMeet(q,t,unit)) { all = false; break; } } if (all) return true; } if (p.isClass() && q.isClass() || p.isInterface() && q.isNull() || q.isInterface() && p.isNull()) { if (!qd.inherits(pd) && !pd.inherits(qd)) { return true; } } if (pd.isFinal()) { if (pd.getTypeParameters().isEmpty() && !q.involvesTypeParameters() && !p.isSubtypeOf(q) && !(qd instanceof UnknownType)) { return true; } if (q.isClassOrInterface() && !pd.inherits(qd)) { return true; } } if (qd.isFinal()) { if (qd.getTypeParameters().isEmpty() && !p.involvesTypeParameters() && !q.isSubtypeOf(p) && !(p.isUnknown())) { return true; } if (p.isClassOrInterface() && !qd.inherits(pd)) { return true; } } // Interface ed = unit.getEmptyDeclaration(); // Interface id = unit.getIterableDeclaration(); // if (pd.inherits(ed) && qd.inherits(id) && // unit.isNonemptyIterableType(q) || // pd.inherits(id) && qd.inherits(ed) && // unit.isNonemptyIterableType(p)) { // return true; // } Interface st = unit.getSequentialDeclaration(); if (q.isClassOrInterface() && pd.inherits(st) && !qd.inherits(st) && !st.inherits(qd) || p.isClassOrInterface() && qd.inherits(st) && !pd.inherits(st) && !st.inherits(pd) && !p.involvesTypeParameters()) { return true; } Interface nst = unit.getSequenceDeclaration(); if (pd.inherits(nst) && qd.inherits(st) || qd.inherits(nst) && pd.inherits(st)) { Type pet = unit.getSequentialElementType(p); Type qet = unit.getSequentialElementType(q); if (emptyMeet(pet, qet, unit)) { return true; } } Class td = unit.getTupleDeclaration(); if (pd.inherits(td) && qd.inherits(td)) { List<Type> pal = p.getTypeArgumentList(); List<Type> qal = q.getTypeArgumentList(); if (pal.size()>=3 && qal.size()>=3) { if (emptyMeet(pal.get(1), qal.get(1), unit) || emptyMeet(pal.get(2), qal.get(2), unit)) { return true; } } } if (pd.inherits(td) && qd.inherits(st)) { List<Type> pal = p.getTypeArgumentList(); Type qet = unit.getSequentialElementType(q); if (pal.size()>=3) { if (emptyMeet(pal.get(1), qet, unit) || emptyMeet(pal.get(2), unit.getSequentialType(qet), unit)) { return true; } } } if (qd.inherits(td) && pd.inherits(st)) { List<Type> qal = q.getTypeArgumentList(); Type pet = unit.getSequentialElementType(p); if (qal.size()>=3) { if (emptyMeet(qal.get(1), pet, unit) || emptyMeet(qal.get(2), unit.getSequentialType(pet), unit)) { return true; } } } return false; } /** * Given two instantiations of a qualified type * constructor, determine the qualifying type of the * principal instantiation of that type constructor for * the intersection of the two types. */ static Type principalQualifyingType( Type pt, Type t, TypeDeclaration td, Unit unit) { Type ptqt = pt.getQualifyingType(); Type tqt = t.getQualifyingType(); Scope tdc = td.getContainer(); if (ptqt!=null && tqt!=null && tdc instanceof TypeDeclaration) { TypeDeclaration qtd = (TypeDeclaration) tdc; Type pst = ptqt.getSupertype(qtd); Type st = tqt.getSupertype(qtd); if (pst!=null && st!=null) { return principalInstantiation(qtd, pst, st, unit); } } return null; } /** * Determine if a type of form X<P>&X<Q> is equivalent * to Nothing where X<T> is invariant in T. * * @param p the argument type P * @param q the argument type Q */ private static boolean hasEmptyIntersectionOfInvariantInstantiations( Type p, Type q) { List<TypeDeclaration> pstds = p.getDeclaration() .getSupertypeDeclarations(); List<TypeDeclaration> qstds = q.getDeclaration() .getSupertypeDeclarations(); Set<TypeDeclaration> set = new HashSet<TypeDeclaration> (pstds.size()+qstds.size()); set.addAll(pstds); set.retainAll(qstds); for (TypeDeclaration std: pstds) { Type pst = null; Type qst = null; for (TypeParameter tp: std.getTypeParameters()) { if (tp.isInvariant()) { if (pst==null) { pst = p.getSupertype(std); } if (qst==null) { qst = q.getSupertype(std); } if (pst!=null && qst!=null) { Type psta = pst.getTypeArguments() .get(tp); Type qsta = qst.getTypeArguments() .get(tp); //TODO: why isWellDefined() instead of isTypeUnknown() ? if (psta!=null && psta.isWellDefined() && !pst.involvesTypeParameters() && qsta!=null && qsta.isWellDefined() && !qst.involvesTypeParameters()) { boolean psti = pst.isInvariant(tp); boolean pstcov = pst.isCovariant(tp); boolean pstcontra = pst.isContravariant(tp); boolean qsti = qst.isInvariant(tp); boolean qstcov = qst.isCovariant(tp); boolean qstcontra = qst.isContravariant(tp); if (psti && qsti && !psta.isExactly(qsta) || pstcov && qsti && !qsta.isSubtypeOf(psta) || qstcov && psti && !psta.isSubtypeOf(qsta) || pstcontra && qsti && !psta.isSubtypeOf(qsta) || qstcontra && psti && !qsta.isSubtypeOf(psta)) { return true; } } } } } } return false; } public static String formatPath(List<String> path, char separator) { StringBuilder sb = new StringBuilder(); for (int i=0; i<path.size(); i++) { String pathPart = path.get(i); if (! pathPart.isEmpty()) { sb.append(pathPart); if (i<path.size()-1) sb.append(separator); } } return sb.toString(); } public static String formatPath(List<String> path) { return formatPath(path, '.'); } /** * Form the union of the given types, eliminating * duplicates. */ public static Type unionType( Type lhst, Type rhst, Unit unit) { List<Type> list = new ArrayList<Type>(2); addToUnion(list, rhst); addToUnion(list, lhst); UnionType ut = new UnionType(unit); ut.setCaseTypes(list); return ut.getType(); } /** * Form the intersection of the given types, * canonicalizing, and eliminating duplicates. */ public static Type intersectionType( Type lhst, Type rhst, Unit unit) { Type simpleIntersection = getSimpleIntersection(lhst, rhst); if (simpleIntersection != null) { return simpleIntersection; } List<Type> list = new ArrayList<Type>(2); addToIntersection(list, rhst, unit); addToIntersection(list, lhst, unit); IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(list); return it.canonicalize().getType(); } /** * Form the union of the given types, without * eliminating duplicates. */ public static Type union( List<Type> types, Unit unit) { if (types.size()==1) { return types.get(0); } UnionType ut = new UnionType(unit); ut.setCaseTypes(types); return ut.getType(); } /** * Form the intersection of the given types, without * eliminating duplicates nor canonicalizing. */ public static Type intersection( List<Type> types, Unit unit) { if (types.size()==1) { return types.get(0); } IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(types); return it.getType(); } /** * Form the canonical intersection of the given types, * without eliminating duplicates. */ public static Type canonicalIntersection( List<Type> types, Unit unit) { if (types.size()==1) { return types.get(0); } IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(types); return it.canonicalize().getType(); } private static Type getSimpleIntersection( Type a, Type b) { if (a == null || b == null) { return null; } TypeDeclaration ad = a.getDeclaration(); TypeDeclaration bd = b.getDeclaration(); if (ad == null || bd == null) { return null; } if (!a.isClassOrInterface()) { if (a.isUnion() && b.isClassOrInterface()) { return getSimpleIntersection(b, (ClassOrInterface) bd, a); } return null; } else if (!b.isClassOrInterface()) { // here aDecl MUST BE a ClassOrInterface as per flow if (b.isUnion()) { return getSimpleIntersection(a, (ClassOrInterface) ad, b); } return null; } String an = ad.getQualifiedNameString(); String bn = bd.getQualifiedNameString(); if (an.equals(bn) && ad.getTypeParameters().isEmpty() && bd.getTypeParameters().isEmpty()) return a; if (a.isAnything()) { // everything is an Anything return b; } if (b.isAnything()) { // everything is an Anything return a; } if (a.isObject()) { // every ClassOrInterface is an object except Null if (b.isNull() || b.isNullValue()) { return ad.getUnit().getNothingType(); } else { return b; } } if (b.isObject()) { // every ClassOrInterface is an object except Null if (a.isNull() || a.isNullValue()) { return bd.getUnit().getNothingType(); } else { return a; } } if (a.isNull()) { // only null is null if (b.isNull() || b.isNullValue()) { return b; } else { return ad.getUnit().getNothingType(); } } if (b.isNull()) { // only null is null if (a.isNull() || a.isNullValue()) { return a; } else { return bd.getUnit().getNothingType(); } } // not simple return null; } private static Type getSimpleIntersection( Type a, ClassOrInterface aDecl, Type b) { // we only handle Foo|Null if (b.getCaseTypes().size() != 2) { return null; } // we only handle Object and Null intersections boolean aIsObject = a.isObject(); boolean aIsNull = a.isNull(); if (!aIsObject && !aIsNull) { return null; } Type caseA = b.getCaseTypes().get(0); Type caseB = b.getCaseTypes().get(1); boolean isANull = caseA.isNull(); boolean isBNull = caseB.isNull(); if (aIsObject) { if (isANull) { return simpleObjectIntersection(aDecl, caseB); } if (isBNull) { return simpleObjectIntersection(aDecl, caseA); } // too complex return null; } if (aIsNull) { if (isANull) { return caseA; } if (isBNull) { return caseB; } // too complex return null; } // too complex return null; } private static Type simpleObjectIntersection( ClassOrInterface objectDecl, Type type) { if (type.isClassOrInterface()) { return type; } else if (type.isTypeParameter()) { List<Type> satisfiedTypes = type.getSatisfiedTypes(); if (satisfiedTypes.isEmpty()) { // trivial intersection TP&Object Unit unit = objectDecl.getUnit(); List<Type> types = new ArrayList<Type>(2); types.add(type); types.add(objectDecl.getType()); return canonicalIntersection(types, unit); } for (Type sat: satisfiedTypes) { if (sat.isObject()) { // it is already an Object return type; } } // too complex return null; } // too complex return null; } public static boolean isElementOfUnion( Type unionType, ClassOrInterface ci) { for (Type ct: unionType.getCaseTypes()) { if (ct.isClassOrInterface() && ct.getDeclaration().equals(ci)) { return true; } } return false; } /** * Find the member which best matches the given signature * among the given list of members. In the case that * there are multiple matching declarations, attempt to * return the "best" match, according to some ad-hoc * rules that roughly follow how Java resolves * overloaded methods. * * @param members a list of members to search * @param name the name of the member to find * @param signature the parameter types to match, or * null if we're not matching on parameter types * @param ellipsis true of we want to find a declaration * which supports varags, or false otherwise * * @return the best matching declaration */ public static Declaration lookupMember( List<Declaration> members, String name, List<Type> signature, boolean ellipsis) { List<Declaration> results = null; Declaration result = null; Declaration inexactMatch = null; for (int i=0, size=members.size(); i<size ; i++) { Declaration d = members.get(i); if (isResolvable(d) && isNamed(name, d)) { if (signature==null) { //no argument types: either a type //declaration, an attribute, or a method //reference - don't return overloaded //forms of the declaration (instead //return the "abstraction" of them) if (notOverloaded(d)) { return d; } } else { if (notOverloaded(d)) { //we have found either a non-overloaded //declaration, or the "abstraction" //which of all the overloaded forms //of the declaration //Note: I could not do this optimization // because then it could not distinguish // between Java open() and isOpen() /*if (!isAbstraction(d)) { return d; }*/ inexactMatch = d; } if (hasMatchingSignature(d, signature, ellipsis)) { //we have found an exactly matching //overloaded declaration if (result == null) { result = d; // first match } else { // more than one match, move to array if (results == null) { results = new ArrayList<Declaration>(2); results.add(result); } addIfBetterMatch(results, d, signature); } } } } } // if we never needed a results array if (results == null) { // single result if (result != null) { return result; } // no exact match return inexactMatch; } switch (results.size()) { case 0: //no exact match, so return the non-overloaded //declaration or the "abstraction" of the //overloaded declaration return inexactMatch; case 1: //exactly one exact match, so return it return results.get(0); default: //more than one matching overloaded declaration, //so return the "abstraction" of the overloaded //declaration return inexactMatch; } } private static void addIfBetterMatch( List<Declaration> results, Declaration d, List<Type> signature) { boolean add=true; for (Iterator<Declaration> i = results.iterator(); i.hasNext();) { Declaration o = i.next(); if (betterMatch(d, o, signature)) { i.remove(); } else if (betterMatch(o, d, signature)) { //TODO: note asymmetry here resulting in nondeterminate behavior! add=false; } } if (add) results.add(d); } public static Declaration findMatchingOverloadedClass( Class abstractionClass, List<Type> signature, boolean ellipsis) { List<Declaration> results = new ArrayList<Declaration>(1); if (!abstractionClass.isAbstraction()) { return abstractionClass; } for (Declaration overloaded: abstractionClass.getOverloads()) { if (hasMatchingSignature(overloaded, signature, ellipsis, false)) { addIfBetterMatch(results, overloaded, signature); } } if (results.size() == 1) { return results.get(0); } return abstractionClass; } public static boolean isTypeUnknown(Type type) { return type==null || type.getDeclaration()==null || type.containsUnknowns(); } public static List<Type> getSignature( Declaration dec) { if (!(dec instanceof Functional)) { return null; } Functional fun = (Functional) dec; List<ParameterList> parameterLists = fun.getParameterLists(); if (parameterLists == null || parameterLists.isEmpty()) { return null; } ParameterList parameterList = parameterLists.get(0); if (parameterList == null) { return null; } List<Parameter> parameters = parameterList.getParameters(); if (parameters == null) { return null; } List<Type> signature = new ArrayList<Type> (parameters.size()); Unit unit = dec.getUnit(); for (Parameter param: parameters) { FunctionOrValue model = param.getModel(); Type t = model==null ? unit.getUnknownType() : model.getType(); signature.add(t); } return signature; } public static boolean isCompletelyVisible( Declaration member, Type pt) { if (pt.isUnion()) { for (Type ct: pt.getCaseTypes()) { if (!isCompletelyVisible(member, ct.substitute(pt))) { return false; } } return true; } else if (pt.isIntersection()) { for (Type ct: pt.getSatisfiedTypes()) { if (!isCompletelyVisible(member, ct.substitute(pt))) { return false; } } return true; } else { if (!isVisible(member, pt.getDeclaration())) { return false; } for (Type at: pt.getTypeArgumentList()) { if (at!=null && !isCompletelyVisible(member, at)) { return false; } } return true; } } static boolean isVisible(Declaration member, TypeDeclaration type) { return type instanceof TypeParameter || type.isVisible(member.getVisibleScope()) && (member.getVisibleScope()!=null || !member.getUnit().getPackage().isShared() || type.getUnit().getPackage().isShared()); } /** * Given two instantiations of the same type constructor, * construct a principal instantiation that is a supertype * of both. This is impossible in the following special * cases: * * - an abstract class which does not obey the principal * instantiation inheritance rule * - an intersection between two instantiations of the * same type where one argument is a type parameter * * Nevertheless, we give it our best shot! */ public static Type principalInstantiation( TypeDeclaration dec, Type first, Type second, Unit unit) { List<TypeParameter> tps = dec.getTypeParameters(); List<Type> args = new ArrayList<Type>(tps.size()); Map<TypeParameter,SiteVariance> varianceOverrides = new HashMap<TypeParameter,SiteVariance>(1); for (TypeParameter tp: tps) { Type firstArg = first.getTypeArguments().get(tp); Type secondArg = second.getTypeArguments().get(tp); Type arg; if (firstArg==null || secondArg==null) { arg = unit.getUnknownType(); } else { boolean firstCo = first.isCovariant(tp); boolean secondCo = second.isCovariant(tp); boolean firstContra = first.isContravariant(tp); boolean secondContra = second.isContravariant(tp); boolean firstInv = !firstCo && !firstContra; boolean secondInv = !secondCo && !secondContra; boolean parameterized = firstArg.involvesTypeParameters() || secondArg.involvesTypeParameters(); if (firstContra && secondContra) { arg = unionType( firstArg, secondArg, unit); if (!tp.isContravariant()) { varianceOverrides.put(tp, IN); } } else if (firstCo && secondCo) { arg = intersectionType( firstArg, secondArg, unit); if (!tp.isCovariant()) { varianceOverrides.put(tp, OUT); } } else if (firstContra && secondInv) { if (firstArg.isSubtypeOf(secondArg)) { arg = secondArg; } else if (parameterized) { //irreconcilable instantiations arg = unit.getUnknownType(); } else { return unit.getNothingType(); } } else if (firstCo && secondInv) { if (secondArg.isSubtypeOf(firstArg)) { arg = secondArg; } else if (parameterized) { //irreconcilable instantiations arg = unit.getUnknownType(); } else { return unit.getNothingType(); } } else if (secondCo && firstInv) { if (firstArg.isSubtypeOf(secondArg)) { arg = firstArg; } else if (parameterized) { //irreconcilable instantiations arg = unit.getUnknownType(); } else { return unit.getNothingType(); } } else if (secondContra && firstInv) { if (secondArg.isSubtypeOf(firstArg)) { arg = firstArg; } else if (parameterized) { //irreconcilable instantiations arg = unit.getUnknownType(); } else { return unit.getNothingType(); } } else if (firstInv && secondInv) { if (firstArg.isExactly(secondArg)) { arg = firstArg; } else if (parameterized) { //type parameters that might represent //equivalent types at runtime, //irreconcilable instantiations //TODO: detect cases where we know for // sure that the types are disjoint // because the type parameters only // occur as type args arg = unit.getUnknownType(); } else { //the type arguments are distinct, and the //intersection is Nothing, so there is //no reasonable principal instantiation return unit.getNothingType(); } } else { //opposite variances //irreconcilable instantiations arg = unit.getUnknownType(); } } args.add(arg); } Type result = dec.appliedType(principalQualifyingType( first, second, dec, unit), args); result.setVarianceOverrides(varianceOverrides); return result; } public static boolean areConsistentSupertypes( Type st1, Type st2, Unit unit) { //can't inherit two instantiations of an invariant type //Note: I don't think we need to check type parameters of // the qualifying type, since you're not allowed to // subtype an arbitrary instantiation of a nested // type - only supertypes of the outer type // Nor do we need to check variance overrides since // supertypes can't have them. List<TypeParameter> typeParameters = st1.getDeclaration().getTypeParameters(); for (TypeParameter tp: typeParameters) { if (!tp.isCovariant() && !tp.isContravariant()) { Type ta1 = st1.getTypeArguments().get(tp); Type ta2 = st2.getTypeArguments().get(tp); if (ta1!=null && ta2!=null && !ta1.isExactly(ta2)) { return false; } } } return !intersectionType(st1, st2, unit).isNothing(); } /** * The intersection of the types inherited of the given * declaration. No need to worry about canonicalization * because: * * 1. an inherited type can't be a union, and * 2. they are prevented from being disjoint types. */ public static Type intersectionOfSupertypes( TypeDeclaration td) { Type extendedType = td.getExtendedType(); List<Type> satisfiedTypes = td.getSatisfiedTypes(); List<Type> list = new ArrayList<Type> (satisfiedTypes.size()+1); if (extendedType!=null) { list.add(extendedType); } list.addAll(satisfiedTypes); Unit unit = td.getUnit(); IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(list); return it.getType(); } /** * The union of the case types of the given declaration. */ public static Type unionOfCaseTypes( TypeDeclaration td) { List<Type> caseTypes = td.getCaseTypes(); Unit unit = td.getUnit(); if (caseTypes==null) { return unit.getAnythingType(); } List<Type> list = new ArrayList<Type> (caseTypes.size()+1); list.addAll(caseTypes); UnionType it = new UnionType(unit); it.setCaseTypes(list); return it.getType(); } public static int addHashForModule(int ret, Declaration decl) { Module module = getModule(decl); return (37 * ret) + (module != null ? module.hashCode() : 0); } public static boolean sameModule(Declaration a, Declaration b) { Module aMod = getModule(a); Module bMod = getModule(b); return aMod.equals(bMod); } public static void clearProducedTypeCache(TypeDeclaration decl) { Module module = getModule(decl); if(module != null){ module.clearCache(decl); } } public static List<Declaration> getInterveningRefinements( String name, List<Type> signature, Declaration root, TypeDeclaration bottom, TypeDeclaration top) { List<Declaration> result = new ArrayList<Declaration>(2); for (TypeDeclaration std: bottom.getSupertypeDeclarations()) { if (std.inherits(top) && !std.equals(bottom)) { Declaration member = std.getDirectMember(name, signature, false); if (member!=null && member.isShared() && !isAbstraction(member)) { TypeDeclaration td = (TypeDeclaration) member.getContainer(); Declaration refined = td.getRefinedMember(name, signature, false); if (refined!=null && refined.equals(root)) { result.add(member); } } } } return result; } public static List<Declaration> getInheritedDeclarations( String name, TypeDeclaration bottom) { List<Declaration> result = new ArrayList<Declaration>(2); for (TypeDeclaration std: bottom.getSupertypeDeclarations()) { if (!std.equals(bottom)) { Declaration member = std.getDirectMember(name, null, false); if (member!=null && member.isShared() && !isAbstraction(member)) { result.add(member); } } } return result; } /** * Is the given declaration a constructor or singleton * constructor of a toplevel class? * * Constructors of toplevel classes can be directly * imported into the toplevel namespace of a compilation * unit. */ public static boolean isToplevelClassConstructor( TypeDeclaration td, Declaration dec) { return td.isToplevel() && (dec instanceof Constructor || dec instanceof FunctionOrValue && ((FunctionOrValue) dec).getTypeDeclaration() instanceof Constructor); } /** * Is the given declaration a toplevel anonymous class? * * Members of toplevel anonymous classes can be directly * imported into the toplevel namespace of a compilation * unit. */ public static boolean isToplevelAnonymousClass(Scope s) { if (s instanceof Class) { Class td = (Class) s; return td.isAnonymous() && td.isToplevel(); } else { return false; } } public static boolean isNative(Declaration dec) { return dec != null && dec.isNative(); } public static boolean isNativeHeader(Declaration dec) { return dec != null && dec.isNativeHeader(); } public static boolean isNativeImplementation(Declaration dec) { return dec != null && dec.isNative() && !dec.isNativeHeader(); } public static boolean isInNativeContainer(Declaration dec) { Scope container = dec.getContainer(); if (container instanceof Declaration) { Declaration d = (Declaration) container; return d.isNative(); } return false; } public static Declaration getNativeDeclaration( Declaration decl, Backend backend) { return getNativeDeclaration(decl, backend == null ? null : backend.backendSupport); } public static Declaration getNativeDeclaration( Declaration dec, BackendSupport backendSupport) { if (dec.isNative() && backendSupport != null) { Declaration abstraction = null; if (backendSupport.supportsBackend( Backend.fromAnnotation( dec.getNativeBackend()))) { abstraction = dec; } else { List<Declaration> overloads = dec.getOverloads(); if (overloads != null) { for (Declaration d: overloads) { if (backendSupport.supportsBackend( Backend.fromAnnotation( d.getNativeBackend()))) { abstraction = d; break; } } } } return abstraction; } else { return dec; } } /** * The list of type parameters of the given generic * declaration as types. (As viewed within the body of * the generic declaration.) * * @param dec a generic declaration or type constructor * @return a list of types of its type parameters * * @see Declaration#getTypeParametersAsArguments */ public static List<Type> typeParametersAsArgList(Generic dec) { List<TypeParameter> params = dec.getTypeParameters(); if (params.isEmpty()) { return NO_TYPE_ARGS; } int size = params.size(); List<Type> paramsAsArgs = new ArrayList<Type>(size); for (int i=0; i<size; i++) { TypeParameter param = params.get(i); paramsAsArgs.add(param.getType()); } return paramsAsArgs; } /** * Find the declaration with the given name that occurs * directly in the given scope, taking into account the * given backend, if any. Does not take into account * Java overloading * * @param scope any scope * @param name the name of a declaration occurring * directly in the scope, and not overloaded * @param backend the native backend name * * @return the matching declaration */ public static Declaration getDirectMemberForBackend( Scope scope, String name, String backend) { for (Declaration dec: scope.getMembers()) { if (isResolvable(dec) && isNamed(name, dec)) { String nat = dec.getNativeBackend(); if (nat==null) { return dec; } else { if (nat.equals(backend)) { return dec; } } } } return null; } /** * Find the header with the given name that occurs * directly in the given scope or if that scope is * itself a native implementation first look up * the scope's native header and find the requested * header there. * * @param scope any scope * @param name the name of a declaration * * @return the matching declaration */ public static Declaration getNativeHeader(Scope container, String name) { if (container instanceof Declaration) { Declaration cd = (Declaration)container; if (cd.isNative() && !cd.isNativeHeader()) { // The container is a native implementation so // we first need to find _its_ header Scope c = (Scope)getDirectMemberForBackend(cd.getContainer(), cd.getName(), Backend.None.nativeAnnotation); if (c != null) { // Is this the Value part of an object? if (c instanceof Value && isObject((Value)c)) { // Then use the Class part as the container c = ((Value)c).getType().getDeclaration(); } container = c; } } } // Find the header Declaration header = getDirectMemberForBackend(container, name, Backend.None.nativeAnnotation); return header; } // Check if the Value is part of an object (is there a // better way to check this?) public static boolean isObject(Value v) { return v.getType().getDeclaration() .getQualifiedNameString() .equals(v.getQualifiedNameString()); } public static boolean isImplemented(Declaration decl) { if (decl instanceof FunctionOrValue) { FunctionOrValue fov = (FunctionOrValue) decl; return fov.isImplemented(); } return false; } public static boolean eq(Object decl, Object other) { if (decl == null) { return other == null; } else { return decl.equals(other); } } public static boolean equal(Declaration decl, Declaration other) { if (decl instanceof UnionType || decl instanceof IntersectionType || other instanceof UnionType || other instanceof IntersectionType) { return false; } return ModelUtil.eq(decl, other); } public static boolean equalModules(Module scope, Module other) { return eq(scope, other); } public static Module getModule(Declaration decl) { return decl.getUnit().getPackage().getModule(); } public static Package getPackage(Declaration decl) { return decl.getUnit().getPackage(); } public static Package getPackageContainer(Scope scope) { // stop when null or when it's a Package while(scope != null && !(scope instanceof Package)){ // stop if the container is not a Scope if(!(scope.getContainer() instanceof Scope)) return null; scope = (Scope) scope.getContainer(); } return (Package) scope; } public static Module getModuleContainer(Scope scope) { Package pkg = getPackageContainer(scope); return pkg != null ? pkg.getModule() : null; } public static ClassOrInterface getClassOrInterfaceContainer( Element decl) { return getClassOrInterfaceContainer(decl, true); } public static ClassOrInterface getClassOrInterfaceContainer( Element decl, boolean includingDecl) { if (!includingDecl) { decl = (Element) decl.getContainer(); } // stop when null or when it's a ClassOrInterface while(decl != null && !(decl instanceof ClassOrInterface)){ // stop if the container is not an Element if(!(decl.getContainer() instanceof Element)) return null; decl = (Element) decl.getContainer(); } return (ClassOrInterface) decl; } public static void setVisibleScope(Declaration model) { Scope s=model.getContainer(); while (s!=null) { if (s instanceof Declaration) { if (model.isShared()) { if (!((Declaration) s).isShared()) { model.setVisibleScope(s.getContainer()); break; } } else { model.setVisibleScope(s); break; } } else if (s instanceof Package) { //TODO: unshared packages! /*if (!((Package) s).isShared()) { model.setVisibleScope(s); }*/ if (!model.isShared()) { model.setVisibleScope(s); } //null visible scope means visible everywhere break; } else { model.setVisibleScope(s); break; } s = s.getContainer(); } } /** * Determines whether the declaration's containing scope is a class or interface * @param decl The declaration * @return true if the declaration is within a class or interface */ public static boolean withinClassOrInterface(Declaration decl) { return decl.getContainer() instanceof ClassOrInterface; } public static boolean withinClass(Declaration decl) { return decl.getContainer() instanceof Class; } public static boolean isLocalToInitializer(Declaration decl) { return withinClass(decl) && !isCaptured(decl); } public static boolean isCaptured(Declaration decl) { // Shared elements are implicitely captured although the typechecker doesn't mark them that way return decl.isCaptured() || decl.isShared(); } public static boolean isNonTransientValue(Declaration decl) { return (decl instanceof Value) && !((Value)decl).isTransient(); } /** * Is the given scope a local scope but not an initializer scope? */ public static boolean isLocalNotInitializerScope(Scope scope) { return scope instanceof FunctionOrValue || scope instanceof Constructor || scope instanceof ControlBlock || scope instanceof NamedArgumentList || scope instanceof Specification; } /** * Determines whether the declaration is local to a method, * getter or setter, but <strong>returns {@code false} for a declaration * local to a Class initializer.</strong> * @param decl The declaration * @return true if the declaration is local */ public static boolean isLocalNotInitializer(Declaration decl) { return isLocalNotInitializerScope(decl.getContainer()); } public static boolean argumentSatisfiesEnumeratedConstraint( Type receiver, Declaration member, List<Type> typeArguments, Type argType, TypeParameter param) { List<Type> caseTypes = param.getCaseTypes(); if (caseTypes==null || caseTypes.isEmpty()) { //no enumerated constraint return true; } //if the type argument is a subtype of one of the cases //of the type parameter then the constraint is satisfied for (Type ct: caseTypes) { Type cts = ct.appliedType(receiver, member, typeArguments, null); if (argType.isSubtypeOf(cts)) { return true; } } //if the type argument is itself a type parameter with //an enumerated constraint, and every enumerated case //is a subtype of one of the cases of the type parameter, //then the constraint is satisfied TypeDeclaration atd = argType.getDeclaration(); if (argType.isTypeParameter()) { List<Type> argCaseTypes = atd.getCaseTypes(); if (argCaseTypes!=null && !argCaseTypes.isEmpty()) { for (Type act: argCaseTypes) { boolean foundCase = false; for (Type ct: caseTypes) { Type cts = ct.appliedType(receiver, member, typeArguments, null); if (act.isSubtypeOf(cts)) { foundCase = true; break; } } if (!foundCase) { return false; } } return true; } } return false; } public static boolean isBooleanTrue(Declaration d) { return d!=null && d.getQualifiedNameString() .equals("ceylon.language::true"); } public static boolean isBooleanFalse(Declaration d) { return d!=null && d.getQualifiedNameString() .equals("ceylon.language::false"); } public static Type genericFunctionType( Generic generic, Scope scope, Declaration member, Reference reference, Unit unit) { List<TypeParameter> typeParameters = generic.getTypeParameters(); TypeAlias ta = new TypeAlias(); ta.setContainer(scope); ta.setName("Anonymous#" + member.getName()); ta.setAnonymous(true); ta.setScope(scope); ta.setUnit(unit); ta.setExtendedType(reference.getFullType()); ta.setTypeParameters(typeParameters); Type type = ta.getType(); type.setTypeConstructor(true); return type; } public static boolean isConstructor(Declaration member) { return member instanceof Constructor || member instanceof FunctionOrValue && ((FunctionOrValue) member) .getTypeDeclaration() instanceof Constructor; } }
src/com/redhat/ceylon/model/typechecker/model/ModelUtil.java
package com.redhat.ceylon.model.typechecker.model; import static com.redhat.ceylon.model.typechecker.model.SiteVariance.IN; import static com.redhat.ceylon.model.typechecker.model.SiteVariance.OUT; import static java.lang.Character.charCount; import static java.lang.Character.isLowerCase; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.common.BackendSupport; /** * Model utilities. * * @author Stéphane Épardaud <stef@epardaud.fr> * @author Gavin King */ public class ModelUtil { static final List<Type> NO_TYPE_ARGS = Collections.<Type>emptyList(); static final Map<TypeParameter, Type> EMPTY_TYPE_ARG_MAP = Collections.<TypeParameter,Type>emptyMap(); static final Map<TypeParameter, SiteVariance> EMPTY_VARIANCE_MAP = emptyMap(); /** * Is the second scope contained by the first scope? */ public static boolean contains(Scope outer, Scope inner) { if (outer != null) { while (inner!=null) { if (inner.equals(outer)) { return true; } inner = inner.getScope(); } } return false; } /** * Get the nearest containing scope that is not a * ConditionScope. */ public static Scope getRealScope(Scope scope) { while (!(scope instanceof Package)) { if (!(scope instanceof ConditionScope)) { return scope; } scope = scope.getContainer(); } return null; } /** * Get the class or interface that "this" and "super" * refer to. */ public static ClassOrInterface getContainingClassOrInterface(Scope scope) { while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { return (ClassOrInterface) scope; } scope = scope.getContainer(); } return null; } /** * Get the declaration that contains the specified declaration, if any. */ public static Declaration getContainingDeclaration(Declaration d) { if (d.isToplevel()) return null; Scope scope = d.getContainer(); while (!(scope instanceof Package)) { if (scope instanceof Declaration) { return (Declaration) scope; } scope = scope.getContainer(); } return null; } /** * Get the declaration that contains the specified scope, if any. */ public static Declaration getContainingDeclarationOfScope(Scope scope) { while (!(scope instanceof Package)) { if (scope instanceof Declaration) { return (Declaration) scope; } scope = scope.getContainer(); } return null; } /** * Get the class or interface that "outer" refers to. */ public static Type getOuterClassOrInterface(Scope scope) { Boolean foundInner = false; while (!(scope instanceof Package)) { if (scope instanceof ClassOrInterface) { if (foundInner) { ClassOrInterface ci = (ClassOrInterface) scope; return ci.getType(); } else { foundInner = true; } } scope = scope.getContainer(); } return null; } /** * Convenience method to bind a single type argument * to a toplevel type declaration. */ public static Type appliedType( TypeDeclaration declaration, Type typeArgument) { if (declaration==null) return null; return declaration.appliedType(null, singletonList(typeArgument)); } /** * Convenience method to bind a list of type arguments * to a toplevel type declaration. */ public static Type appliedType( TypeDeclaration declaration, Type... typeArguments) { if (declaration==null) return null; return declaration.appliedType(null, asList(typeArguments)); } public static boolean isResolvable(Declaration declaration) { return declaration.getName()!=null && !declaration.isSetter() && //return getters, not setters !declaration.isAnonymous(); //don't return the type associated with an object dec } public static boolean isAbstraction(Declaration d) { return d!=null && d.isAbstraction(); } public static boolean notOverloaded(Declaration d) { if (d==null || !d.isFunctional()) { return true; } else { return !d.isOverloaded() || d.isAbstraction(); } } public static boolean isOverloadedVersion(Declaration decl) { return decl!=null && (decl.isOverloaded() && !decl.isAbstraction()) && !decl.isNative(); } static boolean hasMatchingSignature( Declaration dec, List<Type> signature, boolean ellipsis) { return hasMatchingSignature(dec, signature, ellipsis, true); } static boolean hasMatchingSignature( Declaration dec, List<Type> signature, boolean spread, boolean excludeAbstractClasses) { if (excludeAbstractClasses && dec instanceof Class && ((Class) dec).isAbstract()) { return false; } if (dec instanceof Functional) { if (dec.isAbstraction()) { return false; } Functional f = (Functional) dec; Unit unit = dec.getUnit(); List<ParameterList> pls = f.getParameterLists(); if (pls!=null && !pls.isEmpty()) { ParameterList pl = pls.get(0); List<Parameter> params = pl.getParameters(); int size = params.size(); boolean hasSeqParam = pl.hasSequencedParameter(); int sigSize = signature.size(); if (hasSeqParam) { size--; if (sigSize<size) { return false; } } else if (sigSize!=size) { return false; } for (int i=0; i<size; i++) { FunctionOrValue pm = params.get(i) .getModel(); if (pm==null) { return false; } Type pdt = pm.appliedReference(null, NO_TYPE_ARGS) .getFullType(); if (pdt==null) { return false; } Type sdt = signature.get(i); if (!matches(sdt, pdt, unit)) { return false; } } if (hasSeqParam) { FunctionOrValue model = params.get(size).getModel(); Type pdt = model.appliedReference(null, NO_TYPE_ARGS) .getFullType(); if (pdt==null || pdt.getTypeArgumentList() .isEmpty()) { return false; } //Note: don't use Unit.getIterableType() // because this gets called from // model loader out-of-phase Type ipdt = pdt.getTypeArgumentList() .get(0); for (int i=size; i<sigSize; i++) { if (spread && i==sigSize-1) { Type sdt = signature.get(i); Type isdt = unit.getIteratedType(sdt); if (!matches(isdt, ipdt, unit)) { return false; } } else { Type sdt = signature.get(i); if (!matches(sdt, ipdt, unit)) { return false; } } } } else if (spread) { // if the method doesn't take sequenced // params and we have an ellipsis let's // not use it since we expect a variadic // method // TODO: this is basically wrong now that // we can spread tuples return false; } return true; } else { return false; } } else { return false; } } public static boolean matches( Type argType, Type paramType, Unit unit) { if (paramType==null || argType==null) { return false; } //Ignore optionality for resolving overloads, since //all Java parameters are treated as optional, //except primitive-typed parameters Type nvt = unit.getNullType(); if (nvt.isSubtypeOf(argType) && !nvt.isSubtypeOf(paramType)) { return false; //only for primitives } Type defParamType = unit.getDefiniteType(paramType); Type defArgType = unit.getDefiniteType(argType); Type nt = unit.getNullType(); if (defArgType.isSubtypeOf(nt)) { return true; } if (isTypeUnknown(defArgType) || isTypeUnknown(defParamType)) { return false; } if (!erase(defArgType, unit) .inherits(erase(defParamType, unit)) && notUnderlyingTypesEqual(defParamType, defArgType)) { return false; } return true; } private static boolean notUnderlyingTypesEqual( Type paramType, Type sigType) { String sut = sigType.getUnderlyingType(); String put = paramType.getUnderlyingType(); return sut==null || put==null || !sut.equals(put); } static boolean betterMatch(Declaration d, Declaration r, List<Type> signature) { if (d instanceof Functional && r instanceof Functional) { Functional df = (Functional) d; Functional rf = (Functional) r; List<ParameterList> dpls = df.getParameterLists(); List<ParameterList> rpls = rf.getParameterLists(); if (dpls!=null && !dpls.isEmpty() && rpls!=null && !rpls.isEmpty()) { ParameterList dpls0 = dpls.get(0); ParameterList rpls0 = rpls.get(0); List<Parameter> dpl = dpls0.getParameters(); List<Parameter> rpl = rpls0.getParameters(); int dplSize = dpl.size(); int rplSize = rpl.size(); //ignore sequenced parameters boolean dhsp = dpls0.hasSequencedParameter(); boolean rhsp = rpls0.hasSequencedParameter(); //always prefer a signature without varargs //over one with a varargs parameter if (!dhsp && rhsp) { return true; } if (dhsp && !rhsp) { return false; } //ignore sequenced parameters if (dhsp) dplSize--; if (rhsp) rplSize--; if (dplSize==rplSize) { //if all parameters are of more specific //or equal type, prefer it Unit unit = d.getUnit(); for (int i=0; i<dplSize; i++) { Type dplt = dpl.get(i).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type paramType = unit.getDefiniteType(dplt); Type rplt = rpl.get(i).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type otherType = unit.getDefiniteType(rplt); Type argumentType = signature != null && signature.size() >= i ? signature.get(i) : null; if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } TypeDeclaration ptd = erase(paramType, unit); TypeDeclaration otd = erase(otherType, unit); if(paramType.isExactly(otherType) && supportsCoercion(ptd) && // do we have different scores? hasWorseScore( getCoercionScore( argumentType, paramType), getCoercionScore( argumentType, otherType))) { return false; } if (!ptd.inherits(otd) && notUnderlyingTypesEqual( paramType, otherType)) { return false; } } // check sequenced parameters last if (dhsp && rhsp){ Type dplt = dpl.get(dplSize).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type paramType = unit.getDefiniteType(dplt); Type rplt = rpl.get(dplSize).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type otherType = unit.getDefiniteType(rplt); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } paramType = unit.getIteratedType(paramType); otherType = unit.getIteratedType(otherType); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } TypeDeclaration ptd = erase(paramType, unit); TypeDeclaration otd = erase(otherType, unit); if (paramType.isExactly(otherType) && supportsCoercion(ptd)) { Type widerArgumentType = getWiderArgumentType( paramType, signature, dplSize); // do we have different scores? int pscore = getCoercionScore( widerArgumentType, paramType); int oscore = getCoercionScore( widerArgumentType, otherType); if (hasWorseScore(pscore, oscore)) { return false; } } if (!ptd.inherits(otd) && notUnderlyingTypesEqual( paramType, otherType)) { return false; } } return true; } } } return false; } private static boolean supportsCoercion( TypeDeclaration decl) { return decl.isInteger() || decl.isFloat(); } private static boolean hasWorseScore( int underlyingTypeCoercionScoreA, int underlyingTypeCoercionScoreB) { if (underlyingTypeCoercionScoreA != underlyingTypeCoercionScoreB) { if (underlyingTypeCoercionScoreA > 0 && underlyingTypeCoercionScoreB > 0) { // both truncations, prefer the smaller // truncation if (underlyingTypeCoercionScoreA > underlyingTypeCoercionScoreB) { return true; } } else if(underlyingTypeCoercionScoreA > 0) { // A is a truncation, B is a widening, // prefer widening return true; } else if(underlyingTypeCoercionScoreA == 0) { // A is a perfect match, it's not worse return false; } else if(underlyingTypeCoercionScoreB == 0) { // B is a perfect match but A is not, // so it's worse return true; } else if(underlyingTypeCoercionScoreB > 0) { // A is a widening, B is a truncation, // so it's not worse return false; } else { // A is a widening and B is a widening too, // A is worse than B if it widens more than B return underlyingTypeCoercionScoreA < underlyingTypeCoercionScoreB; } } return false;// same score or we don't know } private static Type getWiderArgumentType( Type paramType, List<Type> signature, int startAt) { if (startAt >= signature.size()) { return null; } TypeDeclaration decl = paramType.getDeclaration(); Unit unit = decl.getUnit(); if (decl.isInteger()) { int bestScore = 0; Type ret = null; for(int i=startAt; i<signature.size(); i++){ Type argType = signature.get(i); String underlyingType = argType.getUnderlyingType(); int score = 0; if (underlyingType == null || underlyingType.equals("long")) { return argType; // found the wider sort } else if (underlyingType.equals("int")) { score = 2; } else if (underlyingType.equals("short")) { score = 1; } // keep the widest argument type if (score > bestScore) { bestScore = score; ret = argType; } } return ret; } else if (decl.equals(unit.getFloatDeclaration())) { int bestScore = 0; Type ret = null; for (int i=startAt; i<signature.size(); i++) { Type argType = signature.get(i); String underlyingType = argType.getUnderlyingType(); int score = 0; if (underlyingType == null || underlyingType.equals("double")) { return argType; // found the wider sort } else if (underlyingType.equals("float")) { score = 1; } // keep the widest argument type if (score > bestScore){ bestScore = score; ret = argType; } } return ret; } // not relevant return null; } /** * Returns 0 of there's no coercion, > 0 if we have to * truncate the argument type to fit the param type, * the higher for the worse truncation, or < 0 if we * have to widen the argument type to fit the param type, * the lower for the worse widening. */ private static int getCoercionScore( Type argumentType, Type paramType) { if (argumentType == null) { return 0; } // only consider types of Integer of Float if (paramType.isExactly(argumentType)) { String aType = argumentType.getUnderlyingType(); String pType = paramType.getUnderlyingType(); if (aType == null && pType == null) { return 0; } Unit unit = argumentType.getDeclaration().getUnit(); TypeDeclaration decl = paramType.getDeclaration(); if (decl.isInteger()) { if (aType == null) { aType = "long"; } if (pType == null) { pType = "long"; } int aScore = getPrimitiveScore(aType); int bScore = getPrimitiveScore(pType); /* * aType aTypeScore pType pTypeScore score * short 0 short 0 0 * short 0 int 1 -1 (widening) * short 0 long 2 -2 (widening) * int 1 short 0 1 (truncation) * int 1 int 1 0 * int 1 long 2 -1 (widening) * long 2 short 0 2 (truncation) * long 2 int 1 1 (truncation) * long 2 long 2 0 */ return aScore - bScore; } else if (decl.equals(unit.getFloatDeclaration())) { if (aType == null) { aType = "double"; } if (pType == null) { pType = "double"; } int aScore = getPrimitiveScore(aType); int bScore = getPrimitiveScore(pType); /* * aType aTypeScore pType pTypeScore score * float 0 float 0 0 * float 0 double 1 -1 (widening) * double 1 float 0 1 (truncation) * double 1 double 1 0 */ return aScore - bScore; } } // no truncation for the rest return 0; } private static int getPrimitiveScore(String underlyingType) { if (underlyingType.equals("long")) { return 2; } if (underlyingType.equals("int") || underlyingType.equals("double")) { return 1; } if (underlyingType.equals("short") || underlyingType.equals("float")) { return 0; } return 0; } static boolean strictlyBetterMatch(Declaration d, Declaration r) { if (d instanceof Functional && r instanceof Functional) { List<ParameterList> dpls = ((Functional) d).getParameterLists(); List<ParameterList> rpls = ((Functional) r).getParameterLists(); if (dpls!=null && !dpls.isEmpty() && rpls!=null && !rpls.isEmpty()) { ParameterList dpls0 = dpls.get(0); ParameterList rpls0 = rpls.get(0); List<Parameter> dpl = dpls0.getParameters(); List<Parameter> rpl = rpls0.getParameters(); int dplSize = dpl.size(); int rplSize = rpl.size(); //ignore sequenced parameters boolean dhsp = dpls0.hasSequencedParameter(); boolean rhsp = rpls0.hasSequencedParameter(); //always prefer a signature without varargs //over one with a varargs parameter if (!dhsp && rhsp) { return true; } if (dhsp && !rhsp) { return false; } //ignore sequenced parameters if (dhsp) dplSize--; if (rhsp) rplSize--; if (dplSize==rplSize) { //if all parameters are of more specific //or equal type, prefer it boolean atLeastOneBetter = false; Unit unit = d.getUnit(); for (int i=0; i<dplSize; i++) { Type dplt = dpl.get(i).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type paramType = unit.getDefiniteType(dplt); Type rplt = rpl.get(i).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type otherType = unit.getDefiniteType(rplt); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } TypeDeclaration ptd = erase(paramType, unit); TypeDeclaration otd = erase(otherType, unit); if (!ptd.inherits(otd) && notUnderlyingTypesEqual( paramType, otherType)) { return false; } if (ptd.inherits(otd) && !otd.inherits(ptd) && notUnderlyingTypesEqual( paramType, otherType)) { atLeastOneBetter = true; } } // check sequenced parameters last if (dhsp && rhsp) { Type dplt = dpl.get(dplSize).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type paramType = unit.getDefiniteType(dplt); Type rplt = rpl.get(dplSize).getModel() .appliedReference(null, NO_TYPE_ARGS) .getFullType(); Type otherType = unit.getDefiniteType(rplt); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } paramType = unit.getIteratedType(paramType); otherType = unit.getIteratedType(otherType); if (isTypeUnknown(otherType) || isTypeUnknown(paramType)) { return false; } TypeDeclaration ptd = erase(paramType, unit); TypeDeclaration otd = erase(otherType, unit); if (!ptd.inherits(otd) && notUnderlyingTypesEqual( paramType, otherType)) { return false; } if (ptd.inherits(otd) && !otd.inherits(ptd) && notUnderlyingTypesEqual( paramType, otherType)) { atLeastOneBetter = true; } } return atLeastOneBetter; } } } return false; } public static boolean isNamed(String name, Declaration d) { String dname = d.getName(); return dname!=null && dname.equals(name); } static TypeDeclaration erase(Type paramType, Unit unit) { if (paramType.isTypeParameter()) { if (paramType.getSatisfiedTypes().isEmpty()) { Type et = paramType.getExtendedType(); return et==null ? null : et.getDeclaration(); } else { //TODO: Is this actually correct? // What is Java's rule here? Type st = paramType.getSatisfiedTypes() .get(0); return st==null ? null : st.getDeclaration(); } } else if (paramType.isUnion()) { //TODO: this is very sucky, cos in theory a // union might be assignable to the // parameter type with a typecast return unit.getObjectDeclaration(); } else if (paramType.isIntersection()) { List<Type> sts = paramType.getSatisfiedTypes(); if (sts.size()==2) { //attempt to eliminate Basic from the //intersection - very useful for anonymous //classes, whose denotableType is often an //intersection with Basic Type first = sts.get(0); Type second = sts.get(1); if (first!=null && first.isBasic()) { return erase(second, unit); } else if (second!=null && second.isBasic()) { return erase(first, unit); } } //TODO: this is very sucky, cos in theory an // intersection might be assignable to the // parameter type with a typecast return unit.getObjectDeclaration(); } else { return paramType.getDeclaration(); } } /** * Match the name of the given declaration to the given * pattern. A name matches if: * * - it starts with the pattern, ignoring case, or * - the pattern consists of all uppercase after the * first character, and its uppercase "humps" match * the pattern. */ public static boolean isNameMatching( String startingWith, Declaration d) { return isNameMatching(startingWith, d.getName()); } public static boolean isNameMatching( String startingWith, Import i) { return isNameMatching(startingWith, i.getAlias()); } public static boolean isNameMatching( String startingWith, String name) { if (startingWith==null || startingWith.isEmpty()) { return true; } if (name==null || name.isEmpty()) { return false; } int nameLength = name.length(); int startingWithLength = startingWith.length(); if (nameLength<startingWithLength) { return false; } if (name.regionMatches(true,0,startingWith,0,startingWithLength)) { return true; } int c = startingWith.codePointAt(0); int d = name.codePointAt(0); if (c!=d) { return false; } //camel hump matching, starting from second character: int i=1, j=1; while (i<startingWithLength) { if (j>=nameLength) { return false; } while (i<startingWithLength && isLowerCase(c=startingWith.codePointAt(i))) { d = name.codePointAt(j); if (c==d) { i+=charCount(c); j+=charCount(d); if (i>=startingWithLength) { return true; } if (j>=nameLength) { return false; } } else { return false; } } while (j<nameLength && isLowerCase(d=name.codePointAt(j))) { j+=charCount(d); if (j>=nameLength) { return false; } } c = startingWith.codePointAt(i); d = name.codePointAt(j); i+=charCount(c); j+=charCount(d); if (d!=c) { return false; } } return true; } /** * Given a declaration, a list of type arguments to the * declaration, and a receiving type, collect together * all interesting type arguments. The resulting map * includes all type arguments from the receiving type * and all its qualifying types. That's useful, because * {@link Type.Substitution} works with a single * aggregated map, and so for performance * {@link Type#substitute(Type)} and * {@link Type#substitute(TypedReference)} * assume that the given type or reference holds such a * single aggregated map. * * @return a map of type parameter to type argument * * @param declaration a declaration * @param receivingType the receiving produced type * of which the declaration is a member * @param typeArguments all the explicit or inferred * type arguments of the declaration, including * those from qualifying types */ public static Map<TypeParameter,Type> getTypeArgumentMap(Declaration declaration, Type receivingType, List<Type> typeArguments) { List<TypeParameter> typeParameters = getTypeParameters(declaration); int count = countTypeParameters(receivingType, typeParameters); if (count==0) { return EMPTY_TYPE_ARG_MAP; } else { return aggregateTypeArguments(receivingType, typeArguments, typeParameters, count); } } private static Map<TypeParameter, Type> aggregateTypeArguments(Type receivingType, List<Type> typeArguments, List<TypeParameter> typeParameters, int count) { Map<TypeParameter,Type> map = new HashMap<TypeParameter,Type> (count); //make sure we collect all type arguments //from the whole qualified type! if (receivingType!=null) { if (receivingType.isIntersection()) { for (Type dt: receivingType.getSatisfiedTypes()) { while (dt!=null) { map.putAll(dt.getTypeArguments()); dt = dt.getQualifyingType(); } } } else { Type dt = receivingType; while (dt!=null) { map.putAll(dt.getTypeArguments()); dt = dt.getQualifyingType(); } } } if (typeArguments!=null) { //now turn the type argument tuple into a //map from type parameter to argument for (int i=0; i<typeParameters.size() && i<typeArguments.size(); i++) { map.put(typeParameters.get(i), typeArguments.get(i)); } } return map; } public static Map<TypeParameter,SiteVariance> getVarianceMap(Declaration declaration, Type receivingType, List<SiteVariance> variances) { if (variances==null) { return EMPTY_VARIANCE_MAP; } else { List<TypeParameter> typeParameters = getTypeParameters(declaration); int count = countTypeParameters(receivingType, typeParameters); if (count==0) { return EMPTY_VARIANCE_MAP; } else { return aggregateVariances(receivingType, variances, typeParameters); } } } private static Map<TypeParameter, SiteVariance> aggregateVariances(Type receivingType, List<SiteVariance> variances, List<TypeParameter> typeParameters) { Map<TypeParameter,SiteVariance> map = new HashMap<TypeParameter,SiteVariance>(); //make sure we collect all type arguments //from the whole qualified type! if (receivingType!=null) { if (receivingType.isIntersection()) { for (Type dt: receivingType.getSatisfiedTypes()) { while (dt!=null) { map.putAll(dt.getVarianceOverrides()); dt = dt.getQualifyingType(); } } } else { Type dt = receivingType; while (dt!=null) { map.putAll(dt.getVarianceOverrides()); dt = dt.getQualifyingType(); } } } for (int i=0; i<typeParameters.size() && i<variances.size(); i++) { SiteVariance var = variances.get(i); if (var!=null) { map.put(typeParameters.get(i), var); } } return map; } private static int countTypeParameters( Type receivingType, List<TypeParameter> typeParameters) { int count = typeParameters.size(); //make sure we count all type arguments //from the whole qualified type! if (receivingType!=null) { if (receivingType.isIntersection()) { for (Type dt: receivingType.getSatisfiedTypes()) { while (dt!=null) { count += dt.getTypeArguments().size(); dt = dt.getQualifyingType(); } } } else { Type dt = receivingType; while (dt!=null) { count += dt.getTypeArguments().size(); dt = dt.getQualifyingType(); } } } return count; } public static List<TypeParameter> getTypeParameters( Declaration declaration) { if (declaration instanceof Generic) { Generic g = (Generic) declaration; return g.getTypeParameters(); } else { return emptyList(); } } static <T> List<T> list(List<T> list, T element) { List<T> result = new ArrayList<T>(list.size()+1); result.addAll(list); result.add(element); return result; } /** * Helper method for eliminating duplicate types from * lists of types that form a union type, taking into * account that a subtype is a "duplicate" of its * supertype. */ public static void addToUnion(List<Type> list, Type pt) { if (pt==null || !list.isEmpty() && pt.isNothing()) { return; } else if (pt.isAnything()) { list.clear(); list.add(pt); } else if (pt.isUnion()) { // cheaper c-for than foreach List<Type> caseTypes = pt.getCaseTypes(); for ( int i=0, size=caseTypes.size(); i<size; i++ ) { Type t = caseTypes.get(i); addToUnion(list, t.substitute(pt)); } } else if (pt.isWellDefined()) { boolean add=true; // cheaper c-for than foreach for (int i=0; i<list.size(); i++) { Type t = list.get(i); if (pt.isSubtypeOf(t)) { add=false; break; } else if (pt.isSupertypeOf(t)) { list.remove(i); i--; // redo this index } } if (add) { list.add(pt); } } } /** * Helper method for eliminating duplicate types from * lists of types that form an intersection type, taking * into account that a supertype is a "duplicate" of its * subtype. */ public static void addToIntersection(List<Type> list, Type type, Unit unit) { if (type==null || !list.isEmpty() && type.isAnything()) { return; } else if (type.isNothing()) { list.clear(); list.add(type); } else if (type.isIntersection()) { List<Type> satisfiedTypes = type.getSatisfiedTypes(); for (int i=0, size=satisfiedTypes.size(); i<size; i++) { Type t = satisfiedTypes.get(i); addToIntersection(list, t, unit); } } else { if (type.isWellDefined()) { TypeDeclaration dec = type.getDeclaration(); for (int i=0; i<list.size(); i++) { Type t = list.get(i); if (t.isSubtypeOf(type)) { return; } else if (type.isSubtypeOf(t)) { list.remove(i); i--; // redo this index } else if (disjoint(type, t, unit)) { list.clear(); list.add(unit.getNothingType()); return; } else { if (type.isClassOrInterface() && t.isClassOrInterface() && t.getDeclaration().equals(dec) && !type.containsUnknowns() && !t.containsUnknowns()) { //canonicalize a type of form //T<InX,OutX>&T<InY,OutY> to //T<InX|InY,OutX&OutY> Type pi = principalInstantiation( dec, type, t, unit); if (!pi.containsUnknowns()) { list.remove(i); list.add(pi); return; } } } } if (list.size()>1) { //it is possible to have a type that is //a supertype of the intersection, even //though it is not a supertype of any of //the intersected types! Type t = canonicalIntersection(list, unit); if (type.isSupertypeOf(t)) { return; } } list.add(type); } } } /** * Are the given types disjoint? * * @param p the first type * @param q the second type * enumerated type are disjoint * @param unit * * @return true if the types are disjoint */ private static boolean disjoint(Type p, Type q, Unit unit) { if (q.getDeclaration() .isDisjoint(p.getDeclaration())) { return true; } else { //we have to resolve aliases here, or computing //supertype declarations gets incredibly slow //for the big stack of union type aliases in //ceylon.ast Type ps = p.resolveAliases(); Type qs = q.resolveAliases(); return emptyMeet(ps, qs, unit) || hasEmptyIntersectionOfInvariantInstantiations(ps, qs); } } /** * implement the rule that Foo&Bar==Nothing if * here exists some enumerated type Baz with * * Baz of Foo | Bar * * (the intersection of disjoint types is empty) * * @param type a type which might be disjoint from * a list of other given types * @param list the list of other types * @param unit * * @return true of the given type was disjoint from * the given list of types */ /*private static boolean reduceIfDisjoint(Type type, List<Type> list, Unit unit) { if (list.isEmpty()) { return false; } TypeDeclaration typeDec = type.getDeclaration(); List<TypeDeclaration> supertypes = typeDec.getSupertypeDeclarations(); for (int i=0, l=supertypes.size(); i<l; i++) { TypeDeclaration supertype = supertypes.get(i); List<Type> cts = supertype.getCaseTypes(); if (cts!=null) { TypeDeclaration ctd=null; for (int cti=0, ctl=cts.size(); cti<ctl; cti++) { TypeDeclaration ct = cts.get(cti) .getDeclaration(); if (typeDec.inherits(ct)) { ctd = ct; break; } } if (ctd!=null) { for (int cti=0, ctl=cts.size(); cti<ctl; cti++) { TypeDeclaration ct = cts.get(cti) .getDeclaration(); if (ct!=ctd) { for (int ti=0, tl=list.size(); ti<tl; ti++) { Type t = list.get(ti); if (t.getDeclaration() .inherits(ct)) { return true; } } } } } } } return false; }*/ /** * The meet of two classes unrelated by inheritance, * or of Null with an interface type is empty. The meet * of an anonymous class with a type to which it is not * assignable is empty. */ private static boolean emptyMeet( Type p, Type q, Unit unit) { if (p==null || q==null) { return false; } if (p.isNothing() || q.isNothing()) { return true; } TypeDeclaration pd = p.getDeclaration(); TypeDeclaration qd = q.getDeclaration(); if (p.isTypeParameter()) { p = canonicalIntersection( p.getSatisfiedTypes(), unit); pd = p.getDeclaration(); } if (q.isTypeParameter()) { q = canonicalIntersection( q.getSatisfiedTypes(), unit); qd = q.getDeclaration(); } if (q.isIntersection()) { for (Type t: q.getSatisfiedTypes()) { if (emptyMeet(p,t,unit)) { return true; } } return false; } if (p.isIntersection()) { for (Type t: p.getSatisfiedTypes()) { if (emptyMeet(q,t,unit)) { return true; } } return false; } if (q.isUnion()) { for (Type t: q.getCaseTypes()) { if (!emptyMeet(p,t,unit)) { return false; } } return true; } else if (qd.getCaseTypes()!=null) { boolean all = true; for (Type t: qd.getCaseTypes()) { if (t.getDeclaration().isSelfType() || !emptyMeet(p,t,unit)) { all = false; break; } } if (all) return true; } if (p.isUnion()) { for (Type t: p.getCaseTypes()) { if (!emptyMeet(q,t,unit)) { return false; } } return true; } else if (p.getCaseTypes()!=null) { boolean all = true; for (Type t: pd.getCaseTypes()) { if (t.getDeclaration().isSelfType() || !emptyMeet(q,t,unit)) { all = false; break; } } if (all) return true; } if (p.isClass() && q.isClass() || p.isInterface() && q.isNull() || q.isInterface() && p.isNull()) { if (!qd.inherits(pd) && !pd.inherits(qd)) { return true; } } if (pd.isFinal()) { if (pd.getTypeParameters().isEmpty() && !q.involvesTypeParameters() && !p.isSubtypeOf(q) && !(qd instanceof UnknownType)) { return true; } if (q.isClassOrInterface() && !pd.inherits(qd)) { return true; } } if (qd.isFinal()) { if (qd.getTypeParameters().isEmpty() && !p.involvesTypeParameters() && !q.isSubtypeOf(p) && !(p.isUnknown())) { return true; } if (p.isClassOrInterface() && !qd.inherits(pd)) { return true; } } // Interface ed = unit.getEmptyDeclaration(); // Interface id = unit.getIterableDeclaration(); // if (pd.inherits(ed) && qd.inherits(id) && // unit.isNonemptyIterableType(q) || // pd.inherits(id) && qd.inherits(ed) && // unit.isNonemptyIterableType(p)) { // return true; // } Interface st = unit.getSequentialDeclaration(); if (q.isClassOrInterface() && pd.inherits(st) && !qd.inherits(st) && !st.inherits(qd) || p.isClassOrInterface() && qd.inherits(st) && !pd.inherits(st) && !st.inherits(pd) && !p.involvesTypeParameters()) { return true; } Interface nst = unit.getSequenceDeclaration(); if (pd.inherits(nst) && qd.inherits(st) || qd.inherits(nst) && pd.inherits(st)) { Type pet = unit.getSequentialElementType(p); Type qet = unit.getSequentialElementType(q); if (emptyMeet(pet, qet, unit)) { return true; } } Class td = unit.getTupleDeclaration(); if (pd.inherits(td) && qd.inherits(td)) { List<Type> pal = p.getTypeArgumentList(); List<Type> qal = q.getTypeArgumentList(); if (pal.size()>=3 && qal.size()>=3) { if (emptyMeet(pal.get(1), qal.get(1), unit) || emptyMeet(pal.get(2), qal.get(2), unit)) { return true; } } } if (pd.inherits(td) && qd.inherits(st)) { List<Type> pal = p.getTypeArgumentList(); Type qet = unit.getSequentialElementType(q); if (pal.size()>=3) { if (emptyMeet(pal.get(1), qet, unit) || emptyMeet(pal.get(2), unit.getSequentialType(qet), unit)) { return true; } } } if (qd.inherits(td) && pd.inherits(st)) { List<Type> qal = q.getTypeArgumentList(); Type pet = unit.getSequentialElementType(p); if (qal.size()>=3) { if (emptyMeet(qal.get(1), pet, unit) || emptyMeet(qal.get(2), unit.getSequentialType(pet), unit)) { return true; } } } return false; } /** * Given two instantiations of a qualified type constructor, * determine the qualifying type of the principal * instantiation of that type constructor for the * intersection of the two types. */ static Type principalQualifyingType( Type pt, Type t, TypeDeclaration td, Unit unit) { Type ptqt = pt.getQualifyingType(); Type tqt = t.getQualifyingType(); Scope tdc = td.getContainer(); if (ptqt!=null && tqt!=null && tdc instanceof TypeDeclaration) { TypeDeclaration qtd = (TypeDeclaration) tdc; Type pst = ptqt.getSupertype(qtd); Type st = tqt.getSupertype(qtd); if (pst!=null && st!=null) { return principalInstantiation(qtd, pst, st, unit); } } return null; } /** * Determine if a type of form X<P>&X<Q> is equivalent * to Nothing where X<T> is invariant in T. * * @param p the argument type P * @param q the argument type Q */ private static boolean hasEmptyIntersectionOfInvariantInstantiations( Type p, Type q) { List<TypeDeclaration> pstds = p.getDeclaration() .getSupertypeDeclarations(); List<TypeDeclaration> qstds = q.getDeclaration() .getSupertypeDeclarations(); Set<TypeDeclaration> set = new HashSet<TypeDeclaration> (pstds.size()+qstds.size()); set.addAll(pstds); set.retainAll(qstds); for (TypeDeclaration std: pstds) { Type pst = null; Type qst = null; for (TypeParameter tp: std.getTypeParameters()) { if (tp.isInvariant()) { if (pst==null) { pst = p.getSupertype(std); } if (qst==null) { qst = q.getSupertype(std); } if (pst!=null && qst!=null) { Type psta = pst.getTypeArguments() .get(tp); Type qsta = qst.getTypeArguments() .get(tp); //TODO: why isWellDefined() instead of isTypeUnknown() ? if (psta!=null && psta.isWellDefined() && !pst.involvesTypeParameters() && qsta!=null && qsta.isWellDefined() && !qst.involvesTypeParameters()) { boolean psti = pst.isInvariant(tp); boolean pstcov = pst.isCovariant(tp); boolean pstcontra = pst.isContravariant(tp); boolean qsti = qst.isInvariant(tp); boolean qstcov = qst.isCovariant(tp); boolean qstcontra = qst.isContravariant(tp); if (psti && qsti && !psta.isExactly(qsta) || pstcov && qsti && !qsta.isSubtypeOf(psta) || qstcov && psti && !psta.isSubtypeOf(qsta) || pstcontra && qsti && !psta.isSubtypeOf(qsta) || qstcontra && psti && !qsta.isSubtypeOf(psta)) { return true; } } } } } } return false; } public static String formatPath(List<String> path, char separator) { StringBuilder sb = new StringBuilder(); for (int i=0; i<path.size(); i++) { String pathPart = path.get(i); if (! pathPart.isEmpty()) { sb.append(pathPart); if (i<path.size()-1) sb.append(separator); } } return sb.toString(); } public static String formatPath(List<String> path) { return formatPath(path, '.'); } /** * Form the union of the given types, eliminating * duplicates. */ public static Type unionType( Type lhst, Type rhst, Unit unit) { List<Type> list = new ArrayList<Type>(2); addToUnion(list, rhst); addToUnion(list, lhst); UnionType ut = new UnionType(unit); ut.setCaseTypes(list); return ut.getType(); } /** * Form the intersection of the given types, * canonicalizing, and eliminating duplicates. */ public static Type intersectionType( Type lhst, Type rhst, Unit unit) { Type simpleIntersection = getSimpleIntersection(lhst, rhst); if (simpleIntersection != null) { return simpleIntersection; } List<Type> list = new ArrayList<Type>(2); addToIntersection(list, rhst, unit); addToIntersection(list, lhst, unit); IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(list); return it.canonicalize().getType(); } /** * Form the union of the given types, without * eliminating duplicates. */ public static Type union( List<Type> types, Unit unit) { if (types.size()==1) { return types.get(0); } UnionType ut = new UnionType(unit); ut.setCaseTypes(types); return ut.getType(); } /** * Form the intersection of the given types, without * eliminating duplicates nor canonicalizing. */ public static Type intersection( List<Type> types, Unit unit) { if (types.size()==1) { return types.get(0); } IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(types); return it.getType(); } /** * Form the canonical intersection of the given types, * without eliminating duplicates. */ public static Type canonicalIntersection( List<Type> types, Unit unit) { if (types.size()==1) { return types.get(0); } IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(types); return it.canonicalize().getType(); } private static Type getSimpleIntersection( Type a, Type b) { if (a == null || b == null) { return null; } TypeDeclaration aDecl = a.getDeclaration(); TypeDeclaration bDecl = b.getDeclaration(); if (aDecl == null || bDecl == null) { return null; } if (!a.isClassOrInterface()) { if (a.isUnion() && b.isClassOrInterface()) { return getSimpleIntersection(b, (ClassOrInterface) bDecl, a); } return null; } if (!b.isClassOrInterface()) { // here aDecl MUST BE a ClassOrInterface as per flow if (b.isUnion()) { return getSimpleIntersection(a, (ClassOrInterface) aDecl, b); } return null; } String aName = aDecl.getQualifiedNameString(); String bName = bDecl.getQualifiedNameString(); if (aName.equals(bName) && aDecl.getTypeParameters().isEmpty() && bDecl.getTypeParameters().isEmpty()) return a; if (a.isAnything()) { // everything is an Anything return b; } if (b.isAnything()) { // everything is an Anything return a; } if (a.isObject()) { // every ClassOrInterface is an object except Null if (b.isNull() || b.isNullValue()) { return aDecl.getUnit().getNothingType(); } return b; } if (b.isObject()) { // every ClassOrInterface is an object except Null if (a.isNull() || a.isNullValue()) { return aDecl.getUnit().getNothingType(); } return a; } if (a.isNull()) { // only null is null if (b.isNull() || b.isNullValue()) { return b; } return aDecl.getUnit().getNothingType(); } if (b.isNull()) { // only null is null if (a.isNull() || a.isNullValue()) { return a; } return aDecl.getUnit().getNothingType(); } // not simple return null; } private static Type getSimpleIntersection( Type a, ClassOrInterface aDecl, Type b) { // we only handle Foo|Null if (b.getCaseTypes().size() != 2) { return null; } // we only handle Object and Null intersections boolean aIsObject = a.isObject(); boolean aIsNull = a.isNull(); if (!aIsObject && !aIsNull) { return null; } Type caseA = b.getCaseTypes().get(0); Type caseB = b.getCaseTypes().get(1); boolean isANull = caseA.isNull(); boolean isBNull = caseB.isNull(); if (aIsObject) { if (isANull) { return simpleObjectIntersection(aDecl, caseB); } if (isBNull) { return simpleObjectIntersection(aDecl, caseA); } // too complex return null; } if (aIsNull) { if (isANull) { return caseA; } if (isBNull) { return caseB; } // too complex return null; } // too complex return null; } private static Type simpleObjectIntersection( ClassOrInterface objectDecl, Type type) { if (type.isClassOrInterface()) { return type; } else if (type.isTypeParameter()) { List<Type> satisfiedTypes = type.getSatisfiedTypes(); if (satisfiedTypes.isEmpty()) { // trivial intersection TP&Object Unit unit = objectDecl.getUnit(); List<Type> types = new ArrayList<Type>(2); types.add(type); types.add(objectDecl.getType()); return canonicalIntersection(types, unit); } for (Type sat: satisfiedTypes) { if (sat.isObject()) { // it is already an Object return type; } } // too complex return null; } // too complex return null; } public static boolean isElementOfUnion( Type unionType, ClassOrInterface ci) { for (Type ct: unionType.getCaseTypes()) { if (ct.isClassOrInterface() && ct.getDeclaration().equals(ci)) { return true; } } return false; } /** * Find the member which best matches the given signature * among the given list of members. In the case that * there are multiple matching declarations, attempt to * return the "best" match, according to some ad-hoc * rules that roughly follow how Java resolves * overloaded methods. * * @param members a list of members to search * @param name the name of the member to find * @param signature the parameter types to match, or * null if we're not matching on parameter types * @param ellipsis true of we want to find a declaration * which supports varags, or false otherwise * * @return the best matching declaration */ public static Declaration lookupMember( List<Declaration> members, String name, List<Type> signature, boolean ellipsis) { List<Declaration> results = null; Declaration result = null; Declaration inexactMatch = null; for (int i=0, size=members.size(); i<size ; i++) { Declaration d = members.get(i); if (isResolvable(d) && isNamed(name, d)) { if (signature==null) { //no argument types: either a type //declaration, an attribute, or a method //reference - don't return overloaded //forms of the declaration (instead //return the "abstraction" of them) if (notOverloaded(d)) { return d; } } else { if (notOverloaded(d)) { //we have found either a non-overloaded //declaration, or the "abstraction" //which of all the overloaded forms //of the declaration //Note: I could not do this optimization // because then it could not distinguish // between Java open() and isOpen() /*if (!isAbstraction(d)) { return d; }*/ inexactMatch = d; } if (hasMatchingSignature(d, signature, ellipsis)) { //we have found an exactly matching //overloaded declaration if (result == null) { result = d; // first match } else { // more than one match, move to array if (results == null) { results = new ArrayList<Declaration>(2); results.add(result); } addIfBetterMatch(results, d, signature); } } } } } // if we never needed a results array if (results == null) { // single result if (result != null) { return result; } // no exact match return inexactMatch; } switch (results.size()) { case 0: //no exact match, so return the non-overloaded //declaration or the "abstraction" of the //overloaded declaration return inexactMatch; case 1: //exactly one exact match, so return it return results.get(0); default: //more than one matching overloaded declaration, //so return the "abstraction" of the overloaded //declaration return inexactMatch; } } private static void addIfBetterMatch( List<Declaration> results, Declaration d, List<Type> signature) { boolean add=true; for (Iterator<Declaration> i = results.iterator(); i.hasNext();) { Declaration o = i.next(); if (betterMatch(d, o, signature)) { i.remove(); } else if (betterMatch(o, d, signature)) { //TODO: note asymmetry here resulting in nondeterminate behavior! add=false; } } if (add) results.add(d); } public static Declaration findMatchingOverloadedClass( Class abstractionClass, List<Type> signature, boolean ellipsis) { List<Declaration> results = new ArrayList<Declaration>(1); if (!abstractionClass.isAbstraction()) { return abstractionClass; } for (Declaration overloaded: abstractionClass.getOverloads()) { if (hasMatchingSignature(overloaded, signature, ellipsis, false)) { addIfBetterMatch(results, overloaded, signature); } } if (results.size() == 1) { return results.get(0); } return abstractionClass; } public static boolean isTypeUnknown(Type type) { return type==null || type.getDeclaration()==null || type.containsUnknowns(); } public static List<Type> getSignature( Declaration dec) { if (!(dec instanceof Functional)) { return null; } Functional fun = (Functional) dec; List<ParameterList> parameterLists = fun.getParameterLists(); if (parameterLists == null || parameterLists.isEmpty()) { return null; } ParameterList parameterList = parameterLists.get(0); if (parameterList == null) { return null; } List<Parameter> parameters = parameterList.getParameters(); if (parameters == null) { return null; } List<Type> signature = new ArrayList<Type> (parameters.size()); Unit unit = dec.getUnit(); for (Parameter param: parameters) { FunctionOrValue model = param.getModel(); Type t = model==null ? unit.getUnknownType() : model.getType(); signature.add(t); } return signature; } public static boolean isCompletelyVisible( Declaration member, Type pt) { if (pt.isUnion()) { for (Type ct: pt.getCaseTypes()) { if (!isCompletelyVisible(member, ct.substitute(pt))) { return false; } } return true; } else if (pt.isIntersection()) { for (Type ct: pt.getSatisfiedTypes()) { if (!isCompletelyVisible(member, ct.substitute(pt))) { return false; } } return true; } else { if (!isVisible(member, pt.getDeclaration())) { return false; } for (Type at: pt.getTypeArgumentList()) { if (at!=null && !isCompletelyVisible(member, at)) { return false; } } return true; } } static boolean isVisible(Declaration member, TypeDeclaration type) { return type instanceof TypeParameter || type.isVisible(member.getVisibleScope()) && (member.getVisibleScope()!=null || !member.getUnit().getPackage().isShared() || type.getUnit().getPackage().isShared()); } /** * Given two instantiations of the same type constructor, * construct a principal instantiation that is a supertype * of both. This is impossible in the following special * cases: * * - an abstract class which does not obey the principal * instantiation inheritance rule * - an intersection between two instantiations of the * same type where one argument is a type parameter * * Nevertheless, we give it our best shot! */ public static Type principalInstantiation( TypeDeclaration dec, Type first, Type second, Unit unit) { List<TypeParameter> tps = dec.getTypeParameters(); List<Type> args = new ArrayList<Type>(tps.size()); Map<TypeParameter,SiteVariance> varianceOverrides = new HashMap<TypeParameter,SiteVariance>(1); for (TypeParameter tp: tps) { Type firstArg = first.getTypeArguments().get(tp); Type secondArg = second.getTypeArguments().get(tp); Type arg; if (firstArg==null || secondArg==null) { arg = unit.getUnknownType(); } else { boolean firstCo = first.isCovariant(tp); boolean secondCo = second.isCovariant(tp); boolean firstContra = first.isContravariant(tp); boolean secondContra = second.isContravariant(tp); boolean firstInv = !firstCo && !firstContra; boolean secondInv = !secondCo && !secondContra; boolean parameterized = firstArg.involvesTypeParameters() || secondArg.involvesTypeParameters(); if (firstContra && secondContra) { arg = unionType( firstArg, secondArg, unit); if (!tp.isContravariant()) { varianceOverrides.put(tp, IN); } } else if (firstCo && secondCo) { arg = intersectionType( firstArg, secondArg, unit); if (!tp.isCovariant()) { varianceOverrides.put(tp, OUT); } } else if (firstContra && secondInv) { if (firstArg.isSubtypeOf(secondArg)) { arg = secondArg; } else if (parameterized) { //irreconcilable instantiations arg = unit.getUnknownType(); } else { return unit.getNothingType(); } } else if (firstCo && secondInv) { if (secondArg.isSubtypeOf(firstArg)) { arg = secondArg; } else if (parameterized) { //irreconcilable instantiations arg = unit.getUnknownType(); } else { return unit.getNothingType(); } } else if (secondCo && firstInv) { if (firstArg.isSubtypeOf(secondArg)) { arg = firstArg; } else if (parameterized) { //irreconcilable instantiations arg = unit.getUnknownType(); } else { return unit.getNothingType(); } } else if (secondContra && firstInv) { if (secondArg.isSubtypeOf(firstArg)) { arg = firstArg; } else if (parameterized) { //irreconcilable instantiations arg = unit.getUnknownType(); } else { return unit.getNothingType(); } } else if (firstInv && secondInv) { if (firstArg.isExactly(secondArg)) { arg = firstArg; } else if (parameterized) { //type parameters that might represent //equivalent types at runtime, //irreconcilable instantiations //TODO: detect cases where we know for // sure that the types are disjoint // because the type parameters only // occur as type args arg = unit.getUnknownType(); } else { //the type arguments are distinct, and the //intersection is Nothing, so there is //no reasonable principal instantiation return unit.getNothingType(); } } else { //opposite variances //irreconcilable instantiations arg = unit.getUnknownType(); } } args.add(arg); } Type result = dec.appliedType(principalQualifyingType( first, second, dec, unit), args); result.setVarianceOverrides(varianceOverrides); return result; } public static boolean areConsistentSupertypes( Type st1, Type st2, Unit unit) { //can't inherit two instantiations of an invariant type //Note: I don't think we need to check type parameters of // the qualifying type, since you're not allowed to // subtype an arbitrary instantiation of a nested // type - only supertypes of the outer type // Nor do we need to check variance overrides since // supertypes can't have them. List<TypeParameter> typeParameters = st1.getDeclaration().getTypeParameters(); for (TypeParameter tp: typeParameters) { if (!tp.isCovariant() && !tp.isContravariant()) { Type ta1 = st1.getTypeArguments().get(tp); Type ta2 = st2.getTypeArguments().get(tp); if (ta1!=null && ta2!=null && !ta1.isExactly(ta2)) { return false; } } } return !intersectionType(st1, st2, unit).isNothing(); } /** * The intersection of the types inherited of the given * declaration. No need to worry about canonicalization * because: * * 1. an inherited type can't be a union, and * 2. they are prevented from being disjoint types. */ public static Type intersectionOfSupertypes( TypeDeclaration td) { Type extendedType = td.getExtendedType(); List<Type> satisfiedTypes = td.getSatisfiedTypes(); List<Type> list = new ArrayList<Type> (satisfiedTypes.size()+1); if (extendedType!=null) { list.add(extendedType); } list.addAll(satisfiedTypes); Unit unit = td.getUnit(); IntersectionType it = new IntersectionType(unit); it.setSatisfiedTypes(list); return it.getType(); } /** * The union of the case types of the given declaration. */ public static Type unionOfCaseTypes( TypeDeclaration td) { List<Type> caseTypes = td.getCaseTypes(); Unit unit = td.getUnit(); if (caseTypes==null) { return unit.getAnythingType(); } List<Type> list = new ArrayList<Type> (caseTypes.size()+1); list.addAll(caseTypes); UnionType it = new UnionType(unit); it.setCaseTypes(list); return it.getType(); } public static int addHashForModule(int ret, Declaration decl) { Module module = getModule(decl); return (37 * ret) + (module != null ? module.hashCode() : 0); } public static boolean sameModule(Declaration a, Declaration b) { Module aMod = getModule(a); Module bMod = getModule(b); return aMod.equals(bMod); } public static void clearProducedTypeCache(TypeDeclaration decl) { Module module = getModule(decl); if(module != null){ module.clearCache(decl); } } public static List<Declaration> getInterveningRefinements( String name, List<Type> signature, Declaration root, TypeDeclaration bottom, TypeDeclaration top) { List<Declaration> result = new ArrayList<Declaration>(2); for (TypeDeclaration std: bottom.getSupertypeDeclarations()) { if (std.inherits(top) && !std.equals(bottom)) { Declaration member = std.getDirectMember(name, signature, false); if (member!=null && member.isShared() && !isAbstraction(member)) { TypeDeclaration td = (TypeDeclaration) member.getContainer(); Declaration refined = td.getRefinedMember(name, signature, false); if (refined!=null && refined.equals(root)) { result.add(member); } } } } return result; } public static List<Declaration> getInheritedDeclarations( String name, TypeDeclaration bottom) { List<Declaration> result = new ArrayList<Declaration>(2); for (TypeDeclaration std: bottom.getSupertypeDeclarations()) { if (!std.equals(bottom)) { Declaration member = std.getDirectMember(name, null, false); if (member!=null && member.isShared() && !isAbstraction(member)) { result.add(member); } } } return result; } /** * Is the given declaration a constructor or singleton * constructor of a toplevel class? * * Constructors of toplevel classes can be directly * imported into the toplevel namespace of a compilation * unit. */ public static boolean isToplevelClassConstructor( TypeDeclaration td, Declaration dec) { return td.isToplevel() && (dec instanceof Constructor || dec instanceof FunctionOrValue && ((FunctionOrValue) dec).getTypeDeclaration() instanceof Constructor); } /** * Is the given declaration a toplevel anonymous class? * * Members of toplevel anonymous classes can be directly * imported into the toplevel namespace of a compilation * unit. */ public static boolean isToplevelAnonymousClass(Scope s) { if (s instanceof Class) { Class td = (Class) s; return td.isAnonymous() && td.isToplevel(); } else { return false; } } public static boolean isNative(Declaration dec) { return dec != null && dec.isNative(); } public static boolean isNativeHeader(Declaration dec) { return dec != null && dec.isNativeHeader(); } public static boolean isNativeImplementation(Declaration dec) { return dec != null && dec.isNative() && !dec.isNativeHeader(); } public static boolean isInNativeContainer(Declaration dec) { Scope container = dec.getContainer(); if (container instanceof Declaration) { Declaration d = (Declaration) container; return d.isNative(); } return false; } public static Declaration getNativeDeclaration( Declaration decl, Backend backend) { return getNativeDeclaration(decl, backend == null ? null : backend.backendSupport); } public static Declaration getNativeDeclaration( Declaration dec, BackendSupport backendSupport) { if (dec.isNative() && backendSupport != null) { Declaration abstraction = null; if (backendSupport.supportsBackend( Backend.fromAnnotation( dec.getNativeBackend()))) { abstraction = dec; } else { List<Declaration> overloads = dec.getOverloads(); if (overloads != null) { for (Declaration d: overloads) { if (backendSupport.supportsBackend( Backend.fromAnnotation( d.getNativeBackend()))) { abstraction = d; break; } } } } return abstraction; } else { return dec; } } /** * The list of type parameters of the given generic * declaration as types. (As viewed within the body of * the generic declaration.) * * @param dec a generic declaration or type constructor * @return a list of types of its type parameters * * @see Declaration#getTypeParametersAsArguments */ public static List<Type> typeParametersAsArgList(Generic dec) { List<TypeParameter> params = dec.getTypeParameters(); if (params.isEmpty()) { return NO_TYPE_ARGS; } int size = params.size(); List<Type> paramsAsArgs = new ArrayList<Type>(size); for (int i=0; i<size; i++) { TypeParameter param = params.get(i); paramsAsArgs.add(param.getType()); } return paramsAsArgs; } /** * Find the declaration with the given name that occurs * directly in the given scope, taking into account the * given backend, if any. Does not take into account * Java overloading * * @param scope any scope * @param name the name of a declaration occurring * directly in the scope, and not overloaded * @param backend the native backend name * * @return the matching declaration */ public static Declaration getDirectMemberForBackend( Scope scope, String name, String backend) { for (Declaration dec: scope.getMembers()) { if (isResolvable(dec) && isNamed(name, dec)) { String nat = dec.getNativeBackend(); if (nat==null) { return dec; } else { if (nat.equals(backend)) { return dec; } } } } return null; } /** * Find the header with the given name that occurs * directly in the given scope or if that scope is * itself a native implementation first look up * the scope's native header and find the requested * header there. * * @param scope any scope * @param name the name of a declaration * * @return the matching declaration */ public static Declaration getNativeHeader(Scope container, String name) { if (container instanceof Declaration) { Declaration cd = (Declaration)container; if (cd.isNative() && !cd.isNativeHeader()) { // The container is a native implementation so // we first need to find _its_ header Scope c = (Scope)getDirectMemberForBackend(cd.getContainer(), cd.getName(), Backend.None.nativeAnnotation); if (c != null) { // Is this the Value part of an object? if (c instanceof Value && isObject((Value)c)) { // Then use the Class part as the container c = ((Value)c).getType().getDeclaration(); } container = c; } } } // Find the header Declaration header = getDirectMemberForBackend(container, name, Backend.None.nativeAnnotation); return header; } // Check if the Value is part of an object (is there a // better way to check this?) public static boolean isObject(Value v) { return v.getType().getDeclaration() .getQualifiedNameString() .equals(v.getQualifiedNameString()); } public static boolean isImplemented(Declaration decl) { if (decl instanceof FunctionOrValue) { FunctionOrValue fov = (FunctionOrValue) decl; return fov.isImplemented(); } return false; } public static boolean eq(Object decl, Object other) { if (decl == null) { return other == null; } else { return decl.equals(other); } } public static boolean equal(Declaration decl, Declaration other) { if (decl instanceof UnionType || decl instanceof IntersectionType || other instanceof UnionType || other instanceof IntersectionType) { return false; } return ModelUtil.eq(decl, other); } public static boolean equalModules(Module scope, Module other) { return eq(scope, other); } public static Module getModule(Declaration decl) { return decl.getUnit().getPackage().getModule(); } public static Package getPackage(Declaration decl) { return decl.getUnit().getPackage(); } public static Package getPackageContainer(Scope scope) { // stop when null or when it's a Package while(scope != null && !(scope instanceof Package)){ // stop if the container is not a Scope if(!(scope.getContainer() instanceof Scope)) return null; scope = (Scope) scope.getContainer(); } return (Package) scope; } public static Module getModuleContainer(Scope scope) { Package pkg = getPackageContainer(scope); return pkg != null ? pkg.getModule() : null; } public static ClassOrInterface getClassOrInterfaceContainer( Element decl) { return getClassOrInterfaceContainer(decl, true); } public static ClassOrInterface getClassOrInterfaceContainer( Element decl, boolean includingDecl) { if (!includingDecl) { decl = (Element) decl.getContainer(); } // stop when null or when it's a ClassOrInterface while(decl != null && !(decl instanceof ClassOrInterface)){ // stop if the container is not an Element if(!(decl.getContainer() instanceof Element)) return null; decl = (Element) decl.getContainer(); } return (ClassOrInterface) decl; } public static void setVisibleScope(Declaration model) { Scope s=model.getContainer(); while (s!=null) { if (s instanceof Declaration) { if (model.isShared()) { if (!((Declaration) s).isShared()) { model.setVisibleScope(s.getContainer()); break; } } else { model.setVisibleScope(s); break; } } else if (s instanceof Package) { //TODO: unshared packages! /*if (!((Package) s).isShared()) { model.setVisibleScope(s); }*/ if (!model.isShared()) { model.setVisibleScope(s); } //null visible scope means visible everywhere break; } else { model.setVisibleScope(s); break; } s = s.getContainer(); } } /** * Determines whether the declaration's containing scope is a class or interface * @param decl The declaration * @return true if the declaration is within a class or interface */ public static boolean withinClassOrInterface(Declaration decl) { return decl.getContainer() instanceof ClassOrInterface; } public static boolean withinClass(Declaration decl) { return decl.getContainer() instanceof Class; } public static boolean isLocalToInitializer(Declaration decl) { return withinClass(decl) && !isCaptured(decl); } public static boolean isCaptured(Declaration decl) { // Shared elements are implicitely captured although the typechecker doesn't mark them that way return decl.isCaptured() || decl.isShared(); } public static boolean isNonTransientValue(Declaration decl) { return (decl instanceof Value) && !((Value)decl).isTransient(); } /** * Is the given scope a local scope but not an initializer scope? */ public static boolean isLocalNotInitializerScope(Scope scope) { return scope instanceof FunctionOrValue || scope instanceof Constructor || scope instanceof ControlBlock || scope instanceof NamedArgumentList || scope instanceof Specification; } /** * Determines whether the declaration is local to a method, * getter or setter, but <strong>returns {@code false} for a declaration * local to a Class initializer.</strong> * @param decl The declaration * @return true if the declaration is local */ public static boolean isLocalNotInitializer(Declaration decl) { return isLocalNotInitializerScope(decl.getContainer()); } public static boolean argumentSatisfiesEnumeratedConstraint( Type receiver, Declaration member, List<Type> typeArguments, Type argType, TypeParameter param) { List<Type> caseTypes = param.getCaseTypes(); if (caseTypes==null || caseTypes.isEmpty()) { //no enumerated constraint return true; } //if the type argument is a subtype of one of the cases //of the type parameter then the constraint is satisfied for (Type ct: caseTypes) { Type cts = ct.appliedType(receiver, member, typeArguments, null); if (argType.isSubtypeOf(cts)) { return true; } } //if the type argument is itself a type parameter with //an enumerated constraint, and every enumerated case //is a subtype of one of the cases of the type parameter, //then the constraint is satisfied TypeDeclaration atd = argType.getDeclaration(); if (argType.isTypeParameter()) { List<Type> argCaseTypes = atd.getCaseTypes(); if (argCaseTypes!=null && !argCaseTypes.isEmpty()) { for (Type act: argCaseTypes) { boolean foundCase = false; for (Type ct: caseTypes) { Type cts = ct.appliedType(receiver, member, typeArguments, null); if (act.isSubtypeOf(cts)) { foundCase = true; break; } } if (!foundCase) { return false; } } return true; } } return false; } public static boolean isBooleanTrue(Declaration d) { return d!=null && d.getQualifiedNameString() .equals("ceylon.language::true"); } public static boolean isBooleanFalse(Declaration d) { return d!=null && d.getQualifiedNameString() .equals("ceylon.language::false"); } public static Type genericFunctionType( Generic generic, Scope scope, Declaration member, Reference reference, Unit unit) { List<TypeParameter> typeParameters = generic.getTypeParameters(); TypeAlias ta = new TypeAlias(); ta.setContainer(scope); ta.setName("Anonymous#" + member.getName()); ta.setAnonymous(true); ta.setScope(scope); ta.setUnit(unit); ta.setExtendedType(reference.getFullType()); ta.setTypeParameters(typeParameters); Type type = ta.getType(); type.setTypeConstructor(true); return type; } public static boolean isConstructor(Declaration member) { return member instanceof Constructor || member instanceof FunctionOrValue && ((FunctionOrValue) member) .getTypeDeclaration() instanceof Constructor; } }
minor cleanups
src/com/redhat/ceylon/model/typechecker/model/ModelUtil.java
minor cleanups
Java
apache-2.0
33f2df85264e655c68c162121ce09503e2dba6ef
0
Wikidata/Wikidata-Toolkit,Wikidata/Wikidata-Toolkit
package org.wikidata.wdtk.rdf; /* * #%L * Wikidata Toolkit RDF * %% * Copyright (C) 2014 Wikidata Toolkit Developers * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.wikidata.wdtk.datamodel.interfaces.GlobeCoordinatesValue; import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue; import org.wikidata.wdtk.datamodel.interfaces.QuantityValue; import org.wikidata.wdtk.datamodel.interfaces.Reference; import org.wikidata.wdtk.datamodel.interfaces.Snak; import org.wikidata.wdtk.datamodel.interfaces.SnakGroup; import org.wikidata.wdtk.datamodel.interfaces.Statement; import org.wikidata.wdtk.datamodel.interfaces.TimeValue; /** * This class contains static methods and constants that define the various OWL * and RDF vocabularies that are used in the export. * * @author Markus Kroetzsch * */ public class Vocabulary { final static MessageDigest md; static { try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException( "Your Java does not support MD5 hashes. You should be concerned."); } } // Prefixes public static final String PREFIX_WBONTO = "http://www.wikidata.org/ontology#"; public static final String PREFIX_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; public static final String PREFIX_RDFS = "http://www.w3.org/2000/01/rdf-schema#"; public static final String PREFIX_OWL = "http://www.w3.org/2002/07/owl#"; public static final String PREFIX_XSD = "http://www.w3.org/2001/XMLSchema#"; public static final String PREFIX_SCHEMA = "http://schema.org/"; public static final String PREFIX_SKOS = "http://www.w3.org/2004/02/skos/core#"; public static final String PREFIX_PROV = "http://www.w3.org/ns/prov#"; // Vocabulary elements that are part of ontology language standards public static final String RDF_TYPE = PREFIX_RDF + "type"; public static final String RDFS_LABEL = PREFIX_RDFS + "label"; public static final String RDFS_SEE_ALSO = PREFIX_RDFS + "seeAlso"; public static final String RDFS_LITERAL = PREFIX_RDFS + "Literal"; public static final String RDFS_SUBCLASS_OF = PREFIX_RDFS + "subClassOf"; public static final String RDFS_SUBPROPERTY_OF = PREFIX_RDFS + "subPropertyOf"; public static final String OWL_THING = PREFIX_OWL + "Thing"; public static final String OWL_CLASS = PREFIX_OWL + "Class"; public static final String OWL_OBJECT_PROPERTY = PREFIX_OWL + "ObjectProperty"; public static final String OWL_DATATYPE_PROPERTY = PREFIX_OWL + "DatatypeProperty"; public static final String OWL_RESTRICTION = PREFIX_OWL + "Restriction"; public static final String OWL_SOME_VALUES_FROM = PREFIX_OWL + "someValuesFrom"; public static final String OWL_ON_PROPERTY = PREFIX_OWL + "onProperty"; public static final String OWL_COMPLEMENT_OF = PREFIX_OWL + "complementOf"; public static final String XSD_DOUBLE = PREFIX_XSD + "double"; public static final String XSD_DECIMAL = PREFIX_XSD + "decimal"; public static final String XSD_INT = PREFIX_XSD + "int"; public static final String XSD_DATE = PREFIX_XSD + "date"; public static final String XSD_G_YEAR = PREFIX_XSD + "gYear"; public static final String XSD_G_YEAR_MONTH = PREFIX_XSD + "gYearMonth"; public static final String XSD_DATETIME = PREFIX_XSD + "dateTime"; public static final String XSD_STRING = PREFIX_XSD + "string"; // Prefixes for value/reference URI construction static final String VALUE_PREFIX_GLOBECOORDS = "VC"; static final String VALUE_PREFIX_QUANTITY = "VQ"; static final String VALUE_PREFIX_TIME = "VT"; static final String VALUE_PREFIX_REFERENCE = "R"; /** * Hash map defining the OWL declaration types of the standard vocabulary. * Declaring this explicitly is useful to obtain a self-contained RDF file, * even when importing ontologies that provide further details on some of * the vocabulary. */ static final Map<String, String> VOCABULARY_TYPES = new HashMap<String, String>(); // Vocabulary elements that are not declared by the ontology language /** * Property "altLabel" of SKOS. */ public static final String SKOS_ALT_LABEL = PREFIX_SKOS + "altLabel"; static { VOCABULARY_TYPES.put(SKOS_ALT_LABEL, OWL_DATATYPE_PROPERTY); } /** * Property "about" of schema.org. */ public static final String SCHEMA_ABOUT = PREFIX_SCHEMA + "about"; static { VOCABULARY_TYPES.put(SCHEMA_ABOUT, OWL_OBJECT_PROPERTY); } /** * Property "description" of schema.org. */ public static final String SCHEMA_DESCRIPTION = PREFIX_SCHEMA + "description"; static { VOCABULARY_TYPES.put(SCHEMA_DESCRIPTION, OWL_DATATYPE_PROPERTY); } /** * Property "inLanguage" of schema.org. */ public static final String SCHEMA_IN_LANGUAGE = PREFIX_SCHEMA + "inLanguage"; static { VOCABULARY_TYPES.put(SCHEMA_IN_LANGUAGE, OWL_DATATYPE_PROPERTY); } /** * Property "wasDerivedFrom" of the provenance ontology. */ public static final String PROV_WAS_DERIVED_FROM = PREFIX_PROV + "wasDerivedFrom"; static { VOCABULARY_TYPES.put(PROV_WAS_DERIVED_FROM, OWL_OBJECT_PROPERTY); } // Wikibase ontology /** * Class for Wikibase items. */ public static final String WB_ITEM = PREFIX_WBONTO + "Item"; static { VOCABULARY_TYPES.put(WB_ITEM, OWL_CLASS); } /** * Class for Wikibase reference. */ public static final String WB_REFERENCE = PREFIX_WBONTO + "Reference"; static { VOCABULARY_TYPES.put(WB_REFERENCE, OWL_CLASS); } /** * Class for Wikibase properties. */ public static final String WB_PROPERTY = PREFIX_WBONTO + "Property"; static { VOCABULARY_TYPES.put(WB_PROPERTY, OWL_CLASS); } /** * Class for Wikibase statements. */ public static final String WB_STATEMENT = PREFIX_WBONTO + "Statement"; static { VOCABULARY_TYPES.put(WB_STATEMENT, OWL_CLASS); } /** * Class for Wikipedia articles. */ public static final String WB_ARTICLE = PREFIX_WBONTO + "Article"; static { VOCABULARY_TYPES.put(WB_ARTICLE, OWL_CLASS); } /** * Class for Wikibase quantity values. */ public static final String WB_QUANTITY_VALUE = PREFIX_WBONTO + "QuantityValue"; static { VOCABULARY_TYPES.put(WB_QUANTITY_VALUE, OWL_CLASS); } /** * Class for Wikibase time values. */ public static final String WB_TIME_VALUE = PREFIX_WBONTO + "TimeValue"; static { VOCABULARY_TYPES.put(WB_TIME_VALUE, OWL_CLASS); } /** * Class for Wikibase globe coordinates values. */ public static final String WB_GLOBE_COORDINATES_VALUE = PREFIX_WBONTO + "GlobeCoordinatesValue"; static { VOCABULARY_TYPES.put(WB_GLOBE_COORDINATES_VALUE, OWL_CLASS); } /** * Property for defining the datatype of a Wikibase property. */ public static final String WB_PROPERTY_TYPE = PREFIX_WBONTO + "propertyType"; static { VOCABULARY_TYPES.put(WB_PROPERTY_TYPE, OWL_OBJECT_PROPERTY); } /** * Property for Wikibase rank. */ public static final String WB_RANK = PREFIX_WBONTO + "rank"; static { VOCABULARY_TYPES.put(WB_RANK, OWL_OBJECT_PROPERTY); } /** * Property for defining the globe of a globe coordinates value. */ public static final String WB_GLOBE = PREFIX_WBONTO + "globe"; static { VOCABULARY_TYPES.put(WB_GLOBE, OWL_OBJECT_PROPERTY); } /** * Property for defining the latitude of a globe coordinates value. */ public static final String WB_LATITUDE = PREFIX_WBONTO + "latitude"; static { VOCABULARY_TYPES.put(WB_LATITUDE, OWL_DATATYPE_PROPERTY); } /** * Property for defining the longitude of a globe coordinates value. */ public static final String WB_LONGITUDE = PREFIX_WBONTO + "longitude"; static { VOCABULARY_TYPES.put(WB_LONGITUDE, OWL_DATATYPE_PROPERTY); } /** * Property for defining the precision of a globe coordinates value. */ public static final String WB_GC_PRECISION = PREFIX_WBONTO + "gcPrecision"; static { VOCABULARY_TYPES.put(WB_GC_PRECISION, OWL_DATATYPE_PROPERTY); } /** * Property for defining the time point of a time value. */ public static final String WB_TIME = PREFIX_WBONTO + "time"; static { VOCABULARY_TYPES.put(WB_TIME, OWL_DATATYPE_PROPERTY); } /** * Property for defining the precision of a time value. */ public static final String WB_TIME_PRECISION = PREFIX_WBONTO + "timePrecision"; static { VOCABULARY_TYPES.put(WB_TIME_PRECISION, OWL_DATATYPE_PROPERTY); } /** * Property for defining the preferred calendar of a time value. */ public static final String WB_PREFERRED_CALENDAR = PREFIX_WBONTO + "preferredCalendar"; static { VOCABULARY_TYPES.put(WB_PREFERRED_CALENDAR, OWL_OBJECT_PROPERTY); } /** * Property for defining the numeric value of a quantity value. */ public static final String WB_NUMERIC_VALUE = PREFIX_WBONTO + "numericValue"; static { VOCABULARY_TYPES.put(WB_NUMERIC_VALUE, OWL_DATATYPE_PROPERTY); } /** * Property for defining the lower bound of a quantity value. */ public static final String WB_LOWER_BOUND = PREFIX_WBONTO + "lowerBound"; static { VOCABULARY_TYPES.put(WB_LOWER_BOUND, OWL_DATATYPE_PROPERTY); } /** * Property for defining the upper bound of a quantity value. */ public static final String WB_UPPER_BOUND = PREFIX_WBONTO + "upperBound"; static { VOCABULARY_TYPES.put(WB_UPPER_BOUND, OWL_DATATYPE_PROPERTY); } /** * Property for defining the unit of a quantity value. */ public static final String WB_QUANTITY_UNIT = PREFIX_WBONTO + "quantityUnit"; static { VOCABULARY_TYPES.put(WB_QUANTITY_UNIT, OWL_OBJECT_PROPERTY); } /** * IRI used as the unit of quantities that have no unit. */ public static final String WB_NO_UNIT = "http://www.wikidata.org/entity/Q199"; public static final String WB_NORMAL_RANK = PREFIX_WBONTO + "NormalRank"; public static final String WB_PREFERRED_RANK = PREFIX_WBONTO + "PreferredRank"; public static final String WB_DEPRECATED_RANK = PREFIX_WBONTO + "DeprecatedRank"; /** * Property for defining a linkage between a property and the URIs which are * used to connect properties to statement. */ public static final String WB_PROPERTY_STATEMENT_LINKAGE = PREFIX_WBONTO + "propertyStatementLinkage"; static { VOCABULARY_TYPES .put(WB_PROPERTY_STATEMENT_LINKAGE, OWL_OBJECT_PROPERTY); } /** * Property for defining a linkage between a property and the URIs which are * used to connect statements to its values. */ public static final String WB_PROPERTY_VALUE_LINKAGE = PREFIX_WBONTO + "propertyValueLinkage"; static { VOCABULARY_TYPES.put(WB_PROPERTY_VALUE_LINKAGE, OWL_OBJECT_PROPERTY); } /** * Property for defining a linkage between a property and the URIs which are * used to connect statements to its qualifiers. */ public static final String WB_PROPERTY_QUALTIFIER_LINKAGE = PREFIX_WBONTO + "propertyQualifierLinkage"; static { VOCABULARY_TYPES.put(WB_PROPERTY_QUALTIFIER_LINKAGE, OWL_OBJECT_PROPERTY); } /** * Property for defining a linkage between a property and the URIs which are * used to connect references to its attributes. */ public static final String WB_PROPERTY_REFERENCE_LINKAGE = PREFIX_WBONTO + "propertyReferenceLinkage"; static { VOCABULARY_TYPES .put(WB_PROPERTY_REFERENCE_LINKAGE, OWL_OBJECT_PROPERTY); } /** * Property for defining a linkage between a property and the URIs which are * used to connect properties to values in simple statements. */ public static final String WB_PROPERTY_SIMPLE_CLAIM = PREFIX_WBONTO + "propertySimpleClaim"; static { VOCABULARY_TYPES.put(WB_PROPERTY_SIMPLE_CLAIM, OWL_OBJECT_PROPERTY); } /** * Returns a map that defines OWL types for all known vocabulary elements. * * @return a map from vocabulary URIs to OWL type URIs */ public static Map<String, String> getKnownVocabularyTypes() { return Collections.unmodifiableMap(VOCABULARY_TYPES); } /** * Get the URI for the given statement. * * @param statement * the statement for which to create a URI * @return the URI */ public static String getStatementUri(Statement statement) { int i = statement.getStatementId().indexOf('$') + 1; return statement.getClaim().getSubject().getIri() + "-" + statement.getStatementId().substring(i); } /** * Get the URI for the given property in the given context. * * @param propertyIdValue * the property id for which to create a URI * @param propertyContext * the context for which the URI will be needed * @return the URI */ public static String getPropertyUri(PropertyIdValue propertyIdValue, PropertyContext propertyContext) { switch (propertyContext) { case STATEMENT: return propertyIdValue.getIri() + "s"; case VALUE: return propertyIdValue.getIri() + "v"; case QUALIFIER: return propertyIdValue.getIri() + "q"; case REFERENCE: return propertyIdValue.getIri() + "r"; case SIMPLE_CLAIM: return propertyIdValue.getIri() + "c"; default: return null; } } public static String getReferenceUri(Reference reference, String uriPrefix) { md.reset(); for (SnakGroup snakgroup : reference.getSnakGroups()) { for (Snak snak : snakgroup.getSnaks()) { updateMessageDigestWithInt(md, snak.hashCode()); } } return uriPrefix + VALUE_PREFIX_REFERENCE + bytesToHex(md.digest()); } public static String getTimeValueUri(TimeValue value, String uriPrefix) { md.reset(); updateMessageDigestWithLong(md, value.getYear()); md.update(value.getMonth()); md.update(value.getDay()); md.update(value.getHour()); md.update(value.getMinute()); md.update(value.getSecond()); updateMessageDigestWithString(md, value.getPreferredCalendarModel()); updateMessageDigestWithInt(md, value.getBeforeTolerance()); updateMessageDigestWithInt(md, value.getAfterTolerance()); updateMessageDigestWithInt(md, value.getTimezoneOffset()); return uriPrefix + VALUE_PREFIX_TIME + bytesToHex(md.digest()); } public static String getGlobeCoordinatesValueUri( GlobeCoordinatesValue value, String uriPrefix) { md.reset(); updateMessageDigestWithString(md, value.getGlobe()); updateMessageDigestWithLong(md, Double.valueOf(value.getLatitude()) .hashCode()); updateMessageDigestWithLong(md, Double.valueOf(value.getLongitude()) .hashCode()); updateMessageDigestWithLong(md, Double.valueOf(value.getPrecision()) .hashCode()); return uriPrefix + VALUE_PREFIX_GLOBECOORDS + bytesToHex(md.digest()); } public static String getQuantityValueUri(QuantityValue value, String uriPrefix) { md.reset(); updateMessageDigestWithInt(md, value.getNumericValue().hashCode()); updateMessageDigestWithInt(md, value.getLowerBound().hashCode()); updateMessageDigestWithInt(md, value.getUpperBound().hashCode()); return uriPrefix + VALUE_PREFIX_QUANTITY + bytesToHex(md.digest()); } static ByteBuffer longByteBuffer = ByteBuffer.allocate(Long.SIZE / 8); static void updateMessageDigestWithLong(MessageDigest md, long x) { longByteBuffer.putLong(0, x); longByteBuffer.rewind(); // important! md.update(longByteBuffer); } static ByteBuffer intByteBuffer = ByteBuffer.allocate(Integer.SIZE / 8); static void updateMessageDigestWithInt(MessageDigest md, int x) { intByteBuffer.putInt(0, x); intByteBuffer.rewind(); // important! md.update(intByteBuffer); } static void updateMessageDigestWithString(MessageDigest md, String s) { if (s == null) { return; } md.update(s.getBytes(StandardCharsets.UTF_8)); } final protected static char[] hexArray = "0123456789abcdef".toCharArray(); static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } }
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/Vocabulary.java
package org.wikidata.wdtk.rdf; /* * #%L * Wikidata Toolkit RDF * %% * Copyright (C) 2014 Wikidata Toolkit Developers * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.wikidata.wdtk.datamodel.interfaces.GlobeCoordinatesValue; import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue; import org.wikidata.wdtk.datamodel.interfaces.QuantityValue; import org.wikidata.wdtk.datamodel.interfaces.Reference; import org.wikidata.wdtk.datamodel.interfaces.Snak; import org.wikidata.wdtk.datamodel.interfaces.SnakGroup; import org.wikidata.wdtk.datamodel.interfaces.Statement; import org.wikidata.wdtk.datamodel.interfaces.TimeValue; /** * This class contains static methods and constants that define the various OWL * and RDF vocabularies that are used in the export. * * @author Markus Kroetzsch * */ public class Vocabulary { final static MessageDigest md; static { try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException( "Your Java does not support MD5 hashes. You should be concerned."); } } // Prefixes public static final String PREFIX_WBONTO = "http://www.wikidata.org/ontology#"; public static final String PREFIX_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; public static final String PREFIX_RDFS = "http://www.w3.org/2000/01/rdf-schema#"; public static final String PREFIX_OWL = "http://www.w3.org/2002/07/owl#"; public static final String PREFIX_XSD = "http://www.w3.org/2001/XMLSchema#"; public static final String PREFIX_SCHEMA = "http://schema.org/"; public static final String PREFIX_SKOS = "http://www.w3.org/2004/02/skos/core#"; public static final String PREFIX_PROV = "http://www.w3.org/ns/prov#"; // Vocabulary elements that are part of ontology language standards public static final String RDF_TYPE = PREFIX_RDF + "type"; public static final String RDFS_LABEL = PREFIX_RDFS + "label"; public static final String RDFS_SEE_ALSO = PREFIX_RDFS + "seeAlso"; public static final String RDFS_LITERAL = PREFIX_RDFS + "Literal"; public static final String RDFS_SUBCLASS_OF = PREFIX_RDFS + "subClassOf"; public static final String RDFS_SUBPROPERTY_OF = PREFIX_RDFS + "subPropertyOf"; public static final String OWL_THING = PREFIX_OWL + "Thing"; public static final String OWL_CLASS = PREFIX_OWL + "Class"; public static final String OWL_OBJECT_PROPERTY = PREFIX_OWL + "ObjectProperty"; public static final String OWL_DATATYPE_PROPERTY = PREFIX_OWL + "DatatypeProperty"; public static final String OWL_RESTRICTION = PREFIX_OWL + "Restriction"; public static final String OWL_SOME_VALUES_FROM = PREFIX_OWL + "someValuesFrom"; public static final String OWL_ON_PROPERTY = PREFIX_OWL + "onProperty"; public static final String OWL_COMPLEMENT_OF = PREFIX_OWL + "complementOf"; public static final String XSD_DOUBLE = PREFIX_XSD + "double"; public static final String XSD_DECIMAL = PREFIX_XSD + "decimal"; public static final String XSD_INT = PREFIX_XSD + "int"; public static final String XSD_DATE = PREFIX_XSD + "date"; public static final String XSD_G_YEAR = PREFIX_XSD + "gYear"; public static final String XSD_G_YEAR_MONTH = PREFIX_XSD + "gYearMonth"; public static final String XSD_DATETIME = PREFIX_XSD + "dateTime"; public static final String XSD_STRING = PREFIX_XSD + "string"; // Prefixes for value/reference URI construction static final String VALUE_PREFIX_GLOBECOORDS = "VC"; static final String VALUE_PREFIX_QUANTITY = "VQ"; static final String VALUE_PREFIX_TIME = "VT"; static final String VALUE_PREFIX_REFERENCE = "R"; /** * Hash map defining the OWL declaration types of the standard vocabulary. * Declaring this explicitly is useful to obtain a self-contained RDF file, * even when importing ontologies that provide further details on some of * the vocabulary. */ static final Map<String, String> VOCABULARY_TYPES = new HashMap<String, String>(); // Vocabulary elements that are not declared by the ontology language /** * Property "altLabel" of SKOS. */ public static final String SKOS_ALT_LABEL = PREFIX_SKOS + "altLabel"; static { VOCABULARY_TYPES.put(SKOS_ALT_LABEL, OWL_DATATYPE_PROPERTY); } /** * Property "about" of schema.org. */ public static final String SCHEMA_ABOUT = PREFIX_SCHEMA + "about"; static { VOCABULARY_TYPES.put(SCHEMA_ABOUT, OWL_OBJECT_PROPERTY); } /** * Property "description" of schema.org. */ public static final String SCHEMA_DESCRIPTION = PREFIX_SCHEMA + "description"; static { VOCABULARY_TYPES.put(SCHEMA_DESCRIPTION, OWL_DATATYPE_PROPERTY); } /** * Property "inLanguage" of schema.org. */ public static final String SCHEMA_IN_LANGUAGE = PREFIX_SCHEMA + "inLanguage"; static { VOCABULARY_TYPES.put(SCHEMA_IN_LANGUAGE, OWL_DATATYPE_PROPERTY); } /** * Property "wasDerivedFrom" of the provenance ontology. */ public static final String PROV_WAS_DERIVED_FROM = PREFIX_PROV + "wasDerivedFrom"; static { VOCABULARY_TYPES.put(PROV_WAS_DERIVED_FROM, OWL_OBJECT_PROPERTY); } // Wikibase ontology /** * Class for Wikibase items. */ public static final String WB_ITEM = PREFIX_WBONTO + "Item"; static { VOCABULARY_TYPES.put(WB_ITEM, OWL_CLASS); } /** * Class for Wikibase reference. */ public static final String WB_REFERENCE = PREFIX_WBONTO + "Reference"; static { VOCABULARY_TYPES.put(WB_REFERENCE, OWL_CLASS); } /** * Class for Wikibase properties. */ public static final String WB_PROPERTY = PREFIX_WBONTO + "Property"; static { VOCABULARY_TYPES.put(WB_PROPERTY, OWL_CLASS); } /** * Class for Wikibase statements. */ public static final String WB_STATEMENT = PREFIX_WBONTO + "Statement"; static { VOCABULARY_TYPES.put(WB_STATEMENT, OWL_CLASS); } /** * Class for Wikipedia articles. */ public static final String WB_ARTICLE = PREFIX_WBONTO + "Article"; static { VOCABULARY_TYPES.put(WB_ARTICLE, OWL_CLASS); } /** * Class for Wikibase quantity values. */ public static final String WB_QUANTITY_VALUE = PREFIX_WBONTO + "QuantityValue"; static { VOCABULARY_TYPES.put(WB_QUANTITY_VALUE, OWL_CLASS); } /** * Class for Wikibase time values. */ public static final String WB_TIME_VALUE = PREFIX_WBONTO + "TimeValue"; static { VOCABULARY_TYPES.put(WB_TIME_VALUE, OWL_CLASS); } /** * Class for Wikibase globe coordinates values. */ public static final String WB_GLOBE_COORDINATES_VALUE = PREFIX_WBONTO + "GlobeCoordinatesValue"; static { VOCABULARY_TYPES.put(WB_GLOBE_COORDINATES_VALUE, OWL_CLASS); } /** * Property for defining the datatype of a Wikibase property. */ public static final String WB_PROPERTY_TYPE = PREFIX_WBONTO + "propertyType"; static { VOCABULARY_TYPES.put(WB_PROPERTY_TYPE, OWL_OBJECT_PROPERTY); } /** * Property for Wikibase rank. */ public static final String WB_RANK = PREFIX_WBONTO + "rank"; static { VOCABULARY_TYPES.put(WB_RANK, OWL_OBJECT_PROPERTY); } /** * Property for defining the globe of a globe coordinates value. */ public static final String WB_GLOBE = PREFIX_WBONTO + "globe"; static { VOCABULARY_TYPES.put(WB_GLOBE, OWL_OBJECT_PROPERTY); } /** * Property for defining the latitude of a globe coordinates value. */ public static final String WB_LATITUDE = PREFIX_WBONTO + "latitude"; static { VOCABULARY_TYPES.put(WB_LATITUDE, OWL_DATATYPE_PROPERTY); } /** * Property for defining the longitude of a globe coordinates value. */ public static final String WB_LONGITUDE = PREFIX_WBONTO + "longitude"; static { VOCABULARY_TYPES.put(WB_LONGITUDE, OWL_DATATYPE_PROPERTY); } /** * Property for defining the precision of a globe coordinates value. */ public static final String WB_GC_PRECISION = PREFIX_WBONTO + "gcPrecision"; static { VOCABULARY_TYPES.put(WB_GC_PRECISION, OWL_DATATYPE_PROPERTY); } /** * Property for defining the time point of a time value. */ public static final String WB_TIME = PREFIX_WBONTO + "time"; static { VOCABULARY_TYPES.put(WB_TIME, OWL_DATATYPE_PROPERTY); } /** * Property for defining the precision of a time value. */ public static final String WB_TIME_PRECISION = PREFIX_WBONTO + "timePrecision"; static { VOCABULARY_TYPES.put(WB_TIME_PRECISION, OWL_DATATYPE_PROPERTY); } /** * Property for defining the preferred calendar of a time value. */ public static final String WB_PREFERRED_CALENDAR = PREFIX_WBONTO + "preferredCalendar"; static { VOCABULARY_TYPES.put(WB_PREFERRED_CALENDAR, OWL_OBJECT_PROPERTY); } /** * Property for defining the numeric value of a quantity value. */ public static final String WB_NUMERIC_VALUE = PREFIX_WBONTO + "numericValue"; static { VOCABULARY_TYPES.put(WB_NUMERIC_VALUE, OWL_DATATYPE_PROPERTY); } /** * Property for defining the lower bound of a quantity value. */ public static final String WB_LOWER_BOUND = PREFIX_WBONTO + "lowerBound"; static { VOCABULARY_TYPES.put(WB_LOWER_BOUND, OWL_DATATYPE_PROPERTY); } /** * Property for defining the upper bound of a quantity value. */ public static final String WB_UPPER_BOUND = PREFIX_WBONTO + "upperBound"; static { VOCABULARY_TYPES.put(WB_UPPER_BOUND, OWL_DATATYPE_PROPERTY); } /** * Property for defining the unit of a quantity value. */ public static final String WB_QUANTITY_UNIT = PREFIX_WBONTO + "quantityUnit"; static { VOCABULARY_TYPES.put(WB_QUANTITY_UNIT, OWL_OBJECT_PROPERTY); } /** * IRI used as the unit of quantities that have no unit. */ public static final String WB_NO_UNIT = "http://www.wikidata.org/entity/Q199"; public static final String WB_NORMAL_RANK = PREFIX_WBONTO + "NormalRank"; public static final String WB_PREFERRED_RANK = PREFIX_WBONTO + "PreferredRank"; public static final String WB_DEPRECATED_RANK = PREFIX_WBONTO + "DeprecatedRank"; /** * Property for defining a linkage between a property and the URIs which are * used to connect properties to statement. */ public static final String WB_PROPERTY_STATEMENT_LINKAGE = PREFIX_WBONTO + "propertyStatementLinkage"; static { VOCABULARY_TYPES .put(WB_PROPERTY_STATEMENT_LINKAGE, OWL_OBJECT_PROPERTY); } /** * Property for defining a linkage between a property and the URIs which are * used to connect statements to its values. */ public static final String WB_PROPERTY_VALUE_LINKAGE = PREFIX_WBONTO + "propertyValueLinkage"; static { VOCABULARY_TYPES.put(WB_PROPERTY_VALUE_LINKAGE, OWL_OBJECT_PROPERTY); } /** * Property for defining a linkage between a property and the URIs which are * used to connect statements to its qualifiers. */ public static final String WB_PROPERTY_QUALTIFIER_LINKAGE = PREFIX_WBONTO + "propertyQualifierLinkage"; static { VOCABULARY_TYPES.put(WB_PROPERTY_QUALTIFIER_LINKAGE, OWL_OBJECT_PROPERTY); } /** * Property for defining a linkage between a property and the URIs which are * used to connect references to its attributes. */ public static final String WB_PROPERTY_REFERENCE_LINKAGE = PREFIX_WBONTO + "propertyReferenceLinkage"; static { VOCABULARY_TYPES .put(WB_PROPERTY_REFERENCE_LINKAGE, OWL_OBJECT_PROPERTY); } /** * Property for defining a linkage between a property and the URIs which are * used to connect properties to values in simple statements. */ public static final String WB_PROPERTY_SIMPLE_CLAIM = PREFIX_WBONTO + "propertySimpleClaim"; static { VOCABULARY_TYPES.put(WB_PROPERTY_SIMPLE_CLAIM, OWL_OBJECT_PROPERTY); } /** * Returns a map that defines OWL types for all known vocabulary elements. * * @return a map from vocabulary URIs to OWL type URIs */ public static Map<String, String> getKnownVocabularyTypes() { return Collections.unmodifiableMap(VOCABULARY_TYPES); } /** * Get the URI for the given statement. * * @param statement * the statement for which to create a URI * @return the URI */ public static String getStatementUri(Statement statement) { int i = statement.getStatementId().indexOf('$') + 1; return statement.getClaim().getSubject().getIri() + "S" + statement.getStatementId().substring(i); } /** * Get the URI for the given property in the given context. * * @param propertyIdValue * the property id for which to create a URI * @param propertyContext * the context for which the URI will be needed * @return the URI */ public static String getPropertyUri(PropertyIdValue propertyIdValue, PropertyContext propertyContext) { switch (propertyContext) { case STATEMENT: return propertyIdValue.getIri() + "s"; case VALUE: return propertyIdValue.getIri() + "v"; case QUALIFIER: return propertyIdValue.getIri() + "q"; case REFERENCE: return propertyIdValue.getIri() + "r"; case SIMPLE_CLAIM: return propertyIdValue.getIri() + "c"; default: return null; } } public static String getReferenceUri(Reference reference, String uriPrefix) { md.reset(); for (SnakGroup snakgroup : reference.getSnakGroups()) { for (Snak snak : snakgroup.getSnaks()) { updateMessageDigestWithInt(md, snak.hashCode()); } } return uriPrefix + VALUE_PREFIX_REFERENCE + bytesToHex(md.digest()); } public static String getTimeValueUri(TimeValue value, String uriPrefix) { md.reset(); updateMessageDigestWithLong(md, value.getYear()); md.update(value.getMonth()); md.update(value.getDay()); md.update(value.getHour()); md.update(value.getMinute()); md.update(value.getSecond()); updateMessageDigestWithString(md, value.getPreferredCalendarModel()); updateMessageDigestWithInt(md, value.getBeforeTolerance()); updateMessageDigestWithInt(md, value.getAfterTolerance()); updateMessageDigestWithInt(md, value.getTimezoneOffset()); return uriPrefix + VALUE_PREFIX_TIME + bytesToHex(md.digest()); } public static String getGlobeCoordinatesValueUri( GlobeCoordinatesValue value, String uriPrefix) { md.reset(); updateMessageDigestWithString(md, value.getGlobe()); updateMessageDigestWithLong(md, Double.valueOf(value.getLatitude()) .hashCode()); updateMessageDigestWithLong(md, Double.valueOf(value.getLongitude()) .hashCode()); updateMessageDigestWithLong(md, Double.valueOf(value.getPrecision()) .hashCode()); return uriPrefix + VALUE_PREFIX_GLOBECOORDS + bytesToHex(md.digest()); } public static String getQuantityValueUri(QuantityValue value, String uriPrefix) { md.reset(); updateMessageDigestWithInt(md, value.getNumericValue().hashCode()); updateMessageDigestWithInt(md, value.getLowerBound().hashCode()); updateMessageDigestWithInt(md, value.getUpperBound().hashCode()); return uriPrefix + VALUE_PREFIX_QUANTITY + bytesToHex(md.digest()); } static ByteBuffer longByteBuffer = ByteBuffer.allocate(Long.SIZE / 8); static void updateMessageDigestWithLong(MessageDigest md, long x) { longByteBuffer.putLong(0, x); longByteBuffer.rewind(); // important! md.update(longByteBuffer); } static ByteBuffer intByteBuffer = ByteBuffer.allocate(Integer.SIZE / 8); static void updateMessageDigestWithInt(MessageDigest md, int x) { intByteBuffer.putInt(0, x); intByteBuffer.rewind(); // important! md.update(intByteBuffer); } static void updateMessageDigestWithString(MessageDigest md, String s) { if (s == null) { return; } md.update(s.getBytes(StandardCharsets.UTF_8)); } final protected static char[] hexArray = "0123456789abcdef".toCharArray(); static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } }
change StatementId format
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/Vocabulary.java
change StatementId format
Java
apache-2.0
a486002f112924367ff3d2c8ab5fe68996b23f89
0
LittlePanpc/android-download-manager
src/com/littlepanpc/downloader/db/DownloadDBHelper.java
package com.littlepanpc.downloader.db; import com.littlepanpc.downloader.util.LogUtils; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * @class: DownloadDBHelper * @Description: create or update database table---\"downloads.db\" * @author: Peter Pan * @email: happychinapc@gmail.com * @date: 2014-5-19 下午6:07:39 * @since: 1.0.0 * */ public class DownloadDBHelper extends SQLiteOpenHelper { private static final String TAG = DownloadDBHelper.class.getSimpleName(); public static final String DB_NAME = "downloads.db"; public static final String DB_TABLE_NAME = "download_task"; public static final int DB_VERSION = 1; private static DownloadDBHelper instance; /** * @Title: getInstance * @Description: concurrent singleTon---double checking lock pattern * @param context * @return * @return DownloadDBHelper * @throws */ public static DownloadDBHelper getInstance(Context context) { if (instance == null) { synchronized (DownloadDBHelper.class) { if (instance == null) { instance = new DownloadDBHelper(context); } } } LogUtils.i(TAG, "getInstance---"+instance); return instance; } /** * <p>Title: </p> * <p>Description: Constructor</p> * * @param context */ private DownloadDBHelper(Context context) { // TODO Auto-generated constructor stub super(context, DB_NAME, null, DB_VERSION); LogUtils.i(TAG, "DownloadDBHelper constructor"); } /* (non-Javadoc) * <p>Title: onCreate</p> * <p>Description: create database table</p> * @param db * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase) */ @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub LogUtils.i(TAG, "onCreate start"); String createSQL = "create table " + DB_TABLE_NAME + "(" + "_id integer primary key autoincrement, " + "url text unique, " + "parent_path text, " + "file_name text, " + "downloaded_size integer, " + "total_size integer, " + "status integer)"; LogUtils.i(TAG, "createsql---"+createSQL); LogUtils.i(TAG, "onCreate before execute"); db.execSQL(createSQL); LogUtils.i(TAG, "onCreate after execute"); LogUtils.i(TAG, "onCreate finish"); } /* (non-Javadoc) * <p>Title: onUpgrade</p> * <p>Description: update database table</p> * @param db * @param oldVersion * @param newVersion * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int) */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub String dropSQL = "drop table if exists " + DB_TABLE_NAME; LogUtils.i(TAG, "dropsql---"+dropSQL); LogUtils.i(TAG, "onUpgrade before execute"); db.execSQL(dropSQL); LogUtils.i(TAG, "onUpgrade after execute"); onCreate(db); LogUtils.i(TAG, "onUpgrade finish"); } }
Delete DownloadDBHelper.java
src/com/littlepanpc/downloader/db/DownloadDBHelper.java
Delete DownloadDBHelper.java
Java
apache-2.0
4e77fb850dbbb77d9efa70e00f28fe3dd3738d03
0
GlenKPeterson/UncleJim,GlenKPeterson/UncleJim
// Copyright 2015-04-13 PlanBase Inc. & Glen Peterson // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.organicdesign.fp.collections; import org.organicdesign.fp.tuple.Tuple2; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; /** An unmodifiable map. This cannot extend Collection because the remove() method would then be inherited from both Collection and Map and Collection.remove() returns a boolean while Map.remove() returns a V (the type of the value in the key/value pair). Maybe an UnmodSizedIterable is called for? */ public interface UnmodMap<K,V> extends Map<K,V>, UnmodIterable<UnmodMap.UnEntry<K,V>>, Sized { // ========================================== Static ========================================== /** Implements equals and hashCode() methods compatible with java.util.Map (which ignores order) to make defining unmod Maps easier. Inherits hashCode() and toString() from AbstractUnmodIterable. */ abstract class AbstractUnmodMap<K,V> extends AbstractUnmodIterable<UnmodMap.UnEntry<K,V>> implements UnmodMap<K,V> { @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Map)) { return false; } Map<?, ?> that = (Map<?, ?>) other; if (that.size() != size()) { return false; } try { for (Entry<K, V> e : this) { K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(that.get(key) == null && that.containsKey(key))) { return false; } } else { if (!value.equals(that.get(key))) { return false; } } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } } /** * A map entry (key-value pair). The <tt>UnmodMap.entrySet</tt> method returns * a collection-view of the map, whose elements are of this class. The * <i>only</i> way to obtain a reference to a map entry is from the * iterator of this collection-view. * * @see UnmodMap#entrySet() */ interface UnEntry<K,V> extends Map.Entry<K,V> { class EntryToUnEntryIter<K,V> implements UnmodIterator<UnEntry<K,V>> { //, Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903082500L; private final Iterator<Entry<K,V>> innerIter; EntryToUnEntryIter(Iterator<Entry<K,V>> i) { innerIter = i; } @Override public boolean hasNext() { return innerIter.hasNext(); } @Override public UnEntry<K, V> next() { class Wrapper implements UnEntry<K,V>, Serializable { // For serializable. Make sure to change whenever internal data format changes. private static final long serialVersionUID = 20160903082500L; private final Entry<K,V> entry; private Wrapper(Entry<K,V> e) { entry = e; } @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if ( !(other instanceof Entry) ) { return false; } Entry that = (Entry) other; return Objects.equals(entry.getKey(), that.getKey()) && Objects.equals(entry.getValue(), that.getValue()); } @Override public int hashCode() { return entry.hashCode(); } @Override public String toString() { return "entry(" + entry.getKey() + "," + entry.getValue() + ")"; } }; return new Wrapper(innerIter.next()); } } class EntryToUnEntrySortedIter<K,V> extends EntryToUnEntryIter<K,V> implements UnmodSortedIterator<UnEntry<K,V>> { //, Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903082500L; EntryToUnEntrySortedIter(Iterator<Entry<K,V>> i) { super(i); } } class UnmodKeyIter<K,V> implements UnmodIterator<K> { //, Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903174100L; private final Iterator<? extends Map.Entry<K,V>> iter; UnmodKeyIter(Iterator<? extends Map.Entry<K,V>> i) { iter = i; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public K next() { return iter.next().getKey(); } } class UnmodSortedKeyIter<K,V> extends UnmodKeyIter<K,V> implements UnmodSortedIterator<K> { // , Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903174100L; UnmodSortedKeyIter(Iterator<? extends Map.Entry<K,V>> i) { super(i); } } class UnmodValIter<K,V> implements UnmodIterator<V> { //, Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903174100L; private final Iterator<? extends Map.Entry<K,V>> iter; UnmodValIter(Iterator<? extends Map.Entry<K,V>> i) { iter = i; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public V next() { return iter.next().getValue(); } } class UnmodSortedValIter<K,V> extends UnmodValIter<K,V> implements UnmodSortedIterator<V> { // , Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903174100L; UnmodSortedValIter(Iterator<? extends Map.Entry<K,V>> i) { super(i); } } /** Use {@link org.organicdesign.fp.tuple.Tuple2#of(java.util.Map.Entry)} instead. */ @Deprecated static <K,V> UnEntry<K,V> entryToUnEntry(Map.Entry<K,V> entry) { return Tuple2.of(entry); } static <K,V> UnmodIterator<UnEntry<K,V>> entryIterToUnEntryUnIter(Iterator<Entry<K,V>> innerIter) { return new EntryToUnEntryIter<>(innerIter); } static <K,V> UnmodSortedIterator<UnEntry<K,V>> entryIterToUnEntrySortedUnIter(Iterator<Entry<K,V>> innerIter) { return new EntryToUnEntrySortedIter<>(innerIter); } // This should be done with a cast, not with code. // static <K,V> UnmodSortedIterator<UnEntry<K,V>> unSortIterEntToUnSortIterUnEnt( // UnmodSortedIterator<Entry<K,V>> innerIter) { // return new UnmodSortedIterator<UnEntry<K, V>>() { // @Override public boolean hasNext() { return innerIter.hasNext(); } // @Override public UnEntry<K, V> next() { // return UnmodMap.UnEntry.entryToUnEntry(innerIter.next()); // } // }; // } // /** Not compatible with immutability - use {@link ImMap#assoc(Object, Object)} instead because it returns a new map. */ @SuppressWarnings("deprecation") @Override @Deprecated default V setValue(V value) { throw new UnsupportedOperationException("Modification attempted"); } } // ========================================= Instance ========================================= // Modification Operations /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default void clear() { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("Modification attempted"); } // boolean containsKey(Object key) // boolean containsValue(Object value) /** Most maps are not designed for this - the default implementation has O(n) performance. {@inheritDoc} */ // This is the place to define this slow operation so that it can be used in // values().contains(), UnmodSortedMap.containsValue() and UnmodSortedMap.values().contains(). @SuppressWarnings("SuspiciousMethodCalls") @Override default boolean containsValue(Object value) { for (UnEntry<K,V> item : this) { if (Objects.equals(item.getValue(), value)) { return true; } } return false; } /** Returns a view of the mappings contained in this map. The set will contain UnmodMap.UnEntry items, but that return signature is illegal in Java, so you'll just have to remember. An UnmodMap is iterable, so this method is probably not nearly as useful as it once was. {@inheritDoc} */ @Override default UnmodSet<Entry<K,V>> entrySet() { class EntrySet extends UnmodSet.AbstractUnmodSet<Entry<K,V>> implements Serializable { // For serializable. Make sure to change whenever internal data format changes. private static final long serialVersionUID = 20160903104400L; private final UnmodMap<K,V> parent; private EntrySet(UnmodMap<K,V> p) { parent = p; } @SuppressWarnings("unchecked") @Override public boolean contains(Object o) { if ( !(o instanceof Entry) ) { return false; } Entry<K,V> entry = (Entry<K,V>) o; if (!parent.containsKey(entry.getKey())) { return false; } V value = parent.get(entry.getKey()); return Objects.equals(entry.getValue(), value); } @SuppressWarnings("unchecked") @Override public UnmodIterator<Entry<K,V>> iterator() { // Converting from // UnmodIterator<UnEntry<K,V>> to // UnmodIterator<Entry<K,V>> // Is a totally legal widening conversion (at runtime) because UnEntry extends // (is an) Entry. But Java's type system doesn't know that because (I think) // it's a higher kinded type. Thanks to type erasure, we can forget about all // that and cast it to a base type then suppress the unchecked warning. // // Hmm... It's possible for this to return an Entry if the wrapped collection // uses them... Not sure how much that matters. return (UnmodIterator) parent.iterator(); } @Override public int size() { return parent.size(); } @Override public String toString() { return UnmodIterable.toString("UnmodMap.entrySet", this); } } return new EntrySet(this); } // boolean equals(Object o) // @Override default boolean equals(Object other) { // // Cheapest operation first... // if (this == other) { return true; } // // if ( (other == null) || // !(other instanceof Map) || // (this.hashCode() != other.hashCode()) ) { // return false; // } // // Details... // final Map that = (Map) other; // if (this.size() != that.size()) { // return false; // } // return this.entrySet().containsAll(that.entrySet()); // } // default void forEach(BiConsumer<? super K,? super V> action) // V get(Object key) // default V getOrDefault(Object key, V defaultValue) // @Override default int hashCode() { // if (size() == 0) { return 0; } // return Arrays.hashCode(entrySet().toArray()); // }; /** {@inheritDoc} */ @Override default boolean isEmpty() { return size() == 0; } /** Returns a view of the keys contained in this map. An UnmodMap is iterable, so this method is probably not nearly as useful as it once was. {@inheritDoc} */ @Override default UnmodSet<K> keySet() { class KeySet extends UnmodSet.AbstractUnmodSet<K> implements Serializable { // For serializable. Make sure to change whenever internal data format changes. private static final long serialVersionUID = 20160903104400L; private final UnmodMap<K,V> parent; private KeySet(UnmodMap<K,V> p) { parent = p; } @SuppressWarnings("SuspiciousMethodCalls") @Override public boolean contains(Object o) { return parent.containsKey(o); } @Override public UnmodIterator<K> iterator() { return new UnEntry.UnmodKeyIter<>(parent.iterator()); } @Override public int size() { return parent.size(); } @Override public String toString() { return UnmodIterable.toString("UnmodMap.keySet", this); } } return new KeySet(this); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("Modification attempted"); } /** Not compatible with immutability - use {@link ImMap#assoc(Object, Object)} instead because it returns a new map. */ @Override @Deprecated default V put(K key, V value) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default void putAll(Map<? extends K, ? extends V> m) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V putIfAbsent(K key, V value) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V remove(Object key) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default boolean remove(Object key, Object value) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V replace(K key, V value) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException("Modification attempted"); } // int size() /** This method has been deprecated because it is impossible to implement equals() or hashCode() on the resulting collection, and calling this method is probably at least a missed opportunity, if not an outright error. Use an UnmodMap as an UnmodIterable&lt;UnmodMap.UnEntry&gt; instead. If you don't care about eliminating duplicate values, and want a compatible return type call: <pre><code>myMap.map((UnEntry&lt;K,V&gt; entry) -&gt; entry.getValue()) .toImSet();</code></pre> If you want to keep a count of duplicates, try something like this, but it has a different signature: <pre><code>ImMap&lt;V,Integer&gt; valueCounts = myMap.foldLeft(PersistentHashMap.empty(), (ImMap&lt;V,Integer&gt; accum, UnEntry&lt;K,V&gt; origEntry) -&gt; { V inVal = origEntry.getValue(); return accum.assoc(inVal, accum.getOrElse(inVal, 0) + 1); });</code></pre> You really shouldn't turn values() into a List, because a List has order and an unsorted Map is unordered by key, and especially unordered by value. On a SortedMap, List is the proper return type. java.util.HashMap.values() returns an instance of java.util.HashMap.Values which does *not* have equals() or hashCode() defined. This is because List.equals() and Set.equals() return not-equal when compared to a Collection. There is no good way to implement a reflexive equals with both of those because they are just too different. Ultimately, Collection just isn't specific enough to instantiate, but we do it anyway here for backward compatibility. We don't implement equals() or hashCode() either because the result could have duplicates. If the Map isn't sorted, the result could have random ordering. {@inheritDoc} */ @Deprecated @Override default UnmodCollection<V> values() { class Impl implements UnmodCollection<V>, Serializable { // For serializable. Make sure to change whenever internal data format changes. private static final long serialVersionUID = 20160903104400L; private final UnmodMap<K,V> parent; private Impl(UnmodMap<K,V> p) { parent = p; } @SuppressWarnings("SuspiciousMethodCalls") @Override public boolean contains(Object o) { return parent.containsValue(o); } @Override public UnmodIterator<V> iterator() { return new UnEntry.UnmodValIter<>(parent.iterator()); } @Override public int size() { return parent.size(); } @Override public String toString() { return UnmodIterable.toString("UnmodMap.values", this); } }; return new Impl(this); } }
src/main/java/org/organicdesign/fp/collections/UnmodMap.java
// Copyright 2015-04-13 PlanBase Inc. & Glen Peterson // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.organicdesign.fp.collections; import java.io.Serializable; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Function; import org.organicdesign.fp.tuple.Tuple2; /** An unmodifiable map. This cannot extend Collection because the remove() method would then be inherited from both Collection and Map and Collection.remove() returns a boolean while Map.remove() returns a V (the type of the value in the key/value pair). Maybe an UnmodSizedIterable is called for? */ public interface UnmodMap<K,V> extends Map<K,V>, UnmodIterable<UnmodMap.UnEntry<K,V>>, Sized { // ========================================== Static ========================================== /** Implements equals and hashCode() methods compatible with java.util.Map (which ignores order) to make defining unmod Maps easier. Inherits hashCode() and toString() from AbstractUnmodIterable. */ abstract class AbstractUnmodMap<K,V> extends AbstractUnmodIterable<UnmodMap.UnEntry<K,V>> implements UnmodMap<K,V> { @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Map)) { return false; } Map<?, ?> that = (Map<?, ?>) other; if (that.size() != size()) { return false; } try { for (Entry<K, V> e : this) { K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(that.get(key) == null && that.containsKey(key))) { return false; } } else { if (!value.equals(that.get(key))) { return false; } } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } } /** * A map entry (key-value pair). The <tt>UnmodMap.entrySet</tt> method returns * a collection-view of the map, whose elements are of this class. The * <i>only</i> way to obtain a reference to a map entry is from the * iterator of this collection-view. * * @see UnmodMap#entrySet() */ interface UnEntry<K,V> extends Map.Entry<K,V> { class EntryToUnEntryIter<K,V> implements UnmodIterator<UnEntry<K,V>> { //, Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903082500L; private final Iterator<Entry<K,V>> innerIter; EntryToUnEntryIter(Iterator<Entry<K,V>> i) { innerIter = i; } @Override public boolean hasNext() { return innerIter.hasNext(); } @Override public UnEntry<K, V> next() { class Wrapper implements UnEntry<K,V>, Serializable { // For serializable. Make sure to change whenever internal data format changes. private static final long serialVersionUID = 20160903082500L; private final Entry<K,V> entry; private Wrapper(Entry<K,V> e) { entry = e; } @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if ( !(other instanceof Entry) ) { return false; } Entry that = (Entry) other; return Objects.equals(entry.getKey(), that.getKey()) && Objects.equals(entry.getValue(), that.getValue()); } @Override public int hashCode() { return entry.hashCode(); } @Override public String toString() { return "entry(" + entry.getKey() + "," + entry.getValue() + ")"; } }; return new Wrapper(innerIter.next()); } } class EntryToUnEntrySortedIter<K,V> extends EntryToUnEntryIter<K,V> implements UnmodSortedIterator<UnEntry<K,V>> { //, Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903082500L; EntryToUnEntrySortedIter(Iterator<Entry<K,V>> i) { super(i); } } class UnmodKeyIter<K,V> implements UnmodIterator<K> { //, Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903174100L; private final Iterator<? extends Map.Entry<K,V>> iter; UnmodKeyIter(Iterator<? extends Map.Entry<K,V>> i) { iter = i; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public K next() { return iter.next().getKey(); } } class UnmodSortedKeyIter<K,V> extends UnmodKeyIter<K,V> implements UnmodSortedIterator<K> { // , Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903174100L; UnmodSortedKeyIter(Iterator<? extends Map.Entry<K,V>> i) { super(i); } } class UnmodValIter<K,V> implements UnmodIterator<V> { //, Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903174100L; private final Iterator<? extends Map.Entry<K,V>> iter; UnmodValIter(Iterator<? extends Map.Entry<K,V>> i) { iter = i; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public V next() { return iter.next().getValue(); } } class UnmodSortedValIter<K,V> extends UnmodValIter<K,V> implements UnmodSortedIterator<V> { // , Serializable { // For serializable. Make sure to change whenever internal data format changes. // private static final long serialVersionUID = 20160903174100L; UnmodSortedValIter(Iterator<? extends Map.Entry<K,V>> i) { super(i); } } /** Use {@link org.organicdesign.fp.tuple.Tuple2#of(java.util.Map.Entry)} instead. */ @Deprecated static <K,V> UnEntry<K,V> entryToUnEntry(Map.Entry<K,V> entry) { return Tuple2.of(entry); } static <K,V> UnmodIterator<UnEntry<K,V>> entryIterToUnEntryUnIter(Iterator<Entry<K,V>> innerIter) { return new EntryToUnEntryIter<>(innerIter); } static <K,V> UnmodSortedIterator<UnEntry<K,V>> entryIterToUnEntrySortedUnIter(Iterator<Entry<K,V>> innerIter) { return new EntryToUnEntrySortedIter<>(innerIter); } // This should be done with a cast, not with code. // static <K,V> UnmodSortedIterator<UnEntry<K,V>> unSortIterEntToUnSortIterUnEnt( // UnmodSortedIterator<Entry<K,V>> innerIter) { // return new UnmodSortedIterator<UnEntry<K, V>>() { // @Override public boolean hasNext() { return innerIter.hasNext(); } // @Override public UnEntry<K, V> next() { // return UnmodMap.UnEntry.entryToUnEntry(innerIter.next()); // } // }; // } // /** Not allowed - this is supposed to be unmodifiable */ @SuppressWarnings("deprecation") @Override @Deprecated default V setValue(V value) { throw new UnsupportedOperationException("Modification attempted"); } } // ========================================= Instance ========================================= // Modification Operations /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default void clear() { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("Modification attempted"); } // boolean containsKey(Object key) // boolean containsValue(Object value) /** Most maps are not designed for this - the default implementation has O(n) performance. {@inheritDoc} */ // This is the place to define this slow operation so that it can be used in // values().contains(), UnmodSortedMap.containsValue() and UnmodSortedMap.values().contains(). @SuppressWarnings("SuspiciousMethodCalls") @Override default boolean containsValue(Object value) { for (UnEntry<K,V> item : this) { if (Objects.equals(item.getValue(), value)) { return true; } } return false; } /** Returns a view of the mappings contained in this map. The set will contain UnmodMap.UnEntry items, but that return signature is illegal in Java, so you'll just have to remember. An UnmodMap is iterable, so this method is probably not nearly as useful as it once was. {@inheritDoc} */ @Override default UnmodSet<Entry<K,V>> entrySet() { class EntrySet extends UnmodSet.AbstractUnmodSet<Entry<K,V>> implements Serializable { // For serializable. Make sure to change whenever internal data format changes. private static final long serialVersionUID = 20160903104400L; private final UnmodMap<K,V> parent; private EntrySet(UnmodMap<K,V> p) { parent = p; } @SuppressWarnings("unchecked") @Override public boolean contains(Object o) { if ( !(o instanceof Entry) ) { return false; } Entry<K,V> entry = (Entry<K,V>) o; if (!parent.containsKey(entry.getKey())) { return false; } V value = parent.get(entry.getKey()); return Objects.equals(entry.getValue(), value); } @SuppressWarnings("unchecked") @Override public UnmodIterator<Entry<K,V>> iterator() { // Converting from // UnmodIterator<UnEntry<K,V>> to // UnmodIterator<Entry<K,V>> // Is a totally legal widening conversion (at runtime) because UnEntry extends // (is an) Entry. But Java's type system doesn't know that because (I think) // it's a higher kinded type. Thanks to type erasure, we can forget about all // that and cast it to a base type then suppress the unchecked warning. // // Hmm... It's possible for this to return an Entry if the wrapped collection // uses them... Not sure how much that matters. return (UnmodIterator) parent.iterator(); } @Override public int size() { return parent.size(); } @Override public String toString() { return UnmodIterable.toString("UnmodMap.entrySet", this); } } return new EntrySet(this); } // boolean equals(Object o) // @Override default boolean equals(Object other) { // // Cheapest operation first... // if (this == other) { return true; } // // if ( (other == null) || // !(other instanceof Map) || // (this.hashCode() != other.hashCode()) ) { // return false; // } // // Details... // final Map that = (Map) other; // if (this.size() != that.size()) { // return false; // } // return this.entrySet().containsAll(that.entrySet()); // } // default void forEach(BiConsumer<? super K,? super V> action) // V get(Object key) // default V getOrDefault(Object key, V defaultValue) // @Override default int hashCode() { // if (size() == 0) { return 0; } // return Arrays.hashCode(entrySet().toArray()); // }; /** {@inheritDoc} */ @Override default boolean isEmpty() { return size() == 0; } /** Returns a view of the keys contained in this map. An UnmodMap is iterable, so this method is probably not nearly as useful as it once was. {@inheritDoc} */ @Override default UnmodSet<K> keySet() { class KeySet extends UnmodSet.AbstractUnmodSet<K> implements Serializable { // For serializable. Make sure to change whenever internal data format changes. private static final long serialVersionUID = 20160903104400L; private final UnmodMap<K,V> parent; private KeySet(UnmodMap<K,V> p) { parent = p; } @SuppressWarnings("SuspiciousMethodCalls") @Override public boolean contains(Object o) { return parent.containsKey(o); } @Override public UnmodIterator<K> iterator() { return new UnEntry.UnmodKeyIter<>(parent.iterator()); } @Override public int size() { return parent.size(); } @Override public String toString() { return UnmodIterable.toString("UnmodMap.keySet", this); } } return new KeySet(this); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V put(K key, V value) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default void putAll(Map<? extends K, ? extends V> m) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V putIfAbsent(K key, V value) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V remove(Object key) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default boolean remove(Object key, Object value) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default V replace(K key, V value) { throw new UnsupportedOperationException("Modification attempted"); } /** Not allowed - this is supposed to be unmodifiable */ @Override @Deprecated default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException("Modification attempted"); } // int size() /** This method has been deprecated because it is impossible to implement equals() or hashCode() on the resulting collection, and calling this method is probably at least a missed opportunity, if not an outright error. Use an UnmodMap as an UnmodIterable&lt;UnmodMap.UnEntry&gt; instead. If you don't care about eliminating duplicate values, and want a compatible return type call: <pre><code>myMap.map((UnEntry&lt;K,V&gt; entry) -&gt; entry.getValue()) .toImSet();</code></pre> If you want to keep a count of duplicates, try something like this, but it has a different signature: <pre><code>ImMap&lt;V,Integer&gt; valueCounts = myMap.foldLeft(PersistentHashMap.empty(), (ImMap&lt;V,Integer&gt; accum, UnEntry&lt;K,V&gt; origEntry) -&gt; { V inVal = origEntry.getValue(); return accum.assoc(inVal, accum.getOrElse(inVal, 0) + 1); });</code></pre> You really shouldn't turn values() into a List, because a List has order and an unsorted Map is unordered by key, and especially unordered by value. On a SortedMap, List is the proper return type. java.util.HashMap.values() returns an instance of java.util.HashMap.Values which does *not* have equals() or hashCode() defined. This is because List.equals() and Set.equals() return not-equal when compared to a Collection. There is no good way to implement a reflexive equals with both of those because they are just too different. Ultimately, Collection just isn't specific enough to instantiate, but we do it anyway here for backward compatibility. We don't implement equals() or hashCode() either because the result could have duplicates. If the Map isn't sorted, the result could have random ordering. {@inheritDoc} */ @Deprecated @Override default UnmodCollection<V> values() { class Impl implements UnmodCollection<V>, Serializable { // For serializable. Make sure to change whenever internal data format changes. private static final long serialVersionUID = 20160903104400L; private final UnmodMap<K,V> parent; private Impl(UnmodMap<K,V> p) { parent = p; } @SuppressWarnings("SuspiciousMethodCalls") @Override public boolean contains(Object o) { return parent.containsValue(o); } @Override public UnmodIterator<V> iterator() { return new UnEntry.UnmodValIter<>(parent.iterator()); } @Override public int size() { return parent.size(); } @Override public String toString() { return UnmodIterable.toString("UnmodMap.values", this); } }; return new Impl(this); } }
Added helpful javadoc link.
src/main/java/org/organicdesign/fp/collections/UnmodMap.java
Added helpful javadoc link.
Java
apache-2.0
51760c6608d4c41ef39e8a30dfe89759f8b65679
0
apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.realm; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.apache.juli.logging.LogFactory; import com.unboundid.ldap.listener.InMemoryDirectoryServer; import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; import com.unboundid.ldap.listener.InMemoryListenerConfig; import com.unboundid.ldap.sdk.AddRequest; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPResult; import com.unboundid.ldap.sdk.ResultCode; @RunWith(Parameterized.class) public class TestJNDIRealmIntegration { private static final String USER_PATTERN = "cn={0},ou=people,dc=example,dc=com"; private static final String USER_SEARCH = "cn={0}"; private static final String USER_BASE = "ou=people,dc=example,dc=com"; private static final String ROLE_SEARCH_A = "member={0}"; private static final String ROLE_SEARCH_B = "member=cn={1},ou=people,dc=example,dc=com"; private static final String ROLE_SEARCH_C = "member=cn={2},ou=people,dc=example,dc=com"; private static final String ROLE_BASE = "ou=people,dc=example,dc=com"; private static InMemoryDirectoryServer ldapServer; @Parameterized.Parameters(name = "{index}: user[{5}], pwd[{6}]") public static Collection<Object[]> parameters() { List<Object[]> parameterSets = new ArrayList<>(); for (String userRoleAttribute : new String[] { "cn", null }) { for (String roleSearch : new String[] { ROLE_SEARCH_A, ROLE_SEARCH_B, ROLE_SEARCH_C }) { if (userRoleAttribute != null) { addUsers(USER_PATTERN, null, null, roleSearch, ROLE_BASE, userRoleAttribute, parameterSets, 1); addUsers(USER_PATTERN, null, null, roleSearch, ROLE_BASE, userRoleAttribute, parameterSets, 4); addUsers(null, USER_SEARCH, USER_BASE, roleSearch, ROLE_BASE, userRoleAttribute, parameterSets, 1); addUsers(null, USER_SEARCH, USER_BASE, roleSearch, ROLE_BASE, userRoleAttribute, parameterSets, 4); } } parameterSets.add(new Object[] { "cn={0},ou=s\\;ub,ou=people,dc=example,dc=com", null, null, ROLE_SEARCH_A, "{3},ou=people,dc=example,dc=com", "testsub", "test", new String[] { "TestGroup4" }, userRoleAttribute, Integer.valueOf(1) }); parameterSets.add(new Object[] { "cn={0},ou=s\\;ub,ou=people,dc=example,dc=com", null, null, ROLE_SEARCH_A, "{3},ou=people,dc=example,dc=com", "testsub", "test", new String[] { "TestGroup4" }, userRoleAttribute, Integer.valueOf(4) }); } return parameterSets; } private static void addUsers(String userPattern, String userSearch, String userBase, String roleSearch, String roleBase, String userRoleAttribute, List<Object[]> parameterSets, int poolSize) { parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "test", "test", new String[] {"TestGroup"}, userRoleAttribute, Integer.valueOf(poolSize) }); parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "t;", "test", new String[] {"TestGroup"}, userRoleAttribute, Integer.valueOf(poolSize) }); parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "t*", "test", new String[] {"TestGroup"}, userRoleAttribute, Integer.valueOf(poolSize) }); parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "t=", "test", new String[] {"Test<Group*2", "Test>Group*3"}, userRoleAttribute, Integer.valueOf(poolSize) }); parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "norole", "test", new String[0], userRoleAttribute, Integer.valueOf(poolSize) }); // Bug 65373 parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "<>+=\"#;,rrr", "<>+=\"#;,rrr", new String[0], userRoleAttribute, Integer.valueOf(poolSize) }); } @Parameter(0) public String realmConfigUserPattern; @Parameter(1) public String realmConfigUserSearch; @Parameter(2) public String realmConfigUserBase; @Parameter(3) public String realmConfigRoleSearch; @Parameter(4) public String realmConfigRoleBase; @Parameter(5) public String username; @Parameter(6) public String credentials; @Parameter(7) public String[] groups; @Parameter(8) public String realmConfigUserRoleAttribute; @Parameter(9) public int poolSize; @Test public void testAuthenication() throws Exception { JNDIRealm realm = new JNDIRealm(); realm.containerLog = LogFactory.getLog(TestJNDIRealmIntegration.class); realm.setConnectionURL("ldap://localhost:" + ldapServer.getListenPort()); realm.setUserPattern(realmConfigUserPattern); realm.setUserSearch(realmConfigUserSearch); realm.setUserBase(realmConfigUserBase); realm.setUserRoleAttribute(realmConfigUserRoleAttribute); realm.setRoleName("cn"); realm.setRoleBase(realmConfigRoleBase); realm.setRoleSearch(realmConfigRoleSearch); realm.setRoleNested(true); realm.setConnectionPoolSize(poolSize); // If using pooling, simply try more to see what happens for (int i = 0; i < poolSize; i++) { GenericPrincipal p = (GenericPrincipal) realm.authenticate(username, credentials); Assert.assertNotNull(p); Assert.assertEquals(username, p.name); Set<String> actualGroups = new HashSet<>(Arrays.asList(p.getRoles())); Set<String> expectedGroups = new HashSet<>(Arrays.asList(groups)); Assert.assertEquals(expectedGroups.size(), actualGroups.size()); Set<String> tmp = new HashSet<>(); tmp.addAll(expectedGroups); tmp.removeAll(actualGroups); Assert.assertEquals(0, tmp.size()); } } @BeforeClass public static void createLDAP() throws Exception { InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=example,dc=com"); InetAddress localhost = InetAddress.getByName("localhost"); InMemoryListenerConfig listenerConfig = new InMemoryListenerConfig("localListener", localhost, 0, null, null, null); config.setListenerConfigs(listenerConfig); config.addAdditionalBindCredentials("cn=admin", "password"); ldapServer = new InMemoryDirectoryServer(config); ldapServer.startListening(); try (LDAPConnection conn = ldapServer.getConnection()) { // Note: Only the DNs need attribute value escaping AddRequest addBase = new AddRequest( "dn: dc=example,dc=com", "objectClass: top", "objectClass: domain", "dc: example"); LDAPResult result = conn.processOperation(addBase); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addPeople = new AddRequest( "dn: ou=people,dc=example,dc=com", "objectClass: top", "objectClass: organizationalUnit"); result = conn.processOperation(addPeople); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTest = new AddRequest( "dn: cn=test,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: test", "sn: Test", "userPassword: test"); result = conn.processOperation(addUserTest); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTestSemicolon = new AddRequest( "dn: cn=t\\;,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: t;", "sn: Tsemicolon", "userPassword: test"); result = conn.processOperation(addUserTestSemicolon); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTestAsterisk = new AddRequest( "dn: cn=t*,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: t*", "sn: Tasterisk", "userPassword: test"); result = conn.processOperation(addUserTestAsterisk); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTestEquals = new AddRequest( "dn: cn=t\\=,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: t=", "sn: Tequals", "userPassword: test"); result = conn.processOperation(addUserTestEquals); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserNoRole = new AddRequest( "dn: cn=norole,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: norole", "sn: No Role", "userPassword: test"); result = conn.processOperation(addUserNoRole); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addGroupTest = new AddRequest( "dn: cn=TestGroup,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: groupOfNames", "cn: TestGroup", "member: cn=test,ou=people,dc=example,dc=com", "member: cn=t\\;,ou=people,dc=example,dc=com", "member: cn=t\\*,ou=people,dc=example,dc=com"); result = conn.processOperation(addGroupTest); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addGroupTest2 = new AddRequest( "dn: cn=Test\\<Group*2,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: groupOfNames", "cn: Test<Group*2", "member: cn=t\\=,ou=people,dc=example,dc=com"); result = conn.processOperation(addGroupTest2); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addGroupTest3 = new AddRequest( "dn: cn=Test\\>Group*3,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: groupOfNames", "cn: Test>Group*3", "member: cn=Test\\<Group*2,ou=people,dc=example,dc=com"); result = conn.processOperation(addGroupTest3); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addPeopleSub = new AddRequest( "dn: ou=s\\;ub,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: organizationalUnit"); result = conn.processOperation(addPeopleSub); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTestSub = new AddRequest( "dn: cn=testsub,ou=s\\;ub,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: testsub", "sn: Testsub", "userPassword: test"); result = conn.processOperation(addUserTestSub); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addGroupTest4 = new AddRequest( "dn: cn=TestGroup4,ou=s\\;ub,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: groupOfNames", "cn: TestGroup4", "member: cn=testsub,ou=s\\;ub,ou=people,dc=example,dc=com"); result = conn.processOperation(addGroupTest4); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); // Bug 65373 AddRequest addUserBug65373 = new AddRequest( "dn: cn=\\3C\\3E\\2B=\\22#\\3B\\2Crrr,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: <>+=\"#;,rrr", "sn: Bug 65373", "userPassword: <>+=\"#;,rrr"); result = conn.processOperation(addUserBug65373); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); } } @AfterClass public static void destroyLDAP() { ldapServer.shutDown(true); } }
test/org/apache/catalina/realm/TestJNDIRealmIntegration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.realm; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.apache.juli.logging.LogFactory; import com.unboundid.ldap.listener.InMemoryDirectoryServer; import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; import com.unboundid.ldap.listener.InMemoryListenerConfig; import com.unboundid.ldap.sdk.AddRequest; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.LDAPResult; import com.unboundid.ldap.sdk.ResultCode; @RunWith(Parameterized.class) public class TestJNDIRealmIntegration { private static final String USER_PATTERN = "cn={0},ou=people,dc=example,dc=com"; private static final String USER_SEARCH = "cn={0}"; private static final String USER_BASE = "ou=people,dc=example,dc=com"; private static final String ROLE_SEARCH_A = "member={0}"; private static final String ROLE_SEARCH_B = "member=cn={1},ou=people,dc=example,dc=com"; private static final String ROLE_SEARCH_C = "member=cn={2},ou=people,dc=example,dc=com"; private static final String ROLE_BASE = "ou=people,dc=example,dc=com"; private static InMemoryDirectoryServer ldapServer; @Parameterized.Parameters(name = "{index}: user[{5}], pwd[{6}]") public static Collection<Object[]> parameters() { List<Object[]> parameterSets = new ArrayList<>(); for (String userRoleAttribute : new String[] { "cn", null }) { for (String roleSearch : new String[] { ROLE_SEARCH_A, ROLE_SEARCH_B, ROLE_SEARCH_C }) { if (userRoleAttribute != null) { addUsers(USER_PATTERN, null, null, roleSearch, ROLE_BASE, userRoleAttribute, parameterSets); addUsers(null, USER_SEARCH, USER_BASE, roleSearch, ROLE_BASE, userRoleAttribute, parameterSets); } } parameterSets.add(new Object[] { "cn={0},ou=s\\;ub,ou=people,dc=example,dc=com", null, null, ROLE_SEARCH_A, "{3},ou=people,dc=example,dc=com", "testsub", "test", new String[] { "TestGroup4" }, userRoleAttribute }); } return parameterSets; } private static void addUsers(String userPattern, String userSearch, String userBase, String roleSearch, String roleBase, String userRoleAttribute, List<Object[]> parameterSets) { parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "test", "test", new String[] {"TestGroup"}, userRoleAttribute }); parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "t;", "test", new String[] {"TestGroup"}, userRoleAttribute }); parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "t*", "test", new String[] {"TestGroup"}, userRoleAttribute }); parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "t=", "test", new String[] {"Test<Group*2", "Test>Group*3"}, userRoleAttribute }); parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "norole", "test", new String[0], userRoleAttribute }); // Bug 65373 parameterSets.add(new Object[] { userPattern, userSearch, userBase, roleSearch, roleBase, "<>+=\"#;,rrr", "<>+=\"#;,rrr", new String[0], userRoleAttribute }); } @Parameter(0) public String realmConfigUserPattern; @Parameter(1) public String realmConfigUserSearch; @Parameter(2) public String realmConfigUserBase; @Parameter(3) public String realmConfigRoleSearch; @Parameter(4) public String realmConfigRoleBase; @Parameter(5) public String username; @Parameter(6) public String credentials; @Parameter(7) public String[] groups; @Parameter(8) public String realmConfigUserRoleAttribute; @Test public void testAuthenication() throws Exception { JNDIRealm realm = new JNDIRealm(); realm.containerLog = LogFactory.getLog(TestJNDIRealmIntegration.class); realm.setConnectionURL("ldap://localhost:" + ldapServer.getListenPort()); realm.setUserPattern(realmConfigUserPattern); realm.setUserSearch(realmConfigUserSearch); realm.setUserBase(realmConfigUserBase); realm.setUserRoleAttribute(realmConfigUserRoleAttribute); realm.setRoleName("cn"); realm.setRoleBase(realmConfigRoleBase); realm.setRoleSearch(realmConfigRoleSearch); realm.setRoleNested(true); GenericPrincipal p = (GenericPrincipal) realm.authenticate(username, credentials); Assert.assertNotNull(p); Assert.assertEquals(username, p.name); Set<String> actualGroups = new HashSet<>(Arrays.asList(p.getRoles())); Set<String> expectedGroups = new HashSet<>(Arrays.asList(groups)); Assert.assertEquals(expectedGroups.size(), actualGroups.size()); Set<String> tmp = new HashSet<>(); tmp.addAll(expectedGroups); tmp.removeAll(actualGroups); Assert.assertEquals(0, tmp.size()); } @BeforeClass public static void createLDAP() throws Exception { InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=example,dc=com"); InetAddress localhost = InetAddress.getByName("localhost"); InMemoryListenerConfig listenerConfig = new InMemoryListenerConfig("localListener", localhost, 0, null, null, null); config.setListenerConfigs(listenerConfig); config.addAdditionalBindCredentials("cn=admin", "password"); ldapServer = new InMemoryDirectoryServer(config); ldapServer.startListening(); try (LDAPConnection conn = ldapServer.getConnection()) { // Note: Only the DNs need attribute value escaping AddRequest addBase = new AddRequest( "dn: dc=example,dc=com", "objectClass: top", "objectClass: domain", "dc: example"); LDAPResult result = conn.processOperation(addBase); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addPeople = new AddRequest( "dn: ou=people,dc=example,dc=com", "objectClass: top", "objectClass: organizationalUnit"); result = conn.processOperation(addPeople); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTest = new AddRequest( "dn: cn=test,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: test", "sn: Test", "userPassword: test"); result = conn.processOperation(addUserTest); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTestSemicolon = new AddRequest( "dn: cn=t\\;,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: t;", "sn: Tsemicolon", "userPassword: test"); result = conn.processOperation(addUserTestSemicolon); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTestAsterisk = new AddRequest( "dn: cn=t*,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: t*", "sn: Tasterisk", "userPassword: test"); result = conn.processOperation(addUserTestAsterisk); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTestEquals = new AddRequest( "dn: cn=t\\=,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: t=", "sn: Tequals", "userPassword: test"); result = conn.processOperation(addUserTestEquals); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserNoRole = new AddRequest( "dn: cn=norole,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: norole", "sn: No Role", "userPassword: test"); result = conn.processOperation(addUserNoRole); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addGroupTest = new AddRequest( "dn: cn=TestGroup,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: groupOfNames", "cn: TestGroup", "member: cn=test,ou=people,dc=example,dc=com", "member: cn=t\\;,ou=people,dc=example,dc=com", "member: cn=t\\*,ou=people,dc=example,dc=com"); result = conn.processOperation(addGroupTest); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addGroupTest2 = new AddRequest( "dn: cn=Test\\<Group*2,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: groupOfNames", "cn: Test<Group*2", "member: cn=t\\=,ou=people,dc=example,dc=com"); result = conn.processOperation(addGroupTest2); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addGroupTest3 = new AddRequest( "dn: cn=Test\\>Group*3,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: groupOfNames", "cn: Test>Group*3", "member: cn=Test\\<Group*2,ou=people,dc=example,dc=com"); result = conn.processOperation(addGroupTest3); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addPeopleSub = new AddRequest( "dn: ou=s\\;ub,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: organizationalUnit"); result = conn.processOperation(addPeopleSub); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addUserTestSub = new AddRequest( "dn: cn=testsub,ou=s\\;ub,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: testsub", "sn: Testsub", "userPassword: test"); result = conn.processOperation(addUserTestSub); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); AddRequest addGroupTest4 = new AddRequest( "dn: cn=TestGroup4,ou=s\\;ub,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: groupOfNames", "cn: TestGroup4", "member: cn=testsub,ou=s\\;ub,ou=people,dc=example,dc=com"); result = conn.processOperation(addGroupTest4); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); // Bug 65373 AddRequest addUserBug65373 = new AddRequest( "dn: cn=\\3C\\3E\\2B=\\22#\\3B\\2Crrr,ou=people,dc=example,dc=com", "objectClass: top", "objectClass: person", "objectClass: organizationalPerson", "cn: <>+=\"#;,rrr", "sn: Bug 65373", "userPassword: <>+=\"#;,rrr"); result = conn.processOperation(addUserBug65373); Assert.assertEquals(ResultCode.SUCCESS, result.getResultCode()); } } @AfterClass public static void destroyLDAP() { ldapServer.shutDown(true); } }
Add additional tests with pooling
test/org/apache/catalina/realm/TestJNDIRealmIntegration.java
Add additional tests with pooling
Java
apache-2.0
8376be63e56281fffbb29fb9ed7275c4e1139cd2
0
babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble
// JSPySequenceListWrapper.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.lang.python; import java.util.*; import org.python.core.*; import ed.js.*; import ed.js.func.*; import ed.js.engine.*; import static ed.lang.python.Python.*; /** * This class mainly exists to translate JS Array methods/attributes into * Python. * * Like other wrapper classes, it will probably eventually have to keep a copy * of both the Python and JS versions of any contained objects, so that when * they get set in JS and then retrieved in JS, the same thing comes out, but * Python also gets a version. */ public class JSPySequenceListWrapper extends JSPyObjectWrapper implements java.util.List { static final boolean DEBUG = Boolean.getBoolean( "DEBUG.JSPYSEQUENCELISTWRAPPER" ); /** @unexpose */ private final static JSFunction _cons = new JSPySequenceListWrapperCons(); public static class JSPySequenceListWrapperCons extends JSFunctionCalls1 { public JSObject newOne(){ throw new RuntimeException("you shouldn't be able to instantiate a sequence wrapper from JS"); } public Object call( Scope scope , Object a , Object[] extra ){ throw new RuntimeException("you shouldn't be able to instantiate a sequence wrapper from JS"); } protected void init(){ _prototype.set( "some", new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); JSFunction f = (JSFunction)fo; for ( Object o : a._pSeq ){ Object j = toJS( o ); if ( JS_evalToBool( f.call( s , j ) ) ) return true; } return false; } } ); _prototype.set( "every", new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); JSFunction f = (JSFunction)fo; for ( Object o : a._pSeq ){ Object j = toJS( o ); if ( ! JS_evalToBool( f.call( s , j ) ) ) return false; } return true; } } ); _prototype.set( "push", new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); PyObject p = toPython( fo ); a._pSeq.invoke( "append" , p ); return a._pSeq.__len__(); } } ); _prototype.set( "filter", new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ if( ! ( fo instanceof JSFunction ) ) throw new RuntimeException( "first argument to filter must be a function" ); JSFunction f = (JSFunction)fo; JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); JSArray arr = new JSArray(); for ( Object o : a._pSeq ){ Object res = f.call( s , toJS( o ) ); if( JS_evalToBool( res ) ) arr.add( toJS( o ) ); } return arr; } } ); _prototype.set( "map" , new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ if( ! ( fo instanceof JSFunction ) ) throw new RuntimeException( "first argument to map must be a function" ); JSFunction f = (JSFunction)fo; JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); JSArray arr = new JSArray(); for ( Object o : a._pSeq ){ Object res = f.call( s , toJS( o ) ); arr.add( res ); } return arr; } } ); } } public JSPySequenceListWrapper( PySequenceList o ){ super( o ); _pSeq = o; setConstructor( _cons ); } public Object get( Object n ){ if( n instanceof String || n instanceof JSString ){ String s = n.toString(); if( s.equals( "length" ) ) return _p.__len__(); } return super.get( n ); } public Object removeField( Object n ){ _p.__delitem__( toPython( n ) ); return null; // FIXME: we removed both of them, who cares } public Collection<String> keySet( boolean includePrototype ){ List<String> keys = new ArrayList<String>(); int n = _pSeq.__len__(); for( int i = 0 ; i < n ; ++i ){ keys.add( Integer.toString( i ) ); } return keys; } public String toString(){ return _p.toString(); } private PySequenceList _pSeq; // just to fool the static typing // java.util.List API public boolean contains( Object o ){ return _pSeq.contains( toPython( o ) ); } public boolean containsAll( Collection c ){ // FIXME return true; } public boolean equals( Object o ){ // FIXME? return _pSeq.equals( o ); } /* public int hashCode(){ return _pSeq.hashCode(); }*/ public Iterator iterator(){ // FIXME return null; } public boolean remove( Object o ){ return _pSeq.remove( toPython( o ) ); } public boolean removeAll( Collection c ){ // FIXME return false; } public Object set( int index , Object element ){ // FIXME return null; } public int size(){ return _pSeq.size(); } public Object[] toArray(){ // FIXME return null; } public Object[] toArray( Object[] a ){ return null; } public void add( int index, Object element ){ _pSeq.add( index, toPython( element ) ); } public boolean add( Object o ){ return _pSeq.add( toPython( o ) ); } public boolean addAll( Collection c ){ // FIXME return false; } public boolean addAll( int index , Collection c ){ // FIXME return false; } public void clear(){ // FIXME } public Object get( int index ){ return toJS( _pSeq.get( index ) ); } public int indexOf( Object o ){ return _pSeq.indexOf( toPython( o ) ); } public boolean isEmpty(){ return _pSeq.isEmpty(); } public int lastIndexOf( Object o ){ return _pSeq.lastIndexOf( toPython( o ) ); } public ListIterator listIterator(){ // FIXME return null; } public ListIterator listIterator( int index ){ // FIXME return null; } public Object remove( int index ){ return toJS( _pSeq.remove( index ) ); } public boolean retainAll( Collection c ){ // FIXME return true; } public List subList( int fromIndex , int toIndex ){ // FIXME return null; } }
src/main/ed/lang/python/JSPySequenceListWrapper.java
// JSPySequenceListWrapper.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.lang.python; import java.util.*; import org.python.core.*; import ed.js.*; import ed.js.func.*; import ed.js.engine.*; import static ed.lang.python.Python.*; /** * This class mainly exists to translate JS Array methods/attributes into * Python. * * Like other wrapper classes, it will probably eventually have to keep a copy * of both the Python and JS versions of any contained objects, so that when * they get set in JS and then retrieved in JS, the same thing comes out, but * Python also gets a version. */ public class JSPySequenceListWrapper extends JSPyObjectWrapper implements java.util.List { static final boolean DEBUG = Boolean.getBoolean( "DEBUG.JSPYSEQUENCELISTWRAPPER" ); /** @unexpose */ private final static JSFunction _cons = new JSPySequenceListWrapperCons(); public static class JSPySequenceListWrapperCons extends JSFunctionCalls1 { public JSObject newOne(){ throw new RuntimeException("you shouldn't be able to instantiate a sequence wrapper from JS"); } public Object call( Scope scope , Object a , Object[] extra ){ throw new RuntimeException("you shouldn't be able to instantiate a sequence wrapper from JS"); } protected void init(){ _prototype.set( "some", new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); JSFunction f = (JSFunction)fo; for ( Object o : a._pSeq ){ Object j = toJS( o ); if ( JS_evalToBool( f.call( s , j ) ) ) return true; } return false; } } ); _prototype.set( "every", new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); JSFunction f = (JSFunction)fo; for ( Object o : a._pSeq ){ Object j = toJS( o ); if ( ! JS_evalToBool( f.call( s , j ) ) ) return false; } return true; } } ); _prototype.set( "push", new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); PyObject p = toPython( fo ); a._pSeq.invoke( "append" , p ); return a._pSeq.__len__(); } } ); _prototype.set( "filter", new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ if( ! ( fo instanceof JSFunction ) ) throw new RuntimeException( "first argument to filter must be a function" ); JSFunction f = (JSFunction)fo; JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); JSArray arr = new JSArray(); for ( Object o : a._pSeq ){ Object res = f.call( s , toJS( o ) ); if( JS_evalToBool( res ) ) arr.add( toJS( o ) ); } return arr; } } ); _prototype.set( "map" , new JSFunctionCalls1() { public Object call( Scope s , Object fo , Object foo[] ){ if( ! ( fo instanceof JSFunction ) ) throw new RuntimeException( "first argument to map must be a function" ); JSFunction f = (JSFunction)fo; JSPySequenceListWrapper a = (JSPySequenceListWrapper)(s.getThis()); JSArray arr = new JSArray(); for ( Object o : a._pSeq ){ Object res = f.call( s , toJS( o ) ); arr.add( res ); } return arr; } } ); } } public JSPySequenceListWrapper( PySequenceList o ){ super( o ); _pSeq = o; setConstructor( _cons ); } public Object get( Object n ){ if( n instanceof String || n instanceof JSString ){ String s = n.toString(); if( s.equals( "length" ) ) return _p.__len__(); } return super.get( n ); } public Object removeField( Object n ){ _p.__delitem__( toPython( n ) ); return null; // FIXME: we removed both of them, who cares } public Collection<String> keySet( boolean includePrototype ){ List<String> keys = new ArrayList<String>(); int n = _pSeq.__len__(); for( int i = 0 ; i < n ; ++i ){ keys.add( Integer.toString( i ) ); } return keys; } public String toString(){ return _p.toString(); } private PySequenceList _pSeq; // just to fool the static typing // java.util.List API public boolean contains( Object o ){ return _pSeq.contains( toPy( o ) ); } public boolean containsAll( Collection c ){ // FIXME return true; } public boolean equals( Object o ){ // FIXME? return _pSeq.equals( o ); } public boolean int hashCode(){ return _pSeq.hashCode(); } public Iterator iterator(){ // FIXME return null; } public boolean remove( Object o ){ return _pSeq.remove( toPy( o ) ); } public boolean removeAll( Collection c ){ // FIXME return false; } public int size(){ return _pSeq.size(); } public Object[] toArray(){ // FIXME return null; } public Object[] toArray( Object[] a ){ return null; } public void add( int index, Object element ){ return _pSeq.add( index, toPy( element ) ); } public boolean add( Object o ){ return _pSeq.add( toPy( o ) ); } public Object get( int index ){ return toJS( _pSeq.get( index ) ); } public int indexOf( Object o ){ return _pSeq.indexOf( toPy( o ) ); } public boolean isEmpty(){ return _pSeq.isEmpty(); } public int lastIndexOf( Object o ){ return _pSeq.lastIndexOf( toPy( o ) ); } public ListIterator listIterator(){ // FIXME return null; } public ListIterator listIterator( int index ){ // FIXME return null; } public Object remove( int index ){ return toJS( _pSeq.remove( index ) ); } public List subList( int fromIndex , int toIndex ){ // FIXME return null; } }
Fix the build.
src/main/ed/lang/python/JSPySequenceListWrapper.java
Fix the build.
Java
apache-2.0
7be0bd14435be1696851501013d687d61dbb8e34
0
MaxRau/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,oriontribunal/CoffeeMud
package com.planet_ink.coffee_mud.Abilities.Misc; import com.planet_ink.coffee_mud.Abilities.StdAbility; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2001-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class ItemRejuv extends StdAbility implements ItemTicker { @Override public String ID() { return "ItemRejuv"; } private final static String localizedName = CMLib.lang().L("ItemRejuv"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(ItemRejuv)"); @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode(){return CAN_ITEMS;} @Override protected int canTargetCode(){return 0;} @Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;} protected Room myProperLocation=null; protected Vector<Item> contents=new Vector<Item>(); protected Vector<Item> ccontents=new Vector<Item>(); public synchronized void loadContent(ItemTicker ticker, Item item, Room room) { if(ticker instanceof ItemRejuv) { final ItemRejuv ability=(ItemRejuv)ticker; ability.contents.add(item); final Item newItem=(Item)item.copyOf(); newItem.stopTicking(); newItem.setContainer(item.container()); ability.ccontents.add(newItem); for(int r=0;r<room.numItems();r++) { final Item content=room.getItem(r); if((content!=null)&&(content.container()==item)) loadContent(ability,content,room); } } } @Override public Room properLocation(){return myProperLocation;} @Override public void setProperLocation(Room room) { myProperLocation=room; } @Override public void loadMeUp(Item item, Room room) { unloadIfNecessary(item); contents=new Vector<Item>(); ccontents=new Vector<Item>(); final ItemRejuv ability=new ItemRejuv(); ability.myProperLocation=room; if(item.fetchEffect(ability.ID())==null) item.addEffect(ability); ability.setSavable(false); loadContent(ability,item,room); contents.trimToSize(); ccontents.trimToSize(); CMLib.threads().startTickDown(ability,Tickable.TICKID_ROOM_ITEM_REJUV,item.phyStats().rejuv()); } @Override public void unloadIfNecessary(Item item) { final ItemRejuv a=(ItemRejuv)item.fetchEffect(new ItemRejuv().ID()); if(a!=null) a.unInvoke(); } @Override public String accountForYourself() { return ""; } @Override public boolean isVerifiedContents(Item item) { if(item==null) return false; return contents.contains(item); } public synchronized void verifyFixContents() { final Room R=myProperLocation; for(int i=0;i<contents.size();i++) { final Item thisItem=contents.elementAt(i); if(thisItem!=null) { final Container thisContainer=ccontents.elementAt(i).container(); if((!R.isContent(thisItem)) &&((!CMLib.flags().isMobile(thisItem)) || (!CMLib.flags().isInTheGame(thisItem,true)))) { final Item newThisItem=(Item)ccontents.elementAt(i).copyOf(); contents.setElementAt(newThisItem,i); for(int c=0;c<ccontents.size();c++) { final Item thatItem=ccontents.elementAt(c); if((thatItem.container()==thisItem)&&(newThisItem instanceof Container)) thatItem.setContainer((Container)newThisItem); } if(newThisItem instanceof Container) { final Container C=(Container)newThisItem; final boolean locked=C.defaultsLocked(); final boolean open=(!locked) && (!C.defaultsClosed()); C.setDoorsNLocks(C.hasADoor(),open,C.defaultsClosed(),C.hasALock(),locked,C.defaultsLocked()); } newThisItem.setExpirationDate(0); R.addItem(newThisItem); newThisItem.setContainer(thisContainer); } else thisItem.setContainer(thisContainer); } } } @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; final Item item=(Item)affected; final Room R=myProperLocation; if((item==null)||(R==null)) return false; if(tickID==Tickable.TICKID_ROOM_ITEM_REJUV) { if((CMLib.flags().canNotBeCamped(item)||CMLib.flags().canNotBeCamped(R)) && (R.numPCInhabitants() > 0) && (!CMLib.tracking().isAnAdminHere(R,false))) { CMLib.threads().setTickPending(ticking,Tickable.TICKID_ROOM_ITEM_REJUV); return true; // it will just come back next time } verifyFixContents(); if((!R.isContent(item)) &&((!CMLib.flags().isMobile(item)) || (!CMLib.flags().isInTheGame(item,true)))) { unloadIfNecessary(item); loadMeUp(contents.elementAt(0),R); return false; } if(item instanceof Container) { final Container C=(Container)item; final boolean locked=C.defaultsLocked(); final boolean open=(!locked) && (!C.defaultsClosed()); C.setDoorsNLocks(C.hasADoor(),open,C.defaultsClosed(),C.hasALock(),locked,C.defaultsClosed()); } } return true; } }
com/planet_ink/coffee_mud/Abilities/Misc/ItemRejuv.java
package com.planet_ink.coffee_mud.Abilities.Misc; import com.planet_ink.coffee_mud.Abilities.StdAbility; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2001-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @SuppressWarnings({"unchecked","rawtypes"}) public class ItemRejuv extends StdAbility implements ItemTicker { @Override public String ID() { return "ItemRejuv"; } private final static String localizedName = CMLib.lang().L("ItemRejuv"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(ItemRejuv)"); @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode(){return CAN_ITEMS;} @Override protected int canTargetCode(){return 0;} @Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;} protected Room myProperLocation=null; protected Vector contents=new Vector(); protected Vector ccontents=new Vector(); public synchronized void loadContent(ItemTicker ticker, Item item, Room room) { if(ticker instanceof ItemRejuv) { final ItemRejuv ability=(ItemRejuv)ticker; ability.contents.addElement(item); final Item newItem=(Item)item.copyOf(); newItem.stopTicking(); newItem.setContainer(item.container()); ability.ccontents.addElement(newItem); for(int r=0;r<room.numItems();r++) { final Item content=room.getItem(r); if((content!=null)&&(content.container()==item)) loadContent(ability,content,room); } } } @Override public Room properLocation(){return myProperLocation;} @Override public void setProperLocation(Room room) { myProperLocation=room; } @Override public void loadMeUp(Item item, Room room) { unloadIfNecessary(item); contents=new Vector(); ccontents=new Vector(); final ItemRejuv ability=new ItemRejuv(); ability.myProperLocation=room; if(item.fetchEffect(ability.ID())==null) item.addEffect(ability); ability.setSavable(false); loadContent(ability,item,room); contents.trimToSize(); ccontents.trimToSize(); CMLib.threads().startTickDown(ability,Tickable.TICKID_ROOM_ITEM_REJUV,item.phyStats().rejuv()); } @Override public void unloadIfNecessary(Item item) { final ItemRejuv a=(ItemRejuv)item.fetchEffect(new ItemRejuv().ID()); if(a!=null) a.unInvoke(); } @Override public String accountForYourself() { return ""; } @Override public boolean isVerifiedContents(Item item) { if(item==null) return false; return contents.contains(item); } public synchronized void verifyFixContents() { final Room R=myProperLocation; for(int i=0;i<contents.size();i++) { final Item thisItem=(Item)contents.elementAt(i); if(thisItem!=null) { final Container thisContainer=((Item)ccontents.elementAt(i)).container(); if((!R.isContent(thisItem)) &&((!CMLib.flags().isMobile(thisItem)) || (!CMLib.flags().isInTheGame(thisItem,true)))) { final Item newThisItem=(Item)((Item)ccontents.elementAt(i)).copyOf(); contents.setElementAt(newThisItem,i); for(int c=0;c<ccontents.size();c++) { final Item thatItem=(Item)ccontents.elementAt(c); if((thatItem.container()==thisItem)&&(newThisItem instanceof Container)) thatItem.setContainer((Container)newThisItem); } if(newThisItem instanceof Container) { final Container C=(Container)newThisItem; final boolean locked=C.defaultsLocked(); final boolean open=(!locked) && (!C.defaultsClosed()); C.setDoorsNLocks(C.hasADoor(),open,C.defaultsClosed(),C.hasALock(),locked,C.defaultsLocked()); } newThisItem.setExpirationDate(0); R.addItem(newThisItem); newThisItem.setContainer(thisContainer); } else thisItem.setContainer(thisContainer); } } } @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; final Item item=(Item)affected; final Room R=myProperLocation; if((item==null)||(R==null)) return false; if(tickID==Tickable.TICKID_ROOM_ITEM_REJUV) { if((CMLib.flags().canNotBeCamped(item)||CMLib.flags().canNotBeCamped(R)) && (R.numPCInhabitants() > 0) && (!CMLib.tracking().isAnAdminHere(R,false))) { CMLib.threads().setTickPending(ticking,Tickable.TICKID_ROOM_ITEM_REJUV); return true; // it will just come back next time } verifyFixContents(); if((!R.isContent(item)) &&((!CMLib.flags().isMobile(item)) || (!CMLib.flags().isInTheGame(item,true)))) { unloadIfNecessary(item); loadMeUp((Item)contents.elementAt(0),R); return false; } if(item instanceof Container) { final Container C=(Container)item; final boolean locked=C.defaultsLocked(); final boolean open=(!locked) && (!C.defaultsClosed()); C.setDoorsNLocks(C.hasADoor(),open,C.defaultsClosed(),C.hasALock(),locked,C.defaultsClosed()); } } return true; } }
git-svn-id: svn://192.168.1.10/public/CoffeeMud@12371 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Abilities/Misc/ItemRejuv.java
Java
apache-2.0
609d2ba1cca44cf7de20189fc3442e6c39f78adb
0
hubrick/vertx-kafka-service,hubrick/vertx-kafka-service
/** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hubrick.vertx.kafka.consumer; import com.google.common.math.IntMath; import com.google.common.util.concurrent.RateLimiter; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.hubrick.vertx.kafka.consumer.config.KafkaConsumerConfiguration; import io.vertx.core.Future; import io.vertx.core.Vertx; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.StringDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Iterator; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Phaser; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; /** * @author Marcus Thiesen * @since 1.0.0 */ class KafkaConsumerManager { private final static Logger LOG = LoggerFactory.getLogger(KafkaConsumerManager.class); private final static ThreadFactory FACTORY = new ThreadFactoryBuilder() .setNameFormat("kafka-consumer-thread-%d") .setUncaughtExceptionHandler((thread, throwable) -> LOG.error("Uncaught exception in thread {}", thread.getName(), throwable)) .setDaemon(true) .build(); private final Vertx vertx; private final KafkaConsumer<String,String> consumer; private final KafkaConsumerConfiguration configuration; private final KafkaConsumerHandler handler; private final Set<Long> unacknowledgedOffsets = Collections.newSetFromMap(new ConcurrentHashMap<Long, Boolean>()); private final ExecutorService messageProcessorExececutor = Executors.newSingleThreadExecutor(FACTORY); private final Phaser phaser = new Phaser() { @Override protected boolean onAdvance(int phase, int registeredParties) { LOG.debug("{}: Advance: Phase {}, registeredParties {}", configuration.getKafkaTopic(), phase, registeredParties); return false; } }; private final AtomicLong lastCommittedOffset = new AtomicLong(); private final AtomicLong currentPartition = new AtomicLong(-1); private final AtomicLong lastCommitTime = new AtomicLong(System.currentTimeMillis()); private final Optional<RateLimiter> rateLimiter; public KafkaConsumerManager(Vertx vertx, KafkaConsumer<String,String> consumer, KafkaConsumerConfiguration configuration, KafkaConsumerHandler handler) { this.vertx = vertx; this.consumer = consumer; this.configuration = configuration; this.handler = handler; this.rateLimiter = configuration.getMessagesPerSecond() > 0.0D ? Optional.of(RateLimiter.create(configuration.getMessagesPerSecond())) : Optional.empty(); } public static KafkaConsumerManager create(final Vertx vertx, final KafkaConsumerConfiguration configuration, final KafkaConsumerHandler handler) { final Properties properties = createProperties(configuration); final KafkaConsumer consumer = new KafkaConsumer(properties, new StringDeserializer(), new StringDeserializer()); return new KafkaConsumerManager(vertx, consumer, configuration, handler); } protected static Properties createProperties(KafkaConsumerConfiguration configuration) { final Properties properties = new Properties(); properties.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, configuration.getClientId()); properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, configuration.getBootstrapServers()); properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, configuration.getGroupId()); properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Boolean.FALSE.toString()); properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, configuration.getOffsetReset()); return properties; } public void stop() { messageProcessorExececutor.shutdownNow(); consumer.unsubscribe(); consumer.close(); } public void start() { final String kafkaTopic = configuration.getKafkaTopic(); consumer.subscribe(Collections.singletonList(kafkaTopic)); messageProcessorExececutor.submit(() -> read()); } private void read() { while (!consumer.subscription().isEmpty()) { final ConsumerRecords<String, String> records = consumer.poll(60000); final Iterator<ConsumerRecord<String, String>> iterator = records.iterator(); while (iterator.hasNext()) { rateLimiter.ifPresent(limiter -> limiter.acquire()); final int phase = phaser.register(); final ConsumerRecord<String, String> msg = iterator.next(); final long offset = msg.offset(); final long partition = msg.partition(); unacknowledgedOffsets.add(offset); lastCommittedOffset.compareAndSet(0, offset); currentPartition.compareAndSet(-1, partition); handle(msg.value(), offset, configuration.getMaxRetries(), configuration.getInitialRetryDelaySeconds()); if (unacknowledgedOffsets.size() >= configuration.getMaxUnacknowledged() || partititionChanged(partition) || tooManyUncommittedOffsets(offset) || commitTimeoutReached()) { LOG.info("{}: Got {} unacknowledged messages, waiting for ACKs in order to commit", configuration.getKafkaTopic(), unacknowledgedOffsets.size()); if (!waitForAcks(phase)) { return; } commitOffsetsIfAllAcknowledged(offset); LOG.info("{}: Continuing message processing", configuration.getKafkaTopic()); } } } } private void handle(String msg, Long offset, int tries, int delaySeconds) { final Future<Void> futureResult = Future.future(); futureResult.setHandler(result -> { if(result.succeeded()) { unacknowledgedOffsets.remove(offset); phaser.arriveAndDeregister(); } else { final int nextDelaySeconds = computeNextDelay(delaySeconds); if (tries > 0) { LOG.error("{}: Exception occurred during kafka message processing, will retry in {} seconds: {}", configuration.getKafkaTopic(), delaySeconds, msg, result.cause()); final int nextTry = tries - 1; vertx.setTimer(delaySeconds * 1000, event -> handle(msg, offset, nextTry, nextDelaySeconds)); } else { LOG.error("{}: Exception occurred during kafka message processing. Max number of retries reached. Skipping message: {}", configuration.getKafkaTopic(), msg, result.cause()); unacknowledgedOffsets.remove(offset); phaser.arriveAndDeregister(); } } }); handler.handle(msg, futureResult); } private boolean commitTimeoutReached() { return System.currentTimeMillis() - lastCommitTime.get() >= configuration.getCommitTimeoutMs(); } private boolean partititionChanged(long partition) { if (currentPartition.get() != partition) { LOG.info("{}: Partition changed from {} to {}", configuration.getKafkaTopic(), currentPartition.get(), partition); currentPartition.set(partition); return true; } return false; } private int computeNextDelay(int delaySeconds) { try { return Math.min(IntMath.checkedMultiply(delaySeconds, 2), configuration.getMaxRetryDelaySeconds()); } catch (ArithmeticException e) { return configuration.getMaxRetryDelaySeconds(); } } private boolean waitForAcks(int phase) { try { phaser.awaitAdvanceInterruptibly(phase, configuration.getAckTimeoutSeconds(), TimeUnit.SECONDS); return true; } catch (InterruptedException e) { LOG.error("{}: Interrupted while waiting for ACKs", configuration.getKafkaTopic(), e); return false; } catch (TimeoutException e) { LOG.error("{}: Waited for {} ACKs for longer than {} seconds, not making any progress ({}/{})", new Object[]{ configuration.getKafkaTopic(), Integer.valueOf(unacknowledgedOffsets.size()), Long.valueOf(configuration.getAckTimeoutSeconds()), Integer.valueOf(phase), Integer.valueOf(phaser.getPhase())}); return waitForAcks(phase); } } private boolean tooManyUncommittedOffsets(final long offset) { return lastCommittedOffset.get() + configuration.getMaxUncommitedOffsets() <= offset; } private void commitOffsetsIfAllAcknowledged(final long currentOffset) { if (unacknowledgedOffsets.isEmpty()) { LOG.info("{}: Committing at offset {}", configuration.getKafkaTopic(), currentOffset); consumer.commitSync(); lastCommittedOffset.set(currentOffset); lastCommitTime.set(System.currentTimeMillis()); } else { LOG.warn("{}: Can not commit because {} ACKs missing", configuration.getKafkaTopic(), unacknowledgedOffsets.size()); } } }
src/main/java/com/hubrick/vertx/kafka/consumer/KafkaConsumerManager.java
/** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hubrick.vertx.kafka.consumer; import com.google.common.math.IntMath; import com.google.common.util.concurrent.RateLimiter; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.hubrick.vertx.kafka.consumer.config.KafkaConsumerConfiguration; import io.vertx.core.Future; import io.vertx.core.Vertx; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.StringDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Iterator; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Phaser; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; /** * @author Marcus Thiesen * @since 1.0.0 */ class KafkaConsumerManager { private final static Logger LOG = LoggerFactory.getLogger(KafkaConsumerManager.class); private final static ThreadFactory FACTORY = new ThreadFactoryBuilder() .setNameFormat("kafka-consumer-thread-%d") .setUncaughtExceptionHandler((thread, throwable) -> LOG.error("Uncaught exception in thread {}", thread.getName(), throwable)) .setDaemon(true) .build(); private final Vertx vertx; private final KafkaConsumer<String,String> consumer; private final KafkaConsumerConfiguration configuration; private final KafkaConsumerHandler handler; private final Set<Long> unacknowledgedOffsets = Collections.newSetFromMap(new ConcurrentHashMap<Long, Boolean>()); private final ExecutorService messageProcessorExececutor = Executors.newSingleThreadExecutor(FACTORY); private final Phaser phaser = new Phaser() { @Override protected boolean onAdvance(int phase, int registeredParties) { LOG.debug("{} Advance: Phase {}, registeredParties {}", configuration.getKafkaTopic(), phase, registeredParties); return false; } }; private final AtomicLong lastCommittedOffset = new AtomicLong(); private final AtomicLong currentPartition = new AtomicLong(-1); private final AtomicLong lastCommitTime = new AtomicLong(System.currentTimeMillis()); private final Optional<RateLimiter> rateLimiter; public KafkaConsumerManager(Vertx vertx, KafkaConsumer<String,String> consumer, KafkaConsumerConfiguration configuration, KafkaConsumerHandler handler) { this.vertx = vertx; this.consumer = consumer; this.configuration = configuration; this.handler = handler; this.rateLimiter = configuration.getMessagesPerSecond() > 0.0D ? Optional.of(RateLimiter.create(configuration.getMessagesPerSecond())) : Optional.empty(); } public static KafkaConsumerManager create(final Vertx vertx, final KafkaConsumerConfiguration configuration, final KafkaConsumerHandler handler) { final Properties properties = createProperties(configuration); final KafkaConsumer consumer = new KafkaConsumer(properties, new StringDeserializer(), new StringDeserializer()); return new KafkaConsumerManager(vertx, consumer, configuration, handler); } protected static Properties createProperties(KafkaConsumerConfiguration configuration) { final Properties properties = new Properties(); properties.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, configuration.getClientId()); properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, configuration.getBootstrapServers()); properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, configuration.getGroupId()); properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Boolean.FALSE.toString()); properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, configuration.getOffsetReset()); return properties; } public void stop() { messageProcessorExececutor.shutdownNow(); consumer.unsubscribe(); consumer.close(); } public void start() { final String kafkaTopic = configuration.getKafkaTopic(); consumer.subscribe(Collections.singletonList(kafkaTopic)); messageProcessorExececutor.submit(() -> read()); } private void read() { while (!consumer.subscription().isEmpty()) { final ConsumerRecords<String, String> records = consumer.poll(60000); final Iterator<ConsumerRecord<String, String>> iterator = records.iterator(); while (iterator.hasNext()) { rateLimiter.ifPresent(limiter -> limiter.acquire()); final int phase = phaser.register(); final ConsumerRecord<String, String> msg = iterator.next(); final long offset = msg.offset(); final long partition = msg.partition(); unacknowledgedOffsets.add(offset); lastCommittedOffset.compareAndSet(0, offset); currentPartition.compareAndSet(-1, partition); handle(msg.value(), offset, configuration.getMaxRetries(), configuration.getInitialRetryDelaySeconds()); if (unacknowledgedOffsets.size() >= configuration.getMaxUnacknowledged() || partititionChanged(partition) || tooManyUncommittedOffsets(offset) || commitTimeoutReached()) { LOG.info("{} Got {} unacknowledged messages, waiting for ACKs in order to commit", configuration.getKafkaTopic(), unacknowledgedOffsets.size()); if (!waitForAcks(phase)) { return; } commitOffsetsIfAllAcknowledged(offset); LOG.info("{} Continuing message processing", configuration.getKafkaTopic()); } } } } private void handle(String msg, Long offset, int tries, int delaySeconds) { final Future<Void> futureResult = Future.future(); futureResult.setHandler(result -> { if(result.succeeded()) { unacknowledgedOffsets.remove(offset); phaser.arriveAndDeregister(); } else { final int nextDelaySeconds = computeNextDelay(delaySeconds); if (tries > 0) { LOG.error("{} Exception occurred during kafka message processing, will retry in {} seconds: {}", configuration.getKafkaTopic(), delaySeconds, msg, result.cause()); final int nextTry = tries - 1; vertx.setTimer(delaySeconds * 1000, event -> handle(msg, offset, nextTry, nextDelaySeconds)); } else { LOG.error("{} Exception occurred during kafka message processing. Max number of retries reached. Skipping message: {}", configuration.getKafkaTopic(), msg, result.cause()); unacknowledgedOffsets.remove(offset); phaser.arriveAndDeregister(); } } }); handler.handle(msg, futureResult); } private boolean commitTimeoutReached() { return System.currentTimeMillis() - lastCommitTime.get() >= configuration.getCommitTimeoutMs(); } private boolean partititionChanged(long partition) { if (currentPartition.get() != partition) { LOG.info("{} Partition changed from {} to {}", configuration.getKafkaTopic(), currentPartition.get(), partition); currentPartition.set(partition); return true; } return false; } private int computeNextDelay(int delaySeconds) { try { return Math.min(IntMath.checkedMultiply(delaySeconds, 2), configuration.getMaxRetryDelaySeconds()); } catch (ArithmeticException e) { return configuration.getMaxRetryDelaySeconds(); } } private boolean waitForAcks(int phase) { try { phaser.awaitAdvanceInterruptibly(phase, configuration.getAckTimeoutSeconds(), TimeUnit.SECONDS); return true; } catch (InterruptedException e) { LOG.error("{} Interrupted while waiting for ACKs", configuration.getKafkaTopic(), e); return false; } catch (TimeoutException e) { LOG.error("{} Waited for {} ACKs for longer than {} seconds, not making any progress ({}/{})", new Object[]{ configuration.getKafkaTopic(), Integer.valueOf(unacknowledgedOffsets.size()), Long.valueOf(configuration.getAckTimeoutSeconds()), Integer.valueOf(phase), Integer.valueOf(phaser.getPhase())}); return waitForAcks(phase); } } private boolean tooManyUncommittedOffsets(final long offset) { return lastCommittedOffset.get() + configuration.getMaxUncommitedOffsets() <= offset; } private void commitOffsetsIfAllAcknowledged(final long currentOffset) { if (unacknowledgedOffsets.isEmpty()) { LOG.info("{} Committing at offset {}", configuration.getKafkaTopic(), currentOffset); consumer.commitSync(); lastCommittedOffset.set(currentOffset); lastCommitTime.set(System.currentTimeMillis()); } else { LOG.warn("{} Can not commit because {} ACKs missing", configuration.getKafkaTopic(), unacknowledgedOffsets.size()); } } }
Make log messages nicer
src/main/java/com/hubrick/vertx/kafka/consumer/KafkaConsumerManager.java
Make log messages nicer
Java
apache-2.0
764eb837f97c317e1aad9d011de4fcca45d5b7dc
0
amplab/succinct,SwathiMystery/succinct,SwathiMystery/succinct,amplab/succinct
package edu.berkeley.cs.succinct; import edu.berkeley.cs.succinct.bitmap.BMArray; import edu.berkeley.cs.succinct.bitmap.BitMap; import edu.berkeley.cs.succinct.dictionary.Tables; import edu.berkeley.cs.succinct.qsufsort.QSufSort; import edu.berkeley.cs.succinct.util.CommonUtils; import edu.berkeley.cs.succinct.util.SerializedOperations; import edu.berkeley.cs.succinct.util.buffers.ThreadSafeByteBuffer; import edu.berkeley.cs.succinct.util.buffers.ThreadSafeIntBuffer; import edu.berkeley.cs.succinct.util.buffers.ThreadSafeLongBuffer; import edu.berkeley.cs.succinct.wavelettree.WaveletTree; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.*; public class SuccinctCore implements Serializable { private static final long serialVersionUID = 1382615274437547247L; public transient static final byte EOF = 1; protected transient ThreadSafeByteBuffer metadata; protected transient ThreadSafeByteBuffer alphabetmap; protected transient ThreadSafeLongBuffer contextmap; protected transient ThreadSafeByteBuffer alphabet; protected transient ThreadSafeLongBuffer sa; protected transient ThreadSafeLongBuffer isa; protected transient ThreadSafeLongBuffer neccol; protected transient ThreadSafeLongBuffer necrow; protected transient ThreadSafeLongBuffer rowoffsets; protected transient ThreadSafeLongBuffer coloffsets; protected transient ThreadSafeLongBuffer celloffsets; protected transient ThreadSafeIntBuffer rowsizes; protected transient ThreadSafeIntBuffer colsizes; protected transient ThreadSafeIntBuffer roff; protected transient ThreadSafeIntBuffer coff; protected transient ThreadSafeByteBuffer[] wavelettree; // Metadata private transient int originalSize; private transient int sampledSASize; private transient int alphaSize; private transient int sigmaSize; private transient int bits; private transient int sampledSABits; private transient int samplingBase; private transient int samplingRate; private transient int numContexts; private transient int contextLen; protected transient HashMap<Byte, Pair<Long, Integer>> alphabetMap; protected transient Map<Long, Long> contextMap; public enum StorageMode { MEMORY_ONLY, MEMORY_MAPPED } protected transient StorageMode storageMode; /** * * Constructor to initialize SuccinctCore from input byte array and specified context length. * @param input Input byte array. * @param contextLen Context length. */ public SuccinctCore(byte[] input, int contextLen) { this.setContextLen(contextLen); // Initializing Table data Tables.init(); // Append the EOF byte int end = input.length; input = Arrays.copyOf(input, input.length + 1); input[end] = EOF; // Construct Succinct data-structures construct(input); } /** * Constructor to load the data from persisted Succinct data-structures. * * @param path Path to load data from. * @param storageMode Mode in which data is stored (In-memory or Memory-mapped) */ public SuccinctCore(String path, StorageMode storageMode) { this.storageMode = storageMode; try { Tables.init(); if(storageMode == StorageMode.MEMORY_ONLY) { readFromFile(path); } else { memoryMap(path); } } catch (IOException e) { e.printStackTrace(); } } /** * Get the original size. * * @return The originalSize. */ public int getOriginalSize() { return originalSize; } /** * Set the original size. * * @param originalSize The originalSize to set. */ public void setOriginalSize(int originalSize) { this.originalSize = originalSize; } public int getSampledSASize() { return sampledSASize; } public void setSampledSASize(int sampledSASize) { this.sampledSASize = sampledSASize; } public int getAlphaSize() { return alphaSize; } public void setAlphaSize(int alphaSize) { this.alphaSize = alphaSize; } public int getSigmaSize() { return sigmaSize; } public void setSigmaSize(int sigmaSize) { this.sigmaSize = sigmaSize; } public int getBits() { return bits; } public void setBits(int bits) { this.bits = bits; } public int getSampledSABits() { return sampledSABits; } public void setSampledSABits(int sampledSABits) { this.sampledSABits = sampledSABits; } public int getSamplingBase() { return samplingBase; } public void setSamplingBase(int samplingBase) { this.samplingBase = samplingBase; } public int getSamplingRate() { return samplingRate; } public void setSamplingRate(int samplingRate) { this.samplingRate = samplingRate; } public int getNumContexts() { return numContexts; } public void setNumContexts(int numContexts) { this.numContexts = numContexts; } public int getContextLen() { return contextLen; } public void setContextLen(int contextLen) { this.contextLen = contextLen; } public static class Pair<T1, T2> { public T1 first; public T2 second; /** * Constructor to initialize pair * * @param first First element. * @param second Second element. */ public Pair(T1 first, T2 second) { this.first = first; this.second = second; } /** * Overrides toString() for Object. * @return String representation of the pair. */ @Override public String toString() { return "(" + first.toString() + ", " + second.toString() + ")"; } } /** * Represents a numeric range, [first, second] (inclusive). It is an * invalid/empty range iff second < first. */ class Range implements Comparable<Range> { public long first, second; /** * Constructor to initialize pair * * @param first First element. * @param second Second element. */ public Range(long first, long second) { this.first = first; this.second = second; } @Override public int compareTo(Range that) { long diff1 = this.first - that.first; long diff2 = this.second - that.second; if (diff1 == 0) { return diff2 < 0 ? -1 : (diff2 == 0 ? 0 : 1); } else { return diff1 < 0 ? -1 : 1; } } @Override public String toString() { return String.format("[%d, %d]", first, second); } } /** * Lookup NPA at specified index. * * @param i Index into NPA. * @return Value of NPA at specified index. */ public long lookupNPA(long i) { if(i > getOriginalSize() - 1 || i < 0) { throw new ArrayIndexOutOfBoundsException("NPA index out of bounds: i = " + i + " originalSize = " + getOriginalSize()); } int colId, rowId, cellId, cellOff, contextSize, contextPos; long colOff, rowOff; // Search columnoffset colId = SerializedOperations.ArrayOps.getRank1(coloffsets.buffer(), 0, getSigmaSize(), i) - 1; // Get columnoffset colOff = coloffsets.get(colId); // Search celloffsets cellId = SerializedOperations.ArrayOps.getRank1(celloffsets.buffer(), coff.get(colId), colsizes.get(colId), i - colOff) - 1; // Get position within cell cellOff = (int) (i - colOff - celloffsets.get(coff.get(colId) + cellId)); // Search rowoffsets rowId = (int) neccol.get(coff.get(colId) + cellId); // Get rowoffset rowOff = rowoffsets.get(rowId); // Get context size contextSize = rowsizes.get(rowId); // Get context position contextPos = SerializedOperations.ArrayOps.getRank1(necrow.buffer(), roff.get(rowId), rowsizes.get(rowId), colId) - 1; long cellValue = cellOff; if (wavelettree[rowId] != null) { cellValue = SerializedOperations.WaveletTreeOps.getValue( (ByteBuffer) wavelettree[rowId].rewind(), contextPos, cellOff, 0, contextSize - 1); wavelettree[rowId].rewind(); } return rowOff + cellValue; } /** * Lookup SA at specified index. * * @param i Index into SA. * @return Value of SA at specified index. */ public long lookupSA(long i) { if(i > getOriginalSize() - 1 || i < 0) { throw new ArrayIndexOutOfBoundsException("SA index out of bounds: i = " + i + " originalSize = " + getOriginalSize()); } long numHops = 0; while (i % getSamplingRate() != 0) { i = lookupNPA(i); numHops++; } long sampledValue = SerializedOperations.BMArrayOps.getVal(sa.buffer(), (int) (i / getSamplingRate()), getSampledSABits()); if(sampledValue < numHops) { return getOriginalSize() - (numHops - sampledValue); } return sampledValue - numHops; } /** * Lookup ISA at specified index. * * @param i Index into ISA. * @return Value of ISA at specified index. */ public long lookupISA(long i) { if(i > getOriginalSize() - 1 || i < 0) { throw new ArrayIndexOutOfBoundsException("ISA index out of bounds: i = " + i + " originalSize = " + getOriginalSize()); } int sampleIdx = (int) (i / getSamplingRate()); long pos = SerializedOperations.BMArrayOps.getVal(isa.buffer(), sampleIdx, getSampledSABits()); i -= (sampleIdx * getSamplingRate()); while (i != 0) { pos = lookupNPA(pos); i--; } return pos; } /** * Construct Succinct data structures from input byte array. * * @param input Input byte array. */ private void construct(byte[] input) { // Collect metadata setOriginalSize(input.length); setBits(CommonUtils.intLog2(getOriginalSize() + 1)); setSamplingBase(5); // Hard coded setSamplingRate((1 << getSamplingBase())); // Construct SA, ISA QSufSort qsuf = new QSufSort(); qsuf.buildSuffixArray(input); BMArray cSA = new BMArray(qsuf.getSA(), 0, getOriginalSize()); BMArray cISA = new BMArray(qsuf.getISA(), 0, getOriginalSize()); this.constructAux(cSA, input); setSigmaSize(0); // TODO: Combine sigmaSize and alphaSize int alphaBits = CommonUtils.intLog2(getAlphaSize() + 1); BMArray textBitMap = new BMArray(getOriginalSize(), alphaBits); for (int i = 0; i < getOriginalSize(); i++) { textBitMap.setVal(i, alphabetMap.get(input[i]).second); setSigmaSize(Math.max(alphabetMap.get(input[i]).second, getSigmaSize())); } setSigmaSize(getSigmaSize() + 1); this.constructNPA(textBitMap, cSA, cISA); this.constructCSA(cSA); setNumContexts(contextMap.size()); metadata = ThreadSafeByteBuffer.allocate(36); metadata.putInt(getOriginalSize()); metadata.putInt(getSampledSASize()); metadata.putInt(getAlphaSize()); metadata.putInt(getSigmaSize()); metadata.putInt(getBits()); metadata.putInt(getSampledSABits()); metadata.putInt(getSamplingBase()); metadata.putInt(getSamplingRate()); metadata.putInt(getNumContexts()); metadata.rewind(); } /** * Construct auxiliary data structures. * * @param SA Suffix Array. * @param input Input byte array. */ private void constructAux(BMArray SA, byte[] input) { ArrayList<Long> CinvIndex = new ArrayList<Long>(); byte[] alphabetArray; alphabetMap = new HashMap<Byte, Pair<Long, Integer>>(); setAlphaSize(1); for (long i = 1; i < input.length; ++i) { if (input[(int) SA.getVal((int) i)] != input[(int) SA.getVal((int) (i - 1))]) { CinvIndex.add(i); setAlphaSize(getAlphaSize() + 1); } } setAlphaSize(getAlphaSize() + 1); alphabetArray = new byte[getAlphaSize()]; alphabetArray[0] = input[(int) SA.getVal(0)]; alphabetMap.put(alphabetArray[0], new Pair<Long, Integer>(0L, 0)); long i; for (i = 1; i < getAlphaSize() - 1; i++) { long sel = CinvIndex.get((int) i - 1); alphabetArray[(int) i] = input[(int) SA.getVal((int) sel)]; alphabetMap.put(alphabetArray[(int) i], new Pair<Long, Integer>(sel, (int) i)); } alphabetMap.put((byte) 0, new Pair<Long, Integer>((long) input.length, (int) i)); alphabetArray[(int) i] = (char) 0; // Serialize cmap alphabetmap = ThreadSafeByteBuffer.allocate(alphabetMap.size() * (1 + 8 + 4)); for (Byte c : alphabetMap.keySet()) { Pair<Long, Integer> cval = alphabetMap.get(c); alphabetmap.put(c); alphabetmap.putLong(cval.first); alphabetmap.putInt(cval.second); } alphabetmap.rewind(); // Serialize S alphabet = ThreadSafeByteBuffer.allocate(alphabetArray.length); for (int j = 0; j < alphabetArray.length; j++) { alphabet.put(alphabetArray[j]); } alphabet.rewind(); } /** * Constructs NPA. * * @param T Input byte array as a bitmap. * @param SA Suffix Array. * @param ISA Inverse Suffix Array. */ private void constructNPA(BMArray T, BMArray SA, BMArray ISA) { ArrayList<Long> rowOffsets; ArrayList<Long> colOffsets; ArrayList<ArrayList<Long>> cellOffsets; ArrayList<ArrayList<Long>> necCol; ArrayList<ArrayList<Long>> necRow; int necColSize = 0, necRowSize = 0, cellOffsetsSize = 0; int k = 0, contextVal, contextId; long k1, k2, lOff = 0, npaVal, p = 0; HashMap<Long, Long> contextSizesMap = new HashMap<Long, Long>(); ArrayList<ArrayList<ArrayList<Long>>> table; ArrayList<Pair<ArrayList<Long>, Character>> context = new ArrayList<Pair<ArrayList<Long>, Character>>(); ArrayList<Long> cell; ArrayList<Long> contextValues = new ArrayList<Long>(); ArrayList<Long> contextColumnIds = new ArrayList<Long>(); boolean flag; long[] sizes, starts, c_sizes; long last_i = 0; contextMap = new TreeMap<Long, Long>(); for (long i = 0; i < getOriginalSize(); i++) { long contextValue = getContextVal(T, i); contextMap.put(contextValue, 0L); if (!contextSizesMap.containsKey(contextValue)) { contextSizesMap.put(contextValue, 1L); } else { contextSizesMap.put(contextValue, contextSizesMap.get(contextValue) + 1); } } sizes = new long[contextMap.size()]; c_sizes = new long[contextMap.size()]; starts = new long[contextMap.size()]; for (Map.Entry<Long, Long> currentContext : contextMap.entrySet()) { sizes[k] = contextSizesMap.get(currentContext.getKey()); starts[k] = getOriginalSize(); contextMap.put(currentContext.getKey(), (long) k); k++; } assert (k == contextMap.size()); contextSizesMap.clear(); BitMap NonNullBitMap = new BitMap(k * getSigmaSize()); table = new ArrayList<ArrayList<ArrayList<Long>>>(k); cellOffsets = new ArrayList<ArrayList<Long>>(); necCol = new ArrayList<ArrayList<Long>>(); colOffsets = new ArrayList<Long>(); rowOffsets = new ArrayList<Long>(); necRow = new ArrayList<ArrayList<Long>>(); wavelettree = new ThreadSafeByteBuffer[k]; for (int i = 0; i < k; i++) { table.add(new ArrayList<ArrayList<Long>>(getSigmaSize())); for (int j = 0; j < getSigmaSize(); j++) { ArrayList<Long> tableCell = new ArrayList<Long>(); table.get(i).add(tableCell); } necRow.add(new ArrayList<Long>()); } for (int i = 0; i < getSigmaSize(); i++) { necCol.add(new ArrayList<Long>()); cellOffsets.add(new ArrayList<Long>()); } k1 = SA.getVal(0); contextId = (int) getContextVal(T, (k1 + 1) % getOriginalSize()); contextVal = contextMap.get((long) contextId).intValue(); npaVal = ISA.getVal((int) ((SA.getVal(0) + 1) % getOriginalSize())); table.get(contextVal).get((int) (lOff / k)).add(npaVal); starts[contextVal] = Math.min(starts[contextVal], npaVal); c_sizes[contextVal]++; NonNullBitMap.setBit((int) contextVal); necCol.get(0).add((long) contextVal); necColSize++; colOffsets.add(0L); cellOffsets.get(0).add(0L); cellOffsetsSize++; for (long i = 1; i < getOriginalSize(); i++) { k1 = SA.getVal((int) i); k2 = SA.getVal((int) i - 1); contextId = (int) getContextVal(T, (k1 + 1) % getOriginalSize()); contextVal = contextMap.get((long) contextId).intValue(); // context value cannot exceed k, the number of contexts assert (contextVal < k); // If the column has changed, mark in colOffsets, cellOffsets; // update l offset if (!compareT(T, k1, k2, 1)) { colOffsets.add(i); lOff += k; last_i = i; cellOffsets.get((int) (lOff / k)).add(i - last_i); cellOffsetsSize++; } else if (!compareT(T, (k1 + 1) % getOriginalSize(), (k2 + 1) % getOriginalSize(), getContextLen())) { // Context has changed; mark in cellOffsets cellOffsets.get((int) (lOff / k)).add(i - last_i); cellOffsetsSize++; } // If we haven't marked it already, mark current cell as non empty if (NonNullBitMap.getBit((int) (lOff + contextVal)) == 0) { NonNullBitMap.setBit((int) (lOff + contextVal)); necCol.get((int) (lOff / k)).add((long) contextVal); necColSize++; } // Obtain actual npa value npaVal = ISA.getVal((int) ((SA.getVal((int) i) + 1) % getOriginalSize())); assert (lOff / k < getSigmaSize()); // Push npa value to npa table: note indices. indexed by context // value, and lOffs / k table.get(contextVal).get((int) (lOff / k)).add(npaVal); starts[contextVal] = Math.min(starts[contextVal], npaVal); if (table.get(contextVal).get((int) (lOff / k)).size() == 1) { c_sizes[contextVal]++; } } for (int i = 0; i < k; i++) { flag = false; for (int j = 0; j < getSigmaSize(); j++) { if (!flag && NonNullBitMap.getBit(i + j * k) == 1) { rowOffsets.add(p); p += table.get(i).get(j).size(); flag = true; } else if (NonNullBitMap.getBit(i + j * k) == 1) { p += table.get(i).get(j).size(); } if (NonNullBitMap.getBit(i + j * k) == 1) { cell = new ArrayList<Long>(); for (long t = 0; t < table.get(i).get(j).size(); t++) { cell.add(table.get(i).get(j).get((int) t) - starts[i]); } assert (cell.size() > 0); context.add(new Pair<ArrayList<Long>, Character>(cell, (char) j)); necRow.get(i).add((long) j); necRowSize++; } } assert (context.size() > 0); for (int j = 0; j < context.size(); j++) { assert (context.get(j).first.size() > 0); for (int t = 0; t < context.get(j).first.size(); t++) { contextValues.add(context.get(j).first.get(t)); contextColumnIds.add((long) j); } } assert (contextValues.size() > 0); assert (contextColumnIds.size() == contextValues.size()); WaveletTree wTree = new WaveletTree(0, context.size() - 1, contextValues, contextColumnIds); wavelettree[i] = ThreadSafeByteBuffer.fromByteBuffer(wTree.getByteBuffer()); contextValues.clear(); contextColumnIds.clear(); context.clear(); } table.clear(); // Serialize neccol neccol = ThreadSafeLongBuffer.allocate(necColSize); for (int i = 0; i < necCol.size(); i++) { for (int j = 0; j < necCol.get(i).size(); j++) { neccol.put(necCol.get(i).get(j)); } } neccol.rewind(); // Serialize necrow necrow = ThreadSafeLongBuffer.allocate(necRowSize); for (int i = 0; i < necRow.size(); i++) { for (int j = 0; j < necRow.get(i).size(); j++) { necrow.put(necRow.get(i).get(j)); } } necrow.rewind(); // Serialize rowoffsets rowoffsets = ThreadSafeLongBuffer.allocate(rowOffsets.size()); for (int i = 0; i < rowOffsets.size(); i++) { rowoffsets.put(rowOffsets.get(i)); } rowoffsets.rewind(); // Serialize coloffsets coloffsets = ThreadSafeLongBuffer.allocate(colOffsets.size()); for (int i = 0; i < colOffsets.size(); i++) { coloffsets.put(colOffsets.get(i)); } coloffsets.rewind(); // Serialize celloffsets celloffsets = ThreadSafeLongBuffer.allocate(cellOffsetsSize); for (int i = 0; i < cellOffsets.size(); i++) { for (int j = 0; j < cellOffsets.get(i).size(); j++) { celloffsets.put(cellOffsets.get(i).get(j)); } } celloffsets.rewind(); // Serialize rowsizes rowsizes = ThreadSafeIntBuffer.allocate(necRow.size()); for (int i = 0; i < necRow.size(); i++) { rowsizes.put(necRow.get(i).size()); } rowsizes.rewind(); // Serialize colsizes colsizes = ThreadSafeIntBuffer.allocate(necCol.size()); for (int i = 0; i < necCol.size(); i++) { colsizes.put(necCol.get(i).size()); } colsizes.rewind(); // Serialize roff int size = 0; roff = ThreadSafeIntBuffer.allocate(necRow.size()); for (int i = 0; i < necRow.size(); i++) { roff.put(size); size += necRow.get(i).size(); } roff.rewind(); // Serialize coff size = 0; coff = ThreadSafeIntBuffer.allocate(necCol.size()); for (int i = 0; i < necCol.size(); i++) { coff.put(size); size += necCol.get(i).size(); } coff.rewind(); // Serialize contexts contextmap = ThreadSafeLongBuffer.allocate(2 * contextMap.size()); for (Long c : contextMap.keySet()) { contextmap.put(c); contextmap.put(contextMap.get(c)); } contextmap.rewind(); } /** * Compare two positions in bitmap representation of input. * * @param T Bitmap representation of input. * @param i First position. * @param j Second position. * @param len Length of pattern to compare. * @return Result of comparison. */ private boolean compareT(BMArray T, long i, long j, int len) { for (long p = i; p < i + len; p++) { if (T.getVal((int) p) != T.getVal((int) j++)) { return false; } } return true; } /** * Get context value at specified index in bitmap representation of input. * * @param T Bitmap representation of input. * @param i Index into input. * @return Value of context at specified index. */ private long getContextVal(BMArray T, long i) { long val = 0; long max = Math.min(i + getContextLen(), getOriginalSize()); for (long p = i; p < max; p++) { val = val * getSigmaSize() + T.getVal((int) p); } if (max < i + getContextLen()) { for (long p = 0; p < (i + getContextLen()) % getOriginalSize(); p++) { val = val * getSigmaSize() + T.getVal((int) p); } } return val; } /** * Construct compressed SA and ISA from bitmap representation of SA. * * @param cSA Bitmap representation of SA. */ private int constructCSA(BMArray cSA) { setSamplingRate((1 << getSamplingBase())); setSampledSASize((getOriginalSize() / getSamplingRate()) + 1); setSampledSABits(CommonUtils.intLog2(getOriginalSize() + 1)); long saValue; BMArray SA = new BMArray(getSampledSASize(), getSampledSABits()); BMArray ISA = new BMArray(getSampledSASize(), getSampledSABits()); for (int i = 0; i < getOriginalSize(); i++) { saValue = cSA.getVal(i); if (i % getSamplingRate() == 0) { SA.setVal(i / getSamplingRate(), saValue); } if (saValue % getSamplingRate() == 0) { ISA.setVal((int)(saValue / getSamplingRate()), i); } } // Serialize SA sa = ThreadSafeLongBuffer.wrap(SA.data); // Serialize ISA isa = ThreadSafeLongBuffer.wrap(ISA.data); return 0; } /** * Write Succinct data structures to a DataOutputStream. * * @param os Output stream to write data to. * @throws IOException */ protected void writeToStream(DataOutputStream os) throws IOException { WritableByteChannel dataChannel = Channels.newChannel(os); dataChannel.write(metadata.order(ByteOrder.BIG_ENDIAN)); dataChannel.write(alphabetmap.order(ByteOrder.BIG_ENDIAN)); ByteBuffer bufContext = ByteBuffer.allocate(contextmap.limit() * 8); bufContext.asLongBuffer().put(contextmap.buffer()); dataChannel.write(bufContext.order(ByteOrder.BIG_ENDIAN)); dataChannel.write(alphabet.order(ByteOrder.BIG_ENDIAN)); ByteBuffer bufSA = ByteBuffer.allocate(sa.limit() * 8); bufSA.asLongBuffer().put(sa.buffer()); dataChannel.write(bufSA.order(ByteOrder.BIG_ENDIAN)); ByteBuffer bufISA = ByteBuffer.allocate(isa.limit() * 8); bufISA.asLongBuffer().put(isa.buffer()); dataChannel.write(bufISA.order(ByteOrder.BIG_ENDIAN)); os.writeInt(neccol.limit()); ByteBuffer bufNecCol = ByteBuffer.allocate(neccol.limit() * 8); bufNecCol.asLongBuffer().put(neccol.buffer()); dataChannel.write(bufNecCol.order(ByteOrder.BIG_ENDIAN)); os.writeInt(necrow.limit()); ByteBuffer bufNecRow = ByteBuffer.allocate(necrow.limit() * 8); bufNecRow.asLongBuffer().put(necrow.buffer()); dataChannel.write(bufNecRow.order(ByteOrder.BIG_ENDIAN)); os.writeInt(rowoffsets.limit()); ByteBuffer bufRowOff = ByteBuffer.allocate(rowoffsets.limit() * 8); bufRowOff.asLongBuffer().put(rowoffsets.buffer()); dataChannel.write(bufRowOff.order(ByteOrder.BIG_ENDIAN)); os.writeInt(coloffsets.limit()); ByteBuffer bufColOff = ByteBuffer.allocate(coloffsets.limit() * 8); bufColOff.asLongBuffer().put(coloffsets.buffer()); dataChannel.write(bufColOff.order(ByteOrder.BIG_ENDIAN)); os.writeInt(celloffsets.limit()); ByteBuffer bufCellOff = ByteBuffer.allocate(celloffsets.limit() * 8); bufCellOff.asLongBuffer().put(celloffsets.buffer()); dataChannel.write(bufCellOff.order(ByteOrder.BIG_ENDIAN)); os.writeInt(rowsizes.limit()); ByteBuffer bufRowSizes = ByteBuffer.allocate(rowsizes.limit() * 4); bufRowSizes.asIntBuffer().put(rowsizes.buffer()); dataChannel.write(bufRowSizes.order(ByteOrder.BIG_ENDIAN)); os.writeInt(colsizes.limit()); ByteBuffer bufColSizes = ByteBuffer.allocate(colsizes.limit() * 4); bufColSizes.asIntBuffer().put(colsizes.buffer()); dataChannel.write(bufColSizes.order(ByteOrder.BIG_ENDIAN)); os.writeInt(roff.limit()); ByteBuffer bufROff = ByteBuffer.allocate(roff.limit() * 4); bufROff.asIntBuffer().put(roff.buffer()); dataChannel.write(bufROff.order(ByteOrder.BIG_ENDIAN)); os.writeInt(coff.limit()); ByteBuffer bufCoff = ByteBuffer.allocate(coff.limit() * 4); bufCoff.asIntBuffer().put(coff.buffer()); dataChannel.write(bufCoff.order(ByteOrder.BIG_ENDIAN)); for (int i = 0; i < wavelettree.length; i++) { int wavelettreeSize = (wavelettree[i] == null) ? 0 : wavelettree[i].limit(); os.writeInt(wavelettreeSize); if (wavelettreeSize != 0) { dataChannel.write(wavelettree[i].order(ByteOrder.BIG_ENDIAN)); } } } /** * Reads Succinct data structures from a DataInputStream. * * @param is Stream to read data structures from. * @throws IOException */ protected void readFromStream(DataInputStream is) throws IOException { ReadableByteChannel dataChannel = Channels.newChannel(is); this.setOriginalSize(is.readInt()); this.setSampledSASize(is.readInt()); this.setAlphaSize(is.readInt()); this.setSigmaSize(is.readInt()); this.setBits(is.readInt()); this.setSampledSABits(is.readInt()); this.setSamplingBase(is.readInt()); this.setSamplingRate(is.readInt()); this.setNumContexts(is.readInt()); metadata = ThreadSafeByteBuffer.allocate(36); metadata.putInt(getOriginalSize()); metadata.putInt(getSampledSASize()); metadata.putInt(getAlphaSize()); metadata.putInt(getSigmaSize()); metadata.putInt(getBits()); metadata.putInt(getSampledSABits()); metadata.putInt(getSamplingBase()); metadata.putInt(getSamplingRate()); metadata.putInt(getNumContexts()); metadata.rewind(); int cmapSize = this.getAlphaSize(); this.alphabetmap = ThreadSafeByteBuffer.allocate(cmapSize * (1 + 8 + 4)); dataChannel.read(this.alphabetmap.buffer()); this.alphabetmap.rewind(); // Deserialize cmap alphabetMap = new HashMap<Byte, Pair<Long, Integer>>(); for (int i = 0; i < this.getAlphaSize(); i++) { byte c = alphabetmap.get(); long v1 = alphabetmap.getLong(); int v2 = alphabetmap.getInt(); alphabetMap.put(c, new Pair<Long, Integer>(v1, v2)); } // Read contexts int contextsSize = this.getNumContexts(); ByteBuffer contextBuf = ByteBuffer.allocate(contextsSize * 8 * 2); dataChannel.read(contextBuf); contextBuf.rewind(); this.contextmap = ThreadSafeLongBuffer.fromLongBuffer(contextBuf.asLongBuffer()); // Deserialize contexts contextMap = new HashMap<Long, Long>(); for (int i = 0; i < this.getNumContexts(); i++) { long v1 = contextmap.get(); long v2 = contextmap.get(); contextMap.put(v1, v2); } // Read slist int slistSize = this.getAlphaSize(); this.alphabet = ThreadSafeByteBuffer.allocate(slistSize); dataChannel.read(this.alphabet.buffer()); this.alphabet.rewind(); // Read sa int saSize = (getSampledSASize() * getSampledSABits()) / 64 + 1; ByteBuffer saBuf = ByteBuffer.allocate(saSize * 8); dataChannel.read(saBuf); saBuf.rewind(); this.sa = ThreadSafeLongBuffer.fromLongBuffer(saBuf.asLongBuffer()); // Read sainv int isaSize = (getSampledSASize() * getSampledSABits()) / 64 + 1; ByteBuffer isaBuf = ByteBuffer.allocate(isaSize * 8); dataChannel.read(isaBuf); isaBuf.rewind(); this.isa = ThreadSafeLongBuffer.fromLongBuffer(isaBuf.asLongBuffer()); // Read neccol int neccolSize = is.readInt(); ByteBuffer neccolBuf = ByteBuffer.allocate(neccolSize * 8); dataChannel.read(neccolBuf); neccolBuf.rewind(); this.neccol = ThreadSafeLongBuffer.fromLongBuffer(neccolBuf.asLongBuffer()); // Read necrow int necrowSize = is.readInt(); ByteBuffer necrowBuf = ByteBuffer.allocate(necrowSize * 8); dataChannel.read(necrowBuf); necrowBuf.rewind(); this.necrow = ThreadSafeLongBuffer.fromLongBuffer(necrowBuf.asLongBuffer()); // Read rowoffsets int rowoffsetsSize = is.readInt(); ByteBuffer rowoffsetsBuf = ByteBuffer.allocate(rowoffsetsSize * 8); dataChannel.read(rowoffsetsBuf); rowoffsetsBuf.rewind(); this.rowoffsets = ThreadSafeLongBuffer.fromLongBuffer(rowoffsetsBuf.asLongBuffer()); // Read coloffsets int coloffsetsSize = is.readInt(); ByteBuffer coloffsetsBuf = ByteBuffer.allocate(coloffsetsSize * 8); dataChannel.read(coloffsetsBuf); coloffsetsBuf.rewind(); this.coloffsets = ThreadSafeLongBuffer.fromLongBuffer(coloffsetsBuf.asLongBuffer()); // Read celloffsets int celloffsetsSize = is.readInt(); ByteBuffer celloffsetsBuf = ByteBuffer.allocate(celloffsetsSize * 8); dataChannel.read(celloffsetsBuf); celloffsetsBuf.rewind(); this.celloffsets = ThreadSafeLongBuffer.fromLongBuffer(celloffsetsBuf.asLongBuffer()); // Read rowsizes int rowsizesSize = is.readInt(); ByteBuffer rowsizesBuf = ByteBuffer.allocate(rowsizesSize * 4); dataChannel.read(rowsizesBuf); rowsizesBuf.rewind(); this.rowsizes = ThreadSafeIntBuffer.fromIntBuffer(rowsizesBuf.asIntBuffer()); int colsizesSize = is.readInt(); ByteBuffer colsizesBuf = ByteBuffer.allocate(colsizesSize * 4); dataChannel.read(colsizesBuf); colsizesBuf.rewind(); this.colsizes = ThreadSafeIntBuffer.fromIntBuffer(colsizesBuf.asIntBuffer()); int roffSize = is.readInt(); ByteBuffer roffBuf = ByteBuffer.allocate(roffSize * 4); dataChannel.read(roffBuf); roffBuf.rewind(); this.roff = ThreadSafeIntBuffer.fromIntBuffer(roffBuf.asIntBuffer()); int coffSize = is.readInt(); ByteBuffer coffBuf = ByteBuffer.allocate(coffSize * 4); dataChannel.read(coffBuf); coffBuf.rewind(); this.coff = ThreadSafeIntBuffer.fromIntBuffer(coffBuf.asIntBuffer()); int sum = 0; wavelettree = new ThreadSafeByteBuffer[contextsSize]; for (int i = 0; i < contextsSize; i++) { int wavelettreeSize = is.readInt(); sum += wavelettreeSize; wavelettree[i] = null; if (wavelettreeSize != 0) { ByteBuffer wavelettreeBuf = ByteBuffer.allocate(wavelettreeSize); dataChannel.read(wavelettreeBuf); wavelettree[i] = ThreadSafeByteBuffer.fromByteBuffer(((ByteBuffer) wavelettreeBuf.rewind())); } } } /** * Slices, orders and limits ByteBuffer. * * @param buf Buffer to slice, order and limit. * @param size Size to which buffer should be limited. * @return Sliced, ordered and limited buffer. */ private ByteBuffer sliceOrderLimit(ByteBuffer buf, int size) { ByteBuffer ret = (ByteBuffer) buf.slice().order(ByteOrder.BIG_ENDIAN).limit(size); buf.position(buf.position() + size); return ret; } /** * Reads Succinct data structures from a ByteBuffer. * * @param buf ByteBuffer to read Succinct data structures from. */ public void readFromBuffer(ByteBuffer buf) { buf.rewind(); metadata = ThreadSafeByteBuffer.fromByteBuffer(sliceOrderLimit(buf, 36)); // Deserialize metadata originalSize = metadata.getInt(); sampledSASize = metadata.getInt(); alphaSize = metadata.getInt(); sigmaSize = metadata.getInt(); bits = metadata.getInt(); sampledSABits = metadata.getInt(); samplingBase = metadata.getInt(); samplingRate = metadata.getInt(); numContexts = metadata.getInt(); metadata.rewind(); int alphabetmapSize = alphaSize * (1 + 8 + 4); alphabetmap = ThreadSafeByteBuffer.fromByteBuffer(sliceOrderLimit(buf, alphabetmapSize)); // Deserialize alphabetmap alphabetMap = new HashMap<Byte, Pair<Long, Integer>>(); for (int i = 0; i < this.alphaSize; i++) { byte c = alphabetmap.get(); long v1 = alphabetmap.getLong(); int v2 = alphabetmap.getInt(); alphabetMap.put(c, new Pair<Long, Integer>(v1, v2)); } alphabetmap.rewind(); // Read contexts int contextmapSize = numContexts * 8 * 2; contextmap = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, contextmapSize).asLongBuffer()); // Deserialize contexts contextMap = new HashMap<Long, Long>(); for (int i = 0; i < this.numContexts; i++) { long v1 = contextmap.get(); long v2 = contextmap.get(); contextMap.put(v1, v2); } contextmap.rewind(); // Read alphabet alphabet = ThreadSafeByteBuffer.fromByteBuffer(sliceOrderLimit(buf, alphaSize)); // Read sa int saSize = ((sampledSASize * sampledSABits) / 64 + 1) * 8; sa = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, saSize).asLongBuffer()); // Read isa int isaSize = ((sampledSASize * sampledSABits) / 64 + 1) * 8; isa = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, isaSize).asLongBuffer()); // Read neccol int neccolSize = buf.getInt() * 8; neccol = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, neccolSize).asLongBuffer()); // Read necrow int necrowSize = buf.getInt() * 8; necrow = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, necrowSize).asLongBuffer()); // Read rowoffsets int rowoffsetsSize = buf.getInt() * 8; rowoffsets = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, rowoffsetsSize).asLongBuffer()); // Read coloffsets int coloffsetsSize = buf.getInt() * 8; coloffsets = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, coloffsetsSize).asLongBuffer()); // Read celloffsets int celloffsetsSize = buf.getInt() * 8; celloffsets = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, celloffsetsSize).asLongBuffer()); // Read rowsizes int rowsizesSize = buf.getInt() * 4; rowsizes = ThreadSafeIntBuffer.fromIntBuffer(sliceOrderLimit(buf, rowsizesSize).asIntBuffer()); int colsizesSize = buf.getInt() * 4; colsizes = ThreadSafeIntBuffer.fromIntBuffer(sliceOrderLimit(buf, colsizesSize).asIntBuffer()); int roffSize = buf.getInt() * 4; roff = ThreadSafeIntBuffer.fromIntBuffer(sliceOrderLimit(buf, roffSize).asIntBuffer()); int coffSize = buf.getInt() * 4; coff = ThreadSafeIntBuffer.fromIntBuffer(sliceOrderLimit(buf, coffSize).asIntBuffer()); wavelettree = new ThreadSafeByteBuffer[getNumContexts()]; for (int i = 0; i < getNumContexts(); i++) { int wavelettreeSize = buf.getInt(); wavelettree[i] = null; if (wavelettreeSize != 0) { wavelettree[i] = ThreadSafeByteBuffer.fromByteBuffer(sliceOrderLimit(buf, wavelettreeSize)); } } } /** * Write Succinct data structures to file. * * @param path Path to file where Succinct data structures should be written. * @throws IOException */ public void writeToFile(String path) throws IOException { FileOutputStream fos = new FileOutputStream(path); DataOutputStream os = new DataOutputStream(fos); writeToStream(os); } /** * Read Succinct data structures into memory from file. * * @param path Path to serialized Succinct data structures. * @throws IOException */ public void readFromFile(String path) throws IOException { FileInputStream fis = new FileInputStream(path); DataInputStream is = new DataInputStream(fis); readFromStream(is); } /** * Memory maps serialized Succinct data structures. * * @param path Path to serialized Succinct data structures. * @throws IOException */ public void memoryMap(String path) throws IOException { File file = new File(path); long size = file.length(); FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel(); ByteBuffer buf = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size); readFromBuffer(buf); } /** * Convert Succinct data-structures to a byte array. * * @return Byte array containing serialzied Succinct data structures. * @throws IOException */ protected byte[] toByteArray() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); writeToStream(new DataOutputStream(bos)); return bos.toByteArray(); } /** * Read Succinct data structures from byte array. * * @param data Byte array to read data from. * @throws IOException */ protected void fromByteArray(byte[] data) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(data); readFromStream(new DataInputStream(bis)); } /** * Serialize SuccinctBuffer to OutputStream. * * @param oos ObjectOutputStream to write to. * @throws IOException */ private void writeObject(ObjectOutputStream oos) throws IOException { resetBuffers(); writeToStream(new DataOutputStream(oos)); resetBuffers(); } /** * Deserialize SuccinctBuffer from InputStream. * * @param ois ObjectInputStream to read from. * @throws IOException */ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { Tables.init(); readFromStream(new DataInputStream(ois)); } /** * Reposition all byte buffers to their respective starting positions. */ protected void resetBuffers() { metadata.order(ByteOrder.BIG_ENDIAN).rewind(); alphabetmap.order(ByteOrder.BIG_ENDIAN).rewind(); contextmap.rewind(); alphabet.rewind(); sa.rewind(); isa.rewind(); neccol.rewind(); necrow.rewind(); rowoffsets.rewind(); coloffsets.rewind(); celloffsets.rewind(); rowsizes.rewind(); colsizes.rewind(); roff.rewind(); coff.rewind(); for(int i = 0; i < wavelettree.length; i++) { if(wavelettree[i] != null) { wavelettree[i].order(ByteOrder.BIG_ENDIAN).rewind(); } } } }
core/src/main/java/edu/berkeley/cs/succinct/SuccinctCore.java
package edu.berkeley.cs.succinct; import edu.berkeley.cs.succinct.bitmap.BMArray; import edu.berkeley.cs.succinct.bitmap.BitMap; import edu.berkeley.cs.succinct.dictionary.Tables; import edu.berkeley.cs.succinct.qsufsort.QSufSort; import edu.berkeley.cs.succinct.util.CommonUtils; import edu.berkeley.cs.succinct.util.SerializedOperations; import edu.berkeley.cs.succinct.util.buffers.ThreadSafeByteBuffer; import edu.berkeley.cs.succinct.util.buffers.ThreadSafeIntBuffer; import edu.berkeley.cs.succinct.util.buffers.ThreadSafeLongBuffer; import edu.berkeley.cs.succinct.wavelettree.WaveletTree; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.*; public class SuccinctCore implements Serializable { private static final long serialVersionUID = 1382615274437547247L; public transient static final byte EOF = 1; protected transient ThreadSafeByteBuffer metadata; protected transient ThreadSafeByteBuffer alphabetmap; protected transient ThreadSafeLongBuffer contextmap; protected transient ThreadSafeByteBuffer alphabet; protected transient ThreadSafeLongBuffer sa; protected transient ThreadSafeLongBuffer isa; protected transient ThreadSafeLongBuffer neccol; protected transient ThreadSafeLongBuffer necrow; protected transient ThreadSafeLongBuffer rowoffsets; protected transient ThreadSafeLongBuffer coloffsets; protected transient ThreadSafeLongBuffer celloffsets; protected transient ThreadSafeIntBuffer rowsizes; protected transient ThreadSafeIntBuffer colsizes; protected transient ThreadSafeIntBuffer roff; protected transient ThreadSafeIntBuffer coff; protected transient ThreadSafeByteBuffer[] wavelettree; // Metadata private transient int originalSize; private transient int sampledSASize; private transient int alphaSize; private transient int sigmaSize; private transient int bits; private transient int sampledSABits; private transient int samplingBase; private transient int samplingRate; private transient int numContexts; private transient int contextLen; protected transient HashMap<Byte, Pair<Long, Integer>> alphabetMap; protected transient Map<Long, Long> contextMap; public enum StorageMode { MEMORY_ONLY, MEMORY_MAPPED } protected transient StorageMode storageMode; /** * * Constructor to initialize SuccinctCore from input byte array and specified context length. * @param input Input byte array. * @param contextLen Context length. */ public SuccinctCore(byte[] input, int contextLen) { this.setContextLen(contextLen); // Initializing Table data Tables.init(); // Append the EOF byte int end = input.length; input = Arrays.copyOf(input, input.length + 1); input[end] = EOF; // Construct Succinct data-structures construct(input); } /** * Constructor to load the data from persisted Succinct data-structures. * * @param path Path to load data from. * @param storageMode Mode in which data is stored (In-memory or Memory-mapped) */ public SuccinctCore(String path, StorageMode storageMode) { this.storageMode = storageMode; try { Tables.init(); if(storageMode == StorageMode.MEMORY_ONLY) { readFromFile(path); } else { memoryMap(path); } } catch (IOException e) { e.printStackTrace(); } } /** * Get the original size. * * @return The originalSize. */ public int getOriginalSize() { return originalSize; } /** * Set the original size. * * @param originalSize The originalSize to set. */ public void setOriginalSize(int originalSize) { this.originalSize = originalSize; } public int getSampledSASize() { return sampledSASize; } public void setSampledSASize(int sampledSASize) { this.sampledSASize = sampledSASize; } public int getAlphaSize() { return alphaSize; } public void setAlphaSize(int alphaSize) { this.alphaSize = alphaSize; } public int getSigmaSize() { return sigmaSize; } public void setSigmaSize(int sigmaSize) { this.sigmaSize = sigmaSize; } public int getBits() { return bits; } public void setBits(int bits) { this.bits = bits; } public int getSampledSABits() { return sampledSABits; } public void setSampledSABits(int sampledSABits) { this.sampledSABits = sampledSABits; } public int getSamplingBase() { return samplingBase; } public void setSamplingBase(int samplingBase) { this.samplingBase = samplingBase; } public int getSamplingRate() { return samplingRate; } public void setSamplingRate(int samplingRate) { this.samplingRate = samplingRate; } public int getNumContexts() { return numContexts; } public void setNumContexts(int numContexts) { this.numContexts = numContexts; } public int getContextLen() { return contextLen; } public void setContextLen(int contextLen) { this.contextLen = contextLen; } public static class Pair<T1, T2> { public T1 first; public T2 second; /** * Constructor to initialize pair * * @param first First element. * @param second Second element. */ public Pair(T1 first, T2 second) { this.first = first; this.second = second; } /** * Overrides toString() for Object. * @return String representation of the pair. */ @Override public String toString() { return "(" + first.toString() + ", " + second.toString() + ")"; } } /** * Represents a numeric range, [first, second] (inclusive). It is an * invalid/empty range iff second < first. */ class Range implements Comparable<Range> { public long first, second; /** * Constructor to initialize pair * * @param first First element. * @param second Second element. */ public Range(long first, long second) { this.first = first; this.second = second; } @Override public int compareTo(Range that) { long diff1 = this.first - that.first; long diff2 = this.second - that.second; if (diff1 == 0) { return diff2 < 0 ? -1 : (diff2 == 0 ? 0 : 1); } else { return diff1 < 0 ? -1 : 1; } } @Override public String toString() { return String.format("[%d, %d]", first, second); } } /** * Lookup NPA at specified index. * * @param i Index into NPA. * @return Value of NPA at specified index. */ public long lookupNPA(long i) { if(i > getOriginalSize() - 1 || i < 0) { throw new ArrayIndexOutOfBoundsException("NPA index out of bounds: i = " + i + " originalSize = " + getOriginalSize()); } int colId, rowId, cellId, cellOff, contextSize, contextPos; long colOff, rowOff; // Search columnoffset colId = SerializedOperations.ArrayOps.getRank1(coloffsets.buffer(), 0, getSigmaSize(), i) - 1; // Get columnoffset colOff = coloffsets.get(colId); // Search celloffsets cellId = SerializedOperations.ArrayOps.getRank1(celloffsets.buffer(), coff.get(colId), colsizes.get(colId), i - colOff) - 1; // Get position within cell cellOff = (int) (i - colOff - celloffsets.get(coff.get(colId) + cellId)); // Search rowoffsets rowId = (int) neccol.get(coff.get(colId) + cellId); // Get rowoffset rowOff = rowoffsets.get(rowId); // Get context size contextSize = rowsizes.get(rowId); // Get context position contextPos = SerializedOperations.ArrayOps.getRank1(necrow.buffer(), roff.get(rowId), rowsizes.get(rowId), colId) - 1; long cellValue = cellOff; if (wavelettree[rowId] != null) { cellValue = SerializedOperations.WaveletTreeOps.getValue( (ByteBuffer) wavelettree[rowId].rewind(), contextPos, cellOff, 0, contextSize - 1); wavelettree[rowId].rewind(); } return rowOff + cellValue; } /** * Lookup SA at specified index. * * @param i Index into SA. * @return Value of SA at specified index. */ public long lookupSA(long i) { if(i > getOriginalSize() - 1 || i < 0) { throw new ArrayIndexOutOfBoundsException("SA index out of bounds: i = " + i + " originalSize = " + getOriginalSize()); } long numHops = 0; while (i % getSamplingRate() != 0) { i = lookupNPA(i); numHops++; } long sampledValue = SerializedOperations.BMArrayOps.getVal(sa.buffer(), (int) (i / getSamplingRate()), getSampledSABits()); if(sampledValue < numHops) { return getOriginalSize() - (numHops - sampledValue); } return sampledValue - numHops; } /** * Lookup ISA at specified index. * * @param i Index into ISA. * @return Value of ISA at specified index. */ public long lookupISA(long i) { if(i > getOriginalSize() - 1 || i < 0) { throw new ArrayIndexOutOfBoundsException("ISA index out of bounds: i = " + i + " originalSize = " + getOriginalSize()); } int sampleIdx = (int) (i / getSamplingRate()); long pos = SerializedOperations.BMArrayOps.getVal(isa.buffer(), sampleIdx, getSampledSABits()); i -= (sampleIdx * getSamplingRate()); while (i != 0) { pos = lookupNPA(pos); i--; } return pos; } /** * Construct Succinct data structures from input byte array. * * @param input Input byte array. */ private void construct(byte[] input) { // Collect metadata setOriginalSize(input.length); setBits(CommonUtils.intLog2(getOriginalSize() + 1)); setSamplingBase(5); // Hard coded setSamplingRate((1 << getSamplingBase())); // Construct SA, ISA QSufSort qsuf = new QSufSort(); qsuf.buildSuffixArray(input); BMArray cSA = new BMArray(qsuf.getSA(), 0, getOriginalSize()); BMArray cISA = new BMArray(qsuf.getISA(), 0, getOriginalSize()); this.constructAux(cSA, input); setSigmaSize(0); // TODO: Combine sigmaSize and alphaSize int alphaBits = CommonUtils.intLog2(getAlphaSize() + 1); BMArray textBitMap = new BMArray(getOriginalSize(), alphaBits); for (int i = 0; i < getOriginalSize(); i++) { textBitMap.setVal(i, alphabetMap.get(input[i]).second); setSigmaSize(Math.max(alphabetMap.get(input[i]).second, getSigmaSize())); } setSigmaSize(getSigmaSize() + 1); this.constructNPA(textBitMap, cSA, cISA); this.constructCSA(cSA); setNumContexts(contextMap.size()); metadata = ThreadSafeByteBuffer.allocate(36); metadata.putInt(getOriginalSize()); metadata.putInt(getSampledSASize()); metadata.putInt(getAlphaSize()); metadata.putInt(getSigmaSize()); metadata.putInt(getBits()); metadata.putInt(getSampledSABits()); metadata.putInt(getSamplingBase()); metadata.putInt(getSamplingRate()); metadata.putInt(getNumContexts()); metadata.rewind(); } /** * Construct auxiliary data structures. * * @param SA Suffix Array. * @param input Input byte array. */ private void constructAux(BMArray SA, byte[] input) { ArrayList<Long> CinvIndex = new ArrayList<Long>(); byte[] alphabetArray; alphabetMap = new HashMap<Byte, Pair<Long, Integer>>(); setAlphaSize(1); for (long i = 1; i < input.length; ++i) { if (input[(int) SA.getVal((int) i)] != input[(int) SA.getVal((int) (i - 1))]) { CinvIndex.add(i); setAlphaSize(getAlphaSize() + 1); } } setAlphaSize(getAlphaSize() + 1); alphabetArray = new byte[getAlphaSize()]; alphabetArray[0] = input[(int) SA.getVal(0)]; alphabetMap.put(alphabetArray[0], new Pair<Long, Integer>(0L, 0)); long i; for (i = 1; i < getAlphaSize() - 1; i++) { long sel = CinvIndex.get((int) i - 1); alphabetArray[(int) i] = input[(int) SA.getVal((int) sel)]; alphabetMap.put(alphabetArray[(int) i], new Pair<Long, Integer>(sel, (int) i)); } alphabetMap.put((byte) 0, new Pair<Long, Integer>((long) input.length, (int) i)); alphabetArray[(int) i] = (char) 0; // Serialize cmap alphabetmap = ThreadSafeByteBuffer.allocate(alphabetMap.size() * (1 + 8 + 4)); for (Byte c : alphabetMap.keySet()) { Pair<Long, Integer> cval = alphabetMap.get(c); alphabetmap.put(c); alphabetmap.putLong(cval.first); alphabetmap.putInt(cval.second); } alphabetmap.rewind(); // Serialize S alphabet = ThreadSafeByteBuffer.allocate(alphabetArray.length); for (int j = 0; j < alphabetArray.length; j++) { alphabet.put(alphabetArray[j]); } alphabet.rewind(); } /** * Constructs NPA. * * @param T Input byte array as a bitmap. * @param SA Suffix Array. * @param ISA Inverse Suffix Array. */ private void constructNPA(BMArray T, BMArray SA, BMArray ISA) { ArrayList<Long> rowOffsets; ArrayList<Long> colOffsets; ArrayList<ArrayList<Long>> cellOffsets; ArrayList<ArrayList<Long>> necCol; ArrayList<ArrayList<Long>> necRow; int necColSize = 0, necRowSize = 0, cellOffsetsSize = 0; int k = 0, contextVal, contextId; long k1, k2, lOff = 0, npaVal, p = 0; HashMap<Long, Long> contextSizesMap = new HashMap<Long, Long>(); ArrayList<ArrayList<ArrayList<Long>>> table; ArrayList<Pair<ArrayList<Long>, Character>> context = new ArrayList<Pair<ArrayList<Long>, Character>>(); ArrayList<Long> cell; ArrayList<Long> contextValues = new ArrayList<Long>(); ArrayList<Long> contextColumnIds = new ArrayList<Long>(); boolean flag; long[] sizes, starts, c_sizes; long last_i = 0; contextMap = new TreeMap<Long, Long>(); for (long i = 0; i < getOriginalSize(); i++) { long contextValue = getContextVal(T, i); contextMap.put(contextValue, 0L); if (!contextSizesMap.containsKey(contextValue)) { contextSizesMap.put(contextValue, 1L); } else { contextSizesMap.put(contextValue, contextSizesMap.get(contextValue) + 1); } } sizes = new long[contextMap.size()]; c_sizes = new long[contextMap.size()]; starts = new long[contextMap.size()]; for (Map.Entry<Long, Long> currentContext : contextMap.entrySet()) { sizes[k] = contextSizesMap.get(currentContext.getKey()); starts[k] = getOriginalSize(); contextMap.put(currentContext.getKey(), (long) k); k++; } assert (k == contextMap.size()); contextSizesMap.clear(); BitMap NonNullBitMap = new BitMap(k * getSigmaSize()); table = new ArrayList<ArrayList<ArrayList<Long>>>(k); cellOffsets = new ArrayList<ArrayList<Long>>(); necCol = new ArrayList<ArrayList<Long>>(); colOffsets = new ArrayList<Long>(); rowOffsets = new ArrayList<Long>(); necRow = new ArrayList<ArrayList<Long>>(); wavelettree = new ThreadSafeByteBuffer[k]; for (int i = 0; i < k; i++) { table.add(new ArrayList<ArrayList<Long>>(getSigmaSize())); for (int j = 0; j < getSigmaSize(); j++) { ArrayList<Long> tableCell = new ArrayList<Long>(); table.get(i).add(tableCell); } necRow.add(new ArrayList<Long>()); } for (int i = 0; i < getSigmaSize(); i++) { necCol.add(new ArrayList<Long>()); cellOffsets.add(new ArrayList<Long>()); } k1 = SA.getVal(0); contextId = (int) getContextVal(T, (k1 + 1) % getOriginalSize()); contextVal = contextMap.get((long) contextId).intValue(); npaVal = ISA.getVal((int) ((SA.getVal(0) + 1) % getOriginalSize())); table.get(contextVal).get((int) (lOff / k)).add(npaVal); starts[contextVal] = Math.min(starts[contextVal], npaVal); c_sizes[contextVal]++; NonNullBitMap.setBit((int) contextVal); necCol.get(0).add((long) contextVal); necColSize++; colOffsets.add(0L); cellOffsets.get(0).add(0L); cellOffsetsSize++; for (long i = 1; i < getOriginalSize(); i++) { k1 = SA.getVal((int) i); k2 = SA.getVal((int) i - 1); contextId = (int) getContextVal(T, (k1 + 1) % getOriginalSize()); contextVal = contextMap.get((long) contextId).intValue(); // context value cannot exceed k, the number of contexts assert (contextVal < k); // If the column has changed, mark in colOffsets, cellOffsets; // update l offset if (!compareT(T, k1, k2, 1)) { colOffsets.add(i); lOff += k; last_i = i; cellOffsets.get((int) (lOff / k)).add(i - last_i); cellOffsetsSize++; } else if (!compareT(T, (k1 + 1) % getOriginalSize(), (k2 + 1) % getOriginalSize(), getContextLen())) { // Context has changed; mark in cellOffsets cellOffsets.get((int) (lOff / k)).add(i - last_i); cellOffsetsSize++; } // If we haven't marked it already, mark current cell as non empty if (NonNullBitMap.getBit((int) (lOff + contextVal)) == 0) { NonNullBitMap.setBit((int) (lOff + contextVal)); necCol.get((int) (lOff / k)).add((long) contextVal); necColSize++; } // Obtain actual npa value npaVal = ISA.getVal((int) ((SA.getVal((int) i) + 1) % getOriginalSize())); assert (lOff / k < getSigmaSize()); // Push npa value to npa table: note indices. indexed by context // value, and lOffs / k table.get(contextVal).get((int) (lOff / k)).add(npaVal); starts[contextVal] = Math.min(starts[contextVal], npaVal); if (table.get(contextVal).get((int) (lOff / k)).size() == 1) { c_sizes[contextVal]++; } } for (int i = 0; i < k; i++) { flag = false; for (int j = 0; j < getSigmaSize(); j++) { if (!flag && NonNullBitMap.getBit(i + j * k) == 1) { rowOffsets.add(p); p += table.get(i).get(j).size(); flag = true; } else if (NonNullBitMap.getBit(i + j * k) == 1) { p += table.get(i).get(j).size(); } if (NonNullBitMap.getBit(i + j * k) == 1) { cell = new ArrayList<Long>(); for (long t = 0; t < table.get(i).get(j).size(); t++) { cell.add(table.get(i).get(j).get((int) t) - starts[i]); } assert (cell.size() > 0); context.add(new Pair<ArrayList<Long>, Character>(cell, (char) j)); necRow.get(i).add((long) j); necRowSize++; } } assert (context.size() > 0); for (int j = 0; j < context.size(); j++) { assert (context.get(j).first.size() > 0); for (int t = 0; t < context.get(j).first.size(); t++) { contextValues.add(context.get(j).first.get(t)); contextColumnIds.add((long) j); } } assert (contextValues.size() > 0); assert (contextColumnIds.size() == contextValues.size()); WaveletTree wTree = new WaveletTree(0, context.size() - 1, contextValues, contextColumnIds); wavelettree[i] = ThreadSafeByteBuffer.fromByteBuffer(wTree.getByteBuffer()); contextValues.clear(); contextColumnIds.clear(); context.clear(); } table.clear(); // Serialize neccol neccol = ThreadSafeLongBuffer.allocate(necColSize); for (int i = 0; i < necCol.size(); i++) { for (int j = 0; j < necCol.get(i).size(); j++) { neccol.put(necCol.get(i).get(j)); } } neccol.rewind(); // Serialize necrow necrow = ThreadSafeLongBuffer.allocate(necRowSize); for (int i = 0; i < necRow.size(); i++) { for (int j = 0; j < necRow.get(i).size(); j++) { necrow.put(necRow.get(i).get(j)); } } necrow.rewind(); // Serialize rowoffsets rowoffsets = ThreadSafeLongBuffer.allocate(rowOffsets.size()); for (int i = 0; i < rowOffsets.size(); i++) { rowoffsets.put(rowOffsets.get(i)); } rowoffsets.rewind(); // Serialize coloffsets coloffsets = ThreadSafeLongBuffer.allocate(colOffsets.size()); for (int i = 0; i < colOffsets.size(); i++) { coloffsets.put(colOffsets.get(i)); } coloffsets.rewind(); // Serialize celloffsets celloffsets = ThreadSafeLongBuffer.allocate(cellOffsetsSize); for (int i = 0; i < cellOffsets.size(); i++) { for (int j = 0; j < cellOffsets.get(i).size(); j++) { celloffsets.put(cellOffsets.get(i).get(j)); } } celloffsets.rewind(); // Serialize rowsizes rowsizes = ThreadSafeIntBuffer.allocate(necRow.size()); for (int i = 0; i < necRow.size(); i++) { rowsizes.put(necRow.get(i).size()); } rowsizes.rewind(); // Serialize colsizes colsizes = ThreadSafeIntBuffer.allocate(necCol.size()); for (int i = 0; i < necCol.size(); i++) { colsizes.put(necCol.get(i).size()); } colsizes.rewind(); // Serialize roff int size = 0; roff = ThreadSafeIntBuffer.allocate(necRow.size()); for (int i = 0; i < necRow.size(); i++) { roff.put(size); size += necRow.get(i).size(); } roff.rewind(); // Serialize coff size = 0; coff = ThreadSafeIntBuffer.allocate(necCol.size()); for (int i = 0; i < necCol.size(); i++) { coff.put(size); size += necCol.get(i).size(); } coff.rewind(); // Serialize contexts contextmap = ThreadSafeLongBuffer.allocate(2 * contextMap.size()); for (Long c : contextMap.keySet()) { contextmap.put(c); contextmap.put(contextMap.get(c)); } contextmap.rewind(); } /** * Compare two positions in bitmap representation of input. * * @param T Bitmap representation of input. * @param i First position. * @param j Second position. * @param len Length of pattern to compare. * @return Result of comparison. */ private boolean compareT(BMArray T, long i, long j, int len) { for (long p = i; p < i + len; p++) { if (T.getVal((int) p) != T.getVal((int) j++)) { return false; } } return true; } /** * Get context value at specified index in bitmap representation of input. * * @param T Bitmap representation of input. * @param i Index into input. * @return Value of context at specified index. */ private long getContextVal(BMArray T, long i) { long val = 0; long max = Math.min(i + getContextLen(), getOriginalSize()); for (long p = i; p < max; p++) { val = val * getSigmaSize() + T.getVal((int) p); } if (max < i + getContextLen()) { for (long p = 0; p < (i + getContextLen()) % getOriginalSize(); p++) { val = val * getSigmaSize() + T.getVal((int) p); } } return val; } /** * Construct compressed SA and ISA from bitmap representation of SA. * * @param cSA Bitmap representation of SA. */ private int constructCSA(BMArray cSA) { setSamplingRate((1 << getSamplingBase())); setSampledSASize((getOriginalSize() / getSamplingRate()) + 1); setSampledSABits(CommonUtils.intLog2(getOriginalSize() + 1)); long saValue; BMArray SA = new BMArray(getSampledSASize(), getSampledSABits()); BMArray ISA = new BMArray(getSampledSASize(), getSampledSABits()); for (int i = 0; i < getOriginalSize(); i++) { saValue = cSA.getVal(i); if (i % getSamplingRate() == 0) { SA.setVal(i / getSamplingRate(), saValue); } if (saValue % getSamplingRate() == 0) { ISA.setVal((int)(saValue / getSamplingRate()), i); } } // Serialize SA sa = ThreadSafeLongBuffer.wrap(SA.data); // Serialize ISA isa = ThreadSafeLongBuffer.wrap(ISA.data); return 0; } protected void writeToStream(DataOutputStream os) throws IOException { WritableByteChannel dataChannel = Channels.newChannel(os); dataChannel.write(metadata.order(ByteOrder.BIG_ENDIAN)); dataChannel.write(alphabetmap.order(ByteOrder.BIG_ENDIAN)); ByteBuffer bufContext = ByteBuffer.allocate(contextmap.limit() * 8); bufContext.asLongBuffer().put(contextmap.buffer()); dataChannel.write(bufContext.order(ByteOrder.BIG_ENDIAN)); dataChannel.write(alphabet.order(ByteOrder.BIG_ENDIAN)); ByteBuffer bufSA = ByteBuffer.allocate(sa.limit() * 8); bufSA.asLongBuffer().put(sa.buffer()); dataChannel.write(bufSA.order(ByteOrder.BIG_ENDIAN)); ByteBuffer bufISA = ByteBuffer.allocate(isa.limit() * 8); bufISA.asLongBuffer().put(isa.buffer()); dataChannel.write(bufISA.order(ByteOrder.BIG_ENDIAN)); os.writeInt(neccol.limit()); ByteBuffer bufNecCol = ByteBuffer.allocate(neccol.limit() * 8); bufNecCol.asLongBuffer().put(neccol.buffer()); dataChannel.write(bufNecCol.order(ByteOrder.BIG_ENDIAN)); os.writeInt(necrow.limit()); ByteBuffer bufNecRow = ByteBuffer.allocate(necrow.limit() * 8); bufNecRow.asLongBuffer().put(necrow.buffer()); dataChannel.write(bufNecRow.order(ByteOrder.BIG_ENDIAN)); os.writeInt(rowoffsets.limit()); ByteBuffer bufRowOff = ByteBuffer.allocate(rowoffsets.limit() * 8); bufRowOff.asLongBuffer().put(rowoffsets.buffer()); dataChannel.write(bufRowOff.order(ByteOrder.BIG_ENDIAN)); os.writeInt(coloffsets.limit()); ByteBuffer bufColOff = ByteBuffer.allocate(coloffsets.limit() * 8); bufColOff.asLongBuffer().put(coloffsets.buffer()); dataChannel.write(bufColOff.order(ByteOrder.BIG_ENDIAN)); os.writeInt(celloffsets.limit()); ByteBuffer bufCellOff = ByteBuffer.allocate(celloffsets.limit() * 8); bufCellOff.asLongBuffer().put(celloffsets.buffer()); dataChannel.write(bufCellOff.order(ByteOrder.BIG_ENDIAN)); os.writeInt(rowsizes.limit()); ByteBuffer bufRowSizes = ByteBuffer.allocate(rowsizes.limit() * 4); bufRowSizes.asIntBuffer().put(rowsizes.buffer()); dataChannel.write(bufRowSizes.order(ByteOrder.BIG_ENDIAN)); os.writeInt(colsizes.limit()); ByteBuffer bufColSizes = ByteBuffer.allocate(colsizes.limit() * 4); bufColSizes.asIntBuffer().put(colsizes.buffer()); dataChannel.write(bufColSizes.order(ByteOrder.BIG_ENDIAN)); os.writeInt(roff.limit()); ByteBuffer bufROff = ByteBuffer.allocate(roff.limit() * 4); bufROff.asIntBuffer().put(roff.buffer()); dataChannel.write(bufROff.order(ByteOrder.BIG_ENDIAN)); os.writeInt(coff.limit()); ByteBuffer bufCoff = ByteBuffer.allocate(coff.limit() * 4); bufCoff.asIntBuffer().put(coff.buffer()); dataChannel.write(bufCoff.order(ByteOrder.BIG_ENDIAN)); for (int i = 0; i < wavelettree.length; i++) { int wavelettreeSize = (wavelettree[i] == null) ? 0 : wavelettree[i].limit(); os.writeInt(wavelettreeSize); if (wavelettreeSize != 0) { dataChannel.write(wavelettree[i].order(ByteOrder.BIG_ENDIAN)); } } } protected void readFromStream(DataInputStream is) throws IOException { ReadableByteChannel dataChannel = Channels.newChannel(is); this.setOriginalSize(is.readInt()); this.setSampledSASize(is.readInt()); this.setAlphaSize(is.readInt()); this.setSigmaSize(is.readInt()); this.setBits(is.readInt()); this.setSampledSABits(is.readInt()); this.setSamplingBase(is.readInt()); this.setSamplingRate(is.readInt()); this.setNumContexts(is.readInt()); metadata = ThreadSafeByteBuffer.allocate(36); metadata.putInt(getOriginalSize()); metadata.putInt(getSampledSASize()); metadata.putInt(getAlphaSize()); metadata.putInt(getSigmaSize()); metadata.putInt(getBits()); metadata.putInt(getSampledSABits()); metadata.putInt(getSamplingBase()); metadata.putInt(getSamplingRate()); metadata.putInt(getNumContexts()); metadata.rewind(); int cmapSize = this.getAlphaSize(); this.alphabetmap = ThreadSafeByteBuffer.allocate(cmapSize * (1 + 8 + 4)); dataChannel.read(this.alphabetmap.buffer()); this.alphabetmap.rewind(); // Deserialize cmap alphabetMap = new HashMap<Byte, Pair<Long, Integer>>(); for (int i = 0; i < this.getAlphaSize(); i++) { byte c = alphabetmap.get(); long v1 = alphabetmap.getLong(); int v2 = alphabetmap.getInt(); alphabetMap.put(c, new Pair<Long, Integer>(v1, v2)); } // Read contexts int contextsSize = this.getNumContexts(); ByteBuffer contextBuf = ByteBuffer.allocate(contextsSize * 8 * 2); dataChannel.read(contextBuf); contextBuf.rewind(); this.contextmap = ThreadSafeLongBuffer.fromLongBuffer(contextBuf.asLongBuffer()); // Deserialize contexts contextMap = new HashMap<Long, Long>(); for (int i = 0; i < this.getNumContexts(); i++) { long v1 = contextmap.get(); long v2 = contextmap.get(); contextMap.put(v1, v2); } // Read slist int slistSize = this.getAlphaSize(); this.alphabet = ThreadSafeByteBuffer.allocate(slistSize); dataChannel.read(this.alphabet.buffer()); this.alphabet.rewind(); // Read sa int saSize = (getSampledSASize() * getSampledSABits()) / 64 + 1; ByteBuffer saBuf = ByteBuffer.allocate(saSize * 8); dataChannel.read(saBuf); saBuf.rewind(); this.sa = ThreadSafeLongBuffer.fromLongBuffer(saBuf.asLongBuffer()); // Read sainv int isaSize = (getSampledSASize() * getSampledSABits()) / 64 + 1; ByteBuffer isaBuf = ByteBuffer.allocate(isaSize * 8); dataChannel.read(isaBuf); isaBuf.rewind(); this.isa = ThreadSafeLongBuffer.fromLongBuffer(isaBuf.asLongBuffer()); // Read neccol int neccolSize = is.readInt(); ByteBuffer neccolBuf = ByteBuffer.allocate(neccolSize * 8); dataChannel.read(neccolBuf); neccolBuf.rewind(); this.neccol = ThreadSafeLongBuffer.fromLongBuffer(neccolBuf.asLongBuffer()); // Read necrow int necrowSize = is.readInt(); ByteBuffer necrowBuf = ByteBuffer.allocate(necrowSize * 8); dataChannel.read(necrowBuf); necrowBuf.rewind(); this.necrow = ThreadSafeLongBuffer.fromLongBuffer(necrowBuf.asLongBuffer()); // Read rowoffsets int rowoffsetsSize = is.readInt(); ByteBuffer rowoffsetsBuf = ByteBuffer.allocate(rowoffsetsSize * 8); dataChannel.read(rowoffsetsBuf); rowoffsetsBuf.rewind(); this.rowoffsets = ThreadSafeLongBuffer.fromLongBuffer(rowoffsetsBuf.asLongBuffer()); // Read coloffsets int coloffsetsSize = is.readInt(); ByteBuffer coloffsetsBuf = ByteBuffer.allocate(coloffsetsSize * 8); dataChannel.read(coloffsetsBuf); coloffsetsBuf.rewind(); this.coloffsets = ThreadSafeLongBuffer.fromLongBuffer(coloffsetsBuf.asLongBuffer()); // Read celloffsets int celloffsetsSize = is.readInt(); ByteBuffer celloffsetsBuf = ByteBuffer.allocate(celloffsetsSize * 8); dataChannel.read(celloffsetsBuf); celloffsetsBuf.rewind(); this.celloffsets = ThreadSafeLongBuffer.fromLongBuffer(celloffsetsBuf.asLongBuffer()); // Read rowsizes int rowsizesSize = is.readInt(); ByteBuffer rowsizesBuf = ByteBuffer.allocate(rowsizesSize * 4); dataChannel.read(rowsizesBuf); rowsizesBuf.rewind(); this.rowsizes = ThreadSafeIntBuffer.fromIntBuffer(rowsizesBuf.asIntBuffer()); int colsizesSize = is.readInt(); ByteBuffer colsizesBuf = ByteBuffer.allocate(colsizesSize * 4); dataChannel.read(colsizesBuf); colsizesBuf.rewind(); this.colsizes = ThreadSafeIntBuffer.fromIntBuffer(colsizesBuf.asIntBuffer()); int roffSize = is.readInt(); ByteBuffer roffBuf = ByteBuffer.allocate(roffSize * 4); dataChannel.read(roffBuf); roffBuf.rewind(); this.roff = ThreadSafeIntBuffer.fromIntBuffer(roffBuf.asIntBuffer()); int coffSize = is.readInt(); ByteBuffer coffBuf = ByteBuffer.allocate(coffSize * 4); dataChannel.read(coffBuf); coffBuf.rewind(); this.coff = ThreadSafeIntBuffer.fromIntBuffer(coffBuf.asIntBuffer()); int sum = 0; wavelettree = new ThreadSafeByteBuffer[contextsSize]; for (int i = 0; i < contextsSize; i++) { int wavelettreeSize = is.readInt(); sum += wavelettreeSize; wavelettree[i] = null; if (wavelettreeSize != 0) { ByteBuffer wavelettreeBuf = ByteBuffer.allocate(wavelettreeSize); dataChannel.read(wavelettreeBuf); wavelettree[i] = ThreadSafeByteBuffer.fromByteBuffer(((ByteBuffer) wavelettreeBuf.rewind())); } } } private ByteBuffer sliceOrderLimit(ByteBuffer buf, int size) { ByteBuffer ret = (ByteBuffer) buf.slice().order(ByteOrder.BIG_ENDIAN).limit(size); buf.position(buf.position() + size); return ret; } public void readFromBuffer(ByteBuffer buf) { buf.rewind(); metadata = ThreadSafeByteBuffer.fromByteBuffer(sliceOrderLimit(buf, 36)); // Deserialize metadata originalSize = metadata.getInt(); sampledSASize = metadata.getInt(); alphaSize = metadata.getInt(); sigmaSize = metadata.getInt(); bits = metadata.getInt(); sampledSABits = metadata.getInt(); samplingBase = metadata.getInt(); samplingRate = metadata.getInt(); numContexts = metadata.getInt(); metadata.rewind(); int alphabetmapSize = alphaSize * (1 + 8 + 4); alphabetmap = ThreadSafeByteBuffer.fromByteBuffer(sliceOrderLimit(buf, alphabetmapSize)); // Deserialize alphabetmap alphabetMap = new HashMap<Byte, Pair<Long, Integer>>(); for (int i = 0; i < this.alphaSize; i++) { byte c = alphabetmap.get(); long v1 = alphabetmap.getLong(); int v2 = alphabetmap.getInt(); alphabetMap.put(c, new Pair<Long, Integer>(v1, v2)); } alphabetmap.rewind(); // Read contexts int contextmapSize = numContexts * 8 * 2; contextmap = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, contextmapSize).asLongBuffer()); // Deserialize contexts contextMap = new HashMap<Long, Long>(); for (int i = 0; i < this.numContexts; i++) { long v1 = contextmap.get(); long v2 = contextmap.get(); contextMap.put(v1, v2); } contextmap.rewind(); // Read alphabet alphabet = ThreadSafeByteBuffer.fromByteBuffer(sliceOrderLimit(buf, alphaSize)); // Read sa int saSize = ((sampledSASize * sampledSABits) / 64 + 1) * 8; sa = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, saSize).asLongBuffer()); // Read isa int isaSize = ((sampledSASize * sampledSABits) / 64 + 1) * 8; isa = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, isaSize).asLongBuffer()); // Read neccol int neccolSize = buf.getInt() * 8; neccol = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, neccolSize).asLongBuffer()); // Read necrow int necrowSize = buf.getInt() * 8; necrow = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, necrowSize).asLongBuffer()); // Read rowoffsets int rowoffsetsSize = buf.getInt() * 8; rowoffsets = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, rowoffsetsSize).asLongBuffer()); // Read coloffsets int coloffsetsSize = buf.getInt() * 8; coloffsets = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, coloffsetsSize).asLongBuffer()); // Read celloffsets int celloffsetsSize = buf.getInt() * 8; celloffsets = ThreadSafeLongBuffer.fromLongBuffer(sliceOrderLimit(buf, celloffsetsSize).asLongBuffer()); // Read rowsizes int rowsizesSize = buf.getInt() * 4; rowsizes = ThreadSafeIntBuffer.fromIntBuffer(sliceOrderLimit(buf, rowsizesSize).asIntBuffer()); int colsizesSize = buf.getInt() * 4; colsizes = ThreadSafeIntBuffer.fromIntBuffer(sliceOrderLimit(buf, colsizesSize).asIntBuffer()); int roffSize = buf.getInt() * 4; roff = ThreadSafeIntBuffer.fromIntBuffer(sliceOrderLimit(buf, roffSize).asIntBuffer()); int coffSize = buf.getInt() * 4; coff = ThreadSafeIntBuffer.fromIntBuffer(sliceOrderLimit(buf, coffSize).asIntBuffer()); wavelettree = new ThreadSafeByteBuffer[getNumContexts()]; for (int i = 0; i < getNumContexts(); i++) { int wavelettreeSize = buf.getInt(); wavelettree[i] = null; if (wavelettreeSize != 0) { wavelettree[i] = ThreadSafeByteBuffer.fromByteBuffer(sliceOrderLimit(buf, wavelettreeSize)); } } } public void writeToFile(String path) throws IOException { FileOutputStream fos = new FileOutputStream(path); DataOutputStream os = new DataOutputStream(fos); writeToStream(os); } public void readFromFile(String path) throws IOException { FileInputStream fis = new FileInputStream(path); DataInputStream is = new DataInputStream(fis); readFromStream(is); } public void memoryMap(String path) throws IOException { File file = new File(path); long size = file.length(); FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel(); ByteBuffer buf = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size); readFromBuffer(buf); } protected byte[] toByteArray() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); writeToStream(new DataOutputStream(bos)); return bos.toByteArray(); } protected void fromByteArray(byte[] data) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(data); readFromStream(new DataInputStream(bis)); } /** * Serialize SuccinctBuffer to OutputStream. * * @param oos ObjectOutputStream to write to. * @throws IOException */ private void writeObject(ObjectOutputStream oos) throws IOException { resetBuffers(); writeToStream(new DataOutputStream(oos)); resetBuffers(); } /** * Deserialize SuccinctBuffer from InputStream. * * @param ois ObjectInputStream to read from. * @throws IOException */ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { Tables.init(); readFromStream(new DataInputStream(ois)); } /** * Reposition all byte buffers to their respective starting positions. */ protected void resetBuffers() { metadata.order(ByteOrder.BIG_ENDIAN).rewind(); alphabetmap.order(ByteOrder.BIG_ENDIAN).rewind(); contextmap.rewind(); alphabet.rewind(); sa.rewind(); isa.rewind(); neccol.rewind(); necrow.rewind(); rowoffsets.rewind(); coloffsets.rewind(); celloffsets.rewind(); rowsizes.rewind(); colsizes.rewind(); roff.rewind(); coff.rewind(); for(int i = 0; i < wavelettree.length; i++) { if(wavelettree[i] != null) { wavelettree[i].order(ByteOrder.BIG_ENDIAN).rewind(); } } } }
Added comments
core/src/main/java/edu/berkeley/cs/succinct/SuccinctCore.java
Added comments
Java
apache-2.0
702982c6685094449d58882f390e9fe4eb100625
0
zibhub/GNDMS,zibhub/GNDMS,zibhub/GNDMS,zibhub/GNDMS
package de.zib.gndms.GORFX.service; import de.zib.gndms.GORFX.service.util.WidAux; import de.zib.gndms.common.GORFX.service.TaskFlowService; import de.zib.gndms.common.model.gorfx.types.*; import de.zib.gndms.common.rest.*; import de.zib.gndms.common.stuff.devel.NotYetImplementedException; import de.zib.gndms.gndmc.gorfx.TaskClient; import de.zib.gndms.kit.security.SpringSecurityContextHolder; import de.zib.gndms.logic.model.TaskAction; import de.zib.gndms.logic.model.TaskExecutionService; import de.zib.gndms.logic.model.gorfx.taskflow.TaskFlowAux; import de.zib.gndms.logic.model.gorfx.taskflow.TaskFlowFactory; import de.zib.gndms.logic.model.gorfx.taskflow.TaskFlowProvider; import de.zib.gndms.logic.model.gorfx.taskflow.UnsatisfiableOrderException; import de.zib.gndms.model.common.NoSuchResourceException; import de.zib.gndms.model.common.PermissionInfo; import de.zib.gndms.model.common.PersistentContract; import de.zib.gndms.model.gorfx.types.DelegatingOrder; import de.zib.gndms.neomodel.common.Dao; import de.zib.gndms.neomodel.gorfx.TaskBuilder; import de.zib.gndms.neomodel.gorfx.TaskFlow; import de.zib.gndms.neomodel.gorfx.Taskling; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.util.*; /* * Copyright 2008-2011 Zuse Institute Berlin (ZIB) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author try ma ik jo rr a zib * @date 13.01.2011 15:17:47 * * @brief A controller for a REST taskflow resource which implements the * TaskFlowService interface. * * The taskflow service acts as interface to instantiated taskflow * resources. The instantiation or creation happens through the GORFX * service itself. * * This implicates that all method invocation concern a single * taskflow, not the service as a whole. */ @Controller @RequestMapping( "/gorfx" ) public class TaskFlowServiceImpl implements TaskFlowService { // private ORQDao orqDao; private String localBaseUrl; private String baseUrl; // inject or read from properties, doesn't contain gorfx postfix private TaskFlowProvider taskFlowProvider; private final List<String> facetsNames = new ArrayList<String>( 6 ); private UriFactory uriFactory; private TaskClient taskClient; private final Logger logger = LoggerFactory.getLogger( this.getClass() ); private TaskExecutionService executorService; private Dao dao; @PostConstruct public void init() { facetsNames.add( "order" ); facetsNames.add( "quote" ); facetsNames.add( "task" ); facetsNames.add( "result" ); facetsNames.add( "status" ); facetsNames.add( "errors" ); uriFactory = new UriFactory(baseUrl); taskClient.setServiceURL( localBaseUrl ); } @RequestMapping( value = "/_{type}/_{id}", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Facets> getFacets( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn ) { Map<String, String> uriargs = taskFlowUriMap( type, id ); GNDMSResponseHeader header = new GNDMSResponseHeader( uriFactory.taskFlowTypeUri( uriargs, null ), null, baseUrl, dn, null ); if ( taskFlowProvider.exists( type ) ) { TaskFlow tf = taskFlowProvider.getFactoryForTaskFlow( type ).find( id ); if ( tf != null ) { ArrayList<Facet> fl = new ArrayList<Facet>( 6 ); for ( String f : facetsNames ) { String fn = uriFactory.taskFlowUri( uriargs, f ); fl.add( new Facet( f, fn ) ); } return new ResponseEntity<Facets>( new Facets( fl ), header, HttpStatus.OK ); } else logger.debug( "request for non existing " + type + ": " + id ); } else logger.debug( "request for non existing type " + type + ": " + id ); return new ResponseEntity<Facets>( new Facets( ), header, HttpStatus.NOT_FOUND ); } @RequestMapping( value = "/_{type}/_{id}", method = RequestMethod.DELETE ) @Secured( "ROLE_USER" ) public ResponseEntity< Integer > deleteTaskflow( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { logger.debug( "removing " + type + " taskflow: " + id ); HttpStatus hs = HttpStatus.NOT_FOUND; if ( taskFlowProvider.exists( type ) ) { TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); TaskFlow tf = tff.find( id ); if ( tf != null ) { if ( tf.hasTaskling() ) taskClient.deleteTask( tf.getTaskling().getId(), dn, wid ); tff.delete( id ); hs = HttpStatus.OK; } } return new ResponseEntity< Integer >( new Integer( 0 ), getHeader( type, id, null, dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/order", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Order> getOrder( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; Order order = null; try { TaskFlow tf = findTF( type, id ); order = tf.getOrder().getOrderBean(); if ( order != null ) hs = HttpStatus.OK; } catch ( NoSuchResourceException e ) { /* intentionally */ } return new ResponseEntity<Order>( order, getHeader( type, id, "order", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/order", method = RequestMethod.POST ) @Secured( "ROLE_USER" ) public ResponseEntity<Void> setOrder( @PathVariable String type, @PathVariable String id, @RequestBody Order orq, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; if ( taskFlowProvider.exists( type ) ) { final TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); final TaskFlow tf = tff.find( id ); if ( tf != null ) hs = TaskFlowServiceAux.setAndValidateOrder( orq, tf, tff ); } return new ResponseEntity<Void>( null, getHeader( type, id, "order", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/quote", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<List<Specifier<Quote>>> getQuotes( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { WidAux.initWid( wid ); logger.debug( "quote called" ); HttpStatus hs = HttpStatus.NOT_FOUND; List<Specifier<Quote>> res = null; if ( taskFlowProvider.exists( type ) ) { TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); TaskFlow tf = tff.find( id ); if ( tf != null ) { try { List<Quote> quoteList = TaskFlowServiceAux.createQuotes( tff, tf ); res = new ArrayList<Specifier<Quote>>( quoteList.size() ); HashMap<String, String> urimap = new HashMap<String, String>( 3 ); urimap.put( "service", "gorfx" ); urimap.put( UriFactory.TASKFLOW_ID, id ); urimap.put( "type", type ); for ( int i = 0; i < quoteList.size(); ++i ) { urimap.put( "idx", String.valueOf( i ) ); Specifier<Quote> sq = new Specifier<Quote>(); sq.setUriMap( Collections.unmodifiableMap( urimap ) ); sq.setUrl( uriFactory.quoteUri( urimap ) ); sq.setPayload( quoteList.get( i ) ); res.add( sq ); } hs = HttpStatus.OK; } catch ( UnsatisfiableOrderException e ) { DelegatingOrder o = tf.getOrder(); logger.debug( "Unsatisfiable order: " + o.getLoggableDescription() ); tf.setUnfulfillableOrder( true ); hs = HttpStatus.BAD_REQUEST; } catch ( Exception e ) { logger.warn( "Exception on order calculation for " + tf.getOrder() .getLoggableDescription(), e ); hs = HttpStatus.INTERNAL_SERVER_ERROR; } } } WidAux.removeWid(); return new ResponseEntity<List<Specifier<Quote>>>( res, getHeader( type, id, "quote", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/quote", method = RequestMethod.POST ) @Secured( "ROLE_USER" ) public ResponseEntity<Integer> setQuote( @PathVariable String type, @PathVariable String id, @RequestBody Quote cont, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; try { TaskFlow tf = findTF( type, id ); tf.setPreferredQuote( cont ); hs = HttpStatus.OK; } catch ( NoSuchResourceException e ) { } return new ResponseEntity<Integer>( 37, getHeader( type, id, "quote", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/quote/_{idx}", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Quote> getQuote( @PathVariable String type, @PathVariable String id, @PathVariable int idx, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; Quote quote = null; try { TaskFlow tf = findTF( type, id ); List<Quote> quoteList = tf.getQuotes(); if ( quoteList != null && idx >= 0 && idx < quoteList.size() ) { quote = quoteList.get( idx ); hs = HttpStatus.OK; } } catch ( NoSuchResourceException e ) { // intentionally } return new ResponseEntity<Quote>( quote, getHeader( type, id, "quote", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/quote/_{idx}", method = RequestMethod.DELETE ) @Secured( "ROLE_USER" ) public ResponseEntity< Integer > deleteQuotes( @PathVariable String type, @PathVariable String id, @PathVariable int idx, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { throw new NotYetImplementedException(); // together with the ProperlyNeverWillBeException } @RequestMapping( value = "/_{type}/_{id}/task", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Specifier<Facets>> getTask( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; Specifier<Facets> spec = null; WidAux.initWid( wid ); try { TaskFlow tf = findTF( type, id ); Taskling t = tf.getTaskling(); if ( t != null ) { logger.debug( "getTask task called" ); spec = TaskClient.TaskServiceAux .getTaskSpecifier( taskClient, t.getId(), uriFactory, taskFlowUriMap( type, id ), dn ); hs = HttpStatus.OK; } } catch ( Exception e ) { logger.warn( "Exception while getting task", e ); } logger.debug( "returning with " + hs.name() ); WidAux.removeWid(); return new ResponseEntity<Specifier<Facets>>( spec, getHeader( type, id, "task", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/task", method = RequestMethod.PUT ) @Secured( "ROLE_USER" ) public ResponseEntity<Specifier<Facets>> createTask( @PathVariable String type, @PathVariable String id, @RequestParam( value = "quote", required = false ) Integer quoteId, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; WidAux.initWid( wid ); logger.debug( "create task called" ); HttpHeaders headers = getHeader( type, id, "task", dn, wid ); if ( taskFlowProvider.exists( type ) ) { TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); TaskFlow tf = tff.find( id ); if ( tf != null ) { if ( tf.getTaskling() != null ) hs = HttpStatus.CONFLICT; else { tf.getOrder().setSecurityContextHolder( new SpringSecurityContextHolder( SecurityContextHolder.getContext() ) ); TaskAction ta = tff.createAction(); Taskling taskling; if ( tf.hasQuotes() ) { logger.debug( "submitting using quote: " + quoteId); taskling = submitTaskActionWithQuotes( quoteId, tf, ta, wid ); } else taskling = executorService.submitTaskAction( dao, ta, tf.getOrder(), wid ); hs = HttpStatus.CREATED; Specifier<Facets> spec = null; try { spec = TaskClient.TaskServiceAux .getTaskSpecifier( taskClient, taskling.getId(), uriFactory, taskFlowUriMap( type, id ), dn ); } catch ( Exception e ) { logger.warn( "Exception while getting task", e ); } return new ResponseEntity<Specifier<Facets>>( spec, headers, hs ); } } } logger.debug( "Problem, returning " + hs.name() ); WidAux.removeWid(); return new ResponseEntity<Specifier<Facets>>( null, headers, hs ); } private Taskling submitTaskActionWithQuotes( final Integer quoteId, final TaskFlow tf, final TaskAction ta, final String wid ) { Taskling taskling;List<Quote> quotes = tf.getQuotes(); Quote quote = quoteId != null && quoteId >= 0 && quoteId < quotes.size() ? quotes.get( quoteId ) : quotes.get( 0 ); taskling = executorService.submitTaskAction( dao, ta, new TaskBuilder().setOrder( tf.getOrder() ) .setContract( PersistentContract.acceptQuoteNow( quote ) ) .setPermissionInfo( new PermissionInfo( "default", "PermissionConfiglet" ) ) , wid ); return taskling; } @RequestMapping( value = "/_{type}/_{id}/status", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<TaskFlowStatus> getStatus( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; TaskFlowStatus tfs = null; try { TaskFlow tf = findTF( type, id ); tfs = TaskFlowAux.statusFromTaskFlow( dao, tf ); Taskling t = tf.getTaskling(); if ( t != null ) { // maybe call task client Specifier<Void> spec = new Specifier<Void>(); Map<String, String> urimap = taskUriMap( type, id, t ); spec.setUrl( uriFactory.taskUri( urimap, "status" ) ); spec.setUriMap( urimap ); tfs.setTaskSpecifier( spec ); hs = HttpStatus.OK; } } catch ( NoSuchResourceException e ) { // intentionally } return new ResponseEntity<TaskFlowStatus>( tfs, getHeader( type, id, "status", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/result", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Specifier<TaskResult>> getResult( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; Specifier<TaskResult> spec = null; try { spec = createTaskSpecifier( TaskResult.class, type, id, "result" ); ResponseEntity<TaskResult> res = taskClient.getResult( spec.getUriMap().get( "taskId" ), dn, wid ); if ( HttpStatus.OK.equals( res.getStatusCode() ) ) { spec.setPayload( res.getBody() ); hs = HttpStatus.OK; } else spec = null; } catch ( NoSuchResourceException e ) { // intentionally } return new ResponseEntity<Specifier<TaskResult>>( spec, getHeader( type, id, "result", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/errors", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<TaskFlowFailure> getErrors( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; TaskFlowFailureImpl taskFlowFailure = new TaskFlowFailureImpl(); try { Specifier<TaskFailure> spec = createTaskSpecifier( TaskFailure.class, type, id, "errors" ); ResponseEntity<TaskFailure> res = taskClient.getErrors( spec.getUriMap().get( "taskId" ), dn, wid ); if ( res.getStatusCode() == HttpStatus.OK ) { spec.setPayload( res.getBody() ); hs = HttpStatus.OK; } } catch ( NoSuchResourceException e ) { // intentionally } return new ResponseEntity<TaskFlowFailure>( taskFlowFailure, getHeader( type, id, "result", dn, wid ), hs ); } protected GNDMSResponseHeader getHeader( String type, String id, String facet, String dn, String wid ) { Map<String, String> uriargs = taskFlowUriMap( type, id ); return new GNDMSResponseHeader( uriFactory.taskFlowTypeUri( uriargs, facet ), facet, baseUrl, dn, wid ); } private Map<String, String> taskFlowUriMap( String type, String id ) { HashMap<String, String> urimap = new HashMap<String, String>( 3 ); urimap.put( UriFactory.SERVICE, "gorfx" ); urimap.put( UriFactory.TASKFLOW_TYPE, type ); urimap.put( UriFactory.TASKFLOW_ID, id ); return urimap; } private Map<String, String> taskUriMap( String type, String id, Taskling t ) { return TaskClient.TaskServiceAux.taskUriMap( t.getId(), taskFlowUriMap( type, id ) ); } private <T> Specifier<T> createTaskSpecifier( Class<T> resClass, String type, String id, String facet ) throws NoSuchResourceException { final TaskFlow tf = findTF( type, id ); final Taskling t = tf.getTaskling(); final Map<String, String> urimap = taskUriMap( type, id, t ); final Specifier<T> spec; if ( t != null ) { spec = new Specifier<T>(); spec.setUrl( uriFactory.taskUri( urimap, facet ) ); spec.setUriMap( urimap ); } else throw new NoSuchResourceException( "task", urimap ); return spec; } protected TaskFlow findTF( String type, String id ) throws NoSuchResourceException { if ( taskFlowProvider.exists( type ) ) { TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); TaskFlow tf = tff.find( id ); if ( tf != null ) return tf; else return TaskFlowServiceAux.fromTask( dao, taskFlowProvider, type, id ); } throw new NoSuchResourceException(); } public Dao getDao() { return dao; } @Inject public void setDao( Dao dao ) { this.dao = dao; } public TaskExecutionService getExecutorService() { return executorService; } @Inject public void setExecutorService( TaskExecutionService executorService ) { this.executorService = executorService; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public void setLocalBaseUrl( String localBaseUrl ) { this.localBaseUrl = localBaseUrl; } @Inject public void setTaskFlowProvider( TaskFlowProvider taskFlowProvider ) { this.taskFlowProvider = taskFlowProvider; } @Inject public void setTaskClient( TaskClient taskClient ) { this.taskClient = taskClient; } }
gorfx/src/de/zib/gndms/GORFX/service/TaskFlowServiceImpl.java
package de.zib.gndms.GORFX.service; import de.zib.gndms.GORFX.service.util.WidAux; import de.zib.gndms.common.GORFX.service.TaskFlowService; import de.zib.gndms.common.model.gorfx.types.*; import de.zib.gndms.common.rest.*; import de.zib.gndms.common.stuff.devel.NotYetImplementedException; import de.zib.gndms.gndmc.gorfx.TaskClient; import de.zib.gndms.kit.security.SpringSecurityContextHolder; import de.zib.gndms.logic.model.TaskAction; import de.zib.gndms.logic.model.TaskExecutionService; import de.zib.gndms.logic.model.gorfx.taskflow.TaskFlowAux; import de.zib.gndms.logic.model.gorfx.taskflow.TaskFlowFactory; import de.zib.gndms.logic.model.gorfx.taskflow.TaskFlowProvider; import de.zib.gndms.logic.model.gorfx.taskflow.UnsatisfiableOrderException; import de.zib.gndms.model.common.NoSuchResourceException; import de.zib.gndms.model.common.PermissionInfo; import de.zib.gndms.model.common.PersistentContract; import de.zib.gndms.model.gorfx.types.DelegatingOrder; import de.zib.gndms.neomodel.common.Dao; import de.zib.gndms.neomodel.gorfx.TaskBuilder; import de.zib.gndms.neomodel.gorfx.TaskFlow; import de.zib.gndms.neomodel.gorfx.Taskling; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.util.*; /* * Copyright 2008-2011 Zuse Institute Berlin (ZIB) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author try ma ik jo rr a zib * @date 13.01.2011 15:17:47 * * @brief A controller for a REST taskflow resource which implements the * TaskFlowService interface. * * The taskflow service acts as interface to instantiated taskflow * resources. The instantiation or creation happens through the GORFX * service itself. * * This implicates that all method invocation concern a single * taskflow, not the service as a whole. */ @Controller @RequestMapping( "/gorfx" ) public class TaskFlowServiceImpl implements TaskFlowService { // private ORQDao orqDao; private String localBaseUrl; private String baseUrl; // inject or read from properties, doesn't contain gorfx postfix private TaskFlowProvider taskFlowProvider; private final List<String> facetsNames = new ArrayList<String>( 6 ); private UriFactory uriFactory; private TaskClient taskClient; private final Logger logger = LoggerFactory.getLogger( this.getClass() ); private TaskExecutionService executorService; private Dao dao; @PostConstruct public void init() { facetsNames.add( "order" ); facetsNames.add( "quote" ); facetsNames.add( "task" ); facetsNames.add( "result" ); facetsNames.add( "status" ); facetsNames.add( "errors" ); uriFactory = new UriFactory(baseUrl); taskClient.setServiceURL( localBaseUrl ); } @RequestMapping( value = "/_{type}/_{id}", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Facets> getFacets( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn ) { Map<String, String> uriargs = taskFlowUriMap( type, id ); GNDMSResponseHeader header = new GNDMSResponseHeader( uriFactory.taskFlowTypeUri( uriargs, null ), null, baseUrl, dn, null ); if ( taskFlowProvider.exists( type ) ) { TaskFlow tf = taskFlowProvider.getFactoryForTaskFlow( type ).find( id ); if ( tf != null ) { ArrayList<Facet> fl = new ArrayList<Facet>( 6 ); for ( String f : facetsNames ) { String fn = uriFactory.taskFlowUri( uriargs, f ); fl.add( new Facet( f, fn ) ); } return new ResponseEntity<Facets>( new Facets( fl ), header, HttpStatus.OK ); } else logger.debug( "request for non existing " + type + ": " + id ); } else logger.debug( "request for non existing type " + type + ": " + id ); return new ResponseEntity<Facets>( new Facets( ), header, HttpStatus.NOT_FOUND ); } @RequestMapping( value = "/_{type}/_{id}", method = RequestMethod.DELETE ) @Secured( "ROLE_USER" ) public ResponseEntity< Integer > deleteTaskflow( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { logger.debug( "removing " + type + " taskflow: " + id ); HttpStatus hs = HttpStatus.NOT_FOUND; if ( taskFlowProvider.exists( type ) ) { TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); TaskFlow tf = tff.find( id ); if ( tf != null ) { if ( tf.hasTaskling() ) taskClient.deleteTask( tf.getTaskling().getId(), dn, wid ); tff.delete( id ); hs = HttpStatus.OK; } } return new ResponseEntity< Integer >( null, getHeader( type, id, null, dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/order", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Order> getOrder( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; Order order = null; try { TaskFlow tf = findTF( type, id ); order = tf.getOrder().getOrderBean(); if ( order != null ) hs = HttpStatus.OK; } catch ( NoSuchResourceException e ) { /* intentionally */ } return new ResponseEntity<Order>( order, getHeader( type, id, "order", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/order", method = RequestMethod.POST ) @Secured( "ROLE_USER" ) public ResponseEntity<Void> setOrder( @PathVariable String type, @PathVariable String id, @RequestBody Order orq, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; if ( taskFlowProvider.exists( type ) ) { final TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); final TaskFlow tf = tff.find( id ); if ( tf != null ) hs = TaskFlowServiceAux.setAndValidateOrder( orq, tf, tff ); } return new ResponseEntity<Void>( null, getHeader( type, id, "order", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/quote", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<List<Specifier<Quote>>> getQuotes( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { WidAux.initWid( wid ); logger.debug( "quote called" ); HttpStatus hs = HttpStatus.NOT_FOUND; List<Specifier<Quote>> res = null; if ( taskFlowProvider.exists( type ) ) { TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); TaskFlow tf = tff.find( id ); if ( tf != null ) { try { List<Quote> quoteList = TaskFlowServiceAux.createQuotes( tff, tf ); res = new ArrayList<Specifier<Quote>>( quoteList.size() ); HashMap<String, String> urimap = new HashMap<String, String>( 3 ); urimap.put( "service", "gorfx" ); urimap.put( UriFactory.TASKFLOW_ID, id ); urimap.put( "type", type ); for ( int i = 0; i < quoteList.size(); ++i ) { urimap.put( "idx", String.valueOf( i ) ); Specifier<Quote> sq = new Specifier<Quote>(); sq.setUriMap( Collections.unmodifiableMap( urimap ) ); sq.setUrl( uriFactory.quoteUri( urimap ) ); sq.setPayload( quoteList.get( i ) ); res.add( sq ); } hs = HttpStatus.OK; } catch ( UnsatisfiableOrderException e ) { DelegatingOrder o = tf.getOrder(); logger.debug( "Unsatisfiable order: " + o.getLoggableDescription() ); tf.setUnfulfillableOrder( true ); hs = HttpStatus.BAD_REQUEST; } catch ( Exception e ) { logger.warn( "Exception on order calculation for " + tf.getOrder() .getLoggableDescription(), e ); hs = HttpStatus.INTERNAL_SERVER_ERROR; } } } WidAux.removeWid(); return new ResponseEntity<List<Specifier<Quote>>>( res, getHeader( type, id, "quote", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/quote", method = RequestMethod.POST ) @Secured( "ROLE_USER" ) public ResponseEntity<Integer> setQuote( @PathVariable String type, @PathVariable String id, @RequestBody Quote cont, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; try { TaskFlow tf = findTF( type, id ); tf.setPreferredQuote( cont ); hs = HttpStatus.OK; } catch ( NoSuchResourceException e ) { } return new ResponseEntity<Integer>( 37, getHeader( type, id, "quote", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/quote/_{idx}", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Quote> getQuote( @PathVariable String type, @PathVariable String id, @PathVariable int idx, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; Quote quote = null; try { TaskFlow tf = findTF( type, id ); List<Quote> quoteList = tf.getQuotes(); if ( quoteList != null && idx >= 0 && idx < quoteList.size() ) { quote = quoteList.get( idx ); hs = HttpStatus.OK; } } catch ( NoSuchResourceException e ) { // intentionally } return new ResponseEntity<Quote>( quote, getHeader( type, id, "quote", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/quote/_{idx}", method = RequestMethod.DELETE ) @Secured( "ROLE_USER" ) public ResponseEntity< Integer > deleteQuotes( @PathVariable String type, @PathVariable String id, @PathVariable int idx, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { throw new NotYetImplementedException(); // together with the ProperlyNeverWillBeException } @RequestMapping( value = "/_{type}/_{id}/task", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Specifier<Facets>> getTask( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; Specifier<Facets> spec = null; WidAux.initWid( wid ); try { TaskFlow tf = findTF( type, id ); Taskling t = tf.getTaskling(); if ( t != null ) { logger.debug( "getTask task called" ); spec = TaskClient.TaskServiceAux .getTaskSpecifier( taskClient, t.getId(), uriFactory, taskFlowUriMap( type, id ), dn ); hs = HttpStatus.OK; } } catch ( Exception e ) { logger.warn( "Exception while getting task", e ); } logger.debug( "returning with " + hs.name() ); WidAux.removeWid(); return new ResponseEntity<Specifier<Facets>>( spec, getHeader( type, id, "task", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/task", method = RequestMethod.PUT ) @Secured( "ROLE_USER" ) public ResponseEntity<Specifier<Facets>> createTask( @PathVariable String type, @PathVariable String id, @RequestParam( value = "quote", required = false ) Integer quoteId, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; WidAux.initWid( wid ); logger.debug( "create task called" ); HttpHeaders headers = getHeader( type, id, "task", dn, wid ); if ( taskFlowProvider.exists( type ) ) { TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); TaskFlow tf = tff.find( id ); if ( tf != null ) { if ( tf.getTaskling() != null ) hs = HttpStatus.CONFLICT; else { tf.getOrder().setSecurityContextHolder( new SpringSecurityContextHolder( SecurityContextHolder.getContext() ) ); TaskAction ta = tff.createAction(); Taskling taskling; if ( tf.hasQuotes() ) { logger.debug( "submitting using quote: " + quoteId); taskling = submitTaskActionWithQuotes( quoteId, tf, ta, wid ); } else taskling = executorService.submitTaskAction( dao, ta, tf.getOrder(), wid ); hs = HttpStatus.CREATED; Specifier<Facets> spec = null; try { spec = TaskClient.TaskServiceAux .getTaskSpecifier( taskClient, taskling.getId(), uriFactory, taskFlowUriMap( type, id ), dn ); } catch ( Exception e ) { logger.warn( "Exception while getting task", e ); } return new ResponseEntity<Specifier<Facets>>( spec, headers, hs ); } } } logger.debug( "Problem, returning " + hs.name() ); WidAux.removeWid(); return new ResponseEntity<Specifier<Facets>>( null, headers, hs ); } private Taskling submitTaskActionWithQuotes( final Integer quoteId, final TaskFlow tf, final TaskAction ta, final String wid ) { Taskling taskling;List<Quote> quotes = tf.getQuotes(); Quote quote = quoteId != null && quoteId >= 0 && quoteId < quotes.size() ? quotes.get( quoteId ) : quotes.get( 0 ); taskling = executorService.submitTaskAction( dao, ta, new TaskBuilder().setOrder( tf.getOrder() ) .setContract( PersistentContract.acceptQuoteNow( quote ) ) .setPermissionInfo( new PermissionInfo( "default", "PermissionConfiglet" ) ) , wid ); return taskling; } @RequestMapping( value = "/_{type}/_{id}/status", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<TaskFlowStatus> getStatus( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; TaskFlowStatus tfs = null; try { TaskFlow tf = findTF( type, id ); tfs = TaskFlowAux.statusFromTaskFlow( dao, tf ); Taskling t = tf.getTaskling(); if ( t != null ) { // maybe call task client Specifier<Void> spec = new Specifier<Void>(); Map<String, String> urimap = taskUriMap( type, id, t ); spec.setUrl( uriFactory.taskUri( urimap, "status" ) ); spec.setUriMap( urimap ); tfs.setTaskSpecifier( spec ); hs = HttpStatus.OK; } } catch ( NoSuchResourceException e ) { // intentionally } return new ResponseEntity<TaskFlowStatus>( tfs, getHeader( type, id, "status", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/result", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<Specifier<TaskResult>> getResult( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; Specifier<TaskResult> spec = null; try { spec = createTaskSpecifier( TaskResult.class, type, id, "result" ); ResponseEntity<TaskResult> res = taskClient.getResult( spec.getUriMap().get( "taskId" ), dn, wid ); if ( HttpStatus.OK.equals( res.getStatusCode() ) ) { spec.setPayload( res.getBody() ); hs = HttpStatus.OK; } else spec = null; } catch ( NoSuchResourceException e ) { // intentionally } return new ResponseEntity<Specifier<TaskResult>>( spec, getHeader( type, id, "result", dn, wid ), hs ); } @RequestMapping( value = "/_{type}/_{id}/errors", method = RequestMethod.GET ) @Secured( "ROLE_USER" ) public ResponseEntity<TaskFlowFailure> getErrors( @PathVariable String type, @PathVariable String id, @RequestHeader( "DN" ) String dn, @RequestHeader( "WId" ) String wid ) { HttpStatus hs = HttpStatus.NOT_FOUND; TaskFlowFailureImpl taskFlowFailure = new TaskFlowFailureImpl(); try { Specifier<TaskFailure> spec = createTaskSpecifier( TaskFailure.class, type, id, "errors" ); ResponseEntity<TaskFailure> res = taskClient.getErrors( spec.getUriMap().get( "taskId" ), dn, wid ); if ( res.getStatusCode() == HttpStatus.OK ) { spec.setPayload( res.getBody() ); hs = HttpStatus.OK; } } catch ( NoSuchResourceException e ) { // intentionally } return new ResponseEntity<TaskFlowFailure>( taskFlowFailure, getHeader( type, id, "result", dn, wid ), hs ); } protected GNDMSResponseHeader getHeader( String type, String id, String facet, String dn, String wid ) { Map<String, String> uriargs = taskFlowUriMap( type, id ); return new GNDMSResponseHeader( uriFactory.taskFlowTypeUri( uriargs, facet ), facet, baseUrl, dn, wid ); } private Map<String, String> taskFlowUriMap( String type, String id ) { HashMap<String, String> urimap = new HashMap<String, String>( 3 ); urimap.put( UriFactory.SERVICE, "gorfx" ); urimap.put( UriFactory.TASKFLOW_TYPE, type ); urimap.put( UriFactory.TASKFLOW_ID, id ); return urimap; } private Map<String, String> taskUriMap( String type, String id, Taskling t ) { return TaskClient.TaskServiceAux.taskUriMap( t.getId(), taskFlowUriMap( type, id ) ); } private <T> Specifier<T> createTaskSpecifier( Class<T> resClass, String type, String id, String facet ) throws NoSuchResourceException { final TaskFlow tf = findTF( type, id ); final Taskling t = tf.getTaskling(); final Map<String, String> urimap = taskUriMap( type, id, t ); final Specifier<T> spec; if ( t != null ) { spec = new Specifier<T>(); spec.setUrl( uriFactory.taskUri( urimap, facet ) ); spec.setUriMap( urimap ); } else throw new NoSuchResourceException( "task", urimap ); return spec; } protected TaskFlow findTF( String type, String id ) throws NoSuchResourceException { if ( taskFlowProvider.exists( type ) ) { TaskFlowFactory tff = taskFlowProvider.getFactoryForTaskFlow( type ); TaskFlow tf = tff.find( id ); if ( tf != null ) return tf; else return TaskFlowServiceAux.fromTask( dao, taskFlowProvider, type, id ); } throw new NoSuchResourceException(); } public Dao getDao() { return dao; } @Inject public void setDao( Dao dao ) { this.dao = dao; } public TaskExecutionService getExecutorService() { return executorService; } @Inject public void setExecutorService( TaskExecutionService executorService ) { this.executorService = executorService; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public void setLocalBaseUrl( String localBaseUrl ) { this.localBaseUrl = localBaseUrl; } @Inject public void setTaskFlowProvider( TaskFlowProvider taskFlowProvider ) { this.taskFlowProvider = taskFlowProvider; } @Inject public void setTaskClient( TaskClient taskClient ) { this.taskClient = taskClient; } }
Bugfix: no Content-Type in response
gorfx/src/de/zib/gndms/GORFX/service/TaskFlowServiceImpl.java
Bugfix: no Content-Type in response
Java
apache-2.0
ec4deb7224fc447b8ab04828c01cf97c5dcc498b
0
popstr/undertow,ctomc/undertow,jasonchaffee/undertow,stuartwdouglas/undertow,undertow-io/undertow,darranl/undertow,ctomc/undertow,stuartwdouglas/undertow,msfm/undertow,Karm/undertow,baranowb/undertow,aldaris/undertow,rogerchina/undertow,yonglehou/undertow,Karm/undertow,baranowb/undertow,emag/codereading-undertow,popstr/undertow,aradchykov/undertow,golovnin/undertow,jstourac/undertow,n1hility/undertow,wildfly-security-incubator/undertow,soul2zimate/undertow,stuartwdouglas/undertow,aldaris/undertow,yonglehou/undertow,aradchykov/undertow,pferraro/undertow,jamezp/undertow,undertow-io/undertow,jamezp/undertow,jasonchaffee/undertow,rhusar/undertow,wildfly-security-incubator/undertow,n1hility/undertow,rogerchina/undertow,rhatlapa/undertow,jstourac/undertow,biddyweb/undertow,golovnin/undertow,pferraro/undertow,jstourac/undertow,biddyweb/undertow,soul2zimate/undertow,msfm/undertow,TomasHofman/undertow,popstr/undertow,pedroigor/undertow,pedroigor/undertow,TomasHofman/undertow,amannm/undertow,darranl/undertow,marschall/undertow,jasonchaffee/undertow,nkhuyu/undertow,TomasHofman/undertow,rhusar/undertow,aradchykov/undertow,nkhuyu/undertow,darranl/undertow,amannm/undertow,grassjedi/undertow,rhatlapa/undertow,grassjedi/undertow,rhatlapa/undertow,rhusar/undertow,Karm/undertow,golovnin/undertow,marschall/undertow,nkhuyu/undertow,grassjedi/undertow,wildfly-security-incubator/undertow,rogerchina/undertow,msfm/undertow,n1hility/undertow,yonglehou/undertow,marschall/undertow,soul2zimate/undertow,baranowb/undertow,emag/codereading-undertow,aldaris/undertow,ctomc/undertow,amannm/undertow,biddyweb/undertow,pferraro/undertow,jamezp/undertow,undertow-io/undertow,pedroigor/undertow
/* * JBoss, Home of Professional Open Source. * Copyright 2013 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.server.handlers; import java.io.IOException; import java.nio.channels.Channel; import java.util.Deque; import io.undertow.UndertowLogger; import io.undertow.server.HttpCompletionHandler; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.CopyOnWriteMap; import io.undertow.util.Headers; import io.undertow.util.Methods; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.channels.ConnectedStreamChannel; import org.xnio.channels.StreamSinkChannel; /** * An HTTP request handler which upgrades the HTTP request and hands it off as a socket to any XNIO consumer. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ChannelUpgradeHandler implements HttpHandler { private final CopyOnWriteMap<String, ChannelListener<? super ConnectedStreamChannel>> handlers = new CopyOnWriteMap<String, ChannelListener<? super ConnectedStreamChannel>>(); private volatile HttpHandler nonUpgradeHandler = ResponseCodeHandler.HANDLE_404; /** * Add a protocol to this handler. * * @param productString the product string to match * @param openListener the open listener to call * @return {@code true} if this product string was not previously registered, {@code false} otherwise */ public boolean addProtocol(String productString, ChannelListener<? super ConnectedStreamChannel> openListener) { if (productString == null) { throw new IllegalArgumentException("productString is null"); } if (openListener == null) { throw new IllegalArgumentException("openListener is null"); } return handlers.putIfAbsent(productString, openListener) == null; } /** * Remove a protocol from this handler. * * @param productString the product string to match * @return the previously registered open listener, or {@code null} if none was registered */ public ChannelListener<? super ConnectedStreamChannel> removeProtocol(String productString) { return handlers.remove(productString); } /** * Get the non-upgrade delegate handler. * * @return the non-upgrade delegate handler */ public HttpHandler getNonUpgradeHandler() { return nonUpgradeHandler; } /** * Set the non-upgrade delegate handler. * * @param nonUpgradeHandler the non-upgrade delegate handler */ public void setNonUpgradeHandler(final HttpHandler nonUpgradeHandler) { HttpHandlers.handlerNotNull(nonUpgradeHandler); this.nonUpgradeHandler = nonUpgradeHandler; } public void handleRequest(final HttpServerExchange exchange, final HttpCompletionHandler completionHandler) { final Deque<String> upgradeStrings = exchange.getRequestHeaders().get(Headers.UPGRADE); if (upgradeStrings != null && exchange.getRequestMethod().equals(Methods.GET)) { for (String string : upgradeStrings) { final ChannelListener<? super ConnectedStreamChannel> listener = handlers.get(string); if (listener != null) { try { exchange.upgradeChannel(string); exchange.getRequestChannel().shutdownReads(); final StreamSinkChannel sinkChannel = exchange.getResponseChannelFactory().create(); sinkChannel.shutdownWrites(); if (!sinkChannel.flush()) { sinkChannel.getWriteSetter().set(ChannelListeners.<StreamSinkChannel>flushingChannelListener(new ChannelListener<Channel>() { public void handleEvent(final Channel channel) { ChannelListeners.invokeChannelListener(exchange.getConnection().getChannel(), listener); } }, null)); sinkChannel.resumeWrites(); } else { ChannelListeners.invokeChannelListener(exchange.getConnection().getChannel(), listener); } return; } catch (IOException e) { completionHandler.handleComplete(); UndertowLogger.REQUEST_LOGGER.debug("Exception handling request", e); } } } } final HttpHandler handler = nonUpgradeHandler; HttpHandlers.executeHandler(handler, exchange, completionHandler); } }
core/src/main/java/io/undertow/server/handlers/ChannelUpgradeHandler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.server.handlers; import io.undertow.server.HttpCompletionHandler; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.util.CopyOnWriteMap; import io.undertow.util.HeaderMap; import io.undertow.util.Headers; import java.nio.channels.Channel; import java.util.Deque; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.channels.ConnectedStreamChannel; import org.xnio.channels.StreamSinkChannel; import org.xnio.channels.SuspendableWriteChannel; /** * An HTTP request handler which upgrades the HTTP request and hands it off as a socket to any XNIO consumer. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ChannelUpgradeHandler implements HttpHandler { private final CopyOnWriteMap<String, ChannelListener<? super ConnectedStreamChannel>> handlers = new CopyOnWriteMap<String, ChannelListener<? super ConnectedStreamChannel>>(); private volatile HttpHandler nonUpgradeHandler; /** * Add a protocol to this handler. * * @param productString the product string to match * @param openListener the open listener to call * @return {@code true} if this product string was not previously registered, {@code false} otherwise */ public boolean addProtocol(String productString, ChannelListener<? super ConnectedStreamChannel> openListener) { if (productString == null) { throw new IllegalArgumentException("productString is null"); } if (openListener == null) { throw new IllegalArgumentException("openListener is null"); } return handlers.putIfAbsent(productString, openListener) == null; } /** * Remove a protocol from this handler. * * @param productString the product string to match * @return the previously registered open listener, or {@code null} if none was registered */ public ChannelListener<? super ConnectedStreamChannel> removeProtocol(String productString) { return handlers.remove(productString); } /** * Get the non-upgrade delegate handler. * * @return the non-upgrade delegate handler */ public HttpHandler getNonUpgradeHandler() { return nonUpgradeHandler; } /** * Set the non-upgrade delegate handler. * * @param nonUpgradeHandler the non-upgrade delegate handler */ public void setNonUpgradeHandler(final HttpHandler nonUpgradeHandler) { this.nonUpgradeHandler = nonUpgradeHandler; } public void handleRequest(final HttpServerExchange exchange, final HttpCompletionHandler completionHandler) { final Deque<String> upgradeStrings = exchange.getRequestHeaders().get(Headers.UPGRADE); if (upgradeStrings != null) for (String string : upgradeStrings) { final ChannelListener<? super ConnectedStreamChannel> listener = handlers.get(string); if (listener != null) { exchange.getRequestChannel().shutdownReads(); final StreamSinkChannel sinkChannel = exchange.getResponseChannelFactory().create(); if (! sinkChannel.flush()) { sinkChannel.getWriteSetter().set(ChannelListeners.<StreamSinkChannel>flushingChannelListener(new ChannelListener<Channel>() { public void handleEvent(final Channel channel) { ChannelListeners.invokeChannelListener(exchange.getConnection().getChannel(), listener); } }, null)); } exchange.upgradeChannel(string); return; } } final HttpHandler handler = nonUpgradeHandler; if (handler == null) { exchange.setResponseCode(404); completionHandler.handleComplete(); } else { HttpHandlers.executeHandler(handler, exchange, completionHandler); } } }
Fix some problems with the ChannelUpgradeHandler
core/src/main/java/io/undertow/server/handlers/ChannelUpgradeHandler.java
Fix some problems with the ChannelUpgradeHandler
Java
apache-2.0
37334470367beb18e4c0070a2181b4aa49544d9b
0
masaki-yamakawa/geode,masaki-yamakawa/geode,smgoller/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,smgoller/geode,smgoller/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,smgoller/geode,smgoller/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,smgoller/geode,masaki-yamakawa/geode,smgoller/geode
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.test.dunit; import static org.apache.geode.test.dunit.internal.AsyncThreadId.nextId; import static org.apache.geode.test.dunit.internal.DUnitLauncher.NUM_VMS; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.Callable; import org.apache.commons.lang3.ArrayUtils; import org.apache.logging.log4j.Logger; import org.apache.geode.internal.process.ProcessUtils; import org.apache.geode.logging.internal.log4j.api.LogService; import org.apache.geode.test.dunit.internal.ChildVMLauncher; import org.apache.geode.test.dunit.internal.IdentifiableCallable; import org.apache.geode.test.dunit.internal.IdentifiableRunnable; import org.apache.geode.test.dunit.internal.MethodInvokerResult; import org.apache.geode.test.dunit.internal.ProcessHolder; import org.apache.geode.test.dunit.internal.RemoteDUnitVMIF; import org.apache.geode.test.dunit.internal.StandAloneDUnitEnv; import org.apache.geode.test.dunit.internal.VMEventNotifier; import org.apache.geode.test.version.VersionManager; /** * This class represents a Java Virtual Machine that runs in a DistributedTest. */ @SuppressWarnings("serial,unused") public class VM implements Serializable { private static final Logger logger = LogService.getLogger(); public static final int CONTROLLER_VM = -1; public static final int DEFAULT_VM_COUNT = NUM_VMS; private static final Object[] EMPTY = new Object[0]; /** The host on which this VM runs */ private final Host host; /** The sequential id of this VM */ private final int id; /** The version of Geode used in this VM */ private String version; /** The hydra client for this VM */ private RemoteDUnitVMIF client; /** The state of this VM */ private volatile boolean available; private transient volatile ProcessHolder processHolder; private final transient ChildVMLauncher childVMLauncher; /** * Returns the {@code VM} identity. For {@link StandAloneDUnitEnv} the number returned is a * zero-based sequence representing the order in with the DUnit {@code VM}s were launched. */ public static int getVMId() { return DUnitEnv.get().getId(); } /** * @deprecated Please use {@link #getVMId()} instead. */ @Deprecated public static int getCurrentVMNum() { return DUnitEnv.get().getId(); } /** * Returns true if executed from the main JUnit VM. */ public static boolean isControllerVM() { return getCurrentVMNum() == CONTROLLER_VM; } /** * Returns true if executed from a DUnit VM. Returns false if executed from the main JUnit VM. */ public static boolean isVM() { return getCurrentVMNum() != CONTROLLER_VM; } /** * Returns a VM that runs in this DistributedTest. * * @param whichVM A zero-based identifier of the VM */ public static VM getVM(int whichVM) { return Host.getHost(0).getVM(whichVM); } /** * Returns a VM running the specified Geode version in this DistributedTest. * * @param version String specifying the Geode version * @param whichVM A zero-based identifier of the VM */ public static VM getVM(String version, int whichVM) { return Host.getHost(0).getVM(version, whichVM); } /** * Returns a collection of all DistributedTest VMs. */ public static List<VM> getAllVMs() { return Host.getHost(0).getAllVMs(); } /** * Returns the number of VMs that run in this DistributedTest. */ public static int getVMCount() { return Host.getHost(0).getVMCount(); } /** * Returns the DistributedTest Locator VM. */ public static VM getLocator() { return Host.getLocator(); } /** * Returns the DistributedTest Locator VM. */ public static VM getController() { return getVM(CONTROLLER_VM); } /** * Returns the machine name hosting this DistributedTest. */ public static String getHostName() { return Host.getHost(0).getHostName(); } /** * Returns the name of a VM for use in the RMI naming service or working directory on disk */ public static String getVMName(final String version, final int pid) { if (pid == -2) { return "locator"; } if (pid < 0 || VersionManager.isCurrentVersion(version)) { return "vm" + pid; } else { return "vm" + pid + "_v" + version; } } /** * Returns an array of all provided VMs. */ public static VM[] toArray(VM... vms) { return vms; } /** * Returns an array of all provided VMs. */ public static VM[] toArray(List<VM> vmList) { return vmList.toArray(new VM[0]); } /** * Returns an array of all provided VMs. */ public static VM[] toArray(List<VM> vmList, VM... vms) { return ArrayUtils.addAll(vmList.toArray(new VM[0]), vms); } /** * Returns an array of all provided VMs. */ public static VM[] toArray(VM[] vmArray, VM... vms) { return ArrayUtils.addAll(vmArray, vms); } /** * Registers a {@link VMEventListener}. */ public static void addVMEventListener(final VMEventListener listener) { getVMEventNotifier().addVMEventListener(listener); } /** * Deregisters a {@link VMEventListener}. */ public static void removeVMEventListener(final VMEventListener listener) { getVMEventNotifier().removeVMEventListener(listener); } public static String dumpThreads() { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); long[] allThreadIds = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(allThreadIds, true, true); StringBuilder dumpWriter = new StringBuilder(); Arrays.stream(threadInfos) .filter(Objects::nonNull) .forEach(dumpWriter::append); return dumpWriter.toString(); } private static VMEventNotifier getVMEventNotifier() { return Host.getHost(0).getVMEventNotifier(); } public VM(final Host host, final String version, final int id, final RemoteDUnitVMIF client, final ProcessHolder processHolder, final ChildVMLauncher childVMLauncher) { this.host = host; this.id = id; this.version = version; this.client = client; this.processHolder = processHolder; this.childVMLauncher = childVMLauncher; available = true; } /** * Returns the {@code Host} on which this {@code VM} is running. */ public Host getHost() { return host; } /** * Returns the version of Geode used in this VM. * * @see VersionManager#CURRENT_VERSION * @see Host#getVM(String, int) */ public String getVersion() { return version; } /** * Returns the VM id of this {@code VM}. */ public int getId() { return id; } /** * Returns the process id of this {@code VM}. */ public int getPid() { return invoke(() -> ProcessUtils.identifyPid()); } /** * Invokes a static zero-arg method with an {@link Object} or {@code void} return type in this * {@code VM}. If the return type of the method is {@code void}, {@code null} is returned. * * @param targetClass The class on which to invoke the method * @param methodName The name of the method to invoke * * @throws RMIException Wraps any underlying exception thrown while invoking the method in this VM * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead */ @Deprecated public <V> V invoke(final Class<?> targetClass, final String methodName) { checkAvailability(targetClass.getName(), methodName); return executeMethodOnClass(targetClass, methodName, new Object[0]); } /** * Asynchronously invokes a static zero-arg method with an {@code Object} or {@code void} return * type in this VM. If the return type of the method is {@code void}, {@code null} is returned. * * @param targetClass The class on which to invoke the method * @param methodName The name of the method to invoke * * @deprecated Please use {@link #invokeAsync(SerializableCallableIF)} instead */ @Deprecated public <V> AsyncInvocation<V> invokeAsync(final Class<?> targetClass, final String methodName) { return invokeAsync(targetClass, methodName, null); } /** * Invokes a static method with an {@link Object} or {@code void} return type in this VM. If the * return type of the method is {@code void}, {@code null} is returned. * * @param targetClass The class on which to invoke the method * @param methodName The name of the method to invoke * @param args Arguments passed to the method call (must be {@link Serializable}). * * @throws RMIException Wraps any underlying exception thrown while invoking the method in this * {@code VM} * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead */ @Deprecated public <V> V invoke(final Class<?> targetClass, final String methodName, final Object[] args) { checkAvailability(targetClass.getName(), methodName); return executeMethodOnClass(targetClass, methodName, args); } /** * Asynchronously invokes an instance method with an {@link Object} or {@code void} return type in * this {@code VM}. If the return type of the method is {@code void}, {@code null} is returned. * * @param targetObject The object on which to invoke the method * @param methodName The name of the method to invoke * @param args Arguments passed to the method call (must be {@link Serializable}). * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead */ @Deprecated public <V> AsyncInvocation<V> invokeAsync(final Object targetObject, final String methodName, final Object[] args) { return AsyncInvocation .<V>create(targetObject, methodName, () -> invoke(targetObject, methodName, args), this) .start(); } /** * Asynchronously invokes an instance method with an {@link Object} or {@code void} return type in * this {@code VM}. If the return type of the method is {@code void}, {@code null} is returned. * * @param targetClass The class on which to invoke the method * @param methodName The name of the method to invoke * @param args Arguments passed to the method call (must be {@link Serializable}). * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead */ @Deprecated public <V> AsyncInvocation<V> invokeAsync(final Class<?> targetClass, final String methodName, final Object[] args) { return AsyncInvocation .<V>create(targetClass, methodName, () -> invoke(targetClass, methodName, args), this) .start(); } /** * Invokes the {@code run} method of a {@link Runnable} in this VM. Recall that {@code run} takes * no arguments and has no return value. * * @param runnable The {@code Runnable} to be run * * @see SerializableRunnable */ public <V> AsyncInvocation<V> invokeAsync(final SerializableRunnableIF runnable) { IdentifiableRunnable target = new IdentifiableRunnable(nextId(), runnable); return AsyncInvocation .<V>create(target, () -> invoke(target, target.getMethodName(), EMPTY), this).start(); } /** * Invokes the {@code run} method of a {@link Runnable} in this VM. Recall that {@code run} takes * no arguments and has no return value. The {@code Runnable} is wrapped in a * {@link IdentifiableRunnable} having the given name so it shows up in DUnit logs. * * @param runnable The {@code Runnable} to be run * @param name The name of the {@code Runnable}, which will be logged in DUnit output * * @see SerializableRunnable */ public <V> AsyncInvocation<V> invokeAsync(final String name, final SerializableRunnableIF runnable) { IdentifiableRunnable target = new IdentifiableRunnable(nextId(), name, runnable); return AsyncInvocation .<V>create(target, () -> invoke(target, target.getMethodName(), EMPTY), this).start(); } /** * Invokes the {@code call} method of a {@link Callable} in this {@code VM}. * * @param callable The {@code Callable} to be run * @param name The name of the {@code Callable}, which will be logged in dunit output * * @see SerializableCallable */ public <V> AsyncInvocation<V> invokeAsync(final String name, final SerializableCallableIF<V> callable) { IdentifiableCallable<V> target = new IdentifiableCallable<>(nextId(), name, callable); return AsyncInvocation.create(target, () -> invoke(target, target.getMethodName(), EMPTY), this) .start(); } /** * Invokes the {@code call} method of a {@link Callable} in this {@code VM}. * * @param callable The {@code Callable} to be run * * @see SerializableCallable */ public <V> AsyncInvocation<V> invokeAsync(final SerializableCallableIF<V> callable) { IdentifiableCallable<V> target = new IdentifiableCallable<>(nextId(), callable); return AsyncInvocation.create(target, () -> invoke(target, target.getMethodName(), EMPTY), this) .start(); } /** * Invokes the {@code run} method of a {@link Runnable} in this {@code VM}. Recall that * {@code run} takes no arguments and has no return value. * * @param runnable The {@code Runnable} to be run * @param name The name of the {@code Runnable}, which will be logged in DUnit output * * @see SerializableRunnable */ public void invoke(final String name, final SerializableRunnableIF runnable) { checkAvailability(IdentifiableRunnable.class.getName(), "run"); executeMethodOnObject(new IdentifiableRunnable(name, runnable), "run", new Object[0]); } /** * Invokes the {@code run} method of a {@link Runnable} in this {@code VM}. Recall that * {@code run} takes no arguments and has no return value. * * @param runnable The {@code Runnable} to be run * * @see SerializableRunnable */ public void invoke(final SerializableRunnableIF runnable) { checkAvailability(runnable.getClass().getName(), "run"); executeMethodOnObject(runnable, "run", new Object[0]); } /** * Invokes the {@code call} method of a {@link Callable} in this {@code VM}. * * @param callable The {@code Callable} to be run * @param name The name of the {@code Callable}, which will be logged in DUnit output * * @see SerializableCallable */ public <V> V invoke(final String name, final SerializableCallableIF<V> callable) { checkAvailability(IdentifiableCallable.class.getName(), "call"); return executeMethodOnObject(new IdentifiableCallable<>(name, callable), "call", new Object[0]); } /** * Invokes the {@code call} method of a {@link Callable} in this {@code VM}. * * @param callable The {@code Callable} to be run * * @see SerializableCallable */ public <V> V invoke(final SerializableCallableIF<V> callable) { checkAvailability(callable.getClass().getName(), "call"); return executeMethodOnObject(callable, "call", new Object[0]); } /** * Invokes an instance method with no arguments on an object that is serialized into this * {@code VM}. The return type of the method can be either {@link Object} or {@code void}. If the * return type of the method is {@code void}, {@code null} is returned. * * @param targetObject The receiver of the method invocation * @param methodName The name of the method to invoke * * @throws RMIException Wraps any underlying exception thrown while invoking the method in this * {@code VM} * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead. */ @Deprecated public <V> V invoke(final Object targetObject, final String methodName) { checkAvailability(targetObject.getClass().getName(), methodName); return executeMethodOnObject(targetObject, methodName, new Object[0]); } /** * Invokes an instance method on an object that is serialized into this {@code VM}. The return * type of the method can be either {@link Object} or {@code void}. If the return type of the * method is {@code void}, {@code null} is returned. * * @param targetObject The receiver of the method invocation * @param methodName The name of the method to invoke * @param args Arguments passed to the method call (must be {@link Serializable}). * * @throws RMIException Wraps any underlying exception thrown while invoking the method in this * {@code VM} * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead. */ @Deprecated public <V> V invoke(final Object targetObject, final String methodName, final Object[] args) { checkAvailability(targetObject.getClass().getName(), methodName); return executeMethodOnObject(targetObject, methodName, args); } /** * Restart an unavailable VM */ public synchronized void makeAvailable() { if (!available) { available = true; bounce(); } } /** * Synchronously bounces (nice kill and restarts) this {@code VM}. Concurrent bounce attempts are * synchronized but attempts to invoke methods on a bouncing {@code VM} will cause test failure. * Tests using bounce should be placed at the end of the DUnit test suite, since an exception here * will cause all tests using the unsuccessfully bounced {@code VM} to fail. * * This method is currently not supported by the standalone DUnit runner. * * Note: bounce invokes shutdown hooks. * * @throws RMIException if an exception occurs while bouncing this {@code VM} */ public void bounce() { bounce(version, false); } /** * Synchronously bounces (forced kill and restarts) this {@code VM}. Concurrent bounce attempts * are * synchronized but attempts to invoke methods on a bouncing {@code VM} will cause test failure. * Tests using bounce should be placed at the end of the DUnit test suite, since an exception here * will cause all tests using the unsuccessfully bounced {@code VM} to fail. * * This method is currently not supported by the standalone DUnit runner. * * Note: Forced bounce does not invoke shutdown hooks. * * @throws RMIException if an exception occurs while bouncing this {@code VM} */ public void bounceForcibly() { bounce(version, true); } public void bounce(final String targetVersion) { bounce(targetVersion, false); } private synchronized void bounce(final String targetVersion, boolean force) { checkAvailability(getClass().getName(), "bounceVM"); logger.info("Bouncing {} old pid is {} and version is {}", id, getPid(), version); getVMEventNotifier().notifyBeforeBounceVM(this); available = false; try { if (force) { processHolder.killForcibly(); } else { SerializableRunnableIF runnable = () -> new Thread(() -> { try { // sleep before exit so that the rmi call is returned Thread.sleep(100); System.exit(0); } catch (InterruptedException e) { logger.error("VM bounce thread interrupted before exiting.", e); } }).start(); executeMethodOnObject(runnable, "run", new Object[0]); } processHolder.waitFor(); processHolder = childVMLauncher.launchVM(targetVersion, id, true); version = targetVersion; client = childVMLauncher.getStub(id); available = true; logger.info("Bounced {}. New pid is {} and version is {}", id, getPid(), version); getVMEventNotifier().notifyAfterBounceVM(this); } catch (InterruptedException | IOException | NotBoundException e) { throw new Error("Unable to restart VM " + id, e); } } private void checkAvailability(String className, String methodName) { if (!available) { throw new RMIException(this, className, methodName, new IllegalStateException("VM not available: " + this)); } } public File getWorkingDirectory() { return DUnitEnv.get().getWorkingDirectory(getVersion(), getId()); } @Override public String toString() { return "VM " + getId() + " running on " + getHost() + (VersionManager.isCurrentVersion(version) ? "" : (" with version " + version)); } private <V> V executeMethodOnObject(final Object targetObject, final String methodName, final Object[] args) { try { MethodInvokerResult result = client.executeMethodOnObject(targetObject, methodName, args); if (result.exceptionOccurred()) { throw new RMIException(this, targetObject.getClass().getName(), methodName, result.getException(), result.getStackTrace()); } return (V) result.getResult(); } catch (RemoteException exception) { throw new RMIException(this, targetObject.getClass().getName(), methodName, exception); } } private <V> V executeMethodOnClass(final Class<?> targetClass, final String methodName, final Object[] args) { try { MethodInvokerResult result = client.executeMethodOnClass(targetClass.getName(), methodName, args); if (result.exceptionOccurred()) { throw new RMIException(this, targetClass.getName(), methodName, result.getException(), result.getStackTrace()); } return (V) result.getResult(); } catch (RemoteException exception) { throw new RMIException(this, targetClass.getName(), methodName, exception); } } }
geode-dunit/src/main/java/org/apache/geode/test/dunit/VM.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.test.dunit; import static org.apache.geode.test.dunit.internal.AsyncThreadId.nextId; import static org.apache.geode.test.dunit.internal.DUnitLauncher.NUM_VMS; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.Callable; import org.apache.commons.lang3.ArrayUtils; import org.apache.logging.log4j.Logger; import org.apache.geode.internal.process.ProcessUtils; import org.apache.geode.logging.internal.log4j.api.LogService; import org.apache.geode.test.dunit.internal.ChildVMLauncher; import org.apache.geode.test.dunit.internal.IdentifiableCallable; import org.apache.geode.test.dunit.internal.IdentifiableRunnable; import org.apache.geode.test.dunit.internal.MethodInvokerResult; import org.apache.geode.test.dunit.internal.ProcessHolder; import org.apache.geode.test.dunit.internal.RemoteDUnitVMIF; import org.apache.geode.test.dunit.internal.StandAloneDUnitEnv; import org.apache.geode.test.dunit.internal.VMEventNotifier; import org.apache.geode.test.version.VersionManager; /** * This class represents a Java Virtual Machine that runs in a DistributedTest. */ @SuppressWarnings("serial,unused") public class VM implements Serializable { private static final Logger logger = LogService.getLogger(); public static final int CONTROLLER_VM = -1; public static final int DEFAULT_VM_COUNT = NUM_VMS; private static final Object[] EMPTY = new Object[0]; /** The host on which this VM runs */ private final Host host; /** The sequential id of this VM */ private final int id; /** The version of Geode used in this VM */ private String version; /** The hydra client for this VM */ private RemoteDUnitVMIF client; /** The state of this VM */ private volatile boolean available; private transient volatile ProcessHolder processHolder; private final transient ChildVMLauncher childVMLauncher; /** * Returns the {@code VM} identity. For {@link StandAloneDUnitEnv} the number returned is a * zero-based sequence representing the order in with the DUnit {@code VM}s were launched. */ public static int getVMId() { return DUnitEnv.get().getId(); } /** * @deprecated Please use {@link #getVMId()} instead. */ @Deprecated public static int getCurrentVMNum() { return DUnitEnv.get().getId(); } /** * Returns true if executed from the main JUnit VM. */ public static boolean isControllerVM() { return getCurrentVMNum() == CONTROLLER_VM; } /** * Returns true if executed from a DUnit VM. Returns false if executed from the main JUnit VM. */ public static boolean isVM() { return getCurrentVMNum() != CONTROLLER_VM; } /** * Returns a VM that runs in this DistributedTest. * * @param whichVM A zero-based identifier of the VM */ public static VM getVM(int whichVM) { return Host.getHost(0).getVM(whichVM); } /** * Returns a VM running the specified Geode version in this DistributedTest. * * @param version String specifying the Geode version * @param whichVM A zero-based identifier of the VM */ public static VM getVM(String version, int whichVM) { return Host.getHost(0).getVM(whichVM); } /** * Returns a collection of all DistributedTest VMs. */ public static List<VM> getAllVMs() { return Host.getHost(0).getAllVMs(); } /** * Returns the number of VMs that run in this DistributedTest. */ public static int getVMCount() { return Host.getHost(0).getVMCount(); } /** * Returns the DistributedTest Locator VM. */ public static VM getLocator() { return Host.getLocator(); } /** * Returns the DistributedTest Locator VM. */ public static VM getController() { return getVM(CONTROLLER_VM); } /** * Returns the machine name hosting this DistributedTest. */ public static String getHostName() { return Host.getHost(0).getHostName(); } /** * Returns the name of a VM for use in the RMI naming service or working directory on disk */ public static String getVMName(final String version, final int pid) { if (pid == -2) { return "locator"; } if (pid < 0 || VersionManager.isCurrentVersion(version)) { return "vm" + pid; } else { return "vm" + pid + "_v" + version; } } /** * Returns an array of all provided VMs. */ public static VM[] toArray(VM... vms) { return vms; } /** * Returns an array of all provided VMs. */ public static VM[] toArray(List<VM> vmList) { return vmList.toArray(new VM[0]); } /** * Returns an array of all provided VMs. */ public static VM[] toArray(List<VM> vmList, VM... vms) { return ArrayUtils.addAll(vmList.toArray(new VM[0]), vms); } /** * Returns an array of all provided VMs. */ public static VM[] toArray(VM[] vmArray, VM... vms) { return ArrayUtils.addAll(vmArray, vms); } /** * Registers a {@link VMEventListener}. */ public static void addVMEventListener(final VMEventListener listener) { getVMEventNotifier().addVMEventListener(listener); } /** * Deregisters a {@link VMEventListener}. */ public static void removeVMEventListener(final VMEventListener listener) { getVMEventNotifier().removeVMEventListener(listener); } public static String dumpThreads() { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); long[] allThreadIds = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(allThreadIds, true, true); StringBuilder dumpWriter = new StringBuilder(); Arrays.stream(threadInfos) .filter(Objects::nonNull) .forEach(dumpWriter::append); return dumpWriter.toString(); } private static VMEventNotifier getVMEventNotifier() { return Host.getHost(0).getVMEventNotifier(); } public VM(final Host host, final String version, final int id, final RemoteDUnitVMIF client, final ProcessHolder processHolder, final ChildVMLauncher childVMLauncher) { this.host = host; this.id = id; this.version = version; this.client = client; this.processHolder = processHolder; this.childVMLauncher = childVMLauncher; available = true; } /** * Returns the {@code Host} on which this {@code VM} is running. */ public Host getHost() { return host; } /** * Returns the version of Geode used in this VM. * * @see VersionManager#CURRENT_VERSION * @see Host#getVM(String, int) */ public String getVersion() { return version; } /** * Returns the VM id of this {@code VM}. */ public int getId() { return id; } /** * Returns the process id of this {@code VM}. */ public int getPid() { return invoke(() -> ProcessUtils.identifyPid()); } /** * Invokes a static zero-arg method with an {@link Object} or {@code void} return type in this * {@code VM}. If the return type of the method is {@code void}, {@code null} is returned. * * @param targetClass The class on which to invoke the method * @param methodName The name of the method to invoke * * @throws RMIException Wraps any underlying exception thrown while invoking the method in this VM * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead */ @Deprecated public <V> V invoke(final Class<?> targetClass, final String methodName) { checkAvailability(targetClass.getName(), methodName); return executeMethodOnClass(targetClass, methodName, new Object[0]); } /** * Asynchronously invokes a static zero-arg method with an {@code Object} or {@code void} return * type in this VM. If the return type of the method is {@code void}, {@code null} is returned. * * @param targetClass The class on which to invoke the method * @param methodName The name of the method to invoke * * @deprecated Please use {@link #invokeAsync(SerializableCallableIF)} instead */ @Deprecated public <V> AsyncInvocation<V> invokeAsync(final Class<?> targetClass, final String methodName) { return invokeAsync(targetClass, methodName, null); } /** * Invokes a static method with an {@link Object} or {@code void} return type in this VM. If the * return type of the method is {@code void}, {@code null} is returned. * * @param targetClass The class on which to invoke the method * @param methodName The name of the method to invoke * @param args Arguments passed to the method call (must be {@link Serializable}). * * @throws RMIException Wraps any underlying exception thrown while invoking the method in this * {@code VM} * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead */ @Deprecated public <V> V invoke(final Class<?> targetClass, final String methodName, final Object[] args) { checkAvailability(targetClass.getName(), methodName); return executeMethodOnClass(targetClass, methodName, args); } /** * Asynchronously invokes an instance method with an {@link Object} or {@code void} return type in * this {@code VM}. If the return type of the method is {@code void}, {@code null} is returned. * * @param targetObject The object on which to invoke the method * @param methodName The name of the method to invoke * @param args Arguments passed to the method call (must be {@link Serializable}). * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead */ @Deprecated public <V> AsyncInvocation<V> invokeAsync(final Object targetObject, final String methodName, final Object[] args) { return AsyncInvocation .<V>create(targetObject, methodName, () -> invoke(targetObject, methodName, args), this) .start(); } /** * Asynchronously invokes an instance method with an {@link Object} or {@code void} return type in * this {@code VM}. If the return type of the method is {@code void}, {@code null} is returned. * * @param targetClass The class on which to invoke the method * @param methodName The name of the method to invoke * @param args Arguments passed to the method call (must be {@link Serializable}). * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead */ @Deprecated public <V> AsyncInvocation<V> invokeAsync(final Class<?> targetClass, final String methodName, final Object[] args) { return AsyncInvocation .<V>create(targetClass, methodName, () -> invoke(targetClass, methodName, args), this) .start(); } /** * Invokes the {@code run} method of a {@link Runnable} in this VM. Recall that {@code run} takes * no arguments and has no return value. * * @param runnable The {@code Runnable} to be run * * @see SerializableRunnable */ public <V> AsyncInvocation<V> invokeAsync(final SerializableRunnableIF runnable) { IdentifiableRunnable target = new IdentifiableRunnable(nextId(), runnable); return AsyncInvocation .<V>create(target, () -> invoke(target, target.getMethodName(), EMPTY), this).start(); } /** * Invokes the {@code run} method of a {@link Runnable} in this VM. Recall that {@code run} takes * no arguments and has no return value. The {@code Runnable} is wrapped in a * {@link IdentifiableRunnable} having the given name so it shows up in DUnit logs. * * @param runnable The {@code Runnable} to be run * @param name The name of the {@code Runnable}, which will be logged in DUnit output * * @see SerializableRunnable */ public <V> AsyncInvocation<V> invokeAsync(final String name, final SerializableRunnableIF runnable) { IdentifiableRunnable target = new IdentifiableRunnable(nextId(), name, runnable); return AsyncInvocation .<V>create(target, () -> invoke(target, target.getMethodName(), EMPTY), this).start(); } /** * Invokes the {@code call} method of a {@link Callable} in this {@code VM}. * * @param callable The {@code Callable} to be run * @param name The name of the {@code Callable}, which will be logged in dunit output * * @see SerializableCallable */ public <V> AsyncInvocation<V> invokeAsync(final String name, final SerializableCallableIF<V> callable) { IdentifiableCallable<V> target = new IdentifiableCallable<>(nextId(), name, callable); return AsyncInvocation.create(target, () -> invoke(target, target.getMethodName(), EMPTY), this) .start(); } /** * Invokes the {@code call} method of a {@link Callable} in this {@code VM}. * * @param callable The {@code Callable} to be run * * @see SerializableCallable */ public <V> AsyncInvocation<V> invokeAsync(final SerializableCallableIF<V> callable) { IdentifiableCallable<V> target = new IdentifiableCallable<>(nextId(), callable); return AsyncInvocation.create(target, () -> invoke(target, target.getMethodName(), EMPTY), this) .start(); } /** * Invokes the {@code run} method of a {@link Runnable} in this {@code VM}. Recall that * {@code run} takes no arguments and has no return value. * * @param runnable The {@code Runnable} to be run * @param name The name of the {@code Runnable}, which will be logged in DUnit output * * @see SerializableRunnable */ public void invoke(final String name, final SerializableRunnableIF runnable) { checkAvailability(IdentifiableRunnable.class.getName(), "run"); executeMethodOnObject(new IdentifiableRunnable(name, runnable), "run", new Object[0]); } /** * Invokes the {@code run} method of a {@link Runnable} in this {@code VM}. Recall that * {@code run} takes no arguments and has no return value. * * @param runnable The {@code Runnable} to be run * * @see SerializableRunnable */ public void invoke(final SerializableRunnableIF runnable) { checkAvailability(runnable.getClass().getName(), "run"); executeMethodOnObject(runnable, "run", new Object[0]); } /** * Invokes the {@code call} method of a {@link Callable} in this {@code VM}. * * @param callable The {@code Callable} to be run * @param name The name of the {@code Callable}, which will be logged in DUnit output * * @see SerializableCallable */ public <V> V invoke(final String name, final SerializableCallableIF<V> callable) { checkAvailability(IdentifiableCallable.class.getName(), "call"); return executeMethodOnObject(new IdentifiableCallable<>(name, callable), "call", new Object[0]); } /** * Invokes the {@code call} method of a {@link Callable} in this {@code VM}. * * @param callable The {@code Callable} to be run * * @see SerializableCallable */ public <V> V invoke(final SerializableCallableIF<V> callable) { checkAvailability(callable.getClass().getName(), "call"); return executeMethodOnObject(callable, "call", new Object[0]); } /** * Invokes an instance method with no arguments on an object that is serialized into this * {@code VM}. The return type of the method can be either {@link Object} or {@code void}. If the * return type of the method is {@code void}, {@code null} is returned. * * @param targetObject The receiver of the method invocation * @param methodName The name of the method to invoke * * @throws RMIException Wraps any underlying exception thrown while invoking the method in this * {@code VM} * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead. */ @Deprecated public <V> V invoke(final Object targetObject, final String methodName) { checkAvailability(targetObject.getClass().getName(), methodName); return executeMethodOnObject(targetObject, methodName, new Object[0]); } /** * Invokes an instance method on an object that is serialized into this {@code VM}. The return * type of the method can be either {@link Object} or {@code void}. If the return type of the * method is {@code void}, {@code null} is returned. * * @param targetObject The receiver of the method invocation * @param methodName The name of the method to invoke * @param args Arguments passed to the method call (must be {@link Serializable}). * * @throws RMIException Wraps any underlying exception thrown while invoking the method in this * {@code VM} * * @deprecated Please use {@link #invoke(SerializableCallableIF)} instead. */ @Deprecated public <V> V invoke(final Object targetObject, final String methodName, final Object[] args) { checkAvailability(targetObject.getClass().getName(), methodName); return executeMethodOnObject(targetObject, methodName, args); } /** * Restart an unavailable VM */ public synchronized void makeAvailable() { if (!available) { available = true; bounce(); } } /** * Synchronously bounces (nice kill and restarts) this {@code VM}. Concurrent bounce attempts are * synchronized but attempts to invoke methods on a bouncing {@code VM} will cause test failure. * Tests using bounce should be placed at the end of the DUnit test suite, since an exception here * will cause all tests using the unsuccessfully bounced {@code VM} to fail. * * This method is currently not supported by the standalone DUnit runner. * * Note: bounce invokes shutdown hooks. * * @throws RMIException if an exception occurs while bouncing this {@code VM} */ public void bounce() { bounce(version, false); } /** * Synchronously bounces (forced kill and restarts) this {@code VM}. Concurrent bounce attempts * are * synchronized but attempts to invoke methods on a bouncing {@code VM} will cause test failure. * Tests using bounce should be placed at the end of the DUnit test suite, since an exception here * will cause all tests using the unsuccessfully bounced {@code VM} to fail. * * This method is currently not supported by the standalone DUnit runner. * * Note: Forced bounce does not invoke shutdown hooks. * * @throws RMIException if an exception occurs while bouncing this {@code VM} */ public void bounceForcibly() { bounce(version, true); } public void bounce(final String targetVersion) { bounce(targetVersion, false); } private synchronized void bounce(final String targetVersion, boolean force) { checkAvailability(getClass().getName(), "bounceVM"); logger.info("Bouncing {} old pid is {} and version is {}", id, getPid(), version); getVMEventNotifier().notifyBeforeBounceVM(this); available = false; try { if (force) { processHolder.killForcibly(); } else { SerializableRunnableIF runnable = () -> new Thread(() -> { try { // sleep before exit so that the rmi call is returned Thread.sleep(100); System.exit(0); } catch (InterruptedException e) { logger.error("VM bounce thread interrupted before exiting.", e); } }).start(); executeMethodOnObject(runnable, "run", new Object[0]); } processHolder.waitFor(); processHolder = childVMLauncher.launchVM(targetVersion, id, true); version = targetVersion; client = childVMLauncher.getStub(id); available = true; logger.info("Bounced {}. New pid is {} and version is {}", id, getPid(), version); getVMEventNotifier().notifyAfterBounceVM(this); } catch (InterruptedException | IOException | NotBoundException e) { throw new Error("Unable to restart VM " + id, e); } } private void checkAvailability(String className, String methodName) { if (!available) { throw new RMIException(this, className, methodName, new IllegalStateException("VM not available: " + this)); } } public File getWorkingDirectory() { return DUnitEnv.get().getWorkingDirectory(getVersion(), getId()); } @Override public String toString() { return "VM " + getId() + " running on " + getHost() + (VersionManager.isCurrentVersion(version) ? "" : (" with version " + version)); } private <V> V executeMethodOnObject(final Object targetObject, final String methodName, final Object[] args) { try { MethodInvokerResult result = client.executeMethodOnObject(targetObject, methodName, args); if (result.exceptionOccurred()) { throw new RMIException(this, targetObject.getClass().getName(), methodName, result.getException(), result.getStackTrace()); } return (V) result.getResult(); } catch (RemoteException exception) { throw new RMIException(this, targetObject.getClass().getName(), methodName, exception); } } private <V> V executeMethodOnClass(final Class<?> targetClass, final String methodName, final Object[] args) { try { MethodInvokerResult result = client.executeMethodOnClass(targetClass.getName(), methodName, args); if (result.exceptionOccurred()) { throw new RMIException(this, targetClass.getName(), methodName, result.getException(), result.getStackTrace()); } return (V) result.getResult(); } catch (RemoteException exception) { throw new RMIException(this, targetClass.getName(), methodName, exception); } } }
GEODE-8544: Making VM class start versioned VM (#5559)
geode-dunit/src/main/java/org/apache/geode/test/dunit/VM.java
GEODE-8544: Making VM class start versioned VM (#5559)
Java
bsd-3-clause
da8025eb7a9f6bd4d9e4181996d57f3f9368f3d1
0
City-Outdoors/City-Outdoors-Android
package uk.co.jarofgreen.cityoutdoors.API; import org.apache.http.client.HttpClient; import java.io.File; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.SocketException; import java.net.UnknownHostException; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.sax.Element; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; import android.util.Log; import android.util.Xml; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.HttpHostConnectException; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.xml.sax.Attributes; import uk.co.jarofgreen.cityoutdoors.R; /** * * @author James Baster <james@jarofgreen.co.uk> * @copyright City of Edinburgh Council & James Baster * @license Open Source under the 3-clause BSD License * @url https://github.com/City-Outdoors/City-Outdoors-Android */ public abstract class BaseCall { Context context; public BaseCall(Context context) { super(); this.context = context; } protected String errorMessage; protected String errorCode; protected HttpClient httpclient; protected HttpPost httppost; protected MultipartEntity multipartEntity; protected HttpResponse response; protected HttpEntity entity; protected InputStream is; protected boolean isUserTokenAttached = false; protected void setUpCall(String url) { httpclient = new DefaultHttpClient(); httppost = new HttpPost(context.getString(R.string.server_url) + url); multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(context); int userID = settings.getInt("userID", -1); if (userID > 0) { addDataToCall("userID", userID); addDataToCall("userToken", settings.getString("userToken","")); isUserTokenAttached = true; } } protected void addDataToCall(String key, String value) { if (value != null) { try { multipartEntity.addPart(key, new StringBody(value)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } protected void addDataToCall(String key, Integer value) { if (value != null) { try { multipartEntity.addPart(key, new StringBody(Integer.toString(value))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } protected void addDataToCall(String key, Float value) { if (value != null) { try { multipartEntity.addPart(key, new StringBody(Float.toString(value))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } protected void addFileToCall(String key, String fileName) { multipartEntity.addPart(key, new FileBody(new File(fileName))); } protected void makeCall(RootElement root) { Element errorTag = root.getChild("error"); errorTag.setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { errorCode = attributes.getValue("code"); } }); errorTag.setEndTextElementListener(new EndTextElementListener(){ public void end(String body) { errorMessage = body; } }); try { httppost.setEntity(multipartEntity); response = httpclient.execute(httppost); entity = response.getEntity(); is = entity.getContent(); Xml.parse(is, Xml.Encoding.UTF_8, root.getContentHandler()); } catch (SocketException e) { errorCode = "A1"; errorMessage = "Can not connect to internet"; } catch (UnknownHostException e) { errorCode = "A2"; errorMessage = "Can not connect to internet"; } catch (Exception e) { throw new RuntimeException(e); } } public boolean hasError() { return (errorMessage != null) || (errorCode != null) ; } public String getErrorMessage() { return errorMessage; } public String getErrorCode() { return errorCode; } }
app/src/uk/co/jarofgreen/cityoutdoors/API/BaseCall.java
package uk.co.jarofgreen.cityoutdoors.API; import org.apache.http.client.HttpClient; import java.io.File; import java.io.InputStream; import java.io.UnsupportedEncodingException; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.sax.Element; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; import android.util.Log; import android.util.Xml; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.xml.sax.Attributes; import uk.co.jarofgreen.cityoutdoors.R; /** * * @author James Baster <james@jarofgreen.co.uk> * @copyright City of Edinburgh Council & James Baster * @license Open Source under the 3-clause BSD License * @url https://github.com/City-Outdoors/City-Outdoors-Android */ public abstract class BaseCall { Context context; public BaseCall(Context context) { super(); this.context = context; } protected String errorMessage; protected String errorCode; protected HttpClient httpclient; protected HttpPost httppost; protected MultipartEntity multipartEntity; protected HttpResponse response; protected HttpEntity entity; protected InputStream is; protected boolean isUserTokenAttached = false; protected void setUpCall(String url) { httpclient = new DefaultHttpClient(); httppost = new HttpPost(context.getString(R.string.server_url) + url); multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(context); int userID = settings.getInt("userID", -1); if (userID > 0) { addDataToCall("userID", userID); addDataToCall("userToken", settings.getString("userToken","")); isUserTokenAttached = true; } } protected void addDataToCall(String key, String value) { if (value != null) { try { multipartEntity.addPart(key, new StringBody(value)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } protected void addDataToCall(String key, Integer value) { if (value != null) { try { multipartEntity.addPart(key, new StringBody(Integer.toString(value))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } protected void addDataToCall(String key, Float value) { if (value != null) { try { multipartEntity.addPart(key, new StringBody(Float.toString(value))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } protected void addFileToCall(String key, String fileName) { multipartEntity.addPart(key, new FileBody(new File(fileName))); } protected void makeCall(RootElement root) { Element errorTag = root.getChild("error"); errorTag.setStartElementListener(new StartElementListener(){ public void start(Attributes attributes) { errorCode = attributes.getValue("code"); } }); errorTag.setEndTextElementListener(new EndTextElementListener(){ public void end(String body) { errorMessage = body; } }); try { httppost.setEntity(multipartEntity); response = httpclient.execute(httppost); entity = response.getEntity(); is = entity.getContent(); Xml.parse(is, Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new RuntimeException(e); } } public boolean hasError() { return (errorMessage != null) || (errorCode != null) ; } public String getErrorMessage() { return errorMessage; } public String getErrorCode() { return errorCode; } }
Catch networking errors gracefully
app/src/uk/co/jarofgreen/cityoutdoors/API/BaseCall.java
Catch networking errors gracefully
Java
bsd-3-clause
ff81b4e8e8a1546146532dfc822acccc02612a4f
0
psygate/CivModCore,psygate/CivModCore
package vg.civcraft.mc.civmodcore.util; import java.nio.ByteBuffer; import java.util.UUID; import org.apache.commons.lang3.ArrayUtils; /** * Class of utilities relating to UUIDs * * @author Protonull */ public final class UuidUtils { public static final UUID IDENTITY = new UUID(0L, 0L); /** * Determines whether a given UUID is null or a default 0,0 value. * * @param uuid The UUID to test. * @return Returns true if the given UUID is null or default. */ public static boolean isNullOrIdentity(final UUID uuid) { return uuid == null || IDENTITY.equals(uuid); } /** * Attempts to parse a UUID from a given string. * * @param value The string to parse. * @return Returns a valid UUID, or null. */ public static UUID fromString(final String value) { if (value == null) { return null; } try { return UUID.fromString(value); } catch (final Exception ignored) { return null; } } /** * Converts a UUID to a byte array. * * @param uuid The UUID to convert, can be null. * @return Returns a 16 byte array representing the UUID. */ public static byte[] uuidToBytes(final UUID uuid) { if (isNullOrIdentity(uuid)) { return new byte[16]; } // Creating a new ByteBuffer to almost immediately expend it just // to get the bytes is a bit extra, but other ways aren't as clean // or readable. final ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); return buffer.array(); } /** * <p>Converts a given byte array to a UUID.</p> * * <p>Note: You can provide a byte array of any length, or even null. Null or zero length arrays will * return {@link #IDENTITY}. Byte arrays less than 16 elements long will be used with the remainder * inferred as zeroed out bytes. With byte arrays larger than 16 elements, only those first 16 * elements are considered.</p> * * @param bytes The byte array to create the UUID from. * @return Returns an instance of UUID based on the given bytes. */ public static UUID bytesToUUID(byte[] bytes) { if (ArrayUtils.isEmpty(bytes)) { return IDENTITY; } if (bytes.length < 16) { // Support shorter UUIDs bytes = ArrayUtils.addAll(bytes, new byte[16 - bytes.length]); } final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); final long high = byteBuffer.getLong(); final long low = byteBuffer.getLong(); return new UUID(high, low); } }
src/main/java/vg/civcraft/mc/civmodcore/util/UuidUtils.java
package vg.civcraft.mc.civmodcore.util; import java.nio.ByteBuffer; import java.util.UUID; import org.apache.commons.lang3.ArrayUtils; /** * Class of utilities relating to UUIDs * * @author Protonull */ public final class UuidUtils { public static final UUID IDENTITY = new UUID(0L, 0L); /** * Determines whether a given UUID is null or a default 0,0 value. * * @param uuid The UUID to test. * @return Returns true if the given UUID is null or default. */ public static boolean isNullOrIdentity(final UUID uuid) { return uuid == null || IDENTITY.equals(uuid); } /** * Converts a UUID to a byte array. * * @param uuid The UUID to convert, can be null. * @return Returns a 16 byte array representing the UUID. */ public static byte[] uuidToBytes(final UUID uuid) { if (isNullOrIdentity(uuid)) { return new byte[16]; } // Creating a new ByteBuffer to almost immediately expend it just // to get the bytes is a bit extra, but other ways aren't as clean // or readable. final ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()); buffer.putLong(uuid.getLeastSignificantBits()); return buffer.array(); } /** * <p>Converts a given byte array to a UUID.</p> * * <p>Note: You can provide a byte array of any length, or even null. Null or zero length arrays will * return {@link #IDENTITY}. Byte arrays less than 16 elements long will be used with the remainder * inferred as zeroed out bytes. With byte arrays larger than 16 elements, only those first 16 * elements are considered.</p> * * @param bytes The byte array to create the UUID from. * @return Returns an instance of UUID based on the given bytes. */ public static UUID bytesToUUID(byte[] bytes) { if (ArrayUtils.isEmpty(bytes)) { return IDENTITY; } if (bytes.length < 16) { // Support shorter UUIDs bytes = ArrayUtils.addAll(bytes, new byte[16 - bytes.length]); } final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); final long high = byteBuffer.getLong(); final long low = byteBuffer.getLong(); return new UUID(high, low); } }
Add UuidUtils.fromString() for less throwy UUID parsing
src/main/java/vg/civcraft/mc/civmodcore/util/UuidUtils.java
Add UuidUtils.fromString() for less throwy UUID parsing
Java
bsd-3-clause
6987a61a9a3fdb88ce449964bff9ab452f117dbd
0
pepyakin/threetenbp,jnehlmeier/threetenbp,pepyakin/threetenbp,jnehlmeier/threetenbp,ThreeTen/threetenbp,naixx/threetenbp,ThreeTen/threetenbp,naixx/threetenbp
/* * Copyright (c) 2007-2011, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.time.calendar; import javax.time.CalendricalException; import javax.time.Instant; import javax.time.calendar.zone.ZoneOffsetTransition; import javax.time.calendar.zone.ZoneRules; /** * Provides common implementations of {@code ZoneResolver}. * <p> * A {@link ZoneResolver} provides a strategy for handling the gaps and overlaps * on the time-line that occur due to changes in the offset from UTC, usually * caused by Daylight Savings Time. * <p> * ZoneResolvers is a utility class. * All resolvers returned are immutable and thread-safe. * * @author Stephen Colebourne */ public final class ZoneResolvers { /** * Private constructor. */ private ZoneResolvers() { } //----------------------------------------------------------------------- /** * Returns the strict zone resolver which rejects all gaps and overlaps * as invalid, resulting in an exception. * * @return the strict resolver, not null */ public static ZoneResolver strict() { return Strict.INSTANCE; } /** * Class implementing strict resolver. */ private static final class Strict extends ZoneResolver { /** The singleton instance. */ private static final Strict INSTANCE = new Strict(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { throw new CalendricalException("Local time " + newDateTime + " does not exist in time-zone " + zone + " due to a gap in the local time-line"); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { throw new CalendricalException("Local time " + newDateTime + " has two matching offsets, " + discontinuity.getOffsetBefore() + " and " + discontinuity.getOffsetAfter() + ", in time-zone " + zone); } } //----------------------------------------------------------------------- /** * Returns the pre-transition zone resolver, which returns the instant * one nanosecond before the transition for gaps, and the earlier offset * for overlaps. * * @return the pre-transition resolver, not null */ public static ZoneResolver preTransition() { return PreTransition.INSTANCE; } /** * Class implementing preTransition resolver. */ private static final class PreTransition extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PreTransition(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { Instant instantBefore = discontinuity.getInstant().minusNanos(1); return OffsetDateTime.ofInstant(instantBefore, discontinuity.getOffsetBefore()); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetBefore()); } } //----------------------------------------------------------------------- /** * Returns the post-transition zone resolver, which returns the instant * after the transition for gaps, and the later offset for overlaps. * * @return the post-transition resolver, not null */ public static ZoneResolver postTransition() { return PostTransition.INSTANCE; } /** * Class implementing postTransition resolver. */ private static final class PostTransition extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PostTransition(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } //----------------------------------------------------------------------- /** * Returns the post-gap-pre-overlap zone resolver, which returns the instant * after the transition for gaps, and the earlier offset for overlaps. * * @return the post-transition resolver, not null */ public static ZoneResolver postGapPreOverlap() { return PostGapPreOverlap.INSTANCE; } /** * Class implementing postGapPreOverlap resolver. */ private static final class PostGapPreOverlap extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PostGapPreOverlap(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetBefore()); } } //----------------------------------------------------------------------- /** * Returns the retain offset resolver, which returns the instant after the * transition for gaps, and the same offset for overlaps. * <p> * This resolver is the same as the {{@link #postTransition()} resolver with * one additional rule. When processing an overlap, this resolver attempts * to use the same offset as the offset specified in the old date-time. * If that offset is invalid then the later offset is chosen. * <p> * This resolver is most commonly useful when adding or subtracting time * from a {@code ZonedDateTime}. * * @return the retain offset resolver, not null */ public static ZoneResolver retainOffset() { return RetainOffset.INSTANCE; } /** * Class implementing retain offset resolver. */ private static final class RetainOffset extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new RetainOffset(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { if (oldDateTime != null && discontinuity.isValidOffset(oldDateTime.getOffset())) { return OffsetDateTime.of(newDateTime, oldDateTime.getOffset()); } return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } //----------------------------------------------------------------------- /** * Returns the push forward resolver, which changes the time of the result * in a gap by adding the length of the gap. * <p> * If the discontinuity is a gap, then the resolver will add the length of * the gap in seconds to the local time. * For example, given a gap from 01:00 to 02:00 and a time of 01:20, this * will add one hour to result in 02:20. * <p> * If the discontinuity is an overlap, then the resolver will choose the * later of the two offsets. * * @return the push forward resolver, not null */ public static ZoneResolver pushForward() { return PushForward.INSTANCE; } /** * Class implementing push forward resolver. */ private static final class PushForward extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PushForward(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { LocalDateTime result = newDateTime.plus(discontinuity.getTransitionSize()); return OffsetDateTime.of(result, discontinuity.getOffsetAfter()); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } //----------------------------------------------------------------------- /** * Creates a combined resolver, using two different strategies for gap and overlap. * <p> * If either argument is {@code null} then the {@link #strict()} resolver is used. * * @param gapResolver the resolver to use for a gap, null means strict * @param overlapResolver the resolver to use for an overlap, null means strict * @return the combination resolver, not null */ public static ZoneResolver combination(ZoneResolver gapResolver, ZoneResolver overlapResolver) { gapResolver = (gapResolver == null ? strict() : gapResolver); overlapResolver = (overlapResolver == null ? strict() : overlapResolver); if (gapResolver == overlapResolver) { return gapResolver; } return new Combination(gapResolver, overlapResolver); } /** * Class implementing combination resolver. */ private static final class Combination extends ZoneResolver { /** The gap resolver. */ private final ZoneResolver gapResolver; /** The overlap resolver. */ private final ZoneResolver overlapResolver; /** * Constructor. * @param gapResolver the resolver to use for a gap, not null * @param overlapResolver the resolver to use for an overlap, not null */ Combination(ZoneResolver gapResolver, ZoneResolver overlapResolver) { this.gapResolver = gapResolver; this.overlapResolver = overlapResolver; } /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return gapResolver.handleGap(zone, rules, discontinuity, newDateTime, oldDateTime); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return overlapResolver.handleOverlap(zone, rules, discontinuity, newDateTime, oldDateTime); } } }
src/main/java/javax/time/calendar/ZoneResolvers.java
/* * Copyright (c) 2007-2011, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.time.calendar; import javax.time.CalendricalException; import javax.time.Instant; import javax.time.calendar.zone.ZoneOffsetTransition; import javax.time.calendar.zone.ZoneRules; /** * Provides common implementations of {@code ZoneResolver}. * <p> * A {@link ZoneResolver} provides a strategy for handling the gaps and overlaps * on the time-line that occur due to changes in the offset from UTC, usually * caused by Daylight Savings Time. * <p> * ZoneResolvers is a utility class. * All resolvers returned are immutable and thread-safe. * * @author Stephen Colebourne */ public final class ZoneResolvers { /** * Private constructor. */ private ZoneResolvers() { } //----------------------------------------------------------------------- /** * Returns the strict zone resolver which rejects all gaps and overlaps * as invalid, resulting in an exception. * * @return the strict resolver, not null */ public static ZoneResolver strict() { return Strict.INSTANCE; } /** * Class implementing strict resolver. */ private static class Strict extends ZoneResolver { /** The singleton instance. */ private static final Strict INSTANCE = new Strict(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { throw new CalendricalException("Local time " + newDateTime + " does not exist in time-zone " + zone + " due to a gap in the local time-line"); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { throw new CalendricalException("Local time " + newDateTime + " has two matching offsets, " + discontinuity.getOffsetBefore() + " and " + discontinuity.getOffsetAfter() + ", in time-zone " + zone); } } //----------------------------------------------------------------------- /** * Returns the pre-transition zone resolver, which returns the instant * one nanosecond before the transition for gaps, and the earlier offset * for overlaps. * * @return the pre-transition resolver, not null */ public static ZoneResolver preTransition() { return PreTransition.INSTANCE; } /** * Class implementing preTransition resolver. */ private static class PreTransition extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PreTransition(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { Instant instantBefore = discontinuity.getInstant().minusNanos(1); return OffsetDateTime.ofInstant(instantBefore, discontinuity.getOffsetBefore()); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetBefore()); } } //----------------------------------------------------------------------- /** * Returns the post-transition zone resolver, which returns the instant * after the transition for gaps, and the later offset for overlaps. * * @return the post-transition resolver, not null */ public static ZoneResolver postTransition() { return PostTransition.INSTANCE; } /** * Class implementing postTransition resolver. */ private static class PostTransition extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PostTransition(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } //----------------------------------------------------------------------- /** * Returns the post-gap-pre-overlap zone resolver, which returns the instant * after the transition for gaps, and the earlier offset for overlaps. * * @return the post-transition resolver, not null */ public static ZoneResolver postGapPreOverlap() { return PostGapPreOverlap.INSTANCE; } /** * Class implementing postGapPreOverlap resolver. */ private static class PostGapPreOverlap extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PostGapPreOverlap(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetBefore()); } } //----------------------------------------------------------------------- /** * Returns the retain offset resolver, which returns the instant after the * transition for gaps, and the same offset for overlaps. * <p> * This resolver is the same as the {{@link #postTransition()} resolver with * one additional rule. When processing an overlap, this resolver attempts * to use the same offset as the offset specified in the old date-time. * If that offset is invalid then the later offset is chosen. * <p> * This resolver is most commonly useful when adding or subtracting time * from a {@code ZonedDateTime}. * * @return the retain offset resolver, not null */ public static ZoneResolver retainOffset() { return RetainOffset.INSTANCE; } /** * Class implementing retain offset resolver. */ private static class RetainOffset extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new RetainOffset(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { if (oldDateTime != null && discontinuity.isValidOffset(oldDateTime.getOffset())) { return OffsetDateTime.of(newDateTime, oldDateTime.getOffset()); } return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } //----------------------------------------------------------------------- /** * Returns the push forward resolver, which changes the time of the result * in a gap by adding the length of the gap. * <p> * If the discontinuity is a gap, then the resolver will add the length of * the gap in seconds to the local time. * For example, given a gap from 01:00 to 02:00 and a time of 01:20, this * will add one hour to result in 02:20. * <p> * If the discontinuity is an overlap, then the resolver will choose the * later of the two offsets. * * @return the push forward resolver, not null */ public static ZoneResolver pushForward() { return PushForward.INSTANCE; } /** * Class implementing push forward resolver. */ private static class PushForward extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PushForward(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { LocalDateTime result = newDateTime.plus(discontinuity.getTransitionSize()); return OffsetDateTime.of(result, discontinuity.getOffsetAfter()); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } //----------------------------------------------------------------------- /** * Creates a combined resolver, using two different strategies for gap and overlap. * <p> * If either argument is {@code null} then the {@link #strict()} resolver is used. * * @param gapResolver the resolver to use for a gap, null means strict * @param overlapResolver the resolver to use for an overlap, null means strict * @return the combination resolver, not null */ public static ZoneResolver combination(ZoneResolver gapResolver, ZoneResolver overlapResolver) { gapResolver = (gapResolver == null ? strict() : gapResolver); overlapResolver = (overlapResolver == null ? strict() : overlapResolver); if (gapResolver == overlapResolver) { return gapResolver; } return new Combination(gapResolver, overlapResolver); } /** * Class implementing combination resolver. */ private static class Combination extends ZoneResolver { /** The gap resolver. */ private final ZoneResolver gapResolver; /** The overlap resolver. */ private final ZoneResolver overlapResolver; /** * Constructor. * @param gapResolver the resolver to use for a gap, not null * @param overlapResolver the resolver to use for an overlap, not null */ public Combination(ZoneResolver gapResolver, ZoneResolver overlapResolver) { this.gapResolver = gapResolver; this.overlapResolver = overlapResolver; } /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return gapResolver.handleGap(zone, rules, discontinuity, newDateTime, oldDateTime); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return overlapResolver.handleOverlap(zone, rules, discontinuity, newDateTime, oldDateTime); } } }
Tidy ZoneResolvers, but cannot stop Combination class from class-loading
src/main/java/javax/time/calendar/ZoneResolvers.java
Tidy ZoneResolvers, but cannot stop Combination class from class-loading
Java
mit
429cd11b85cb8d7d812785f2f2c15a3b79c1a583
0
jakobehmsen/permoize
package permoize; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.function.BiFunction; public class ReflectivePusher { private ReflectivePusher() { } @SuppressWarnings("unchecked") public static <T, R> T create(Class<T> c, T implementer, Pusher<R> puller, BiFunction<Method, Object[], R> requestResolver) { return (T) Proxy.newProxyInstance(c.getClassLoader(), new Class<?>[]{c}, (proxy, method, args) -> { boolean isTransient = method.isAnnotationPresent(Transient.class); if(!isTransient) { boolean isCreator = method.isAnnotationPresent(Creator.class); if(!isCreator) { R request = requestResolver.apply(method, args); puller.put(request); return null; } else { Object result = method.invoke(implementer, args); // Wrap result into some sort of builder proxy - how? /* What should the result be wrapped into? Some sort of builder that both collects and forwards messages in an entirely transient sense */ return Builder.create(method.getReturnType(), new Invocation(method, args), result); } } else { return method.invoke(implementer, args); } }); } }
eclipse/src/permoize/ReflectivePusher.java
package permoize; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.function.BiFunction; public class ReflectivePusher { private ReflectivePusher() { } @SuppressWarnings("unchecked") public static <T, R> T create(Class<T> c, T implementer, Pusher<R> puller, BiFunction<Method, Object[], R> requestResolver) { return (T) Proxy.newProxyInstance(c.getClassLoader(), new Class<?>[]{c}, (proxy, method, args) -> { boolean isTransient = method.isAnnotationPresent(Transient.class); if(!isTransient) { boolean isCreator = method.isAnnotationPresent(Creator.class); if(!isCreator) { // If an argument is a builder, then something special should happen... for(int i = 0; i < args.length; i++) { Object arg = args[i]; if(arg instanceof Builder) { Builder builderArg = (Builder)arg; // Somehow, the builder should be bound to the request // The args are bound to the request... // So, when a builder is serialized, it should be serialized in such // a way that when it is read, then it somehow recreates itself... How? Where? } } R request = requestResolver.apply(method, args); puller.put(request); return null; } else { Object result = method.invoke(implementer, args); // Wrap result into some sort of builder proxy - how? /* What should the result be wrapped into? Some sort of builder that both collects and forwards messages in an entirely transient sense */ return Builder.create(method.getReturnType(), result); } } else { return method.invoke(implementer, args); } }); } }
Removed redundant logic. Signed-off-by: Jakob Brandsborg Ehmsen <387ed33cc9ebf98b733caa2520baacd616b28aa5@gmail.com>
eclipse/src/permoize/ReflectivePusher.java
Removed redundant logic.
Java
mit
11d70716f353552a79b4e1f0422702385c1c67fb
0
Batix/rundeck-ansible-plugin,Batix/rundeck-ansible-plugin
/** * Ansible Runner Builder. * * @author Yassine Azzouz <a href="mailto:yassine.azzouz@gmail.com">yassine.azzouz@gmail.com</a> */ package com.batix.rundeck.core; import com.dtolabs.rundeck.core.common.INodeEntry; import com.dtolabs.rundeck.core.common.INodeSet; import com.batix.rundeck.core.AnsibleDescribable.AuthenticationType; import com.batix.rundeck.core.AnsibleDescribable.BecomeMethodType; import com.dtolabs.rundeck.core.common.Framework; import com.dtolabs.rundeck.core.dispatcher.DataContextUtils; import com.dtolabs.rundeck.core.execution.ExecutionContext; import com.dtolabs.rundeck.core.plugins.configuration.ConfigurationException; import com.dtolabs.rundeck.core.storage.ResourceMeta; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import org.rundeck.storage.api.Path; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.rundeck.storage.api.PathUtil; import org.rundeck.storage.api.StorageException; public class AnsibleRunnerBuilder { private ExecutionContext context; private Framework framework; private String frameworkProject; private Map<String, Object> jobConf; private Collection<INodeEntry> nodes; private Collection<File> tempFiles; AnsibleRunnerBuilder(final ExecutionContext context, final Framework framework) { this.context = context; this.framework = framework; this.frameworkProject = context.getFrameworkProject(); this.jobConf = new HashMap<String, Object>(); this.nodes = Collections.emptySet(); this.tempFiles = new LinkedList<>(); } public AnsibleRunnerBuilder(final ExecutionContext context, final Framework framework, INodeSet nodes, final Map<String, Object> configuration) { this.context = context; this.framework = framework; this.frameworkProject = context.getFrameworkProject(); this.jobConf = configuration; this.nodes = nodes.getNodes(); this.tempFiles = new LinkedList<>(); } public AnsibleRunnerBuilder(final INodeEntry node,final ExecutionContext context, final Framework framework, final Map<String, Object> configuration) { this.context = context; this.framework = framework; this.frameworkProject = context.getFrameworkProject(); this.jobConf = configuration; this.nodes = Collections.singleton(node); this.tempFiles = new LinkedList<>(); } private byte[] loadStoragePathData(final String passwordStoragePath) throws IOException { if (null == passwordStoragePath) { return null; } ResourceMeta contents = context.getStorageTree().getResource(passwordStoragePath).getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); } public String getPrivateKeyfilePath() { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_KEYPATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } return path; } public String getPrivateKeyStoragePath() { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_KEYPATH_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } return path; } public InputStream getPrivateKeyStorageData() throws IOException { String privateKeyResourcePath = getPrivateKeyStoragePath(); if (null == privateKeyResourcePath) { return null; } return context .getStorageTree() .getResource(privateKeyResourcePath) .getContents() .getInputStream(); } public String getPasswordStoragePath() { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_PASSWORD_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } return path; } public String getSshPrivateKey() throws ConfigurationException{ //look for storage option String storagePath = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_KEYPATH_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if(null!=storagePath){ //look up storage value if (storagePath.contains("${")) { storagePath = DataContextUtils.replaceDataReferences( storagePath, context.getDataContext() ); } Path path = PathUtil.asPath(storagePath); try { ResourceMeta contents = context.getStorageTree().getResource(path) .getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (StorageException e) { throw new ConfigurationException("Failed to read the ssh private key for " + "storage path: " + storagePath + ": " + e.getMessage()); } catch (IOException e) { throw new ConfigurationException("Failed to read the ssh private key for " + "storage path: " + storagePath + ": " + e.getMessage()); } } else { //else look up option value final String path = getPrivateKeyfilePath(); if (path != null) { try { return new String(Files.readAllBytes(Paths.get(path))); } catch (IOException e) { throw new ConfigurationException("Failed to read the ssh private key from path " + path + ": " + e.getMessage()); } } else { return null; } } } public String getSshPassword() throws ConfigurationException{ //look for option values first //typically jobs use secure options to dynamically setup the ssh password final String passwordOption = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_PASSWORD_OPTION, AnsibleDescribable.DEFAULT_ANSIBLE_SSH_PASSWORD_OPTION, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); String sshPassword = PropertyResolver.evaluateSecureOption(passwordOption, getContext()); if(null!=sshPassword){ // is true if there is an ssh option defined in the private data context return sshPassword; } else { //look for storage option String storagePath = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_PASSWORD_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if(null!=storagePath){ //look up storage value if (storagePath.contains("${")) { storagePath = DataContextUtils.replaceDataReferences( storagePath, context.getDataContext() ); } Path path = PathUtil.asPath(storagePath); try { ResourceMeta contents = context.getStorageTree().getResource(path) .getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (StorageException e) { throw new ConfigurationException("Failed to read the shh password for " + "storage path: " + storagePath + ": " + e.getMessage()); } catch (IOException e) { throw new ConfigurationException("Failed to read the ssh password for " + "storage path: " + storagePath + ": " + e.getMessage()); } } else { return null; } } } public Integer getSSHTimeout() throws ConfigurationException { Integer timeout = null; final String stimeout = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_TIMEOUT, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != stimeout) { try { timeout = Integer.parseInt(stimeout); } catch (NumberFormatException e) { throw new ConfigurationException("Can't parse timeout value" + timeout + ": " + e.getMessage()); } } return timeout; } public String getSshUser() { final String user; user = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_USER, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != user && user.contains("${")) { return DataContextUtils.replaceDataReferences(user, getContext().getDataContext()); } return user; } public AuthenticationType getSshAuthenticationType() { String authType = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_AUTH_TYPE, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != authType) { return AuthenticationType.valueOf(authType); } return AuthenticationType.privateKey; } public String getBecomeUser() { final String user; user = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_USER, null, getFrameworkProject(), getFramework(),getNode(), getjobConf() ); if (null != user && user.contains("${")) { return DataContextUtils.replaceDataReferences(user, getContext().getDataContext()); } return user; } public Boolean getBecome() { Boolean become = null; String sbecome = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != sbecome) { become = Boolean.parseBoolean(sbecome); } return become; } public String getExtraParams() { final String extraParams; extraParams = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_EXTRA_PARAM, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != extraParams && extraParams.contains("${")) { return DataContextUtils.replaceDataReferences(extraParams, getContext().getDataContext()); } return extraParams; } public BecomeMethodType getBecomeMethod() { String becomeMethod = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_METHOD, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != becomeMethod) { return BecomeMethodType.valueOf(becomeMethod); } return null; } public byte[] getPasswordStorageData() throws IOException{ return loadStoragePathData(getPasswordStoragePath()); } public String getBecomePasswordStoragePath() { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_PASSWORD_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } return path; } public byte[] getBecomePasswordStorageData() throws IOException{ return loadStoragePathData(getBecomePasswordStoragePath()); } public String getBecomePassword(String prefix) { final String passwordOption = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_PASSWORD_OPTION, AnsibleDescribable.DEFAULT_ANSIBLE_BECOME_PASSWORD_OPTION, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); return PropertyResolver.evaluateSecureOption(passwordOption, getContext()); } public String getBecomePassword() throws ConfigurationException{ //look for option values first //typically jobs use secure options to dynamically setup the become password String passwordOption = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_PASSWORD_OPTION, AnsibleDescribable.DEFAULT_ANSIBLE_BECOME_PASSWORD_OPTION, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); String becomePassword = PropertyResolver.evaluateSecureOption(passwordOption, getContext()); if(null!=becomePassword){ // is true if there is a become option defined in the private data context return becomePassword; } else { //look for storage option String storagePath = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_PASSWORD_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if(null!=storagePath){ //look up storage value if (storagePath.contains("${")) { storagePath = DataContextUtils.replaceDataReferences( storagePath, context.getDataContext() ); } Path path = PathUtil.asPath(storagePath); try { ResourceMeta contents = context.getStorageTree().getResource(path) .getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (StorageException e) { throw new ConfigurationException("Failed to read the become password for " + "storage path: " + storagePath + ": " + e.getMessage()); } catch (IOException e) { throw new ConfigurationException("Failed to read the become password for " + "storage path: " + storagePath + ": " + e.getMessage()); } } else { return null; } } } public String getVaultKey() throws ConfigurationException{ //look for storage option String storagePath = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_VAULTSTORE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if(null!=storagePath){ //look up storage value if (storagePath.contains("${")) { storagePath = DataContextUtils.replaceDataReferences( storagePath, context.getDataContext() ); } Path path = PathUtil.asPath(storagePath); try { ResourceMeta contents = context.getStorageTree().getResource(path) .getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (StorageException e) { throw new ConfigurationException("Failed to read the vault key for " + "storage path: " + storagePath + ": " + e.getMessage()); } catch (IOException e) { throw new ConfigurationException("Failed to read the vault key for " + "storage path: " + storagePath + ": " + e.getMessage()); } } else { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_VAULT_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } if (path != null) { try { return new String(Files.readAllBytes(Paths.get(path))); } catch (IOException e) { throw new ConfigurationException("Failed to read the ssh private key from path " + path + ": " + e.getMessage()); } } else { return null; } } } public String getPlaybookPath() { String playbook = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_PLAYBOOK_PATH) ) { playbook = (String) jobConf.get(AnsibleDescribable.ANSIBLE_PLAYBOOK_PATH); } if (null != playbook && playbook.contains("${")) { return DataContextUtils.replaceDataReferences(playbook, getContext().getDataContext()); } return playbook; } public String getPlaybookInline() { String playbook = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_PLAYBOOK_INLINE) ) { playbook = (String) jobConf.get(AnsibleDescribable.ANSIBLE_PLAYBOOK_INLINE); } if (null != playbook && playbook.contains("${")) { return DataContextUtils.replaceDataReferences(playbook, getContext().getDataContext()); } return playbook; } public String getModule() { String module = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_MODULE) ) { module = (String) jobConf.get(AnsibleDescribable.ANSIBLE_MODULE); } if (null != module && module.contains("${")) { return DataContextUtils.replaceDataReferences(module, getContext().getDataContext()); } return module; } public String getModuleArgs() { String args = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_MODULE_ARGS) ) { args = (String) jobConf.get(AnsibleDescribable.ANSIBLE_MODULE_ARGS); } if (null != args && args.contains("${")) { return DataContextUtils.replaceDataReferences(args, getContext().getDataContext()); } return args; } public String getExecutable() { final String executable; executable = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_EXECUTABLE, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != executable && executable.contains("${")) { return DataContextUtils.replaceDataReferences(executable, getContext().getDataContext()); } return executable; } public Boolean getDebug() { Boolean debug = Boolean.FALSE; String sdebug = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_DEBUG, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != sdebug) { debug = Boolean.parseBoolean(sdebug); } return debug; } public Boolean gatherFacts() { Boolean gatherFacts = null; String sgatherFacts = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_GATHER_FACTS, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != sgatherFacts) { gatherFacts = Boolean.parseBoolean(sgatherFacts); } return gatherFacts; } public Boolean ignoreErrors() { Boolean ignoreErrors = null; String signoreErrors = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_IGNORE_ERRORS, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != signoreErrors) { ignoreErrors = Boolean.parseBoolean(signoreErrors); } return ignoreErrors; } public String getIgnoreTagsPrefix() { final String ignoreTagsPrefix; ignoreTagsPrefix = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_IGNORE_TAGS, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != ignoreTagsPrefix && ignoreTagsPrefix.contains("${")) { return DataContextUtils.replaceDataReferences(ignoreTagsPrefix, getContext().getDataContext()); } return ignoreTagsPrefix; } public String getExtraVars() { final String extraVars; extraVars = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_EXTRA_VARS, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != extraVars && extraVars.contains("${")) { return DataContextUtils.replaceDataReferences(extraVars, getContext().getDataContext()); } return extraVars; } public Boolean generateInventory() { Boolean generateInventory = null; String sgenerateInventory = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_GENERATE_INVENTORY, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != sgenerateInventory) { generateInventory = Boolean.parseBoolean(sgenerateInventory); } return generateInventory; } public String getInventory() throws ConfigurationException { String inventory; Boolean isGenerated = generateInventory(); if (isGenerated !=null && isGenerated) { File tempInventory = new AnsibleInventoryBuilder(this.nodes).buildInventory(); tempFiles.add(tempInventory); inventory = tempInventory.getAbsolutePath(); return inventory; } inventory = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_INVENTORY, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != inventory && inventory.contains("${")) { return DataContextUtils.replaceDataReferences(inventory, getContext().getDataContext()); } return inventory; } public String getLimit() throws ConfigurationException { final String limit; // Return Null if Disabled if(PropertyResolver.resolveBooleanProperty( AnsibleDescribable.ANSIBLE_DISABLE_LIMIT, Boolean.valueOf(AnsibleDescribable.DISABLE_LIMIT_PROP.getDefaultValue()), getFrameworkProject(), getFramework(), getNode(), getjobConf())){ return null; } // Get Limit from Rundeck limit = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_LIMIT, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != limit && limit.contains("${")) { return DataContextUtils.replaceDataReferences(limit, getContext().getDataContext()); } return limit; } public String getConfigFile() { final String configFile; configFile = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_CONFIG_FILE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != configFile && configFile.contains("${")) { return DataContextUtils.replaceDataReferences(configFile, getContext().getDataContext()); } return configFile; } public String getBaseDir() { String baseDir = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_BASE_DIR_PATH) ) { baseDir = (String) jobConf.get(AnsibleDescribable.ANSIBLE_BASE_DIR_PATH); } if (null != baseDir && baseDir.contains("${")) { return DataContextUtils.replaceDataReferences(baseDir, getContext().getDataContext()); } return baseDir; } public AnsibleRunner buildAnsibleRunner() throws ConfigurationException{ AnsibleRunner runner = null; String playbook; String module; if ((playbook = getPlaybookPath()) != null) { runner = AnsibleRunner.playbookPath(playbook); } else if ((playbook = getPlaybookInline()) != null) { runner = AnsibleRunner.playbookInline(playbook); } else if ((module = getModule()) != null) { runner = AnsibleRunner.adHoc(module, getModuleArgs()); } else { throw new ConfigurationException("Missing module or playbook job arguments"); } final AuthenticationType authType = getSshAuthenticationType(); if (AuthenticationType.privateKey == authType) { final String privateKey = getSshPrivateKey(); if (privateKey != null) { runner = runner.sshPrivateKey(privateKey); } } else if (AuthenticationType.password == authType) { final String password = getSshPassword(); if (password != null) { runner = runner.sshUsePassword(Boolean.TRUE).sshPass(password); } } // set rundeck options as environment variables Map<String,String> options = context.getDataContext().get("option"); if (options != null) { runner = runner.options(options); } String inventory = getInventory(); if (inventory != null) { runner = runner.setInventory(inventory); } String limit = getLimit(); if (limit != null) { runner = runner.limit(limit); } Boolean debug = getDebug(); if (debug != null) { if (debug == Boolean.TRUE) { runner = runner.debug(Boolean.TRUE); } else { runner = runner.debug(Boolean.FALSE); } } String extraParams = getExtraParams(); if (extraParams != null) { runner = runner.extraParams(extraParams); } String extraVars = getExtraVars(); if (extraVars != null) { runner = runner.extraVars(extraVars); } String user = getSshUser(); if (user != null) { runner = runner.sshUser(user); } String vault = getVaultKey(); if (vault != null) { runner = runner.vaultPass(vault); } Integer timeout = getSSHTimeout(); if (timeout != null) { runner = runner.sshTimeout(timeout); } Boolean become = getBecome(); if (become != null) { runner = runner.become(become); } String become_user = getBecomeUser(); if (become_user != null) { runner = runner.becomeUser(become_user); } BecomeMethodType become_method = getBecomeMethod(); if (become_method != null) { runner = runner.becomeMethod(become_method.name()); } String become_password = getBecomePassword(); if (become_password != null) { runner = runner.becomePassword(become_password); } String configFile = getConfigFile(); if (configFile != null) { runner = runner.configFile(configFile); } String baseDir = getBaseDir(); if (baseDir != null) { runner = runner.baseDirectory(baseDir); } return runner; } public ExecutionContext getContext() { return context; } public Framework getFramework() { return framework; } public INodeEntry getNode() { return nodes.size() == 1 ? nodes.iterator().next() : null; } public String getFrameworkProject() { return frameworkProject; } public Map<String,Object> getjobConf() { return jobConf; } public void cleanupTempFiles() { for (File temp : tempFiles) { if (!getDebug()) { temp.delete(); } } tempFiles.clear(); } }
src/main/java/com/batix/rundeck/core/AnsibleRunnerBuilder.java
/** * Ansible Runner Builder. * * @author Yassine Azzouz <a href="mailto:yassine.azzouz@gmail.com">yassine.azzouz@gmail.com</a> */ package com.batix.rundeck.core; import com.dtolabs.rundeck.core.common.INodeEntry; import com.dtolabs.rundeck.core.common.INodeSet; import com.batix.rundeck.core.AnsibleDescribable.AuthenticationType; import com.batix.rundeck.core.AnsibleDescribable.BecomeMethodType; import com.dtolabs.rundeck.core.common.Framework; import com.dtolabs.rundeck.core.dispatcher.DataContextUtils; import com.dtolabs.rundeck.core.execution.ExecutionContext; import com.dtolabs.rundeck.core.plugins.configuration.ConfigurationException; import com.dtolabs.rundeck.core.storage.ResourceMeta; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import org.rundeck.storage.api.Path; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import org.rundeck.storage.api.PathUtil; import org.rundeck.storage.api.StorageException; public class AnsibleRunnerBuilder { private ExecutionContext context; private Framework framework; private String frameworkProject; private Map<String, Object> jobConf; private Collection<INodeEntry> nodes; private Collection<File> tempFiles; AnsibleRunnerBuilder(final ExecutionContext context, final Framework framework) { this.context = context; this.framework = framework; this.frameworkProject = context.getFrameworkProject(); this.jobConf = new HashMap<String, Object>(); this.nodes = Collections.emptySet(); this.tempFiles = new LinkedList<>(); } public AnsibleRunnerBuilder(final ExecutionContext context, final Framework framework, INodeSet nodes, final Map<String, Object> configuration) { this.context = context; this.framework = framework; this.frameworkProject = context.getFrameworkProject(); this.jobConf = configuration; this.nodes = nodes.getNodes(); this.tempFiles = new LinkedList<>(); } public AnsibleRunnerBuilder(final INodeEntry node,final ExecutionContext context, final Framework framework, final Map<String, Object> configuration) { this.context = context; this.framework = framework; this.frameworkProject = context.getFrameworkProject(); this.jobConf = configuration; this.nodes = Collections.singleton(node); this.tempFiles = new LinkedList<>(); } private byte[] loadStoragePathData(final String passwordStoragePath) throws IOException { if (null == passwordStoragePath) { return null; } ResourceMeta contents = context.getStorageTree().getResource(passwordStoragePath).getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); } public String getPrivateKeyfilePath() { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_KEYPATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } return path; } public String getPrivateKeyStoragePath() { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_KEYPATH_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } return path; } public InputStream getPrivateKeyStorageData() throws IOException { String privateKeyResourcePath = getPrivateKeyStoragePath(); if (null == privateKeyResourcePath) { return null; } return context .getStorageTree() .getResource(privateKeyResourcePath) .getContents() .getInputStream(); } public String getPasswordStoragePath() { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_PASSWORD_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } return path; } public String getSshPrivateKey() throws ConfigurationException{ //look for storage option String storagePath = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_KEYPATH_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if(null!=storagePath){ //look up storage value if (storagePath.contains("${")) { storagePath = DataContextUtils.replaceDataReferences( storagePath, context.getDataContext() ); } Path path = PathUtil.asPath(storagePath); try { ResourceMeta contents = context.getStorageTree().getResource(path) .getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (StorageException e) { throw new ConfigurationException("Failed to read the ssh private key for " + "storage path: " + storagePath + ": " + e.getMessage()); } catch (IOException e) { throw new ConfigurationException("Failed to read the ssh private key for " + "storage path: " + storagePath + ": " + e.getMessage()); } } else { //else look up option value final String path = getPrivateKeyfilePath(); if (path != null) { try { return new String(Files.readAllBytes(Paths.get(path))); } catch (IOException e) { throw new ConfigurationException("Failed to read the ssh private key from path " + path + ": " + e.getMessage()); } } else { return null; } } } public String getSshPassword() throws ConfigurationException{ //look for option values first //typically jobs use secure options to dynamically setup the ssh password final String passwordOption = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_PASSWORD_OPTION, AnsibleDescribable.DEFAULT_ANSIBLE_SSH_PASSWORD_OPTION, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); String sshPassword = PropertyResolver.evaluateSecureOption(passwordOption, getContext()); if(null!=sshPassword){ // is true if there is an ssh option defined in the private data context return sshPassword; } else { //look for storage option String storagePath = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_PASSWORD_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if(null!=storagePath){ //look up storage value if (storagePath.contains("${")) { storagePath = DataContextUtils.replaceDataReferences( storagePath, context.getDataContext() ); } Path path = PathUtil.asPath(storagePath); try { ResourceMeta contents = context.getStorageTree().getResource(path) .getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (StorageException e) { throw new ConfigurationException("Failed to read the shh password for " + "storage path: " + storagePath + ": " + e.getMessage()); } catch (IOException e) { throw new ConfigurationException("Failed to read the ssh password for " + "storage path: " + storagePath + ": " + e.getMessage()); } } else { return null; } } } public Integer getSSHTimeout() throws ConfigurationException { Integer timeout = null; final String stimeout = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_TIMEOUT, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != stimeout) { try { timeout = Integer.parseInt(stimeout); } catch (NumberFormatException e) { throw new ConfigurationException("Can't parse timeout value" + timeout + ": " + e.getMessage()); } } return timeout; } public String getSshUser() { final String user; user = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_USER, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != user && user.contains("${")) { return DataContextUtils.replaceDataReferences(user, getContext().getDataContext()); } return user; } public AuthenticationType getSshAuthenticationType() { String authType = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_SSH_AUTH_TYPE, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != authType) { return AuthenticationType.valueOf(authType); } return AuthenticationType.privateKey; } public String getBecomeUser() { final String user; user = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_USER, null, getFrameworkProject(), getFramework(),getNode(), getjobConf() ); if (null != user && user.contains("${")) { return DataContextUtils.replaceDataReferences(user, getContext().getDataContext()); } return user; } public Boolean getBecome() { Boolean become = null; String sbecome = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != sbecome) { become = Boolean.parseBoolean(sbecome); } return become; } public String getExtraParams() { final String extraParams; extraParams = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_EXTRA_PARAM, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != extraParams && extraParams.contains("${")) { return DataContextUtils.replaceDataReferences(extraParams, getContext().getDataContext()); } return extraParams; } public BecomeMethodType getBecomeMethod() { String becomeMethod = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_METHOD, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != becomeMethod) { return BecomeMethodType.valueOf(becomeMethod); } return null; } public byte[] getPasswordStorageData() throws IOException{ return loadStoragePathData(getPasswordStoragePath()); } public String getBecomePasswordStoragePath() { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_PASSWORD_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } return path; } public byte[] getBecomePasswordStorageData() throws IOException{ return loadStoragePathData(getBecomePasswordStoragePath()); } public String getBecomePassword(String prefix) { final String passwordOption = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_PASSWORD_OPTION, AnsibleDescribable.DEFAULT_ANSIBLE_BECOME_PASSWORD_OPTION, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); return PropertyResolver.evaluateSecureOption(passwordOption, getContext()); } public String getBecomePassword() throws ConfigurationException{ //look for option values first //typically jobs use secure options to dynamically setup the become password String passwordOption = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_PASSWORD_OPTION, AnsibleDescribable.DEFAULT_ANSIBLE_BECOME_PASSWORD_OPTION, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); String becomePassword = PropertyResolver.evaluateSecureOption(passwordOption, getContext()); if(null!=becomePassword){ // is true if there is a become option defined in the private data context return becomePassword; } else { //look for storage option String storagePath = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_BECOME_PASSWORD_STORAGE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if(null!=storagePath){ //look up storage value if (storagePath.contains("${")) { storagePath = DataContextUtils.replaceDataReferences( storagePath, context.getDataContext() ); } Path path = PathUtil.asPath(storagePath); try { ResourceMeta contents = context.getStorageTree().getResource(path) .getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (StorageException e) { throw new ConfigurationException("Failed to read the become password for " + "storage path: " + storagePath + ": " + e.getMessage()); } catch (IOException e) { throw new ConfigurationException("Failed to read the become password for " + "storage path: " + storagePath + ": " + e.getMessage()); } } else { return null; } } } public String getVaultKey() throws ConfigurationException{ //look for storage option String storagePath = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_VAULTSTORE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if(null!=storagePath){ //look up storage value if (storagePath.contains("${")) { storagePath = DataContextUtils.replaceDataReferences( storagePath, context.getDataContext() ); } Path path = PathUtil.asPath(storagePath); try { ResourceMeta contents = context.getStorageTree().getResource(path) .getContents(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); contents.writeContent(byteArrayOutputStream); return new String(byteArrayOutputStream.toByteArray()); } catch (StorageException e) { throw new ConfigurationException("Failed to read the vault key for " + "storage path: " + storagePath + ": " + e.getMessage()); } catch (IOException e) { throw new ConfigurationException("Failed to read the vault key for " + "storage path: " + storagePath + ": " + e.getMessage()); } } else { String path = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_VAULT_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); //expand properties in path if (path != null && path.contains("${")) { path = DataContextUtils.replaceDataReferences(path, context.getDataContext()); } if (path != null) { try { return new String(Files.readAllBytes(Paths.get(path))); } catch (IOException e) { throw new ConfigurationException("Failed to read the ssh private key from path " + path + ": " + e.getMessage()); } } else { return null; } } } public String getPlaybookPath() { String playbook = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_PLAYBOOK_PATH) ) { playbook = (String) jobConf.get(AnsibleDescribable.ANSIBLE_PLAYBOOK_PATH); } if (null != playbook && playbook.contains("${")) { return DataContextUtils.replaceDataReferences(playbook, getContext().getDataContext()); } return playbook; } public String getPlaybookInline() { String playbook = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_PLAYBOOK_INLINE) ) { playbook = (String) jobConf.get(AnsibleDescribable.ANSIBLE_PLAYBOOK_INLINE); } if (null != playbook && playbook.contains("${")) { return DataContextUtils.replaceDataReferences(playbook, getContext().getDataContext()); } return playbook; } public String getModule() { String module = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_MODULE) ) { module = (String) jobConf.get(AnsibleDescribable.ANSIBLE_MODULE); } if (null != module && module.contains("${")) { return DataContextUtils.replaceDataReferences(module, getContext().getDataContext()); } return module; } public String getModuleArgs() { String args = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_MODULE_ARGS) ) { args = (String) jobConf.get(AnsibleDescribable.ANSIBLE_MODULE_ARGS); } if (null != args && args.contains("${")) { return DataContextUtils.replaceDataReferences(args, getContext().getDataContext()); } return args; } public String getExecutable() { final String executable; executable = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_EXECUTABLE, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != executable && executable.contains("${")) { return DataContextUtils.replaceDataReferences(executable, getContext().getDataContext()); } return executable; } public Boolean getDebug() { Boolean debug = Boolean.FALSE; String sdebug = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_DEBUG, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != sdebug) { debug = Boolean.parseBoolean(sdebug); } return debug; } public Boolean gatherFacts() { Boolean gatherFacts = null; String sgatherFacts = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_GATHER_FACTS, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != sgatherFacts) { gatherFacts = Boolean.parseBoolean(sgatherFacts); } return gatherFacts; } public Boolean ignoreErrors() { Boolean ignoreErrors = null; String signoreErrors = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_IGNORE_ERRORS, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != signoreErrors) { ignoreErrors = Boolean.parseBoolean(signoreErrors); } return ignoreErrors; } public String getIgnoreTagsPrefix() { final String ignoreTagsPrefix; ignoreTagsPrefix = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_IGNORE_TAGS, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != ignoreTagsPrefix && ignoreTagsPrefix.contains("${")) { return DataContextUtils.replaceDataReferences(ignoreTagsPrefix, getContext().getDataContext()); } return ignoreTagsPrefix; } public String getExtraVars() { final String extraVars; extraVars = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_EXTRA_VARS, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != extraVars && extraVars.contains("${")) { return DataContextUtils.replaceDataReferences(extraVars, getContext().getDataContext()); } return extraVars; } public Boolean generateInventory() { Boolean generateInventory = null; String sgenerateInventory = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_GENERATE_INVENTORY, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != sgenerateInventory) { generateInventory = Boolean.parseBoolean(sgenerateInventory); } return generateInventory; } public String getInventory() throws ConfigurationException { String inventory; if (generateInventory()) { File tempInventory = new AnsibleInventoryBuilder(this.nodes).buildInventory(); tempFiles.add(tempInventory); inventory = tempInventory.getAbsolutePath(); return inventory; } inventory = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_INVENTORY, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != inventory && inventory.contains("${")) { return DataContextUtils.replaceDataReferences(inventory, getContext().getDataContext()); } return inventory; } public String getLimit() throws ConfigurationException { final String limit; // Return Null if Disabled if(PropertyResolver.resolveBooleanProperty( AnsibleDescribable.ANSIBLE_DISABLE_LIMIT, Boolean.valueOf(AnsibleDescribable.DISABLE_LIMIT_PROP.getDefaultValue()), getFrameworkProject(), getFramework(), getNode(), getjobConf())){ return null; } // Get Limit from Rundeck limit = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_LIMIT, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != limit && limit.contains("${")) { return DataContextUtils.replaceDataReferences(limit, getContext().getDataContext()); } return limit; } public String getConfigFile() { final String configFile; configFile = PropertyResolver.resolveProperty( AnsibleDescribable.ANSIBLE_CONFIG_FILE_PATH, null, getFrameworkProject(), getFramework(), getNode(), getjobConf() ); if (null != configFile && configFile.contains("${")) { return DataContextUtils.replaceDataReferences(configFile, getContext().getDataContext()); } return configFile; } public String getBaseDir() { String baseDir = null; if ( getjobConf().containsKey(AnsibleDescribable.ANSIBLE_BASE_DIR_PATH) ) { baseDir = (String) jobConf.get(AnsibleDescribable.ANSIBLE_BASE_DIR_PATH); } if (null != baseDir && baseDir.contains("${")) { return DataContextUtils.replaceDataReferences(baseDir, getContext().getDataContext()); } return baseDir; } public AnsibleRunner buildAnsibleRunner() throws ConfigurationException{ AnsibleRunner runner = null; String playbook; String module; if ((playbook = getPlaybookPath()) != null) { runner = AnsibleRunner.playbookPath(playbook); } else if ((playbook = getPlaybookInline()) != null) { runner = AnsibleRunner.playbookInline(playbook); } else if ((module = getModule()) != null) { runner = AnsibleRunner.adHoc(module, getModuleArgs()); } else { throw new ConfigurationException("Missing module or playbook job arguments"); } final AuthenticationType authType = getSshAuthenticationType(); if (AuthenticationType.privateKey == authType) { final String privateKey = getSshPrivateKey(); if (privateKey != null) { runner = runner.sshPrivateKey(privateKey); } } else if (AuthenticationType.password == authType) { final String password = getSshPassword(); if (password != null) { runner = runner.sshUsePassword(Boolean.TRUE).sshPass(password); } } // set rundeck options as environment variables Map<String,String> options = context.getDataContext().get("option"); if (options != null) { runner = runner.options(options); } String inventory = getInventory(); if (inventory != null) { runner = runner.setInventory(inventory); } String limit = getLimit(); if (limit != null) { runner = runner.limit(limit); } Boolean debug = getDebug(); if (debug != null) { if (debug == Boolean.TRUE) { runner = runner.debug(Boolean.TRUE); } else { runner = runner.debug(Boolean.FALSE); } } String extraParams = getExtraParams(); if (extraParams != null) { runner = runner.extraParams(extraParams); } String extraVars = getExtraVars(); if (extraVars != null) { runner = runner.extraVars(extraVars); } String user = getSshUser(); if (user != null) { runner = runner.sshUser(user); } String vault = getVaultKey(); if (vault != null) { runner = runner.vaultPass(vault); } Integer timeout = getSSHTimeout(); if (timeout != null) { runner = runner.sshTimeout(timeout); } Boolean become = getBecome(); if (become != null) { runner = runner.become(become); } String become_user = getBecomeUser(); if (become_user != null) { runner = runner.becomeUser(become_user); } BecomeMethodType become_method = getBecomeMethod(); if (become_method != null) { runner = runner.becomeMethod(become_method.name()); } String become_password = getBecomePassword(); if (become_password != null) { runner = runner.becomePassword(become_password); } String configFile = getConfigFile(); if (configFile != null) { runner = runner.configFile(configFile); } String baseDir = getBaseDir(); if (baseDir != null) { runner = runner.baseDirectory(baseDir); } return runner; } public ExecutionContext getContext() { return context; } public Framework getFramework() { return framework; } public INodeEntry getNode() { return nodes.size() == 1 ? nodes.iterator().next() : null; } public String getFrameworkProject() { return frameworkProject; } public Map<String,Object> getjobConf() { return jobConf; } public void cleanupTempFiles() { for (File temp : tempFiles) { if (!getDebug()) { temp.delete(); } } tempFiles.clear(); } }
Fixing NPE on getInventory method: https://github.com/Batix/rundeck-ansible-plugin/issues/182
src/main/java/com/batix/rundeck/core/AnsibleRunnerBuilder.java
Fixing NPE on getInventory method: https://github.com/Batix/rundeck-ansible-plugin/issues/182
Java
mit
cc751be96959a3bf8e04b4600c41c024982396f6
0
GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth,GluuFederation/oxAuth
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.oxauth.client.model; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule; import org.gluu.oxauth.model.crypto.AbstractCryptoProvider; import org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm; import org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm; import org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm; import org.gluu.oxauth.model.exception.InvalidJwtException; import org.gluu.oxauth.model.jwe.Jwe; import org.gluu.oxauth.model.jwe.JweEncrypterImpl; import org.gluu.oxauth.model.jwt.JwtClaims; import org.gluu.oxauth.model.jwt.JwtHeader; import org.gluu.oxauth.model.jwt.JwtType; import org.gluu.oxauth.model.util.Base64Util; import org.gluu.oxauth.model.util.Util; import static org.gluu.oxauth.model.jwt.JwtStateClaimName.*; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.PublicKey; /** * @author Javier Rojas Blum * @version November 20, 2018 */ public class JwtState { private static final Logger LOG = Logger.getLogger(JwtState.class); // Header private JwtType type; private SignatureAlgorithm signatureAlgorithm; private KeyEncryptionAlgorithm keyEncryptionAlgorithm; private BlockEncryptionAlgorithm blockEncryptionAlgorithm; private String keyId; // Payload private String rfp; private String iat; private String exp; private String iss; private String aud; private String targetLinkUri; private String as; private String jti; private String atHash; private String cHash; private JSONObject additionalClaims; // Signature/Encryption Keys private String sharedKey; private AbstractCryptoProvider cryptoProvider; public JwtState(SignatureAlgorithm signatureAlgorithm, AbstractCryptoProvider cryptoProvider) { this(signatureAlgorithm, cryptoProvider, null, null, null); } public JwtState(SignatureAlgorithm signatureAlgorithm, String sharedKey, AbstractCryptoProvider cryptoProvider) { this(signatureAlgorithm, cryptoProvider, null, null, sharedKey); } public JwtState(KeyEncryptionAlgorithm keyEncryptionAlgorithm, BlockEncryptionAlgorithm blockEncryptionAlgorithm, AbstractCryptoProvider cryptoProvider) { this(null, cryptoProvider, keyEncryptionAlgorithm, blockEncryptionAlgorithm, null); } public JwtState(KeyEncryptionAlgorithm keyEncryptionAlgorithm, BlockEncryptionAlgorithm blockEncryptionAlgorithm, String sharedKey) { this(null, null, keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedKey); } private JwtState(SignatureAlgorithm signatureAlgorithm, AbstractCryptoProvider cryptoProvider, KeyEncryptionAlgorithm keyEncryptionAlgorithm, BlockEncryptionAlgorithm blockEncryptionAlgorithm, String sharedKey) { this.type = JwtType.JWT; this.signatureAlgorithm = signatureAlgorithm; this.cryptoProvider = cryptoProvider; this.keyEncryptionAlgorithm = keyEncryptionAlgorithm; this.blockEncryptionAlgorithm = blockEncryptionAlgorithm; this.sharedKey = sharedKey; } public JwtType getType() { return type; } public void setType(JwtType type) { this.type = type; } public SignatureAlgorithm getSignatureAlgorithm() { return signatureAlgorithm; } public void setSignatureAlgorithm(SignatureAlgorithm signatureAlgorithm) { this.signatureAlgorithm = signatureAlgorithm; } public KeyEncryptionAlgorithm getKeyEncryptionAlgorithm() { return keyEncryptionAlgorithm; } public void setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm keyEncryptionAlgorithm) { this.keyEncryptionAlgorithm = keyEncryptionAlgorithm; } public BlockEncryptionAlgorithm getBlockEncryptionAlgorithm() { return blockEncryptionAlgorithm; } public void setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm blockEncryptionAlgorithm) { this.blockEncryptionAlgorithm = blockEncryptionAlgorithm; } /** * Identifier of the key used to sign this state token at the issuer. * Identifier of the key used to encrypt this JWT state token at the issuer. * * @return The key identifier */ public String getKeyId() { return keyId; } /** * Identifier of the key used to sign this state token at the issuer. * Identifier of the key used to encrypt this JWT state token at the issuer. * * @param keyId The key identifier */ public void setKeyId(String keyId) { this.keyId = keyId; } /** * String containing a verifiable identifier for the browser session, * that cannot be guessed by a third party. * The verification of this element by the client protects it from * accepting authorization responses generated in response to forged * requests generated by third parties. * * @return The Request Forgery Protection value */ public String getRfp() { return rfp; } /** * String containing a verifiable identifier for the browser session, * that cannot be guessed by a third party. * The verification of this element by the client protects it from * accepting authorization responses generated in response to forged * requests generated by third parties. * * @param rfp The Request Forgery Protection value */ public void setRfp(String rfp) { this.rfp = rfp; } /** * Timestamp of when this Authorization Request was issued. * * @return The Issued at value */ public String getIat() { return iat; } /** * Timestamp of when this Authorization Request was issued. * * @param iat The Issued at value */ public void setIat(String iat) { this.iat = iat; } /** * The expiration time claim identifies the expiration time on or after which * the JWT MUST NOT be accepted for processing. * The processing of the "exp" claim requires that the current date/time MUST * be before the expiration date/time listed in the "exp" claim. * Implementers MAY provide for some small leeway, usually no more than a * few minutes, to account for clock skew. * Its value MUST be a number containing an IntDate value. * * @return The expiration time value */ public String getExp() { return exp; } /** * The expiration time claim identifies the expiration time on or after which * the JWT MUST NOT be accepted for processing. * The processing of the "exp" claim requires that the current date/time MUST * be before the expiration date/time listed in the "exp" claim. * Implementers MAY provide for some small leeway, usually no more than a * few minutes, to account for clock skew. * Its value MUST be a number containing an IntDate value. * * @param exp The expiration time value */ public void setExp(String exp) { this.exp = exp; } /** * String identifying the party that issued this state value. * * @return The issuer value */ public String getIss() { return iss; } /** * String identifying the party that issued this state value. * * @param iss The issuer value */ public void setIss(String iss) { this.iss = iss; } /** * String identifying the client that this state value is intended for. * * @return The audience */ public String getAud() { return aud; } /** * String identifying the client that this state value is intended for. * * @param aud The audience */ public void setAud(String aud) { this.aud = aud; } /** * URI containing the location the user agent is to be redirected to after authorization. * * @return The target link URI */ public String getTargetLinkUri() { return targetLinkUri; } /** * URI containing the location the user agent is to be redirected to after authorization. * * @param targetLinkUri The target link URI */ public void setTargetLinkUri(String targetLinkUri) { this.targetLinkUri = targetLinkUri; } /** * String identifying the authorization server that this request was sent to. * * @return The authorization server */ public String getAs() { return as; } /** * String identifying the authorization server that this request was sent to. * * @param as The authorization server */ public void setAs(String as) { this.as = as; } /** * The "jti" (JWT ID) claim provides a unique identifier for the JWT. * The identifier value MUST be assigned in a manner that ensures that * there is a negligible probability that the same value will be * accidentally assigned to a different data object. * The "jti" claim can be used to prevent the JWT from being replayed. * The "jti" value is a case-sensitive string. * * @return The JWT ID */ public String getJti() { return jti; } /** * The "jti" (JWT ID) claim provides a unique identifier for the JWT. * The identifier value MUST be assigned in a manner that ensures that * there is a negligible probability that the same value will be * accidentally assigned to a different data object. * The "jti" claim can be used to prevent the JWT from being replayed. * The "jti" value is a case-sensitive string. * * @param jti The JWT ID */ public void setJti(String jti) { this.jti = jti; } /** * Access Token hash value. Its value is the base64url encoding of the left-most half * of the hash of the octets of the ASCII representation of the "access_token" value, * where the hash algorithm used is the hash algorithm used in the "alg" parameter of * the State Token's JWS header. * For instance, if the "alg" is "RS256", hash the "access_token" value with SHA-256, * then take the left-most 128 bits and base64url encode them. * The "at_hash" value is a case sensitive string. * This is REQUIRED if the JWT [RFC7519] state token is being produced by the AS and * issued with a "access_token" in the authorization response. * * @return The access token hash value */ public String getAtHash() { return atHash; } /** * Access Token hash value. Its value is the base64url encoding of the left-most half * of the hash of the octets of the ASCII representation of the "access_token" value, * where the hash algorithm used is the hash algorithm used in the "alg" parameter of * the State Token's JWS header. * For instance, if the "alg" is "RS256", hash the "access_token" value with SHA-256, * then take the left-most 128 bits and base64url encode them. * The "at_hash" value is a case sensitive string. * This is REQUIRED if the JWT [RFC7519] state token is being produced by the AS and * issued with a "access_token" in the authorization response. * * @param atHash The access token hash value */ public void setAtHash(String atHash) { this.atHash = atHash; } /** * Code hash value. Its value is the base64url encoding of the left-most half of the * hash of the octets of the ASCII representation of the "code" value, where the hash * algorithm used is the hash algorithm used in the "alg" header parameter of the * State Token's JWS [RFC7515] header. * For instance, if the "alg" is "HS512", hash the "code" value with SHA-512, then * take the left-most 256 bits and base64url encode them. * The "c_hash" value is a case sensitive string. * This is REQUIRED if the JWT [RFC7519] state token is being produced by the AS and * issued with a "code" in the authorization response. * * @return The code hash value */ public String getcHash() { return cHash; } /** * Code hash value. Its value is the base64url encoding of the left-most half of the * hash of the octets of the ASCII representation of the "code" value, where the hash * algorithm used is the hash algorithm used in the "alg" header parameter of the * State Token's JWS [RFC7515] header. * For instance, if the "alg" is "HS512", hash the "code" value with SHA-512, then * take the left-most 256 bits and base64url encode them. * The "c_hash" value is a case sensitive string. * This is REQUIRED if the JWT [RFC7519] state token is being produced by the AS and * issued with a "code" in the authorization response. * * @param cHash The code hash value */ public void setcHash(String cHash) { this.cHash = cHash; } public JSONObject getAdditionalClaims() { return additionalClaims; } public void setAdditionalClaims(JSONObject additionalClaims) { this.additionalClaims = additionalClaims; } public String getEncodedJwt(JSONObject jwks) throws Exception { String encodedJwt = null; if (keyEncryptionAlgorithm != null && blockEncryptionAlgorithm != null) { JweEncrypterImpl jweEncrypter; if (cryptoProvider != null && jwks != null) { PublicKey publicKey = cryptoProvider.getPublicKey(keyId, jwks); jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, publicKey); } else { jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedKey.getBytes(Util.UTF8_STRING_ENCODING)); } String header = toPrettyJson(headerToJSONObject()); String encodedHeader = Base64Util.base64urlencode(header.getBytes(Util.UTF8_STRING_ENCODING)); String claims = toPrettyJson(payloadToJSONObject()); String encodedClaims = Base64Util.base64urlencode(claims.getBytes(Util.UTF8_STRING_ENCODING)); Jwe jwe = new Jwe(); jwe.setHeader(new JwtHeader(encodedHeader)); jwe.setClaims(new JwtClaims(encodedClaims)); jweEncrypter.encrypt(jwe); encodedJwt = jwe.toString(); } else { if (cryptoProvider == null) { throw new Exception("The Crypto Provider cannot be null."); } JSONObject headerJsonObject = headerToJSONObject(); JSONObject payloadJsonObject = payloadToJSONObject(); String headerString = headerJsonObject.toString(); String payloadString = payloadJsonObject.toString(); String encodedHeader = Base64Util.base64urlencode(headerString.getBytes(Util.UTF8_STRING_ENCODING)); String encodedPayload = Base64Util.base64urlencode(payloadString.getBytes(Util.UTF8_STRING_ENCODING)); String signingInput = encodedHeader + "." + encodedPayload; String encodedSignature = cryptoProvider.sign(signingInput, keyId, sharedKey, signatureAlgorithm); encodedJwt = encodedHeader + "." + encodedPayload + "." + encodedSignature; } return encodedJwt; } public String getEncodedJwt() throws Exception { return getEncodedJwt(null); } protected JSONObject headerToJSONObject() throws InvalidJwtException { JwtHeader jwtHeader = new JwtHeader(); jwtHeader.setType(type); if (keyEncryptionAlgorithm != null && blockEncryptionAlgorithm != null) { jwtHeader.setAlgorithm(keyEncryptionAlgorithm); jwtHeader.setEncryptionMethod(blockEncryptionAlgorithm); } else { jwtHeader.setAlgorithm(signatureAlgorithm); } jwtHeader.setKeyId(keyId); return jwtHeader.toJsonObject(); } protected JSONObject payloadToJSONObject() throws JSONException { JSONObject obj = new JSONObject(); try { if (StringUtils.isNotBlank(rfp)) { obj.put(RFP, rfp); } if (StringUtils.isNotBlank(keyId)) { obj.put(KID, keyId); } if (StringUtils.isNotBlank(iat)) { obj.put(IAT, iat); } if (StringUtils.isNotBlank(exp)) { obj.put(EXP, exp); } if (StringUtils.isNotBlank(iss)) { obj.put(ISS, iss); } if (StringUtils.isNotBlank(aud)) { obj.put(AUD, aud); } if (StringUtils.isNotBlank(targetLinkUri)) { obj.put(TARGET_LINK_URI, URLEncoder.encode(targetLinkUri, "UTF-8")); } if (StringUtils.isNotBlank(as)) { obj.put(AS, as); } if (StringUtils.isNotBlank(jti)) { obj.put(JTI, jti); } if (StringUtils.isNotBlank(atHash)) { obj.put(AT_HASH, atHash); } if (StringUtils.isNotBlank(cHash)) { obj.put(C_HASH, cHash); } if (additionalClaims != null) { obj.put(ADDITIONAL_CLAIMS, additionalClaims); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return obj; } public String toPrettyJson(JSONObject jsonObject) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonOrgModule()); return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject); } }
Client/src/main/java/org/gluu/oxauth/client/model/JwtState.java
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.gluu.oxauth.client.model; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import org.gluu.oxauth.model.crypto.AbstractCryptoProvider; import org.gluu.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm; import org.gluu.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm; import org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm; import org.gluu.oxauth.model.exception.InvalidJwtException; import org.gluu.oxauth.model.jwe.Jwe; import org.gluu.oxauth.model.jwe.JweEncrypterImpl; import org.gluu.oxauth.model.jwt.JwtClaims; import org.gluu.oxauth.model.jwt.JwtHeader; import org.gluu.oxauth.model.jwt.JwtType; import org.gluu.oxauth.model.util.Base64Util; import org.gluu.oxauth.model.util.Util; import static org.gluu.oxauth.model.jwt.JwtStateClaimName.*; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.PublicKey; /** * @author Javier Rojas Blum * @version November 20, 2018 */ public class JwtState { private static final Logger LOG = Logger.getLogger(JwtState.class); // Header private JwtType type; private SignatureAlgorithm signatureAlgorithm; private KeyEncryptionAlgorithm keyEncryptionAlgorithm; private BlockEncryptionAlgorithm blockEncryptionAlgorithm; private String keyId; // Payload private String rfp; private String iat; private String exp; private String iss; private String aud; private String targetLinkUri; private String as; private String jti; private String atHash; private String cHash; private JSONObject additionalClaims; // Signature/Encryption Keys private String sharedKey; private AbstractCryptoProvider cryptoProvider; public JwtState(SignatureAlgorithm signatureAlgorithm, AbstractCryptoProvider cryptoProvider) { this(signatureAlgorithm, cryptoProvider, null, null, null); } public JwtState(SignatureAlgorithm signatureAlgorithm, String sharedKey, AbstractCryptoProvider cryptoProvider) { this(signatureAlgorithm, cryptoProvider, null, null, sharedKey); } public JwtState(KeyEncryptionAlgorithm keyEncryptionAlgorithm, BlockEncryptionAlgorithm blockEncryptionAlgorithm, AbstractCryptoProvider cryptoProvider) { this(null, cryptoProvider, keyEncryptionAlgorithm, blockEncryptionAlgorithm, null); } public JwtState(KeyEncryptionAlgorithm keyEncryptionAlgorithm, BlockEncryptionAlgorithm blockEncryptionAlgorithm, String sharedKey) { this(null, null, keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedKey); } private JwtState(SignatureAlgorithm signatureAlgorithm, AbstractCryptoProvider cryptoProvider, KeyEncryptionAlgorithm keyEncryptionAlgorithm, BlockEncryptionAlgorithm blockEncryptionAlgorithm, String sharedKey) { this.type = JwtType.JWT; this.signatureAlgorithm = signatureAlgorithm; this.cryptoProvider = cryptoProvider; this.keyEncryptionAlgorithm = keyEncryptionAlgorithm; this.blockEncryptionAlgorithm = blockEncryptionAlgorithm; this.sharedKey = sharedKey; } public JwtType getType() { return type; } public void setType(JwtType type) { this.type = type; } public SignatureAlgorithm getSignatureAlgorithm() { return signatureAlgorithm; } public void setSignatureAlgorithm(SignatureAlgorithm signatureAlgorithm) { this.signatureAlgorithm = signatureAlgorithm; } public KeyEncryptionAlgorithm getKeyEncryptionAlgorithm() { return keyEncryptionAlgorithm; } public void setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm keyEncryptionAlgorithm) { this.keyEncryptionAlgorithm = keyEncryptionAlgorithm; } public BlockEncryptionAlgorithm getBlockEncryptionAlgorithm() { return blockEncryptionAlgorithm; } public void setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm blockEncryptionAlgorithm) { this.blockEncryptionAlgorithm = blockEncryptionAlgorithm; } /** * Identifier of the key used to sign this state token at the issuer. * Identifier of the key used to encrypt this JWT state token at the issuer. * * @return The key identifier */ public String getKeyId() { return keyId; } /** * Identifier of the key used to sign this state token at the issuer. * Identifier of the key used to encrypt this JWT state token at the issuer. * * @param keyId The key identifier */ public void setKeyId(String keyId) { this.keyId = keyId; } /** * String containing a verifiable identifier for the browser session, * that cannot be guessed by a third party. * The verification of this element by the client protects it from * accepting authorization responses generated in response to forged * requests generated by third parties. * * @return The Request Forgery Protection value */ public String getRfp() { return rfp; } /** * String containing a verifiable identifier for the browser session, * that cannot be guessed by a third party. * The verification of this element by the client protects it from * accepting authorization responses generated in response to forged * requests generated by third parties. * * @param rfp The Request Forgery Protection value */ public void setRfp(String rfp) { this.rfp = rfp; } /** * Timestamp of when this Authorization Request was issued. * * @return The Issued at value */ public String getIat() { return iat; } /** * Timestamp of when this Authorization Request was issued. * * @param iat The Issued at value */ public void setIat(String iat) { this.iat = iat; } /** * The expiration time claim identifies the expiration time on or after which * the JWT MUST NOT be accepted for processing. * The processing of the "exp" claim requires that the current date/time MUST * be before the expiration date/time listed in the "exp" claim. * Implementers MAY provide for some small leeway, usually no more than a * few minutes, to account for clock skew. * Its value MUST be a number containing an IntDate value. * * @return The expiration time value */ public String getExp() { return exp; } /** * The expiration time claim identifies the expiration time on or after which * the JWT MUST NOT be accepted for processing. * The processing of the "exp" claim requires that the current date/time MUST * be before the expiration date/time listed in the "exp" claim. * Implementers MAY provide for some small leeway, usually no more than a * few minutes, to account for clock skew. * Its value MUST be a number containing an IntDate value. * * @param exp The expiration time value */ public void setExp(String exp) { this.exp = exp; } /** * String identifying the party that issued this state value. * * @return The issuer value */ public String getIss() { return iss; } /** * String identifying the party that issued this state value. * * @param iss The issuer value */ public void setIss(String iss) { this.iss = iss; } /** * String identifying the client that this state value is intended for. * * @return The audience */ public String getAud() { return aud; } /** * String identifying the client that this state value is intended for. * * @param aud The audience */ public void setAud(String aud) { this.aud = aud; } /** * URI containing the location the user agent is to be redirected to after authorization. * * @return The target link URI */ public String getTargetLinkUri() { return targetLinkUri; } /** * URI containing the location the user agent is to be redirected to after authorization. * * @param targetLinkUri The target link URI */ public void setTargetLinkUri(String targetLinkUri) { this.targetLinkUri = targetLinkUri; } /** * String identifying the authorization server that this request was sent to. * * @return The authorization server */ public String getAs() { return as; } /** * String identifying the authorization server that this request was sent to. * * @param as The authorization server */ public void setAs(String as) { this.as = as; } /** * The "jti" (JWT ID) claim provides a unique identifier for the JWT. * The identifier value MUST be assigned in a manner that ensures that * there is a negligible probability that the same value will be * accidentally assigned to a different data object. * The "jti" claim can be used to prevent the JWT from being replayed. * The "jti" value is a case-sensitive string. * * @return The JWT ID */ public String getJti() { return jti; } /** * The "jti" (JWT ID) claim provides a unique identifier for the JWT. * The identifier value MUST be assigned in a manner that ensures that * there is a negligible probability that the same value will be * accidentally assigned to a different data object. * The "jti" claim can be used to prevent the JWT from being replayed. * The "jti" value is a case-sensitive string. * * @param jti The JWT ID */ public void setJti(String jti) { this.jti = jti; } /** * Access Token hash value. Its value is the base64url encoding of the left-most half * of the hash of the octets of the ASCII representation of the "access_token" value, * where the hash algorithm used is the hash algorithm used in the "alg" parameter of * the State Token's JWS header. * For instance, if the "alg" is "RS256", hash the "access_token" value with SHA-256, * then take the left-most 128 bits and base64url encode them. * The "at_hash" value is a case sensitive string. * This is REQUIRED if the JWT [RFC7519] state token is being produced by the AS and * issued with a "access_token" in the authorization response. * * @return The access token hash value */ public String getAtHash() { return atHash; } /** * Access Token hash value. Its value is the base64url encoding of the left-most half * of the hash of the octets of the ASCII representation of the "access_token" value, * where the hash algorithm used is the hash algorithm used in the "alg" parameter of * the State Token's JWS header. * For instance, if the "alg" is "RS256", hash the "access_token" value with SHA-256, * then take the left-most 128 bits and base64url encode them. * The "at_hash" value is a case sensitive string. * This is REQUIRED if the JWT [RFC7519] state token is being produced by the AS and * issued with a "access_token" in the authorization response. * * @param atHash The access token hash value */ public void setAtHash(String atHash) { this.atHash = atHash; } /** * Code hash value. Its value is the base64url encoding of the left-most half of the * hash of the octets of the ASCII representation of the "code" value, where the hash * algorithm used is the hash algorithm used in the "alg" header parameter of the * State Token's JWS [RFC7515] header. * For instance, if the "alg" is "HS512", hash the "code" value with SHA-512, then * take the left-most 256 bits and base64url encode them. * The "c_hash" value is a case sensitive string. * This is REQUIRED if the JWT [RFC7519] state token is being produced by the AS and * issued with a "code" in the authorization response. * * @return The code hash value */ public String getcHash() { return cHash; } /** * Code hash value. Its value is the base64url encoding of the left-most half of the * hash of the octets of the ASCII representation of the "code" value, where the hash * algorithm used is the hash algorithm used in the "alg" header parameter of the * State Token's JWS [RFC7515] header. * For instance, if the "alg" is "HS512", hash the "code" value with SHA-512, then * take the left-most 256 bits and base64url encode them. * The "c_hash" value is a case sensitive string. * This is REQUIRED if the JWT [RFC7519] state token is being produced by the AS and * issued with a "code" in the authorization response. * * @param cHash The code hash value */ public void setcHash(String cHash) { this.cHash = cHash; } public JSONObject getAdditionalClaims() { return additionalClaims; } public void setAdditionalClaims(JSONObject additionalClaims) { this.additionalClaims = additionalClaims; } public String getEncodedJwt(JSONObject jwks) throws Exception { String encodedJwt = null; if (keyEncryptionAlgorithm != null && blockEncryptionAlgorithm != null) { JweEncrypterImpl jweEncrypter; if (cryptoProvider != null && jwks != null) { PublicKey publicKey = cryptoProvider.getPublicKey(keyId, jwks); jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, publicKey); } else { jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, sharedKey.getBytes(Util.UTF8_STRING_ENCODING)); } String header = headerToJSONObject().toString(); String encodedHeader = Base64Util.base64urlencode(header.getBytes(Util.UTF8_STRING_ENCODING)); String claims = payloadToJSONObject().toString(); String encodedClaims = Base64Util.base64urlencode(claims.getBytes(Util.UTF8_STRING_ENCODING)); Jwe jwe = new Jwe(); jwe.setHeader(new JwtHeader(encodedHeader)); jwe.setClaims(new JwtClaims(encodedClaims)); jweEncrypter.encrypt(jwe); encodedJwt = jwe.toString(); } else { if (cryptoProvider == null) { throw new Exception("The Crypto Provider cannot be null."); } JSONObject headerJsonObject = headerToJSONObject(); JSONObject payloadJsonObject = payloadToJSONObject(); String headerString = headerJsonObject.toString(); String payloadString = payloadJsonObject.toString(); String encodedHeader = Base64Util.base64urlencode(headerString.getBytes(Util.UTF8_STRING_ENCODING)); String encodedPayload = Base64Util.base64urlencode(payloadString.getBytes(Util.UTF8_STRING_ENCODING)); String signingInput = encodedHeader + "." + encodedPayload; String encodedSignature = cryptoProvider.sign(signingInput, keyId, sharedKey, signatureAlgorithm); encodedJwt = encodedHeader + "." + encodedPayload + "." + encodedSignature; } return encodedJwt; } public String getEncodedJwt() throws Exception { return getEncodedJwt(null); } protected JSONObject headerToJSONObject() throws InvalidJwtException { JwtHeader jwtHeader = new JwtHeader(); jwtHeader.setType(type); if (keyEncryptionAlgorithm != null && blockEncryptionAlgorithm != null) { jwtHeader.setAlgorithm(keyEncryptionAlgorithm); jwtHeader.setEncryptionMethod(blockEncryptionAlgorithm); } else { jwtHeader.setAlgorithm(signatureAlgorithm); } jwtHeader.setKeyId(keyId); return jwtHeader.toJsonObject(); } protected JSONObject payloadToJSONObject() throws JSONException { JSONObject obj = new JSONObject(); try { if (StringUtils.isNotBlank(rfp)) { obj.put(RFP, rfp); } if (StringUtils.isNotBlank(keyId)) { obj.put(KID, keyId); } if (StringUtils.isNotBlank(iat)) { obj.put(IAT, iat); } if (StringUtils.isNotBlank(exp)) { obj.put(EXP, exp); } if (StringUtils.isNotBlank(iss)) { obj.put(ISS, iss); } if (StringUtils.isNotBlank(aud)) { obj.put(AUD, aud); } if (StringUtils.isNotBlank(targetLinkUri)) { obj.put(TARGET_LINK_URI, URLEncoder.encode(targetLinkUri, "UTF-8")); } if (StringUtils.isNotBlank(as)) { obj.put(AS, as); } if (StringUtils.isNotBlank(jti)) { obj.put(JTI, jti); } if (StringUtils.isNotBlank(atHash)) { obj.put(AT_HASH, atHash); } if (StringUtils.isNotBlank(cHash)) { obj.put(C_HASH, cHash); } if (additionalClaims != null) { obj.put(ADDITIONAL_CLAIMS, additionalClaims); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return obj; } }
Fix Jwt stte json serialization
Client/src/main/java/org/gluu/oxauth/client/model/JwtState.java
Fix Jwt stte json serialization
Java
mit
bbfb82f7bc7a8d9d10fa79ae8b305ed5c4f28ebd
0
d2fn/passage,d2fn/passage,d2fn/passage,d2fn/passage
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2012-13 The Processing Foundation Copyright (c) 2004-12 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.core; import io.measures.passage.geometry.Projectable2D; import processing.data.*; import processing.event.*; import processing.event.Event; import processing.opengl.*; import java.applet.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.text.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JFileChooser; import javax.swing.filechooser.FileSystemView; /** * Base class for all sketches that use processing.core. * <p/> * Note that you should not use AWT or Swing components inside a Processing * applet. The surface is made to automatically update itself, and will cause * problems with redraw of components drawn above it. If you'd like to * integrate other Java components, see below. * <p/> * The <A HREF="http://wiki.processing.org/w/Window_Size_and_Full_Screen"> * Window Size and Full Screen</A> page on the Wiki has useful information * about sizing, multiple displays, full screen, etc. * <p/> * As of release 0145, Processing uses active mode rendering in all cases. * All animation tasks happen on the "Processing Animation Thread". The * setup() and draw() methods are handled by that thread, and events (like * mouse movement and key presses, which are fired by the event dispatch * thread or EDT) are queued to be (safely) handled at the end of draw(). * For code that needs to run on the EDT, use SwingUtilities.invokeLater(). * When doing so, be careful to synchronize between that code (since * invokeLater() will make your code run from the EDT) and the Processing * animation thread. Use of a callback function or the registerXxx() methods * in PApplet can help ensure that your code doesn't do something naughty. * <p/> * As of Processing 2.0, we have discontinued support for versions of Java * prior to 1.6. We don't have enough people to support it, and for a * project of our (tiny) size, we should be focusing on the future, rather * than working around legacy Java code. * <p/> * This class extends Applet instead of JApplet because 1) historically, * we supported Java 1.1, which does not include Swing (without an * additional, sizable, download), and 2) Swing is a bloated piece of crap. * A Processing applet is a heavyweight AWT component, and can be used the * same as any other AWT component, with or without Swing. * <p/> * Similarly, Processing runs in a Frame and not a JFrame. However, there's * nothing to prevent you from embedding a PApplet into a JFrame, it's just * that the base version uses a regular AWT frame because there's simply * no need for Swing in that context. If people want to use Swing, they can * embed themselves as they wish. * <p/> * It is possible to use PApplet, along with core.jar in other projects. * This also allows you to embed a Processing drawing area into another Java * application. This means you can use standard GUI controls with a Processing * sketch. Because AWT and Swing GUI components cannot be used on top of a * PApplet, you can instead embed the PApplet inside another GUI the way you * would any other Component. * <p/> * Because the default animation thread will run at 60 frames per second, * an embedded PApplet can make the parent application sluggish. You can use * frameRate() to make it update less often, or you can use noLoop() and loop() * to disable and then re-enable looping. If you want to only update the sketch * intermittently, use noLoop() inside setup(), and redraw() whenever the * screen needs to be updated once (or loop() to re-enable the animation * thread). The following example embeds a sketch and also uses the noLoop() * and redraw() methods. You need not use noLoop() and redraw() when embedding * if you want your application to animate continuously. * <PRE> * public class ExampleFrame extends Frame { * * public ExampleFrame() { * super("Embedded PApplet"); * * setLayout(new BorderLayout()); * PApplet embed = new Embedded(); * add(embed, BorderLayout.CENTER); * * // important to call this whenever embedding a PApplet. * // It ensures that the animation thread is started and * // that other internal variables are properly set. * embed.init(); * } * } * * public class Embedded extends PApplet { * * public void setup() { * // original setup code here ... * size(400, 400); * * // prevent thread from starving everything else * noLoop(); * } * * public void draw() { * // drawing code goes here * } * * public void mousePressed() { * // do something based on mouse movement * * // update the screen (run draw once) * redraw(); * } * } * </PRE> * @usage Web &amp; Application */ public class PApplet extends Applet implements PConstants, Runnable, MouseListener, MouseWheelListener, MouseMotionListener, KeyListener, FocusListener { /** * Full name of the Java version (i.e. 1.5.0_11). * Prior to 0125, this was only the first three digits. */ public static final String javaVersionName = System.getProperty("java.version"); /** * Version of Java that's in use, whether 1.1 or 1.3 or whatever, * stored as a float. * <p> * Note that because this is stored as a float, the values may * not be <EM>exactly</EM> 1.3 or 1.4. Instead, make sure you're * comparing against 1.3f or 1.4f, which will have the same amount * of error (i.e. 1.40000001). This could just be a double, but * since Processing only uses floats, it's safer for this to be a float * because there's no good way to specify a double with the preproc. */ public static final float javaVersion = new Float(javaVersionName.substring(0, 3)).floatValue(); /** * Current platform in use. * <p> * Equivalent to System.getProperty("os.name"), just used internally. */ /** * Current platform in use, one of the * PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER. */ static public int platform; /** * Name associated with the current 'platform' (see PConstants.platformNames) */ //static public String platformName; static { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { platform = MACOSX; } else if (osname.indexOf("Windows") != -1) { platform = WINDOWS; } else if (osname.equals("Linux")) { // true for the ibm vm platform = LINUX; } else { platform = OTHER; } } /** * Setting for whether to use the Quartz renderer on OS X. The Quartz * renderer is on its way out for OS X, but Processing uses it by default * because it's much faster than the Sun renderer. In some cases, however, * the Quartz renderer is preferred. For instance, fonts are less thick * when using the Sun renderer, so to improve how fonts look, * change this setting before you call PApplet.main(). * <pre> * static public void main(String[] args) { * PApplet.useQuartz = false; * PApplet.main(new String[] { "YourSketch" }); * } * </pre> * This setting must be called before any AWT work happens, so that's why * it's such a terrible hack in how it's employed here. Calling setProperty() * inside setup() is a joke, since it's long since the AWT has been invoked. * <p/> * On OS X with a retina display, this option is ignored, because Apple's * Java implementation takes over and forces the Quartz renderer. */ // static public boolean useQuartz = true; static public boolean useQuartz = false; /** * Whether to use native (AWT) dialogs for selectInput and selectOutput. * The native dialogs on Linux tend to be pretty awful. With selectFolder() * this is ignored, because there is no native folder selector, except on * Mac OS X. On OS X, the native folder selector will be used unless * useNativeSelect is set to false. */ static public boolean useNativeSelect = (platform != LINUX); // /** // * Modifier flags for the shortcut key used to trigger menus. // * (Cmd on Mac OS X, Ctrl on Linux and Windows) // */ // static public final int MENU_SHORTCUT = // Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** The PGraphics renderer associated with this PApplet */ public PGraphics g; /** The frame containing this applet (if any) */ public Frame frame; // disabled on retina inside init() boolean useActive = true; // boolean useActive = false; // boolean useStrategy = true; boolean useStrategy = false; Canvas canvas; // /** // * Usually just 0, but with multiple displays, the X and Y coordinates of // * the screen will depend on the current screen's position relative to // * the other displays. // */ // public int displayX; // public int displayY; /** * ( begin auto-generated from screenWidth.xml ) * * System variable which stores the width of the computer screen. For * example, if the current screen resolution is 1024x768, * <b>displayWidth</b> is 1024 and <b>displayHeight</b> is 768. These * dimensions are useful when exporting full-screen applications. * <br /><br /> * To ensure that the sketch takes over the entire screen, use "Present" * instead of "Run". Otherwise the window will still have a frame border * around it and not be placed in the upper corner of the screen. On Mac OS * X, the menu bar will remain present unless "Present" mode is used. * * ( end auto-generated ) * @webref environment */ public int displayWidth; /** * ( begin auto-generated from screenHeight.xml ) * * System variable that stores the height of the computer screen. For * example, if the current screen resolution is 1024x768, * <b>screenWidth</b> is 1024 and <b>screenHeight</b> is 768. These * dimensions are useful when exporting full-screen applications. * <br /><br /> * To ensure that the sketch takes over the entire screen, use "Present" * instead of "Run". Otherwise the window will still have a frame border * around it and not be placed in the upper corner of the screen. On Mac OS * X, the menu bar will remain present unless "Present" mode is used. * * ( end auto-generated ) * @webref environment */ public int displayHeight; /** * A leech graphics object that is echoing all events. */ public PGraphics recorder; /** * Command line options passed in from main(). * <p> * This does not include the arguments passed in to PApplet itself. */ public String[] args; /** Path to sketch folder */ public String sketchPath; //folder; static final boolean DEBUG = false; // static final boolean DEBUG = true; /** Default width and height for applet when not specified */ static public final int DEFAULT_WIDTH = 100; static public final int DEFAULT_HEIGHT = 100; /** * Minimum dimensions for the window holding an applet. This varies between * platforms, Mac OS X 10.3 (confirmed with 10.7 and Java 6) can do any * height but requires at least 128 pixels width. Windows XP has another * set of limitations. And for all I know, Linux probably lets you make * windows with negative sizes. */ static public final int MIN_WINDOW_WIDTH = 128; static public final int MIN_WINDOW_HEIGHT = 128; /** * Gets set by main() if --present (old) or --full-screen (newer) are used, * and is returned by sketchFullscreen() when initializing in main(). */ // protected boolean fullScreen = false; /** * Exception thrown when size() is called the first time. * <p> * This is used internally so that setup() is forced to run twice * when the renderer is changed. This is the only way for us to handle * invoking the new renderer while also in the midst of rendering. */ static public class RendererChangeException extends RuntimeException { } /** * true if no size() command has been executed. This is used to wait until * a size has been set before placing in the window and showing it. */ public boolean defaultSize; /** Storage for the current renderer size to avoid re-allocation. */ Dimension currentSize = new Dimension(); // volatile boolean resizeRequest; // volatile int resizeWidth; // volatile int resizeHeight; /** * ( begin auto-generated from pixels.xml ) * * Array containing the values for all the pixels in the display window. * These values are of the color datatype. This array is the size of the * display window. For example, if the image is 100x100 pixels, there will * be 10000 values and if the window is 200x300 pixels, there will be 60000 * values. The <b>index</b> value defines the position of a value within * the array. For example, the statement <b>color b = pixels[230]</b> will * set the variable <b>b</b> to be equal to the value at that location in * the array.<br /> * <br /> * Before accessing this array, the data must loaded with the * <b>loadPixels()</b> function. After the array data has been modified, * the <b>updatePixels()</b> function must be run to update the changes. * Without <b>loadPixels()</b>, running the code may (or will in future * releases) result in a NullPointerException. * * ( end auto-generated ) * * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#updatePixels() * @see PApplet#get(int, int, int, int) * @see PApplet#set(int, int, int) * @see PImage */ public int pixels[]; /** * ( begin auto-generated from width.xml ) * * System variable which stores the width of the display window. This value * is set by the first parameter of the <b>size()</b> function. For * example, the function call <b>size(320, 240)</b> sets the <b>width</b> * variable to the value 320. The value of <b>width</b> is zero until * <b>size()</b> is called. * * ( end auto-generated ) * @webref environment */ public int width; /** * ( begin auto-generated from height.xml ) * * System variable which stores the height of the display window. This * value is set by the second parameter of the <b>size()</b> function. For * example, the function call <b>size(320, 240)</b> sets the <b>height</b> * variable to the value 240. The value of <b>height</b> is zero until * <b>size()</b> is called. * * ( end auto-generated ) * @webref environment * */ public int height; /** * ( begin auto-generated from mouseX.xml ) * * The system variable <b>mouseX</b> always contains the current horizontal * coordinate of the mouse. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * * */ public int mouseX; /** * ( begin auto-generated from mouseY.xml ) * * The system variable <b>mouseY</b> always contains the current vertical * coordinate of the mouse. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * */ public int mouseY; /** * ( begin auto-generated from pmouseX.xml ) * * The system variable <b>pmouseX</b> always contains the horizontal * position of the mouse in the frame previous to the current frame.<br /> * <br /> * You may find that <b>pmouseX</b> and <b>pmouseY</b> have different * values inside <b>draw()</b> and inside events like <b>mousePressed()</b> * and <b>mouseMoved()</b>. This is because they're used for different * roles, so don't mix them. Inside <b>draw()</b>, <b>pmouseX</b> and * <b>pmouseY</b> update only once per frame (once per trip through your * <b>draw()</b>). But, inside mouse events, they update each time the * event is called. If they weren't separated, then the mouse would be read * only once per frame, making response choppy. If the mouse variables were * always updated multiple times per frame, using <NOBR><b>line(pmouseX, * pmouseY, mouseX, mouseY)</b></NOBR> inside <b>draw()</b> would have lots * of gaps, because <b>pmouseX</b> may have changed several times in * between the calls to <b>line()</b>. Use <b>pmouseX</b> and * <b>pmouseY</b> inside <b>draw()</b> if you want values relative to the * previous frame. Use <b>pmouseX</b> and <b>pmouseY</b> inside the mouse * functions if you want continuous response. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#pmouseY * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseX; /** * ( begin auto-generated from pmouseY.xml ) * * The system variable <b>pmouseY</b> always contains the vertical position * of the mouse in the frame previous to the current frame. More detailed * information about how <b>pmouseY</b> is updated inside of <b>draw()</b> * and mouse events is explained in the reference for <b>pmouseX</b>. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#pmouseX * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseY; /** * previous mouseX/Y for the draw loop, separated out because this is * separate from the pmouseX/Y when inside the mouse event handlers. */ protected int dmouseX, dmouseY; /** * pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc) * these are different because mouse events are queued to the end of * draw, so the previous position has to be updated on each event, * as opposed to the pmouseX/Y that's used inside draw, which is expected * to be updated once per trip through draw(). */ protected int emouseX, emouseY; /** * Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used, * otherwise pmouseX/Y are always zero, causing a nasty jump. * <p> * Just using (frameCount == 0) won't work since mouseXxxxx() * may not be called until a couple frames into things. * <p> * @deprecated Please refrain from using this variable, it will be removed * from future releases of Processing because it cannot be used consistently * across platforms and input methods. */ @Deprecated public boolean firstMouse; /** * ( begin auto-generated from mouseButton.xml ) * * Processing automatically tracks if the mouse button is pressed and which * button is pressed. The value of the system variable <b>mouseButton</b> * is either <b>LEFT</b>, <b>RIGHT</b>, or <b>CENTER</b> depending on which * button is pressed. * * ( end auto-generated ) * * <h3>Advanced:</h3> * * If running on Mac OS, a ctrl-click will be interpreted as the right-hand * mouse button (unlike Java, which reports it as the left mouse). * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public int mouseButton; /** * ( begin auto-generated from mousePressed_var.xml ) * * Variable storing if a mouse button is pressed. The value of the system * variable <b>mousePressed</b> is true if a mouse button is pressed and * false if a button is not pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public boolean mousePressed; /** * @deprecated Use a mouse event handler that passes an event instead. */ @Deprecated public MouseEvent mouseEvent; /** * ( begin auto-generated from key.xml ) * * The system variable <b>key</b> always contains the value of the most * recent key on the keyboard that was used (either pressed or released). * <br/> <br/> * For non-ASCII keys, use the <b>keyCode</b> variable. The keys included * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and * DELETE) do not require checking to see if they key is coded, and you * should simply use the <b>key</b> variable instead of <b>keyCode</b> If * you're making cross-platform projects, note that the ENTER key is * commonly used on PCs and Unix and the RETURN key is used instead on * Macintosh. Check for both ENTER and RETURN to make sure your program * will work for all platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Last key pressed. * <p> * If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT, * this will be set to CODED (0xffff or 65535). * * @webref input:keyboard * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public char key; /** * ( begin auto-generated from keyCode.xml ) * * The variable <b>keyCode</b> is used to detect special keys such as the * UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking * for these keys, it's first necessary to check and see if the key is * coded. This is done with the conditional "if (key == CODED)" as shown in * the example. * <br/> <br/> * The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, * RETURN, ESC, and DELETE) do not require checking to see if they key is * coded, and you should simply use the <b>key</b> variable instead of * <b>keyCode</b> If you're making cross-platform projects, note that the * ENTER key is commonly used on PCs and Unix and the RETURN key is used * instead on Macintosh. Check for both ENTER and RETURN to make sure your * program will work for all platforms. * <br/> <br/> * For users familiar with Java, the values for UP and DOWN are simply * shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other * keyCode values can be found in the Java <a * href="http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html">KeyEvent</a> reference. * * ( end auto-generated ) * * <h3>Advanced</h3> * When "key" is set to CODED, this will contain a Java key code. * <p> * For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT. * Also available are ALT, CONTROL and SHIFT. A full set of constants * can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables. * * @webref input:keyboard * @see PApplet#key * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public int keyCode; /** * ( begin auto-generated from keyPressed_var.xml ) * * The boolean system variable <b>keyPressed</b> is <b>true</b> if any key * is pressed and <b>false</b> if no keys are pressed. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public boolean keyPressed; /** * The last KeyEvent object passed into a mouse function. * @deprecated Use a key event handler that passes an event instead. */ @Deprecated public KeyEvent keyEvent; /** * ( begin auto-generated from focused.xml ) * * Confirms if a Processing program is "focused", meaning that it is active * and will accept input from mouse or keyboard. This variable is "true" if * it is focused and "false" if not. This variable is often used when you * want to warn people they need to click on or roll over an applet before * it will work. * * ( end auto-generated ) * @webref environment */ public boolean focused = false; /** * Confirms if a Processing program is running inside a web browser. This * variable is "true" if the program is online and "false" if not. */ @Deprecated public boolean online = false; // This is deprecated because it's poorly named (and even more poorly // understood). Further, we'll probably be removing applets soon, in which // case this won't work at all. If you want this feature, you can check // whether getAppletContext() returns null. /** * Time in milliseconds when the applet was started. * <p> * Used by the millis() function. */ long millisOffset = System.currentTimeMillis(); /** * ( begin auto-generated from frameRate_var.xml ) * * The system variable <b>frameRate</b> contains the approximate frame rate * of the software as it executes. The initial value is 10 fps and is * updated with each frame. The value is averaged (integrated) over several * frames. As such, this value won't be valid until after 5-10 frames. * * ( end auto-generated ) * @webref environment * @see PApplet#frameRate(float) */ public float frameRate = 10; /** Last time in nanoseconds that frameRate was checked */ protected long frameRateLastNanos = 0; /** As of release 0116, frameRate(60) is called as a default */ protected float frameRateTarget = 60; protected long frameRatePeriod = 1000000000L / 60L; protected boolean looping; /** flag set to true when a redraw is asked for by the user */ protected boolean redraw; /** * ( begin auto-generated from frameCount.xml ) * * The system variable <b>frameCount</b> contains the number of frames * displayed since the program started. Inside <b>setup()</b> the value is * 0 and and after the first iteration of draw it is 1, etc. * * ( end auto-generated ) * @webref environment * @see PApplet#frameRate(float) */ public int frameCount; /** true if the sketch has stopped permanently. */ public volatile boolean finished; /** * true if the animation thread is paused. */ public volatile boolean paused; /** * true if exit() has been called so that things shut down * once the main thread kicks off. */ protected boolean exitCalled; Object pauseObject = new Object(); Thread thread; // messages to send if attached as an external vm /** * Position of the upper-lefthand corner of the editor window * that launched this applet. */ static public final String ARGS_EDITOR_LOCATION = "--editor-location"; /** * Location for where to position the applet window on screen. * <p> * This is used by the editor to when saving the previous applet * location, or could be used by other classes to launch at a * specific position on-screen. */ static public final String ARGS_EXTERNAL = "--external"; static public final String ARGS_LOCATION = "--location"; static public final String ARGS_DISPLAY = "--display"; static public final String ARGS_BGCOLOR = "--bgcolor"; /** @deprecated use --full-screen instead. */ static public final String ARGS_PRESENT = "--present"; static public final String ARGS_FULL_SCREEN = "--full-screen"; // static public final String ARGS_EXCLUSIVE = "--exclusive"; static public final String ARGS_STOP_COLOR = "--stop-color"; static public final String ARGS_HIDE_STOP = "--hide-stop"; /** * Allows the user or PdeEditor to set a specific sketch folder path. * <p> * Used by PdeEditor to pass in the location where saveFrame() * and all that stuff should write things. */ static public final String ARGS_SKETCH_FOLDER = "--sketch-path"; /** * When run externally to a PdeEditor, * this is sent by the applet when it quits. */ //static public final String EXTERNAL_QUIT = "__QUIT__"; static public final String EXTERNAL_STOP = "__STOP__"; /** * When run externally to a PDE Editor, this is sent by the applet * whenever the window is moved. * <p> * This is used so that the editor can re-open the sketch window * in the same position as the user last left it. */ static public final String EXTERNAL_MOVE = "__MOVE__"; /** true if this sketch is being run by the PDE */ boolean external = false; /** * Not official API, using internally because of the tweaks required. */ boolean retina; static final String ERROR_MIN_MAX = "Cannot use min() or max() on an empty array."; // during rev 0100 dev cycle, working on new threading model, // but need to disable and go conservative with changes in order // to get pdf and audio working properly first. // for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs. //static final boolean CRUSTY_THREADS = false; //true; /** * Applet initialization. This can do GUI work because the components have * not been 'realized' yet: things aren't visible, displayed, etc. */ @Override public void init() { // println("init() called " + Integer.toHexString(hashCode())); // using a local version here since the class variable is deprecated // Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // screenWidth = screen.width; // screenHeight = screen.height; if (checkRetina()) { // The active-mode rendering seems to be 2x slower, so disable it // with retina. On a non-retina machine, however, useActive seems // the only (or best) way to handle the rendering. useActive = false; } // send tab keys through to the PApplet setFocusTraversalKeysEnabled(false); //millisOffset = System.currentTimeMillis(); // moved to the variable declaration finished = false; // just for clarity // this will be cleared by draw() if it is not overridden looping = true; redraw = true; // draw this guy once firstMouse = true; // these need to be inited before setup // sizeMethods = new RegisteredMethods(); // pauseMethods = new RegisteredMethods(); // resumeMethods = new RegisteredMethods(); // preMethods = new RegisteredMethods(); // drawMethods = new RegisteredMethods(); // postMethods = new RegisteredMethods(); // mouseEventMethods = new RegisteredMethods(); // keyEventMethods = new RegisteredMethods(); // disposeMethods = new RegisteredMethods(); try { getAppletContext(); online = true; } catch (NullPointerException e) { online = false; } try { if (sketchPath == null) { sketchPath = System.getProperty("user.dir"); } } catch (Exception e) { } // may be a security problem Dimension size = getSize(); if ((size.width != 0) && (size.height != 0)) { // When this PApplet is embedded inside a Java application with other // Component objects, its size() may already be set externally (perhaps // by a LayoutManager). In this case, honor that size as the default. // Size of the component is set, just create a renderer. g = makeGraphics(size.width, size.height, sketchRenderer(), null, true); // This doesn't call setSize() or setPreferredSize() because the fact // that a size was already set means that someone is already doing it. } else { // Set the default size, until the user specifies otherwise this.defaultSize = true; int w = sketchWidth(); int h = sketchHeight(); g = makeGraphics(w, h, sketchRenderer(), null, true); // Fire component resize event setSize(w, h); setPreferredSize(new Dimension(w, h)); } width = g.width; height = g.height; // addListeners(); // 2.0a6 // moved out of addListeners() in 2.0a6 addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; if (!looping) { redraw(); } } }); // if (thread == null) { // paused = true; thread = new Thread(this, "Animation Thread"); thread.start(); // } // this is automatically called in applets // though it's here for applications anyway // start(); } private boolean checkRetina() { if (platform == MACOSX) { // This should probably be reset each time there's a display change. // A 5-minute search didn't turn up any such event in the Java API. // Also, should we use the Toolkit associated with the editor window? final String javaVendor = System.getProperty("java.vendor"); if (javaVendor.contains("Apple")) { Float prop = (Float) getToolkit().getDesktopProperty("apple.awt.contentScaleFactor"); if (prop != null) { return prop == 2; } } else if (javaVendor.contains("Oracle")) { String version = System.getProperty("java.version"); // 1.7.0_40 String[] m = match(version, "1.(\\d).*_(\\d+)"); // Make sure this is Oracle Java 7u40 or later if (m != null && PApplet.parseInt(m[1]) >= 7 && PApplet.parseInt(m[1]) >= 40) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = env.getDefaultScreenDevice(); try { Field field = device.getClass().getDeclaredField("scale"); if (field != null) { field.setAccessible(true); Object scale = field.get(device); if (scale instanceof Integer && ((Integer)scale).intValue() == 2) { return true; } } } catch (Exception ignore) { } } } } return false; } public int sketchQuality() { return 2; } public int sketchWidth() { return DEFAULT_WIDTH; } public int sketchHeight() { return DEFAULT_HEIGHT; } public String sketchRenderer() { return JAVA2D; } public boolean sketchFullScreen() { // return fullScreen; return false; } public void orientation(int which) { // ignore calls to the orientation command } /** * Called by the browser or applet viewer to inform this applet that it * should start its execution. It is called after the init method and * each time the applet is revisited in a Web page. * <p/> * Called explicitly via the first call to PApplet.paint(), because * PAppletGL needs to have a usable screen before getting things rolling. */ @Override public void start() { debug("start() called"); // new Exception().printStackTrace(System.out); paused = false; // unpause the thread resume(); // resumeMethods.handle(); handleMethods("resume"); debug("un-pausing thread"); synchronized (pauseObject) { debug("start() calling pauseObject.notifyAll()"); // try { pauseObject.notifyAll(); // wake up the animation thread debug("un-pausing thread 3"); // } catch (InterruptedException e) { } } } /** * Called by the browser or applet viewer to inform * this applet that it should stop its execution. * <p/> * Unfortunately, there are no guarantees from the Java spec * when or if stop() will be called (i.e. on browser quit, * or when moving between web pages), and it's not always called. */ @Override public void stop() { // this used to shut down the sketch, but that code has // been moved to destroy/dispose() // if (paused) { // synchronized (pauseObject) { // try { // pauseObject.wait(); // } catch (InterruptedException e) { // // waiting for this interrupt on a start() (resume) call // } // } // } // on the next trip through the animation thread, things will go sleepy-by paused = true; // causes animation thread to sleep pause(); handleMethods("pause"); // actual pause will happen in the run() method // synchronized (pauseObject) { // debug("stop() calling pauseObject.wait()"); // try { // pauseObject.wait(); // } catch (InterruptedException e) { // // waiting for this interrupt on a start() (resume) call // } // } } /** * Sketch has been paused. Called when switching tabs in a browser or * swapping to a different application on Android. Also called just before * quitting. Use to safely disable things like serial, sound, or sensors. */ public void pause() { } /** * Sketch has resumed. Called when switching tabs in a browser or * swapping to this application on Android. Also called on startup. * Use this to safely disable things like serial, sound, or sensors. */ public void resume() { } /** * Called by the browser or applet viewer to inform this applet * that it is being reclaimed and that it should destroy * any resources that it has allocated. * <p/> * destroy() supposedly gets called as the applet viewer * is shutting down the applet. stop() is called * first, and then destroy() to really get rid of things. * no guarantees on when they're run (on browser quit, or * when moving between pages), though. */ @Override public void destroy() { this.dispose(); } ////////////////////////////////////////////////////////////// /** Map of registered methods, stored by name. */ HashMap<String, RegisteredMethods> registerMap = new HashMap<String, PApplet.RegisteredMethods>(); class RegisteredMethods { int count; Object[] objects; // Because the Method comes from the class being called, // it will be unique for most, if not all, objects. Method[] methods; Object[] emptyArgs = new Object[] { }; void handle() { handle(emptyArgs); } void handle(Object[] args) { for (int i = 0; i < count; i++) { try { methods[i].invoke(objects[i], args); } catch (Exception e) { // check for wrapped exception, get root exception Throwable t; if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; t = ite.getCause(); } else { t = e; } // check for RuntimeException, and allow to bubble up if (t instanceof RuntimeException) { // re-throw exception throw (RuntimeException) t; } else { // trap and print as usual t.printStackTrace(); } } } } void add(Object object, Method method) { if (findIndex(object) == -1) { if (objects == null) { objects = new Object[5]; methods = new Method[5]; } else if (count == objects.length) { objects = (Object[]) PApplet.expand(objects); methods = (Method[]) PApplet.expand(methods); } objects[count] = object; methods[count] = method; count++; } else { die(method.getName() + "() already added for this instance of " + object.getClass().getName()); } } /** * Removes first object/method pair matched (and only the first, * must be called multiple times if object is registered multiple times). * Does not shrink array afterwards, silently returns if method not found. */ // public void remove(Object object, Method method) { // int index = findIndex(object, method); public void remove(Object object) { int index = findIndex(object); if (index != -1) { // shift remaining methods by one to preserve ordering count--; for (int i = index; i < count; i++) { objects[i] = objects[i+1]; methods[i] = methods[i+1]; } // clean things out for the gc's sake objects[count] = null; methods[count] = null; } } // protected int findIndex(Object object, Method method) { protected int findIndex(Object object) { for (int i = 0; i < count; i++) { if (objects[i] == object) { // if (objects[i] == object && methods[i].equals(method)) { //objects[i].equals() might be overridden, so use == for safety // since here we do care about actual object identity //methods[i]==method is never true even for same method, so must use // equals(), this should be safe because of object identity return i; } } return -1; } } /** * Register a built-in event so that it can be fired for libraries, etc. * Supported events include: * <ul> * <li>pre – at the very top of the draw() method (safe to draw) * <li>draw – at the end of the draw() method (safe to draw) * <li>post – after draw() has exited (not safe to draw) * <li>pause – called when the sketch is paused * <li>resume – called when the sketch is resumed * <li>dispose – when the sketch is shutting down (definitely not safe to draw) * <ul> * In addition, the new (for 2.0) processing.event classes are passed to * the following event types: * <ul> * <li>mouseEvent * <li>keyEvent * <li>touchEvent * </ul> * The older java.awt events are no longer supported. * See the Library Wiki page for more details. * @param methodName name of the method to be called * @param target the target object that should receive the event */ public void registerMethod(String methodName, Object target) { if (methodName.equals("mouseEvent")) { registerWithArgs("mouseEvent", target, new Class[] { processing.event.MouseEvent.class }); } else if (methodName.equals("keyEvent")) { registerWithArgs("keyEvent", target, new Class[] { processing.event.KeyEvent.class }); } else if (methodName.equals("touchEvent")) { registerWithArgs("touchEvent", target, new Class[] { processing.event.TouchEvent.class }); } else { registerNoArgs(methodName, target); } } private void registerNoArgs(String name, Object o) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { meth = new RegisteredMethods(); registerMap.put(name, meth); } Class<?> c = o.getClass(); try { Method method = c.getMethod(name, new Class[] {}); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } private void registerWithArgs(String name, Object o, Class<?> cargs[]) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { meth = new RegisteredMethods(); registerMap.put(name, meth); } Class<?> c = o.getClass(); try { Method method = c.getMethod(name, cargs); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } // public void registerMethod(String methodName, Object target, Object... args) { // registerWithArgs(methodName, target, args); // } public void unregisterMethod(String name, Object target) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { die("No registered methods with the name " + name + "() were found."); } try { // Method method = o.getClass().getMethod(name, new Class[] {}); // meth.remove(o, method); meth.remove(target); } catch (Exception e) { die("Could not unregister " + name + "() for " + target, e); } } protected void handleMethods(String methodName) { RegisteredMethods meth = registerMap.get(methodName); if (meth != null) { meth.handle(); } } protected void handleMethods(String methodName, Object[] args) { RegisteredMethods meth = registerMap.get(methodName); if (meth != null) { meth.handle(args); } } @Deprecated public void registerSize(Object o) { System.err.println("The registerSize() command is no longer supported."); // Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; // registerWithArgs(sizeMethods, "size", o, methodArgs); } @Deprecated public void registerPre(Object o) { registerNoArgs("pre", o); } @Deprecated public void registerDraw(Object o) { registerNoArgs("draw", o); } @Deprecated public void registerPost(Object o) { registerNoArgs("post", o); } @Deprecated public void registerDispose(Object o) { registerNoArgs("dispose", o); } @Deprecated public void unregisterSize(Object o) { System.err.println("The unregisterSize() command is no longer supported."); // Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; // unregisterWithArgs(sizeMethods, "size", o, methodArgs); } @Deprecated public void unregisterPre(Object o) { unregisterMethod("pre", o); } @Deprecated public void unregisterDraw(Object o) { unregisterMethod("draw", o); } @Deprecated public void unregisterPost(Object o) { unregisterMethod("post", o); } @Deprecated public void unregisterDispose(Object o) { unregisterMethod("dispose", o); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // Old methods with AWT API that should not be used. // These were never implemented on Android so they're stored separately. RegisteredMethods mouseEventMethods, keyEventMethods; protected void reportDeprecation(Class<?> c, boolean mouse) { if (g != null) { PGraphics.showWarning("The class " + c.getName() + " is incompatible with Processing 2.0."); PGraphics.showWarning("A library (or other code) is using register" + (mouse ? "Mouse" : "Key") + "Event() " + "which is no longer available."); // This will crash with OpenGL, so quit anyway if (g instanceof PGraphicsOpenGL) { PGraphics.showWarning("Stopping the sketch because this code will " + "not work correctly with OpenGL."); throw new RuntimeException("This sketch uses a library that " + "needs to be updated for Processing 2.0."); } } } @Deprecated public void registerMouseEvent(Object o) { Class<?> c = o.getClass(); reportDeprecation(c, true); try { Method method = c.getMethod("mouseEvent", new Class[] { java.awt.event.MouseEvent.class }); if (mouseEventMethods == null) { mouseEventMethods = new RegisteredMethods(); } mouseEventMethods.add(o, method); } catch (Exception e) { die("Could not register mouseEvent() for " + o, e); } } @Deprecated public void unregisterMouseEvent(Object o) { try { // Method method = o.getClass().getMethod("mouseEvent", new Class[] { MouseEvent.class }); // mouseEventMethods.remove(o, method); mouseEventMethods.remove(o); } catch (Exception e) { die("Could not unregister mouseEvent() for " + o, e); } } @Deprecated public void registerKeyEvent(Object o) { Class<?> c = o.getClass(); reportDeprecation(c, false); try { Method method = c.getMethod("keyEvent", new Class[] { java.awt.event.KeyEvent.class }); if (keyEventMethods == null) { keyEventMethods = new RegisteredMethods(); } keyEventMethods.add(o, method); } catch (Exception e) { die("Could not register keyEvent() for " + o, e); } } @Deprecated public void unregisterKeyEvent(Object o) { try { // Method method = o.getClass().getMethod("keyEvent", new Class[] { KeyEvent.class }); // keyEventMethods.remove(o, method); keyEventMethods.remove(o); } catch (Exception e) { die("Could not unregister keyEvent() for " + o, e); } } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from setup.xml ) * * The <b>setup()</b> function is called once when the program starts. It's * used to define initial * enviroment properties such as screen size and background color and to * load media such as images * and fonts as the program starts. There can only be one <b>setup()</b> * function for each program and * it shouldn't be called again after its initial execution. Note: * Variables declared within * <b>setup()</b> are not accessible within other functions, including * <b>draw()</b>. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#size(int, int) * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#draw() */ public void setup() { } /** * ( begin auto-generated from draw.xml ) * * Called directly after <b>setup()</b> and continuously executes the lines * of code contained inside its block until the program is stopped or * <b>noLoop()</b> is called. The <b>draw()</b> function is called * automatically and should never be called explicitly. It should always be * controlled with <b>noLoop()</b>, <b>redraw()</b> and <b>loop()</b>. * After <b>noLoop()</b> stops the code in <b>draw()</b> from executing, * <b>redraw()</b> causes the code inside <b>draw()</b> to execute once and * <b>loop()</b> will causes the code inside <b>draw()</b> to execute * continuously again. The number of times <b>draw()</b> executes in each * second may be controlled with <b>frameRate()</b> function. * There can only be one <b>draw()</b> function for each sketch * and <b>draw()</b> must exist if you want the code to run continuously or * to process events such as <b>mousePressed()</b>. Sometimes, you might * have an empty call to <b>draw()</b> in your program as shown in the * above example. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#setup() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#redraw() * @see PApplet#frameRate(float) */ public void draw() { // if no draw method, then shut things down //System.out.println("no draw method, goodbye"); finished = true; } ////////////////////////////////////////////////////////////// protected void resizeRenderer(int newWidth, int newHeight) { debug("resizeRenderer request for " + newWidth + " " + newHeight); if (width != newWidth || height != newHeight) { debug(" former size was " + width + " " + height); g.setSize(newWidth, newHeight); width = newWidth; height = newHeight; } } /** * ( begin auto-generated from size.xml ) * * Defines the dimension of the display window in units of pixels. The * <b>size()</b> function must be the first line in <b>setup()</b>. If * <b>size()</b> is not used, the default size of the window is 100x100 * pixels. The system variables <b>width</b> and <b>height</b> are set by * the parameters passed to this function.<br /> * <br /> * Do not use variables as the parameters to <b>size()</b> function, * because it will cause problems when exporting your sketch. When * variables are used, the dimensions of your sketch cannot be determined * during export. Instead, employ numeric values in the <b>size()</b> * statement, and then use the built-in <b>width</b> and <b>height</b> * variables inside your program when the dimensions of the display window * are needed.<br /> * <br /> * The <b>size()</b> function can only be used once inside a sketch, and * cannot be used for resizing.<br/> * <br/> <b>renderer</b> parameter selects which rendering engine to use. * For example, if you will be drawing 3D shapes, use <b>P3D</b>, if you * want to export images from a program as a PDF file use <b>PDF</b>. A * brief description of the three primary renderers follows:<br /> * <br /> * <b>P2D</b> (Processing 2D) - The default renderer that supports two * dimensional drawing.<br /> * <br /> * <b>P3D</b> (Processing 3D) - 3D graphics renderer that makes use of * OpenGL-compatible graphics hardware.<br /> * <br /> * <b>PDF</b> - The PDF renderer draws 2D graphics directly to an Acrobat * PDF file. This produces excellent results when you need vector shapes * for high resolution output or printing. You must first use Import * Library &rarr; PDF to make use of the library. More information can be * found in the PDF library reference.<br /> * <br /> * The P3D renderer doesn't support <b>strokeCap()</b> or * <b>strokeJoin()</b>, which can lead to ugly results when using * <b>strokeWeight()</b>. (<a * href="http://code.google.com/p/processing/issues/detail?id=123">Issue * 123</a>) <br /> * <br /> * The maximum width and height is limited by your operating system, and is * usually the width and height of your actual screen. On some machines it * may simply be the number of pixels on your current screen, meaning that * a screen of 800x600 could support <b>size(1600, 300)</b>, since it's the * same number of pixels. This varies widely so you'll have to try * different rendering modes and sizes until you get what you're looking * for. If you need something larger, use <b>createGraphics</b> to create a * non-visible drawing surface.<br /> * <br /> * Again, the <b>size()</b> function must be the first line of the code (or * first item inside setup). Any code that appears before the <b>size()</b> * command may run more than once, which can lead to confusing results. * * ( end auto-generated ) * * <h3>Advanced</h3> * If using Java 1.3 or later, this will default to using * PGraphics2, the Java2D-based renderer. If using Java 1.1, * or if PGraphics2 is not available, then PGraphics will be used. * To set your own renderer, use the other version of the size() * method that takes a renderer as its last parameter. * <p> * If called once a renderer has already been set, this will * use the previous renderer and simply resize it. * * @webref environment * @param w width of the display window in units of pixels * @param h height of the display window in units of pixels */ public void size(int w, int h) { size(w, h, JAVA2D, null); } /** * @param renderer Either P2D, P3D, or PDF */ public void size(int w, int h, String renderer) { size(w, h, renderer, null); } /** * @nowebref */ public void size(final int w, final int h, String renderer, String path) { // Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing) EventQueue.invokeLater(new Runnable() { public void run() { // Set the preferred size so that the layout managers can handle it setPreferredSize(new Dimension(w, h)); setSize(w, h); } }); // ensure that this is an absolute path if (path != null) path = savePath(path); String currentRenderer = g.getClass().getName(); if (currentRenderer.equals(renderer)) { // Avoid infinite loop of throwing exception to reset renderer resizeRenderer(w, h); //redraw(); // will only be called insize draw() } else { // renderer is being changed // otherwise ok to fall through and create renderer below // the renderer is changing, so need to create a new object g = makeGraphics(w, h, renderer, path, true); this.width = w; this.height = h; // fire resize event to make sure the applet is the proper size // setSize(iwidth, iheight); // this is the function that will run if the user does their own // size() command inside setup, so set defaultSize to false. defaultSize = false; // throw an exception so that setup() is called again // but with a properly sized render // this is for opengl, which needs a valid, properly sized // display before calling anything inside setup(). throw new RendererChangeException(); } } public PGraphics createGraphics(int w, int h) { return createGraphics(w, h, JAVA2D); } /** * ( begin auto-generated from createGraphics.xml ) * * Creates and returns a new <b>PGraphics</b> object of the types P2D or * P3D. Use this class if you need to draw into an off-screen graphics * buffer. The PDF renderer requires the filename parameter. The DXF * renderer should not be used with <b>createGraphics()</b>, it's only * built for use with <b>beginRaw()</b> and <b>endRaw()</b>.<br /> * <br /> * It's important to call any drawing functions between <b>beginDraw()</b> * and <b>endDraw()</b> statements. This is also true for any functions * that affect drawing, such as <b>smooth()</b> or <b>colorMode()</b>.<br/> * <br/> the main drawing surface which is completely opaque, surfaces * created with <b>createGraphics()</b> can have transparency. This makes * it possible to draw into a graphics and maintain the alpha channel. By * using <b>save()</b> to write a PNG or TGA file, the transparency of the * graphics object will be honored. Note that transparency levels are * binary: pixels are either complete opaque or transparent. For the time * being, this means that text characters will be opaque blocks. This will * be fixed in a future release (<a * href="http://code.google.com/p/processing/issues/detail?id=80">Issue 80</a>). * * ( end auto-generated ) * <h3>Advanced</h3> * Create an offscreen PGraphics object for drawing. This can be used * for bitmap or vector images drawing or rendering. * <UL> * <LI>Do not use "new PGraphicsXxxx()", use this method. This method * ensures that internal variables are set up properly that tie the * new graphics context back to its parent PApplet. * <LI>The basic way to create bitmap images is to use the <A * HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A> * function. * <LI>If you want to create a really large scene and write that, * first make sure that you've allocated a lot of memory in the Preferences. * <LI>If you want to create images that are larger than the screen, * you should create your own PGraphics object, draw to that, and use * <A HREF="http://processing.org/reference/save_.html">save()</A>. * <PRE> * * PGraphics big; * * void setup() { * big = createGraphics(3000, 3000); * * big.beginDraw(); * big.background(128); * big.line(20, 1800, 1800, 900); * // etc.. * big.endDraw(); * * // make sure the file is written to the sketch folder * big.save("big.tif"); * } * * </PRE> * <LI>It's important to always wrap drawing to createGraphics() with * beginDraw() and endDraw() (beginFrame() and endFrame() prior to * revision 0115). The reason is that the renderer needs to know when * drawing has stopped, so that it can update itself internally. * This also handles calling the defaults() method, for people familiar * with that. * <LI>With Processing 0115 and later, it's possible to write images in * formats other than the default .tga and .tiff. The exact formats and * background information can be found in the developer's reference for * <A HREF="http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)">PImage.save()</A>. * </UL> * * @webref rendering * @param w width in pixels * @param h height in pixels * @param renderer Either P2D, P3D, or PDF * * @see PGraphics#PGraphics * */ public PGraphics createGraphics(int w, int h, String renderer) { PGraphics pg = makeGraphics(w, h, renderer, null, false); //pg.parent = this; // make save() work return pg; } /** * Create an offscreen graphics surface for drawing, in this case * for a renderer that writes to a file (such as PDF or DXF). * @param path the name of the file (can be an absolute or relative path) */ public PGraphics createGraphics(int w, int h, String renderer, String path) { if (path != null) { path = savePath(path); } PGraphics pg = makeGraphics(w, h, renderer, path, false); pg.parent = this; // make save() work return pg; } /** * Version of createGraphics() used internally. */ protected PGraphics makeGraphics(int w, int h, String renderer, String path, boolean primary) { String openglError = external ? "Before using OpenGL, first select " + "Import Library > OpenGL from the Sketch menu." : "The Java classpath and native library path is not " + // welcome to Java programming! "properly set for using the OpenGL library."; if (!primary && !g.isGL()) { if (renderer.equals(P2D)) { throw new RuntimeException("createGraphics() with P2D requires size() to use P2D or P3D"); } else if (renderer.equals(P3D)) { throw new RuntimeException("createGraphics() with P3D or OPENGL requires size() to use P2D or P3D"); } } try { Class<?> rendererClass = Thread.currentThread().getContextClassLoader().loadClass(renderer); Constructor<?> constructor = rendererClass.getConstructor(new Class[] { }); PGraphics pg = (PGraphics) constructor.newInstance(); pg.setParent(this); pg.setPrimary(primary); if (path != null) pg.setPath(path); // pg.setQuality(sketchQuality()); pg.setSize(w, h); // everything worked, return it return pg; } catch (InvocationTargetException ite) { String msg = ite.getTargetException().getMessage(); if ((msg != null) && (msg.indexOf("no jogl in java.library.path") != -1)) { throw new RuntimeException(openglError + " (The native library is missing.)"); } else { ite.getTargetException().printStackTrace(); Throwable target = ite.getTargetException(); if (platform == MACOSX) target.printStackTrace(System.out); // bug // neither of these help, or work //target.printStackTrace(System.err); //System.err.flush(); //System.out.println(System.err); // and the object isn't null throw new RuntimeException(target.getMessage()); } } catch (ClassNotFoundException cnfe) { if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsOpenGL") != -1) { throw new RuntimeException(openglError + " (The library .jar file is missing.)"); } else { throw new RuntimeException("You need to use \"Import Library\" " + "to add " + renderer + " to your sketch."); } } catch (Exception e) { if ((e instanceof IllegalArgumentException) || (e instanceof NoSuchMethodException) || (e instanceof IllegalAccessException)) { if (e.getMessage().contains("cannot be <= 0")) { // IllegalArgumentException will be thrown if w/h is <= 0 // http://code.google.com/p/processing/issues/detail?id=983 throw new RuntimeException(e); } else { e.printStackTrace(); String msg = renderer + " needs to be updated " + "for the current release of Processing."; throw new RuntimeException(msg); } } else { if (platform == MACOSX) e.printStackTrace(System.out); throw new RuntimeException(e.getMessage()); } } } /** * ( begin auto-generated from createImage.xml ) * * Creates a new PImage (the datatype for storing images). This provides a * fresh buffer of pixels to play with. Set the size of the buffer with the * <b>width</b> and <b>height</b> parameters. The <b>format</b> parameter * defines how the pixels are stored. See the PImage reference for more information. * <br/> <br/> * Be sure to include all three parameters, specifying only the width and * height (but no format) will produce a strange error. * <br/> <br/> * Advanced users please note that createImage() should be used instead of * the syntax <tt>new PImage()</tt>. * * ( end auto-generated ) * <h3>Advanced</h3> * Preferred method of creating new PImage objects, ensures that a * reference to the parent PApplet is included, which makes save() work * without needing an absolute path. * * @webref image * @param w width in pixels * @param h height in pixels * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel) * @see PImage * @see PGraphics */ public PImage createImage(int w, int h, int format) { PImage image = new PImage(w, h, format); image.parent = this; // make save() work return image; } /* public PImage createImage(int w, int h, int format) { return createImage(w, h, format, null); } // unapproved public PImage createImage(int w, int h, int format, Object params) { PImage image = new PImage(w, h, format); if (params != null) { image.setParams(g, params); } image.parent = this; // make save() work return image; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . @Override public void update(Graphics screen) { paint(screen); } @Override public void paint(Graphics screen) { // int r = (int) random(10000); // System.out.println("into paint " + r); //super.paint(screen); // ignore the very first call to paint, since it's coming // from the o.s., and the applet will soon update itself anyway. if (frameCount == 0) { // println("Skipping frame"); // paint() may be called more than once before things // are finally painted to the screen and the thread gets going return; } // without ignoring the first call, the first several frames // are confused because paint() gets called in the midst of // the initial nextFrame() call, so there are multiple // updates fighting with one another. // make sure the screen is visible and usable // (also prevents over-drawing when using PGraphicsOpenGL) /* the 1.5.x version if (g != null) { // added synchronization for 0194 because of flicker issues with JAVA2D // http://code.google.com/p/processing/issues/detail?id=558 // g.image is synchronized so that draw/loop and paint don't // try to fight over it. this was causing a randomized slowdown // that would cut the frameRate into a third on macosx, // and is probably related to the windows sluggishness bug too if (g.image != null) { System.out.println("ui paint"); synchronized (g.image) { screen.drawImage(g.image, 0, 0, null); } } } */ // if (useActive) { // return; // } // if (insideDraw) { // new Exception().printStackTrace(System.out); // } if (!insideDraw && (g != null) && (g.image != null)) { if (useStrategy) { render(); } else { // System.out.println("drawing to screen"); //screen.drawImage(g.image, 0, 0, null); // not retina friendly screen.drawImage(g.image, 0, 0, width, height, null); } } else { debug(insideDraw + " " + g + " " + ((g != null) ? g.image : "-")); } } protected synchronized void render() { if (canvas == null) { removeListeners(this); canvas = new Canvas(); add(canvas); setIgnoreRepaint(true); canvas.setIgnoreRepaint(true); addListeners(canvas); // add(canvas, BorderLayout.CENTER); // doLayout(); } canvas.setBounds(0, 0, width, height); // System.out.println("render(), canvas bounds are " + canvas.getBounds()); if (canvas.getBufferStrategy() == null) { // whole block [121222] // System.out.println("creating a strategy"); canvas.createBufferStrategy(2); } BufferStrategy strategy = canvas.getBufferStrategy(); if (strategy == null) { return; } // Render single frame do { // The following loop ensures that the contents of the drawing buffer // are consistent in case the underlying surface was recreated do { Graphics draw = strategy.getDrawGraphics(); draw.drawImage(g.image, 0, 0, width, height, null); draw.dispose(); // Repeat the rendering if the drawing buffer contents // were restored // System.out.println("restored " + strategy.contentsRestored()); } while (strategy.contentsRestored()); // Display the buffer // System.out.println("showing"); strategy.show(); // Repeat the rendering if the drawing buffer was lost // System.out.println("lost " + strategy.contentsLost()); // System.out.println(); } while (strategy.contentsLost()); } /* // active paint method (also the 1.2.1 version) protected void paint() { try { Graphics screen = this.getGraphics(); if (screen != null) { if ((g != null) && (g.image != null)) { screen.drawImage(g.image, 0, 0, null); } Toolkit.getDefaultToolkit().sync(); } } catch (Exception e) { // Seen on applet destroy, maybe can ignore? e.printStackTrace(); // } finally { // if (g != null) { // g.dispose(); // } } } protected void paint_1_5_1() { try { Graphics screen = getGraphics(); if (screen != null) { if (g != null) { // added synchronization for 0194 because of flicker issues with JAVA2D // http://code.google.com/p/processing/issues/detail?id=558 if (g.image != null) { System.out.println("active paint"); synchronized (g.image) { screen.drawImage(g.image, 0, 0, null); } Toolkit.getDefaultToolkit().sync(); } } } } catch (Exception e) { // Seen on applet destroy, maybe can ignore? e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// /** * Main method for the primary animation thread. * * <A HREF="http://java.sun.com/products/jfc/tsc/articles/painting/">Painting in AWT and Swing</A> */ public void run() { // not good to make this synchronized, locks things up long beforeTime = System.nanoTime(); long overSleepTime = 0L; int noDelays = 0; // Number of frames with a delay of 0 ms before the // animation thread yields to other running threads. final int NO_DELAYS_PER_YIELD = 15; /* // this has to be called after the exception is thrown, // otherwise the supporting libs won't have a valid context to draw to Object methodArgs[] = new Object[] { new Integer(width), new Integer(height) }; sizeMethods.handle(methodArgs); */ if (!online) { start(); } while ((Thread.currentThread() == thread) && !finished) { if (paused) { debug("PApplet.run() paused, calling object wait..."); synchronized (pauseObject) { try { pauseObject.wait(); debug("out of wait"); } catch (InterruptedException e) { // waiting for this interrupt on a start() (resume) call } } } debug("done with pause"); // while (paused) { // debug("paused..."); // try { // Thread.sleep(100L); // } catch (InterruptedException e) { } // ignored // } // Don't resize the renderer from the EDT (i.e. from a ComponentEvent), // otherwise it may attempt a resize mid-render. // if (resizeRequest) { // resizeRenderer(resizeWidth, resizeHeight); // resizeRequest = false; // } if (g != null) { getSize(currentSize); if (currentSize.width != g.width || currentSize.height != g.height) { resizeRenderer(currentSize.width, currentSize.height); } } // render a single frame //handleDraw(); if (g != null) g.requestDraw(); if (frameCount == 1) { // for 2.0a6, moving this request to the EDT EventQueue.invokeLater(new Runnable() { public void run() { // Call the request focus event once the image is sure to be on // screen and the component is valid. The OpenGL renderer will // request focus for its canvas inside beginDraw(). // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // requestFocus(); // Changing to this version for 0187 // http://code.google.com/p/processing/issues/detail?id=279 //requestFocusInWindow(); // For 2.0, pass this to the renderer, to lend a hand to OpenGL g.requestFocus(); } }); } // wait for update & paint to happen before drawing next frame // this is necessary since the drawing is sometimes in a // separate thread, meaning that the next frame will start // before the update/paint is completed long afterTime = System.nanoTime(); long timeDiff = afterTime - beforeTime; //System.out.println("time diff is " + timeDiff); long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime; if (sleepTime > 0) { // some time left in this cycle try { // Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L)); noDelays = 0; // Got some sleep, not delaying anymore } catch (InterruptedException ex) { } overSleepTime = (System.nanoTime() - afterTime) - sleepTime; //System.out.println(" oversleep is " + overSleepTime); } else { // sleepTime <= 0; the frame took longer than the period // excess -= sleepTime; // store excess time value overSleepTime = 0L; noDelays++; if (noDelays > NO_DELAYS_PER_YIELD) { Thread.yield(); // give another thread a chance to run noDelays = 0; } } beforeTime = System.nanoTime(); } dispose(); // call to shutdown libs? // If the user called the exit() function, the window should close, // rather than the sketch just halting. if (exitCalled) { exitActual(); } } protected boolean insideDraw; //synchronized public void handleDisplay() { public void handleDraw() { debug("handleDraw() " + g + " " + looping + " " + redraw + " valid:" + this.isValid() + " visible:" + this.isVisible()); if (canDraw()) { if (!g.canDraw()) { debug("g.canDraw() is false"); // Don't draw if the renderer is not yet ready. // (e.g. OpenGL has to wait for a peer to be on screen) return; } insideDraw = true; g.beginDraw(); if (recorder != null) { recorder.beginDraw(); } long now = System.nanoTime(); if (frameCount == 0) { GraphicsConfiguration gc = getGraphicsConfiguration(); if (gc == null) return; GraphicsDevice displayDevice = getGraphicsConfiguration().getDevice(); if (displayDevice == null) return; Rectangle screenRect = displayDevice.getDefaultConfiguration().getBounds(); // screenX = screenRect.x; // screenY = screenRect.y; displayWidth = screenRect.width; displayHeight = screenRect.height; try { //println("Calling setup()"); setup(); //println("Done with setup()"); } catch (RendererChangeException e) { // Give up, instead set the new renderer and re-attempt setup() return; } this.defaultSize = false; } else { // frameCount > 0, meaning an actual draw() // update the current frameRate double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0); float instantaneousRate = (float) rate / 1000.0f; frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f); if (frameCount != 0) { handleMethods("pre"); } // use dmouseX/Y as previous mouse pos, since this is the // last position the mouse was in during the previous draw. pmouseX = dmouseX; pmouseY = dmouseY; //println("Calling draw()"); draw(); //println("Done calling draw()"); // dmouseX/Y is updated only once per frame (unlike emouseX/Y) dmouseX = mouseX; dmouseY = mouseY; // these are called *after* loop so that valid // drawing commands can be run inside them. it can't // be before, since a call to background() would wipe // out anything that had been drawn so far. dequeueEvents(); // dequeueMouseEvents(); // dequeueKeyEvents(); handleMethods("draw"); redraw = false; // unset 'redraw' flag in case it was set // (only do this once draw() has run, not just setup()) } g.endDraw(); if (recorder != null) { recorder.endDraw(); } insideDraw = false; if (useActive) { if (useStrategy) { render(); } else { Graphics screen = getGraphics(); screen.drawImage(g.image, 0, 0, width, height, null); } } else { repaint(); } // getToolkit().sync(); // force repaint now (proper method) if (frameCount != 0) { handleMethods("post"); } frameRateLastNanos = now; frameCount++; } } /** Not official API, not guaranteed to work in the future. */ public boolean canDraw() { return g != null && (looping || redraw); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from redraw.xml ) * * Executes the code within <b>draw()</b> one time. This functions allows * the program to update the display window only when necessary, for * example when an event registered by <b>mousePressed()</b> or * <b>keyPressed()</b> occurs. * <br/><br/> structuring a program, it only makes sense to call redraw() * within events such as <b>mousePressed()</b>. This is because * <b>redraw()</b> does not run <b>draw()</b> immediately (it only sets a * flag that indicates an update is needed). * <br/><br/> <b>redraw()</b> within <b>draw()</b> has no effect because * <b>draw()</b> is continuously called anyway. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#draw() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#frameRate(float) */ synchronized public void redraw() { if (!looping) { redraw = true; // if (thread != null) { // // wake from sleep (necessary otherwise it'll be // // up to 10 seconds before update) // if (CRUSTY_THREADS) { // thread.interrupt(); // } else { // synchronized (blocker) { // blocker.notifyAll(); // } // } // } } } /** * ( begin auto-generated from loop.xml ) * * Causes Processing to continuously execute the code within <b>draw()</b>. * If <b>noLoop()</b> is called, the code in <b>draw()</b> stops executing. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#noLoop() * @see PApplet#redraw() * @see PApplet#draw() */ synchronized public void loop() { if (!looping) { looping = true; } } /** * ( begin auto-generated from noLoop.xml ) * * Stops Processing from continuously executing the code within * <b>draw()</b>. If <b>loop()</b> is called, the code in <b>draw()</b> * begin to run continuously again. If using <b>noLoop()</b> in * <b>setup()</b>, it should be the last line inside the block. * <br/> <br/> * When <b>noLoop()</b> is used, it's not possible to manipulate or access * the screen inside event handling functions such as <b>mousePressed()</b> * or <b>keyPressed()</b>. Instead, use those functions to call * <b>redraw()</b> or <b>loop()</b>, which will run <b>draw()</b>, which * can update the screen properly. This means that when noLoop() has been * called, no drawing can happen, and functions like saveFrame() or * loadPixels() may not be used. * <br/> <br/> * Note that if the sketch is resized, <b>redraw()</b> will be called to * update the sketch, even after <b>noLoop()</b> has been specified. * Otherwise, the sketch would enter an odd state until <b>loop()</b> was called. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#loop() * @see PApplet#redraw() * @see PApplet#draw() */ synchronized public void noLoop() { if (looping) { looping = false; } } ////////////////////////////////////////////////////////////// // public void addListeners() { // addMouseListener(this); // addMouseMotionListener(this); // addKeyListener(this); // addFocusListener(this); // // addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; // // if (!looping) { // redraw(); // } // } // }); // } // // // public void removeListeners() { // removeMouseListener(this); // removeMouseMotionListener(this); // removeKeyListener(this); // removeFocusListener(this); // //// removeComponentListener(??); //// addComponentListener(new ComponentAdapter() { //// public void componentResized(ComponentEvent e) { //// Component c = e.getComponent(); //// //System.out.println("componentResized() " + c); //// Rectangle bounds = c.getBounds(); //// resizeRequest = true; //// resizeWidth = bounds.width; //// resizeHeight = bounds.height; //// //// if (!looping) { //// redraw(); //// } //// } //// }); // } public void addListeners(Component comp) { comp.addMouseListener(this); comp.addMouseWheelListener(this); comp.addMouseMotionListener(this); comp.addKeyListener(this); comp.addFocusListener(this); // canvas.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; // // if (!looping) { // redraw(); // } // } // }); } public void removeListeners(Component comp) { comp.removeMouseListener(this); comp.removeMouseWheelListener(this); comp.removeMouseMotionListener(this); comp.removeKeyListener(this); comp.removeFocusListener(this); } /** * Call to remove, then add, listeners to a component. * Avoids issues with double-adding. */ public void updateListeners(Component comp) { removeListeners(comp); addListeners(comp); } ////////////////////////////////////////////////////////////// // protected Event eventQueue[] = new Event[10]; // protected int eventCount; class InternalEventQueue { protected Event queue[] = new Event[10]; protected int offset; protected int count; synchronized void add(Event e) { if (count == queue.length) { queue = (Event[]) expand(queue); } queue[count++] = e; } synchronized Event remove() { if (offset == count) { throw new RuntimeException("Nothing left on the event queue."); } Event outgoing = queue[offset++]; if (offset == count) { // All done, time to reset offset = 0; count = 0; } return outgoing; } synchronized boolean available() { return count != 0; } } InternalEventQueue eventQueue = new InternalEventQueue(); /** * Add an event to the internal event queue, or process it immediately if * the sketch is not currently looping. */ public void postEvent(processing.event.Event pe) { // if (pe instanceof MouseEvent) { //// switch (pe.getFlavor()) { //// case Event.MOUSE: // if (looping) { // enqueueMouseEvent((MouseEvent) pe); // } else { // handleMouseEvent((MouseEvent) pe); // enqueueEvent(pe); // } // } else if (pe instanceof KeyEvent) { // if (looping) { // enqueueKeyEvent((KeyEvent) pe); // } else { // handleKeyEvent((KeyEvent) pe); // } // } // synchronized (eventQueue) { // if (eventCount == eventQueue.length) { // eventQueue = (Event[]) expand(eventQueue); // } // eventQueue[eventCount++] = pe; // } eventQueue.add(pe); if (!looping) { dequeueEvents(); } } // protected void enqueueEvent(Event e) { // synchronized (eventQueue) { // if (eventCount == eventQueue.length) { // eventQueue = (Event[]) expand(eventQueue); // } // eventQueue[eventCount++] = e; // } // } protected void dequeueEvents() { // can't do this.. thread lock // synchronized (eventQueue) { // for (int i = 0; i < eventCount; i++) { // Event e = eventQueue[i]; while (eventQueue.available()) { Event e = eventQueue.remove(); switch (e.getFlavor()) { case Event.MOUSE: handleMouseEvent((MouseEvent) e); break; case Event.KEY: handleKeyEvent((KeyEvent) e); break; } // } // eventCount = 0; } } ////////////////////////////////////////////////////////////// // MouseEvent mouseEventQueue[] = new MouseEvent[10]; // int mouseEventCount; // // protected void enqueueMouseEvent(MouseEvent e) { // synchronized (mouseEventQueue) { // if (mouseEventCount == mouseEventQueue.length) { // MouseEvent temp[] = new MouseEvent[mouseEventCount << 1]; // System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount); // mouseEventQueue = temp; // } // mouseEventQueue[mouseEventCount++] = e; // } // } // // protected void dequeueMouseEvents() { // synchronized (mouseEventQueue) { // for (int i = 0; i < mouseEventCount; i++) { // handleMouseEvent(mouseEventQueue[i]); // } // mouseEventCount = 0; // } // } /** * Actually take action based on a mouse event. * Internally updates mouseX, mouseY, mousePressed, and mouseEvent. * Then it calls the event type with no params, * i.e. mousePressed() or mouseReleased() that the user may have * overloaded to do something more useful. */ protected void handleMouseEvent(MouseEvent event) { // http://dev.processing.org/bugs/show_bug.cgi?id=170 // also prevents mouseExited() on the mac from hosing the mouse // position, because x/y are bizarre values on the exit event. // see also the id check below.. both of these go together. // Not necessary to set mouseX/Y on PRESS or RELEASE events because the // actual position will have been set by a MOVE or DRAG event. if (event.getAction() == MouseEvent.DRAG || event.getAction() == MouseEvent.MOVE) { pmouseX = emouseX; pmouseY = emouseY; mouseX = event.getX(); mouseY = event.getY(); } // Get the (already processed) button code mouseButton = event.getButton(); // Compatibility for older code (these have AWT object params, not P5) if (mouseEventMethods != null) { // Probably also good to check this, in case anyone tries to call // postEvent() with an artificial event they've created. if (event.getNative() != null) { mouseEventMethods.handle(new Object[] { event.getNative() }); } } // this used to only be called on mouseMoved and mouseDragged // change it back if people run into trouble if (firstMouse) { pmouseX = mouseX; pmouseY = mouseY; dmouseX = mouseX; dmouseY = mouseY; firstMouse = false; } mouseEvent = event; // Do this up here in case a registered method relies on the // boolean for mousePressed. switch (event.getAction()) { case MouseEvent.PRESS: mousePressed = true; break; case MouseEvent.RELEASE: mousePressed = false; break; } handleMethods("mouseEvent", new Object[] { event }); switch (event.getAction()) { case MouseEvent.PRESS: // mousePressed = true; mousePressed(event); break; case MouseEvent.RELEASE: // mousePressed = false; mouseReleased(event); break; case MouseEvent.CLICK: mouseClicked(event); break; case MouseEvent.DRAG: mouseDragged(event); break; case MouseEvent.MOVE: mouseMoved(event); break; case MouseEvent.ENTER: mouseEntered(event); break; case MouseEvent.EXIT: mouseExited(event); break; case MouseEvent.WHEEL: mouseWheel(event); break; } if ((event.getAction() == MouseEvent.DRAG) || (event.getAction() == MouseEvent.MOVE)) { emouseX = mouseX; emouseY = mouseY; } } /* // disabling for now; requires Java 1.7 and "precise" semantics are odd... // returns 0.1 for tick-by-tick scrolling on OS X, but it's not a matter of // calling ceil() on the value: 1.5 goes to 1, but 2.3 goes to 2. // "precise" is a whole different animal, so add later API to shore that up. static protected Method preciseWheelMethod; static { try { preciseWheelMethod = MouseWheelEvent.class.getMethod("getPreciseWheelRotation", new Class[] { }); } catch (Exception e) { // ignored, the method will just be set to null } } */ /** * Figure out how to process a mouse event. When loop() has been * called, the events will be queued up until drawing is complete. * If noLoop() has been called, then events will happen immediately. */ protected void nativeMouseEvent(java.awt.event.MouseEvent nativeEvent) { // the 'amount' is the number of button clicks for a click event, // or the number of steps/clicks on the wheel for a mouse wheel event. int peCount = nativeEvent.getClickCount(); int peAction = 0; switch (nativeEvent.getID()) { case java.awt.event.MouseEvent.MOUSE_PRESSED: peAction = MouseEvent.PRESS; break; case java.awt.event.MouseEvent.MOUSE_RELEASED: peAction = MouseEvent.RELEASE; break; case java.awt.event.MouseEvent.MOUSE_CLICKED: peAction = MouseEvent.CLICK; break; case java.awt.event.MouseEvent.MOUSE_DRAGGED: peAction = MouseEvent.DRAG; break; case java.awt.event.MouseEvent.MOUSE_MOVED: peAction = MouseEvent.MOVE; break; case java.awt.event.MouseEvent.MOUSE_ENTERED: peAction = MouseEvent.ENTER; break; case java.awt.event.MouseEvent.MOUSE_EXITED: peAction = MouseEvent.EXIT; break; //case java.awt.event.MouseWheelEvent.WHEEL_UNIT_SCROLL: case java.awt.event.MouseEvent.MOUSE_WHEEL: peAction = MouseEvent.WHEEL; /* if (preciseWheelMethod != null) { try { peAmount = ((Double) preciseWheelMethod.invoke(nativeEvent, (Object[]) null)).floatValue(); } catch (Exception e) { preciseWheelMethod = null; } } */ peCount = ((MouseWheelEvent) nativeEvent).getWheelRotation(); break; } //System.out.println(nativeEvent); //int modifiers = nativeEvent.getModifiersEx(); // If using getModifiersEx(), the regular modifiers don't set properly. int modifiers = nativeEvent.getModifiers(); int peModifiers = modifiers & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.META_MASK | InputEvent.ALT_MASK); // Windows and OS X seem to disagree on how to handle this. Windows only // sets BUTTON1_DOWN_MASK, while OS X seems to set BUTTON1_MASK. // This is an issue in particular with mouse release events: // http://code.google.com/p/processing/issues/detail?id=1294 // The fix for which led to a regression (fixed here by checking both): // http://code.google.com/p/processing/issues/detail?id=1332 int peButton = 0; // if ((modifiers & InputEvent.BUTTON1_MASK) != 0 || // (modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) { // peButton = LEFT; // } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0 || // (modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) { // peButton = CENTER; // } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0 || // (modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) { // peButton = RIGHT; // } if ((modifiers & InputEvent.BUTTON1_MASK) != 0) { peButton = LEFT; } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) { peButton = CENTER; } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) { peButton = RIGHT; } // If running on macos, allow ctrl-click as right mouse. Prior to 0215, // this used isPopupTrigger() on the native event, but that doesn't work // for mouseClicked and mouseReleased (or others). if (platform == MACOSX) { //if (nativeEvent.isPopupTrigger()) { if ((modifiers & InputEvent.CTRL_MASK) != 0) { peButton = RIGHT; } } postEvent(new MouseEvent(nativeEvent, nativeEvent.getWhen(), peAction, peModifiers, nativeEvent.getX(), nativeEvent.getY(), peButton, peCount)); } /** * If you override this or any function that takes a "MouseEvent e" * without calling its super.mouseXxxx() then mouseX, mouseY, * mousePressed, and mouseEvent will no longer be set. * * @nowebref */ public void mousePressed(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseReleased(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseClicked(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseEntered(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseExited(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseDragged(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseMoved(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseWheelMoved(java.awt.event.MouseWheelEvent e) { nativeMouseEvent(e); } /** * ( begin auto-generated from mousePressed.xml ) * * The <b>mousePressed()</b> function is called once after every time a * mouse button is pressed. The <b>mouseButton</b> variable (see the * related reference entry) can be used to determine which button has been pressed. * * ( end auto-generated ) * <h3>Advanced</h3> * * If you must, use * int button = mouseEvent.getButton(); * to figure out which button was clicked. It will be one of: * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3 * Note, however, that this is completely inconsistent across * platforms. * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mouseButton * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mousePressed() { } public void mousePressed(MouseEvent event) { mousePressed(); } /** * ( begin auto-generated from mouseReleased.xml ) * * The <b>mouseReleased()</b> function is called every time a mouse button * is released. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mouseButton * @see PApplet#mousePressed() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mouseReleased() { } public void mouseReleased(MouseEvent event) { mouseReleased(); } /** * ( begin auto-generated from mouseClicked.xml ) * * The <b>mouseClicked()</b> function is called once after a mouse button * has been pressed and then released. * * ( end auto-generated ) * <h3>Advanced</h3> * When the mouse is clicked, mousePressed() will be called, * then mouseReleased(), then mouseClicked(). Note that * mousePressed is already false inside of mouseClicked(). * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mouseButton * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mouseClicked() { } public void mouseClicked(MouseEvent event) { mouseClicked(); } /** * ( begin auto-generated from mouseDragged.xml ) * * The <b>mouseDragged()</b> function is called once every time the mouse * moves and a mouse button is pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() */ public void mouseDragged() { } public void mouseDragged(MouseEvent event) { mouseDragged(); } /** * ( begin auto-generated from mouseMoved.xml ) * * The <b>mouseMoved()</b> function is called every time the mouse moves * and a mouse button is not pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseDragged() */ public void mouseMoved() { } public void mouseMoved(MouseEvent event) { mouseMoved(); } public void mouseEntered() { } public void mouseEntered(MouseEvent event) { mouseEntered(); } public void mouseExited() { } public void mouseExited(MouseEvent event) { mouseExited(); } /** * @nowebref */ public void mouseWheel() { } /** * The event.getAmount() method returns negative values if the mouse wheel * if rotated up or away from the user and positive in the other direction. * On OS X with "natural" scrolling enabled, the values are opposite. * * @webref input:mouse * @param event the MouseEvent */ public void mouseWheel(MouseEvent event) { mouseWheel(); } ////////////////////////////////////////////////////////////// // KeyEvent keyEventQueue[] = new KeyEvent[10]; // int keyEventCount; // // protected void enqueueKeyEvent(KeyEvent e) { // synchronized (keyEventQueue) { // if (keyEventCount == keyEventQueue.length) { // KeyEvent temp[] = new KeyEvent[keyEventCount << 1]; // System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount); // keyEventQueue = temp; // } // keyEventQueue[keyEventCount++] = e; // } // } // // protected void dequeueKeyEvents() { // synchronized (keyEventQueue) { // for (int i = 0; i < keyEventCount; i++) { // keyEvent = keyEventQueue[i]; // handleKeyEvent(keyEvent); // } // keyEventCount = 0; // } // } // protected void handleKeyEvent(java.awt.event.KeyEvent event) { // keyEvent = event; // key = event.getKeyChar(); // keyCode = event.getKeyCode(); // // if (keyEventMethods != null) { // keyEventMethods.handle(new Object[] { event }); // } // // switch (event.getID()) { // case KeyEvent.KEY_PRESSED: // keyPressed = true; // keyPressed(); // break; // case KeyEvent.KEY_RELEASED: // keyPressed = false; // keyReleased(); // break; // case KeyEvent.KEY_TYPED: // keyTyped(); // break; // } // // // if someone else wants to intercept the key, they should // // set key to zero (or something besides the ESC). // if (event.getID() == java.awt.event.KeyEvent.KEY_PRESSED) { // if (key == java.awt.event.KeyEvent.VK_ESCAPE) { // exit(); // } // // When running tethered to the Processing application, respond to // // Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior // // when running independently, because this sketch may be one component // // embedded inside an application that has its own close behavior. // if (external && // event.getModifiers() == MENU_SHORTCUT && // event.getKeyCode() == 'W') { // exit(); // } // } // } protected void handleKeyEvent(KeyEvent event) { keyEvent = event; key = event.getKey(); keyCode = event.getKeyCode(); switch (event.getAction()) { case KeyEvent.PRESS: keyPressed = true; keyPressed(keyEvent); break; case KeyEvent.RELEASE: keyPressed = false; keyReleased(keyEvent); break; case KeyEvent.TYPE: keyTyped(keyEvent); break; } if (keyEventMethods != null) { keyEventMethods.handle(new Object[] { event.getNative() }); } handleMethods("keyEvent", new Object[] { event }); // if someone else wants to intercept the key, they should // set key to zero (or something besides the ESC). if (event.getAction() == KeyEvent.PRESS) { //if (key == java.awt.event.KeyEvent.VK_ESCAPE) { if (key == ESC) { exit(); } // When running tethered to the Processing application, respond to // Ctrl-W (or Cmd-W) events by closing the sketch. Not enabled when // running independently, because this sketch may be one component // embedded inside an application that has its own close behavior. if (external && event.getKeyCode() == 'W' && ((event.isMetaDown() && platform == MACOSX) || (event.isControlDown() && platform != MACOSX))) { // Can't use this native stuff b/c the native event might be NEWT // if (external && event.getNative() instanceof java.awt.event.KeyEvent && // ((java.awt.event.KeyEvent) event.getNative()).getModifiers() == // Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() && // event.getKeyCode() == 'W') { exit(); } } } protected void nativeKeyEvent(java.awt.event.KeyEvent event) { int peAction = 0; switch (event.getID()) { case java.awt.event.KeyEvent.KEY_PRESSED: peAction = KeyEvent.PRESS; break; case java.awt.event.KeyEvent.KEY_RELEASED: peAction = KeyEvent.RELEASE; break; case java.awt.event.KeyEvent.KEY_TYPED: peAction = KeyEvent.TYPE; break; } // int peModifiers = event.getModifiersEx() & // (InputEvent.SHIFT_DOWN_MASK | // InputEvent.CTRL_DOWN_MASK | // InputEvent.META_DOWN_MASK | // InputEvent.ALT_DOWN_MASK); int peModifiers = event.getModifiers() & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.META_MASK | InputEvent.ALT_MASK); postEvent(new KeyEvent(event, event.getWhen(), peAction, peModifiers, event.getKeyChar(), event.getKeyCode())); } /** * Overriding keyXxxxx(KeyEvent e) functions will cause the 'key', * 'keyCode', and 'keyEvent' variables to no longer work; * key events will no longer be queued until the end of draw(); * and the keyPressed(), keyReleased() and keyTyped() methods * will no longer be called. * * @nowebref */ public void keyPressed(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * @nowebref */ public void keyReleased(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * @nowebref */ public void keyTyped(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * * ( begin auto-generated from keyPressed.xml ) * * The <b>keyPressed()</b> function is called once every time a key is * pressed. The key that was pressed is stored in the <b>key</b> variable. * <br/> <br/> * For non-ASCII keys, use the <b>keyCode</b> variable. The keys included * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and * DELETE) do not require checking to see if they key is coded, and you * should simply use the <b>key</b> variable instead of <b>keyCode</b> If * you're making cross-platform projects, note that the ENTER key is * commonly used on PCs and Unix and the RETURN key is used instead on * Macintosh. Check for both ENTER and RETURN to make sure your program * will work for all platforms. * <br/> <br/> * Because of how operating systems handle key repeats, holding down a key * may cause multiple calls to keyPressed() (and keyReleased() as well). * The rate of repeat is set by the operating system and how each computer * is configured. * * ( end auto-generated ) * <h3>Advanced</h3> * * Called each time a single key on the keyboard is pressed. * Because of how operating systems handle key repeats, holding * down a key will cause multiple calls to keyPressed(), because * the OS repeat takes over. * <p> * Examples for key handling: * (Tested on Windows XP, please notify if different on other * platforms, I have a feeling Mac OS and Linux may do otherwise) * <PRE> * 1. Pressing 'a' on the keyboard: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * keyReleased with key == 'a' and keyCode == 'A' * * 2. Pressing 'A' on the keyboard: * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * * 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off): * keyPressed with key == CODED and keyCode == SHIFT * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * keyReleased with key == CODED and keyCode == SHIFT * * 4. Holding down the 'a' key. * The following will happen several times, * depending on your machine's "key repeat rate" settings: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * When you finally let go, you'll get: * keyReleased with key == 'a' and keyCode == 'A' * * 5. Pressing and releasing the 'shift' key * keyPressed with key == CODED and keyCode == SHIFT * keyReleased with key == CODED and keyCode == SHIFT * (note there is no keyTyped) * * 6. Pressing the tab key in an applet with Java 1.4 will * normally do nothing, but PApplet dynamically shuts * this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows). * Java 1.1 (Microsoft VM) passes the TAB key through normally. * Not tested on other platforms or for 1.3. * </PRE> * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyReleased() */ public void keyPressed() { } public void keyPressed(KeyEvent event) { keyPressed(); } /** * ( begin auto-generated from keyReleased.xml ) * * The <b>keyReleased()</b> function is called once every time a key is * released. The key that was released will be stored in the <b>key</b> * variable. See <b>key</b> and <b>keyReleased</b> for more information. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() */ public void keyReleased() { } public void keyReleased(KeyEvent event) { keyReleased(); } /** * ( begin auto-generated from keyTyped.xml ) * * The <b>keyTyped()</b> function is called once every time a key is * pressed, but action keys such as Ctrl, Shift, and Alt are ignored. * Because of how operating systems handle key repeats, holding down a key * will cause multiple calls to <b>keyTyped()</b>, the rate is set by the * operating system and how each computer is configured. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#keyPressed * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyReleased() */ public void keyTyped() { } public void keyTyped(KeyEvent event) { keyTyped(); } ////////////////////////////////////////////////////////////// // i am focused man, and i'm not afraid of death. // and i'm going all out. i circle the vultures in a van // and i run the block. public void focusGained() { } public void focusGained(FocusEvent e) { focused = true; focusGained(); } public void focusLost() { } public void focusLost(FocusEvent e) { focused = false; focusLost(); } ////////////////////////////////////////////////////////////// // getting the time /** * ( begin auto-generated from millis.xml ) * * Returns the number of milliseconds (thousandths of a second) since * starting an applet. This information is often used for timing animation * sequences. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p> * This is a function, rather than a variable, because it may * change multiple times per frame. * * @webref input:time_date * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ public int millis() { return (int) (System.currentTimeMillis() - millisOffset); } /** * ( begin auto-generated from second.xml ) * * Processing communicates with the clock on your computer. The * <b>second()</b> function returns the current second as a value from 0 - 59. * * ( end auto-generated ) * @webref input:time_date * @see PApplet#millis() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ static public int second() { return Calendar.getInstance().get(Calendar.SECOND); } /** * ( begin auto-generated from minute.xml ) * * Processing communicates with the clock on your computer. The * <b>minute()</b> function returns the current minute as a value from 0 - 59. * * ( end auto-generated ) * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * * */ static public int minute() { return Calendar.getInstance().get(Calendar.MINUTE); } /** * ( begin auto-generated from hour.xml ) * * Processing communicates with the clock on your computer. The * <b>hour()</b> function returns the current hour as a value from 0 - 23. * * ( end auto-generated ) * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ static public int hour() { return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * ( begin auto-generated from day.xml ) * * Processing communicates with the clock on your computer. The * <b>day()</b> function returns the current day as a value from 1 - 31. * * ( end auto-generated ) * <h3>Advanced</h3> * Get the current day of the month (1 through 31). * <p> * If you're looking for the day of the week (M-F or whatever) * or day of the year (1..365) then use java's Calendar.get() * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#month() * @see PApplet#year() */ static public int day() { return Calendar.getInstance().get(Calendar.DAY_OF_MONTH); } /** * ( begin auto-generated from month.xml ) * * Processing communicates with the clock on your computer. The * <b>month()</b> function returns the current month as a value from 1 - 12. * * ( end auto-generated ) * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#year() */ static public int month() { // months are number 0..11 so change to colloquial 1..12 return Calendar.getInstance().get(Calendar.MONTH) + 1; } /** * ( begin auto-generated from year.xml ) * * Processing communicates with the clock on your computer. The * <b>year()</b> function returns the current year as an integer (2003, * 2004, 2005, etc). * * ( end auto-generated ) * The <b>year()</b> function returns the current year as an integer (2003, 2004, 2005, etc). * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() */ static public int year() { return Calendar.getInstance().get(Calendar.YEAR); } ////////////////////////////////////////////////////////////// // controlling time (playing god) /** * The delay() function causes the program to halt for a specified time. * Delay times are specified in thousandths of a second. For example, * running delay(3000) will stop the program for three seconds and * delay(500) will stop the program for a half-second. * * The screen only updates when the end of draw() is reached, so delay() * cannot be used to slow down drawing. For instance, you cannot use delay() * to control the timing of an animation. * * The delay() function should only be used for pausing scripts (i.e. * a script that needs to pause a few seconds before attempting a download, * or a sketch that needs to wait a few milliseconds before reading from * the serial port). */ public void delay(int napTime) { //if (frameCount != 0) { //if (napTime > 0) { try { Thread.sleep(napTime); } catch (InterruptedException e) { } //} //} } /** * ( begin auto-generated from frameRate.xml ) * * Specifies the number of frames to be displayed every second. If the * processor is not fast enough to maintain the specified rate, it will not * be achieved. For example, the function call <b>frameRate(30)</b> will * attempt to refresh 30 times a second. It is recommended to set the frame * rate within <b>setup()</b>. The default rate is 60 frames per second. * * ( end auto-generated ) * @webref environment * @param fps number of desired frames per second * @see PApplet#setup() * @see PApplet#draw() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#redraw() */ public void frameRate(float fps) { frameRateTarget = fps; frameRatePeriod = (long) (1000000000.0 / frameRateTarget); g.setFrameRate(fps); } ////////////////////////////////////////////////////////////// /** * Reads the value of a param. Values are always read as a String so if you * want them to be an integer or other datatype they must be converted. The * <b>param()</b> function will only work in a web browser. The function * should be called inside <b>setup()</b>, otherwise the applet may not yet * be initialized and connected to its parent web browser. * * @param name name of the param to read * @deprecated no more applet support */ public String param(String name) { if (online) { return getParameter(name); } else { System.err.println("param() only works inside a web browser"); } return null; } /** * <h3>Advanced</h3> * Show status in the status bar of a web browser, or in the * System.out console. Eventually this might show status in the * p5 environment itself, rather than relying on the console. * * @deprecated no more applet support */ public void status(String value) { if (online) { showStatus(value); } else { System.out.println(value); // something more interesting? } } public void link(String url) { // link(url, null); try { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(new URI(url)); } else { // Just pass it off to open() and hope for the best open(url); } } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } /** * Links to a webpage either in the same window or in a new window. The * complete URL must be specified. * * <h3>Advanced</h3> * Link to an external page without all the muss. * <p> * When run with an applet, uses the browser to open the url, * for applications, attempts to launch a browser with the url. * <p> * Works on Mac OS X and Windows. For Linux, use: * <PRE>open(new String[] { "firefox", url });</PRE> * or whatever you want as your browser, since Linux doesn't * yet have a standard method for launching URLs. * * @param url the complete URL, as a String in quotes * @param target the name of the window in which to load the URL, as a String in quotes * @deprecated the 'target' parameter is no longer relevant with the removal of applets */ public void link(String url, String target) { link(url); /* try { if (platform == WINDOWS) { // the following uses a shell execute to launch the .html file // note that under cygwin, the .html files have to be chmodded +x // after they're unpacked from the zip file. i don't know why, // and don't understand what this does in terms of windows // permissions. without the chmod, the command prompt says // "Access is denied" in both cygwin and the "dos" prompt. //Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" + // referenceFile + ".html"); // replace ampersands with control sequence for DOS. // solution contributed by toxi on the bugs board. url = url.replaceAll("&","^&"); // open dos prompt, give it 'start' command, which will // open the url properly. start by itself won't work since // it appears to need cmd Runtime.getRuntime().exec("cmd /c start " + url); } else if (platform == MACOSX) { //com.apple.mrj.MRJFileUtils.openURL(url); try { // Class<?> mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils"); // Method openMethod = // mrjFileUtils.getMethod("openURL", new Class[] { String.class }); Class<?> eieio = Class.forName("com.apple.eio.FileManager"); Method openMethod = eieio.getMethod("openURL", new Class[] { String.class }); openMethod.invoke(null, new Object[] { url }); } catch (Exception e) { e.printStackTrace(); } } else { //throw new RuntimeException("Can't open URLs for this platform"); // Just pass it off to open() and hope for the best open(url); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not open " + url); } */ } /** * ( begin auto-generated from open.xml ) * * Attempts to open an application or file using your platform's launcher. * The <b>file</b> parameter is a String specifying the file name and * location. The location parameter must be a full path name, or the name * of an executable in the system's PATH. In most cases, using a full path * is the best option, rather than relying on the system PATH. Be sure to * make the file executable before attempting to open it (chmod +x). * <br/> <br/> * The <b>args</b> parameter is a String or String array which is passed to * the command line. If you have multiple parameters, e.g. an application * and a document, or a command with multiple switches, use the version * that takes a String array, and place each individual item in a separate * element. * <br/> <br/> * If args is a String (not an array), then it can only be a single file or * application with no parameters. It's not the same as executing that * String using a shell. For instance, open("jikes -help") will not work properly. * <br/> <br/> * This function behaves differently on each platform. On Windows, the * parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the * "open" command is used (type "man open" in Terminal.app for * documentation). On Linux, it first tries gnome-open, then kde-open, but * if neither are available, it sends the command to the shell without any * alterations. * <br/> <br/> * For users familiar with Java, this is not quite the same as * Runtime.exec(), because the launcher command is prepended. Instead, the * <b>exec(String[])</b> function is a shortcut for * Runtime.getRuntime.exec(String[]). * * ( end auto-generated ) * @webref input:files * @param filename name of the file * @usage Application */ static public void open(String filename) { open(new String[] { filename }); } static String openLauncher; /** * Launch a process using a platforms shell. This version uses an array * to make it easier to deal with spaces in the individual elements. * (This avoids the situation of trying to put single or double quotes * around different bits). * * @param argv list of commands passed to the command line */ static public Process open(String argv[]) { String[] params = null; if (platform == WINDOWS) { // just launching the .html file via the shell works // but make sure to chmod +x the .html files first // also place quotes around it in case there's a space // in the user.dir part of the url params = new String[] { "cmd", "/c" }; } else if (platform == MACOSX) { params = new String[] { "open" }; } else if (platform == LINUX) { if (openLauncher == null) { // Attempt to use gnome-open try { Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" }); /*int result =*/ p.waitFor(); // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04) openLauncher = "gnome-open"; } catch (Exception e) { } } if (openLauncher == null) { // Attempt with kde-open try { Process p = Runtime.getRuntime().exec(new String[] { "kde-open" }); /*int result =*/ p.waitFor(); openLauncher = "kde-open"; } catch (Exception e) { } } if (openLauncher == null) { System.err.println("Could not find gnome-open or kde-open, " + "the open() command may not work."); } if (openLauncher != null) { params = new String[] { openLauncher }; } //} else { // give up and just pass it to Runtime.exec() //open(new String[] { filename }); //params = new String[] { filename }; } if (params != null) { // If the 'open', 'gnome-open' or 'cmd' are already included if (params[0].equals(argv[0])) { // then don't prepend those params again return exec(argv); } else { params = concat(params, argv); return exec(params); } } else { return exec(argv); } } static public Process exec(String[] argv) { try { return Runtime.getRuntime().exec(argv); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not open " + join(argv, ' ')); } } ////////////////////////////////////////////////////////////// /** * Function for an applet/application to kill itself and * display an error. Mostly this is here to be improved later. */ public void die(String what) { dispose(); throw new RuntimeException(what); } /** * Same as above but with an exception. Also needs work. */ public void die(String what, Exception e) { if (e != null) e.printStackTrace(); die(what); } /** * ( begin auto-generated from exit.xml ) * * Quits/stops/exits the program. Programs without a <b>draw()</b> function * exit automatically after the last line has run, but programs with * <b>draw()</b> run continuously until the program is manually stopped or * <b>exit()</b> is run.<br /> * <br /> * Rather than terminating immediately, <b>exit()</b> will cause the sketch * to exit after <b>draw()</b> has completed (or after <b>setup()</b> * completes if called during the <b>setup()</b> function).<br /> * <br /> * For Java programmers, this is <em>not</em> the same as System.exit(). * Further, System.exit() should not be used because closing out an * application while <b>draw()</b> is running may cause a crash * (particularly with P3D). * * ( end auto-generated ) * @webref structure */ public void exit() { if (thread == null) { // exit immediately, dispose() has already been called, // meaning that the main thread has long since exited exitActual(); } else if (looping) { // dispose() will be called as the thread exits finished = true; // tell the code to call exit2() to do a System.exit() // once the next draw() has completed exitCalled = true; } else if (!looping) { // if not looping, shut down things explicitly, // because the main thread will be sleeping dispose(); // now get out exitActual(); } } void exitActual() { try { System.exit(0); } catch (SecurityException e) { // don't care about applet security exceptions } } /** * Called to dispose of resources and shut down the sketch. * Destroys the thread, dispose the renderer,and notify listeners. * <p> * Not to be called or overriden by users. If called multiple times, * will only notify listeners once. Register a dispose listener instead. */ public void dispose() { // moved here from stop() finished = true; // let the sketch know it is shut down time // don't run the disposers twice if (thread != null) { thread = null; // shut down renderer if (g != null) { g.dispose(); } // run dispose() methods registered by libraries handleMethods("dispose"); } } ////////////////////////////////////////////////////////////// /** * Call a method in the current class based on its name. * <p/> * Note that the function being called must be public. Inside the PDE, * 'public' is automatically added, but when used without the preprocessor, * (like from Eclipse) you'll have to do it yourself. */ public void method(String name) { try { Method method = getClass().getMethod(name, new Class[] {}); method.invoke(this, new Object[] { }); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println("There is no public " + name + "() method " + "in the class " + getClass().getName()); } catch (Exception e) { e.printStackTrace(); } } /** * Launch a new thread and call the specified function from that new thread. * This is a very simple way to do a thread without needing to get into * classes, runnables, etc. * <p/> * Note that the function being called must be public. Inside the PDE, * 'public' is automatically added, but when used without the preprocessor, * (like from Eclipse) you'll have to do it yourself. */ public void thread(final String name) { Thread later = new Thread() { @Override public void run() { method(name); } }; later.start(); } ////////////////////////////////////////////////////////////// // SCREEN GRABASS /** * ( begin auto-generated from save.xml ) * * Saves an image from the display window. Images are saved in TIFF, TARGA, * JPEG, and PNG format depending on the extension within the * <b>filename</b> parameter. For example, "image.tif" will have a TIFF * image and "image.png" will save a PNG image. If no extension is included * in the filename, the image will save in TIFF format and <b>.tif</b> will * be added to the name. These files are saved to the sketch's folder, * which may be opened by selecting "Show sketch folder" from the "Sketch" * menu. It is not possible to use <b>save()</b> while running the program * in a web browser. * <br/> images saved from the main drawing window will be opaque. To save * images without a background, use <b>createGraphics()</b>. * * ( end auto-generated ) * @webref output:image * @param filename any sequence of letters and numbers * @see PApplet#saveFrame() * @see PApplet#createGraphics(int, int, String) */ public void save(String filename) { g.save(savePath(filename)); } /** */ public void saveFrame() { try { g.save(savePath("screen-" + nf(frameCount, 4) + ".tif")); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * ( begin auto-generated from saveFrame.xml ) * * Saves a numbered sequence of images, one image each time the function is * run. To save an image that is identical to the display window, run the * function at the end of <b>draw()</b> or within mouse and key events such * as <b>mousePressed()</b> and <b>keyPressed()</b>. If <b>saveFrame()</b> * is called without parameters, it will save the files as screen-0000.tif, * screen-0001.tif, etc. It is possible to specify the name of the sequence * with the <b>filename</b> parameter and make the choice of saving TIFF, * TARGA, PNG, or JPEG files with the <b>ext</b> parameter. These image * sequences can be loaded into programs such as Apple's QuickTime software * and made into movies. These files are saved to the sketch's folder, * which may be opened by selecting "Show sketch folder" from the "Sketch" * menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * All images saved from the main drawing window will be opaque. To save * images without a background, use <b>createGraphics()</b>. * * ( end auto-generated ) * @webref output:image * @see PApplet#save(String) * @see PApplet#createGraphics(int, int, String, String) * @param filename any sequence of letters or numbers that ends with either ".tif", ".tga", ".jpg", or ".png" */ public void saveFrame(String filename) { try { g.save(savePath(insertFrame(filename))); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * Check a string for #### signs to see if the frame number should be * inserted. Used for functions like saveFrame() and beginRecord() to * replace the # marks with the frame number. If only one # is used, * it will be ignored, under the assumption that it's probably not * intended to be the frame number. */ public String insertFrame(String what) { int first = what.indexOf('#'); int last = what.lastIndexOf('#'); if ((first != -1) && (last - first > 0)) { String prefix = what.substring(0, first); int count = last - first + 1; String suffix = what.substring(last + 1); return prefix + nf(frameCount, count) + suffix; } return what; // no change } ////////////////////////////////////////////////////////////// // CURSOR // int cursorType = ARROW; // cursor type boolean cursorVisible = true; // cursor visibility flag // PImage invisibleCursor; Cursor invisibleCursor; /** * Set the cursor type * @param kind either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT */ public void cursor(int kind) { setCursor(Cursor.getPredefinedCursor(kind)); cursorVisible = true; this.cursorType = kind; } /** * Replace the cursor with the specified PImage. The x- and y- * coordinate of the center will be the center of the image. */ public void cursor(PImage img) { cursor(img, img.width/2, img.height/2); } /** * ( begin auto-generated from cursor.xml ) * * Sets the cursor to a predefined symbol, an image, or makes it visible if * already hidden. If you are trying to set an image as the cursor, it is * recommended to make the size 16x16 or 32x32 pixels. It is not possible * to load an image as the cursor if you are exporting your program for the * Web and not all MODES work with all Web browsers. The values for * parameters <b>x</b> and <b>y</b> must be less than the dimensions of the image. * <br /> <br /> * Setting or hiding the cursor generally does not work with "Present" mode * (when running full-screen). * * ( end auto-generated ) * <h3>Advanced</h3> * Set a custom cursor to an image with a specific hotspot. * Only works with JDK 1.2 and later. * Currently seems to be broken on Java 1.4 for Mac OS X * <p> * Based on code contributed by Amit Pitaru, plus additional * code to handle Java versions via reflection by Jonathan Feinberg. * Reflection removed for release 0128 and later. * @webref environment * @see PApplet#noCursor() * @param img any variable of type PImage * @param x the horizontal active spot of the cursor * @param y the vertical active spot of the cursor */ public void cursor(PImage img, int x, int y) { // don't set this as cursor type, instead use cursor_type // to save the last cursor used in case cursor() is called //cursor_type = Cursor.CUSTOM_CURSOR; Image jimage = createImage(new MemoryImageSource(img.width, img.height, img.pixels, 0, img.width)); Point hotspot = new Point(x, y); Toolkit tk = Toolkit.getDefaultToolkit(); Cursor cursor = tk.createCustomCursor(jimage, hotspot, "Custom Cursor"); setCursor(cursor); cursorVisible = true; } /** * Show the cursor after noCursor() was called. * Notice that the program remembers the last set cursor type */ public void cursor() { // maybe should always set here? seems dangerous, since // it's likely that java will set the cursor to something // else on its own, and the applet will be stuck b/c bagel // thinks that the cursor is set to one particular thing if (!cursorVisible) { cursorVisible = true; setCursor(Cursor.getPredefinedCursor(cursorType)); } } /** * ( begin auto-generated from noCursor.xml ) * * Hides the cursor from view. Will not work when running the program in a * web browser or when running in full screen (Present) mode. * * ( end auto-generated ) * <h3>Advanced</h3> * Hide the cursor by creating a transparent image * and using it as a custom cursor. * @webref environment * @see PApplet#cursor() * @usage Application */ public void noCursor() { // in 0216, just re-hide it? // if (!cursorVisible) return; // don't hide if already hidden. if (invisibleCursor == null) { BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); invisibleCursor = getToolkit().createCustomCursor(cursorImg, new Point(8, 8), "blank"); } // was formerly 16x16, but the 0x0 was added by jdf as a fix // for macosx, which wasn't honoring the invisible cursor // cursor(invisibleCursor, 8, 8); setCursor(invisibleCursor); cursorVisible = false; } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from print.xml ) * * Writes to the console area of the Processing environment. This is often * helpful for looking at the data a program is producing. The companion * function <b>println()</b> works like <b>print()</b>, but creates a new * line of text for each call to the function. Individual elements can be * separated with quotes ("") and joined with the addition operator (+).<br /> * <br /> * Beginning with release 0125, to print the contents of an array, use * println(). There's no sensible way to do a <b>print()</b> of an array, * because there are too many possibilities for how to separate the data * (spaces, commas, etc). If you want to print an array as a single line, * use <b>join()</b>. With <b>join()</b>, you can choose any delimiter you * like and <b>print()</b> the result.<br /> * <br /> * Using <b>print()</b> on an object will output <b>null</b>, a memory * location that may look like "@10be08," or the result of the * <b>toString()</b> method from the object that's being printed. Advanced * users who want more useful output when calling <b>print()</b> on their * own classes can add a <b>toString()</b> method to the class that returns * a String. * * ( end auto-generated ) * @webref output:text_area * @usage IDE * @param what data to print to console * @see PApplet#println() * @see PApplet#printArray(Object) * @see PApplet#join(String[], char) */ static public void print(byte what) { System.out.print(what); System.out.flush(); } static public void print(boolean what) { System.out.print(what); System.out.flush(); } static public void print(char what) { System.out.print(what); System.out.flush(); } static public void print(int what) { System.out.print(what); System.out.flush(); } static public void print(long what) { System.out.print(what); System.out.flush(); } static public void print(float what) { System.out.print(what); System.out.flush(); } static public void print(double what) { System.out.print(what); System.out.flush(); } static public void print(String what) { System.out.print(what); System.out.flush(); } /** * @param variables list of data, separated by commas */ static public void print(Object... variables) { StringBuilder sb = new StringBuilder(); for (Object o : variables) { if (sb.length() != 0) { sb.append(" "); } if (o == null) { sb.append("null"); } else { sb.append(o.toString()); } } System.out.print(sb.toString()); } /* static public void print(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.print("null"); } else { System.out.println(what.toString()); } } */ /** * ( begin auto-generated from println.xml ) * * Writes to the text area of the Processing environment's console. This is * often helpful for looking at the data a program is producing. Each call * to this function creates a new line of output. Individual elements can * be separated with quotes ("") and joined with the string concatenation * operator (+). See <b>print()</b> for more about what to expect in the output. * <br/><br/> <b>println()</b> on an array (by itself) will write the * contents of the array to the console. This is often helpful for looking * at the data a program is producing. A new line is put between each * element of the array. This function can only print one dimensional * arrays. For arrays with higher dimensions, the result will be closer to * that of <b>print()</b>. * * ( end auto-generated ) * @webref output:text_area * @usage IDE * @see PApplet#print(byte) * @see PApplet#printArray(Object) */ static public void println() { System.out.println(); } /** * @param what data to print to console */ static public void println(byte what) { System.out.println(what); System.out.flush(); } static public void println(boolean what) { System.out.println(what); System.out.flush(); } static public void println(char what) { System.out.println(what); System.out.flush(); } static public void println(int what) { System.out.println(what); System.out.flush(); } static public void println(long what) { System.out.println(what); System.out.flush(); } static public void println(float what) { System.out.println(what); System.out.flush(); } static public void println(double what) { System.out.println(what); System.out.flush(); } static public void println(String what) { System.out.println(what); System.out.flush(); } /** * @param variables list of data, separated by commas */ static public void println(Object... variables) { // System.out.println("got " + variables.length + " variables"); print(variables); println(); } /* // Breaking this out since the compiler doesn't know the difference between // Object... and just Object (with an array passed in). This should take care // of the confusion for at least the most common case (a String array). // On second thought, we're going the printArray() route, since the other // object types are also used frequently. static public void println(String[] array) { for (int i = 0; i < array.length; i++) { System.out.println("[" + i + "] \"" + array[i] + "\""); } System.out.flush(); } */ /** * For arrays, use printArray() instead. This function causes a warning * because the new print(Object...) and println(Object...) functions can't * be reliably bound by the compiler. */ static public void println(Object what) { if (what != null && what.getClass().isArray()) { printArray(what); } else { System.out.println(what.toString()); System.out.flush(); } } /** * ( begin auto-generated from printArray.xml ) * * To come... * * ( end auto-generated ) * @webref output:text_area * @param what one-dimensional array * @usage IDE * @see PApplet#print(byte) * @see PApplet#println() */ static public void printArray(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.println("null"); } else { String name = what.getClass().getName(); if (name.charAt(0) == '[') { switch (name.charAt(1)) { case '[': // don't even mess with multi-dimensional arrays (case '[') // or anything else that's not int, float, boolean, char System.out.println(what); break; case 'L': // print a 1D array of objects as individual elements Object poo[] = (Object[]) what; for (int i = 0; i < poo.length; i++) { if (poo[i] instanceof String) { System.out.println("[" + i + "] \"" + poo[i] + "\""); } else { System.out.println("[" + i + "] " + poo[i]); } } break; case 'Z': // boolean boolean zz[] = (boolean[]) what; for (int i = 0; i < zz.length; i++) { System.out.println("[" + i + "] " + zz[i]); } break; case 'B': // byte byte bb[] = (byte[]) what; for (int i = 0; i < bb.length; i++) { System.out.println("[" + i + "] " + bb[i]); } break; case 'C': // char char cc[] = (char[]) what; for (int i = 0; i < cc.length; i++) { System.out.println("[" + i + "] '" + cc[i] + "'"); } break; case 'I': // int int ii[] = (int[]) what; for (int i = 0; i < ii.length; i++) { System.out.println("[" + i + "] " + ii[i]); } break; case 'J': // int long jj[] = (long[]) what; for (int i = 0; i < jj.length; i++) { System.out.println("[" + i + "] " + jj[i]); } break; case 'F': // float float ff[] = (float[]) what; for (int i = 0; i < ff.length; i++) { System.out.println("[" + i + "] " + ff[i]); } break; case 'D': // double double dd[] = (double[]) what; for (int i = 0; i < dd.length; i++) { System.out.println("[" + i + "] " + dd[i]); } break; default: System.out.println(what); } } else { // not an array System.out.println(what); } } } static public void debug(String msg) { if (DEBUG) println(msg); } // /* // not very useful, because it only works for public (and protected?) // fields of a class, not local variables to methods public void printvar(String name) { try { Field field = getClass().getDeclaredField(name); println(name + " = " + field.get(this)); } catch (Exception e) { e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// // MATH // lots of convenience methods for math with floats. // doubles are overkill for processing applets, and casting // things all the time is annoying, thus the functions below. /** * ( begin auto-generated from abs.xml ) * * Calculates the absolute value (magnitude) of a number. The absolute * value of a number is always positive. * * ( end auto-generated ) * @webref math:calculation * @param n number to compute */ static public final float abs(float n) { return (n < 0) ? -n : n; } static public final int abs(int n) { return (n < 0) ? -n : n; } /** * ( begin auto-generated from sq.xml ) * * Squares a number (multiplies a number by itself). The result is always a * positive number, as multiplying two negative numbers always yields a * positive result. For example, -1 * -1 = 1. * * ( end auto-generated ) * @webref math:calculation * @param n number to square * @see PApplet#sqrt(float) */ static public final float sq(float n) { return n*n; } /** * ( begin auto-generated from sqrt.xml ) * * Calculates the square root of a number. The square root of a number is * always positive, even though there may be a valid negative root. The * square root <b>s</b> of number <b>a</b> is such that <b>s*s = a</b>. It * is the opposite of squaring. * * ( end auto-generated ) * @webref math:calculation * @param n non-negative number * @see PApplet#pow(float, float) * @see PApplet#sq(float) */ static public final float sqrt(float n) { return (float)Math.sqrt(n); } /** * ( begin auto-generated from log.xml ) * * Calculates the natural logarithm (the base-<i>e</i> logarithm) of a * number. This function expects the values greater than 0.0. * * ( end auto-generated ) * @webref math:calculation * @param n number greater than 0.0 */ static public final float log(float n) { return (float)Math.log(n); } /** * ( begin auto-generated from exp.xml ) * * Returns Euler's number <i>e</i> (2.71828...) raised to the power of the * <b>value</b> parameter. * * ( end auto-generated ) * @webref math:calculation * @param n exponent to raise */ static public final float exp(float n) { return (float)Math.exp(n); } /** * ( begin auto-generated from pow.xml ) * * Facilitates exponential expressions. The <b>pow()</b> function is an * efficient way of multiplying numbers by themselves (or their reciprocal) * in large quantities. For example, <b>pow(3, 5)</b> is equivalent to the * expression 3*3*3*3*3 and <b>pow(3, -5)</b> is equivalent to 1 / 3*3*3*3*3. * * ( end auto-generated ) * @webref math:calculation * @param n base of the exponential expression * @param e power by which to raise the base * @see PApplet#sqrt(float) */ static public final float pow(float n, float e) { return (float)Math.pow(n, e); } /** * ( begin auto-generated from max.xml ) * * Determines the largest value in a sequence of numbers. * * ( end auto-generated ) * @webref math:calculation * @param a first number to compare * @param b second number to compare * @see PApplet#min(float, float, float) */ static public final int max(int a, int b) { return (a > b) ? a : b; } static public final float max(float a, float b) { return (a > b) ? a : b; } /* static public final double max(double a, double b) { return (a > b) ? a : b; } */ /** * @param c third number to compare */ static public final int max(int a, int b, int c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } static public final float max(float a, float b, float c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } /** * @param list array of numbers to compare */ static public final int max(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } static public final float max(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } /** * Find the maximum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The maximum value */ /* static public final double max(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } */ static public final int min(int a, int b) { return (a < b) ? a : b; } static public final float min(float a, float b) { return (a < b) ? a : b; } /* static public final double min(double a, double b) { return (a < b) ? a : b; } */ static public final int min(int a, int b, int c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /** * ( begin auto-generated from min.xml ) * * Determines the smallest value in a sequence of numbers. * * ( end auto-generated ) * @webref math:calculation * @param a first number * @param b second number * @param c third number * @see PApplet#max(float, float, float) */ static public final float min(float a, float b, float c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /* static public final double min(double a, double b, double c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } */ /** * @param list array of numbers to compare */ static public final int min(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } static public final float min(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } /** * Find the minimum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The minimum value */ /* static public final double min(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } */ static public final int constrain(int amt, int low, int high) { return (amt < low) ? low : ((amt > high) ? high : amt); } /** * ( begin auto-generated from constrain.xml ) * * Constrains a value to not exceed a maximum and minimum value. * * ( end auto-generated ) * @webref math:calculation * @param amt the value to constrain * @param low minimum limit * @param high maximum limit * @see PApplet#max(float, float, float) * @see PApplet#min(float, float, float) */ static public final float constrain(float amt, float low, float high) { return (amt < low) ? low : ((amt > high) ? high : amt); } /** * ( begin auto-generated from sin.xml ) * * Calculates the sine of an angle. This function expects the values of the * <b>angle</b> parameter to be provided in radians (values from 0 to * 6.28). Values are returned in the range -1 to 1. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#cos(float) * @see PApplet#tan(float) * @see PApplet#radians(float) */ static public final float sin(float angle) { return (float)Math.sin(angle); } /** * ( begin auto-generated from cos.xml ) * * Calculates the cosine of an angle. This function expects the values of * the <b>angle</b> parameter to be provided in radians (values from 0 to * PI*2). Values are returned in the range -1 to 1. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#sin(float) * @see PApplet#tan(float) * @see PApplet#radians(float) */ static public final float cos(float angle) { return (float)Math.cos(angle); } /** * ( begin auto-generated from tan.xml ) * * Calculates the ratio of the sine and cosine of an angle. This function * expects the values of the <b>angle</b> parameter to be provided in * radians (values from 0 to PI*2). Values are returned in the range * <b>infinity</b> to <b>-infinity</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#cos(float) * @see PApplet#sin(float) * @see PApplet#radians(float) */ static public final float tan(float angle) { return (float)Math.tan(angle); } /** * ( begin auto-generated from asin.xml ) * * The inverse of <b>sin()</b>, returns the arc sine of a value. This * function expects the values in the range of -1 to 1 and values are * returned in the range <b>-PI/2</b> to <b>PI/2</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value the value whose arc sine is to be returned * @see PApplet#sin(float) * @see PApplet#acos(float) * @see PApplet#atan(float) */ static public final float asin(float value) { return (float)Math.asin(value); } /** * ( begin auto-generated from acos.xml ) * * The inverse of <b>cos()</b>, returns the arc cosine of a value. This * function expects the values in the range of -1 to 1 and values are * returned in the range <b>0</b> to <b>PI (3.1415927)</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value the value whose arc cosine is to be returned * @see PApplet#cos(float) * @see PApplet#asin(float) * @see PApplet#atan(float) */ static public final float acos(float value) { return (float)Math.acos(value); } /** * ( begin auto-generated from atan.xml ) * * The inverse of <b>tan()</b>, returns the arc tangent of a value. This * function expects the values in the range of -Infinity to Infinity * (exclusive) and values are returned in the range <b>-PI/2</b> to <b>PI/2 </b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value -Infinity to Infinity (exclusive) * @see PApplet#tan(float) * @see PApplet#asin(float) * @see PApplet#acos(float) */ static public final float atan(float value) { return (float)Math.atan(value); } /** * ( begin auto-generated from atan2.xml ) * * Calculates the angle (in radians) from a specified point to the * coordinate origin as measured from the positive x-axis. Values are * returned as a <b>float</b> in the range from <b>PI</b> to <b>-PI</b>. * The <b>atan2()</b> function is most often used for orienting geometry to * the position of the cursor. Note: The y-coordinate of the point is the * first parameter and the x-coordinate is the second due the the structure * of calculating the tangent. * * ( end auto-generated ) * @webref math:trigonometry * @param y y-coordinate of the point * @param x x-coordinate of the point * @see PApplet#tan(float) */ static public final float atan2(float y, float x) { return (float)Math.atan2(y, x); } /** * ( begin auto-generated from degrees.xml ) * * Converts a radian measurement to its corresponding value in degrees. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90&deg; = PI/2 = 1.5707964. All trigonometric functions in Processing * require their parameters to be specified in radians. * * ( end auto-generated ) * @webref math:trigonometry * @param radians radian value to convert to degrees * @see PApplet#radians(float) */ static public final float degrees(float radians) { return radians * RAD_TO_DEG; } /** * ( begin auto-generated from radians.xml ) * * Converts a degree measurement to its corresponding value in radians. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90&deg; = PI/2 = 1.5707964. All trigonometric functions in Processing * require their parameters to be specified in radians. * * ( end auto-generated ) * @webref math:trigonometry * @param degrees degree value to convert to radians * @see PApplet#degrees(float) */ static public final float radians(float degrees) { return degrees * DEG_TO_RAD; } /** * ( begin auto-generated from ceil.xml ) * * Calculates the closest int value that is greater than or equal to the * value of the parameter. For example, <b>ceil(9.03)</b> returns the value 10. * * ( end auto-generated ) * @webref math:calculation * @param n number to round up * @see PApplet#floor(float) * @see PApplet#round(float) */ static public final int ceil(float n) { return (int) Math.ceil(n); } /** * ( begin auto-generated from floor.xml ) * * Calculates the closest int value that is less than or equal to the value * of the parameter. * * ( end auto-generated ) * @webref math:calculation * @param n number to round down * @see PApplet#ceil(float) * @see PApplet#round(float) */ static public final int floor(float n) { return (int) Math.floor(n); } /** * ( begin auto-generated from round.xml ) * * Calculates the integer closest to the <b>value</b> parameter. For * example, <b>round(9.2)</b> returns the value 9. * * ( end auto-generated ) * @webref math:calculation * @param n number to round * @see PApplet#floor(float) * @see PApplet#ceil(float) */ static public final int round(float n) { return Math.round(n); } static public final float mag(float a, float b) { return (float)Math.sqrt(a*a + b*b); } /** * ( begin auto-generated from mag.xml ) * * Calculates the magnitude (or length) of a vector. A vector is a * direction in space commonly used in computer graphics and linear * algebra. Because it has no "start" position, the magnitude of a vector * can be thought of as the distance from coordinate (0,0) to its (x,y) * value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)". * * ( end auto-generated ) * @webref math:calculation * @param a first value * @param b second value * @param c third value * @see PApplet#dist(float, float, float, float) */ static public final float mag(float a, float b, float c) { return (float)Math.sqrt(a*a + b*b + c*c); } static public final float dist(float x1, float y1, float x2, float y2) { return sqrt(sq(x2-x1) + sq(y2-y1)); } /** * ( begin auto-generated from dist.xml ) * * Calculates the distance between two points. * * ( end auto-generated ) * @webref math:calculation * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param z1 z-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param z2 z-coordinate of the second point */ static public final float dist(float x1, float y1, float z1, float x2, float y2, float z2) { return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1)); } /** * ( begin auto-generated from lerp.xml ) * * Calculates a number between two numbers at a specific increment. The * <b>amt</b> parameter is the amount to interpolate between the two values * where 0.0 equal to the first point, 0.1 is very near the first point, * 0.5 is half-way in between, etc. The lerp function is convenient for * creating motion along a straight path and for drawing dotted lines. * * ( end auto-generated ) * @webref math:calculation * @param start first value * @param stop second value * @param amt float between 0.0 and 1.0 * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ static public final float lerp(float start, float stop, float amt) { return start + (stop-start) * amt; } /** * ( begin auto-generated from norm.xml ) * * Normalizes a number from another range into a value between 0 and 1. * <br/> <br/> * Identical to map(value, low, high, 0, 1); * <br/> <br/> * Numbers outside the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. * * ( end auto-generated ) * @webref math:calculation * @param value the incoming value to be converted * @param start lower bound of the value's current range * @param stop upper bound of the value's current range * @see PApplet#map(float, float, float, float, float) * @see PApplet#lerp(float, float, float) */ static public final float norm(float value, float start, float stop) { return (value - start) / (stop - start); } /** * ( begin auto-generated from map.xml ) * * Re-maps a number from one range to another. In the example above, * the number '25' is converted from a value in the range 0..100 into * a value that ranges from the left edge (0) to the right edge (width) * of the screen. * <br/> <br/> * Numbers outside the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. * * ( end auto-generated ) * @webref math:calculation * @param value the incoming value to be converted * @param start1 lower bound of the value's current range * @param stop1 upper bound of the value's current range * @param start2 lower bound of the value's target range * @param stop2 upper bound of the value's target range * @see PApplet#norm(float, float, float) * @see PApplet#lerp(float, float, float) */ static public final float map(float value, float start1, float stop1, float start2, float stop2) { return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1)); } /* static public final double map(double value, double istart, double istop, double ostart, double ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } */ ////////////////////////////////////////////////////////////// // RANDOM NUMBERS Random internalRandom; /** * */ public final float random(float high) { // avoid an infinite loop when 0 or NaN are passed in if (high == 0 || high != high) { return 0; } if (internalRandom == null) { internalRandom = new Random(); } // for some reason (rounding error?) Math.random() * 3 // can sometimes return '3' (once in ~30 million tries) // so a check was added to avoid the inclusion of 'howbig' float value = 0; do { value = internalRandom.nextFloat() * high; } while (value == high); return value; } /** * ( begin auto-generated from randomGaussian.xml ) * * Returns a float from a random series of numbers having a mean of 0 * and standard deviation of 1. Each time the <b>randomGaussian()</b> * function is called, it returns a number fitting a Gaussian, or * normal, distribution. There is theoretically no minimum or maximum * value that <b>randomGaussian()</b> might return. Rather, there is * just a very low probability that values far from the mean will be * returned; and a higher probability that numbers near the mean will * be returned. * * ( end auto-generated ) * @webref math:random * @see PApplet#random(float,float) * @see PApplet#noise(float, float, float) */ public final float randomGaussian() { if (internalRandom == null) { internalRandom = new Random(); } return (float) internalRandom.nextGaussian(); } /** * ( begin auto-generated from random.xml ) * * Generates random numbers. Each time the <b>random()</b> function is * called, it returns an unexpected value within the specified range. If * one parameter is passed to the function it will return a <b>float</b> * between zero and the value of the <b>high</b> parameter. The function * call <b>random(5)</b> returns values between 0 and 5 (starting at zero, * up to but not including 5). If two parameters are passed, it will return * a <b>float</b> with a value between the the parameters. The function * call <b>random(-5, 10.2)</b> returns values starting at -5 up to (but * not including) 10.2. To convert a floating-point random number to an * integer, use the <b>int()</b> function. * * ( end auto-generated ) * @webref math:random * @param low lower limit * @param high upper limit * @see PApplet#randomSeed(long) * @see PApplet#noise(float, float, float) */ public final float random(float low, float high) { if (low >= high) return low; float diff = high - low; return random(diff) + low; } /** * ( begin auto-generated from randomSeed.xml ) * * Sets the seed value for <b>random()</b>. By default, <b>random()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param seed seed value * @see PApplet#random(float,float) * @see PApplet#noise(float, float, float) * @see PApplet#noiseSeed(long) */ public final void randomSeed(long seed) { if (internalRandom == null) { internalRandom = new Random(); } internalRandom.setSeed(seed); } ////////////////////////////////////////////////////////////// // PERLIN NOISE // [toxi 040903] // octaves and amplitude amount per octave are now user controlled // via the noiseDetail() function. // [toxi 030902] // cleaned up code and now using bagel's cosine table to speed up // [toxi 030901] // implementation by the german demo group farbrausch // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip static final int PERLIN_YWRAPB = 4; static final int PERLIN_YWRAP = 1<<PERLIN_YWRAPB; static final int PERLIN_ZWRAPB = 8; static final int PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB; static final int PERLIN_SIZE = 4095; int perlin_octaves = 4; // default to medium smooth float perlin_amp_falloff = 0.5f; // 50% reduction/octave // [toxi 031112] // new vars needed due to recent change of cos table in PGraphics int perlin_TWOPI, perlin_PI; float[] perlin_cosTable; float[] perlin; Random perlinRandom; /** */ public float noise(float x) { // is this legit? it's a dumb way to do it (but repair it later) return noise(x, 0f, 0f); } /** */ public float noise(float x, float y) { return noise(x, y, 0f); } /** * ( begin auto-generated from noise.xml ) * * Returns the Perlin noise value at specified coordinates. Perlin noise is * a random sequence generator producing a more natural ordered, harmonic * succession of numbers compared to the standard <b>random()</b> function. * It was invented by Ken Perlin in the 1980s and been used since in * graphical applications to produce procedural textures, natural motion, * shapes, terrains etc.<br /><br /> The main difference to the * <b>random()</b> function is that Perlin noise is defined in an infinite * n-dimensional space where each pair of coordinates corresponds to a * fixed semi-random value (fixed only for the lifespan of the program). * The resulting value will always be between 0.0 and 1.0. Processing can * compute 1D, 2D and 3D noise, depending on the number of coordinates * given. The noise value can be animated by moving through the noise space * as demonstrated in the example above. The 2nd and 3rd dimension can also * be interpreted as time.<br /><br />The actual noise is structured * similar to an audio signal, in respect to the function's use of * frequencies. Similar to the concept of harmonics in physics, perlin * noise is computed over several octaves which are added together for the * final result. <br /><br />Another way to adjust the character of the * resulting sequence is the scale of the input coordinates. As the * function works within an infinite space the value of the coordinates * doesn't matter as such, only the distance between successive coordinates * does (eg. when using <b>noise()</b> within a loop). As a general rule * the smaller the difference between coordinates, the smoother the * resulting noise sequence will be. Steps of 0.005-0.03 work best for most * applications, but this will differ depending on use. * * ( end auto-generated ) * * @webref math:random * @param x x-coordinate in noise space * @param y y-coordinate in noise space * @param z z-coordinate in noise space * @see PApplet#noiseSeed(long) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) */ public float noise(float x, float y, float z) { if (perlin == null) { if (perlinRandom == null) { perlinRandom = new Random(); } perlin = new float[PERLIN_SIZE + 1]; for (int i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = perlinRandom.nextFloat(); //(float)Math.random(); } // [toxi 031112] // noise broke due to recent change of cos table in PGraphics // this will take care of it perlin_cosTable = PGraphics.cosLUT; perlin_TWOPI = perlin_PI = PGraphics.SINCOS_LENGTH; perlin_PI >>= 1; } if (x<0) x=-x; if (y<0) y=-y; if (z<0) z=-z; int xi=(int)x, yi=(int)y, zi=(int)z; float xf = x - xi; float yf = y - yi; float zf = z - zi; float rxf, ryf; float r=0; float ampl=0.5f; float n1,n2,n3; for (int i=0; i<perlin_octaves; i++) { int of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB); rxf=noise_fsc(xf); ryf=noise_fsc(yf); n1 = perlin[of&PERLIN_SIZE]; n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1); n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2); n1 += ryf*(n2-n1); of += PERLIN_ZWRAP; n2 = perlin[of&PERLIN_SIZE]; n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2); n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3); n2 += ryf*(n3-n2); n1 += noise_fsc(zf)*(n2-n1); r += n1*ampl; ampl *= perlin_amp_falloff; xi<<=1; xf*=2; yi<<=1; yf*=2; zi<<=1; zf*=2; if (xf>=1.0f) { xi++; xf--; } if (yf>=1.0f) { yi++; yf--; } if (zf>=1.0f) { zi++; zf--; } } return r; } // [toxi 031112] // now adjusts to the size of the cosLUT used via // the new variables, defined above private float noise_fsc(float i) { // using bagel's cosine table instead return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]); } // [toxi 040903] // make perlin noise quality user controlled to allow // for different levels of detail. lower values will produce // smoother results as higher octaves are surpressed /** * ( begin auto-generated from noiseDetail.xml ) * * Adjusts the character and level of detail produced by the Perlin noise * function. Similar to harmonics in physics, noise is computed over * several octaves. Lower octaves contribute more to the output signal and * as such define the overal intensity of the noise, whereas higher octaves * create finer grained details in the noise sequence. By default, noise is * computed over 4 octaves with each octave contributing exactly half than * its predecessor, starting at 50% strength for the 1st octave. This * falloff amount can be changed by adding an additional function * parameter. Eg. a falloff factor of 0.75 means each octave will now have * 75% impact (25% less) of the previous lower octave. Any value between * 0.0 and 1.0 is valid, however note that values greater than 0.5 might * result in greater than 1.0 values returned by <b>noise()</b>.<br /><br * />By changing these parameters, the signal created by the <b>noise()</b> * function can be adapted to fit very specific needs and characteristics. * * ( end auto-generated ) * @webref math:random * @param lod number of octaves to be used by the noise * @param falloff falloff factor for each octave * @see PApplet#noise(float, float, float) */ public void noiseDetail(int lod) { if (lod>0) perlin_octaves=lod; } /** * @param falloff falloff factor for each octave */ public void noiseDetail(int lod, float falloff) { if (lod>0) perlin_octaves=lod; if (falloff>0) perlin_amp_falloff=falloff; } /** * ( begin auto-generated from noiseSeed.xml ) * * Sets the seed value for <b>noise()</b>. By default, <b>noise()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param seed seed value * @see PApplet#noise(float, float, float) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) * @see PApplet#randomSeed(long) */ public void noiseSeed(long seed) { if (perlinRandom == null) perlinRandom = new Random(); perlinRandom.setSeed(seed); // force table reset after changing the random number seed [0122] perlin = null; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . protected String[] loadImageFormats; /** * ( begin auto-generated from loadImage.xml ) * * Loads an image into a variable of type <b>PImage</b>. Four types of * images ( <b>.gif</b>, <b>.jpg</b>, <b>.tga</b>, <b>.png</b>) images may * be loaded. To load correctly, images must be located in the data * directory of the current sketch. In most cases, load all images in * <b>setup()</b> to preload them at the start of the program. Loading * images inside <b>draw()</b> will reduce the speed of a program.<br/> * <br/> <b>filename</b> parameter can also be a URL to a file found * online. For security reasons, a Processing sketch found online can only * download files from the same server from which it came. Getting around * this restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed * applet</a>.<br/> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>loadImage()</b>, as * shown in the third example on this page.<br/> * <br/> an image is not loaded successfully, the <b>null</b> value is * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned from <b>loadImage()</b> is null.<br/> * <br/> on the type of error, a <b>PImage</b> object may still be * returned, but the width and height of the image will be set to -1. This * happens if bad image data is returned or cannot be decoded properly. * Sometimes this happens with image URLs that produce a 403 error or that * redirect to a password prompt, because <b>loadImage()</b> will attempt * to interpret the HTML as image data. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#imageMode(int) * @see PGraphics#background(float, float, float, float) */ public PImage loadImage(String filename) { // return loadImage(filename, null, null); return loadImage(filename, null); } // /** // * @param extension the type of image to load, for example "png", "gif", "jpg" // */ // public PImage loadImage(String filename, String extension) { // return loadImage(filename, extension, null); // } // /** // * @nowebref // */ // public PImage loadImage(String filename, Object params) { // return loadImage(filename, null, params); // } /** * @param extension type of image to load, for example "png", "gif", "jpg" */ public PImage loadImage(String filename, String extension) { //, Object params) { if (extension == null) { String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } } // just in case. them users will try anything! extension = extension.toLowerCase(); if (extension.equals("tga")) { try { PImage image = loadImageTGA(filename); // if (params != null) { // image.setParams(g, params); // } return image; } catch (IOException e) { e.printStackTrace(); return null; } } if (extension.equals("tif") || extension.equals("tiff")) { byte bytes[] = loadBytes(filename); PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes); // if (params != null) { // image.setParams(g, params); // } return image; } // For jpeg, gif, and png, load them using createImage(), // because the javax.imageio code was found to be much slower. // http://dev.processing.org/bugs/show_bug.cgi?id=392 try { if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("gif") || extension.equals("png") || extension.equals("unknown")) { byte bytes[] = loadBytes(filename); if (bytes == null) { return null; } else { Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes); PImage image = loadImageMT(awtImage); if (image.width == -1) { System.err.println("The file " + filename + " contains bad image data, or may not be an image."); } // if it's a .gif image, test to see if it has transparency if (extension.equals("gif") || extension.equals("png")) { image.checkAlpha(); } // if (params != null) { // image.setParams(g, params); // } return image; } } } catch (Exception e) { // show error, but move on to the stuff below, see if it'll work e.printStackTrace(); } if (loadImageFormats == null) { loadImageFormats = ImageIO.getReaderFormatNames(); } if (loadImageFormats != null) { for (int i = 0; i < loadImageFormats.length; i++) { if (extension.equals(loadImageFormats[i])) { return loadImageIO(filename); // PImage image = loadImageIO(filename); // if (params != null) { // image.setParams(g, params); // } // return image; } } } // failed, could not load image after all those attempts System.err.println("Could not find a method to load " + filename); return null; } public PImage requestImage(String filename) { // return requestImage(filename, null, null); return requestImage(filename, null); } /** * ( begin auto-generated from requestImage.xml ) * * This function load images on a separate thread so that your sketch does * not freeze while images load during <b>setup()</b>. While the image is * loading, its width and height will be 0. If an error occurs while * loading the image, its width and height will be set to -1. You'll know * when the image has loaded properly because its width and height will be * greater than 0. Asynchronous image loading (particularly when * downloading from a server) can dramatically improve performance.<br /> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>requestImage()</b>. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @param extension the type of image to load, for example "png", "gif", "jpg" * @see PImage * @see PApplet#loadImage(String, String) */ public PImage requestImage(String filename, String extension) { PImage vessel = createImage(0, 0, ARGB); AsyncImageLoader ail = new AsyncImageLoader(filename, extension, vessel); ail.start(); return vessel; } // /** // * @nowebref // */ // public PImage requestImage(String filename, String extension, Object params) { // PImage vessel = createImage(0, 0, ARGB, params); // AsyncImageLoader ail = // new AsyncImageLoader(filename, extension, vessel); // ail.start(); // return vessel; // } /** * By trial and error, four image loading threads seem to work best when * loading images from online. This is consistent with the number of open * connections that web browsers will maintain. The variable is made public * (however no accessor has been added since it's esoteric) if you really * want to have control over the value used. For instance, when loading local * files, it might be better to only have a single thread (or two) loading * images so that you're disk isn't simply jumping around. */ public int requestImageMax = 4; volatile int requestImageCount; class AsyncImageLoader extends Thread { String filename; String extension; PImage vessel; public AsyncImageLoader(String filename, String extension, PImage vessel) { this.filename = filename; this.extension = extension; this.vessel = vessel; } @Override public void run() { while (requestImageCount == requestImageMax) { try { Thread.sleep(10); } catch (InterruptedException e) { } } requestImageCount++; PImage actual = loadImage(filename, extension); // An error message should have already printed if (actual == null) { vessel.width = -1; vessel.height = -1; } else { vessel.width = actual.width; vessel.height = actual.height; vessel.format = actual.format; vessel.pixels = actual.pixels; } requestImageCount--; } } /** * Load an AWT image synchronously by setting up a MediaTracker for * a single image, and blocking until it has loaded. */ protected PImage loadImageMT(Image awtImage) { MediaTracker tracker = new MediaTracker(this); tracker.addImage(awtImage, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { //e.printStackTrace(); // non-fatal, right? } PImage image = new PImage(awtImage); image.parent = this; return image; } /** * Use Java 1.4 ImageIO methods to load an image. */ protected PImage loadImageIO(String filename) { InputStream stream = createInput(filename); if (stream == null) { System.err.println("The image " + filename + " could not be found."); return null; } try { BufferedImage bi = ImageIO.read(stream); PImage outgoing = new PImage(bi.getWidth(), bi.getHeight()); outgoing.parent = this; bi.getRGB(0, 0, outgoing.width, outgoing.height, outgoing.pixels, 0, outgoing.width); // check the alpha for this image // was gonna call getType() on the image to see if RGB or ARGB, // but it's not actually useful, since gif images will come through // as TYPE_BYTE_INDEXED, which means it'll still have to check for // the transparency. also, would have to iterate through all the other // types and guess whether alpha was in there, so.. just gonna stick // with the old method. outgoing.checkAlpha(); // return the image return outgoing; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Targa image loader for RLE-compressed TGA files. * <p> * Rewritten for 0115 to read/write RLE-encoded targa images. * For 0125, non-RLE encoded images are now supported, along with * images whose y-order is reversed (which is standard for TGA files). * <p> * A version of this function is in MovieMaker.java. Any fixes here * should be applied over in MovieMaker as well. * <p> * Known issue with RLE encoding and odd behavior in some apps: * https://github.com/processing/processing/issues/2096 * Please help! */ protected PImage loadImageTGA(String filename) throws IOException { InputStream is = createInput(filename); if (is == null) return null; byte header[] = new byte[18]; int offset = 0; do { int count = is.read(header, offset, header.length - offset); if (count == -1) return null; offset += count; } while (offset < 18); /* header[2] image type code 2 (0x02) - Uncompressed, RGB images. 3 (0x03) - Uncompressed, black and white images. 10 (0x0A) - Run-length encoded RGB images. 11 (0x0B) - Compressed, black and white images. (grayscale?) header[16] is the bit depth (8, 24, 32) header[17] image descriptor (packed bits) 0x20 is 32 = origin upper-left 0x28 is 32 + 8 = origin upper-left + 32 bits 7 6 5 4 3 2 1 0 128 64 32 16 8 4 2 1 */ int format = 0; if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not (header[16] == 8) && // 8 bits ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit format = ALPHA; } else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not (header[16] == 24) && // 24 bits ((header[17] == 0x20) || (header[17] == 0))) { // origin format = RGB; } else if (((header[2] == 2) || (header[2] == 10)) && (header[16] == 32) && ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 format = ARGB; } if (format == 0) { System.err.println("Unknown .tga file format for " + filename); //" (" + header[2] + " " + //(header[16] & 0xff) + " " + //hex(header[17], 2) + ")"); return null; } int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff); int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff); PImage outgoing = createImage(w, h, format); // where "reversed" means upper-left corner (normal for most of // the modernized world, but "reversed" for the tga spec) //boolean reversed = (header[17] & 0x20) != 0; // https://github.com/processing/processing/issues/1682 boolean reversed = (header[17] & 0x20) == 0; if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded if (reversed) { int index = (h-1) * w; switch (format) { case ALPHA: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read(); } index -= w; } break; case RGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } index -= w; } break; case ARGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } index -= w; } } } else { // not reversed int count = w * h; switch (format) { case ALPHA: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read(); } break; case RGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } break; case ARGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } break; } } } else { // header[2] is 10 or 11 int index = 0; int px[] = outgoing.pixels; while (index < px.length) { int num = is.read(); boolean isRLE = (num & 0x80) != 0; if (isRLE) { num -= 127; // (num & 0x7F) + 1 int pixel = 0; switch (format) { case ALPHA: pixel = is.read(); break; case RGB: pixel = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); break; case ARGB: pixel = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); break; } for (int i = 0; i < num; i++) { px[index++] = pixel; if (index == px.length) break; } } else { // write up to 127 bytes as uncompressed num += 1; switch (format) { case ALPHA: for (int i = 0; i < num; i++) { px[index++] = is.read(); } break; case RGB: for (int i = 0; i < num; i++) { px[index++] = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; case ARGB: for (int i = 0; i < num; i++) { px[index++] = is.read() | //(is.read() << 24) | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; } } } if (!reversed) { int[] temp = new int[w]; for (int y = 0; y < h/2; y++) { int z = (h-1) - y; System.arraycopy(px, y*w, temp, 0, w); System.arraycopy(px, z*w, px, y*w, w); System.arraycopy(temp, 0, px, z*w, w); } } } return outgoing; } ////////////////////////////////////////////////////////////// // DATA I/O // /** // * @webref input:files // * @brief Creates a new XML object // * @param name the name to be given to the root element of the new XML object // * @return an XML object, or null // * @see XML // * @see PApplet#loadXML(String) // * @see PApplet#parseXML(String) // * @see PApplet#saveXML(XML, String) // */ // public XML createXML(String name) { // try { // return new XML(name); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see XML * @see PApplet#parseXML(String) * @see PApplet#saveXML(XML, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadTable(String) */ public XML loadXML(String filename) { return loadXML(filename, null); } // version that uses 'options' though there are currently no supported options /** * @nowebref */ public XML loadXML(String filename, String options) { try { return new XML(createReader(filename), options); // return new XML(createInput(filename), options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref input:files * @brief Converts String content to an XML object * @param data the content to be parsed as XML * @return an XML object, or null * @see XML * @see PApplet#loadXML(String) * @see PApplet#saveXML(XML, String) */ public XML parseXML(String xmlString) { return parseXML(xmlString, null); } public XML parseXML(String xmlString, String options) { try { return XML.parse(xmlString, options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref output:files * @param xml the XML object to save to disk * @param filename name of the file to write to * @see XML * @see PApplet#loadXML(String) * @see PApplet#parseXML(String) */ public boolean saveXML(XML xml, String filename) { return saveXML(xml, filename, null); } public boolean saveXML(XML xml, String filename, String options) { return xml.save(saveFile(filename), options); } public JSONObject parseJSONObject(String input) { return new JSONObject(new StringReader(input)); } /** * @webref input:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONObject loadJSONObject(String filename) { return new JSONObject(createReader(filename)); } static public JSONObject loadJSONObject(File file) { return new JSONObject(createReader(file)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONArray(JSONArray, String) */ public boolean saveJSONObject(JSONObject json, String filename) { return saveJSONObject(json, filename, null); } public boolean saveJSONObject(JSONObject json, String filename, String options) { return json.save(saveFile(filename), options); } public JSONArray parseJSONArray(String input) { return new JSONArray(new StringReader(input)); } /** * @webref input:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONArray loadJSONArray(String filename) { return new JSONArray(createReader(filename)); } static public JSONArray loadJSONArray(File file) { return new JSONArray(createReader(file)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) */ public boolean saveJSONArray(JSONArray json, String filename) { return saveJSONArray(json, filename, null); } public boolean saveJSONArray(JSONArray json, String filename, String options) { return json.save(saveFile(filename), options); } // /** // * @webref input:files // * @see Table // * @see PApplet#loadTable(String) // * @see PApplet#saveTable(Table, String) // */ // public Table createTable() { // return new Table(); // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see Table * @see PApplet#saveTable(Table, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadXML(String) */ public Table loadTable(String filename) { return loadTable(filename, null); } /** * Options may contain "header", "tsv", "csv", or "bin" separated by commas. * * Another option is "dictionary=filename.tsv", which allows users to * specify a "dictionary" file that contains a mapping of the column titles * and the data types used in the table file. This can be far more efficient * (in terms of speed and memory usage) for loading and parsing tables. The * dictionary file can only be tab separated values (.tsv) and its extension * will be ignored. This option was added in Processing 2.0.2. */ public Table loadTable(String filename, String options) { try { String optionStr = Table.extensionOptions(true, filename, options); String[] optionList = trim(split(optionStr, ',')); Table dictionary = null; for (String opt : optionList) { if (opt.startsWith("dictionary=")) { dictionary = loadTable(opt.substring(opt.indexOf('=') + 1), "tsv"); return dictionary.typedParse(createInput(filename), optionStr); } } return new Table(createInput(filename), optionStr); } catch (IOException e) { e.printStackTrace(); return null; } } /** * @webref input:files * @param table the Table object to save to a file * @param filename the filename to which the Table should be saved * @see Table * @see PApplet#loadTable(String) */ public boolean saveTable(Table table, String filename) { return saveTable(table, filename, null); } /** * @param options can be one of "tsv", "csv", "bin", or "html" */ public boolean saveTable(Table table, String filename, String options) { // String ext = checkExtension(filename); // if (ext != null) { // if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin") || ext.equals("html")) { // if (options == null) { // options = ext; // } else { // options = ext + "," + options; // } // } // } try { // Figure out location and make sure the target path exists File outputFile = saveFile(filename); // Open a stream and take care of .gz if necessary return table.save(outputFile, options); } catch (IOException e) { e.printStackTrace(); return false; } } ////////////////////////////////////////////////////////////// // FONT I/O /** * ( begin auto-generated from loadFont.xml ) * * Loads a font into a variable of type <b>PFont</b>. To load correctly, * fonts must be located in the data directory of the current sketch. To * create a font to use with Processing, select "Create Font..." from the * Tools menu. This will create a font in the format Processing requires * and also adds it to the current sketch's data directory.<br /> * <br /> * Like <b>loadImage()</b> and other functions that load data, the * <b>loadFont()</b> function should not be used inside <b>draw()</b>, * because it will slow down the sketch considerably, as the font will be * re-loaded from the disk (or network) on each frame.<br /> * <br /> * For most renderers, Processing displays fonts using the .vlw font * format, which uses images for each letter, rather than defining them * through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with * the JAVA2D renderer, the native version of a font will be used if it is * installed on the user's machine.<br /> * <br /> * Using <b>createFont()</b> (instead of loadFont) enables vector data to * be used with the JAVA2D (default) renderer setting. This can be helpful * when many font sizes are needed, or when using any renderer based on * JAVA2D, such as the PDF library. * * ( end auto-generated ) * @webref typography:loading_displaying * @param filename name of the font to load * @see PFont * @see PGraphics#textFont(PFont, float) * @see PApplet#createFont(String, float, boolean, char[]) */ public PFont loadFont(String filename) { try { InputStream input = createInput(filename); return new PFont(input); } catch (Exception e) { die("Could not load font " + filename + ". " + "Make sure that the font has been copied " + "to the data folder of your sketch.", e); } return null; } /** * Used by PGraphics to remove the requirement for loading a font! */ protected PFont createDefaultFont(float size) { // Font f = new Font("SansSerif", Font.PLAIN, 12); // println("n: " + f.getName()); // println("fn: " + f.getFontName()); // println("ps: " + f.getPSName()); return createFont("Lucida Sans", size, true, null); } public PFont createFont(String name, float size) { return createFont(name, size, true, null); } public PFont createFont(String name, float size, boolean smooth) { return createFont(name, size, smooth, null); } /** * ( begin auto-generated from createFont.xml ) * * Dynamically converts a font to the format used by Processing from either * a font name that's installed on the computer, or from a .ttf or .otf * file inside the sketches "data" folder. This function is an advanced * feature for precise control. On most occasions you should create fonts * through selecting "Create Font..." from the Tools menu. * <br /><br /> * Use the <b>PFont.list()</b> method to first determine the names for the * fonts recognized by the computer and are compatible with this function. * Because of limitations in Java, not all fonts can be used and some might * work with one operating system and not others. When sharing a sketch * with other people or posting it on the web, you may need to include a * .ttf or .otf version of your font in the data directory of the sketch * because other people might not have the font installed on their * computer. Only fonts that can legally be distributed should be included * with a sketch. * <br /><br /> * The <b>size</b> parameter states the font size you want to generate. The * <b>smooth</b> parameter specifies if the font should be antialiased or * not, and the <b>charset</b> parameter is an array of chars that * specifies the characters to generate. * <br /><br /> * This function creates a bitmapped version of a font in the same manner * as the Create Font tool. It loads a font by name, and converts it to a * series of images based on the size of the font. When possible, the * <b>text()</b> function will use a native font rather than the bitmapped * version created behind the scenes with <b>createFont()</b>. For * instance, when using P2D, the actual native version of the font will be * employed by the sketch, improving drawing quality and performance. With * the P3D renderer, the bitmapped version will be used. While this can * drastically improve speed and appearance, results are poor when * exporting if the sketch does not include the .otf or .ttf file, and the * requested font is not available on the machine running the sketch. * * ( end auto-generated ) * @webref typography:loading_displaying * @param name name of the font to load * @param size point size of the font * @param smooth true for an antialiased font, false for aliased * @param charset array containing characters to be generated * @see PFont * @see PGraphics#textFont(PFont, float) * @see PGraphics#text(String, float, float, float, float, float) * @see PApplet#loadFont(String) */ public PFont createFont(String name, float size, boolean smooth, char charset[]) { String lowerName = name.toLowerCase(); Font baseFont = null; try { InputStream stream = null; if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { stream = createInput(name); if (stream == null) { System.err.println("The font \"" + name + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name)); } else { baseFont = PFont.findFont(name); } return new PFont(baseFont.deriveFont(size), smooth, charset, stream != null); } catch (Exception e) { System.err.println("Problem createFont(" + name + ")"); e.printStackTrace(); return null; } } ////////////////////////////////////////////////////////////// // FILE/FOLDER SELECTION private Frame selectFrame; private Frame selectFrame() { if (frame != null) { selectFrame = frame; } else if (selectFrame == null) { Component comp = getParent(); while (comp != null) { if (comp instanceof Frame) { selectFrame = (Frame) comp; break; } comp = comp.getParent(); } // Who you callin' a hack? if (selectFrame == null) { selectFrame = new Frame(); } } return selectFrame; } /** * Open a platform-specific file chooser dialog to select a file for input. * After the selection is made, the selected File will be passed to the * 'callback' function. If the dialog is closed or canceled, null will be * sent to the function, so that the program is not waiting for additional * input. The callback is necessary because of how threading works. * * <pre> * void setup() { * selectInput("Select a file to process:", "fileSelected"); * } * * void fileSelected(File selection) { * if (selection == null) { * println("Window was closed or the user hit cancel."); * } else { * println("User selected " + fileSeleted.getAbsolutePath()); * } * } * </pre> * * For advanced users, the method must be 'public', which is true for all * methods inside a sketch when run from the PDE, but must explicitly be * set when using Eclipse or other development environments. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectInput(String prompt, String callback) { selectInput(prompt, callback, null); } public void selectInput(String prompt, String callback, File file) { selectInput(prompt, callback, file, this); } public void selectInput(String prompt, String callback, File file, Object callbackObject) { selectInput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectInput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD); } /** * See selectInput() for details. * * @webref output:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectOutput(String prompt, String callback) { selectOutput(prompt, callback, null); } public void selectOutput(String prompt, String callback, File file) { selectOutput(prompt, callback, file, this); } public void selectOutput(String prompt, String callback, File file, Object callbackObject) { selectOutput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectOutput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE); } static protected void selectImpl(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame, final int mode) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (useNativeSelect) { FileDialog dialog = new FileDialog(parentFrame, prompt, mode); if (defaultSelection != null) { dialog.setDirectory(defaultSelection.getParent()); dialog.setFile(defaultSelection.getName()); } dialog.setVisible(true); String directory = dialog.getDirectory(); String filename = dialog.getFile(); if (filename != null) { selectedFile = new File(directory, filename); } } else { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(prompt); if (defaultSelection != null) { chooser.setSelectedFile(defaultSelection); } int result = -1; if (mode == FileDialog.SAVE) { result = chooser.showSaveDialog(parentFrame); } else if (mode == FileDialog.LOAD) { result = chooser.showOpenDialog(parentFrame); } if (result == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } /** * See selectInput() for details. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectFolder(String prompt, String callback) { selectFolder(prompt, callback, null); } public void selectFolder(String prompt, String callback, File file) { selectFolder(prompt, callback, file, this); } public void selectFolder(String prompt, String callback, File file, Object callbackObject) { selectFolder(prompt, callback, file, callbackObject, selectFrame()); } static public void selectFolder(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (platform == MACOSX && useNativeSelect != false) { FileDialog fileDialog = new FileDialog(parentFrame, prompt, FileDialog.LOAD); System.setProperty("apple.awt.fileDialogForDirectories", "true"); fileDialog.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); String filename = fileDialog.getFile(); if (filename != null) { selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile()); } } else { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(prompt); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (defaultSelection != null) { fileChooser.setSelectedFile(defaultSelection); } int result = fileChooser.showOpenDialog(parentFrame); if (result == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } static private void selectCallback(File selectedFile, String callbackMethod, Object callbackObject) { try { Class<?> callbackClass = callbackObject.getClass(); Method selectMethod = callbackClass.getMethod(callbackMethod, new Class[] { File.class }); selectMethod.invoke(callbackObject, new Object[] { selectedFile }); } catch (IllegalAccessException iae) { System.err.println(callbackMethod + "() must be public"); } catch (InvocationTargetException ite) { ite.printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println(callbackMethod + "() could not be found"); } } ////////////////////////////////////////////////////////////// // EXTENSIONS /** * Get the compression-free extension for this filename. * @param filename The filename to check * @return an extension, skipping past .gz if it's present */ static public String checkExtension(String filename) { // Don't consider the .gz as part of the name, createInput() // and createOuput() will take care of fixing that up. if (filename.toLowerCase().endsWith(".gz")) { filename = filename.substring(0, filename.length() - 3); } int dotIndex = filename.lastIndexOf('.'); if (dotIndex != -1) { return filename.substring(dotIndex + 1).toLowerCase(); } return null; } ////////////////////////////////////////////////////////////// // READERS AND WRITERS /** * ( begin auto-generated from createReader.xml ) * * Creates a <b>BufferedReader</b> object that can be used to read files * line-by-line as individual <b>String</b> objects. This is the complement * to the <b>createWriter()</b> function. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref input:files * @param filename name of the file to be opened * @see BufferedReader * @see PApplet#createWriter(String) * @see PrintWriter */ public BufferedReader createReader(String filename) { try { InputStream is = createInput(filename); if (is == null) { System.err.println(filename + " does not exist or could not be read"); return null; } return createReader(is); } catch (Exception e) { if (filename == null) { System.err.println("Filename passed to reader() was null"); } else { System.err.println("Couldn't create a reader for " + filename); } } return null; } /** * @nowebref */ static public BufferedReader createReader(File file) { try { InputStream is = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { is = new GZIPInputStream(is); } return createReader(is); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createReader() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a reader for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to read lines from a stream. If I have to type the * following lines any more I'm gonna send Sun my medical bills. */ static public BufferedReader createReader(InputStream input) { InputStreamReader isr = null; try { isr = new InputStreamReader(input, "UTF-8"); } catch (UnsupportedEncodingException e) { } // not gonna happen return new BufferedReader(isr); } /** * ( begin auto-generated from createWriter.xml ) * * Creates a new file in the sketch folder, and a <b>PrintWriter</b> object * to write to it. For the file to be made correctly, it should be flushed * and must be closed with its <b>flush()</b> and <b>close()</b> methods * (see above example). * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to be created * @see PrintWriter * @see PApplet#createReader * @see BufferedReader */ public PrintWriter createWriter(String filename) { return createWriter(saveFile(filename)); } /** * @nowebref * I want to print lines to a file. I have RSI from typing these * eight lines of code so many times. */ static public PrintWriter createWriter(File file) { try { createPath(file); // make sure in-between folders exist OutputStream output = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { output = new GZIPOutputStream(output); } return createWriter(output); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createWriter() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a writer for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to print lines to a file. Why am I always explaining myself? * It's the JavaSoft API engineers who need to explain themselves. */ static public PrintWriter createWriter(OutputStream output) { try { BufferedOutputStream bos = new BufferedOutputStream(output, 8192); OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8"); return new PrintWriter(osw); } catch (UnsupportedEncodingException e) { } // not gonna happen return null; } ////////////////////////////////////////////////////////////// // FILE INPUT /** * @deprecated As of release 0136, use createInput() instead. */ public InputStream openStream(String filename) { return createInput(filename); } /** * ( begin auto-generated from createInput.xml ) * * This is a function for advanced programmers to open a Java InputStream. * It's useful if you want to use the facilities provided by PApplet to * easily open files from the data folder or from a URL, but want an * InputStream object so that you can use other parts of Java to take more * control of how the stream is read.<br /> * <br /> * The filename passed in can be:<br /> * - A URL, for instance <b>openStream("http://processing.org/")</b><br /> * - A file in the sketch's <b>data</b> folder<br /> * - The full path to a file to be opened locally (when running as an * application)<br /> * <br /> * If the requested item doesn't exist, null is returned. If not online, * this will also check to see if the user is asking for a file whose name * isn't properly capitalized. If capitalization is different, an error * will be printed to the console. This helps prevent issues that appear * when a sketch is exported to the web, where case sensitivity matters, as * opposed to running from inside the Processing Development Environment on * Windows or Mac OS, where case sensitivity is preserved but ignored.<br /> * <br /> * If the file ends with <b>.gz</b>, the stream will automatically be gzip * decompressed. If you don't want the automatic decompression, use the * related function <b>createInputRaw()</b>. * <br /> * In earlier releases, this function was called <b>openStream()</b>.<br /> * <br /> * * ( end auto-generated ) * * <h3>Advanced</h3> * Simplified method to open a Java InputStream. * <p> * This method is useful if you want to use the facilities provided * by PApplet to easily open things from the data folder or from a URL, * but want an InputStream object so that you can use other Java * methods to take more control of how the stream is read. * <p> * If the requested item doesn't exist, null is returned. * (Prior to 0096, die() would be called, killing the applet) * <p> * For 0096+, the "data" folder is exported intact with subfolders, * and openStream() properly handles subdirectories from the data folder * <p> * If not online, this will also check to see if the user is asking * for a file whose name isn't properly capitalized. This helps prevent * issues when a sketch is exported to the web, where case sensitivity * matters, as opposed to Windows and the Mac OS default where * case sensitivity is preserved but ignored. * <p> * It is strongly recommended that libraries use this method to open * data files, so that the loading sequence is handled in the same way * as functions like loadBytes(), loadImage(), etc. * <p> * The filename passed in can be: * <UL> * <LI>A URL, for instance openStream("http://processing.org/"); * <LI>A file in the sketch's data folder * <LI>Another file to be opened locally (when running as an application) * </UL> * * @webref input:files * @param filename the name of the file to use as input * @see PApplet#createOutput(String) * @see PApplet#selectOutput(String) * @see PApplet#selectInput(String) * */ public InputStream createInput(String filename) { InputStream input = createInputRaw(filename); if ((input != null) && filename.toLowerCase().endsWith(".gz")) { try { return new GZIPInputStream(input); } catch (IOException e) { e.printStackTrace(); return null; } } return input; } /** * Call openStream() without automatic gzip decompression. */ public InputStream createInputRaw(String filename) { InputStream stream = null; if (filename == null) return null; if (filename.length() == 0) { // an error will be called by the parent function //System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah if (filename.contains(":")) { // at least smells like URL try { URL url = new URL(filename); stream = url.openStream(); return stream; } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. (fix for 0119) // http://dev.processing.org/bugs/show_bug.cgi?id=403 } catch (IOException e) { // changed for 0117, shouldn't be throwing exception e.printStackTrace(); //System.err.println("Error downloading from URL " + filename); return null; //throw new RuntimeException("Error downloading from URL " + filename); } } // Moved this earlier than the getResourceAsStream() checks, because // calling getResourceAsStream() on a directory lists its contents. // http://dev.processing.org/bugs/show_bug.cgi?id=716 try { // First see if it's in a data folder. This may fail by throwing // a SecurityException. If so, this whole block will be skipped. File file = new File(dataPath(filename)); if (!file.exists()) { // next see if it's just in the sketch folder file = sketchFile(filename); } if (file.isDirectory()) { return null; } if (file.exists()) { try { // handle case sensitivity check String filePath = file.getCanonicalPath(); String filenameActual = new File(filePath).getName(); // make sure there isn't a subfolder prepended to the name String filenameShort = new File(filename).getName(); // if the actual filename is the same, but capitalized // differently, warn the user. //if (filenameActual.equalsIgnoreCase(filenameShort) && //!filenameActual.equals(filenameShort)) { if (!filenameActual.equals(filenameShort)) { throw new RuntimeException("This file is named " + filenameActual + " not " + filename + ". Rename the file " + "or change your code."); } } catch (IOException e) { } } // if this file is ok, may as well just load it stream = new FileInputStream(file); if (stream != null) return stream; // have to break these out because a general Exception might // catch the RuntimeException being thrown above } catch (IOException ioe) { } catch (SecurityException se) { } // Using getClassLoader() prevents java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) ClassLoader cl = getClass().getClassLoader(); // by default, data files are exported to the root path of the jar. // (not the data folder) so check there first. stream = cl.getResourceAsStream("data/" + filename); if (stream != null) { String cn = stream.getClass().getName(); // this is an irritation of sun's java plug-in, which will return // a non-null stream for an object that doesn't exist. like all good // things, this is probably introduced in java 1.5. awesome! // http://dev.processing.org/bugs/show_bug.cgi?id=359 if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // When used with an online script, also need to check without the // data folder, in case it's not in a subfolder called 'data'. // http://dev.processing.org/bugs/show_bug.cgi?id=389 stream = cl.getResourceAsStream(filename); if (stream != null) { String cn = stream.getClass().getName(); if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // Finally, something special for the Internet Explorer users. Turns out // that we can't get files that are part of the same folder using the // methods above when using IE, so we have to resort to the old skool // getDocumentBase() from teh applet dayz. 1996, my brotha. try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); // if (conn instanceof HttpURLConnection) { // HttpURLConnection httpConnection = (HttpURLConnection) conn; // // test for 401 result (HTTP only) // int responseCode = httpConnection.getResponseCode(); // } } } catch (Exception e) { } // IO or NPE or... // Now try it with a 'data' subfolder. getting kinda desperate for data... try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, "data/" + filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); } } catch (Exception e) { } try { // attempt to load from a local file, used when running as // an application, or as a signed applet try { // first try to catch any security exceptions try { stream = new FileInputStream(dataPath(filename)); if (stream != null) return stream; } catch (IOException e2) { } try { stream = new FileInputStream(sketchPath(filename)); if (stream != null) return stream; } catch (Exception e) { } // ignored try { stream = new FileInputStream(filename); if (stream != null) return stream; } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups } catch (Exception e) { //die(e.getMessage(), e); e.printStackTrace(); } return null; } /** * @nowebref */ static public InputStream createInput(File file) { if (file == null) { throw new IllegalArgumentException("File passed to createInput() was null"); } try { InputStream input = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPInputStream(input); } return input; } catch (IOException e) { System.err.println("Could not createInput() for " + file); e.printStackTrace(); return null; } } /** * ( begin auto-generated from loadBytes.xml ) * * Reads the contents of a file or url and places it in a byte array. If a * file is specified, it must be located in the sketch's "data" * directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * * ( end auto-generated ) * @webref input:files * @param filename name of a file in the data folder or a URL. * @see PApplet#loadStrings(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) * */ public byte[] loadBytes(String filename) { InputStream is = createInput(filename); if (is != null) { byte[] outgoing = loadBytes(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); // shouldn't happen } return outgoing; } System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public byte[] loadBytes(InputStream input) { try { BufferedInputStream bis = new BufferedInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { out.write(c); c = bis.read(); } return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Couldn't load bytes from stream"); } return null; } /** * @nowebref */ static public byte[] loadBytes(File file) { InputStream is = createInput(file); return loadBytes(is); } /** * @nowebref */ static public String[] loadStrings(File file) { InputStream is = createInput(file); if (is != null) { String[] outgoing = loadStrings(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); } return outgoing; } return null; } /** * ( begin auto-generated from loadStrings.xml ) * * Reads the contents of a file or url and creates a String array of its * individual lines. If a file is specified, it must be located in the * sketch's "data" directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * <br /> * If the file is not available or an error occurs, <b>null</b> will be * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned is null. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * Load data from a file and shove it into a String array. * <p> * Exceptions are handled internally, when an error, occurs, an * exception is printed to the console and 'null' is returned, * but the program continues running. This is a tradeoff between * 1) showing the user that there was a problem but 2) not requiring * that all i/o code is contained in try/catch blocks, for the sake * of new users (or people who are just trying to get things done * in a "scripting" fashion. If you want to handle exceptions, * use Java methods for I/O. * * @webref input:files * @param filename name of the file or url to load * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) */ public String[] loadStrings(String filename) { InputStream is = createInput(filename); if (is != null) return loadStrings(is); System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public String[] loadStrings(InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); return loadStrings(reader); } catch (IOException e) { e.printStackTrace(); } return null; } static public String[] loadStrings(BufferedReader reader) { try { String lines[] = new String[100]; int lineCount = 0; String line = null; while ((line = reader.readLine()) != null) { if (lineCount == lines.length) { String temp[] = new String[lineCount << 1]; System.arraycopy(lines, 0, temp, 0, lineCount); lines = temp; } lines[lineCount++] = line; } reader.close(); if (lineCount == lines.length) { return lines; } // resize array to appropriate amount for these lines String output[] = new String[lineCount]; System.arraycopy(lines, 0, output, 0, lineCount); return output; } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Error inside loadStrings()"); } return null; } ////////////////////////////////////////////////////////////// // FILE OUTPUT /** * ( begin auto-generated from createOutput.xml ) * * Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b> * for a given filename or path. The file will be created in the sketch * folder, or in the same folder as an exported application. * <br /><br /> * If the path does not exist, intermediate folders will be created. If an * exception occurs, it will be printed to the console, and <b>null</b> * will be returned. * <br /><br /> * This function is a convenience over the Java approach that requires you * to 1) create a FileOutputStream object, 2) determine the exact file * location, and 3) handle exceptions. Exceptions are handled internally by * the function, which is more appropriate for "sketch" projects. * <br /><br /> * If the output filename ends with <b>.gz</b>, the output will be * automatically GZIP compressed as it is written. * * ( end auto-generated ) * @webref output:files * @param filename name of the file to open * @see PApplet#createInput(String) * @see PApplet#selectOutput() */ public OutputStream createOutput(String filename) { return createOutput(saveFile(filename)); } /** * @nowebref */ static public OutputStream createOutput(File file) { try { createPath(file); // make sure the path exists FileOutputStream fos = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPOutputStream(fos); } return fos; } catch (IOException e) { e.printStackTrace(); } return null; } /** * ( begin auto-generated from saveStream.xml ) * * Save the contents of a stream to a file in the sketch folder. This is * basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently * (and with less confusing syntax).<br /> * <br /> * When using the <b>targetFile</b> parameter, it writes to a <b>File</b> * object for greater control over the file location. (Note that unlike * some other functions, this will not automatically compress or uncompress * gzip files.) * * ( end auto-generated ) * * @webref output:files * @param target name of the file to write to * @param source location to read from (a filename, path, or URL) * @see PApplet#createOutput(String) */ public boolean saveStream(String target, String source) { return saveStream(saveFile(target), source); } /** * Identical to the other saveStream(), but writes to a File * object, for greater control over the file location. * <p/> * Note that unlike other api methods, this will not automatically * compress or uncompress gzip files. */ public boolean saveStream(File target, String source) { return saveStream(target, createInputRaw(source)); } /** * @nowebref */ public boolean saveStream(String target, InputStream source) { return saveStream(saveFile(target), source); } /** * @nowebref */ static public boolean saveStream(File target, InputStream source) { File tempFile = null; try { File parentDir = target.getParentFile(); // make sure that this path actually exists before writing createPath(target); tempFile = File.createTempFile(target.getName(), null, parentDir); FileOutputStream targetStream = new FileOutputStream(tempFile); saveStream(targetStream, source); targetStream.close(); targetStream = null; if (target.exists()) { if (!target.delete()) { System.err.println("Could not replace " + target.getAbsolutePath() + "."); } } if (!tempFile.renameTo(target)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); return false; } return true; } catch (IOException e) { if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); return false; } } /** * @nowebref */ static public void saveStream(OutputStream target, InputStream source) throws IOException { BufferedInputStream bis = new BufferedInputStream(source, 16384); BufferedOutputStream bos = new BufferedOutputStream(target); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); } /** * ( begin auto-generated from saveBytes.xml ) * * Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a * file. The data is saved in binary format. This file is saved to the * sketch's folder, which is opened by selecting "Show sketch folder" from * the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to write to * @param data array of bytes to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) */ public void saveBytes(String filename, byte[] data) { saveBytes(saveFile(filename), data); } /** * @nowebref * Saves bytes to a specific File location specified by the user. */ static public void saveBytes(File file, byte[] data) { File tempFile = null; try { File parentDir = file.getParentFile(); tempFile = File.createTempFile(file.getName(), null, parentDir); OutputStream output = createOutput(tempFile); saveBytes(output, data); output.close(); output = null; if (file.exists()) { if (!file.delete()) { System.err.println("Could not replace " + file.getAbsolutePath()); } } if (!tempFile.renameTo(file)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); } } catch (IOException e) { System.err.println("error saving bytes to " + file); if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); } } /** * @nowebref * Spews a buffer of bytes to an OutputStream. */ static public void saveBytes(OutputStream output, byte[] data) { try { output.write(data); output.flush(); } catch (IOException e) { e.printStackTrace(); } } // /** * ( begin auto-generated from saveStrings.xml ) * * Writes an array of strings to a file, one line per string. This file is * saved to the sketch's folder, which is opened by selecting "Show sketch * folder" from the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * Starting with Processing 1.0, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref output:files * @param filename filename for output * @param data string array to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveBytes(String, byte[]) */ public void saveStrings(String filename, String data[]) { saveStrings(saveFile(filename), data); } /** * @nowebref */ static public void saveStrings(File file, String data[]) { saveStrings(createOutput(file), data); } /** * @nowebref */ static public void saveStrings(OutputStream output, String[] data) { PrintWriter writer = createWriter(output); for (int i = 0; i < data.length; i++) { writer.println(data[i]); } writer.flush(); writer.close(); } ////////////////////////////////////////////////////////////// /** * Prepend the sketch folder path to the filename (or path) that is * passed in. External libraries should use this function to save to * the sketch folder. * <p/> * Note that when running as an applet inside a web browser, * the sketchPath will be set to null, because security restrictions * prevent applets from accessing that information. * <p/> * This will also cause an error if the sketch is not inited properly, * meaning that init() was never called on the PApplet when hosted * my some other main() or by other code. For proper use of init(), * see the examples in the main description text for PApplet. */ public String sketchPath(String where) { if (sketchPath == null) { return where; // throw new RuntimeException("The applet was not inited properly, " + // "or security restrictions prevented " + // "it from determining its path."); } // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. // for 0120, added a try/catch anyways. try { if (new File(where).isAbsolute()) return where; } catch (Exception e) { } return sketchPath + File.separator + where; } public File sketchFile(String where) { return new File(sketchPath(where)); } /** * Returns a path inside the applet folder to save to. Like sketchPath(), * but creates any in-between folders so that things save properly. * <p/> * All saveXxxx() functions use the path to the sketch folder, rather than * its data folder. Once exported, the data folder will be found inside the * jar file of the exported application or applet. In this case, it's not * possible to save data into the jar file, because it will often be running * from a server, or marked in-use if running from a local file system. * With this in mind, saving to the data path doesn't make sense anyway. * If you know you're running locally, and want to save to the data folder, * use <TT>saveXxxx("data/blah.dat")</TT>. */ public String savePath(String where) { if (where == null) return null; String filename = sketchPath(where); createPath(filename); return filename; } /** * Identical to savePath(), but returns a File object. */ public File saveFile(String where) { return new File(savePath(where)); } static File desktopFolder; /** Not a supported function. For testing use only. */ static public File desktopFile(String what) { if (desktopFolder == null) { // Should work on Linux and OS X (on OS X, even with the localized version). desktopFolder = new File(System.getProperty("user.home"), "Desktop"); if (!desktopFolder.exists()) { if (platform == WINDOWS) { FileSystemView filesys = FileSystemView.getFileSystemView(); desktopFolder = filesys.getHomeDirectory(); } else { throw new UnsupportedOperationException("Could not find a suitable desktop foldder"); } } } return new File(desktopFolder, what); } /** Not a supported function. For testing use only. */ static public String desktopPath(String what) { return desktopFile(what).getAbsolutePath(); } /** * Return a full path to an item in the data folder. * <p> * This is only available with applications, not applets or Android. * On Windows and Linux, this is simply the data folder, which is located * in the same directory as the EXE file and lib folders. On Mac OS X, this * is a path to the data folder buried inside Contents/Java. * For the latter point, that also means that the data folder should not be * considered writable. Use sketchPath() for now, or inputPath() and * outputPath() once they're available in the 2.0 release. * <p> * dataPath() is not supported with applets because applets have their data * folder wrapped into the JAR file. To read data from the data folder that * works with an applet, you should use other methods such as createInput(), * createReader(), or loadStrings(). */ public String dataPath(String where) { return dataFile(where).getAbsolutePath(); } /** * Return a full path to an item in the data folder as a File object. * See the dataPath() method for more information. */ public File dataFile(String where) { // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. File why = new File(where); if (why.isAbsolute()) return why; String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); if (jarPath.contains("Contents/Java/")) { // The path will be URL encoded (%20 for spaces) coming from above // http://code.google.com/p/processing/issues/detail?id=1073 File containingFolder = new File(urlDecode(jarPath)).getParentFile(); File dataFolder = new File(containingFolder, "data"); System.out.println(dataFolder); return new File(dataFolder, where); } // Windows, Linux, or when not using a Mac OS X .app file return new File(sketchPath + File.separator + "data" + File.separator + where); } /** * On Windows and Linux, this is simply the data folder. On Mac OS X, this is * the path to the data folder buried inside Contents/Java */ // public File inputFile(String where) { // } // public String inputPath(String where) { // } /** * Takes a path and creates any in-between folders if they don't * already exist. Useful when trying to save to a subfolder that * may not actually exist. */ static public void createPath(String path) { createPath(new File(path)); } static public void createPath(File file) { try { String parent = file.getParent(); if (parent != null) { File unit = new File(parent); if (!unit.exists()) unit.mkdirs(); } } catch (SecurityException se) { System.err.println("You don't have permissions to create " + file.getAbsolutePath()); } } static public String getExtension(String filename) { String extension; String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } return extension; } ////////////////////////////////////////////////////////////// // URL ENCODING static public String urlEncode(String str) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // oh c'mon return null; } } static public String urlDecode(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // safe per the JDK source return null; } } ////////////////////////////////////////////////////////////// // SORT /** * ( begin auto-generated from sort.xml ) * * Sorts an array of numbers from smallest to largest and puts an array of * words in alphabetical order. The original array is not modified, a * re-ordered array is returned. The <b>count</b> parameter states the * number of elements to sort. For example if there are 12 elements in an * array and if count is the value 5, only the first five elements on the * array will be sorted. <!--As of release 0126, the alphabetical ordering * is case insensitive.--> * * ( end auto-generated ) * @webref data:array_functions * @param list array to sort * @see PApplet#reverse(boolean[]) */ static public byte[] sort(byte list[]) { return sort(list, list.length); } /** * @param count number of elements to sort, starting from 0 */ static public byte[] sort(byte[] list, int count) { byte[] outgoing = new byte[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public char[] sort(char list[]) { return sort(list, list.length); } static public char[] sort(char[] list, int count) { char[] outgoing = new char[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public int[] sort(int list[]) { return sort(list, list.length); } static public int[] sort(int[] list, int count) { int[] outgoing = new int[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public float[] sort(float list[]) { return sort(list, list.length); } static public float[] sort(float[] list, int count) { float[] outgoing = new float[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public String[] sort(String list[]) { return sort(list, list.length); } static public String[] sort(String[] list, int count) { String[] outgoing = new String[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } ////////////////////////////////////////////////////////////// // ARRAY UTILITIES /** * ( begin auto-generated from arrayCopy.xml ) * * Copies an array (or part of an array) to another array. The <b>src</b> * array is copied to the <b>dst</b> array, beginning at the position * specified by <b>srcPos</b> and into the position specified by * <b>dstPos</b>. The number of elements to copy is determined by * <b>length</b>. The simplified version with two arguments copies an * entire array to another of the same size. It is equivalent to * "arrayCopy(src, 0, dst, 0, src.length)". This function is far more * efficient for copying array data than iterating through a <b>for</b> and * copying each element. * * ( end auto-generated ) * @webref data:array_functions * @param src the source array * @param srcPosition starting position in the source array * @param dst the destination array of the same data type as the source array * @param dstPosition starting position in the destination array * @param length number of array elements to be copied * @see PApplet#concat(boolean[], boolean[]) */ static public void arrayCopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * Convenience method for arraycopy(). * Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE> */ static public void arrayCopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * Shortcut to copy the entire contents of * the source into the destination array. * Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE> */ static public void arrayCopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } // /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } /** * ( begin auto-generated from expand.xml ) * * Increases the size of an array. By default, this function doubles the * size of the array, but the optional <b>newSize</b> parameter provides * precise control over the increase in size. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) expand(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list the array to expand * @see PApplet#shorten(boolean[]) */ static public boolean[] expand(boolean list[]) { return expand(list, list.length << 1); } /** * @param newSize new size for the array */ static public boolean[] expand(boolean list[], int newSize) { boolean temp[] = new boolean[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public byte[] expand(byte list[]) { return expand(list, list.length << 1); } static public byte[] expand(byte list[], int newSize) { byte temp[] = new byte[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public char[] expand(char list[]) { return expand(list, list.length << 1); } static public char[] expand(char list[], int newSize) { char temp[] = new char[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public int[] expand(int list[]) { return expand(list, list.length << 1); } static public int[] expand(int list[], int newSize) { int temp[] = new int[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public long[] expand(long list[]) { return expand(list, list.length << 1); } static public long[] expand(long list[], int newSize) { long temp[] = new long[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public float[] expand(float list[]) { return expand(list, list.length << 1); } static public float[] expand(float list[], int newSize) { float temp[] = new float[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public double[] expand(double list[]) { return expand(list, list.length << 1); } static public double[] expand(double list[], int newSize) { double temp[] = new double[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public String[] expand(String list[]) { return expand(list, list.length << 1); } static public String[] expand(String list[], int newSize) { String temp[] = new String[newSize]; // in case the new size is smaller than list.length System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } /** * @nowebref */ static public Object expand(Object array) { return expand(array, Array.getLength(array) << 1); } static public Object expand(Object list, int newSize) { Class<?> type = list.getClass().getComponentType(); Object temp = Array.newInstance(type, newSize); System.arraycopy(list, 0, temp, 0, Math.min(Array.getLength(list), newSize)); return temp; } // contract() has been removed in revision 0124, use subset() instead. // (expand() is also functionally equivalent) /** * ( begin auto-generated from append.xml ) * * Expands an array by one element and adds data to the new position. The * datatype of the <b>element</b> parameter must be the same as the * datatype of the array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) append(originalArray, element)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param array array to append * @param value new data for the array * @see PApplet#shorten(boolean[]) * @see PApplet#expand(boolean[]) */ static public byte[] append(byte array[], byte value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public char[] append(char array[], char value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public int[] append(int array[], int value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public float[] append(float array[], float value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public String[] append(String array[], String value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public Object append(Object array, Object value) { int length = Array.getLength(array); array = expand(array, length + 1); Array.set(array, length, value); return array; } /** * ( begin auto-generated from shorten.xml ) * * Decreases an array by one element and returns the shortened array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) shorten(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list array to shorten * @see PApplet#append(byte[], byte) * @see PApplet#expand(boolean[]) */ static public boolean[] shorten(boolean list[]) { return subset(list, 0, list.length-1); } static public byte[] shorten(byte list[]) { return subset(list, 0, list.length-1); } static public char[] shorten(char list[]) { return subset(list, 0, list.length-1); } static public int[] shorten(int list[]) { return subset(list, 0, list.length-1); } static public float[] shorten(float list[]) { return subset(list, 0, list.length-1); } static public String[] shorten(String list[]) { return subset(list, 0, list.length-1); } static public Object shorten(Object list) { int length = Array.getLength(list); return subset(list, 0, length - 1); } /** * ( begin auto-generated from splice.xml ) * * Inserts a value or array of values into an existing array. The first two * parameters must be of the same datatype. The <b>array</b> parameter * defines the array which will be modified and the second parameter * defines the data which will be inserted. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) splice(array1, array2, index)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to splice into * @param value value to be spliced in * @param index position in the array from which to insert data * @see PApplet#concat(boolean[], boolean[]) * @see PApplet#subset(boolean[], int, int) */ static final public boolean[] splice(boolean list[], boolean value, int index) { boolean outgoing[] = new boolean[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public boolean[] splice(boolean list[], boolean value[], int index) { boolean outgoing[] = new boolean[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value, int index) { byte outgoing[] = new byte[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value[], int index) { byte outgoing[] = new byte[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public char[] splice(char list[], char value, int index) { char outgoing[] = new char[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public char[] splice(char list[], char value[], int index) { char outgoing[] = new char[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public int[] splice(int list[], int value, int index) { int outgoing[] = new int[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public int[] splice(int list[], int value[], int index) { int outgoing[] = new int[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public float[] splice(float list[], float value, int index) { float outgoing[] = new float[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public float[] splice(float list[], float value[], int index) { float outgoing[] = new float[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public String[] splice(String list[], String value, int index) { String outgoing[] = new String[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public String[] splice(String list[], String value[], int index) { String outgoing[] = new String[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public Object splice(Object list, Object value, int index) { Object[] outgoing = null; int length = Array.getLength(list); // check whether item being spliced in is an array if (value.getClass().getName().charAt(0) == '[') { int vlength = Array.getLength(value); outgoing = new Object[length + vlength]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, vlength); System.arraycopy(list, index, outgoing, index + vlength, length - index); } else { outgoing = new Object[length + 1]; System.arraycopy(list, 0, outgoing, 0, index); Array.set(outgoing, index, value); System.arraycopy(list, index, outgoing, index + 1, length - index); } return outgoing; } static public boolean[] subset(boolean list[], int start) { return subset(list, start, list.length - start); } /** * ( begin auto-generated from subset.xml ) * * Extracts an array of elements from an existing array. The <b>array</b> * parameter defines the array from which the elements will be copied and * the <b>offset</b> and <b>length</b> parameters determine which elements * to extract. If no <b>length</b> is given, elements will be extracted * from the <b>offset</b> to the end of the array. When specifying the * <b>offset</b> remember the first array element is 0. This function does * not change the source array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) subset(originalArray, 0, 4)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to extract from * @param start position to begin * @param count number of values to extract * @see PApplet#splice(boolean[], boolean, int) */ static public boolean[] subset(boolean list[], int start, int count) { boolean output[] = new boolean[count]; System.arraycopy(list, start, output, 0, count); return output; } static public byte[] subset(byte list[], int start) { return subset(list, start, list.length - start); } static public byte[] subset(byte list[], int start, int count) { byte output[] = new byte[count]; System.arraycopy(list, start, output, 0, count); return output; } static public char[] subset(char list[], int start) { return subset(list, start, list.length - start); } static public char[] subset(char list[], int start, int count) { char output[] = new char[count]; System.arraycopy(list, start, output, 0, count); return output; } static public int[] subset(int list[], int start) { return subset(list, start, list.length - start); } static public int[] subset(int list[], int start, int count) { int output[] = new int[count]; System.arraycopy(list, start, output, 0, count); return output; } static public float[] subset(float list[], int start) { return subset(list, start, list.length - start); } static public float[] subset(float list[], int start, int count) { float output[] = new float[count]; System.arraycopy(list, start, output, 0, count); return output; } static public String[] subset(String list[], int start) { return subset(list, start, list.length - start); } static public String[] subset(String list[], int start, int count) { String output[] = new String[count]; System.arraycopy(list, start, output, 0, count); return output; } static public Object subset(Object list, int start) { int length = Array.getLength(list); return subset(list, start, length - start); } static public Object subset(Object list, int start, int count) { Class<?> type = list.getClass().getComponentType(); Object outgoing = Array.newInstance(type, count); System.arraycopy(list, start, outgoing, 0, count); return outgoing; } /** * ( begin auto-generated from concat.xml ) * * Concatenates two arrays. For example, concatenating the array { 1, 2, 3 * } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters * must be arrays of the same datatype. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) concat(array1, array2)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param a first array to concatenate * @param b second array to concatenate * @see PApplet#splice(boolean[], boolean, int) * @see PApplet#arrayCopy(Object, int, Object, int, int) */ static public boolean[] concat(boolean a[], boolean b[]) { boolean c[] = new boolean[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public byte[] concat(byte a[], byte b[]) { byte c[] = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public char[] concat(char a[], char b[]) { char c[] = new char[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public int[] concat(int a[], int b[]) { int c[] = new int[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public float[] concat(float a[], float b[]) { float c[] = new float[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public String[] concat(String a[], String b[]) { String c[] = new String[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public Object concat(Object a, Object b) { Class<?> type = a.getClass().getComponentType(); int alength = Array.getLength(a); int blength = Array.getLength(b); Object outgoing = Array.newInstance(type, alength + blength); System.arraycopy(a, 0, outgoing, 0, alength); System.arraycopy(b, 0, outgoing, alength, blength); return outgoing; } // /** * ( begin auto-generated from reverse.xml ) * * Reverses the order of an array. * * ( end auto-generated ) * @webref data:array_functions * @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[] * @see PApplet#sort(String[], int) */ static public boolean[] reverse(boolean list[]) { boolean outgoing[] = new boolean[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public byte[] reverse(byte list[]) { byte outgoing[] = new byte[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public char[] reverse(char list[]) { char outgoing[] = new char[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public int[] reverse(int list[]) { int outgoing[] = new int[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public float[] reverse(float list[]) { float outgoing[] = new float[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public String[] reverse(String list[]) { String outgoing[] = new String[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public Object reverse(Object list) { Class<?> type = list.getClass().getComponentType(); int length = Array.getLength(list); Object outgoing = Array.newInstance(type, length); for (int i = 0; i < length; i++) { Array.set(outgoing, i, Array.get(list, (length - 1) - i)); } return outgoing; } ////////////////////////////////////////////////////////////// // STRINGS /** * ( begin auto-generated from trim.xml ) * * Removes whitespace characters from the beginning and end of a String. In * addition to standard whitespace characters such as space, carriage * return, and tab, this function also removes the Unicode "nbsp" character. * * ( end auto-generated ) * @webref data:string_functions * @param str any string * @see PApplet#split(String, String) * @see PApplet#join(String[], char) */ static public String trim(String str) { return str.replace('\u00A0', ' ').trim(); } /** * @param array a String array */ static public String[] trim(String[] array) { String[] outgoing = new String[array.length]; for (int i = 0; i < array.length; i++) { if (array[i] != null) { outgoing[i] = array[i].replace('\u00A0', ' ').trim(); } } return outgoing; } /** * ( begin auto-generated from join.xml ) * * Combines an array of Strings into one String, each separated by the * character(s) used for the <b>separator</b> parameter. To join arrays of * ints or floats, it's necessary to first convert them to strings using * <b>nf()</b> or <b>nfs()</b>. * * ( end auto-generated ) * @webref data:string_functions * @param list array of Strings * @param separator char or String to be placed between each item * @see PApplet#split(String, String) * @see PApplet#trim(String) * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) */ static public String join(String[] list, char separator) { return join(list, String.valueOf(separator)); } static public String join(String[] list, String separator) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { if (i != 0) buffer.append(separator); buffer.append(list[i]); } return buffer.toString(); } static public String[] splitTokens(String value) { return splitTokens(value, WHITESPACE); } /** * ( begin auto-generated from splitTokens.xml ) * * The splitTokens() function splits a String at one or many character * "tokens." The <b>tokens</b> parameter specifies the character or * characters to be used as a boundary. * <br/> <br/> * If no <b>tokens</b> character is specified, any whitespace character is * used to split. Whitespace characters include tab (\\t), line feed (\\n), * carriage return (\\r), form feed (\\f), and space. To convert a String * to an array of integers or floats, use the datatype conversion functions * <b>int()</b> and <b>float()</b> to convert the array of Strings. * * ( end auto-generated ) * @webref data:string_functions * @param value the String to be split * @param delim list of individual characters that will be used as separators * @see PApplet#split(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] splitTokens(String value, String delim) { StringTokenizer toker = new StringTokenizer(value, delim); String pieces[] = new String[toker.countTokens()]; int index = 0; while (toker.hasMoreTokens()) { pieces[index++] = toker.nextToken(); } return pieces; } /** * ( begin auto-generated from split.xml ) * * The split() function breaks a string into pieces using a character or * string as the divider. The <b>delim</b> parameter specifies the * character or characters that mark the boundaries between each piece. A * String[] array is returned that contains each of the pieces. * <br/> <br/> * If the result is a set of numbers, you can convert the String[] array to * to a float[] or int[] array using the datatype conversion functions * <b>int()</b> and <b>float()</b> (see example above). * <br/> <br/> * The <b>splitTokens()</b> function works in a similar fashion, except * that it splits using a range of characters instead of a specific * character or sequence. * <!-- /><br /> * This function uses regular expressions to determine how the <b>delim</b> * parameter divides the <b>str</b> parameter. Therefore, if you use * characters such parentheses and brackets that are used with regular * expressions as a part of the <b>delim</b> parameter, you'll need to put * two blackslashes (\\\\) in front of the character (see example above). * You can read more about <a * href="http://en.wikipedia.org/wiki/Regular_expression">regular * expressions</a> and <a * href="http://en.wikipedia.org/wiki/Escape_character">escape * characters</a> on Wikipedia. * --> * * ( end auto-generated ) * @webref data:string_functions * @usage web_application * @param value the String to be split * @param delim the character or String used to separate the data */ static public String[] split(String value, char delim) { // do this so that the exception occurs inside the user's // program, rather than appearing to be a bug inside split() if (value == null) return null; //return split(what, String.valueOf(delim)); // huh char chars[] = value.toCharArray(); int splitCount = 0; //1; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) splitCount++; } // make sure that there is something in the input string //if (chars.length > 0) { // if the last char is a delimeter, get rid of it.. //if (chars[chars.length-1] == delim) splitCount--; // on second thought, i don't agree with this, will disable //} if (splitCount == 0) { String splits[] = new String[1]; splits[0] = new String(value); return splits; } //int pieceCount = splitCount + 1; String splits[] = new String[splitCount + 1]; int splitIndex = 0; int startIndex = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) { splits[splitIndex++] = new String(chars, startIndex, i-startIndex); startIndex = i + 1; } } //if (startIndex != chars.length) { splits[splitIndex] = new String(chars, startIndex, chars.length-startIndex); //} return splits; } static public String[] split(String value, String delim) { ArrayList<String> items = new ArrayList<String>(); int index; int offset = 0; while ((index = value.indexOf(delim, offset)) != -1) { items.add(value.substring(offset, index)); offset = index + delim.length(); } items.add(value.substring(offset)); String[] outgoing = new String[items.size()]; items.toArray(outgoing); return outgoing; } static protected HashMap<String, Pattern> matchPatterns; static Pattern matchPattern(String regexp) { Pattern p = null; if (matchPatterns == null) { matchPatterns = new HashMap<String, Pattern>(); } else { p = matchPatterns.get(regexp); } if (p == null) { if (matchPatterns.size() == 10) { // Just clear out the match patterns here if more than 10 are being // used. It's not terribly efficient, but changes that you have >10 // different match patterns are very slim, unless you're doing // something really tricky (like custom match() methods), in which // case match() won't be efficient anyway. (And you should just be // using your own Java code.) The alternative is using a queue here, // but that's a silly amount of work for negligible benefit. matchPatterns.clear(); } p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); matchPatterns.put(regexp, p); } return p; } /** * ( begin auto-generated from match.xml ) * * The match() function is used to apply a regular expression to a piece of * text, and return matching groups (elements found inside parentheses) as * a String array. No match will return null. If no groups are specified in * the regexp, but the sequence matches, an array of length one (with the * matched text as the first element of the array) will be returned.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match. If the sequence did * match, an array is returned. * If there are groups (specified by sets of parentheses) in the regexp, * then the contents of each will be returned in the array. * Element [0] of a regexp match returns the entire matching string, and * the match groups start at element [1] (the first group is [1], the * second [2], and so on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#matchAll(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] match(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); if (m.find()) { int count = m.groupCount() + 1; String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } return groups; } return null; } /** * ( begin auto-generated from matchAll.xml ) * * This function is used to apply a regular expression to a piece of text, * and return a list of matching groups (elements found inside parentheses) * as a two-dimensional String array. No matches will return null. If no * groups are specified in the regexp, but the sequence matches, a two * dimensional array is still returned, but the second dimension is only of * length one.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, a 2D array is returned. If there are groups (specified by * sets of parentheses) in the regexp, then the contents of each will be * returned in the array. * Assuming, a loop with counter variable i, element [i][0] of a regexp * match returns the entire matching string, and the match groups start at * element [i][1] (the first group is [i][1], the second [i][2], and so * on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#match(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[][] matchAll(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); ArrayList<String[]> results = new ArrayList<String[]>(); int count = m.groupCount() + 1; while (m.find()) { String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } results.add(groups); } if (results.isEmpty()) { return null; } String[][] matches = new String[results.size()][count]; for (int i = 0; i < matches.length; i++) { matches[i] = results.get(i); } return matches; } ////////////////////////////////////////////////////////////// // CASTING FUNCTIONS, INSERTED BY PREPROC /** * Convert a char to a boolean. 'T', 't', and '1' will become the * boolean value true, while 'F', 'f', or '0' will become false. */ /* static final public boolean parseBoolean(char what) { return ((what == 't') || (what == 'T') || (what == '1')); } */ /** * <p>Convert an integer to a boolean. Because of how Java handles upgrading * numbers, this will also cover byte and char (as they will upgrade to * an int without any sort of explicit cast).</p> * <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p> * @return false if 0, true if any other number */ static final public boolean parseBoolean(int what) { return (what != 0); } /* // removed because this makes no useful sense static final public boolean parseBoolean(float what) { return (what != 0); } */ /** * Convert the string "true" or "false" to a boolean. * @return true if 'what' is "true" or "TRUE", false otherwise */ static final public boolean parseBoolean(String what) { return new Boolean(what).booleanValue(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* // removed, no need to introduce strange syntax from other languages static final public boolean[] parseBoolean(char what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1')); } return outgoing; } */ /** * Convert a byte array to a boolean array. Each element will be * evaluated identical to the integer case, where a byte equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ /* static final public boolean[] parseBoolean(byte what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ /** * Convert an int array to a boolean array. An int equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ static final public boolean[] parseBoolean(int what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } /* // removed, not necessary... if necessary, convert to int array first static final public boolean[] parseBoolean(float what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ static final public boolean[] parseBoolean(String what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = new Boolean(what[i]).booleanValue(); } return outgoing; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte parseByte(boolean what) { return what ? (byte)1 : 0; } static final public byte parseByte(char what) { return (byte) what; } static final public byte parseByte(int what) { return (byte) what; } static final public byte parseByte(float what) { return (byte) what; } /* // nixed, no precedent static final public byte[] parseByte(String what) { // note: array[] return what.getBytes(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte[] parseByte(boolean what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? (byte)1 : 0; } return outgoing; } static final public byte[] parseByte(char what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(int what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(float what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } /* static final public byte[][] parseByte(String what[]) { // note: array[][] byte outgoing[][] = new byte[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].getBytes(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char parseChar(boolean what) { // 0/1 or T/F ? return what ? 't' : 'f'; } */ static final public char parseChar(byte what) { return (char) (what & 0xff); } static final public char parseChar(int what) { return (char) what; } /* static final public char parseChar(float what) { // nonsensical return (char) what; } static final public char[] parseChar(String what) { // note: array[] return what.toCharArray(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ? char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? 't' : 'f'; } return outgoing; } */ static final public char[] parseChar(byte what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) (what[i] & 0xff); } return outgoing; } static final public char[] parseChar(int what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } /* static final public char[] parseChar(float what[]) { // nonsensical char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } static final public char[][] parseChar(String what[]) { // note: array[][] char outgoing[][] = new char[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].toCharArray(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int parseInt(boolean what) { return what ? 1 : 0; } /** * Note that parseInt() will un-sign a signed byte value. */ static final public int parseInt(byte what) { return what & 0xff; } /** * Note that parseInt('5') is unlike String in the sense that it * won't return 5, but the ascii value. This is because ((int) someChar) * returns the ascii value, and parseInt() is just longhand for the cast. */ static final public int parseInt(char what) { return what; } /** * Same as floor(), or an (int) cast. */ static final public int parseInt(float what) { return (int) what; } /** * Parse a String into an int value. Returns 0 if the value is bad. */ static final public int parseInt(String what) { return parseInt(what, 0); } /** * Parse a String to an int, and provide an alternate value that * should be used when the number is invalid. */ static final public int parseInt(String what, int otherwise) { try { int offset = what.indexOf('.'); if (offset == -1) { return Integer.parseInt(what); } else { return Integer.parseInt(what.substring(0, offset)); } } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int[] parseInt(boolean what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i] ? 1 : 0; } return list; } static final public int[] parseInt(byte what[]) { // note this unsigns int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = (what[i] & 0xff); } return list; } static final public int[] parseInt(char what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i]; } return list; } static public int[] parseInt(float what[]) { int inties[] = new int[what.length]; for (int i = 0; i < what.length; i++) { inties[i] = (int)what[i]; } return inties; } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, it will be set to zero. * * String s[] = { "1", "300", "44" }; * int numbers[] = parseInt(s); * * numbers will contain { 1, 300, 44 } */ static public int[] parseInt(String what[]) { return parseInt(what, 0); } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, its entry in the * array will be set to the value of the "missing" parameter. * * String s[] = { "1", "300", "apple", "44" }; * int numbers[] = parseInt(s, 9999); * * numbers will contain { 1, 300, 9999, 44 } */ static public int[] parseInt(String what[], int missing) { int output[] = new int[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = Integer.parseInt(what[i]); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float parseFloat(boolean what) { return what ? 1 : 0; } */ /** * Convert an int to a float value. Also handles bytes because of * Java's rules for upgrading values. */ static final public float parseFloat(int what) { // also handles byte return what; } static final public float parseFloat(String what) { return parseFloat(what, Float.NaN); } static final public float parseFloat(String what, float otherwise) { try { return new Float(what).floatValue(); } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float[] parseFloat(boolean what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i] ? 1 : 0; } return floaties; } static final public float[] parseFloat(char what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = (char) what[i]; } return floaties; } */ static final public float[] parseByte(byte what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(int what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(String what[]) { return parseFloat(what, Float.NaN); } static final public float[] parseFloat(String what[], float missing) { float output[] = new float[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = new Float(what[i]).floatValue(); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String str(boolean x) { return String.valueOf(x); } static final public String str(byte x) { return String.valueOf(x); } static final public String str(char x) { return String.valueOf(x); } static final public String str(int x) { return String.valueOf(x); } static final public String str(float x) { return String.valueOf(x); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String[] str(boolean x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(byte x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(char x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(int x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(float x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } ////////////////////////////////////////////////////////////// // INT NUMBER FORMATTING /** * Integer number formatter. */ static private NumberFormat int_nf; static private int int_nf_digits; static private boolean int_nf_commas; static public String[] nf(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], digits); } return formatted; } /** * ( begin auto-generated from nf.xml ) * * Utility function for formatting numbers into strings. There are two * versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers.<br /><br />As shown in the above * example, <b>nf()</b> is used to add zeros to the left and/or right of a * number. This is typically for aligning a list of numbers. To * <em>remove</em> digits from a floating-point number, use the * <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b> * functions. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zero * @see PApplet#nfs(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) * @see PApplet#int(float) */ static public String nf(int num, int digits) { if ((int_nf != null) && (int_nf_digits == digits) && !int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(false); // no commas int_nf_commas = false; int_nf.setMinimumIntegerDigits(digits); int_nf_digits = digits; return int_nf.format(num); } /** * ( begin auto-generated from nfc.xml ) * * Utility function for formatting numbers into strings and placing * appropriate commas to mark units of 1000. There are two versions, one * for formatting ints and one for formatting an array of ints. The value * for the <b>digits</b> parameter should always be a positive integer. * <br/> <br/> * For a non-US locale, this will insert periods instead of commas, or * whatever is apprioriate for that region. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String[] nfc(int num[]) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i]); } return formatted; } /** * nfc() or "number format with commas". This is an unfortunate misnomer * because in locales where a comma is not the separator for numbers, it * won't actually be outputting a comma, it'll use whatever makes sense for * the locale. */ static public String nfc(int num) { if ((int_nf != null) && (int_nf_digits == 0) && int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(true); int_nf_commas = true; int_nf.setMinimumIntegerDigits(0); int_nf_digits = 0; return int_nf.format(num); } /** * number format signed (or space) * Formats a number but leaves a blank space in the front * when it's positive so that it can be properly aligned with * numbers that have a negative sign in front of them. */ /** * ( begin auto-generated from nfs.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but leaves a blank space in front of positive numbers so * they align with negative numbers in spite of the minus symbol. There are * two versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfs(int num, int digits) { return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits)); } static public String[] nfs(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], digits); } return formatted; } // /** * number format positive (or plus) * Formats a number, always placing a - or + sign * in the front when it's negative or positive. */ /** * ( begin auto-generated from nfp.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in * front of negative numbers. There are two versions, one for formatting * floats and one for formatting ints. The values for the <b>digits</b>, * <b>left</b>, and <b>right</b> parameters should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfp(int num, int digits) { return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits)); } static public String[] nfp(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], digits); } return formatted; } ////////////////////////////////////////////////////////////// // FLOAT NUMBER FORMATTING static private NumberFormat float_nf; static private int float_nf_left, float_nf_right; static private boolean float_nf_commas; static public String[] nf(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], left, right); } return formatted; } /** * @param num[] the number(s) to format * @param left number of digits to the left of the decimal point * @param right number of digits to the right of the decimal point */ static public String nf(float num, int left, int right) { if ((float_nf != null) && (float_nf_left == left) && (float_nf_right == right) && !float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(false); float_nf_commas = false; if (left != 0) float_nf.setMinimumIntegerDigits(left); if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = left; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param right number of digits to the right of the decimal point */ static public String[] nfc(float num[], int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i], right); } return formatted; } static public String nfc(float num, int right) { if ((float_nf != null) && (float_nf_left == 0) && (float_nf_right == right) && float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(true); float_nf_commas = true; if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = 0; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfs(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], left, right); } return formatted; } static public String nfs(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right)); } /** * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfp(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], left, right); } return formatted; } static public String nfp(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right)); } ////////////////////////////////////////////////////////////// // HEX/BINARY CONVERSION /** * ( begin auto-generated from hex.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent hexadecimal notation. For example color(0, 102, 153) will * convert to the String "FF006699". This function can help make your geeky * debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 8, because an int value can * only represent up to 32 bits. Specifying more than eight digits will * simply shorten the string to eight anyway. * * ( end auto-generated ) * @webref data:conversion * @param value the value to convert * @see PApplet#unhex(String) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public String hex(byte value) { return hex(value, 2); } static final public String hex(char value) { return hex(value, 4); } static final public String hex(int value) { return hex(value, 8); } /** * @param digits the number of digits (maximum 8) */ static final public String hex(int value, int digits) { String stuff = Integer.toHexString(value).toUpperCase(); if (digits > 8) { digits = 8; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { return "00000000".substring(8 - (digits-length)) + stuff; } return stuff; } /** * ( begin auto-generated from unhex.xml ) * * Converts a String representation of a hexadecimal number to its * equivalent integer value. * * ( end auto-generated ) * * @webref data:conversion * @param value String to convert to an integer * @see PApplet#hex(int, int) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public int unhex(String value) { // has to parse as a Long so that it'll work for numbers bigger than 2^31 return (int) (Long.parseLong(value, 16)); } // /** * Returns a String that contains the binary value of a byte. * The returned value will always have 8 digits. */ static final public String binary(byte value) { return binary(value, 8); } /** * Returns a String that contains the binary value of a char. * The returned value will always have 16 digits because chars * are two bytes long. */ static final public String binary(char value) { return binary(value, 16); } /** * Returns a String that contains the binary value of an int. The length * depends on the size of the number itself. If you want a specific number * of digits use binary(int what, int digits) to specify how many. */ static final public String binary(int value) { return binary(value, 32); } /* * Returns a String that contains the binary value of an int. * The digits parameter determines how many digits will be used. */ /** * ( begin auto-generated from binary.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent binary notation. For example color(0, 102, 153, 255) will * convert to the String "11111111000000000110011010011001". This function * can help make your geeky debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 32, because an int value can * only represent up to 32 bits. Specifying more than 32 digits will simply * shorten the string to 32 anyway. * * ( end auto-generated ) * @webref data:conversion * @param value value to convert * @param digits number of digits to return * @see PApplet#unbinary(String) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public String binary(int value, int digits) { String stuff = Integer.toBinaryString(value); if (digits > 32) { digits = 32; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { int offset = 32 - (digits-length); return "00000000000000000000000000000000".substring(offset) + stuff; } return stuff; } /** * ( begin auto-generated from unbinary.xml ) * * Converts a String representation of a binary number to its equivalent * integer value. For example, unbinary("00001000") will return 8. * * ( end auto-generated ) * @webref data:conversion * @param value String to convert to an integer * @see PApplet#binary(byte) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public int unbinary(String value) { return Integer.parseInt(value, 2); } ////////////////////////////////////////////////////////////// // COLOR FUNCTIONS // moved here so that they can work without // the graphics actually being instantiated (outside setup) /** * ( begin auto-generated from color.xml ) * * Creates colors for storing in variables of the <b>color</b> datatype. * The parameters are interpreted as RGB or HSB values depending on the * current <b>colorMode()</b>. The default mode is RGB values from 0 to 255 * and therefore, the function call <b>color(255, 204, 0)</b> will return a * bright yellow color. More about how colors are stored can be found in * the reference for the <a href="color_datatype.html">color</a> datatype. * * ( end auto-generated ) * @webref color:creating_reading * @param gray number specifying value between white and black * @see PApplet#colorMode(int) */ public final int color(int gray) { if (g == null) { if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(gray); } /** * @nowebref * @param fgray number specifying value between white and black */ public final int color(float fgray) { if (g == null) { int gray = (int) fgray; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray); } /** * As of 0116 this also takes color(#FF8800, alpha) * @param alpha relative to current color range */ public final int color(int gray, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (gray > 255) { // then assume this is actually a #FF8800 return (alpha << 24) | (gray & 0xFFFFFF); } else { //if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return (alpha << 24) | (gray << 16) | (gray << 8) | gray; } } return g.color(gray, alpha); } /** * @nowebref */ public final int color(float fgray, float falpha) { if (g == null) { int gray = (int) fgray; int alpha = (int) falpha; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray, falpha); } /** * @param v1 red or hue values relative to the current color range * @param v2 green or saturation values relative to the current color range * @param v3 blue or brightness values relative to the current color range */ public final int color(int v1, int v2, int v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3); } public final int color(int v1, int v2, int v3, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3, alpha); } public final int color(float v1, float v2, float v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3); } public final int color(float v1, float v2, float v3, float alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3, alpha); } static public int blendColor(int c1, int c2, int mode) { return PImage.blendColor(c1, c2, mode); } ////////////////////////////////////////////////////////////// // MAIN /** * Set this sketch to communicate its state back to the PDE. * <p/> * This uses the stderr stream to write positions of the window * (so that it will be saved by the PDE for the next run) and * notify on quit. See more notes in the Worker class. */ public void setupExternalMessages() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { Point where = ((Frame) e.getSource()).getLocation(); System.err.println(PApplet.EXTERNAL_MOVE + " " + where.x + " " + where.y); System.err.flush(); // doesn't seem to help or hurt } }); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // System.err.println(PApplet.EXTERNAL_QUIT); // System.err.flush(); // important // System.exit(0); exit(); // don't quit, need to just shut everything down (0133) } }); } /** * Set up a listener that will fire proper component resize events * in cases where frame.setResizable(true) is called. */ public void setupFrameResizeListener() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Ignore bad resize events fired during setup to fix // http://dev.processing.org/bugs/show_bug.cgi?id=341 // This should also fix the blank screen on Linux bug // http://dev.processing.org/bugs/show_bug.cgi?id=282 if (frame.isResizable()) { // might be multiple resize calls before visible (i.e. first // when pack() is called, then when it's resized for use). // ignore them because it's not the user resizing things. Frame farm = (Frame) e.getComponent(); if (farm.isVisible()) { Insets insets = farm.getInsets(); Dimension windowSize = farm.getSize(); // JFrame (unlike java.awt.Frame) doesn't include the left/top // insets for placement (though it does seem to need them for // overall size of the window. Perhaps JFrame sets its coord // system so that (0, 0) is always the upper-left of the content // area. Which seems nice, but breaks any f*ing AWT-based code. Rectangle newBounds = new Rectangle(0, 0, //insets.left, insets.top, windowSize.width - insets.left - insets.right, windowSize.height - insets.top - insets.bottom); Rectangle oldBounds = getBounds(); if (!newBounds.equals(oldBounds)) { // the ComponentListener in PApplet will handle calling size() setBounds(newBounds); revalidate(); // let the layout manager do its work } } } } }); } // /** // * GIF image of the Processing logo. // */ // static public final byte[] ICON_IMAGE = { // 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12, // 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117, // 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37, // 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16, // 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45, // 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100, // 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48, // -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25, // 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2, // 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62, // 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102, // 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59 // }; static ArrayList<Image> iconImages; protected void setIconImage(Frame frame) { // On OS X, this only affects what shows up in the dock when minimized. // So this is actually a step backwards. Brilliant. if (platform != MACOSX) { //Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); //frame.setIconImage(image); try { if (iconImages == null) { iconImages = new ArrayList<Image>(); final int[] sizes = { 16, 32, 48, 64 }; for (int sz : sizes) { URL url = getClass().getResource("/icon/icon-" + sz + ".png"); Image image = Toolkit.getDefaultToolkit().getImage(url); iconImages.add(image); //iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame)); } } frame.setIconImages(iconImages); } catch (Exception e) { //e.printStackTrace(); // more or less harmless; don't spew errors } } } // Not gonna do this dynamically, only on startup. Too much headache. // public void fullscreen() { // if (frame != null) { // if (PApplet.platform == MACOSX) { // japplemenubar.JAppleMenuBar.hide(); // } // GraphicsConfiguration gc = frame.getGraphicsConfiguration(); // Rectangle rect = gc.getBounds(); //// GraphicsDevice device = gc.getDevice(); // frame.setBounds(rect.x, rect.y, rect.width, rect.height); // } // } /** * main() method for running this class from the command line. * <p> * <B>The options shown here are not yet finalized and will be * changing over the next several releases.</B> * <p> * The simplest way to turn and applet into an application is to * add the following code to your program: * <PRE>static public void main(String args[]) { * PApplet.main("YourSketchName", args); * }</PRE> * This will properly launch your applet from a double-clickable * .jar or from the command line. * <PRE> * Parameters useful for launching or also used by the PDE: * * --location=x,y upper-lefthand corner of where the applet * should appear on screen. if not used, * the default is to center on the main screen. * * --full-screen put the applet into full screen "present" mode. * * --hide-stop use to hide the stop button in situations where * you don't want to allow users to exit. also * see the FAQ on information for capturing the ESC * key when running in presentation mode. * * --stop-color=#xxxxxx color of the 'stop' text used to quit an * sketch when it's in present mode. * * --bgcolor=#xxxxxx background color of the window. * * --sketch-path location of where to save files from functions * like saveStrings() or saveFrame(). defaults to * the folder that the java application was * launched from, which means if this isn't set by * the pde, everything goes into the same folder * as processing.exe. * * --display=n set what display should be used by this sketch. * displays are numbered starting from 0. * * Parameters used by Processing when running via the PDE * * --external set when the applet is being used by the PDE * * --editor-location=x,y position of the upper-lefthand corner of the * editor window, for placement of applet window * </PRE> */ static public void main(final String[] args) { runSketch(args, null); } /** * Convenience method so that PApplet.main("YourSketch") launches a sketch, * rather than having to wrap it into a String array. * @param mainClass name of the class to load (with package if any) */ static public void main(final String mainClass) { main(mainClass, null); } /** * Convenience method so that PApplet.main("YourSketch", args) launches a * sketch, rather than having to wrap it into a String array, and appending * the 'args' array when not null. * @param mainClass name of the class to load (with package if any) * @param args command line arguments to pass to the sketch */ static public void main(final String mainClass, final String[] passedArgs) { String[] args = new String[] { mainClass }; if (passedArgs != null) { args = concat(args, passedArgs); } runSketch(args, null); } static public void runSketch(final String args[], final PApplet constructedApplet) { // Disable abyssmally slow Sun renderer on OS X 10.5. if (platform == MACOSX) { // Only run this on OS X otherwise it can cause a permissions error. // http://dev.processing.org/bugs/show_bug.cgi?id=976 System.setProperty("apple.awt.graphics.UseQuartz", String.valueOf(useQuartz)); } // Doesn't seem to do much to help avoid flicker System.setProperty("sun.awt.noerasebackground", "true"); // This doesn't do anything. // if (platform == WINDOWS) { // // For now, disable the D3D renderer on Java 6u10 because // // it causes problems with Present mode. // // http://dev.processing.org/bugs/show_bug.cgi?id=1009 // System.setProperty("sun.java2d.d3d", "false"); // } if (args.length < 1) { System.err.println("Usage: PApplet <appletname>"); System.err.println("For additional options, " + "see the Javadoc for PApplet"); System.exit(1); } // EventQueue.invokeLater(new Runnable() { // public void run() { // runSketchEDT(args, constructedApplet); // } // }); // } // // // static public void runSketchEDT(final String args[], final PApplet constructedApplet) { boolean external = false; int[] location = null; int[] editorLocation = null; String name = null; boolean present = false; // boolean exclusive = false; // Color backgroundColor = Color.BLACK; Color backgroundColor = null; //Color.BLACK; Color stopColor = Color.GRAY; GraphicsDevice displayDevice = null; boolean hideStop = false; String param = null, value = null; // try to get the user folder. if running under java web start, // this may cause a security exception if the code is not signed. // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 String folder = null; try { folder = System.getProperty("user.dir"); } catch (Exception e) { } int argIndex = 0; while (argIndex < args.length) { int equals = args[argIndex].indexOf('='); if (equals != -1) { param = args[argIndex].substring(0, equals); value = args[argIndex].substring(equals + 1); if (param.equals(ARGS_EDITOR_LOCATION)) { external = true; editorLocation = parseInt(split(value, ',')); } else if (param.equals(ARGS_DISPLAY)) { int deviceIndex = Integer.parseInt(value); GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice devices[] = environment.getScreenDevices(); if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { displayDevice = devices[deviceIndex]; } else { System.err.println("Display " + value + " does not exist, " + "using the default display instead."); for (int i = 0; i < devices.length; i++) { System.err.println(i + " is " + devices[i]); } } } else if (param.equals(ARGS_BGCOLOR)) { if (value.charAt(0) == '#') value = value.substring(1); backgroundColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_STOP_COLOR)) { if (value.charAt(0) == '#') value = value.substring(1); stopColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_SKETCH_FOLDER)) { folder = value; } else if (param.equals(ARGS_LOCATION)) { location = parseInt(split(value, ',')); } } else { if (args[argIndex].equals(ARGS_PRESENT)) { // keep for compatability present = true; } else if (args[argIndex].equals(ARGS_FULL_SCREEN)) { present = true; // } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { // exclusive = true; } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { hideStop = true; } else if (args[argIndex].equals(ARGS_EXTERNAL)) { external = true; } else { name = args[argIndex]; break; // because of break, argIndex won't increment again } } argIndex++; } // Now that sketch path is passed in args after the sketch name // it's not set in the above loop(the above loop breaks after // finding sketch name). So setting sketch path here. for (int i = 0; i < args.length; i++) { if(args[i].startsWith(ARGS_SKETCH_FOLDER)){ folder = args[i].substring(args[i].indexOf('=') + 1); //System.err.println("SF set " + folder); } } // Set this property before getting into any GUI init code //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); // This )*)(*@#$ Apple crap don't work no matter where you put it // (static method of the class, at the top of main, wherever) if (displayDevice == null) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); displayDevice = environment.getDefaultScreenDevice(); } // Using a JFrame fixes a Windows problem with Present mode. This might // be our error, but usually this is the sort of crap we usually get from // OS X. It's time for a turnaround: Redmond is thinking different too! // https://github.com/processing/processing/issues/1955 Frame frame = new JFrame(displayDevice.getDefaultConfiguration()); // Default Processing gray, which will be replaced below if another // color is specified on the command line (i.e. in the prefs). final Color defaultGray = new Color(0xCC, 0xCC, 0xCC); ((JFrame) frame).getContentPane().setBackground(defaultGray); // Cannot call setResizable(false) until later due to OS X (issue #467) final PApplet applet; if (constructedApplet != null) { applet = constructedApplet; } else { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name); applet = (PApplet) c.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } // Set the trimmings around the image applet.setIconImage(frame); frame.setTitle(name); // frame.setIgnoreRepaint(true); // does nothing // frame.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); //// Rectangle bounds = c.getBounds(); // System.out.println(" " + c.getName() + " wants to be: " + c.getSize()); // } // }); // frame.addComponentListener(new ComponentListener() { // // public void componentShown(ComponentEvent e) { // debug("frame: " + e); // debug(" applet valid? " + applet.isValid()); //// ((PGraphicsJava2D) applet.g).redraw(); // } // // public void componentResized(ComponentEvent e) { // println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentResized() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentMoved(ComponentEvent e) { // //println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // //applet.g.setsi // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentMoved() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentHidden(ComponentEvent e) { // debug("frame: " + e); // } // }); // A handful of things that need to be set before init/start. applet.frame = frame; applet.sketchPath = folder; // If the applet doesn't call for full screen, but the command line does, // enable it. Conversely, if the command line does not, don't disable it. // applet.fullScreen |= present; // Query the applet to see if it wants to be full screen all the time. present |= applet.sketchFullScreen(); // pass everything after the class name in as args to the sketch itself // (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts) applet.args = PApplet.subset(args, argIndex + 1); applet.external = external; // Need to save the window bounds at full screen, // because pack() will cause the bounds to go to zero. // http://dev.processing.org/bugs/show_bug.cgi?id=923 Rectangle screenRect = displayDevice.getDefaultConfiguration().getBounds(); // DisplayMode doesn't work here, because we can't get the upper-left // corner of the display, which is important for multi-display setups. // Sketch has already requested to be the same as the screen's // width and height, so let's roll with full screen mode. if (screenRect.width == applet.sketchWidth() && screenRect.height == applet.sketchHeight()) { present = true; } // For 0149, moving this code (up to the pack() method) before init(). // For OpenGL (and perhaps other renderers in the future), a peer is // needed before a GLDrawable can be created. So pack() needs to be // called on the Frame before applet.init(), which itself calls size(), // and launches the Thread that will kick off setup(). // http://dev.processing.org/bugs/show_bug.cgi?id=891 // http://dev.processing.org/bugs/show_bug.cgi?id=908 if (present) { // if (platform == MACOSX) { // // Call some native code to remove the menu bar on OS X. Not necessary // // on Linux and Windows, who are happy to make full screen windows. // japplemenubar.JAppleMenuBar.hide(); // } // Tried to use this to fix the 'present' mode issue. // Did not help, and the screenRect setup seems to work fine. //frame.setExtendedState(Frame.MAXIMIZED_BOTH); frame.setUndecorated(true); if (backgroundColor != null) { ((JFrame) frame).getContentPane().setBackground(backgroundColor); } // if (exclusive) { // displayDevice.setFullScreenWindow(frame); // // this trashes the location of the window on os x // //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); // fullScreenRect = frame.getBounds(); // } else { frame.setBounds(screenRect); frame.setVisible(true); // } } frame.setLayout(null); frame.add(applet); if (present) { frame.invalidate(); } else { frame.pack(); } // insufficient, places the 100x100 sketches offset strangely //frame.validate(); // disabling resize has to happen after pack() to avoid apparent Apple bug // http://code.google.com/p/processing/issues/detail?id=467 frame.setResizable(false); applet.init(); // applet.start(); // Wait until the applet has figured out its width. // In a static mode app, this will be after setup() has completed, // and the empty draw() has set "finished" to true. // TODO make sure this won't hang if the applet has an exception. while (applet.defaultSize && !applet.finished) { //System.out.println("default size"); try { Thread.sleep(5); } catch (InterruptedException e) { //System.out.println("interrupt"); } } // // If 'present' wasn't already set, but the applet initializes // // to full screen, attempt to make things full screen anyway. // if (!present && // applet.width == screenRect.width && // applet.height == screenRect.height) { // // bounds will be set below, but can't change to setUndecorated() now // present = true; // } // // Opting not to do this, because we can't remove the decorations on the // // window at this point. And re-opening a new winodw is a lot of mess. // // Better all around to just encourage the use of sketchFullScreen() // // or cmd/ctrl-shift-R in the PDE. if (present) { if (platform == MACOSX) { // Call some native code to remove the menu bar on OS X. Not necessary // on Linux and Windows, who are happy to make full screen windows. japplemenubar.JAppleMenuBar.hide(); } // After the pack(), the screen bounds are gonna be 0s frame.setBounds(screenRect); applet.setBounds((screenRect.width - applet.width) / 2, (screenRect.height - applet.height) / 2, applet.width, applet.height); if (!hideStop) { Label label = new Label("stop"); label.setForeground(stopColor); label.addMouseListener(new MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { System.exit(0); } }); frame.add(label); Dimension labelSize = label.getPreferredSize(); // sometimes shows up truncated on mac //System.out.println("label width is " + labelSize.width); labelSize = new Dimension(100, labelSize.height); label.setSize(labelSize); label.setLocation(20, screenRect.height - labelSize.height - 20); } // not always running externally when in present mode if (external) { applet.setupExternalMessages(); } } else { // if not presenting // can't do pack earlier cuz present mode don't like it // (can't go full screen with a frame after calling pack) // frame.pack(); // get insets. get more. Insets insets = frame.getInsets(); int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; int contentW = Math.max(applet.width, MIN_WINDOW_WIDTH); int contentH = Math.max(applet.height, MIN_WINDOW_HEIGHT); frame.setSize(windowW, windowH); if (location != null) { // a specific location was received from the Runner // (applet has been run more than once, user placed window) frame.setLocation(location[0], location[1]); } else if (external && editorLocation != null) { int locationX = editorLocation[0] - 20; int locationY = editorLocation[1]; if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // doesn't fit // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = editorLocation[0] + 66; locationY = editorLocation[1] + 66; if ((locationX + windowW > applet.displayWidth - 33) || (locationY + windowH > applet.displayHeight - 33)) { // otherwise center on screen locationX = (applet.displayWidth - windowW) / 2; locationY = (applet.displayHeight - windowH) / 2; } frame.setLocation(locationX, locationY); } } else { // just center on screen // Can't use frame.setLocationRelativeTo(null) because it sends the // frame to the main display, which undermines the --display setting. frame.setLocation(screenRect.x + (screenRect.width - applet.width) / 2, screenRect.y + (screenRect.height - applet.height) / 2); } Point frameLoc = frame.getLocation(); if (frameLoc.y < 0) { // Windows actually allows you to place frames where they can't be // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 frame.setLocation(frameLoc.x, 30); } if (backgroundColor != null) { // if (backgroundColor == Color.black) { //BLACK) { // // this means no bg color unless specified // backgroundColor = SystemColor.control; // } ((JFrame) frame).getContentPane().setBackground(backgroundColor); } // int usableWindowH = windowH - insets.top - insets.bottom; // applet.setBounds((windowW - applet.width)/2, // insets.top + (usableWindowH - applet.height)/2, // applet.width, applet.height); applet.setBounds((contentW - applet.width)/2, (contentH - applet.height)/2, applet.width, applet.height); if (external) { applet.setupExternalMessages(); } else { // !external frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); } // handle frame resizing events applet.setupFrameResizeListener(); // all set for rockin if (applet.displayable()) { frame.setVisible(true); // Linux doesn't deal with insets the same way. We get fake insets // earlier, and then the window manager will slap its own insets // onto things once the frame is realized on the screen. Awzm. if (platform == LINUX) { Insets irlInsets = frame.getInsets(); if (!irlInsets.equals(insets)) { insets = irlInsets; windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; frame.setSize(windowW, windowH); } } } } // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // (Although this doesn't seem to be the one that was causing problems.) //applet.requestFocus(); // ask for keydowns } /** * These methods provide a means for running an already-constructed * sketch. In particular, it makes it easy to launch a sketch in * Jython: * * <pre>class MySketch(PApplet): * pass * *MySketch().runSketch();</pre> */ protected void runSketch(final String[] args) { final String[] argsWithSketchName = new String[args.length + 1]; System.arraycopy(args, 0, argsWithSketchName, 0, args.length); final String className = this.getClass().getSimpleName(); final String cleanedClass = className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); argsWithSketchName[args.length] = cleanedClass; runSketch(argsWithSketchName, this); } protected void runSketch() { runSketch(new String[0]); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from beginRecord.xml ) * * Opens a new file and all subsequent drawing functions are echoed to this * file as well as the display window. The <b>beginRecord()</b> function * requires two parameters, the first is the renderer and the second is the * file name. This function is always used with <b>endRecord()</b> to stop * the recording process and close the file. * <br /> <br /> * Note that beginRecord() will only pick up any settings that happen after * it has been called. For instance, if you call textFont() before * beginRecord(), then that font will not be set for the file that you're * recording to. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF * @param filename filename for output * @see PApplet#endRecord() */ public PGraphics beginRecord(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); beginRecord(rec); return rec; } /** * @nowebref * Begin recording (echoing) commands to the specified PGraphics object. */ public void beginRecord(PGraphics recorder) { this.recorder = recorder; recorder.beginDraw(); } /** * ( begin auto-generated from endRecord.xml ) * * Stops the recording process started by <b>beginRecord()</b> and closes * the file. * * ( end auto-generated ) * @webref output:files * @see PApplet#beginRecord(String, String) */ public void endRecord() { if (recorder != null) { recorder.endDraw(); recorder.dispose(); recorder = null; } } /** * ( begin auto-generated from beginRaw.xml ) * * To create vectors from 3D data, use the <b>beginRaw()</b> and * <b>endRaw()</b> commands. These commands will grab the shape data just * before it is rendered to the screen. At this stage, your entire scene is * nothing but a long list of individual lines and triangles. This means * that a shape created with <b>sphere()</b> function will be made up of * hundreds of triangles, rather than a single object. Or that a * multi-segment line shape (such as a curve) will be rendered as * individual segments. * <br /><br /> * When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write * to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the * PDF library will write the geometry as flattened triangles and lines, * even if recording from the <b>P3D</b> renderer. * <br /><br /> * If you want a background to show up in your files, use <b>rect(0, 0, * width, height)</b> after setting the <b>fill()</b> to the background * color. Otherwise the background will not be rendered to the file because * the background is not shape. * <br /><br /> * Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D * geometry drawn to 2D file formats. See the <b>hint()</b> reference for * more details. * <br /><br /> * See examples in the reference for the <b>PDF</b> and <b>DXF</b> * libraries for more information. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF or DXF * @param filename filename for output * @see PApplet#endRaw() * @see PApplet#hint(int) */ public PGraphics beginRaw(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); g.beginRaw(rec); return rec; } /** * @nowebref * Begin recording raw shape data to the specified renderer. * * This simply echoes to g.beginRaw(), but since is placed here (rather than * generated by preproc.pl) for clarity and so that it doesn't echo the * command should beginRecord() be in use. * * @param rawGraphics ??? */ public void beginRaw(PGraphics rawGraphics) { g.beginRaw(rawGraphics); } /** * ( begin auto-generated from endRaw.xml ) * * Complement to <b>beginRaw()</b>; they must always be used together. See * the <b>beginRaw()</b> reference for details. * * ( end auto-generated ) * * @webref output:files * @see PApplet#beginRaw(String, String) */ public void endRaw() { g.endRaw(); } /** * Starts shape recording and returns the PShape object that will * contain the geometry. */ /* public PShape beginRecord() { return g.beginRecord(); } */ ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from loadPixels.xml ) * * Loads the pixel data for the display window into the <b>pixels[]</b> * array. This function must always be called before reading from or * writing to <b>pixels[]</b>. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * * ( end auto-generated ) * <h3>Advanced</h3> * Override the g.pixels[] function to set the pixels[] array * that's part of the PApplet object. Allows the use of * pixels[] in the code, rather than g.pixels[]. * * @webref image:pixels * @see PApplet#pixels * @see PApplet#updatePixels() */ public void loadPixels() { g.loadPixels(); pixels = g.pixels; } /** * ( begin auto-generated from updatePixels.xml ) * * Updates the display window with the data in the <b>pixels[]</b> array. * Use in conjunction with <b>loadPixels()</b>. If you're only reading * pixels from the array, there's no need to call <b>updatePixels()</b> * unless there are changes. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * <br/> <br/> * Currently, none of the renderers use the additional parameters to * <b>updatePixels()</b>, however this may be implemented in the future. * * ( end auto-generated ) * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#pixels */ public void updatePixels() { g.updatePixels(); } /** * @nowebref * @param x1 x-coordinate of the upper-left corner * @param y1 y-coordinate of the upper-left corner * @param x2 width of the region * @param y2 height of the region */ public void updatePixels(int x1, int y1, int x2, int y2) { g.updatePixels(x1, y1, x2, y2); } ////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! // This includes the Javadoc comments, which are automatically copied from // the PImage and PGraphics source code files. // public functions for processing.core /** * Store data of some kind for the renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. * @param renderer The PGraphics renderer associated to the image * @param storage The metadata required by the renderer */ public void setCache(PImage image, Object storage) { if (recorder != null) recorder.setCache(image, storage); g.setCache(image, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param renderer The PGraphics renderer associated to the image * @return metadata stored for the specified renderer */ public Object getCache(PImage image) { return g.getCache(image); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose cache data should be removed */ public void removeCache(PImage image) { if (recorder != null) recorder.removeCache(image); g.removeCache(image); } public PGL beginPGL() { return g.beginPGL(); } public void endPGL() { if (recorder != null) recorder.endPGL(); g.endPGL(); } public void flush() { if (recorder != null) recorder.flush(); g.flush(); } public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } /** * Start a new shape of type POLYGON */ public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } /** * ( begin auto-generated from beginShape.xml ) * * Using the <b>beginShape()</b> and <b>endShape()</b> functions allow * creating more complex forms. <b>beginShape()</b> begins recording * vertices for a shape and <b>endShape()</b> stops recording. The value of * the <b>MODE</b> parameter tells it which types of shapes to create from * the provided vertices. With no mode specified, the shape can be any * irregular polygon. The parameters available for beginShape() are POINTS, * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. * After calling the <b>beginShape()</b> function, a series of * <b>vertex()</b> commands must follow. To stop drawing the shape, call * <b>endShape()</b>. The <b>vertex()</b> function with two parameters * specifies a position in 2D and the <b>vertex()</b> function with three * parameters specifies a position in 3D. Each shape will be outlined with * the current stroke color and filled with the fill color. * <br/> <br/> * Transformations such as <b>translate()</b>, <b>rotate()</b>, and * <b>scale()</b> do not work within <b>beginShape()</b>. It is also not * possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b> * within <b>beginShape()</b>. * <br/> <br/> * The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b> * settings to be altered per-vertex, however the default P2D renderer does * not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and * <b>strokeJoin()</b> cannot be changed while inside a * <b>beginShape()</b>/<b>endShape()</b> block with any renderer. * * ( end auto-generated ) * @webref shape:vertex * @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP * @see PShape * @see PGraphics#endShape() * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) */ public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } /** * Sets whether the upcoming vertex is part of an edge. * Equivalent to glEdgeFlag(), for people familiar with OpenGL. */ public void edge(boolean edge) { if (recorder != null) recorder.edge(edge); g.edge(edge); } /** * ( begin auto-generated from normal.xml ) * * Sets the current normal vector. This is for drawing three dimensional * shapes and surfaces and specifies a vector perpendicular to the surface * of the shape which determines how lighting affects it. Processing * attempts to automatically assign normals to shapes, but since that's * imperfect, this is a better option when you want more control. This * function is identical to glNormal3f() in OpenGL. * * ( end auto-generated ) * @webref lights_camera:lights * @param nx x direction * @param ny y direction * @param nz z direction * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#lights() */ public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } /** * ( begin auto-generated from textureMode.xml ) * * Sets the coordinate space for texture mapping. There are two options, * IMAGE, which refers to the actual coordinates of the image, and * NORMAL, which refers to a normalized space of values ranging from 0 * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200 * pixels, mapping the image onto the entire size of a quad would require * the points (0,0) (0,100) (100,200) (0,200). The same mapping in * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). * * ( end auto-generated ) * @webref image:textures * @param mode either IMAGE or NORMAL * @see PGraphics#texture(PImage) * @see PGraphics#textureWrap(int) */ public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } /** * ( begin auto-generated from textureWrap.xml ) * * Description to come... * * ( end auto-generated from textureWrap.xml ) * * @webref image:textures * @param wrap Either CLAMP (default) or REPEAT * @see PGraphics#texture(PImage) * @see PGraphics#textureMode(int) */ public void textureWrap(int wrap) { if (recorder != null) recorder.textureWrap(wrap); g.textureWrap(wrap); } /** * ( begin auto-generated from texture.xml ) * * Sets a texture to be applied to vertex points. The <b>texture()</b> * function must be called between <b>beginShape()</b> and * <b>endShape()</b> and before any calls to <b>vertex()</b>. * <br/> <br/> * When textures are in use, the fill color is ignored. Instead, use tint() * to specify the color of the texture as it is applied to the shape. * * ( end auto-generated ) * @webref image:textures * @param image reference to a PImage object * @see PGraphics#textureMode(int) * @see PGraphics#textureWrap(int) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) */ public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } /** * Removes texture image for current shape. * Needs to be called between beginShape and endShape * */ public void noTexture() { if (recorder != null) recorder.noTexture(); g.noTexture(); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } /** * Used by renderer subclasses or PShape to efficiently pass in already * formatted vertex information. * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT */ public void vertex(float[] v) { if (recorder != null) recorder.vertex(v); g.vertex(v); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } /** * ( begin auto-generated from vertex.xml ) * * All shapes are constructed by connecting a series of vertices. * <b>vertex()</b> is used to specify the vertex coordinates for points, * lines, triangles, quads, and polygons and is used exclusively within the * <b>beginShape()</b> and <b>endShape()</b> function.<br /> * <br /> * Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D * parameter in combination with size as shown in the above example.<br /> * <br /> * This function is also used to map a texture onto the geometry. The * <b>texture()</b> function declares the texture to apply to the geometry * and the <b>u</b> and <b>v</b> coordinates set define the mapping of this * texture to the form. By default, the coordinates used for <b>u</b> and * <b>v</b> are specified in relation to the image's size in pixels, but * this relation can be changed with <b>textureMode()</b>. * * ( end auto-generated ) * @webref shape:vertex * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex * @param z z-coordinate of the vertex * @param u horizontal coordinate for the texture mapping * @param v vertical coordinate for the texture mapping * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#texture(PImage) */ public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } /** * @webref shape:vertex */ public void beginContour() { if (recorder != null) recorder.beginContour(); g.beginContour(); } /** * @webref shape:vertex */ public void endContour() { if (recorder != null) recorder.endContour(); g.endContour(); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } /** * ( begin auto-generated from endShape.xml ) * * The <b>endShape()</b> function is the companion to <b>beginShape()</b> * and may only be called after <b>beginShape()</b>. When <b>endshape()</b> * is called, all of image data defined since the previous call to * <b>beginShape()</b> is written into the image buffer. The constant CLOSE * as the value for the MODE parameter to close the shape (to connect the * beginning and the end). * * ( end auto-generated ) * @webref shape:vertex * @param mode use CLOSE to close the shape * @see PShape * @see PGraphics#beginShape(int) */ public void endShape(int mode) { if (recorder != null) recorder.endShape(mode); g.endShape(mode); } /** * @webref shape * @param filename name of file to load, can be .svg or .obj * @see PShape * @see PApplet#createShape() */ public PShape loadShape(String filename) { return g.loadShape(filename); } public PShape loadShape(String filename, String options) { return g.loadShape(filename, options); } /** * @webref shape * @see PShape * @see PShape#endShape() * @see PApplet#loadShape(String) */ public PShape createShape() { return g.createShape(); } public PShape createShape(PShape source) { return g.createShape(source); } /** * @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP */ public PShape createShape(int type) { return g.createShape(type); } /** * @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX * @param p parameters that match the kind of shape */ public PShape createShape(int kind, float... p) { return g.createShape(kind, p); } /** * ( begin auto-generated from loadShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param fragFilename name of fragment shader file */ public PShader loadShader(String fragFilename) { return g.loadShader(fragFilename); } /** * @param vertFilename name of vertex shader file */ public PShader loadShader(String fragFilename, String vertFilename) { return g.loadShader(fragFilename, vertFilename); } /** * ( begin auto-generated from shader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param shader name of shader file */ public void shader(PShader shader) { if (recorder != null) recorder.shader(shader); g.shader(shader); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void shader(PShader shader, int kind) { if (recorder != null) recorder.shader(shader, kind); g.shader(shader, kind); } /** * ( begin auto-generated from resetShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders */ public void resetShader() { if (recorder != null) recorder.resetShader(); g.resetShader(); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void resetShader(int kind) { if (recorder != null) recorder.resetShader(kind); g.resetShader(kind); } /** * @param shader the fragment shader to apply */ public void filter(PShader shader) { if (recorder != null) recorder.filter(shader); g.filter(shader); } /* * @webref rendering:shaders * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default */ public void clip(float a, float b, float c, float d) { if (recorder != null) recorder.clip(a, b, c, d); g.clip(a, b, c, d); } /* * @webref rendering:shaders */ public void noClip() { if (recorder != null) recorder.noClip(); g.noClip(); } /** * ( begin auto-generated from blendMode.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref Rendering * @param mode the blending mode to use */ public void blendMode(int mode) { if (recorder != null) recorder.blendMode(mode); g.blendMode(mode); } public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); g.bezierVertex(x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezierVertex.xml ) * * Specifies vertex coordinates for Bezier curves. Each call to * <b>bezierVertex()</b> defines the position of two control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time <b>bezierVertex()</b> is used within a * <b>beginShape()</b> call, it must be prefaced with a call to * <b>vertex()</b> to set the first anchor point. This function must be * used between <b>beginShape()</b> and <b>endShape()</b> and only when * there is no MODE parameter specified to <b>beginShape()</b>. Using the * 3D version requires rendering with P3D (see the Environment reference * for more information). * * ( end auto-generated ) * @webref shape:vertex * @param x2 the x-coordinate of the 1st control point * @param y2 the y-coordinate of the 1st control point * @param z2 the z-coordinate of the 1st control point * @param x3 the x-coordinate of the 2nd control point * @param y3 the y-coordinate of the 2nd control point * @param z3 the z-coordinate of the 2nd control point * @param x4 the x-coordinate of the anchor point * @param y4 the y-coordinate of the anchor point * @param z4 the z-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * @webref shape:vertex * @param cx the x-coordinate of the control point * @param cy the y-coordinate of the control point * @param x3 the x-coordinate of the anchor point * @param y3 the y-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void quadraticVertex(float cx, float cy, float x3, float y3) { if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3); g.quadraticVertex(cx, cy, x3, y3); } /** * @param cz the z-coordinate of the control point * @param z3 the z-coordinate of the anchor point */ public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3); g.quadraticVertex(cx, cy, cz, x3, y3, z3); } /** * ( begin auto-generated from curveVertex.xml ) * * Specifies vertex coordinates for curves. This function may only be used * between <b>beginShape()</b> and <b>endShape()</b> and only when there is * no MODE parameter specified to <b>beginShape()</b>. The first and last * points in a series of <b>curveVertex()</b> lines will be used to guide * the beginning and end of a the curve. A minimum of four points is * required to draw a tiny curve between the second and third points. * Adding a fifth point with <b>curveVertex()</b> will draw the curve * between the second, third, and fourth points. The <b>curveVertex()</b> * function is an implementation of Catmull-Rom splines. Using the 3D * version requires rendering with P3D (see the Environment reference for * more information). * * ( end auto-generated ) * * @webref shape:vertex * @param x the x-coordinate of the vertex * @param y the y-coordinate of the vertex * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) */ public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } /** * @param z the z-coordinate of the vertex */ public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } /** * ( begin auto-generated from point.xml ) * * Draws a point, a coordinate in space at the dimension of one pixel. The * first parameter is the horizontal value for the point, the second value * is the vertical value for the point, and the optional third value is the * depth value. Drawing this shape in 3D with the <b>z</b> parameter * requires the P3D parameter in combination with <b>size()</b> as shown in * the above example. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param x x-coordinate of the point * @param y y-coordinate of the point */ public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } /** * @param z z-coordinate of the point */ public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } /** * ( begin auto-generated from line.xml ) * * Draws a line (a direct path between two points) to the screen. The * version of <b>line()</b> with four parameters draws the line in 2D. To * color a line, use the <b>stroke()</b> function. A line cannot be filled, * therefore the <b>fill()</b> function will not affect the color of a * line. 2D lines are drawn with a width of one pixel by default, but this * can be changed with the <b>strokeWeight()</b> function. The version with * six parameters allows the line to be placed anywhere within XYZ space. * Drawing this shape in 3D with the <b>z</b> parameter requires the P3D * parameter in combination with <b>size()</b> as shown in the above example. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) * @see PGraphics#beginShape() */ public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } /** * @param z1 z-coordinate of the first point * @param z2 z-coordinate of the second point */ public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } /** * ( begin auto-generated from triangle.xml ) * * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param x3 x-coordinate of the third point * @param y3 y-coordinate of the third point * @see PApplet#beginShape() */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } /** * ( begin auto-generated from quad.xml ) * * A quad is a quadrilateral, a four sided polygon. It is similar to a * rectangle, but the angles between its edges are not constrained to * ninety degrees. The first pair of parameters (x1,y1) sets the first * vertex and the subsequent pairs should proceed clockwise or * counter-clockwise around the defined shape. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first corner * @param y1 y-coordinate of the first corner * @param x2 x-coordinate of the second corner * @param y2 y-coordinate of the second corner * @param x3 x-coordinate of the third corner * @param y3 y-coordinate of the third corner * @param x4 x-coordinate of the fourth corner * @param y4 y-coordinate of the fourth corner */ public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from rectMode.xml ) * * Modifies the location from which rectangles draw. The default mode is * <b>rectMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>rect()</b> to specify the width and height. The syntax * <b>rectMode(CORNERS)</b> uses the first and second parameters of * <b>rect()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>rectMode(CENTER)</b> draws the image from its center point and uses * the third and forth parameters of <b>rect()</b> to specify the image's * width and height. The syntax <b>rectMode(RADIUS)</b> draws the image * from its center point and uses the third and forth parameters of * <b>rect()</b> to specify half of the image's width and height. The * parameter must be written in ALL CAPS because Processing is a case * sensitive language. Note: In version 125, the mode named CENTER_RADIUS * was shortened to RADIUS. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CORNER, CORNERS, CENTER, or RADIUS * @see PGraphics#rect(float, float, float, float) */ public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } /** * ( begin auto-generated from rect.xml ) * * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. These parameters may be changed with the * <b>rectMode()</b> function. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default * @see PGraphics#rectMode(int) * @see PGraphics#quad(float, float, float, float, float, float, float, float) */ public void rect(float a, float b, float c, float d) { if (recorder != null) recorder.rect(a, b, c, d); g.rect(a, b, c, d); } /** * @param r radii for all four corners */ public void rect(float a, float b, float c, float d, float r) { if (recorder != null) recorder.rect(a, b, c, d, r); g.rect(a, b, c, d, r); } /** * @param tl radius for top-left corner * @param tr radius for top-right corner * @param br radius for bottom-right corner * @param bl radius for bottom-left corner */ public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl); g.rect(a, b, c, d, tl, tr, br, bl); } /** * ( begin auto-generated from ellipseMode.xml ) * * The origin of the ellipse is modified by the <b>ellipseMode()</b> * function. The default configuration is <b>ellipseMode(CENTER)</b>, which * specifies the location of the ellipse as the center of the shape. The * <b>RADIUS</b> mode is the same, but the width and height parameters to * <b>ellipse()</b> specify the radius of the ellipse, rather than the * diameter. The <b>CORNER</b> mode draws the shape from the upper-left * corner of its bounding box. The <b>CORNERS</b> mode uses the four * parameters to <b>ellipse()</b> to set two opposing corners of the * ellipse's bounding box. The parameter must be written in ALL CAPS * because Processing is a case-sensitive language. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CENTER, RADIUS, CORNER, or CORNERS * @see PApplet#ellipse(float, float, float, float) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } /** * ( begin auto-generated from ellipse.xml ) * * Draws an ellipse (oval) in the display window. An ellipse with an equal * <b>width</b> and <b>height</b> is a circle. The first two parameters set * the location, the third sets the width, and the fourth sets the height. * The origin may be changed with the <b>ellipseMode()</b> function. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the ellipse * @param b y-coordinate of the ellipse * @param c width of the ellipse by default * @param d height of the ellipse by default * @see PApplet#ellipseMode(int) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } public void ellipse(Projectable2D p, float c, float d) { if (recorder != null) recorder.ellipse(p.x(), p.y(), c, d); g.ellipse(p.x(), p.y(), c, d); } /** * ( begin auto-generated from arc.xml ) * * Draws an arc in the display window. Arcs are drawn along the outer edge * of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and * <b>height</b> parameters. The origin or the arc's ellipse may be changed * with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b> * parameters specify the angles at which to draw the arc. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the arc's ellipse * @param b y-coordinate of the arc's ellipse * @param c width of the arc's ellipse by default * @param d height of the arc's ellipse by default * @param start angle to start the arc, specified in radians * @param stop angle to stop the arc, specified in radians * @see PApplet#ellipse(float, float, float, float) * @see PApplet#ellipseMode(int) * @see PApplet#radians(float) * @see PApplet#degrees(float) */ public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } /* * @param mode either OPEN, CHORD, or PIE */ public void arc(float a, float b, float c, float d, float start, float stop, int mode) { if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode); g.arc(a, b, c, d, start, stop, mode); } /** * ( begin auto-generated from box.xml ) * * A box is an extruded rectangle. A box with equal dimension on all sides * is a cube. * * ( end auto-generated ) * * @webref shape:3d_primitives * @param size dimension of the box in all dimensions (creates a cube) * @see PGraphics#sphere(float) */ public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } /** * @param w dimension of the box in the x-dimension * @param h dimension of the box in the y-dimension * @param d dimension of the box in the z-dimension */ public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } /** * ( begin auto-generated from sphereDetail.xml ) * * Controls the detail used to render a sphere by adjusting the number of * vertices of the sphere mesh. The default resolution is 30, which creates * a fairly detailed sphere definition with vertices every 360/30 = 12 * degrees. If you're going to render a great number of spheres per frame, * it is advised to reduce the level of detail using this function. The * setting stays active until <b>sphereDetail()</b> is called again with a * new parameter and so should <i>not</i> be called prior to every * <b>sphere()</b> statement, unless you wish to render spheres with * different settings, e.g. using less detail for smaller spheres or ones * further away from the camera. To control the detail of the horizontal * and vertical resolution independently, use the version of the functions * with two parameters. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code for sphereDetail() submitted by toxi [031031]. * Code for enhanced u/v version from davbol [080801]. * * @param res number of segments (minimum 3) used per full circle revolution * @webref shape:3d_primitives * @see PGraphics#sphere(float) */ public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } /** * @param ures number of segments used longitudinally per full circle revolutoin * @param vres number of segments used latitudinally from top to bottom */ public void sphereDetail(int ures, int vres) { if (recorder != null) recorder.sphereDetail(ures, vres); g.sphereDetail(ures, vres); } /** * ( begin auto-generated from sphere.xml ) * * A sphere is a hollow ball made from tessellated triangles. * * ( end auto-generated ) * * <h3>Advanced</h3> * <P> * Implementation notes: * <P> * cache all the points of the sphere in a static array * top and bottom are just a bunch of triangles that land * in the center point * <P> * sphere is a series of concentric circles who radii vary * along the shape, based on, er.. cos or something * <PRE> * [toxi 031031] new sphere code. removed all multiplies with * radius, as scale() will take care of that anyway * * [toxi 031223] updated sphere code (removed modulos) * and introduced sphereAt(x,y,z,r) * to avoid additional translate()'s on the user/sketch side * * [davbol 080801] now using separate sphereDetailU/V * </PRE> * * @webref shape:3d_primitives * @param r the radius of the sphere * @see PGraphics#sphereDetail(int) */ public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } /** * ( begin auto-generated from bezierPoint.xml ) * * Evaluates the Bezier at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a bezier curve * at t. * * ( end auto-generated ) * * <h3>Advanced</h3> * For instance, to convert the following example:<PRE> * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * * // draw it in gray, using 10 steps instead of the default 20 * // this is a slower way to do it, but useful if you need * // to do things with the coordinates at each step * stroke(128); * beginShape(LINE_STRIP); * for (int i = 0; i <= 10; i++) { * float t = i / 10.0f; * float x = bezierPoint(85, 10, 90, 15, t); * float y = bezierPoint(20, 10, 90, 80, t); * vertex(x, y); * } * endShape();</PRE> * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } /** * ( begin auto-generated from bezierTangent.xml ) * * Calculates the tangent of a point on a Bezier curve. There is a good * definition of <a href="http://en.wikipedia.org/wiki/Tangent" * target="new"><em>tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code submitted by Dave Bollinger (davol) for release 0136. * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } /** * ( begin auto-generated from bezierDetail.xml ) * * Sets the resolution at which Beziers display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#curveTightness(float) */ public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezier.xml ) * * Draws a Bezier curve on the screen. These curves are defined by a series * of anchor and control points. The first two parameters specify the first * anchor point and the last two parameters specify the other anchor point. * The middle parameters specify the control points which define the shape * of the curve. Bezier curves were developed by French engineer Pierre * Bezier. Using the 3D version requires rendering with P3D (see the * Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * Draw a cubic bezier curve. The first and last points are * the on-curve points. The middle two are the 'control' points, * or 'handles' in an application like Illustrator. * <P> * Identical to typing: * <PRE>beginShape(); * vertex(x1, y1); * bezierVertex(x2, y2, x3, y3, x4, y4); * endShape(); * </PRE> * In Postscript-speak, this would be: * <PRE>moveto(x1, y1); * curveto(x2, y2, x3, y3, x4, y4);</PRE> * If you were to try and continue that curve like so: * <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE> * This would be done in processing by adding these statements: * <PRE>bezierVertex(x5, y5, x6, y6, x7, y7) * </PRE> * To draw a quadratic (instead of cubic) curve, * use the control point twice by doubling it: * <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE> * * @webref shape:curves * @param x1 coordinates for the first anchor point * @param y1 coordinates for the first anchor point * @param z1 coordinates for the first anchor point * @param x2 coordinates for the first control point * @param y2 coordinates for the first control point * @param z2 coordinates for the first control point * @param x3 coordinates for the second control point * @param y3 coordinates for the second control point * @param z3 coordinates for the second control point * @param x4 coordinates for the second anchor point * @param y4 coordinates for the second anchor point * @param z4 coordinates for the second anchor point * * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from curvePoint.xml ) * * Evalutes the curve at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a curve at t. * * ( end auto-generated ) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of second point on the curve * @param c coordinate of third point on the curve * @param d coordinate of fourth point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } /** * ( begin auto-generated from curveTangent.xml ) * * Calculates the tangent of a point on a curve. There's a good definition * of <em><a href="http://en.wikipedia.org/wiki/Tangent" * target="new">tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code thanks to Dave Bollinger (Bug #715) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierTangent(float, float, float, float, float) */ public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } /** * ( begin auto-generated from curveDetail.xml ) * * Sets the resolution at which curves display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) */ public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } /** * ( begin auto-generated from curveTightness.xml ) * * Modifies the quality of forms created with <b>curve()</b> and * <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the * curve fits to the vertex points. The value 0.0 is the default value for * <b>squishy</b> (this value defines the curves to be Catmull-Rom splines) * and the value 1.0 connects all the points with straight lines. Values * within the range -5.0 and 5.0 will deform the curves but will leave them * recognizable and as values increase in magnitude, they will continue to deform. * * ( end auto-generated ) * * @webref shape:curves * @param tightness amount of deformation from the original vertices * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) */ public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } /** * ( begin auto-generated from curve.xml ) * * Draws a curved line on the screen. The first and second parameters * specify the beginning control point and the last two parameters specify * the ending control point. The middle parameters specify the start and * stop of the curve. Longer curves can be created by putting a series of * <b>curve()</b> functions together or using <b>curveVertex()</b>. An * additional function called <b>curveTightness()</b> provides control for * the visual quality of the curve. The <b>curve()</b> function is an * implementation of Catmull-Rom splines. Using the 3D version requires * rendering with P3D (see the Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * As of revision 0070, this function no longer doubles the first * and last points. The curves are a bit more boring, but it's more * mathematically correct, and properly mirrored in curvePoint(). * <P> * Identical to typing out:<PRE> * beginShape(); * curveVertex(x1, y1); * curveVertex(x2, y2); * curveVertex(x3, y3); * curveVertex(x4, y4); * endShape(); * </PRE> * * @webref shape:curves * @param x1 coordinates for the beginning control point * @param y1 coordinates for the beginning control point * @param x2 coordinates for the first point * @param y2 coordinates for the first point * @param x3 coordinates for the second point * @param y3 coordinates for the second point * @param x4 coordinates for the ending control point * @param y4 coordinates for the ending control point * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } /** * @param z1 coordinates for the beginning control point * @param z2 coordinates for the first point * @param z3 coordinates for the second point * @param z4 coordinates for the ending control point */ public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from smooth.xml ) * * Draws all geometry with smooth (anti-aliased) edges. This will sometimes * slow down the frame rate of the application, but will enhance the visual * refinement. Note that <b>smooth()</b> will also improve image quality of * resized images, and <b>noSmooth()</b> will disable image (and font) * smoothing altogether. * * ( end auto-generated ) * * @webref shape:attributes * @see PGraphics#noSmooth() * @see PGraphics#hint(int) * @see PApplet#size(int, int, String) */ public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } /** * * @param level either 2, 4, or 8 */ public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); } /** * ( begin auto-generated from noSmooth.xml ) * * Draws all geometry with jagged (aliased) edges. * * ( end auto-generated ) * @webref shape:attributes * @see PGraphics#smooth() */ public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } /** * ( begin auto-generated from imageMode.xml ) * * Modifies the location from which images draw. The default mode is * <b>imageMode(CORNER)</b>, which specifies the location to be the upper * left corner and uses the fourth and fifth parameters of <b>image()</b> * to set the image's width and height. The syntax * <b>imageMode(CORNERS)</b> uses the second and third parameters of * <b>image()</b> to set the location of one corner of the image and uses * the fourth and fifth parameters to set the opposite corner. Use * <b>imageMode(CENTER)</b> to draw images centered at the given x and y * position.<br /> * <br /> * The parameter to <b>imageMode()</b> must be written in ALL CAPS because * Processing is a case-sensitive language. * * ( end auto-generated ) * * @webref image:loading_displaying * @param mode either CORNER, CORNERS, or CENTER * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#background(float, float, float, float) */ public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } /** * ( begin auto-generated from image.xml ) * * Displays images to the screen. The images must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the image. Processing currently works with GIF, JPEG, and Targa * images. The <b>img</b> parameter specifies the image to display and the * <b>x</b> and <b>y</b> parameters define the location of the image from * its upper-left corner. The image is displayed at its original size * unless the <b>width</b> and <b>height</b> parameters specify a different * size.<br /> * <br /> * The <b>imageMode()</b> function changes the way the parameters work. For * example, a call to <b>imageMode(CORNERS)</b> will change the * <b>width</b> and <b>height</b> parameters to define the x and y values * of the opposite corner of the image.<br /> * <br /> * The color of an image may be modified with the <b>tint()</b> function. * This function will maintain transparency for GIF and PNG images. * * ( end auto-generated ) * * <h3>Advanced</h3> * Starting with release 0124, when using the default (JAVA2D) renderer, * smooth() will also improve image quality of resized images. * * @webref image:loading_displaying * @param img the image to display * @param a x-coordinate of the image * @param b y-coordinate of the image * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#imageMode(int) * @see PGraphics#tint(float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#alpha(int) */ public void image(PImage img, float a, float b) { if (recorder != null) recorder.image(img, a, b); g.image(img, a, b); } /** * @param c width to display the image * @param d height to display the image */ public void image(PImage img, float a, float b, float c, float d) { if (recorder != null) recorder.image(img, a, b, c, d); g.image(img, a, b, c, d); } /** * Draw an image(), also specifying u/v coordinates. * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). * * @nowebref */ public void image(PImage img, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, v2); g.image(img, a, b, c, d, u1, v1, u2, v2); } /** * ( begin auto-generated from shapeMode.xml ) * * Modifies the location from which shapes draw. The default mode is * <b>shapeMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>shape()</b> to specify the width and height. The syntax * <b>shapeMode(CORNERS)</b> uses the first and second parameters of * <b>shape()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>shapeMode(CENTER)</b> draws the shape from its center point and uses * the third and forth parameters of <b>shape()</b> to specify the width * and height. The parameter must be written in "ALL CAPS" because * Processing is a case sensitive language. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param mode either CORNER, CORNERS, CENTER * @see PShape * @see PGraphics#shape(PShape) * @see PGraphics#rectMode(int) */ public void shapeMode(int mode) { if (recorder != null) recorder.shapeMode(mode); g.shapeMode(mode); } public void shape(PShape shape) { if (recorder != null) recorder.shape(shape); g.shape(shape); } /** * ( begin auto-generated from shape.xml ) * * Displays shapes to the screen. The shapes must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the shape. Processing currently works with SVG shapes only. The * <b>sh</b> parameter specifies the shape to display and the <b>x</b> and * <b>y</b> parameters define the location of the shape from its upper-left * corner. The shape is displayed at its original size unless the * <b>width</b> and <b>height</b> parameters specify a different size. The * <b>shapeMode()</b> function changes the way the parameters work. A call * to <b>shapeMode(CORNERS)</b>, for example, will change the width and * height parameters to define the x and y values of the opposite corner of * the shape. * <br /><br /> * Note complex shapes may draw awkwardly with P3D. This renderer does not * yet support shapes that have holes or complicated breaks. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param shape the shape to display * @param x x-coordinate of the shape * @param y y-coordinate of the shape * @see PShape * @see PApplet#loadShape(String) * @see PGraphics#shapeMode(int) * * Convenience method to draw at a particular location. */ public void shape(PShape shape, float x, float y) { if (recorder != null) recorder.shape(shape, x, y); g.shape(shape, x, y); } /** * @param a x-coordinate of the shape * @param b y-coordinate of the shape * @param c width to display the shape * @param d height to display the shape */ public void shape(PShape shape, float a, float b, float c, float d) { if (recorder != null) recorder.shape(shape, a, b, c, d); g.shape(shape, a, b, c, d); } public void textAlign(int alignX) { if (recorder != null) recorder.textAlign(alignX); g.textAlign(alignX); } /** * ( begin auto-generated from textAlign.xml ) * * Sets the current alignment for drawing text. The parameters LEFT, * CENTER, and RIGHT set the display characteristics of the letters in * relation to the values for the <b>x</b> and <b>y</b> parameters of the * <b>text()</b> function. * <br/> <br/> * In Processing 0125 and later, an optional second parameter can be used * to vertically align the text. BASELINE is the default, and the vertical * alignment will be reset to BASELINE if the second parameter is not used. * The TOP and CENTER parameters are straightforward. The BOTTOM parameter * offsets the line based on the current <b>textDescent()</b>. For multiple * lines, the final line will be aligned to the bottom, with the previous * lines appearing above it. * <br/> <br/> * When using <b>text()</b> with width and height parameters, BASELINE is * ignored, and treated as TOP. (Otherwise, text would by default draw * outside the box, since BASELINE is the default setting. BASELINE is not * a useful drawing mode for text drawn in a rectangle.) * <br/> <br/> * The vertical alignment is based on the value of <b>textAscent()</b>, * which many fonts do not specify correctly. It may be necessary to use a * hack and offset by a few pixels by hand so that the offset looks * correct. To do this as less of a hack, use some percentage of * <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even * if you change the size of the font. * * ( end auto-generated ) * * @webref typography:attributes * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textAlign(int alignX, int alignY) { if (recorder != null) recorder.textAlign(alignX, alignY); g.textAlign(alignX, alignY); } /** * ( begin auto-generated from textAscent.xml ) * * Returns ascent of the current font at its current size. This information * is useful for determining the height of the font above the baseline. For * example, adding the <b>textAscent()</b> and <b>textDescent()</b> values * will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textDescent() */ public float textAscent() { return g.textAscent(); } /** * ( begin auto-generated from textDescent.xml ) * * Returns descent of the current font at its current size. This * information is useful for determining the height of the font below the * baseline. For example, adding the <b>textAscent()</b> and * <b>textDescent()</b> values will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textAscent() */ public float textDescent() { return g.textDescent(); } /** * ( begin auto-generated from textFont.xml ) * * Sets the current font that will be drawn with the <b>text()</b> * function. Fonts must be loaded with <b>loadFont()</b> before it can be * used. This font will be used in all subsequent calls to the * <b>text()</b> function. If no <b>size</b> parameter is input, the font * will appear at its original size (the size it was created at with the * "Create Font..." tool) until it is changed with <b>textSize()</b>. <br * /> <br /> Because fonts are usually bitmaped, you should create fonts at * the sizes that will be used most commonly. Using <b>textFont()</b> * without the size parameter will result in the cleanest-looking text. <br * /><br /> With the default (JAVA2D) and PDF renderers, it's also possible * to enable the use of native fonts via the command * <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in * JAVA2D sketches and PDF output in cases where the vector data is * available: when the font is still installed, or the font is created via * the <b>createFont()</b> function (rather than the Create Font tool). * * ( end auto-generated ) * * @webref typography:loading_displaying * @param which any variable of the type PFont * @see PApplet#createFont(String, float, boolean) * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } /** * @param size the size of the letters in units of pixels */ public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } /** * ( begin auto-generated from textLeading.xml ) * * Sets the spacing between lines of text in units of pixels. This setting * will be used in all subsequent calls to the <b>text()</b> function. * * ( end auto-generated ) * * @webref typography:attributes * @param leading the size in pixels for spacing between lines * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } /** * ( begin auto-generated from textMode.xml ) * * Sets the way text draws to the screen. In the default configuration, the * <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in * two and three dimensional space.<br /> * <br /> * The <b>SHAPE</b> mode draws text using the the glyph outlines of * individual characters rather than as textures. This mode is only * supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the * <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any * other drawing occurs. If the outlines are not available, then * <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will * be used instead.<br /> * <br /> * The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with * <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output * files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is * not currently optimized for <b>P3D</b>, so if recording shape data, use * <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>. * * ( end auto-generated ) * * @webref typography:attributes * @param mode either MODEL or SHAPE * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) * @see PGraphics#beginRaw(PGraphics) * @see PApplet#createFont(String, float, boolean) */ public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } /** * ( begin auto-generated from textSize.xml ) * * Sets the current font size. This size will be used in all subsequent * calls to the <b>text()</b> function. Font size is measured in units of pixels. * * ( end auto-generated ) * * @webref typography:attributes * @param size the size of the letters in units of pixels * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } /** * @param c the character to measure */ public float textWidth(char c) { return g.textWidth(c); } /** * ( begin auto-generated from textWidth.xml ) * * Calculates and returns the width of any character or text string. * * ( end auto-generated ) * * @webref typography:attributes * @param str the String of characters to measure * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public float textWidth(String str) { return g.textWidth(str); } /** * @nowebref */ public float textWidth(char[] chars, int start, int length) { return g.textWidth(chars, start, length); } /** * ( begin auto-generated from text.xml ) * * Draws text to the screen. Displays the information specified in the * <b>data</b> or <b>stringdata</b> parameters on the screen in the * position specified by the <b>x</b> and <b>y</b> parameters and the * optional <b>z</b> parameter. A default font will be used unless a font * is set with the <b>textFont()</b> function. Change the color of the text * with the <b>fill()</b> function. The text displays in relation to the * <b>textAlign()</b> function, which gives the option to draw to the left, * right, and center of the coordinates. * <br /><br /> * The <b>x2</b> and <b>y2</b> parameters define a rectangular area to * display within and may only be used with string data. For text drawn * inside a rectangle, the coordinates are interpreted based on the current * <b>rectMode()</b> setting. * * ( end auto-generated ) * * @webref typography:loading_displaying * @param c the alphanumeric character to be displayed * @param x x-coordinate of text * @param y y-coordinate of text * @see PGraphics#textAlign(int, int) * @see PGraphics#textMode(int) * @see PApplet#loadFont(String) * @see PGraphics#textFont(PFont) * @see PGraphics#rectMode(int) * @see PGraphics#fill(int, float) * @see_external String */ public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } /** * @param z z-coordinate of text */ public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } /** * <h3>Advanced</h3> * Draw a chunk of text. * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, but \r (carriage return, Windows and Mac OS) are * ignored. */ public void text(String str, float x, float y) { if (recorder != null) recorder.text(str, x, y); g.text(str, x, y); } /** * <h3>Advanced</h3> * Method to draw text from an array of chars. This method will usually be * more efficient than drawing from a String object, because the String will * not be converted to a char array before drawing. * @param chars the alphanumberic symbols to be displayed * @param start array index at which to start writing characters * @param stop array index at which to stop writing characters */ public void text(char[] chars, int start, int stop, float x, float y) { if (recorder != null) recorder.text(chars, start, stop, x, y); g.text(chars, start, stop, x, y); } /** * Same as above but with a z coordinate. */ public void text(String str, float x, float y, float z) { if (recorder != null) recorder.text(str, x, y, z); g.text(str, x, y, z); } public void text(char[] chars, int start, int stop, float x, float y, float z) { if (recorder != null) recorder.text(chars, start, stop, x, y, z); g.text(chars, start, stop, x, y, z); } /** * <h3>Advanced</h3> * Draw text in a box that is constrained to a particular size. * The current rectMode() determines what the coordinates mean * (whether x1/y1/x2/y2 or x/y/w/h). * <P/> * Note that the x,y coords of the start of the box * will align with the *ascent* of the text, not the baseline, * as is the case for the other text() functions. * <P/> * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, and \r (carriage return, Windows and Mac OS) are * ignored. * * @param x1 by default, the x-coordinate of text, see rectMode() for more info * @param y1 by default, the x-coordinate of text, see rectMode() for more info * @param x2 by default, the width of the text box, see rectMode() for more info * @param y2 by default, the height of the text box, see rectMode() for more info */ public void text(String str, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(str, x1, y1, x2, y2); g.text(str, x1, y1, x2, y2); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * This does a basic number formatting, to avoid the * generally ugly appearance of printing floats. * Users who want more control should use their own nf() cmmand, * or if they want the long, ugly version of float, * use String.valueOf() to convert the float to a String first. * * @param num the numeric value to be displayed */ public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * ( begin auto-generated from pushMatrix.xml ) * * Pushes the current transformation matrix onto the matrix stack. * Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires * understanding the concept of a matrix stack. The <b>pushMatrix()</b> * function saves the current coordinate system to the stack and * <b>popMatrix()</b> restores the prior coordinate system. * <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with * the other transformation functions and may be embedded to control the * scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void pushMatrix() { if (recorder != null) recorder.pushMatrix(); g.pushMatrix(); } /** * ( begin auto-generated from popMatrix.xml ) * * Pops the current transformation matrix off the matrix stack. * Understanding pushing and popping requires understanding the concept of * a matrix stack. The <b>pushMatrix()</b> function saves the current * coordinate system to the stack and <b>popMatrix()</b> restores the prior * coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used * in conjuction with the other transformation functions and may be * embedded to control the scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() */ public void popMatrix() { if (recorder != null) recorder.popMatrix(); g.popMatrix(); } /** * ( begin auto-generated from translate.xml ) * * Specifies an amount to displace objects within the display window. The * <b>x</b> parameter specifies left/right translation, the <b>y</b> * parameter specifies up/down translation, and the <b>z</b> parameter * specifies translations toward/away from the screen. Using this function * with the <b>z</b> parameter requires using P3D as a parameter in * combination with size as shown in the above example. Transformations * apply to everything that happens after and subsequent calls to the * function accumulates the effect. For example, calling <b>translate(50, * 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70, * 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the * transformation is reset when the loop begins again. This function can be * further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param x left/right translation * @param y up/down translation * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) */ public void translate(float x, float y) { if (recorder != null) recorder.translate(x, y); g.translate(x, y); } /** * @param z forward/backward translation */ public void translate(float x, float y, float z) { if (recorder != null) recorder.translate(x, y, z); g.translate(x, y, z); } /** * ( begin auto-generated from rotate.xml ) * * Rotates a shape the amount specified by the <b>angle</b> parameter. * Angles should be specified in radians (values from 0 to TWO_PI) or * converted to radians with the <b>radians()</b> function. * <br/> <br/> * Objects are always rotated around their relative position to the origin * and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as * <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b> * begins again. * <br/> <br/> * Technically, <b>rotate()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PApplet#radians(float) */ public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } /** * ( begin auto-generated from rotateX.xml ) * * Rotates a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same * as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the example above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } /** * ( begin auto-generated from rotateY.xml ) * * Rotates a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same * as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } /** * ( begin auto-generated from rotateZ.xml ) * * Rotates a shape around the z-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same * as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } /** * <h3>Advanced</h3> * Rotate about a vector in space. Same as the glRotatef() function. * @param x * @param y * @param z */ public void rotate(float angle, float x, float y, float z) { if (recorder != null) recorder.rotate(angle, x, y, z); g.rotate(angle, x, y, z); } /** * ( begin auto-generated from scale.xml ) * * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call <b>scale(2.0)</b> increases the dimension * of a shape by 200%. Transformations apply to everything that happens * after and subsequent calls to the function multiply the effect. For * example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the * same as <b>scale(3.0)</b>. If <b>scale()</b> is called within * <b>draw()</b>, the transformation is reset when the loop begins again. * Using this fuction with the <b>z</b> parameter requires using P3D as a * parameter for <b>size()</b> as shown in the example above. This function * can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param s percentage to scale the object * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } /** * <h3>Advanced</h3> * Scale in X and Y. Equivalent to scale(sx, sy, 1). * * Not recommended for use in 3D, because the z-dimension is just * scaled by 1, since there's no way to know what else to scale it by. * * @param x percentage to scale the object in the x-axis * @param y percentage to scale the object in the y-axis */ public void scale(float x, float y) { if (recorder != null) recorder.scale(x, y); g.scale(x, y); } /** * @param z percentage to scale the object in the z-axis */ public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } /** * ( begin auto-generated from shearX.xml ) * * Shears a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as * <b>shearX(PI)</b>. If <b>shearX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearX()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearX(float angle) { if (recorder != null) recorder.shearX(angle); g.shearX(angle); } /** * ( begin auto-generated from shearY.xml ) * * Shears a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as * <b>shearY(PI)</b>. If <b>shearY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearY()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearX(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearY(float angle) { if (recorder != null) recorder.shearY(angle); g.shearY(angle); } /** * ( begin auto-generated from resetMatrix.xml ) * * Replaces the current matrix with the identity matrix. The equivalent * function in OpenGL is glLoadIdentity(). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#printMatrix() */ public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } /** * ( begin auto-generated from applyMatrix.xml ) * * Multiplies the current matrix by the one specified through the * parameters. This is very slow because it will try to calculate the * inverse of the transform, so avoid it whenever possible. The equivalent * function in OpenGL is glMultMatrix(). * * ( end auto-generated ) * * @webref transform * @source * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#printMatrix() */ public void applyMatrix(PMatrix source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } public void applyMatrix(PMatrix2D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n00 numbers which define the 4x4 matrix to be multiplied * @param n01 numbers which define the 4x4 matrix to be multiplied * @param n02 numbers which define the 4x4 matrix to be multiplied * @param n10 numbers which define the 4x4 matrix to be multiplied * @param n11 numbers which define the 4x4 matrix to be multiplied * @param n12 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(PMatrix3D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n03 numbers which define the 4x4 matrix to be multiplied * @param n13 numbers which define the 4x4 matrix to be multiplied * @param n20 numbers which define the 4x4 matrix to be multiplied * @param n21 numbers which define the 4x4 matrix to be multiplied * @param n22 numbers which define the 4x4 matrix to be multiplied * @param n23 numbers which define the 4x4 matrix to be multiplied * @param n30 numbers which define the 4x4 matrix to be multiplied * @param n31 numbers which define the 4x4 matrix to be multiplied * @param n32 numbers which define the 4x4 matrix to be multiplied * @param n33 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public PMatrix getMatrix() { return g.getMatrix(); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix2D getMatrix(PMatrix2D target) { return g.getMatrix(target); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix3D getMatrix(PMatrix3D target) { return g.getMatrix(target); } /** * Set the current transformation matrix to the contents of another. */ public void setMatrix(PMatrix source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix2D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * ( begin auto-generated from printMatrix.xml ) * * Prints the current matrix to the Console (the text window at the bottom * of Processing). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#applyMatrix(PMatrix) */ public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } /** * ( begin auto-generated from beginCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. The functions are useful if * you want to more control over camera movement, however for most users, * the <b>camera()</b> function will be sufficient.<br /><br />The camera * functions will replace any transformations (such as <b>rotate()</b> or * <b>translate()</b>) that occur before them in <b>draw()</b>, but they * will not automatically replace the camera transform itself. For this * reason, camera functions should be placed at the beginning of * <b>draw()</b> (so that transformations happen afterwards), and the * <b>camera()</b> function can be used after <b>beginCamera()</b> if you * want to reset the camera before applying transformations.<br /><br * />This function sets the matrix mode to the camera matrix so calls such * as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix() * affect the camera. <b>beginCamera()</b> should always be used with a * following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and * <b>endCamera()</b> cannot be nested. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera() * @see PGraphics#endCamera() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#resetMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#scale(float, float, float) */ public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } /** * ( begin auto-generated from endCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. Please see the reference for * <b>beginCamera()</b> for a description of how the functions are used. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } /** * ( begin auto-generated from camera.xml ) * * Sets the position of the camera through setting the eye position, the * center of the scene, and which axis is facing upward. Moving the eye * position and the direction it is pointing (the center of the scene) * allows the images to be seen from different angles. The version without * any parameters sets the camera to the default position, pointing to the * center of the display window with the Y axis as up. The default values * are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / * 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar * to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#endCamera() * @see PGraphics#frustum(float, float, float, float, float, float) */ public void camera() { if (recorder != null) recorder.camera(); g.camera(); } /** * @param eyeX x-coordinate for the eye * @param eyeY y-coordinate for the eye * @param eyeZ z-coordinate for the eye * @param centerX x-coordinate for the center of the scene * @param centerY y-coordinate for the center of the scene * @param centerZ z-coordinate for the center of the scene * @param upX usually 0.0, 1.0, or -1.0 * @param upY usually 0.0, 1.0, or -1.0 * @param upZ usually 0.0, 1.0, or -1.0 */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } /** * ( begin auto-generated from printCamera.xml ) * * Prints the current camera matrix to the Console (the text window at the * bottom of Processing). * * ( end auto-generated ) * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } /** * ( begin auto-generated from ortho.xml ) * * Sets an orthographic projection and defines a parallel clipping volume. * All objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the clipping volume where left and right are the * minimum and maximum x values, top and bottom are the minimum and maximum * y values, and near and far are the minimum and maximum z values. If no * parameters are given, the default is used: ortho(0, width, 0, height, * -10, 10). * * ( end auto-generated ) * * @webref lights_camera:camera */ public void ortho() { if (recorder != null) recorder.ortho(); g.ortho(); } /** * @param left left plane of the clipping volume * @param right right plane of the clipping volume * @param bottom bottom plane of the clipping volume * @param top top plane of the clipping volume */ public void ortho(float left, float right, float bottom, float top) { if (recorder != null) recorder.ortho(left, right, bottom, top); g.ortho(left, right, bottom, top); } /** * @param near maximum distance from the origin to the viewer * @param far maximum distance from the origin away from the viewer */ public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } /** * ( begin auto-generated from perspective.xml ) * * Sets a perspective projection applying foreshortening, making distant * objects appear smaller than closer ones. The parameters define a viewing * volume with the shape of truncated pyramid. Objects near to the front of * the volume appear their actual size, while farther objects appear * smaller. This projection simulates the perspective of the world more * accurately than orthographic projection. The version of perspective * without parameters sets the default perspective and the version with * four parameters allows the programmer to set the area precisely. The * default values are: perspective(PI/3.0, width/height, cameraZ/10.0, * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * * ( end auto-generated ) * * @webref lights_camera:camera */ public void perspective() { if (recorder != null) recorder.perspective(); g.perspective(); } /** * @param fovy field-of-view angle (in radians) for vertical direction * @param aspect ratio of width to height * @param zNear z-position of nearest clipping plane * @param zFar z-position of farthest clipping plane */ public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } /** * ( begin auto-generated from frustum.xml ) * * Sets a perspective matrix defined through the parameters. Works like * glFrustum, except it wipes out the current perspective matrix rather * than muliplying itself with it. * * ( end auto-generated ) * * @webref lights_camera:camera * @param left left coordinate of the clipping plane * @param right right coordinate of the clipping plane * @param bottom bottom coordinate of the clipping plane * @param top top coordinate of the clipping plane * @param near near component of the clipping plane; must be greater than zero * @param far far component of the clipping plane; must be greater than the near value * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) * @see PGraphics#endCamera() * @see PGraphics#perspective(float, float, float, float) */ public void frustum(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); g.frustum(left, right, bottom, top, near, far); } /** * ( begin auto-generated from printProjection.xml ) * * Prints the current projection matrix to the Console (the text window at * the bottom of Processing). * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printProjection() { if (recorder != null) recorder.printProjection(); g.printProjection(); } /** * ( begin auto-generated from screenX.xml ) * * Takes a three-dimensional X, Y, Z position and returns the X value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenY(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenX(float x, float y) { return g.screenX(x, y); } /** * ( begin auto-generated from screenY.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Y value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenY(float x, float y) { return g.screenY(x, y); } /** * @param z 3D z-coordinate to be mapped */ public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } /** * @param z 3D z-coordinate to be mapped */ public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } /** * ( begin auto-generated from screenZ.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Z value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenY(float, float, float) */ public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } /** * ( begin auto-generated from modelX.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the X value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The X value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use. * <br/> <br/> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelY(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelX(float x, float y, float z) { return g.modelX(x, y, z); } /** * ( begin auto-generated from modelY.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Y value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Y value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelY(float x, float y, float z) { return g.modelY(x, y, z); } /** * ( begin auto-generated from modelZ.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Z value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Z value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelY(float, float, float) */ public float modelZ(float x, float y, float z) { return g.modelZ(x, y, z); } /** * ( begin auto-generated from pushStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings. Note that these functions * are always used together. They allow you to change the style settings * and later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * <br /><br /> * The style information controlled by the following functions are included * in the style: * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), * textAlign(), textFont(), textMode(), textSize(), textLeading(), * emissive(), specular(), shininess(), ambient() * * ( end auto-generated ) * * @webref structure * @see PGraphics#popStyle() */ public void pushStyle() { if (recorder != null) recorder.pushStyle(); g.pushStyle(); } /** * ( begin auto-generated from popStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings; these functions are * always used together. They allow you to change the style settings and * later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * * ( end auto-generated ) * * @webref structure * @see PGraphics#pushStyle() */ public void popStyle() { if (recorder != null) recorder.popStyle(); g.popStyle(); } public void style(PStyle s) { if (recorder != null) recorder.style(s); g.style(s); } /** * ( begin auto-generated from strokeWeight.xml ) * * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * <br/> <br/> * When drawing with P3D, series of connected lines (such as the stroke * around a polygon, triangle, or ellipse) produce unattractive results * when a thick stroke weight is set (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). With P3D, the minimum and maximum values for * <b>strokeWeight()</b> are controlled by the graphics card and the * operating system's OpenGL implementation. For instance, the thickness * may not go higher than 10 pixels. * * ( end auto-generated ) * * @webref shape:attributes * @param weight the weight (in pixels) of the stroke * @see PGraphics#stroke(int, float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) */ public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } /** * ( begin auto-generated from strokeJoin.xml ) * * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * <br/> <br/> * This function is not available with the P3D renderer, (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param join either MITER, BEVEL, ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeCap(int) */ public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } /** * ( begin auto-generated from strokeCap.xml ) * * Sets the style for rendering line endings. These ends are either * squared, extended, or rounded and specified with the corresponding * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. * <br/> <br/> * This function is not available with the P3D renderer (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param cap either SQUARE, PROJECT, or ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PApplet#size(int, int, String, String) */ public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } /** * ( begin auto-generated from noStroke.xml ) * * Disables drawing the stroke (outline). If both <b>noStroke()</b> and * <b>noFill()</b> are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @see PGraphics#stroke(float, float, float, float) */ public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } /** * ( begin auto-generated from stroke.xml ) * * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <b>colorMode()</b> (the default color space is RGB, with each * value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * * ( end auto-generated ) * * @param rgb color value in hexadecimal notation * @see PGraphics#noStroke() * @see PGraphics#fill(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } /** * @param alpha opacity of the stroke */ public void stroke(int rgb, float alpha) { if (recorder != null) recorder.stroke(rgb, alpha); g.stroke(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @webref color:setting */ public void stroke(float v1, float v2, float v3) { if (recorder != null) recorder.stroke(v1, v2, v3); g.stroke(v1, v2, v3); } public void stroke(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.stroke(v1, v2, v3, alpha); g.stroke(v1, v2, v3, alpha); } /** * ( begin auto-generated from noTint.xml ) * * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @see PGraphics#tint(float, float, float, float) * @see PGraphics#image(PImage, float, float, float, float) */ public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } /** * ( begin auto-generated from tint.xml ) * * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by setting the alpha.<br /> * <br /> * To make an image transparent, but not change it's color, use white as * the tint color and specify an alpha value. For instance, tint(255, 128) * will make an image 50% transparent (unless <b>colorMode()</b> has been * used).<br /> * <br /> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components.<br /> * <br /> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255.<br /> * <br /> * The <b>tint()</b> function is also used to control the coloring of * textures in 3D. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @param rgb color value in hexadecimal notation * @see PGraphics#noTint() * @see PGraphics#image(PImage, float, float, float, float) */ public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } /** * @param alpha opacity of the image */ public void tint(int rgb, float alpha) { if (recorder != null) recorder.tint(rgb, alpha); g.tint(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void tint(float v1, float v2, float v3) { if (recorder != null) recorder.tint(v1, v2, v3); g.tint(v1, v2, v3); } public void tint(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.tint(v1, v2, v3, alpha); g.tint(v1, v2, v3, alpha); } /** * ( begin auto-generated from noFill.xml ) * * Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b> * are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @see PGraphics#fill(float, float, float, float) */ public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } /** * ( begin auto-generated from fill.xml ) * * Sets the color used to fill shapes. For example, if you run <b>fill(204, * 102, 0)</b>, all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <b>colorMode()</b> (the default color space is RGB, with * each value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * <br/> <br/> * To change the color of an image (or a texture), use tint(). * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param rgb color variable or hex value * @see PGraphics#noFill() * @see PGraphics#stroke(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } /** * @param alpha opacity of the fill */ public void fill(int rgb, float alpha) { if (recorder != null) recorder.fill(rgb, alpha); g.fill(rgb, alpha); } /** * @param gray number specifying value between white and black */ public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void fill(float v1, float v2, float v3) { if (recorder != null) recorder.fill(v1, v2, v3); g.fill(v1, v2, v3); } public void fill(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.fill(v1, v2, v3, alpha); g.fill(v1, v2, v3, alpha); } /** * ( begin auto-generated from ambient.xml ) * * Sets the ambient reflectance for shapes drawn to the screen. This is * combined with the ambient light component of environment. The color * components set through the parameters define the reflectance. For * example in the default color mode, setting v1=255, v2=126, v3=0, would * cause all the red light to reflect and half of the green light to * reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>, * and <b>shininess()</b> in setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#emissive(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void ambient(int rgb) { if (recorder != null) recorder.ambient(rgb); g.ambient(rgb); } /** * @param gray number specifying value between white and black */ public void ambient(float gray) { if (recorder != null) recorder.ambient(gray); g.ambient(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void ambient(float v1, float v2, float v3) { if (recorder != null) recorder.ambient(v1, v2, v3); g.ambient(v1, v2, v3); } /** * ( begin auto-generated from specular.xml ) * * Sets the specular color of the materials used for shapes drawn to the * screen, which sets the color of hightlights. Specular refers to light * which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light). Used in combination * with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#lightSpecular(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#emissive(float, float, float) * @see PGraphics#shininess(float) */ public void specular(int rgb) { if (recorder != null) recorder.specular(rgb); g.specular(rgb); } /** * gray number specifying value between white and black */ public void specular(float gray) { if (recorder != null) recorder.specular(gray); g.specular(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void specular(float v1, float v2, float v3) { if (recorder != null) recorder.specular(v1, v2, v3); g.specular(v1, v2, v3); } /** * ( begin auto-generated from shininess.xml ) * * Sets the amount of gloss in the surface of shapes. Used in combination * with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param shine degree of shininess * @see PGraphics#emissive(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) */ public void shininess(float shine) { if (recorder != null) recorder.shininess(shine); g.shininess(shine); } /** * ( begin auto-generated from emissive.xml ) * * Sets the emissive color of the material used for drawing shapes drawn to * the screen. Used in combination with <b>ambient()</b>, * <b>specular()</b>, and <b>shininess()</b> in setting the material * properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void emissive(int rgb) { if (recorder != null) recorder.emissive(rgb); g.emissive(rgb); } /** * gray number specifying value between white and black */ public void emissive(float gray) { if (recorder != null) recorder.emissive(gray); g.emissive(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void emissive(float v1, float v2, float v3) { if (recorder != null) recorder.emissive(v1, v2, v3); g.emissive(v1, v2, v3); } /** * ( begin auto-generated from lights.xml ) * * Sets the default ambient light, directional light, falloff, and specular * values. The defaults are ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and * lightSpecular(0, 0, 0). Lights need to be included in the draw() to * remain persistent in a looping program. Placing them in the setup() of a * looping program will cause them to only have an effect the first time * through the loop. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#noLights() */ public void lights() { if (recorder != null) recorder.lights(); g.lights(); } /** * ( begin auto-generated from noLights.xml ) * * Disable all lighting. Lighting is turned off by default and enabled with * the <b>lights()</b> function. This function can be used to disable * lighting so that 2D geometry (which does not require lighting) can be * drawn after a set of lighted 3D geometry. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#lights() */ public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } /** * ( begin auto-generated from ambientLight.xml ) * * Adds an ambient light. Ambient light doesn't come from a specific * direction, the rays have light have bounced around so much that objects * are evenly lit from all sides. Ambient lights are almost always used in * combination with other types of lights. Lights need to be included in * the <b>draw()</b> to remain persistent in a looping program. Placing * them in the <b>setup()</b> of a looping program will cause them to only * have an effect the first time through the loop. The effect of the * parameters is determined by the current color mode. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void ambientLight(float v1, float v2, float v3) { if (recorder != null) recorder.ambientLight(v1, v2, v3); g.ambientLight(v1, v2, v3); } /** * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light */ public void ambientLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, z); g.ambientLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from directionalLight.xml ) * * Adds a directional light. Directional light comes from one direction and * is stronger when hitting a surface squarely and weaker if it hits at a a * gentle angle. After hitting a surface, a directional lights scatters in * all directions. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the * direction the light is facing. For example, setting <b>ny</b> to -1 will * cause the geometry to be lit from below (the light is facing directly upward). * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param nx direction along the x-axis * @param ny direction along the y-axis * @param nz direction along the z-axis * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void directionalLight(float v1, float v2, float v3, float nx, float ny, float nz) { if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, nz); g.directionalLight(v1, v2, v3, nx, ny, nz); } /** * ( begin auto-generated from pointLight.xml ) * * Adds a point light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position * of the light. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void pointLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, z); g.pointLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from spotLight.xml ) * * Adds a spot light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the * position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the * direction or light. The <b>angle</b> parameter affects angle of the * spotlight cone. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @param nx direction along the x axis * @param ny direction along the y axis * @param nz direction along the z axis * @param angle angle of the spotlight cone * @param concentration exponent determining the center bias of the cone * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) */ public void spotLight(float v1, float v2, float v3, float x, float y, float z, float nx, float ny, float nz, float angle, float concentration) { if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); } /** * ( begin auto-generated from lightFalloff.xml ) * * Sets the falloff rates for point lights, spot lights, and ambient * lights. The parameters are used to determine the falloff with the * following equation:<br /><br />d = distance from light position to * vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * * QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements * which are created after it in the code. The default value if * <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with * a falloff can be tricky. It is used, for example, if you wanted a region * of your scene to be lit ambiently one color and another region to be lit * ambiently by another color, you would use an ambient light with location * and falloff. You can think of it as a point light that doesn't care * which direction a surface is facing. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param constant constant value or determining falloff * @param linear linear value for determining falloff * @param quadratic quadratic value for determining falloff * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#lightSpecular(float, float, float) */ public void lightFalloff(float constant, float linear, float quadratic) { if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); g.lightFalloff(constant, linear, quadratic); } /** * ( begin auto-generated from lightSpecular.xml ) * * Sets the specular color for lights. Like <b>fill()</b>, it affects only * the elements which are created after it in the code. Specular refers to * light which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light) and is used for * creating highlights. The specular quality of a light interacts with the * specular material qualities set through the <b>specular()</b> and * <b>shininess()</b> functions. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#specular(float, float, float) * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void lightSpecular(float v1, float v2, float v3) { if (recorder != null) recorder.lightSpecular(v1, v2, v3); g.lightSpecular(v1, v2, v3); } /** * ( begin auto-generated from background.xml ) * * The <b>background()</b> function sets the color used for the background * of the Processing window. The default background is light gray. In the * <b>draw()</b> function, the background color is used to clear the * display window at the beginning of each frame. * <br/> <br/> * An image can also be used as the background for a sketch, however its * width and height must be the same size as the sketch window. To resize * an image 'b' to the size of the sketch window, use b.resize(width, height). * <br/> <br/> * Images used as background will ignore the current <b>tint()</b> setting. * <br/> <br/> * It is not possible to use transparency (alpha) in background colors with * the main drawing surface, however they will work properly with <b>createGraphics()</b>. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p>Clear the background with a color that includes an alpha value. This can * only be used with objects created by createGraphics(), because the main * drawing surface cannot be set transparent.</p> * <p>It might be tempting to use this function to partially clear the screen * on each frame, however that's not how this function works. When calling * background(), the pixels will be replaced with pixels that have that level * of transparency. To do a semi-transparent overlay, use fill() with alpha * and draw a rectangle.</p> * * @webref color:setting * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#stroke(float) * @see PGraphics#fill(float) * @see PGraphics#tint(float) * @see PGraphics#colorMode(int) */ public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } /** * @param alpha opacity of the background */ public void background(int rgb, float alpha) { if (recorder != null) recorder.background(rgb, alpha); g.background(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float gray, float alpha) { if (recorder != null) recorder.background(gray, alpha); g.background(gray, alpha); } /** * @param v1 red or hue value (depending on the current color mode) * @param v2 green or saturation value (depending on the current color mode) * @param v3 blue or brightness value (depending on the current color mode) */ public void background(float v1, float v2, float v3) { if (recorder != null) recorder.background(v1, v2, v3); g.background(v1, v2, v3); } public void background(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.background(v1, v2, v3, alpha); g.background(v1, v2, v3, alpha); } /** * @webref color:setting */ public void clear() { if (recorder != null) recorder.clear(); g.clear(); } /** * Takes an RGB or ARGB image and sets it as the background. * The width and height of the image must be the same size as the sketch. * Use image.resize(width, height) to make short work of such a task.<br/> * <br/> * Note that even if the image is set as RGB, the high 8 bits of each pixel * should be set opaque (0xFF000000) because the image data will be copied * directly to the screen, and non-opaque background images may have strange * behavior. Use image.filter(OPAQUE) to handle this easily.<br/> * <br/> * When using 3D, this will also clear the zbuffer (if it exists). * * @param image PImage to set as background (must be same size as the sketch window) */ public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } /** * ( begin auto-generated from colorMode.xml ) * * Changes the way Processing interprets color data. By default, the * parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and * <b>color()</b> are defined by values between 0 and 255 using the RGB * color model. The <b>colorMode()</b> function is used to change the * numerical range used for specifying colors and to switch color systems. * For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values * are specified between 0 and 1. The limits for defining colors are * altered by setting the parameters range1, range2, range3, and range 4. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness * @see PGraphics#background(float) * @see PGraphics#fill(float) * @see PGraphics#stroke(float) */ public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } /** * @param max range for all color elements */ public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } /** * @param max1 range for the red or hue depending on the current color mode * @param max2 range for the green or saturation depending on the current color mode * @param max3 range for the blue or brightness depending on the current color mode */ public void colorMode(int mode, float max1, float max2, float max3) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3); g.colorMode(mode, max1, max2, max3); } /** * @param maxA range for the alpha */ public void colorMode(int mode, float max1, float max2, float max3, float maxA) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3, maxA); g.colorMode(mode, max1, max2, max3, maxA); } /** * ( begin auto-generated from alpha.xml ) * * Extracts the alpha value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float alpha(int rgb) { return g.alpha(rgb); } /** * ( begin auto-generated from red.xml ) * * Extracts the red value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The red() function * is easy to use and undestand, but is slower than another technique. To * achieve the same results when working in <b>colorMode(RGB, 255)</b>, but * with greater speed, use the &gt;&gt; (right shift) operator with a bit * mask. For example, the following two lines of code are equivalent:<br * /><pre>float r1 = red(myColor);<br />float r2 = myColor &gt;&gt; 16 * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float red(int rgb) { return g.red(rgb); } /** * ( begin auto-generated from green.xml ) * * Extracts the green value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>green()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use the &gt;&gt; (right shift) * operator with a bit mask. For example, the following two lines of code * are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 = * myColor &gt;&gt; 8 &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float green(int rgb) { return g.green(rgb); } /** * ( begin auto-generated from blue.xml ) * * Extracts the blue value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>blue()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use a bit mask to remove the other * color components. For example, the following two lines of code are * equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float blue(int rgb) { return g.blue(rgb); } /** * ( begin auto-generated from hue.xml ) * * Extracts the hue value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float hue(int rgb) { return g.hue(rgb); } /** * ( begin auto-generated from saturation.xml ) * * Extracts the saturation value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#brightness(int) */ public final float saturation(int rgb) { return g.saturation(rgb); } /** * ( begin auto-generated from brightness.xml ) * * Extracts the brightness value from a color. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) */ public final float brightness(int rgb) { return g.brightness(rgb); } /** * ( begin auto-generated from lerpColor.xml ) * * Calculates a color or colors between two color at a specific increment. * The <b>amt</b> parameter is the amount to interpolate between the two * values where 0.0 equal to the first point, 0.1 is very near the first * point, 0.5 is half-way in between, etc. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param c1 interpolate from this color * @param c2 interpolate to this color * @param amt between 0.0 and 1.0 * @see PImage#blendColor(int, int, int) * @see PGraphics#color(float, float, float, float) */ public int lerpColor(int c1, int c2, float amt) { return g.lerpColor(c1, c2, amt); } /** * @nowebref * Interpolate between two colors. Like lerp(), but for the * individual color components of a color supplied as an int value. */ static public int lerpColor(int c1, int c2, float amt, int mode) { return PGraphics.lerpColor(c1, c2, amt, mode); } /** * Display a warning that the specified method is only available with 3D. * @param method The method name (no parentheses) */ static public void showDepthWarning(String method) { PGraphics.showDepthWarning(method); } /** * Display a warning that the specified method that takes x, y, z parameters * can only be used with x and y parameters in this renderer. * @param method The method name (no parentheses) */ static public void showDepthWarningXYZ(String method) { PGraphics.showDepthWarningXYZ(method); } /** * Display a warning that the specified method is simply unavailable. */ static public void showMethodWarning(String method) { PGraphics.showMethodWarning(method); } /** * Error that a particular variation of a method is unavailable (even though * other variations are). For instance, if vertex(x, y, u, v) is not * available, but vertex(x, y) is just fine. */ static public void showVariationWarning(String str) { PGraphics.showVariationWarning(str); } /** * Display a warning that the specified method is not implemented, meaning * that it could be either a completely missing function, although other * variations of it may still work properly. */ static public void showMissingWarning(String method) { PGraphics.showMissingWarning(method); } /** * Return true if this renderer should be drawn to the screen. Defaults to * returning true, since nearly all renderers are on-screen beasts. But can * be overridden for subclasses like PDF so that a window doesn't open up. * <br/> <br/> * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, * what to call this? */ public boolean displayable() { return g.displayable(); } /** * Return true if this renderer does rendering through OpenGL. Defaults to false. */ public boolean isGL() { return g.isGL(); } /** * ( begin auto-generated from PImage_get.xml ) * * Reads the color of any pixel or grabs a section of an image. If no * parameters are specified, the entire image is returned. Use the <b>x</b> * and <b>y</b> parameters to get the value of one pixel. Get a section of * the display window by specifying an additional <b>width</b> and * <b>height</b> parameter. When getting an image, the <b>x</b> and * <b>y</b> parameters define the coordinates for the upper-left corner of * the image, regardless of the current <b>imageMode()</b>.<br /> * <br /> * If the pixel requested is outside of the image window, black is * returned. The numbers returned are scaled according to the current color * ranges, but only RGB values are returned by this function. For example, * even though you may have drawn a shape with <b>colorMode(HSB)</b>, the * numbers returned will be in RGB format.<br /> * <br /> * Getting the color of a single pixel with <b>get(x, y)</b> is easy, but * not as fast as grabbing the data directly from <b>pixels[]</b>. The * equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is * <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information. * * ( end auto-generated ) * * <h3>Advanced</h3> * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. * * @webref image:pixels * @brief Reads the color of any pixel or grabs a rectangle of pixels * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @see PApplet#set(int, int, int) * @see PApplet#pixels * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int) */ public int get(int x, int y) { return g.get(x, y); } /** * @param w width of pixel rectangle to get * @param h height of pixel rectangle to get */ public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { return g.get(); } /** * ( begin auto-generated from PImage_set.xml ) * * Changes the color of any pixel or writes an image directly into the * display window.<br /> * <br /> * The <b>x</b> and <b>y</b> parameters specify the pixel to change and the * <b>color</b> parameter specifies the color value. The color parameter is * affected by the current color mode (the default is RGB values from 0 to * 255). When setting an image, the <b>x</b> and <b>y</b> parameters define * the coordinates for the upper-left corner of the image, regardless of * the current <b>imageMode()</b>. * <br /><br /> * Setting the color of a single pixel with <b>set(x, y)</b> is easy, but * not as fast as putting the data directly into <b>pixels[]</b>. The * equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b> * is <b>pixels[y*width+x] = #000000</b>. See the reference for * <b>pixels[]</b> for more information. * * ( end auto-generated ) * * @webref image:pixels * @brief writes a color to any pixel or writes an image into another * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @param c any value of the color datatype * @see PImage#get(int, int, int, int) * @see PImage#pixels * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) */ public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } /** * <h3>Advanced</h3> * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. * * @param img image to copy into the original image */ public void set(int x, int y, PImage img) { if (recorder != null) recorder.set(x, y, img); g.set(x, y, img); } /** * ( begin auto-generated from PImage_mask.xml ) * * Masks part of an image from displaying by loading another image and * using it as an alpha channel. This mask image should only contain * grayscale data, but only the blue color channel is used. The mask image * needs to be the same size as the image to which it is applied.<br /> * <br /> * In addition to using a mask image, an integer array containing the alpha * channel data can be specified directly. This method is useful for * creating dynamically generated alpha masks. This array must be of the * same length as the target image's pixels array and should contain only * grayscale data of values between 0-255. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscale by * performing a proper luminance-based conversion. * * @webref pimage:method * @usage web_application * @brief Masks part of an image with another image as an alpha channel * @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array */ public void mask(PImage img) { if (recorder != null) recorder.mask(img); g.mask(img); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } /** * ( begin auto-generated from PImage_filter.xml ) * * Filters an image as defined by one of the following modes:<br /><br * />THRESHOLD - converts the image to black and white pixels depending if * they are above or below the threshold defined by the level parameter. * The level must be between 0.0 (black) and 1.0(white). If no level is * specified, 0.5 is used.<br /> * <br /> * GRAY - converts any colors in the image to grayscale equivalents<br /> * <br /> * INVERT - sets each pixel to its inverse value<br /> * <br /> * POSTERIZE - limits each channel of the image to the number of colors * specified as the level parameter<br /> * <br /> * BLUR - executes a Guassian blur with the level parameter specifying the * extent of the blurring. If no level parameter is used, the blur is * equivalent to Guassian blur of radius 1<br /> * <br /> * OPAQUE - sets the alpha channel to entirely opaque<br /> * <br /> * ERODE - reduces the light areas with the amount defined by the level * parameter<br /> * <br /> * DILATE - increases the light areas with the amount defined by the level parameter * * ( end auto-generated ) * * <h3>Advanced</h3> * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * * @webref image:pixels * @brief Converts the image to grayscale or black and white * @usage web_application * @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE * @param param unique for each, see above */ public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } /** * ( begin auto-generated from PImage_copy.xml ) * * Copies a region of pixels from one image into another. If the source and * destination regions aren't the same size, it will automatically resize * source pixels to fit the specified target region. No alpha information * is used in the process, however if the source image has an alpha channel * set, it will be copied as well. * <br /><br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies the entire image * @usage web_application * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destination's upper left corner * @param dy Y coordinate of the destination's upper left corner * @param dw destination image width * @param dh destination image height * @see PGraphics#alpha(int) * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); g.copy(sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param src an image variable referring to the source image. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); } public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * ( begin auto-generated from PImage_blend.xml ) * * Blends a region of pixels into the image specified by the <b>img</b> * parameter. These copies utilize full alpha channel support and a choice * of the following modes to blend the colors of source pixels (A) with the * ones of pixels in the destination image (B):<br /> * <br /> * BLEND - linear interpolation of colours: C = A*factor + B<br /> * <br /> * ADD - additive blending with white clip: C = min(A*factor + B, 255)<br /> * <br /> * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, * 0)<br /> * <br /> * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br /> * <br /> * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br /> * <br /> * DIFFERENCE - subtract colors from underlying image.<br /> * <br /> * EXCLUSION - similar to DIFFERENCE, but less extreme.<br /> * <br /> * MULTIPLY - Multiply the colors, result will always be darker.<br /> * <br /> * SCREEN - Opposite multiply, uses inverse values of the colors.<br /> * <br /> * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values.<br /> * <br /> * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br /> * <br /> * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh.<br /> * <br /> * DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop.<br /> * <br /> * BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop.<br /> * <br /> * All modes use the alpha information (highest byte) of source image * pixels as the blending factor. If the source and destination regions are * different sizes, the image will be automatically resized to match the * destination size. If the <b>srcImg</b> parameter is not used, the * display window is used as the source image.<br /> * <br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies a pixel or rectangle of pixels using different blending modes * @param src an image variable referring to the source image * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destinations's upper left corner * @param dy Y coordinate of the destinations's upper left corner * @param dw destination image width * @param dh destination image height * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN * * @see PApplet#alpha(int) * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) * @see PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); } }
src/main/java/processing/core/PApplet.java
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2012-13 The Processing Foundation Copyright (c) 2004-12 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.core; import processing.data.*; import processing.event.*; import processing.event.Event; import processing.opengl.*; import java.applet.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.text.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JFileChooser; import javax.swing.filechooser.FileSystemView; /** * Base class for all sketches that use processing.core. * <p/> * Note that you should not use AWT or Swing components inside a Processing * applet. The surface is made to automatically update itself, and will cause * problems with redraw of components drawn above it. If you'd like to * integrate other Java components, see below. * <p/> * The <A HREF="http://wiki.processing.org/w/Window_Size_and_Full_Screen"> * Window Size and Full Screen</A> page on the Wiki has useful information * about sizing, multiple displays, full screen, etc. * <p/> * As of release 0145, Processing uses active mode rendering in all cases. * All animation tasks happen on the "Processing Animation Thread". The * setup() and draw() methods are handled by that thread, and events (like * mouse movement and key presses, which are fired by the event dispatch * thread or EDT) are queued to be (safely) handled at the end of draw(). * For code that needs to run on the EDT, use SwingUtilities.invokeLater(). * When doing so, be careful to synchronize between that code (since * invokeLater() will make your code run from the EDT) and the Processing * animation thread. Use of a callback function or the registerXxx() methods * in PApplet can help ensure that your code doesn't do something naughty. * <p/> * As of Processing 2.0, we have discontinued support for versions of Java * prior to 1.6. We don't have enough people to support it, and for a * project of our (tiny) size, we should be focusing on the future, rather * than working around legacy Java code. * <p/> * This class extends Applet instead of JApplet because 1) historically, * we supported Java 1.1, which does not include Swing (without an * additional, sizable, download), and 2) Swing is a bloated piece of crap. * A Processing applet is a heavyweight AWT component, and can be used the * same as any other AWT component, with or without Swing. * <p/> * Similarly, Processing runs in a Frame and not a JFrame. However, there's * nothing to prevent you from embedding a PApplet into a JFrame, it's just * that the base version uses a regular AWT frame because there's simply * no need for Swing in that context. If people want to use Swing, they can * embed themselves as they wish. * <p/> * It is possible to use PApplet, along with core.jar in other projects. * This also allows you to embed a Processing drawing area into another Java * application. This means you can use standard GUI controls with a Processing * sketch. Because AWT and Swing GUI components cannot be used on top of a * PApplet, you can instead embed the PApplet inside another GUI the way you * would any other Component. * <p/> * Because the default animation thread will run at 60 frames per second, * an embedded PApplet can make the parent application sluggish. You can use * frameRate() to make it update less often, or you can use noLoop() and loop() * to disable and then re-enable looping. If you want to only update the sketch * intermittently, use noLoop() inside setup(), and redraw() whenever the * screen needs to be updated once (or loop() to re-enable the animation * thread). The following example embeds a sketch and also uses the noLoop() * and redraw() methods. You need not use noLoop() and redraw() when embedding * if you want your application to animate continuously. * <PRE> * public class ExampleFrame extends Frame { * * public ExampleFrame() { * super("Embedded PApplet"); * * setLayout(new BorderLayout()); * PApplet embed = new Embedded(); * add(embed, BorderLayout.CENTER); * * // important to call this whenever embedding a PApplet. * // It ensures that the animation thread is started and * // that other internal variables are properly set. * embed.init(); * } * } * * public class Embedded extends PApplet { * * public void setup() { * // original setup code here ... * size(400, 400); * * // prevent thread from starving everything else * noLoop(); * } * * public void draw() { * // drawing code goes here * } * * public void mousePressed() { * // do something based on mouse movement * * // update the screen (run draw once) * redraw(); * } * } * </PRE> * @usage Web &amp; Application */ public class PApplet extends Applet implements PConstants, Runnable, MouseListener, MouseWheelListener, MouseMotionListener, KeyListener, FocusListener { /** * Full name of the Java version (i.e. 1.5.0_11). * Prior to 0125, this was only the first three digits. */ public static final String javaVersionName = System.getProperty("java.version"); /** * Version of Java that's in use, whether 1.1 or 1.3 or whatever, * stored as a float. * <p> * Note that because this is stored as a float, the values may * not be <EM>exactly</EM> 1.3 or 1.4. Instead, make sure you're * comparing against 1.3f or 1.4f, which will have the same amount * of error (i.e. 1.40000001). This could just be a double, but * since Processing only uses floats, it's safer for this to be a float * because there's no good way to specify a double with the preproc. */ public static final float javaVersion = new Float(javaVersionName.substring(0, 3)).floatValue(); /** * Current platform in use. * <p> * Equivalent to System.getProperty("os.name"), just used internally. */ /** * Current platform in use, one of the * PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER. */ static public int platform; /** * Name associated with the current 'platform' (see PConstants.platformNames) */ //static public String platformName; static { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { platform = MACOSX; } else if (osname.indexOf("Windows") != -1) { platform = WINDOWS; } else if (osname.equals("Linux")) { // true for the ibm vm platform = LINUX; } else { platform = OTHER; } } /** * Setting for whether to use the Quartz renderer on OS X. The Quartz * renderer is on its way out for OS X, but Processing uses it by default * because it's much faster than the Sun renderer. In some cases, however, * the Quartz renderer is preferred. For instance, fonts are less thick * when using the Sun renderer, so to improve how fonts look, * change this setting before you call PApplet.main(). * <pre> * static public void main(String[] args) { * PApplet.useQuartz = false; * PApplet.main(new String[] { "YourSketch" }); * } * </pre> * This setting must be called before any AWT work happens, so that's why * it's such a terrible hack in how it's employed here. Calling setProperty() * inside setup() is a joke, since it's long since the AWT has been invoked. * <p/> * On OS X with a retina display, this option is ignored, because Apple's * Java implementation takes over and forces the Quartz renderer. */ // static public boolean useQuartz = true; static public boolean useQuartz = false; /** * Whether to use native (AWT) dialogs for selectInput and selectOutput. * The native dialogs on Linux tend to be pretty awful. With selectFolder() * this is ignored, because there is no native folder selector, except on * Mac OS X. On OS X, the native folder selector will be used unless * useNativeSelect is set to false. */ static public boolean useNativeSelect = (platform != LINUX); // /** // * Modifier flags for the shortcut key used to trigger menus. // * (Cmd on Mac OS X, Ctrl on Linux and Windows) // */ // static public final int MENU_SHORTCUT = // Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** The PGraphics renderer associated with this PApplet */ public PGraphics g; /** The frame containing this applet (if any) */ public Frame frame; // disabled on retina inside init() boolean useActive = true; // boolean useActive = false; // boolean useStrategy = true; boolean useStrategy = false; Canvas canvas; // /** // * Usually just 0, but with multiple displays, the X and Y coordinates of // * the screen will depend on the current screen's position relative to // * the other displays. // */ // public int displayX; // public int displayY; /** * ( begin auto-generated from screenWidth.xml ) * * System variable which stores the width of the computer screen. For * example, if the current screen resolution is 1024x768, * <b>displayWidth</b> is 1024 and <b>displayHeight</b> is 768. These * dimensions are useful when exporting full-screen applications. * <br /><br /> * To ensure that the sketch takes over the entire screen, use "Present" * instead of "Run". Otherwise the window will still have a frame border * around it and not be placed in the upper corner of the screen. On Mac OS * X, the menu bar will remain present unless "Present" mode is used. * * ( end auto-generated ) * @webref environment */ public int displayWidth; /** * ( begin auto-generated from screenHeight.xml ) * * System variable that stores the height of the computer screen. For * example, if the current screen resolution is 1024x768, * <b>screenWidth</b> is 1024 and <b>screenHeight</b> is 768. These * dimensions are useful when exporting full-screen applications. * <br /><br /> * To ensure that the sketch takes over the entire screen, use "Present" * instead of "Run". Otherwise the window will still have a frame border * around it and not be placed in the upper corner of the screen. On Mac OS * X, the menu bar will remain present unless "Present" mode is used. * * ( end auto-generated ) * @webref environment */ public int displayHeight; /** * A leech graphics object that is echoing all events. */ public PGraphics recorder; /** * Command line options passed in from main(). * <p> * This does not include the arguments passed in to PApplet itself. */ public String[] args; /** Path to sketch folder */ public String sketchPath; //folder; static final boolean DEBUG = false; // static final boolean DEBUG = true; /** Default width and height for applet when not specified */ static public final int DEFAULT_WIDTH = 100; static public final int DEFAULT_HEIGHT = 100; /** * Minimum dimensions for the window holding an applet. This varies between * platforms, Mac OS X 10.3 (confirmed with 10.7 and Java 6) can do any * height but requires at least 128 pixels width. Windows XP has another * set of limitations. And for all I know, Linux probably lets you make * windows with negative sizes. */ static public final int MIN_WINDOW_WIDTH = 128; static public final int MIN_WINDOW_HEIGHT = 128; /** * Gets set by main() if --present (old) or --full-screen (newer) are used, * and is returned by sketchFullscreen() when initializing in main(). */ // protected boolean fullScreen = false; /** * Exception thrown when size() is called the first time. * <p> * This is used internally so that setup() is forced to run twice * when the renderer is changed. This is the only way for us to handle * invoking the new renderer while also in the midst of rendering. */ static public class RendererChangeException extends RuntimeException { } /** * true if no size() command has been executed. This is used to wait until * a size has been set before placing in the window and showing it. */ public boolean defaultSize; /** Storage for the current renderer size to avoid re-allocation. */ Dimension currentSize = new Dimension(); // volatile boolean resizeRequest; // volatile int resizeWidth; // volatile int resizeHeight; /** * ( begin auto-generated from pixels.xml ) * * Array containing the values for all the pixels in the display window. * These values are of the color datatype. This array is the size of the * display window. For example, if the image is 100x100 pixels, there will * be 10000 values and if the window is 200x300 pixels, there will be 60000 * values. The <b>index</b> value defines the position of a value within * the array. For example, the statement <b>color b = pixels[230]</b> will * set the variable <b>b</b> to be equal to the value at that location in * the array.<br /> * <br /> * Before accessing this array, the data must loaded with the * <b>loadPixels()</b> function. After the array data has been modified, * the <b>updatePixels()</b> function must be run to update the changes. * Without <b>loadPixels()</b>, running the code may (or will in future * releases) result in a NullPointerException. * * ( end auto-generated ) * * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#updatePixels() * @see PApplet#get(int, int, int, int) * @see PApplet#set(int, int, int) * @see PImage */ public int pixels[]; /** * ( begin auto-generated from width.xml ) * * System variable which stores the width of the display window. This value * is set by the first parameter of the <b>size()</b> function. For * example, the function call <b>size(320, 240)</b> sets the <b>width</b> * variable to the value 320. The value of <b>width</b> is zero until * <b>size()</b> is called. * * ( end auto-generated ) * @webref environment */ public int width; /** * ( begin auto-generated from height.xml ) * * System variable which stores the height of the display window. This * value is set by the second parameter of the <b>size()</b> function. For * example, the function call <b>size(320, 240)</b> sets the <b>height</b> * variable to the value 240. The value of <b>height</b> is zero until * <b>size()</b> is called. * * ( end auto-generated ) * @webref environment * */ public int height; /** * ( begin auto-generated from mouseX.xml ) * * The system variable <b>mouseX</b> always contains the current horizontal * coordinate of the mouse. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * * */ public int mouseX; /** * ( begin auto-generated from mouseY.xml ) * * The system variable <b>mouseY</b> always contains the current vertical * coordinate of the mouse. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * */ public int mouseY; /** * ( begin auto-generated from pmouseX.xml ) * * The system variable <b>pmouseX</b> always contains the horizontal * position of the mouse in the frame previous to the current frame.<br /> * <br /> * You may find that <b>pmouseX</b> and <b>pmouseY</b> have different * values inside <b>draw()</b> and inside events like <b>mousePressed()</b> * and <b>mouseMoved()</b>. This is because they're used for different * roles, so don't mix them. Inside <b>draw()</b>, <b>pmouseX</b> and * <b>pmouseY</b> update only once per frame (once per trip through your * <b>draw()</b>). But, inside mouse events, they update each time the * event is called. If they weren't separated, then the mouse would be read * only once per frame, making response choppy. If the mouse variables were * always updated multiple times per frame, using <NOBR><b>line(pmouseX, * pmouseY, mouseX, mouseY)</b></NOBR> inside <b>draw()</b> would have lots * of gaps, because <b>pmouseX</b> may have changed several times in * between the calls to <b>line()</b>. Use <b>pmouseX</b> and * <b>pmouseY</b> inside <b>draw()</b> if you want values relative to the * previous frame. Use <b>pmouseX</b> and <b>pmouseY</b> inside the mouse * functions if you want continuous response. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#pmouseY * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseX; /** * ( begin auto-generated from pmouseY.xml ) * * The system variable <b>pmouseY</b> always contains the vertical position * of the mouse in the frame previous to the current frame. More detailed * information about how <b>pmouseY</b> is updated inside of <b>draw()</b> * and mouse events is explained in the reference for <b>pmouseX</b>. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#pmouseX * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseY; /** * previous mouseX/Y for the draw loop, separated out because this is * separate from the pmouseX/Y when inside the mouse event handlers. */ protected int dmouseX, dmouseY; /** * pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc) * these are different because mouse events are queued to the end of * draw, so the previous position has to be updated on each event, * as opposed to the pmouseX/Y that's used inside draw, which is expected * to be updated once per trip through draw(). */ protected int emouseX, emouseY; /** * Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used, * otherwise pmouseX/Y are always zero, causing a nasty jump. * <p> * Just using (frameCount == 0) won't work since mouseXxxxx() * may not be called until a couple frames into things. * <p> * @deprecated Please refrain from using this variable, it will be removed * from future releases of Processing because it cannot be used consistently * across platforms and input methods. */ @Deprecated public boolean firstMouse; /** * ( begin auto-generated from mouseButton.xml ) * * Processing automatically tracks if the mouse button is pressed and which * button is pressed. The value of the system variable <b>mouseButton</b> * is either <b>LEFT</b>, <b>RIGHT</b>, or <b>CENTER</b> depending on which * button is pressed. * * ( end auto-generated ) * * <h3>Advanced:</h3> * * If running on Mac OS, a ctrl-click will be interpreted as the right-hand * mouse button (unlike Java, which reports it as the left mouse). * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public int mouseButton; /** * ( begin auto-generated from mousePressed_var.xml ) * * Variable storing if a mouse button is pressed. The value of the system * variable <b>mousePressed</b> is true if a mouse button is pressed and * false if a button is not pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public boolean mousePressed; /** * @deprecated Use a mouse event handler that passes an event instead. */ @Deprecated public MouseEvent mouseEvent; /** * ( begin auto-generated from key.xml ) * * The system variable <b>key</b> always contains the value of the most * recent key on the keyboard that was used (either pressed or released). * <br/> <br/> * For non-ASCII keys, use the <b>keyCode</b> variable. The keys included * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and * DELETE) do not require checking to see if they key is coded, and you * should simply use the <b>key</b> variable instead of <b>keyCode</b> If * you're making cross-platform projects, note that the ENTER key is * commonly used on PCs and Unix and the RETURN key is used instead on * Macintosh. Check for both ENTER and RETURN to make sure your program * will work for all platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Last key pressed. * <p> * If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT, * this will be set to CODED (0xffff or 65535). * * @webref input:keyboard * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public char key; /** * ( begin auto-generated from keyCode.xml ) * * The variable <b>keyCode</b> is used to detect special keys such as the * UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking * for these keys, it's first necessary to check and see if the key is * coded. This is done with the conditional "if (key == CODED)" as shown in * the example. * <br/> <br/> * The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, * RETURN, ESC, and DELETE) do not require checking to see if they key is * coded, and you should simply use the <b>key</b> variable instead of * <b>keyCode</b> If you're making cross-platform projects, note that the * ENTER key is commonly used on PCs and Unix and the RETURN key is used * instead on Macintosh. Check for both ENTER and RETURN to make sure your * program will work for all platforms. * <br/> <br/> * For users familiar with Java, the values for UP and DOWN are simply * shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other * keyCode values can be found in the Java <a * href="http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html">KeyEvent</a> reference. * * ( end auto-generated ) * * <h3>Advanced</h3> * When "key" is set to CODED, this will contain a Java key code. * <p> * For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT. * Also available are ALT, CONTROL and SHIFT. A full set of constants * can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables. * * @webref input:keyboard * @see PApplet#key * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public int keyCode; /** * ( begin auto-generated from keyPressed_var.xml ) * * The boolean system variable <b>keyPressed</b> is <b>true</b> if any key * is pressed and <b>false</b> if no keys are pressed. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public boolean keyPressed; /** * The last KeyEvent object passed into a mouse function. * @deprecated Use a key event handler that passes an event instead. */ @Deprecated public KeyEvent keyEvent; /** * ( begin auto-generated from focused.xml ) * * Confirms if a Processing program is "focused", meaning that it is active * and will accept input from mouse or keyboard. This variable is "true" if * it is focused and "false" if not. This variable is often used when you * want to warn people they need to click on or roll over an applet before * it will work. * * ( end auto-generated ) * @webref environment */ public boolean focused = false; /** * Confirms if a Processing program is running inside a web browser. This * variable is "true" if the program is online and "false" if not. */ @Deprecated public boolean online = false; // This is deprecated because it's poorly named (and even more poorly // understood). Further, we'll probably be removing applets soon, in which // case this won't work at all. If you want this feature, you can check // whether getAppletContext() returns null. /** * Time in milliseconds when the applet was started. * <p> * Used by the millis() function. */ long millisOffset = System.currentTimeMillis(); /** * ( begin auto-generated from frameRate_var.xml ) * * The system variable <b>frameRate</b> contains the approximate frame rate * of the software as it executes. The initial value is 10 fps and is * updated with each frame. The value is averaged (integrated) over several * frames. As such, this value won't be valid until after 5-10 frames. * * ( end auto-generated ) * @webref environment * @see PApplet#frameRate(float) */ public float frameRate = 10; /** Last time in nanoseconds that frameRate was checked */ protected long frameRateLastNanos = 0; /** As of release 0116, frameRate(60) is called as a default */ protected float frameRateTarget = 60; protected long frameRatePeriod = 1000000000L / 60L; protected boolean looping; /** flag set to true when a redraw is asked for by the user */ protected boolean redraw; /** * ( begin auto-generated from frameCount.xml ) * * The system variable <b>frameCount</b> contains the number of frames * displayed since the program started. Inside <b>setup()</b> the value is * 0 and and after the first iteration of draw it is 1, etc. * * ( end auto-generated ) * @webref environment * @see PApplet#frameRate(float) */ public int frameCount; /** true if the sketch has stopped permanently. */ public volatile boolean finished; /** * true if the animation thread is paused. */ public volatile boolean paused; /** * true if exit() has been called so that things shut down * once the main thread kicks off. */ protected boolean exitCalled; Object pauseObject = new Object(); Thread thread; // messages to send if attached as an external vm /** * Position of the upper-lefthand corner of the editor window * that launched this applet. */ static public final String ARGS_EDITOR_LOCATION = "--editor-location"; /** * Location for where to position the applet window on screen. * <p> * This is used by the editor to when saving the previous applet * location, or could be used by other classes to launch at a * specific position on-screen. */ static public final String ARGS_EXTERNAL = "--external"; static public final String ARGS_LOCATION = "--location"; static public final String ARGS_DISPLAY = "--display"; static public final String ARGS_BGCOLOR = "--bgcolor"; /** @deprecated use --full-screen instead. */ static public final String ARGS_PRESENT = "--present"; static public final String ARGS_FULL_SCREEN = "--full-screen"; // static public final String ARGS_EXCLUSIVE = "--exclusive"; static public final String ARGS_STOP_COLOR = "--stop-color"; static public final String ARGS_HIDE_STOP = "--hide-stop"; /** * Allows the user or PdeEditor to set a specific sketch folder path. * <p> * Used by PdeEditor to pass in the location where saveFrame() * and all that stuff should write things. */ static public final String ARGS_SKETCH_FOLDER = "--sketch-path"; /** * When run externally to a PdeEditor, * this is sent by the applet when it quits. */ //static public final String EXTERNAL_QUIT = "__QUIT__"; static public final String EXTERNAL_STOP = "__STOP__"; /** * When run externally to a PDE Editor, this is sent by the applet * whenever the window is moved. * <p> * This is used so that the editor can re-open the sketch window * in the same position as the user last left it. */ static public final String EXTERNAL_MOVE = "__MOVE__"; /** true if this sketch is being run by the PDE */ boolean external = false; /** * Not official API, using internally because of the tweaks required. */ boolean retina; static final String ERROR_MIN_MAX = "Cannot use min() or max() on an empty array."; // during rev 0100 dev cycle, working on new threading model, // but need to disable and go conservative with changes in order // to get pdf and audio working properly first. // for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs. //static final boolean CRUSTY_THREADS = false; //true; /** * Applet initialization. This can do GUI work because the components have * not been 'realized' yet: things aren't visible, displayed, etc. */ @Override public void init() { // println("init() called " + Integer.toHexString(hashCode())); // using a local version here since the class variable is deprecated // Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // screenWidth = screen.width; // screenHeight = screen.height; if (checkRetina()) { // The active-mode rendering seems to be 2x slower, so disable it // with retina. On a non-retina machine, however, useActive seems // the only (or best) way to handle the rendering. useActive = false; } // send tab keys through to the PApplet setFocusTraversalKeysEnabled(false); //millisOffset = System.currentTimeMillis(); // moved to the variable declaration finished = false; // just for clarity // this will be cleared by draw() if it is not overridden looping = true; redraw = true; // draw this guy once firstMouse = true; // these need to be inited before setup // sizeMethods = new RegisteredMethods(); // pauseMethods = new RegisteredMethods(); // resumeMethods = new RegisteredMethods(); // preMethods = new RegisteredMethods(); // drawMethods = new RegisteredMethods(); // postMethods = new RegisteredMethods(); // mouseEventMethods = new RegisteredMethods(); // keyEventMethods = new RegisteredMethods(); // disposeMethods = new RegisteredMethods(); try { getAppletContext(); online = true; } catch (NullPointerException e) { online = false; } try { if (sketchPath == null) { sketchPath = System.getProperty("user.dir"); } } catch (Exception e) { } // may be a security problem Dimension size = getSize(); if ((size.width != 0) && (size.height != 0)) { // When this PApplet is embedded inside a Java application with other // Component objects, its size() may already be set externally (perhaps // by a LayoutManager). In this case, honor that size as the default. // Size of the component is set, just create a renderer. g = makeGraphics(size.width, size.height, sketchRenderer(), null, true); // This doesn't call setSize() or setPreferredSize() because the fact // that a size was already set means that someone is already doing it. } else { // Set the default size, until the user specifies otherwise this.defaultSize = true; int w = sketchWidth(); int h = sketchHeight(); g = makeGraphics(w, h, sketchRenderer(), null, true); // Fire component resize event setSize(w, h); setPreferredSize(new Dimension(w, h)); } width = g.width; height = g.height; // addListeners(); // 2.0a6 // moved out of addListeners() in 2.0a6 addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; if (!looping) { redraw(); } } }); // if (thread == null) { // paused = true; thread = new Thread(this, "Animation Thread"); thread.start(); // } // this is automatically called in applets // though it's here for applications anyway // start(); } private boolean checkRetina() { if (platform == MACOSX) { // This should probably be reset each time there's a display change. // A 5-minute search didn't turn up any such event in the Java API. // Also, should we use the Toolkit associated with the editor window? final String javaVendor = System.getProperty("java.vendor"); if (javaVendor.contains("Apple")) { Float prop = (Float) getToolkit().getDesktopProperty("apple.awt.contentScaleFactor"); if (prop != null) { return prop == 2; } } else if (javaVendor.contains("Oracle")) { String version = System.getProperty("java.version"); // 1.7.0_40 String[] m = match(version, "1.(\\d).*_(\\d+)"); // Make sure this is Oracle Java 7u40 or later if (m != null && PApplet.parseInt(m[1]) >= 7 && PApplet.parseInt(m[1]) >= 40) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = env.getDefaultScreenDevice(); try { Field field = device.getClass().getDeclaredField("scale"); if (field != null) { field.setAccessible(true); Object scale = field.get(device); if (scale instanceof Integer && ((Integer)scale).intValue() == 2) { return true; } } } catch (Exception ignore) { } } } } return false; } public int sketchQuality() { return 2; } public int sketchWidth() { return DEFAULT_WIDTH; } public int sketchHeight() { return DEFAULT_HEIGHT; } public String sketchRenderer() { return JAVA2D; } public boolean sketchFullScreen() { // return fullScreen; return false; } public void orientation(int which) { // ignore calls to the orientation command } /** * Called by the browser or applet viewer to inform this applet that it * should start its execution. It is called after the init method and * each time the applet is revisited in a Web page. * <p/> * Called explicitly via the first call to PApplet.paint(), because * PAppletGL needs to have a usable screen before getting things rolling. */ @Override public void start() { debug("start() called"); // new Exception().printStackTrace(System.out); paused = false; // unpause the thread resume(); // resumeMethods.handle(); handleMethods("resume"); debug("un-pausing thread"); synchronized (pauseObject) { debug("start() calling pauseObject.notifyAll()"); // try { pauseObject.notifyAll(); // wake up the animation thread debug("un-pausing thread 3"); // } catch (InterruptedException e) { } } } /** * Called by the browser or applet viewer to inform * this applet that it should stop its execution. * <p/> * Unfortunately, there are no guarantees from the Java spec * when or if stop() will be called (i.e. on browser quit, * or when moving between web pages), and it's not always called. */ @Override public void stop() { // this used to shut down the sketch, but that code has // been moved to destroy/dispose() // if (paused) { // synchronized (pauseObject) { // try { // pauseObject.wait(); // } catch (InterruptedException e) { // // waiting for this interrupt on a start() (resume) call // } // } // } // on the next trip through the animation thread, things will go sleepy-by paused = true; // causes animation thread to sleep pause(); handleMethods("pause"); // actual pause will happen in the run() method // synchronized (pauseObject) { // debug("stop() calling pauseObject.wait()"); // try { // pauseObject.wait(); // } catch (InterruptedException e) { // // waiting for this interrupt on a start() (resume) call // } // } } /** * Sketch has been paused. Called when switching tabs in a browser or * swapping to a different application on Android. Also called just before * quitting. Use to safely disable things like serial, sound, or sensors. */ public void pause() { } /** * Sketch has resumed. Called when switching tabs in a browser or * swapping to this application on Android. Also called on startup. * Use this to safely disable things like serial, sound, or sensors. */ public void resume() { } /** * Called by the browser or applet viewer to inform this applet * that it is being reclaimed and that it should destroy * any resources that it has allocated. * <p/> * destroy() supposedly gets called as the applet viewer * is shutting down the applet. stop() is called * first, and then destroy() to really get rid of things. * no guarantees on when they're run (on browser quit, or * when moving between pages), though. */ @Override public void destroy() { this.dispose(); } ////////////////////////////////////////////////////////////// /** Map of registered methods, stored by name. */ HashMap<String, RegisteredMethods> registerMap = new HashMap<String, PApplet.RegisteredMethods>(); class RegisteredMethods { int count; Object[] objects; // Because the Method comes from the class being called, // it will be unique for most, if not all, objects. Method[] methods; Object[] emptyArgs = new Object[] { }; void handle() { handle(emptyArgs); } void handle(Object[] args) { for (int i = 0; i < count; i++) { try { methods[i].invoke(objects[i], args); } catch (Exception e) { // check for wrapped exception, get root exception Throwable t; if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; t = ite.getCause(); } else { t = e; } // check for RuntimeException, and allow to bubble up if (t instanceof RuntimeException) { // re-throw exception throw (RuntimeException) t; } else { // trap and print as usual t.printStackTrace(); } } } } void add(Object object, Method method) { if (findIndex(object) == -1) { if (objects == null) { objects = new Object[5]; methods = new Method[5]; } else if (count == objects.length) { objects = (Object[]) PApplet.expand(objects); methods = (Method[]) PApplet.expand(methods); } objects[count] = object; methods[count] = method; count++; } else { die(method.getName() + "() already added for this instance of " + object.getClass().getName()); } } /** * Removes first object/method pair matched (and only the first, * must be called multiple times if object is registered multiple times). * Does not shrink array afterwards, silently returns if method not found. */ // public void remove(Object object, Method method) { // int index = findIndex(object, method); public void remove(Object object) { int index = findIndex(object); if (index != -1) { // shift remaining methods by one to preserve ordering count--; for (int i = index; i < count; i++) { objects[i] = objects[i+1]; methods[i] = methods[i+1]; } // clean things out for the gc's sake objects[count] = null; methods[count] = null; } } // protected int findIndex(Object object, Method method) { protected int findIndex(Object object) { for (int i = 0; i < count; i++) { if (objects[i] == object) { // if (objects[i] == object && methods[i].equals(method)) { //objects[i].equals() might be overridden, so use == for safety // since here we do care about actual object identity //methods[i]==method is never true even for same method, so must use // equals(), this should be safe because of object identity return i; } } return -1; } } /** * Register a built-in event so that it can be fired for libraries, etc. * Supported events include: * <ul> * <li>pre – at the very top of the draw() method (safe to draw) * <li>draw – at the end of the draw() method (safe to draw) * <li>post – after draw() has exited (not safe to draw) * <li>pause – called when the sketch is paused * <li>resume – called when the sketch is resumed * <li>dispose – when the sketch is shutting down (definitely not safe to draw) * <ul> * In addition, the new (for 2.0) processing.event classes are passed to * the following event types: * <ul> * <li>mouseEvent * <li>keyEvent * <li>touchEvent * </ul> * The older java.awt events are no longer supported. * See the Library Wiki page for more details. * @param methodName name of the method to be called * @param target the target object that should receive the event */ public void registerMethod(String methodName, Object target) { if (methodName.equals("mouseEvent")) { registerWithArgs("mouseEvent", target, new Class[] { processing.event.MouseEvent.class }); } else if (methodName.equals("keyEvent")) { registerWithArgs("keyEvent", target, new Class[] { processing.event.KeyEvent.class }); } else if (methodName.equals("touchEvent")) { registerWithArgs("touchEvent", target, new Class[] { processing.event.TouchEvent.class }); } else { registerNoArgs(methodName, target); } } private void registerNoArgs(String name, Object o) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { meth = new RegisteredMethods(); registerMap.put(name, meth); } Class<?> c = o.getClass(); try { Method method = c.getMethod(name, new Class[] {}); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } private void registerWithArgs(String name, Object o, Class<?> cargs[]) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { meth = new RegisteredMethods(); registerMap.put(name, meth); } Class<?> c = o.getClass(); try { Method method = c.getMethod(name, cargs); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } // public void registerMethod(String methodName, Object target, Object... args) { // registerWithArgs(methodName, target, args); // } public void unregisterMethod(String name, Object target) { RegisteredMethods meth = registerMap.get(name); if (meth == null) { die("No registered methods with the name " + name + "() were found."); } try { // Method method = o.getClass().getMethod(name, new Class[] {}); // meth.remove(o, method); meth.remove(target); } catch (Exception e) { die("Could not unregister " + name + "() for " + target, e); } } protected void handleMethods(String methodName) { RegisteredMethods meth = registerMap.get(methodName); if (meth != null) { meth.handle(); } } protected void handleMethods(String methodName, Object[] args) { RegisteredMethods meth = registerMap.get(methodName); if (meth != null) { meth.handle(args); } } @Deprecated public void registerSize(Object o) { System.err.println("The registerSize() command is no longer supported."); // Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; // registerWithArgs(sizeMethods, "size", o, methodArgs); } @Deprecated public void registerPre(Object o) { registerNoArgs("pre", o); } @Deprecated public void registerDraw(Object o) { registerNoArgs("draw", o); } @Deprecated public void registerPost(Object o) { registerNoArgs("post", o); } @Deprecated public void registerDispose(Object o) { registerNoArgs("dispose", o); } @Deprecated public void unregisterSize(Object o) { System.err.println("The unregisterSize() command is no longer supported."); // Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; // unregisterWithArgs(sizeMethods, "size", o, methodArgs); } @Deprecated public void unregisterPre(Object o) { unregisterMethod("pre", o); } @Deprecated public void unregisterDraw(Object o) { unregisterMethod("draw", o); } @Deprecated public void unregisterPost(Object o) { unregisterMethod("post", o); } @Deprecated public void unregisterDispose(Object o) { unregisterMethod("dispose", o); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // Old methods with AWT API that should not be used. // These were never implemented on Android so they're stored separately. RegisteredMethods mouseEventMethods, keyEventMethods; protected void reportDeprecation(Class<?> c, boolean mouse) { if (g != null) { PGraphics.showWarning("The class " + c.getName() + " is incompatible with Processing 2.0."); PGraphics.showWarning("A library (or other code) is using register" + (mouse ? "Mouse" : "Key") + "Event() " + "which is no longer available."); // This will crash with OpenGL, so quit anyway if (g instanceof PGraphicsOpenGL) { PGraphics.showWarning("Stopping the sketch because this code will " + "not work correctly with OpenGL."); throw new RuntimeException("This sketch uses a library that " + "needs to be updated for Processing 2.0."); } } } @Deprecated public void registerMouseEvent(Object o) { Class<?> c = o.getClass(); reportDeprecation(c, true); try { Method method = c.getMethod("mouseEvent", new Class[] { java.awt.event.MouseEvent.class }); if (mouseEventMethods == null) { mouseEventMethods = new RegisteredMethods(); } mouseEventMethods.add(o, method); } catch (Exception e) { die("Could not register mouseEvent() for " + o, e); } } @Deprecated public void unregisterMouseEvent(Object o) { try { // Method method = o.getClass().getMethod("mouseEvent", new Class[] { MouseEvent.class }); // mouseEventMethods.remove(o, method); mouseEventMethods.remove(o); } catch (Exception e) { die("Could not unregister mouseEvent() for " + o, e); } } @Deprecated public void registerKeyEvent(Object o) { Class<?> c = o.getClass(); reportDeprecation(c, false); try { Method method = c.getMethod("keyEvent", new Class[] { java.awt.event.KeyEvent.class }); if (keyEventMethods == null) { keyEventMethods = new RegisteredMethods(); } keyEventMethods.add(o, method); } catch (Exception e) { die("Could not register keyEvent() for " + o, e); } } @Deprecated public void unregisterKeyEvent(Object o) { try { // Method method = o.getClass().getMethod("keyEvent", new Class[] { KeyEvent.class }); // keyEventMethods.remove(o, method); keyEventMethods.remove(o); } catch (Exception e) { die("Could not unregister keyEvent() for " + o, e); } } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from setup.xml ) * * The <b>setup()</b> function is called once when the program starts. It's * used to define initial * enviroment properties such as screen size and background color and to * load media such as images * and fonts as the program starts. There can only be one <b>setup()</b> * function for each program and * it shouldn't be called again after its initial execution. Note: * Variables declared within * <b>setup()</b> are not accessible within other functions, including * <b>draw()</b>. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#size(int, int) * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#draw() */ public void setup() { } /** * ( begin auto-generated from draw.xml ) * * Called directly after <b>setup()</b> and continuously executes the lines * of code contained inside its block until the program is stopped or * <b>noLoop()</b> is called. The <b>draw()</b> function is called * automatically and should never be called explicitly. It should always be * controlled with <b>noLoop()</b>, <b>redraw()</b> and <b>loop()</b>. * After <b>noLoop()</b> stops the code in <b>draw()</b> from executing, * <b>redraw()</b> causes the code inside <b>draw()</b> to execute once and * <b>loop()</b> will causes the code inside <b>draw()</b> to execute * continuously again. The number of times <b>draw()</b> executes in each * second may be controlled with <b>frameRate()</b> function. * There can only be one <b>draw()</b> function for each sketch * and <b>draw()</b> must exist if you want the code to run continuously or * to process events such as <b>mousePressed()</b>. Sometimes, you might * have an empty call to <b>draw()</b> in your program as shown in the * above example. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#setup() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#redraw() * @see PApplet#frameRate(float) */ public void draw() { // if no draw method, then shut things down //System.out.println("no draw method, goodbye"); finished = true; } ////////////////////////////////////////////////////////////// protected void resizeRenderer(int newWidth, int newHeight) { debug("resizeRenderer request for " + newWidth + " " + newHeight); if (width != newWidth || height != newHeight) { debug(" former size was " + width + " " + height); g.setSize(newWidth, newHeight); width = newWidth; height = newHeight; } } /** * ( begin auto-generated from size.xml ) * * Defines the dimension of the display window in units of pixels. The * <b>size()</b> function must be the first line in <b>setup()</b>. If * <b>size()</b> is not used, the default size of the window is 100x100 * pixels. The system variables <b>width</b> and <b>height</b> are set by * the parameters passed to this function.<br /> * <br /> * Do not use variables as the parameters to <b>size()</b> function, * because it will cause problems when exporting your sketch. When * variables are used, the dimensions of your sketch cannot be determined * during export. Instead, employ numeric values in the <b>size()</b> * statement, and then use the built-in <b>width</b> and <b>height</b> * variables inside your program when the dimensions of the display window * are needed.<br /> * <br /> * The <b>size()</b> function can only be used once inside a sketch, and * cannot be used for resizing.<br/> * <br/> <b>renderer</b> parameter selects which rendering engine to use. * For example, if you will be drawing 3D shapes, use <b>P3D</b>, if you * want to export images from a program as a PDF file use <b>PDF</b>. A * brief description of the three primary renderers follows:<br /> * <br /> * <b>P2D</b> (Processing 2D) - The default renderer that supports two * dimensional drawing.<br /> * <br /> * <b>P3D</b> (Processing 3D) - 3D graphics renderer that makes use of * OpenGL-compatible graphics hardware.<br /> * <br /> * <b>PDF</b> - The PDF renderer draws 2D graphics directly to an Acrobat * PDF file. This produces excellent results when you need vector shapes * for high resolution output or printing. You must first use Import * Library &rarr; PDF to make use of the library. More information can be * found in the PDF library reference.<br /> * <br /> * The P3D renderer doesn't support <b>strokeCap()</b> or * <b>strokeJoin()</b>, which can lead to ugly results when using * <b>strokeWeight()</b>. (<a * href="http://code.google.com/p/processing/issues/detail?id=123">Issue * 123</a>) <br /> * <br /> * The maximum width and height is limited by your operating system, and is * usually the width and height of your actual screen. On some machines it * may simply be the number of pixels on your current screen, meaning that * a screen of 800x600 could support <b>size(1600, 300)</b>, since it's the * same number of pixels. This varies widely so you'll have to try * different rendering modes and sizes until you get what you're looking * for. If you need something larger, use <b>createGraphics</b> to create a * non-visible drawing surface.<br /> * <br /> * Again, the <b>size()</b> function must be the first line of the code (or * first item inside setup). Any code that appears before the <b>size()</b> * command may run more than once, which can lead to confusing results. * * ( end auto-generated ) * * <h3>Advanced</h3> * If using Java 1.3 or later, this will default to using * PGraphics2, the Java2D-based renderer. If using Java 1.1, * or if PGraphics2 is not available, then PGraphics will be used. * To set your own renderer, use the other version of the size() * method that takes a renderer as its last parameter. * <p> * If called once a renderer has already been set, this will * use the previous renderer and simply resize it. * * @webref environment * @param w width of the display window in units of pixels * @param h height of the display window in units of pixels */ public void size(int w, int h) { size(w, h, JAVA2D, null); } /** * @param renderer Either P2D, P3D, or PDF */ public void size(int w, int h, String renderer) { size(w, h, renderer, null); } /** * @nowebref */ public void size(final int w, final int h, String renderer, String path) { // Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing) EventQueue.invokeLater(new Runnable() { public void run() { // Set the preferred size so that the layout managers can handle it setPreferredSize(new Dimension(w, h)); setSize(w, h); } }); // ensure that this is an absolute path if (path != null) path = savePath(path); String currentRenderer = g.getClass().getName(); if (currentRenderer.equals(renderer)) { // Avoid infinite loop of throwing exception to reset renderer resizeRenderer(w, h); //redraw(); // will only be called insize draw() } else { // renderer is being changed // otherwise ok to fall through and create renderer below // the renderer is changing, so need to create a new object g = makeGraphics(w, h, renderer, path, true); this.width = w; this.height = h; // fire resize event to make sure the applet is the proper size // setSize(iwidth, iheight); // this is the function that will run if the user does their own // size() command inside setup, so set defaultSize to false. defaultSize = false; // throw an exception so that setup() is called again // but with a properly sized render // this is for opengl, which needs a valid, properly sized // display before calling anything inside setup(). throw new RendererChangeException(); } } public PGraphics createGraphics(int w, int h) { return createGraphics(w, h, JAVA2D); } /** * ( begin auto-generated from createGraphics.xml ) * * Creates and returns a new <b>PGraphics</b> object of the types P2D or * P3D. Use this class if you need to draw into an off-screen graphics * buffer. The PDF renderer requires the filename parameter. The DXF * renderer should not be used with <b>createGraphics()</b>, it's only * built for use with <b>beginRaw()</b> and <b>endRaw()</b>.<br /> * <br /> * It's important to call any drawing functions between <b>beginDraw()</b> * and <b>endDraw()</b> statements. This is also true for any functions * that affect drawing, such as <b>smooth()</b> or <b>colorMode()</b>.<br/> * <br/> the main drawing surface which is completely opaque, surfaces * created with <b>createGraphics()</b> can have transparency. This makes * it possible to draw into a graphics and maintain the alpha channel. By * using <b>save()</b> to write a PNG or TGA file, the transparency of the * graphics object will be honored. Note that transparency levels are * binary: pixels are either complete opaque or transparent. For the time * being, this means that text characters will be opaque blocks. This will * be fixed in a future release (<a * href="http://code.google.com/p/processing/issues/detail?id=80">Issue 80</a>). * * ( end auto-generated ) * <h3>Advanced</h3> * Create an offscreen PGraphics object for drawing. This can be used * for bitmap or vector images drawing or rendering. * <UL> * <LI>Do not use "new PGraphicsXxxx()", use this method. This method * ensures that internal variables are set up properly that tie the * new graphics context back to its parent PApplet. * <LI>The basic way to create bitmap images is to use the <A * HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A> * function. * <LI>If you want to create a really large scene and write that, * first make sure that you've allocated a lot of memory in the Preferences. * <LI>If you want to create images that are larger than the screen, * you should create your own PGraphics object, draw to that, and use * <A HREF="http://processing.org/reference/save_.html">save()</A>. * <PRE> * * PGraphics big; * * void setup() { * big = createGraphics(3000, 3000); * * big.beginDraw(); * big.background(128); * big.line(20, 1800, 1800, 900); * // etc.. * big.endDraw(); * * // make sure the file is written to the sketch folder * big.save("big.tif"); * } * * </PRE> * <LI>It's important to always wrap drawing to createGraphics() with * beginDraw() and endDraw() (beginFrame() and endFrame() prior to * revision 0115). The reason is that the renderer needs to know when * drawing has stopped, so that it can update itself internally. * This also handles calling the defaults() method, for people familiar * with that. * <LI>With Processing 0115 and later, it's possible to write images in * formats other than the default .tga and .tiff. The exact formats and * background information can be found in the developer's reference for * <A HREF="http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)">PImage.save()</A>. * </UL> * * @webref rendering * @param w width in pixels * @param h height in pixels * @param renderer Either P2D, P3D, or PDF * * @see PGraphics#PGraphics * */ public PGraphics createGraphics(int w, int h, String renderer) { PGraphics pg = makeGraphics(w, h, renderer, null, false); //pg.parent = this; // make save() work return pg; } /** * Create an offscreen graphics surface for drawing, in this case * for a renderer that writes to a file (such as PDF or DXF). * @param path the name of the file (can be an absolute or relative path) */ public PGraphics createGraphics(int w, int h, String renderer, String path) { if (path != null) { path = savePath(path); } PGraphics pg = makeGraphics(w, h, renderer, path, false); pg.parent = this; // make save() work return pg; } /** * Version of createGraphics() used internally. */ protected PGraphics makeGraphics(int w, int h, String renderer, String path, boolean primary) { String openglError = external ? "Before using OpenGL, first select " + "Import Library > OpenGL from the Sketch menu." : "The Java classpath and native library path is not " + // welcome to Java programming! "properly set for using the OpenGL library."; if (!primary && !g.isGL()) { if (renderer.equals(P2D)) { throw new RuntimeException("createGraphics() with P2D requires size() to use P2D or P3D"); } else if (renderer.equals(P3D)) { throw new RuntimeException("createGraphics() with P3D or OPENGL requires size() to use P2D or P3D"); } } try { Class<?> rendererClass = Thread.currentThread().getContextClassLoader().loadClass(renderer); Constructor<?> constructor = rendererClass.getConstructor(new Class[] { }); PGraphics pg = (PGraphics) constructor.newInstance(); pg.setParent(this); pg.setPrimary(primary); if (path != null) pg.setPath(path); // pg.setQuality(sketchQuality()); pg.setSize(w, h); // everything worked, return it return pg; } catch (InvocationTargetException ite) { String msg = ite.getTargetException().getMessage(); if ((msg != null) && (msg.indexOf("no jogl in java.library.path") != -1)) { throw new RuntimeException(openglError + " (The native library is missing.)"); } else { ite.getTargetException().printStackTrace(); Throwable target = ite.getTargetException(); if (platform == MACOSX) target.printStackTrace(System.out); // bug // neither of these help, or work //target.printStackTrace(System.err); //System.err.flush(); //System.out.println(System.err); // and the object isn't null throw new RuntimeException(target.getMessage()); } } catch (ClassNotFoundException cnfe) { if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsOpenGL") != -1) { throw new RuntimeException(openglError + " (The library .jar file is missing.)"); } else { throw new RuntimeException("You need to use \"Import Library\" " + "to add " + renderer + " to your sketch."); } } catch (Exception e) { if ((e instanceof IllegalArgumentException) || (e instanceof NoSuchMethodException) || (e instanceof IllegalAccessException)) { if (e.getMessage().contains("cannot be <= 0")) { // IllegalArgumentException will be thrown if w/h is <= 0 // http://code.google.com/p/processing/issues/detail?id=983 throw new RuntimeException(e); } else { e.printStackTrace(); String msg = renderer + " needs to be updated " + "for the current release of Processing."; throw new RuntimeException(msg); } } else { if (platform == MACOSX) e.printStackTrace(System.out); throw new RuntimeException(e.getMessage()); } } } /** * ( begin auto-generated from createImage.xml ) * * Creates a new PImage (the datatype for storing images). This provides a * fresh buffer of pixels to play with. Set the size of the buffer with the * <b>width</b> and <b>height</b> parameters. The <b>format</b> parameter * defines how the pixels are stored. See the PImage reference for more information. * <br/> <br/> * Be sure to include all three parameters, specifying only the width and * height (but no format) will produce a strange error. * <br/> <br/> * Advanced users please note that createImage() should be used instead of * the syntax <tt>new PImage()</tt>. * * ( end auto-generated ) * <h3>Advanced</h3> * Preferred method of creating new PImage objects, ensures that a * reference to the parent PApplet is included, which makes save() work * without needing an absolute path. * * @webref image * @param w width in pixels * @param h height in pixels * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel) * @see PImage * @see PGraphics */ public PImage createImage(int w, int h, int format) { PImage image = new PImage(w, h, format); image.parent = this; // make save() work return image; } /* public PImage createImage(int w, int h, int format) { return createImage(w, h, format, null); } // unapproved public PImage createImage(int w, int h, int format, Object params) { PImage image = new PImage(w, h, format); if (params != null) { image.setParams(g, params); } image.parent = this; // make save() work return image; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . @Override public void update(Graphics screen) { paint(screen); } @Override public void paint(Graphics screen) { // int r = (int) random(10000); // System.out.println("into paint " + r); //super.paint(screen); // ignore the very first call to paint, since it's coming // from the o.s., and the applet will soon update itself anyway. if (frameCount == 0) { // println("Skipping frame"); // paint() may be called more than once before things // are finally painted to the screen and the thread gets going return; } // without ignoring the first call, the first several frames // are confused because paint() gets called in the midst of // the initial nextFrame() call, so there are multiple // updates fighting with one another. // make sure the screen is visible and usable // (also prevents over-drawing when using PGraphicsOpenGL) /* the 1.5.x version if (g != null) { // added synchronization for 0194 because of flicker issues with JAVA2D // http://code.google.com/p/processing/issues/detail?id=558 // g.image is synchronized so that draw/loop and paint don't // try to fight over it. this was causing a randomized slowdown // that would cut the frameRate into a third on macosx, // and is probably related to the windows sluggishness bug too if (g.image != null) { System.out.println("ui paint"); synchronized (g.image) { screen.drawImage(g.image, 0, 0, null); } } } */ // if (useActive) { // return; // } // if (insideDraw) { // new Exception().printStackTrace(System.out); // } if (!insideDraw && (g != null) && (g.image != null)) { if (useStrategy) { render(); } else { // System.out.println("drawing to screen"); //screen.drawImage(g.image, 0, 0, null); // not retina friendly screen.drawImage(g.image, 0, 0, width, height, null); } } else { debug(insideDraw + " " + g + " " + ((g != null) ? g.image : "-")); } } protected synchronized void render() { if (canvas == null) { removeListeners(this); canvas = new Canvas(); add(canvas); setIgnoreRepaint(true); canvas.setIgnoreRepaint(true); addListeners(canvas); // add(canvas, BorderLayout.CENTER); // doLayout(); } canvas.setBounds(0, 0, width, height); // System.out.println("render(), canvas bounds are " + canvas.getBounds()); if (canvas.getBufferStrategy() == null) { // whole block [121222] // System.out.println("creating a strategy"); canvas.createBufferStrategy(2); } BufferStrategy strategy = canvas.getBufferStrategy(); if (strategy == null) { return; } // Render single frame do { // The following loop ensures that the contents of the drawing buffer // are consistent in case the underlying surface was recreated do { Graphics draw = strategy.getDrawGraphics(); draw.drawImage(g.image, 0, 0, width, height, null); draw.dispose(); // Repeat the rendering if the drawing buffer contents // were restored // System.out.println("restored " + strategy.contentsRestored()); } while (strategy.contentsRestored()); // Display the buffer // System.out.println("showing"); strategy.show(); // Repeat the rendering if the drawing buffer was lost // System.out.println("lost " + strategy.contentsLost()); // System.out.println(); } while (strategy.contentsLost()); } /* // active paint method (also the 1.2.1 version) protected void paint() { try { Graphics screen = this.getGraphics(); if (screen != null) { if ((g != null) && (g.image != null)) { screen.drawImage(g.image, 0, 0, null); } Toolkit.getDefaultToolkit().sync(); } } catch (Exception e) { // Seen on applet destroy, maybe can ignore? e.printStackTrace(); // } finally { // if (g != null) { // g.dispose(); // } } } protected void paint_1_5_1() { try { Graphics screen = getGraphics(); if (screen != null) { if (g != null) { // added synchronization for 0194 because of flicker issues with JAVA2D // http://code.google.com/p/processing/issues/detail?id=558 if (g.image != null) { System.out.println("active paint"); synchronized (g.image) { screen.drawImage(g.image, 0, 0, null); } Toolkit.getDefaultToolkit().sync(); } } } } catch (Exception e) { // Seen on applet destroy, maybe can ignore? e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// /** * Main method for the primary animation thread. * * <A HREF="http://java.sun.com/products/jfc/tsc/articles/painting/">Painting in AWT and Swing</A> */ public void run() { // not good to make this synchronized, locks things up long beforeTime = System.nanoTime(); long overSleepTime = 0L; int noDelays = 0; // Number of frames with a delay of 0 ms before the // animation thread yields to other running threads. final int NO_DELAYS_PER_YIELD = 15; /* // this has to be called after the exception is thrown, // otherwise the supporting libs won't have a valid context to draw to Object methodArgs[] = new Object[] { new Integer(width), new Integer(height) }; sizeMethods.handle(methodArgs); */ if (!online) { start(); } while ((Thread.currentThread() == thread) && !finished) { if (paused) { debug("PApplet.run() paused, calling object wait..."); synchronized (pauseObject) { try { pauseObject.wait(); debug("out of wait"); } catch (InterruptedException e) { // waiting for this interrupt on a start() (resume) call } } } debug("done with pause"); // while (paused) { // debug("paused..."); // try { // Thread.sleep(100L); // } catch (InterruptedException e) { } // ignored // } // Don't resize the renderer from the EDT (i.e. from a ComponentEvent), // otherwise it may attempt a resize mid-render. // if (resizeRequest) { // resizeRenderer(resizeWidth, resizeHeight); // resizeRequest = false; // } if (g != null) { getSize(currentSize); if (currentSize.width != g.width || currentSize.height != g.height) { resizeRenderer(currentSize.width, currentSize.height); } } // render a single frame //handleDraw(); if (g != null) g.requestDraw(); if (frameCount == 1) { // for 2.0a6, moving this request to the EDT EventQueue.invokeLater(new Runnable() { public void run() { // Call the request focus event once the image is sure to be on // screen and the component is valid. The OpenGL renderer will // request focus for its canvas inside beginDraw(). // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // requestFocus(); // Changing to this version for 0187 // http://code.google.com/p/processing/issues/detail?id=279 //requestFocusInWindow(); // For 2.0, pass this to the renderer, to lend a hand to OpenGL g.requestFocus(); } }); } // wait for update & paint to happen before drawing next frame // this is necessary since the drawing is sometimes in a // separate thread, meaning that the next frame will start // before the update/paint is completed long afterTime = System.nanoTime(); long timeDiff = afterTime - beforeTime; //System.out.println("time diff is " + timeDiff); long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime; if (sleepTime > 0) { // some time left in this cycle try { // Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L)); noDelays = 0; // Got some sleep, not delaying anymore } catch (InterruptedException ex) { } overSleepTime = (System.nanoTime() - afterTime) - sleepTime; //System.out.println(" oversleep is " + overSleepTime); } else { // sleepTime <= 0; the frame took longer than the period // excess -= sleepTime; // store excess time value overSleepTime = 0L; noDelays++; if (noDelays > NO_DELAYS_PER_YIELD) { Thread.yield(); // give another thread a chance to run noDelays = 0; } } beforeTime = System.nanoTime(); } dispose(); // call to shutdown libs? // If the user called the exit() function, the window should close, // rather than the sketch just halting. if (exitCalled) { exitActual(); } } protected boolean insideDraw; //synchronized public void handleDisplay() { public void handleDraw() { debug("handleDraw() " + g + " " + looping + " " + redraw + " valid:" + this.isValid() + " visible:" + this.isVisible()); if (canDraw()) { if (!g.canDraw()) { debug("g.canDraw() is false"); // Don't draw if the renderer is not yet ready. // (e.g. OpenGL has to wait for a peer to be on screen) return; } insideDraw = true; g.beginDraw(); if (recorder != null) { recorder.beginDraw(); } long now = System.nanoTime(); if (frameCount == 0) { GraphicsConfiguration gc = getGraphicsConfiguration(); if (gc == null) return; GraphicsDevice displayDevice = getGraphicsConfiguration().getDevice(); if (displayDevice == null) return; Rectangle screenRect = displayDevice.getDefaultConfiguration().getBounds(); // screenX = screenRect.x; // screenY = screenRect.y; displayWidth = screenRect.width; displayHeight = screenRect.height; try { //println("Calling setup()"); setup(); //println("Done with setup()"); } catch (RendererChangeException e) { // Give up, instead set the new renderer and re-attempt setup() return; } this.defaultSize = false; } else { // frameCount > 0, meaning an actual draw() // update the current frameRate double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0); float instantaneousRate = (float) rate / 1000.0f; frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f); if (frameCount != 0) { handleMethods("pre"); } // use dmouseX/Y as previous mouse pos, since this is the // last position the mouse was in during the previous draw. pmouseX = dmouseX; pmouseY = dmouseY; //println("Calling draw()"); draw(); //println("Done calling draw()"); // dmouseX/Y is updated only once per frame (unlike emouseX/Y) dmouseX = mouseX; dmouseY = mouseY; // these are called *after* loop so that valid // drawing commands can be run inside them. it can't // be before, since a call to background() would wipe // out anything that had been drawn so far. dequeueEvents(); // dequeueMouseEvents(); // dequeueKeyEvents(); handleMethods("draw"); redraw = false; // unset 'redraw' flag in case it was set // (only do this once draw() has run, not just setup()) } g.endDraw(); if (recorder != null) { recorder.endDraw(); } insideDraw = false; if (useActive) { if (useStrategy) { render(); } else { Graphics screen = getGraphics(); screen.drawImage(g.image, 0, 0, width, height, null); } } else { repaint(); } // getToolkit().sync(); // force repaint now (proper method) if (frameCount != 0) { handleMethods("post"); } frameRateLastNanos = now; frameCount++; } } /** Not official API, not guaranteed to work in the future. */ public boolean canDraw() { return g != null && (looping || redraw); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from redraw.xml ) * * Executes the code within <b>draw()</b> one time. This functions allows * the program to update the display window only when necessary, for * example when an event registered by <b>mousePressed()</b> or * <b>keyPressed()</b> occurs. * <br/><br/> structuring a program, it only makes sense to call redraw() * within events such as <b>mousePressed()</b>. This is because * <b>redraw()</b> does not run <b>draw()</b> immediately (it only sets a * flag that indicates an update is needed). * <br/><br/> <b>redraw()</b> within <b>draw()</b> has no effect because * <b>draw()</b> is continuously called anyway. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#draw() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#frameRate(float) */ synchronized public void redraw() { if (!looping) { redraw = true; // if (thread != null) { // // wake from sleep (necessary otherwise it'll be // // up to 10 seconds before update) // if (CRUSTY_THREADS) { // thread.interrupt(); // } else { // synchronized (blocker) { // blocker.notifyAll(); // } // } // } } } /** * ( begin auto-generated from loop.xml ) * * Causes Processing to continuously execute the code within <b>draw()</b>. * If <b>noLoop()</b> is called, the code in <b>draw()</b> stops executing. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#noLoop() * @see PApplet#redraw() * @see PApplet#draw() */ synchronized public void loop() { if (!looping) { looping = true; } } /** * ( begin auto-generated from noLoop.xml ) * * Stops Processing from continuously executing the code within * <b>draw()</b>. If <b>loop()</b> is called, the code in <b>draw()</b> * begin to run continuously again. If using <b>noLoop()</b> in * <b>setup()</b>, it should be the last line inside the block. * <br/> <br/> * When <b>noLoop()</b> is used, it's not possible to manipulate or access * the screen inside event handling functions such as <b>mousePressed()</b> * or <b>keyPressed()</b>. Instead, use those functions to call * <b>redraw()</b> or <b>loop()</b>, which will run <b>draw()</b>, which * can update the screen properly. This means that when noLoop() has been * called, no drawing can happen, and functions like saveFrame() or * loadPixels() may not be used. * <br/> <br/> * Note that if the sketch is resized, <b>redraw()</b> will be called to * update the sketch, even after <b>noLoop()</b> has been specified. * Otherwise, the sketch would enter an odd state until <b>loop()</b> was called. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#loop() * @see PApplet#redraw() * @see PApplet#draw() */ synchronized public void noLoop() { if (looping) { looping = false; } } ////////////////////////////////////////////////////////////// // public void addListeners() { // addMouseListener(this); // addMouseMotionListener(this); // addKeyListener(this); // addFocusListener(this); // // addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; // // if (!looping) { // redraw(); // } // } // }); // } // // // public void removeListeners() { // removeMouseListener(this); // removeMouseMotionListener(this); // removeKeyListener(this); // removeFocusListener(this); // //// removeComponentListener(??); //// addComponentListener(new ComponentAdapter() { //// public void componentResized(ComponentEvent e) { //// Component c = e.getComponent(); //// //System.out.println("componentResized() " + c); //// Rectangle bounds = c.getBounds(); //// resizeRequest = true; //// resizeWidth = bounds.width; //// resizeHeight = bounds.height; //// //// if (!looping) { //// redraw(); //// } //// } //// }); // } public void addListeners(Component comp) { comp.addMouseListener(this); comp.addMouseWheelListener(this); comp.addMouseMotionListener(this); comp.addKeyListener(this); comp.addFocusListener(this); // canvas.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // //System.out.println("componentResized() " + c); // Rectangle bounds = c.getBounds(); // resizeRequest = true; // resizeWidth = bounds.width; // resizeHeight = bounds.height; // // if (!looping) { // redraw(); // } // } // }); } public void removeListeners(Component comp) { comp.removeMouseListener(this); comp.removeMouseWheelListener(this); comp.removeMouseMotionListener(this); comp.removeKeyListener(this); comp.removeFocusListener(this); } /** * Call to remove, then add, listeners to a component. * Avoids issues with double-adding. */ public void updateListeners(Component comp) { removeListeners(comp); addListeners(comp); } ////////////////////////////////////////////////////////////// // protected Event eventQueue[] = new Event[10]; // protected int eventCount; class InternalEventQueue { protected Event queue[] = new Event[10]; protected int offset; protected int count; synchronized void add(Event e) { if (count == queue.length) { queue = (Event[]) expand(queue); } queue[count++] = e; } synchronized Event remove() { if (offset == count) { throw new RuntimeException("Nothing left on the event queue."); } Event outgoing = queue[offset++]; if (offset == count) { // All done, time to reset offset = 0; count = 0; } return outgoing; } synchronized boolean available() { return count != 0; } } InternalEventQueue eventQueue = new InternalEventQueue(); /** * Add an event to the internal event queue, or process it immediately if * the sketch is not currently looping. */ public void postEvent(processing.event.Event pe) { // if (pe instanceof MouseEvent) { //// switch (pe.getFlavor()) { //// case Event.MOUSE: // if (looping) { // enqueueMouseEvent((MouseEvent) pe); // } else { // handleMouseEvent((MouseEvent) pe); // enqueueEvent(pe); // } // } else if (pe instanceof KeyEvent) { // if (looping) { // enqueueKeyEvent((KeyEvent) pe); // } else { // handleKeyEvent((KeyEvent) pe); // } // } // synchronized (eventQueue) { // if (eventCount == eventQueue.length) { // eventQueue = (Event[]) expand(eventQueue); // } // eventQueue[eventCount++] = pe; // } eventQueue.add(pe); if (!looping) { dequeueEvents(); } } // protected void enqueueEvent(Event e) { // synchronized (eventQueue) { // if (eventCount == eventQueue.length) { // eventQueue = (Event[]) expand(eventQueue); // } // eventQueue[eventCount++] = e; // } // } protected void dequeueEvents() { // can't do this.. thread lock // synchronized (eventQueue) { // for (int i = 0; i < eventCount; i++) { // Event e = eventQueue[i]; while (eventQueue.available()) { Event e = eventQueue.remove(); switch (e.getFlavor()) { case Event.MOUSE: handleMouseEvent((MouseEvent) e); break; case Event.KEY: handleKeyEvent((KeyEvent) e); break; } // } // eventCount = 0; } } ////////////////////////////////////////////////////////////// // MouseEvent mouseEventQueue[] = new MouseEvent[10]; // int mouseEventCount; // // protected void enqueueMouseEvent(MouseEvent e) { // synchronized (mouseEventQueue) { // if (mouseEventCount == mouseEventQueue.length) { // MouseEvent temp[] = new MouseEvent[mouseEventCount << 1]; // System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount); // mouseEventQueue = temp; // } // mouseEventQueue[mouseEventCount++] = e; // } // } // // protected void dequeueMouseEvents() { // synchronized (mouseEventQueue) { // for (int i = 0; i < mouseEventCount; i++) { // handleMouseEvent(mouseEventQueue[i]); // } // mouseEventCount = 0; // } // } /** * Actually take action based on a mouse event. * Internally updates mouseX, mouseY, mousePressed, and mouseEvent. * Then it calls the event type with no params, * i.e. mousePressed() or mouseReleased() that the user may have * overloaded to do something more useful. */ protected void handleMouseEvent(MouseEvent event) { // http://dev.processing.org/bugs/show_bug.cgi?id=170 // also prevents mouseExited() on the mac from hosing the mouse // position, because x/y are bizarre values on the exit event. // see also the id check below.. both of these go together. // Not necessary to set mouseX/Y on PRESS or RELEASE events because the // actual position will have been set by a MOVE or DRAG event. if (event.getAction() == MouseEvent.DRAG || event.getAction() == MouseEvent.MOVE) { pmouseX = emouseX; pmouseY = emouseY; mouseX = event.getX(); mouseY = event.getY(); } // Get the (already processed) button code mouseButton = event.getButton(); // Compatibility for older code (these have AWT object params, not P5) if (mouseEventMethods != null) { // Probably also good to check this, in case anyone tries to call // postEvent() with an artificial event they've created. if (event.getNative() != null) { mouseEventMethods.handle(new Object[] { event.getNative() }); } } // this used to only be called on mouseMoved and mouseDragged // change it back if people run into trouble if (firstMouse) { pmouseX = mouseX; pmouseY = mouseY; dmouseX = mouseX; dmouseY = mouseY; firstMouse = false; } mouseEvent = event; // Do this up here in case a registered method relies on the // boolean for mousePressed. switch (event.getAction()) { case MouseEvent.PRESS: mousePressed = true; break; case MouseEvent.RELEASE: mousePressed = false; break; } handleMethods("mouseEvent", new Object[] { event }); switch (event.getAction()) { case MouseEvent.PRESS: // mousePressed = true; mousePressed(event); break; case MouseEvent.RELEASE: // mousePressed = false; mouseReleased(event); break; case MouseEvent.CLICK: mouseClicked(event); break; case MouseEvent.DRAG: mouseDragged(event); break; case MouseEvent.MOVE: mouseMoved(event); break; case MouseEvent.ENTER: mouseEntered(event); break; case MouseEvent.EXIT: mouseExited(event); break; case MouseEvent.WHEEL: mouseWheel(event); break; } if ((event.getAction() == MouseEvent.DRAG) || (event.getAction() == MouseEvent.MOVE)) { emouseX = mouseX; emouseY = mouseY; } } /* // disabling for now; requires Java 1.7 and "precise" semantics are odd... // returns 0.1 for tick-by-tick scrolling on OS X, but it's not a matter of // calling ceil() on the value: 1.5 goes to 1, but 2.3 goes to 2. // "precise" is a whole different animal, so add later API to shore that up. static protected Method preciseWheelMethod; static { try { preciseWheelMethod = MouseWheelEvent.class.getMethod("getPreciseWheelRotation", new Class[] { }); } catch (Exception e) { // ignored, the method will just be set to null } } */ /** * Figure out how to process a mouse event. When loop() has been * called, the events will be queued up until drawing is complete. * If noLoop() has been called, then events will happen immediately. */ protected void nativeMouseEvent(java.awt.event.MouseEvent nativeEvent) { // the 'amount' is the number of button clicks for a click event, // or the number of steps/clicks on the wheel for a mouse wheel event. int peCount = nativeEvent.getClickCount(); int peAction = 0; switch (nativeEvent.getID()) { case java.awt.event.MouseEvent.MOUSE_PRESSED: peAction = MouseEvent.PRESS; break; case java.awt.event.MouseEvent.MOUSE_RELEASED: peAction = MouseEvent.RELEASE; break; case java.awt.event.MouseEvent.MOUSE_CLICKED: peAction = MouseEvent.CLICK; break; case java.awt.event.MouseEvent.MOUSE_DRAGGED: peAction = MouseEvent.DRAG; break; case java.awt.event.MouseEvent.MOUSE_MOVED: peAction = MouseEvent.MOVE; break; case java.awt.event.MouseEvent.MOUSE_ENTERED: peAction = MouseEvent.ENTER; break; case java.awt.event.MouseEvent.MOUSE_EXITED: peAction = MouseEvent.EXIT; break; //case java.awt.event.MouseWheelEvent.WHEEL_UNIT_SCROLL: case java.awt.event.MouseEvent.MOUSE_WHEEL: peAction = MouseEvent.WHEEL; /* if (preciseWheelMethod != null) { try { peAmount = ((Double) preciseWheelMethod.invoke(nativeEvent, (Object[]) null)).floatValue(); } catch (Exception e) { preciseWheelMethod = null; } } */ peCount = ((MouseWheelEvent) nativeEvent).getWheelRotation(); break; } //System.out.println(nativeEvent); //int modifiers = nativeEvent.getModifiersEx(); // If using getModifiersEx(), the regular modifiers don't set properly. int modifiers = nativeEvent.getModifiers(); int peModifiers = modifiers & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.META_MASK | InputEvent.ALT_MASK); // Windows and OS X seem to disagree on how to handle this. Windows only // sets BUTTON1_DOWN_MASK, while OS X seems to set BUTTON1_MASK. // This is an issue in particular with mouse release events: // http://code.google.com/p/processing/issues/detail?id=1294 // The fix for which led to a regression (fixed here by checking both): // http://code.google.com/p/processing/issues/detail?id=1332 int peButton = 0; // if ((modifiers & InputEvent.BUTTON1_MASK) != 0 || // (modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) { // peButton = LEFT; // } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0 || // (modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) { // peButton = CENTER; // } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0 || // (modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) { // peButton = RIGHT; // } if ((modifiers & InputEvent.BUTTON1_MASK) != 0) { peButton = LEFT; } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) { peButton = CENTER; } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) { peButton = RIGHT; } // If running on macos, allow ctrl-click as right mouse. Prior to 0215, // this used isPopupTrigger() on the native event, but that doesn't work // for mouseClicked and mouseReleased (or others). if (platform == MACOSX) { //if (nativeEvent.isPopupTrigger()) { if ((modifiers & InputEvent.CTRL_MASK) != 0) { peButton = RIGHT; } } postEvent(new MouseEvent(nativeEvent, nativeEvent.getWhen(), peAction, peModifiers, nativeEvent.getX(), nativeEvent.getY(), peButton, peCount)); } /** * If you override this or any function that takes a "MouseEvent e" * without calling its super.mouseXxxx() then mouseX, mouseY, * mousePressed, and mouseEvent will no longer be set. * * @nowebref */ public void mousePressed(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseReleased(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseClicked(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseEntered(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseExited(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseDragged(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseMoved(java.awt.event.MouseEvent e) { nativeMouseEvent(e); } /** * @nowebref */ public void mouseWheelMoved(java.awt.event.MouseWheelEvent e) { nativeMouseEvent(e); } /** * ( begin auto-generated from mousePressed.xml ) * * The <b>mousePressed()</b> function is called once after every time a * mouse button is pressed. The <b>mouseButton</b> variable (see the * related reference entry) can be used to determine which button has been pressed. * * ( end auto-generated ) * <h3>Advanced</h3> * * If you must, use * int button = mouseEvent.getButton(); * to figure out which button was clicked. It will be one of: * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3 * Note, however, that this is completely inconsistent across * platforms. * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mouseButton * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mousePressed() { } public void mousePressed(MouseEvent event) { mousePressed(); } /** * ( begin auto-generated from mouseReleased.xml ) * * The <b>mouseReleased()</b> function is called every time a mouse button * is released. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mouseButton * @see PApplet#mousePressed() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mouseReleased() { } public void mouseReleased(MouseEvent event) { mouseReleased(); } /** * ( begin auto-generated from mouseClicked.xml ) * * The <b>mouseClicked()</b> function is called once after a mouse button * has been pressed and then released. * * ( end auto-generated ) * <h3>Advanced</h3> * When the mouse is clicked, mousePressed() will be called, * then mouseReleased(), then mouseClicked(). Note that * mousePressed is already false inside of mouseClicked(). * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mouseButton * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mouseClicked() { } public void mouseClicked(MouseEvent event) { mouseClicked(); } /** * ( begin auto-generated from mouseDragged.xml ) * * The <b>mouseDragged()</b> function is called once every time the mouse * moves and a mouse button is pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() */ public void mouseDragged() { } public void mouseDragged(MouseEvent event) { mouseDragged(); } /** * ( begin auto-generated from mouseMoved.xml ) * * The <b>mouseMoved()</b> function is called every time the mouse moves * and a mouse button is not pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseDragged() */ public void mouseMoved() { } public void mouseMoved(MouseEvent event) { mouseMoved(); } public void mouseEntered() { } public void mouseEntered(MouseEvent event) { mouseEntered(); } public void mouseExited() { } public void mouseExited(MouseEvent event) { mouseExited(); } /** * @nowebref */ public void mouseWheel() { } /** * The event.getAmount() method returns negative values if the mouse wheel * if rotated up or away from the user and positive in the other direction. * On OS X with "natural" scrolling enabled, the values are opposite. * * @webref input:mouse * @param event the MouseEvent */ public void mouseWheel(MouseEvent event) { mouseWheel(); } ////////////////////////////////////////////////////////////// // KeyEvent keyEventQueue[] = new KeyEvent[10]; // int keyEventCount; // // protected void enqueueKeyEvent(KeyEvent e) { // synchronized (keyEventQueue) { // if (keyEventCount == keyEventQueue.length) { // KeyEvent temp[] = new KeyEvent[keyEventCount << 1]; // System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount); // keyEventQueue = temp; // } // keyEventQueue[keyEventCount++] = e; // } // } // // protected void dequeueKeyEvents() { // synchronized (keyEventQueue) { // for (int i = 0; i < keyEventCount; i++) { // keyEvent = keyEventQueue[i]; // handleKeyEvent(keyEvent); // } // keyEventCount = 0; // } // } // protected void handleKeyEvent(java.awt.event.KeyEvent event) { // keyEvent = event; // key = event.getKeyChar(); // keyCode = event.getKeyCode(); // // if (keyEventMethods != null) { // keyEventMethods.handle(new Object[] { event }); // } // // switch (event.getID()) { // case KeyEvent.KEY_PRESSED: // keyPressed = true; // keyPressed(); // break; // case KeyEvent.KEY_RELEASED: // keyPressed = false; // keyReleased(); // break; // case KeyEvent.KEY_TYPED: // keyTyped(); // break; // } // // // if someone else wants to intercept the key, they should // // set key to zero (or something besides the ESC). // if (event.getID() == java.awt.event.KeyEvent.KEY_PRESSED) { // if (key == java.awt.event.KeyEvent.VK_ESCAPE) { // exit(); // } // // When running tethered to the Processing application, respond to // // Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior // // when running independently, because this sketch may be one component // // embedded inside an application that has its own close behavior. // if (external && // event.getModifiers() == MENU_SHORTCUT && // event.getKeyCode() == 'W') { // exit(); // } // } // } protected void handleKeyEvent(KeyEvent event) { keyEvent = event; key = event.getKey(); keyCode = event.getKeyCode(); switch (event.getAction()) { case KeyEvent.PRESS: keyPressed = true; keyPressed(keyEvent); break; case KeyEvent.RELEASE: keyPressed = false; keyReleased(keyEvent); break; case KeyEvent.TYPE: keyTyped(keyEvent); break; } if (keyEventMethods != null) { keyEventMethods.handle(new Object[] { event.getNative() }); } handleMethods("keyEvent", new Object[] { event }); // if someone else wants to intercept the key, they should // set key to zero (or something besides the ESC). if (event.getAction() == KeyEvent.PRESS) { //if (key == java.awt.event.KeyEvent.VK_ESCAPE) { if (key == ESC) { exit(); } // When running tethered to the Processing application, respond to // Ctrl-W (or Cmd-W) events by closing the sketch. Not enabled when // running independently, because this sketch may be one component // embedded inside an application that has its own close behavior. if (external && event.getKeyCode() == 'W' && ((event.isMetaDown() && platform == MACOSX) || (event.isControlDown() && platform != MACOSX))) { // Can't use this native stuff b/c the native event might be NEWT // if (external && event.getNative() instanceof java.awt.event.KeyEvent && // ((java.awt.event.KeyEvent) event.getNative()).getModifiers() == // Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() && // event.getKeyCode() == 'W') { exit(); } } } protected void nativeKeyEvent(java.awt.event.KeyEvent event) { int peAction = 0; switch (event.getID()) { case java.awt.event.KeyEvent.KEY_PRESSED: peAction = KeyEvent.PRESS; break; case java.awt.event.KeyEvent.KEY_RELEASED: peAction = KeyEvent.RELEASE; break; case java.awt.event.KeyEvent.KEY_TYPED: peAction = KeyEvent.TYPE; break; } // int peModifiers = event.getModifiersEx() & // (InputEvent.SHIFT_DOWN_MASK | // InputEvent.CTRL_DOWN_MASK | // InputEvent.META_DOWN_MASK | // InputEvent.ALT_DOWN_MASK); int peModifiers = event.getModifiers() & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.META_MASK | InputEvent.ALT_MASK); postEvent(new KeyEvent(event, event.getWhen(), peAction, peModifiers, event.getKeyChar(), event.getKeyCode())); } /** * Overriding keyXxxxx(KeyEvent e) functions will cause the 'key', * 'keyCode', and 'keyEvent' variables to no longer work; * key events will no longer be queued until the end of draw(); * and the keyPressed(), keyReleased() and keyTyped() methods * will no longer be called. * * @nowebref */ public void keyPressed(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * @nowebref */ public void keyReleased(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * @nowebref */ public void keyTyped(java.awt.event.KeyEvent e) { nativeKeyEvent(e); } /** * * ( begin auto-generated from keyPressed.xml ) * * The <b>keyPressed()</b> function is called once every time a key is * pressed. The key that was pressed is stored in the <b>key</b> variable. * <br/> <br/> * For non-ASCII keys, use the <b>keyCode</b> variable. The keys included * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and * DELETE) do not require checking to see if they key is coded, and you * should simply use the <b>key</b> variable instead of <b>keyCode</b> If * you're making cross-platform projects, note that the ENTER key is * commonly used on PCs and Unix and the RETURN key is used instead on * Macintosh. Check for both ENTER and RETURN to make sure your program * will work for all platforms. * <br/> <br/> * Because of how operating systems handle key repeats, holding down a key * may cause multiple calls to keyPressed() (and keyReleased() as well). * The rate of repeat is set by the operating system and how each computer * is configured. * * ( end auto-generated ) * <h3>Advanced</h3> * * Called each time a single key on the keyboard is pressed. * Because of how operating systems handle key repeats, holding * down a key will cause multiple calls to keyPressed(), because * the OS repeat takes over. * <p> * Examples for key handling: * (Tested on Windows XP, please notify if different on other * platforms, I have a feeling Mac OS and Linux may do otherwise) * <PRE> * 1. Pressing 'a' on the keyboard: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * keyReleased with key == 'a' and keyCode == 'A' * * 2. Pressing 'A' on the keyboard: * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * * 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off): * keyPressed with key == CODED and keyCode == SHIFT * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * keyReleased with key == CODED and keyCode == SHIFT * * 4. Holding down the 'a' key. * The following will happen several times, * depending on your machine's "key repeat rate" settings: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * When you finally let go, you'll get: * keyReleased with key == 'a' and keyCode == 'A' * * 5. Pressing and releasing the 'shift' key * keyPressed with key == CODED and keyCode == SHIFT * keyReleased with key == CODED and keyCode == SHIFT * (note there is no keyTyped) * * 6. Pressing the tab key in an applet with Java 1.4 will * normally do nothing, but PApplet dynamically shuts * this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows). * Java 1.1 (Microsoft VM) passes the TAB key through normally. * Not tested on other platforms or for 1.3. * </PRE> * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyReleased() */ public void keyPressed() { } public void keyPressed(KeyEvent event) { keyPressed(); } /** * ( begin auto-generated from keyReleased.xml ) * * The <b>keyReleased()</b> function is called once every time a key is * released. The key that was released will be stored in the <b>key</b> * variable. See <b>key</b> and <b>keyReleased</b> for more information. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() */ public void keyReleased() { } public void keyReleased(KeyEvent event) { keyReleased(); } /** * ( begin auto-generated from keyTyped.xml ) * * The <b>keyTyped()</b> function is called once every time a key is * pressed, but action keys such as Ctrl, Shift, and Alt are ignored. * Because of how operating systems handle key repeats, holding down a key * will cause multiple calls to <b>keyTyped()</b>, the rate is set by the * operating system and how each computer is configured. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#keyPressed * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyReleased() */ public void keyTyped() { } public void keyTyped(KeyEvent event) { keyTyped(); } ////////////////////////////////////////////////////////////// // i am focused man, and i'm not afraid of death. // and i'm going all out. i circle the vultures in a van // and i run the block. public void focusGained() { } public void focusGained(FocusEvent e) { focused = true; focusGained(); } public void focusLost() { } public void focusLost(FocusEvent e) { focused = false; focusLost(); } ////////////////////////////////////////////////////////////// // getting the time /** * ( begin auto-generated from millis.xml ) * * Returns the number of milliseconds (thousandths of a second) since * starting an applet. This information is often used for timing animation * sequences. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p> * This is a function, rather than a variable, because it may * change multiple times per frame. * * @webref input:time_date * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ public int millis() { return (int) (System.currentTimeMillis() - millisOffset); } /** * ( begin auto-generated from second.xml ) * * Processing communicates with the clock on your computer. The * <b>second()</b> function returns the current second as a value from 0 - 59. * * ( end auto-generated ) * @webref input:time_date * @see PApplet#millis() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ static public int second() { return Calendar.getInstance().get(Calendar.SECOND); } /** * ( begin auto-generated from minute.xml ) * * Processing communicates with the clock on your computer. The * <b>minute()</b> function returns the current minute as a value from 0 - 59. * * ( end auto-generated ) * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * * */ static public int minute() { return Calendar.getInstance().get(Calendar.MINUTE); } /** * ( begin auto-generated from hour.xml ) * * Processing communicates with the clock on your computer. The * <b>hour()</b> function returns the current hour as a value from 0 - 23. * * ( end auto-generated ) * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ static public int hour() { return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * ( begin auto-generated from day.xml ) * * Processing communicates with the clock on your computer. The * <b>day()</b> function returns the current day as a value from 1 - 31. * * ( end auto-generated ) * <h3>Advanced</h3> * Get the current day of the month (1 through 31). * <p> * If you're looking for the day of the week (M-F or whatever) * or day of the year (1..365) then use java's Calendar.get() * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#month() * @see PApplet#year() */ static public int day() { return Calendar.getInstance().get(Calendar.DAY_OF_MONTH); } /** * ( begin auto-generated from month.xml ) * * Processing communicates with the clock on your computer. The * <b>month()</b> function returns the current month as a value from 1 - 12. * * ( end auto-generated ) * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#year() */ static public int month() { // months are number 0..11 so change to colloquial 1..12 return Calendar.getInstance().get(Calendar.MONTH) + 1; } /** * ( begin auto-generated from year.xml ) * * Processing communicates with the clock on your computer. The * <b>year()</b> function returns the current year as an integer (2003, * 2004, 2005, etc). * * ( end auto-generated ) * The <b>year()</b> function returns the current year as an integer (2003, 2004, 2005, etc). * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() */ static public int year() { return Calendar.getInstance().get(Calendar.YEAR); } ////////////////////////////////////////////////////////////// // controlling time (playing god) /** * The delay() function causes the program to halt for a specified time. * Delay times are specified in thousandths of a second. For example, * running delay(3000) will stop the program for three seconds and * delay(500) will stop the program for a half-second. * * The screen only updates when the end of draw() is reached, so delay() * cannot be used to slow down drawing. For instance, you cannot use delay() * to control the timing of an animation. * * The delay() function should only be used for pausing scripts (i.e. * a script that needs to pause a few seconds before attempting a download, * or a sketch that needs to wait a few milliseconds before reading from * the serial port). */ public void delay(int napTime) { //if (frameCount != 0) { //if (napTime > 0) { try { Thread.sleep(napTime); } catch (InterruptedException e) { } //} //} } /** * ( begin auto-generated from frameRate.xml ) * * Specifies the number of frames to be displayed every second. If the * processor is not fast enough to maintain the specified rate, it will not * be achieved. For example, the function call <b>frameRate(30)</b> will * attempt to refresh 30 times a second. It is recommended to set the frame * rate within <b>setup()</b>. The default rate is 60 frames per second. * * ( end auto-generated ) * @webref environment * @param fps number of desired frames per second * @see PApplet#setup() * @see PApplet#draw() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#redraw() */ public void frameRate(float fps) { frameRateTarget = fps; frameRatePeriod = (long) (1000000000.0 / frameRateTarget); g.setFrameRate(fps); } ////////////////////////////////////////////////////////////// /** * Reads the value of a param. Values are always read as a String so if you * want them to be an integer or other datatype they must be converted. The * <b>param()</b> function will only work in a web browser. The function * should be called inside <b>setup()</b>, otherwise the applet may not yet * be initialized and connected to its parent web browser. * * @param name name of the param to read * @deprecated no more applet support */ public String param(String name) { if (online) { return getParameter(name); } else { System.err.println("param() only works inside a web browser"); } return null; } /** * <h3>Advanced</h3> * Show status in the status bar of a web browser, or in the * System.out console. Eventually this might show status in the * p5 environment itself, rather than relying on the console. * * @deprecated no more applet support */ public void status(String value) { if (online) { showStatus(value); } else { System.out.println(value); // something more interesting? } } public void link(String url) { // link(url, null); try { if (Desktop.isDesktopSupported()) { Desktop.getDesktop().browse(new URI(url)); } else { // Just pass it off to open() and hope for the best open(url); } } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } /** * Links to a webpage either in the same window or in a new window. The * complete URL must be specified. * * <h3>Advanced</h3> * Link to an external page without all the muss. * <p> * When run with an applet, uses the browser to open the url, * for applications, attempts to launch a browser with the url. * <p> * Works on Mac OS X and Windows. For Linux, use: * <PRE>open(new String[] { "firefox", url });</PRE> * or whatever you want as your browser, since Linux doesn't * yet have a standard method for launching URLs. * * @param url the complete URL, as a String in quotes * @param target the name of the window in which to load the URL, as a String in quotes * @deprecated the 'target' parameter is no longer relevant with the removal of applets */ public void link(String url, String target) { link(url); /* try { if (platform == WINDOWS) { // the following uses a shell execute to launch the .html file // note that under cygwin, the .html files have to be chmodded +x // after they're unpacked from the zip file. i don't know why, // and don't understand what this does in terms of windows // permissions. without the chmod, the command prompt says // "Access is denied" in both cygwin and the "dos" prompt. //Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" + // referenceFile + ".html"); // replace ampersands with control sequence for DOS. // solution contributed by toxi on the bugs board. url = url.replaceAll("&","^&"); // open dos prompt, give it 'start' command, which will // open the url properly. start by itself won't work since // it appears to need cmd Runtime.getRuntime().exec("cmd /c start " + url); } else if (platform == MACOSX) { //com.apple.mrj.MRJFileUtils.openURL(url); try { // Class<?> mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils"); // Method openMethod = // mrjFileUtils.getMethod("openURL", new Class[] { String.class }); Class<?> eieio = Class.forName("com.apple.eio.FileManager"); Method openMethod = eieio.getMethod("openURL", new Class[] { String.class }); openMethod.invoke(null, new Object[] { url }); } catch (Exception e) { e.printStackTrace(); } } else { //throw new RuntimeException("Can't open URLs for this platform"); // Just pass it off to open() and hope for the best open(url); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not open " + url); } */ } /** * ( begin auto-generated from open.xml ) * * Attempts to open an application or file using your platform's launcher. * The <b>file</b> parameter is a String specifying the file name and * location. The location parameter must be a full path name, or the name * of an executable in the system's PATH. In most cases, using a full path * is the best option, rather than relying on the system PATH. Be sure to * make the file executable before attempting to open it (chmod +x). * <br/> <br/> * The <b>args</b> parameter is a String or String array which is passed to * the command line. If you have multiple parameters, e.g. an application * and a document, or a command with multiple switches, use the version * that takes a String array, and place each individual item in a separate * element. * <br/> <br/> * If args is a String (not an array), then it can only be a single file or * application with no parameters. It's not the same as executing that * String using a shell. For instance, open("jikes -help") will not work properly. * <br/> <br/> * This function behaves differently on each platform. On Windows, the * parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the * "open" command is used (type "man open" in Terminal.app for * documentation). On Linux, it first tries gnome-open, then kde-open, but * if neither are available, it sends the command to the shell without any * alterations. * <br/> <br/> * For users familiar with Java, this is not quite the same as * Runtime.exec(), because the launcher command is prepended. Instead, the * <b>exec(String[])</b> function is a shortcut for * Runtime.getRuntime.exec(String[]). * * ( end auto-generated ) * @webref input:files * @param filename name of the file * @usage Application */ static public void open(String filename) { open(new String[] { filename }); } static String openLauncher; /** * Launch a process using a platforms shell. This version uses an array * to make it easier to deal with spaces in the individual elements. * (This avoids the situation of trying to put single or double quotes * around different bits). * * @param argv list of commands passed to the command line */ static public Process open(String argv[]) { String[] params = null; if (platform == WINDOWS) { // just launching the .html file via the shell works // but make sure to chmod +x the .html files first // also place quotes around it in case there's a space // in the user.dir part of the url params = new String[] { "cmd", "/c" }; } else if (platform == MACOSX) { params = new String[] { "open" }; } else if (platform == LINUX) { if (openLauncher == null) { // Attempt to use gnome-open try { Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" }); /*int result =*/ p.waitFor(); // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04) openLauncher = "gnome-open"; } catch (Exception e) { } } if (openLauncher == null) { // Attempt with kde-open try { Process p = Runtime.getRuntime().exec(new String[] { "kde-open" }); /*int result =*/ p.waitFor(); openLauncher = "kde-open"; } catch (Exception e) { } } if (openLauncher == null) { System.err.println("Could not find gnome-open or kde-open, " + "the open() command may not work."); } if (openLauncher != null) { params = new String[] { openLauncher }; } //} else { // give up and just pass it to Runtime.exec() //open(new String[] { filename }); //params = new String[] { filename }; } if (params != null) { // If the 'open', 'gnome-open' or 'cmd' are already included if (params[0].equals(argv[0])) { // then don't prepend those params again return exec(argv); } else { params = concat(params, argv); return exec(params); } } else { return exec(argv); } } static public Process exec(String[] argv) { try { return Runtime.getRuntime().exec(argv); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not open " + join(argv, ' ')); } } ////////////////////////////////////////////////////////////// /** * Function for an applet/application to kill itself and * display an error. Mostly this is here to be improved later. */ public void die(String what) { dispose(); throw new RuntimeException(what); } /** * Same as above but with an exception. Also needs work. */ public void die(String what, Exception e) { if (e != null) e.printStackTrace(); die(what); } /** * ( begin auto-generated from exit.xml ) * * Quits/stops/exits the program. Programs without a <b>draw()</b> function * exit automatically after the last line has run, but programs with * <b>draw()</b> run continuously until the program is manually stopped or * <b>exit()</b> is run.<br /> * <br /> * Rather than terminating immediately, <b>exit()</b> will cause the sketch * to exit after <b>draw()</b> has completed (or after <b>setup()</b> * completes if called during the <b>setup()</b> function).<br /> * <br /> * For Java programmers, this is <em>not</em> the same as System.exit(). * Further, System.exit() should not be used because closing out an * application while <b>draw()</b> is running may cause a crash * (particularly with P3D). * * ( end auto-generated ) * @webref structure */ public void exit() { if (thread == null) { // exit immediately, dispose() has already been called, // meaning that the main thread has long since exited exitActual(); } else if (looping) { // dispose() will be called as the thread exits finished = true; // tell the code to call exit2() to do a System.exit() // once the next draw() has completed exitCalled = true; } else if (!looping) { // if not looping, shut down things explicitly, // because the main thread will be sleeping dispose(); // now get out exitActual(); } } void exitActual() { try { System.exit(0); } catch (SecurityException e) { // don't care about applet security exceptions } } /** * Called to dispose of resources and shut down the sketch. * Destroys the thread, dispose the renderer,and notify listeners. * <p> * Not to be called or overriden by users. If called multiple times, * will only notify listeners once. Register a dispose listener instead. */ public void dispose() { // moved here from stop() finished = true; // let the sketch know it is shut down time // don't run the disposers twice if (thread != null) { thread = null; // shut down renderer if (g != null) { g.dispose(); } // run dispose() methods registered by libraries handleMethods("dispose"); } } ////////////////////////////////////////////////////////////// /** * Call a method in the current class based on its name. * <p/> * Note that the function being called must be public. Inside the PDE, * 'public' is automatically added, but when used without the preprocessor, * (like from Eclipse) you'll have to do it yourself. */ public void method(String name) { try { Method method = getClass().getMethod(name, new Class[] {}); method.invoke(this, new Object[] { }); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println("There is no public " + name + "() method " + "in the class " + getClass().getName()); } catch (Exception e) { e.printStackTrace(); } } /** * Launch a new thread and call the specified function from that new thread. * This is a very simple way to do a thread without needing to get into * classes, runnables, etc. * <p/> * Note that the function being called must be public. Inside the PDE, * 'public' is automatically added, but when used without the preprocessor, * (like from Eclipse) you'll have to do it yourself. */ public void thread(final String name) { Thread later = new Thread() { @Override public void run() { method(name); } }; later.start(); } ////////////////////////////////////////////////////////////// // SCREEN GRABASS /** * ( begin auto-generated from save.xml ) * * Saves an image from the display window. Images are saved in TIFF, TARGA, * JPEG, and PNG format depending on the extension within the * <b>filename</b> parameter. For example, "image.tif" will have a TIFF * image and "image.png" will save a PNG image. If no extension is included * in the filename, the image will save in TIFF format and <b>.tif</b> will * be added to the name. These files are saved to the sketch's folder, * which may be opened by selecting "Show sketch folder" from the "Sketch" * menu. It is not possible to use <b>save()</b> while running the program * in a web browser. * <br/> images saved from the main drawing window will be opaque. To save * images without a background, use <b>createGraphics()</b>. * * ( end auto-generated ) * @webref output:image * @param filename any sequence of letters and numbers * @see PApplet#saveFrame() * @see PApplet#createGraphics(int, int, String) */ public void save(String filename) { g.save(savePath(filename)); } /** */ public void saveFrame() { try { g.save(savePath("screen-" + nf(frameCount, 4) + ".tif")); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * ( begin auto-generated from saveFrame.xml ) * * Saves a numbered sequence of images, one image each time the function is * run. To save an image that is identical to the display window, run the * function at the end of <b>draw()</b> or within mouse and key events such * as <b>mousePressed()</b> and <b>keyPressed()</b>. If <b>saveFrame()</b> * is called without parameters, it will save the files as screen-0000.tif, * screen-0001.tif, etc. It is possible to specify the name of the sequence * with the <b>filename</b> parameter and make the choice of saving TIFF, * TARGA, PNG, or JPEG files with the <b>ext</b> parameter. These image * sequences can be loaded into programs such as Apple's QuickTime software * and made into movies. These files are saved to the sketch's folder, * which may be opened by selecting "Show sketch folder" from the "Sketch" * menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * All images saved from the main drawing window will be opaque. To save * images without a background, use <b>createGraphics()</b>. * * ( end auto-generated ) * @webref output:image * @see PApplet#save(String) * @see PApplet#createGraphics(int, int, String, String) * @param filename any sequence of letters or numbers that ends with either ".tif", ".tga", ".jpg", or ".png" */ public void saveFrame(String filename) { try { g.save(savePath(insertFrame(filename))); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * Check a string for #### signs to see if the frame number should be * inserted. Used for functions like saveFrame() and beginRecord() to * replace the # marks with the frame number. If only one # is used, * it will be ignored, under the assumption that it's probably not * intended to be the frame number. */ public String insertFrame(String what) { int first = what.indexOf('#'); int last = what.lastIndexOf('#'); if ((first != -1) && (last - first > 0)) { String prefix = what.substring(0, first); int count = last - first + 1; String suffix = what.substring(last + 1); return prefix + nf(frameCount, count) + suffix; } return what; // no change } ////////////////////////////////////////////////////////////// // CURSOR // int cursorType = ARROW; // cursor type boolean cursorVisible = true; // cursor visibility flag // PImage invisibleCursor; Cursor invisibleCursor; /** * Set the cursor type * @param kind either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT */ public void cursor(int kind) { setCursor(Cursor.getPredefinedCursor(kind)); cursorVisible = true; this.cursorType = kind; } /** * Replace the cursor with the specified PImage. The x- and y- * coordinate of the center will be the center of the image. */ public void cursor(PImage img) { cursor(img, img.width/2, img.height/2); } /** * ( begin auto-generated from cursor.xml ) * * Sets the cursor to a predefined symbol, an image, or makes it visible if * already hidden. If you are trying to set an image as the cursor, it is * recommended to make the size 16x16 or 32x32 pixels. It is not possible * to load an image as the cursor if you are exporting your program for the * Web and not all MODES work with all Web browsers. The values for * parameters <b>x</b> and <b>y</b> must be less than the dimensions of the image. * <br /> <br /> * Setting or hiding the cursor generally does not work with "Present" mode * (when running full-screen). * * ( end auto-generated ) * <h3>Advanced</h3> * Set a custom cursor to an image with a specific hotspot. * Only works with JDK 1.2 and later. * Currently seems to be broken on Java 1.4 for Mac OS X * <p> * Based on code contributed by Amit Pitaru, plus additional * code to handle Java versions via reflection by Jonathan Feinberg. * Reflection removed for release 0128 and later. * @webref environment * @see PApplet#noCursor() * @param img any variable of type PImage * @param x the horizontal active spot of the cursor * @param y the vertical active spot of the cursor */ public void cursor(PImage img, int x, int y) { // don't set this as cursor type, instead use cursor_type // to save the last cursor used in case cursor() is called //cursor_type = Cursor.CUSTOM_CURSOR; Image jimage = createImage(new MemoryImageSource(img.width, img.height, img.pixels, 0, img.width)); Point hotspot = new Point(x, y); Toolkit tk = Toolkit.getDefaultToolkit(); Cursor cursor = tk.createCustomCursor(jimage, hotspot, "Custom Cursor"); setCursor(cursor); cursorVisible = true; } /** * Show the cursor after noCursor() was called. * Notice that the program remembers the last set cursor type */ public void cursor() { // maybe should always set here? seems dangerous, since // it's likely that java will set the cursor to something // else on its own, and the applet will be stuck b/c bagel // thinks that the cursor is set to one particular thing if (!cursorVisible) { cursorVisible = true; setCursor(Cursor.getPredefinedCursor(cursorType)); } } /** * ( begin auto-generated from noCursor.xml ) * * Hides the cursor from view. Will not work when running the program in a * web browser or when running in full screen (Present) mode. * * ( end auto-generated ) * <h3>Advanced</h3> * Hide the cursor by creating a transparent image * and using it as a custom cursor. * @webref environment * @see PApplet#cursor() * @usage Application */ public void noCursor() { // in 0216, just re-hide it? // if (!cursorVisible) return; // don't hide if already hidden. if (invisibleCursor == null) { BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); invisibleCursor = getToolkit().createCustomCursor(cursorImg, new Point(8, 8), "blank"); } // was formerly 16x16, but the 0x0 was added by jdf as a fix // for macosx, which wasn't honoring the invisible cursor // cursor(invisibleCursor, 8, 8); setCursor(invisibleCursor); cursorVisible = false; } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from print.xml ) * * Writes to the console area of the Processing environment. This is often * helpful for looking at the data a program is producing. The companion * function <b>println()</b> works like <b>print()</b>, but creates a new * line of text for each call to the function. Individual elements can be * separated with quotes ("") and joined with the addition operator (+).<br /> * <br /> * Beginning with release 0125, to print the contents of an array, use * println(). There's no sensible way to do a <b>print()</b> of an array, * because there are too many possibilities for how to separate the data * (spaces, commas, etc). If you want to print an array as a single line, * use <b>join()</b>. With <b>join()</b>, you can choose any delimiter you * like and <b>print()</b> the result.<br /> * <br /> * Using <b>print()</b> on an object will output <b>null</b>, a memory * location that may look like "@10be08," or the result of the * <b>toString()</b> method from the object that's being printed. Advanced * users who want more useful output when calling <b>print()</b> on their * own classes can add a <b>toString()</b> method to the class that returns * a String. * * ( end auto-generated ) * @webref output:text_area * @usage IDE * @param what data to print to console * @see PApplet#println() * @see PApplet#printArray(Object) * @see PApplet#join(String[], char) */ static public void print(byte what) { System.out.print(what); System.out.flush(); } static public void print(boolean what) { System.out.print(what); System.out.flush(); } static public void print(char what) { System.out.print(what); System.out.flush(); } static public void print(int what) { System.out.print(what); System.out.flush(); } static public void print(long what) { System.out.print(what); System.out.flush(); } static public void print(float what) { System.out.print(what); System.out.flush(); } static public void print(double what) { System.out.print(what); System.out.flush(); } static public void print(String what) { System.out.print(what); System.out.flush(); } /** * @param variables list of data, separated by commas */ static public void print(Object... variables) { StringBuilder sb = new StringBuilder(); for (Object o : variables) { if (sb.length() != 0) { sb.append(" "); } if (o == null) { sb.append("null"); } else { sb.append(o.toString()); } } System.out.print(sb.toString()); } /* static public void print(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.print("null"); } else { System.out.println(what.toString()); } } */ /** * ( begin auto-generated from println.xml ) * * Writes to the text area of the Processing environment's console. This is * often helpful for looking at the data a program is producing. Each call * to this function creates a new line of output. Individual elements can * be separated with quotes ("") and joined with the string concatenation * operator (+). See <b>print()</b> for more about what to expect in the output. * <br/><br/> <b>println()</b> on an array (by itself) will write the * contents of the array to the console. This is often helpful for looking * at the data a program is producing. A new line is put between each * element of the array. This function can only print one dimensional * arrays. For arrays with higher dimensions, the result will be closer to * that of <b>print()</b>. * * ( end auto-generated ) * @webref output:text_area * @usage IDE * @see PApplet#print(byte) * @see PApplet#printArray(Object) */ static public void println() { System.out.println(); } /** * @param what data to print to console */ static public void println(byte what) { System.out.println(what); System.out.flush(); } static public void println(boolean what) { System.out.println(what); System.out.flush(); } static public void println(char what) { System.out.println(what); System.out.flush(); } static public void println(int what) { System.out.println(what); System.out.flush(); } static public void println(long what) { System.out.println(what); System.out.flush(); } static public void println(float what) { System.out.println(what); System.out.flush(); } static public void println(double what) { System.out.println(what); System.out.flush(); } static public void println(String what) { System.out.println(what); System.out.flush(); } /** * @param variables list of data, separated by commas */ static public void println(Object... variables) { // System.out.println("got " + variables.length + " variables"); print(variables); println(); } /* // Breaking this out since the compiler doesn't know the difference between // Object... and just Object (with an array passed in). This should take care // of the confusion for at least the most common case (a String array). // On second thought, we're going the printArray() route, since the other // object types are also used frequently. static public void println(String[] array) { for (int i = 0; i < array.length; i++) { System.out.println("[" + i + "] \"" + array[i] + "\""); } System.out.flush(); } */ /** * For arrays, use printArray() instead. This function causes a warning * because the new print(Object...) and println(Object...) functions can't * be reliably bound by the compiler. */ static public void println(Object what) { if (what != null && what.getClass().isArray()) { printArray(what); } else { System.out.println(what.toString()); System.out.flush(); } } /** * ( begin auto-generated from printArray.xml ) * * To come... * * ( end auto-generated ) * @webref output:text_area * @param what one-dimensional array * @usage IDE * @see PApplet#print(byte) * @see PApplet#println() */ static public void printArray(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.println("null"); } else { String name = what.getClass().getName(); if (name.charAt(0) == '[') { switch (name.charAt(1)) { case '[': // don't even mess with multi-dimensional arrays (case '[') // or anything else that's not int, float, boolean, char System.out.println(what); break; case 'L': // print a 1D array of objects as individual elements Object poo[] = (Object[]) what; for (int i = 0; i < poo.length; i++) { if (poo[i] instanceof String) { System.out.println("[" + i + "] \"" + poo[i] + "\""); } else { System.out.println("[" + i + "] " + poo[i]); } } break; case 'Z': // boolean boolean zz[] = (boolean[]) what; for (int i = 0; i < zz.length; i++) { System.out.println("[" + i + "] " + zz[i]); } break; case 'B': // byte byte bb[] = (byte[]) what; for (int i = 0; i < bb.length; i++) { System.out.println("[" + i + "] " + bb[i]); } break; case 'C': // char char cc[] = (char[]) what; for (int i = 0; i < cc.length; i++) { System.out.println("[" + i + "] '" + cc[i] + "'"); } break; case 'I': // int int ii[] = (int[]) what; for (int i = 0; i < ii.length; i++) { System.out.println("[" + i + "] " + ii[i]); } break; case 'J': // int long jj[] = (long[]) what; for (int i = 0; i < jj.length; i++) { System.out.println("[" + i + "] " + jj[i]); } break; case 'F': // float float ff[] = (float[]) what; for (int i = 0; i < ff.length; i++) { System.out.println("[" + i + "] " + ff[i]); } break; case 'D': // double double dd[] = (double[]) what; for (int i = 0; i < dd.length; i++) { System.out.println("[" + i + "] " + dd[i]); } break; default: System.out.println(what); } } else { // not an array System.out.println(what); } } } static public void debug(String msg) { if (DEBUG) println(msg); } // /* // not very useful, because it only works for public (and protected?) // fields of a class, not local variables to methods public void printvar(String name) { try { Field field = getClass().getDeclaredField(name); println(name + " = " + field.get(this)); } catch (Exception e) { e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// // MATH // lots of convenience methods for math with floats. // doubles are overkill for processing applets, and casting // things all the time is annoying, thus the functions below. /** * ( begin auto-generated from abs.xml ) * * Calculates the absolute value (magnitude) of a number. The absolute * value of a number is always positive. * * ( end auto-generated ) * @webref math:calculation * @param n number to compute */ static public final float abs(float n) { return (n < 0) ? -n : n; } static public final int abs(int n) { return (n < 0) ? -n : n; } /** * ( begin auto-generated from sq.xml ) * * Squares a number (multiplies a number by itself). The result is always a * positive number, as multiplying two negative numbers always yields a * positive result. For example, -1 * -1 = 1. * * ( end auto-generated ) * @webref math:calculation * @param n number to square * @see PApplet#sqrt(float) */ static public final float sq(float n) { return n*n; } /** * ( begin auto-generated from sqrt.xml ) * * Calculates the square root of a number. The square root of a number is * always positive, even though there may be a valid negative root. The * square root <b>s</b> of number <b>a</b> is such that <b>s*s = a</b>. It * is the opposite of squaring. * * ( end auto-generated ) * @webref math:calculation * @param n non-negative number * @see PApplet#pow(float, float) * @see PApplet#sq(float) */ static public final float sqrt(float n) { return (float)Math.sqrt(n); } /** * ( begin auto-generated from log.xml ) * * Calculates the natural logarithm (the base-<i>e</i> logarithm) of a * number. This function expects the values greater than 0.0. * * ( end auto-generated ) * @webref math:calculation * @param n number greater than 0.0 */ static public final float log(float n) { return (float)Math.log(n); } /** * ( begin auto-generated from exp.xml ) * * Returns Euler's number <i>e</i> (2.71828...) raised to the power of the * <b>value</b> parameter. * * ( end auto-generated ) * @webref math:calculation * @param n exponent to raise */ static public final float exp(float n) { return (float)Math.exp(n); } /** * ( begin auto-generated from pow.xml ) * * Facilitates exponential expressions. The <b>pow()</b> function is an * efficient way of multiplying numbers by themselves (or their reciprocal) * in large quantities. For example, <b>pow(3, 5)</b> is equivalent to the * expression 3*3*3*3*3 and <b>pow(3, -5)</b> is equivalent to 1 / 3*3*3*3*3. * * ( end auto-generated ) * @webref math:calculation * @param n base of the exponential expression * @param e power by which to raise the base * @see PApplet#sqrt(float) */ static public final float pow(float n, float e) { return (float)Math.pow(n, e); } /** * ( begin auto-generated from max.xml ) * * Determines the largest value in a sequence of numbers. * * ( end auto-generated ) * @webref math:calculation * @param a first number to compare * @param b second number to compare * @see PApplet#min(float, float, float) */ static public final int max(int a, int b) { return (a > b) ? a : b; } static public final float max(float a, float b) { return (a > b) ? a : b; } /* static public final double max(double a, double b) { return (a > b) ? a : b; } */ /** * @param c third number to compare */ static public final int max(int a, int b, int c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } static public final float max(float a, float b, float c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } /** * @param list array of numbers to compare */ static public final int max(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } static public final float max(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } /** * Find the maximum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The maximum value */ /* static public final double max(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } */ static public final int min(int a, int b) { return (a < b) ? a : b; } static public final float min(float a, float b) { return (a < b) ? a : b; } /* static public final double min(double a, double b) { return (a < b) ? a : b; } */ static public final int min(int a, int b, int c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /** * ( begin auto-generated from min.xml ) * * Determines the smallest value in a sequence of numbers. * * ( end auto-generated ) * @webref math:calculation * @param a first number * @param b second number * @param c third number * @see PApplet#max(float, float, float) */ static public final float min(float a, float b, float c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /* static public final double min(double a, double b, double c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } */ /** * @param list array of numbers to compare */ static public final int min(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } static public final float min(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } /** * Find the minimum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The minimum value */ /* static public final double min(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } */ static public final int constrain(int amt, int low, int high) { return (amt < low) ? low : ((amt > high) ? high : amt); } /** * ( begin auto-generated from constrain.xml ) * * Constrains a value to not exceed a maximum and minimum value. * * ( end auto-generated ) * @webref math:calculation * @param amt the value to constrain * @param low minimum limit * @param high maximum limit * @see PApplet#max(float, float, float) * @see PApplet#min(float, float, float) */ static public final float constrain(float amt, float low, float high) { return (amt < low) ? low : ((amt > high) ? high : amt); } /** * ( begin auto-generated from sin.xml ) * * Calculates the sine of an angle. This function expects the values of the * <b>angle</b> parameter to be provided in radians (values from 0 to * 6.28). Values are returned in the range -1 to 1. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#cos(float) * @see PApplet#tan(float) * @see PApplet#radians(float) */ static public final float sin(float angle) { return (float)Math.sin(angle); } /** * ( begin auto-generated from cos.xml ) * * Calculates the cosine of an angle. This function expects the values of * the <b>angle</b> parameter to be provided in radians (values from 0 to * PI*2). Values are returned in the range -1 to 1. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#sin(float) * @see PApplet#tan(float) * @see PApplet#radians(float) */ static public final float cos(float angle) { return (float)Math.cos(angle); } /** * ( begin auto-generated from tan.xml ) * * Calculates the ratio of the sine and cosine of an angle. This function * expects the values of the <b>angle</b> parameter to be provided in * radians (values from 0 to PI*2). Values are returned in the range * <b>infinity</b> to <b>-infinity</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#cos(float) * @see PApplet#sin(float) * @see PApplet#radians(float) */ static public final float tan(float angle) { return (float)Math.tan(angle); } /** * ( begin auto-generated from asin.xml ) * * The inverse of <b>sin()</b>, returns the arc sine of a value. This * function expects the values in the range of -1 to 1 and values are * returned in the range <b>-PI/2</b> to <b>PI/2</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value the value whose arc sine is to be returned * @see PApplet#sin(float) * @see PApplet#acos(float) * @see PApplet#atan(float) */ static public final float asin(float value) { return (float)Math.asin(value); } /** * ( begin auto-generated from acos.xml ) * * The inverse of <b>cos()</b>, returns the arc cosine of a value. This * function expects the values in the range of -1 to 1 and values are * returned in the range <b>0</b> to <b>PI (3.1415927)</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value the value whose arc cosine is to be returned * @see PApplet#cos(float) * @see PApplet#asin(float) * @see PApplet#atan(float) */ static public final float acos(float value) { return (float)Math.acos(value); } /** * ( begin auto-generated from atan.xml ) * * The inverse of <b>tan()</b>, returns the arc tangent of a value. This * function expects the values in the range of -Infinity to Infinity * (exclusive) and values are returned in the range <b>-PI/2</b> to <b>PI/2 </b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value -Infinity to Infinity (exclusive) * @see PApplet#tan(float) * @see PApplet#asin(float) * @see PApplet#acos(float) */ static public final float atan(float value) { return (float)Math.atan(value); } /** * ( begin auto-generated from atan2.xml ) * * Calculates the angle (in radians) from a specified point to the * coordinate origin as measured from the positive x-axis. Values are * returned as a <b>float</b> in the range from <b>PI</b> to <b>-PI</b>. * The <b>atan2()</b> function is most often used for orienting geometry to * the position of the cursor. Note: The y-coordinate of the point is the * first parameter and the x-coordinate is the second due the the structure * of calculating the tangent. * * ( end auto-generated ) * @webref math:trigonometry * @param y y-coordinate of the point * @param x x-coordinate of the point * @see PApplet#tan(float) */ static public final float atan2(float y, float x) { return (float)Math.atan2(y, x); } /** * ( begin auto-generated from degrees.xml ) * * Converts a radian measurement to its corresponding value in degrees. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90&deg; = PI/2 = 1.5707964. All trigonometric functions in Processing * require their parameters to be specified in radians. * * ( end auto-generated ) * @webref math:trigonometry * @param radians radian value to convert to degrees * @see PApplet#radians(float) */ static public final float degrees(float radians) { return radians * RAD_TO_DEG; } /** * ( begin auto-generated from radians.xml ) * * Converts a degree measurement to its corresponding value in radians. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90&deg; = PI/2 = 1.5707964. All trigonometric functions in Processing * require their parameters to be specified in radians. * * ( end auto-generated ) * @webref math:trigonometry * @param degrees degree value to convert to radians * @see PApplet#degrees(float) */ static public final float radians(float degrees) { return degrees * DEG_TO_RAD; } /** * ( begin auto-generated from ceil.xml ) * * Calculates the closest int value that is greater than or equal to the * value of the parameter. For example, <b>ceil(9.03)</b> returns the value 10. * * ( end auto-generated ) * @webref math:calculation * @param n number to round up * @see PApplet#floor(float) * @see PApplet#round(float) */ static public final int ceil(float n) { return (int) Math.ceil(n); } /** * ( begin auto-generated from floor.xml ) * * Calculates the closest int value that is less than or equal to the value * of the parameter. * * ( end auto-generated ) * @webref math:calculation * @param n number to round down * @see PApplet#ceil(float) * @see PApplet#round(float) */ static public final int floor(float n) { return (int) Math.floor(n); } /** * ( begin auto-generated from round.xml ) * * Calculates the integer closest to the <b>value</b> parameter. For * example, <b>round(9.2)</b> returns the value 9. * * ( end auto-generated ) * @webref math:calculation * @param n number to round * @see PApplet#floor(float) * @see PApplet#ceil(float) */ static public final int round(float n) { return Math.round(n); } static public final float mag(float a, float b) { return (float)Math.sqrt(a*a + b*b); } /** * ( begin auto-generated from mag.xml ) * * Calculates the magnitude (or length) of a vector. A vector is a * direction in space commonly used in computer graphics and linear * algebra. Because it has no "start" position, the magnitude of a vector * can be thought of as the distance from coordinate (0,0) to its (x,y) * value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)". * * ( end auto-generated ) * @webref math:calculation * @param a first value * @param b second value * @param c third value * @see PApplet#dist(float, float, float, float) */ static public final float mag(float a, float b, float c) { return (float)Math.sqrt(a*a + b*b + c*c); } static public final float dist(float x1, float y1, float x2, float y2) { return sqrt(sq(x2-x1) + sq(y2-y1)); } /** * ( begin auto-generated from dist.xml ) * * Calculates the distance between two points. * * ( end auto-generated ) * @webref math:calculation * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param z1 z-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param z2 z-coordinate of the second point */ static public final float dist(float x1, float y1, float z1, float x2, float y2, float z2) { return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1)); } /** * ( begin auto-generated from lerp.xml ) * * Calculates a number between two numbers at a specific increment. The * <b>amt</b> parameter is the amount to interpolate between the two values * where 0.0 equal to the first point, 0.1 is very near the first point, * 0.5 is half-way in between, etc. The lerp function is convenient for * creating motion along a straight path and for drawing dotted lines. * * ( end auto-generated ) * @webref math:calculation * @param start first value * @param stop second value * @param amt float between 0.0 and 1.0 * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ static public final float lerp(float start, float stop, float amt) { return start + (stop-start) * amt; } /** * ( begin auto-generated from norm.xml ) * * Normalizes a number from another range into a value between 0 and 1. * <br/> <br/> * Identical to map(value, low, high, 0, 1); * <br/> <br/> * Numbers outside the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. * * ( end auto-generated ) * @webref math:calculation * @param value the incoming value to be converted * @param start lower bound of the value's current range * @param stop upper bound of the value's current range * @see PApplet#map(float, float, float, float, float) * @see PApplet#lerp(float, float, float) */ static public final float norm(float value, float start, float stop) { return (value - start) / (stop - start); } /** * ( begin auto-generated from map.xml ) * * Re-maps a number from one range to another. In the example above, * the number '25' is converted from a value in the range 0..100 into * a value that ranges from the left edge (0) to the right edge (width) * of the screen. * <br/> <br/> * Numbers outside the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. * * ( end auto-generated ) * @webref math:calculation * @param value the incoming value to be converted * @param start1 lower bound of the value's current range * @param stop1 upper bound of the value's current range * @param start2 lower bound of the value's target range * @param stop2 upper bound of the value's target range * @see PApplet#norm(float, float, float) * @see PApplet#lerp(float, float, float) */ static public final float map(float value, float start1, float stop1, float start2, float stop2) { return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1)); } /* static public final double map(double value, double istart, double istop, double ostart, double ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } */ ////////////////////////////////////////////////////////////// // RANDOM NUMBERS Random internalRandom; /** * */ public final float random(float high) { // avoid an infinite loop when 0 or NaN are passed in if (high == 0 || high != high) { return 0; } if (internalRandom == null) { internalRandom = new Random(); } // for some reason (rounding error?) Math.random() * 3 // can sometimes return '3' (once in ~30 million tries) // so a check was added to avoid the inclusion of 'howbig' float value = 0; do { value = internalRandom.nextFloat() * high; } while (value == high); return value; } /** * ( begin auto-generated from randomGaussian.xml ) * * Returns a float from a random series of numbers having a mean of 0 * and standard deviation of 1. Each time the <b>randomGaussian()</b> * function is called, it returns a number fitting a Gaussian, or * normal, distribution. There is theoretically no minimum or maximum * value that <b>randomGaussian()</b> might return. Rather, there is * just a very low probability that values far from the mean will be * returned; and a higher probability that numbers near the mean will * be returned. * * ( end auto-generated ) * @webref math:random * @see PApplet#random(float,float) * @see PApplet#noise(float, float, float) */ public final float randomGaussian() { if (internalRandom == null) { internalRandom = new Random(); } return (float) internalRandom.nextGaussian(); } /** * ( begin auto-generated from random.xml ) * * Generates random numbers. Each time the <b>random()</b> function is * called, it returns an unexpected value within the specified range. If * one parameter is passed to the function it will return a <b>float</b> * between zero and the value of the <b>high</b> parameter. The function * call <b>random(5)</b> returns values between 0 and 5 (starting at zero, * up to but not including 5). If two parameters are passed, it will return * a <b>float</b> with a value between the the parameters. The function * call <b>random(-5, 10.2)</b> returns values starting at -5 up to (but * not including) 10.2. To convert a floating-point random number to an * integer, use the <b>int()</b> function. * * ( end auto-generated ) * @webref math:random * @param low lower limit * @param high upper limit * @see PApplet#randomSeed(long) * @see PApplet#noise(float, float, float) */ public final float random(float low, float high) { if (low >= high) return low; float diff = high - low; return random(diff) + low; } /** * ( begin auto-generated from randomSeed.xml ) * * Sets the seed value for <b>random()</b>. By default, <b>random()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param seed seed value * @see PApplet#random(float,float) * @see PApplet#noise(float, float, float) * @see PApplet#noiseSeed(long) */ public final void randomSeed(long seed) { if (internalRandom == null) { internalRandom = new Random(); } internalRandom.setSeed(seed); } ////////////////////////////////////////////////////////////// // PERLIN NOISE // [toxi 040903] // octaves and amplitude amount per octave are now user controlled // via the noiseDetail() function. // [toxi 030902] // cleaned up code and now using bagel's cosine table to speed up // [toxi 030901] // implementation by the german demo group farbrausch // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip static final int PERLIN_YWRAPB = 4; static final int PERLIN_YWRAP = 1<<PERLIN_YWRAPB; static final int PERLIN_ZWRAPB = 8; static final int PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB; static final int PERLIN_SIZE = 4095; int perlin_octaves = 4; // default to medium smooth float perlin_amp_falloff = 0.5f; // 50% reduction/octave // [toxi 031112] // new vars needed due to recent change of cos table in PGraphics int perlin_TWOPI, perlin_PI; float[] perlin_cosTable; float[] perlin; Random perlinRandom; /** */ public float noise(float x) { // is this legit? it's a dumb way to do it (but repair it later) return noise(x, 0f, 0f); } /** */ public float noise(float x, float y) { return noise(x, y, 0f); } /** * ( begin auto-generated from noise.xml ) * * Returns the Perlin noise value at specified coordinates. Perlin noise is * a random sequence generator producing a more natural ordered, harmonic * succession of numbers compared to the standard <b>random()</b> function. * It was invented by Ken Perlin in the 1980s and been used since in * graphical applications to produce procedural textures, natural motion, * shapes, terrains etc.<br /><br /> The main difference to the * <b>random()</b> function is that Perlin noise is defined in an infinite * n-dimensional space where each pair of coordinates corresponds to a * fixed semi-random value (fixed only for the lifespan of the program). * The resulting value will always be between 0.0 and 1.0. Processing can * compute 1D, 2D and 3D noise, depending on the number of coordinates * given. The noise value can be animated by moving through the noise space * as demonstrated in the example above. The 2nd and 3rd dimension can also * be interpreted as time.<br /><br />The actual noise is structured * similar to an audio signal, in respect to the function's use of * frequencies. Similar to the concept of harmonics in physics, perlin * noise is computed over several octaves which are added together for the * final result. <br /><br />Another way to adjust the character of the * resulting sequence is the scale of the input coordinates. As the * function works within an infinite space the value of the coordinates * doesn't matter as such, only the distance between successive coordinates * does (eg. when using <b>noise()</b> within a loop). As a general rule * the smaller the difference between coordinates, the smoother the * resulting noise sequence will be. Steps of 0.005-0.03 work best for most * applications, but this will differ depending on use. * * ( end auto-generated ) * * @webref math:random * @param x x-coordinate in noise space * @param y y-coordinate in noise space * @param z z-coordinate in noise space * @see PApplet#noiseSeed(long) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) */ public float noise(float x, float y, float z) { if (perlin == null) { if (perlinRandom == null) { perlinRandom = new Random(); } perlin = new float[PERLIN_SIZE + 1]; for (int i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = perlinRandom.nextFloat(); //(float)Math.random(); } // [toxi 031112] // noise broke due to recent change of cos table in PGraphics // this will take care of it perlin_cosTable = PGraphics.cosLUT; perlin_TWOPI = perlin_PI = PGraphics.SINCOS_LENGTH; perlin_PI >>= 1; } if (x<0) x=-x; if (y<0) y=-y; if (z<0) z=-z; int xi=(int)x, yi=(int)y, zi=(int)z; float xf = x - xi; float yf = y - yi; float zf = z - zi; float rxf, ryf; float r=0; float ampl=0.5f; float n1,n2,n3; for (int i=0; i<perlin_octaves; i++) { int of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB); rxf=noise_fsc(xf); ryf=noise_fsc(yf); n1 = perlin[of&PERLIN_SIZE]; n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1); n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2); n1 += ryf*(n2-n1); of += PERLIN_ZWRAP; n2 = perlin[of&PERLIN_SIZE]; n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2); n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3); n2 += ryf*(n3-n2); n1 += noise_fsc(zf)*(n2-n1); r += n1*ampl; ampl *= perlin_amp_falloff; xi<<=1; xf*=2; yi<<=1; yf*=2; zi<<=1; zf*=2; if (xf>=1.0f) { xi++; xf--; } if (yf>=1.0f) { yi++; yf--; } if (zf>=1.0f) { zi++; zf--; } } return r; } // [toxi 031112] // now adjusts to the size of the cosLUT used via // the new variables, defined above private float noise_fsc(float i) { // using bagel's cosine table instead return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]); } // [toxi 040903] // make perlin noise quality user controlled to allow // for different levels of detail. lower values will produce // smoother results as higher octaves are surpressed /** * ( begin auto-generated from noiseDetail.xml ) * * Adjusts the character and level of detail produced by the Perlin noise * function. Similar to harmonics in physics, noise is computed over * several octaves. Lower octaves contribute more to the output signal and * as such define the overal intensity of the noise, whereas higher octaves * create finer grained details in the noise sequence. By default, noise is * computed over 4 octaves with each octave contributing exactly half than * its predecessor, starting at 50% strength for the 1st octave. This * falloff amount can be changed by adding an additional function * parameter. Eg. a falloff factor of 0.75 means each octave will now have * 75% impact (25% less) of the previous lower octave. Any value between * 0.0 and 1.0 is valid, however note that values greater than 0.5 might * result in greater than 1.0 values returned by <b>noise()</b>.<br /><br * />By changing these parameters, the signal created by the <b>noise()</b> * function can be adapted to fit very specific needs and characteristics. * * ( end auto-generated ) * @webref math:random * @param lod number of octaves to be used by the noise * @param falloff falloff factor for each octave * @see PApplet#noise(float, float, float) */ public void noiseDetail(int lod) { if (lod>0) perlin_octaves=lod; } /** * @param falloff falloff factor for each octave */ public void noiseDetail(int lod, float falloff) { if (lod>0) perlin_octaves=lod; if (falloff>0) perlin_amp_falloff=falloff; } /** * ( begin auto-generated from noiseSeed.xml ) * * Sets the seed value for <b>noise()</b>. By default, <b>noise()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param seed seed value * @see PApplet#noise(float, float, float) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) * @see PApplet#randomSeed(long) */ public void noiseSeed(long seed) { if (perlinRandom == null) perlinRandom = new Random(); perlinRandom.setSeed(seed); // force table reset after changing the random number seed [0122] perlin = null; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . protected String[] loadImageFormats; /** * ( begin auto-generated from loadImage.xml ) * * Loads an image into a variable of type <b>PImage</b>. Four types of * images ( <b>.gif</b>, <b>.jpg</b>, <b>.tga</b>, <b>.png</b>) images may * be loaded. To load correctly, images must be located in the data * directory of the current sketch. In most cases, load all images in * <b>setup()</b> to preload them at the start of the program. Loading * images inside <b>draw()</b> will reduce the speed of a program.<br/> * <br/> <b>filename</b> parameter can also be a URL to a file found * online. For security reasons, a Processing sketch found online can only * download files from the same server from which it came. Getting around * this restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed * applet</a>.<br/> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>loadImage()</b>, as * shown in the third example on this page.<br/> * <br/> an image is not loaded successfully, the <b>null</b> value is * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned from <b>loadImage()</b> is null.<br/> * <br/> on the type of error, a <b>PImage</b> object may still be * returned, but the width and height of the image will be set to -1. This * happens if bad image data is returned or cannot be decoded properly. * Sometimes this happens with image URLs that produce a 403 error or that * redirect to a password prompt, because <b>loadImage()</b> will attempt * to interpret the HTML as image data. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#imageMode(int) * @see PGraphics#background(float, float, float, float) */ public PImage loadImage(String filename) { // return loadImage(filename, null, null); return loadImage(filename, null); } // /** // * @param extension the type of image to load, for example "png", "gif", "jpg" // */ // public PImage loadImage(String filename, String extension) { // return loadImage(filename, extension, null); // } // /** // * @nowebref // */ // public PImage loadImage(String filename, Object params) { // return loadImage(filename, null, params); // } /** * @param extension type of image to load, for example "png", "gif", "jpg" */ public PImage loadImage(String filename, String extension) { //, Object params) { if (extension == null) { String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } } // just in case. them users will try anything! extension = extension.toLowerCase(); if (extension.equals("tga")) { try { PImage image = loadImageTGA(filename); // if (params != null) { // image.setParams(g, params); // } return image; } catch (IOException e) { e.printStackTrace(); return null; } } if (extension.equals("tif") || extension.equals("tiff")) { byte bytes[] = loadBytes(filename); PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes); // if (params != null) { // image.setParams(g, params); // } return image; } // For jpeg, gif, and png, load them using createImage(), // because the javax.imageio code was found to be much slower. // http://dev.processing.org/bugs/show_bug.cgi?id=392 try { if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("gif") || extension.equals("png") || extension.equals("unknown")) { byte bytes[] = loadBytes(filename); if (bytes == null) { return null; } else { Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes); PImage image = loadImageMT(awtImage); if (image.width == -1) { System.err.println("The file " + filename + " contains bad image data, or may not be an image."); } // if it's a .gif image, test to see if it has transparency if (extension.equals("gif") || extension.equals("png")) { image.checkAlpha(); } // if (params != null) { // image.setParams(g, params); // } return image; } } } catch (Exception e) { // show error, but move on to the stuff below, see if it'll work e.printStackTrace(); } if (loadImageFormats == null) { loadImageFormats = ImageIO.getReaderFormatNames(); } if (loadImageFormats != null) { for (int i = 0; i < loadImageFormats.length; i++) { if (extension.equals(loadImageFormats[i])) { return loadImageIO(filename); // PImage image = loadImageIO(filename); // if (params != null) { // image.setParams(g, params); // } // return image; } } } // failed, could not load image after all those attempts System.err.println("Could not find a method to load " + filename); return null; } public PImage requestImage(String filename) { // return requestImage(filename, null, null); return requestImage(filename, null); } /** * ( begin auto-generated from requestImage.xml ) * * This function load images on a separate thread so that your sketch does * not freeze while images load during <b>setup()</b>. While the image is * loading, its width and height will be 0. If an error occurs while * loading the image, its width and height will be set to -1. You'll know * when the image has loaded properly because its width and height will be * greater than 0. Asynchronous image loading (particularly when * downloading from a server) can dramatically improve performance.<br /> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>requestImage()</b>. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @param extension the type of image to load, for example "png", "gif", "jpg" * @see PImage * @see PApplet#loadImage(String, String) */ public PImage requestImage(String filename, String extension) { PImage vessel = createImage(0, 0, ARGB); AsyncImageLoader ail = new AsyncImageLoader(filename, extension, vessel); ail.start(); return vessel; } // /** // * @nowebref // */ // public PImage requestImage(String filename, String extension, Object params) { // PImage vessel = createImage(0, 0, ARGB, params); // AsyncImageLoader ail = // new AsyncImageLoader(filename, extension, vessel); // ail.start(); // return vessel; // } /** * By trial and error, four image loading threads seem to work best when * loading images from online. This is consistent with the number of open * connections that web browsers will maintain. The variable is made public * (however no accessor has been added since it's esoteric) if you really * want to have control over the value used. For instance, when loading local * files, it might be better to only have a single thread (or two) loading * images so that you're disk isn't simply jumping around. */ public int requestImageMax = 4; volatile int requestImageCount; class AsyncImageLoader extends Thread { String filename; String extension; PImage vessel; public AsyncImageLoader(String filename, String extension, PImage vessel) { this.filename = filename; this.extension = extension; this.vessel = vessel; } @Override public void run() { while (requestImageCount == requestImageMax) { try { Thread.sleep(10); } catch (InterruptedException e) { } } requestImageCount++; PImage actual = loadImage(filename, extension); // An error message should have already printed if (actual == null) { vessel.width = -1; vessel.height = -1; } else { vessel.width = actual.width; vessel.height = actual.height; vessel.format = actual.format; vessel.pixels = actual.pixels; } requestImageCount--; } } /** * Load an AWT image synchronously by setting up a MediaTracker for * a single image, and blocking until it has loaded. */ protected PImage loadImageMT(Image awtImage) { MediaTracker tracker = new MediaTracker(this); tracker.addImage(awtImage, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { //e.printStackTrace(); // non-fatal, right? } PImage image = new PImage(awtImage); image.parent = this; return image; } /** * Use Java 1.4 ImageIO methods to load an image. */ protected PImage loadImageIO(String filename) { InputStream stream = createInput(filename); if (stream == null) { System.err.println("The image " + filename + " could not be found."); return null; } try { BufferedImage bi = ImageIO.read(stream); PImage outgoing = new PImage(bi.getWidth(), bi.getHeight()); outgoing.parent = this; bi.getRGB(0, 0, outgoing.width, outgoing.height, outgoing.pixels, 0, outgoing.width); // check the alpha for this image // was gonna call getType() on the image to see if RGB or ARGB, // but it's not actually useful, since gif images will come through // as TYPE_BYTE_INDEXED, which means it'll still have to check for // the transparency. also, would have to iterate through all the other // types and guess whether alpha was in there, so.. just gonna stick // with the old method. outgoing.checkAlpha(); // return the image return outgoing; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Targa image loader for RLE-compressed TGA files. * <p> * Rewritten for 0115 to read/write RLE-encoded targa images. * For 0125, non-RLE encoded images are now supported, along with * images whose y-order is reversed (which is standard for TGA files). * <p> * A version of this function is in MovieMaker.java. Any fixes here * should be applied over in MovieMaker as well. * <p> * Known issue with RLE encoding and odd behavior in some apps: * https://github.com/processing/processing/issues/2096 * Please help! */ protected PImage loadImageTGA(String filename) throws IOException { InputStream is = createInput(filename); if (is == null) return null; byte header[] = new byte[18]; int offset = 0; do { int count = is.read(header, offset, header.length - offset); if (count == -1) return null; offset += count; } while (offset < 18); /* header[2] image type code 2 (0x02) - Uncompressed, RGB images. 3 (0x03) - Uncompressed, black and white images. 10 (0x0A) - Run-length encoded RGB images. 11 (0x0B) - Compressed, black and white images. (grayscale?) header[16] is the bit depth (8, 24, 32) header[17] image descriptor (packed bits) 0x20 is 32 = origin upper-left 0x28 is 32 + 8 = origin upper-left + 32 bits 7 6 5 4 3 2 1 0 128 64 32 16 8 4 2 1 */ int format = 0; if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not (header[16] == 8) && // 8 bits ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit format = ALPHA; } else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not (header[16] == 24) && // 24 bits ((header[17] == 0x20) || (header[17] == 0))) { // origin format = RGB; } else if (((header[2] == 2) || (header[2] == 10)) && (header[16] == 32) && ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 format = ARGB; } if (format == 0) { System.err.println("Unknown .tga file format for " + filename); //" (" + header[2] + " " + //(header[16] & 0xff) + " " + //hex(header[17], 2) + ")"); return null; } int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff); int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff); PImage outgoing = createImage(w, h, format); // where "reversed" means upper-left corner (normal for most of // the modernized world, but "reversed" for the tga spec) //boolean reversed = (header[17] & 0x20) != 0; // https://github.com/processing/processing/issues/1682 boolean reversed = (header[17] & 0x20) == 0; if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded if (reversed) { int index = (h-1) * w; switch (format) { case ALPHA: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read(); } index -= w; } break; case RGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } index -= w; } break; case ARGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } index -= w; } } } else { // not reversed int count = w * h; switch (format) { case ALPHA: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read(); } break; case RGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } break; case ARGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } break; } } } else { // header[2] is 10 or 11 int index = 0; int px[] = outgoing.pixels; while (index < px.length) { int num = is.read(); boolean isRLE = (num & 0x80) != 0; if (isRLE) { num -= 127; // (num & 0x7F) + 1 int pixel = 0; switch (format) { case ALPHA: pixel = is.read(); break; case RGB: pixel = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); break; case ARGB: pixel = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); break; } for (int i = 0; i < num; i++) { px[index++] = pixel; if (index == px.length) break; } } else { // write up to 127 bytes as uncompressed num += 1; switch (format) { case ALPHA: for (int i = 0; i < num; i++) { px[index++] = is.read(); } break; case RGB: for (int i = 0; i < num; i++) { px[index++] = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; case ARGB: for (int i = 0; i < num; i++) { px[index++] = is.read() | //(is.read() << 24) | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; } } } if (!reversed) { int[] temp = new int[w]; for (int y = 0; y < h/2; y++) { int z = (h-1) - y; System.arraycopy(px, y*w, temp, 0, w); System.arraycopy(px, z*w, px, y*w, w); System.arraycopy(temp, 0, px, z*w, w); } } } return outgoing; } ////////////////////////////////////////////////////////////// // DATA I/O // /** // * @webref input:files // * @brief Creates a new XML object // * @param name the name to be given to the root element of the new XML object // * @return an XML object, or null // * @see XML // * @see PApplet#loadXML(String) // * @see PApplet#parseXML(String) // * @see PApplet#saveXML(XML, String) // */ // public XML createXML(String name) { // try { // return new XML(name); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see XML * @see PApplet#parseXML(String) * @see PApplet#saveXML(XML, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadTable(String) */ public XML loadXML(String filename) { return loadXML(filename, null); } // version that uses 'options' though there are currently no supported options /** * @nowebref */ public XML loadXML(String filename, String options) { try { return new XML(createReader(filename), options); // return new XML(createInput(filename), options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref input:files * @brief Converts String content to an XML object * @param data the content to be parsed as XML * @return an XML object, or null * @see XML * @see PApplet#loadXML(String) * @see PApplet#saveXML(XML, String) */ public XML parseXML(String xmlString) { return parseXML(xmlString, null); } public XML parseXML(String xmlString, String options) { try { return XML.parse(xmlString, options); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @webref output:files * @param xml the XML object to save to disk * @param filename name of the file to write to * @see XML * @see PApplet#loadXML(String) * @see PApplet#parseXML(String) */ public boolean saveXML(XML xml, String filename) { return saveXML(xml, filename, null); } public boolean saveXML(XML xml, String filename, String options) { return xml.save(saveFile(filename), options); } public JSONObject parseJSONObject(String input) { return new JSONObject(new StringReader(input)); } /** * @webref input:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONObject loadJSONObject(String filename) { return new JSONObject(createReader(filename)); } static public JSONObject loadJSONObject(File file) { return new JSONObject(createReader(file)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONArray(JSONArray, String) */ public boolean saveJSONObject(JSONObject json, String filename) { return saveJSONObject(json, filename, null); } public boolean saveJSONObject(JSONObject json, String filename, String options) { return json.save(saveFile(filename), options); } public JSONArray parseJSONArray(String input) { return new JSONArray(new StringReader(input)); } /** * @webref input:files * @param filename name of a file in the data folder or a URL * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#saveJSONObject(JSONObject, String) * @see PApplet#saveJSONArray(JSONArray, String) */ public JSONArray loadJSONArray(String filename) { return new JSONArray(createReader(filename)); } static public JSONArray loadJSONArray(File file) { return new JSONArray(createReader(file)); } /** * @webref output:files * @see JSONObject * @see JSONArray * @see PApplet#loadJSONObject(String) * @see PApplet#loadJSONArray(String) * @see PApplet#saveJSONObject(JSONObject, String) */ public boolean saveJSONArray(JSONArray json, String filename) { return saveJSONArray(json, filename, null); } public boolean saveJSONArray(JSONArray json, String filename, String options) { return json.save(saveFile(filename), options); } // /** // * @webref input:files // * @see Table // * @see PApplet#loadTable(String) // * @see PApplet#saveTable(Table, String) // */ // public Table createTable() { // return new Table(); // } /** * @webref input:files * @param filename name of a file in the data folder or a URL. * @see Table * @see PApplet#saveTable(Table, String) * @see PApplet#loadBytes(String) * @see PApplet#loadStrings(String) * @see PApplet#loadXML(String) */ public Table loadTable(String filename) { return loadTable(filename, null); } /** * Options may contain "header", "tsv", "csv", or "bin" separated by commas. * * Another option is "dictionary=filename.tsv", which allows users to * specify a "dictionary" file that contains a mapping of the column titles * and the data types used in the table file. This can be far more efficient * (in terms of speed and memory usage) for loading and parsing tables. The * dictionary file can only be tab separated values (.tsv) and its extension * will be ignored. This option was added in Processing 2.0.2. */ public Table loadTable(String filename, String options) { try { String optionStr = Table.extensionOptions(true, filename, options); String[] optionList = trim(split(optionStr, ',')); Table dictionary = null; for (String opt : optionList) { if (opt.startsWith("dictionary=")) { dictionary = loadTable(opt.substring(opt.indexOf('=') + 1), "tsv"); return dictionary.typedParse(createInput(filename), optionStr); } } return new Table(createInput(filename), optionStr); } catch (IOException e) { e.printStackTrace(); return null; } } /** * @webref input:files * @param table the Table object to save to a file * @param filename the filename to which the Table should be saved * @see Table * @see PApplet#loadTable(String) */ public boolean saveTable(Table table, String filename) { return saveTable(table, filename, null); } /** * @param options can be one of "tsv", "csv", "bin", or "html" */ public boolean saveTable(Table table, String filename, String options) { // String ext = checkExtension(filename); // if (ext != null) { // if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin") || ext.equals("html")) { // if (options == null) { // options = ext; // } else { // options = ext + "," + options; // } // } // } try { // Figure out location and make sure the target path exists File outputFile = saveFile(filename); // Open a stream and take care of .gz if necessary return table.save(outputFile, options); } catch (IOException e) { e.printStackTrace(); return false; } } ////////////////////////////////////////////////////////////// // FONT I/O /** * ( begin auto-generated from loadFont.xml ) * * Loads a font into a variable of type <b>PFont</b>. To load correctly, * fonts must be located in the data directory of the current sketch. To * create a font to use with Processing, select "Create Font..." from the * Tools menu. This will create a font in the format Processing requires * and also adds it to the current sketch's data directory.<br /> * <br /> * Like <b>loadImage()</b> and other functions that load data, the * <b>loadFont()</b> function should not be used inside <b>draw()</b>, * because it will slow down the sketch considerably, as the font will be * re-loaded from the disk (or network) on each frame.<br /> * <br /> * For most renderers, Processing displays fonts using the .vlw font * format, which uses images for each letter, rather than defining them * through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with * the JAVA2D renderer, the native version of a font will be used if it is * installed on the user's machine.<br /> * <br /> * Using <b>createFont()</b> (instead of loadFont) enables vector data to * be used with the JAVA2D (default) renderer setting. This can be helpful * when many font sizes are needed, or when using any renderer based on * JAVA2D, such as the PDF library. * * ( end auto-generated ) * @webref typography:loading_displaying * @param filename name of the font to load * @see PFont * @see PGraphics#textFont(PFont, float) * @see PApplet#createFont(String, float, boolean, char[]) */ public PFont loadFont(String filename) { try { InputStream input = createInput(filename); return new PFont(input); } catch (Exception e) { die("Could not load font " + filename + ". " + "Make sure that the font has been copied " + "to the data folder of your sketch.", e); } return null; } /** * Used by PGraphics to remove the requirement for loading a font! */ protected PFont createDefaultFont(float size) { // Font f = new Font("SansSerif", Font.PLAIN, 12); // println("n: " + f.getName()); // println("fn: " + f.getFontName()); // println("ps: " + f.getPSName()); return createFont("Lucida Sans", size, true, null); } public PFont createFont(String name, float size) { return createFont(name, size, true, null); } public PFont createFont(String name, float size, boolean smooth) { return createFont(name, size, smooth, null); } /** * ( begin auto-generated from createFont.xml ) * * Dynamically converts a font to the format used by Processing from either * a font name that's installed on the computer, or from a .ttf or .otf * file inside the sketches "data" folder. This function is an advanced * feature for precise control. On most occasions you should create fonts * through selecting "Create Font..." from the Tools menu. * <br /><br /> * Use the <b>PFont.list()</b> method to first determine the names for the * fonts recognized by the computer and are compatible with this function. * Because of limitations in Java, not all fonts can be used and some might * work with one operating system and not others. When sharing a sketch * with other people or posting it on the web, you may need to include a * .ttf or .otf version of your font in the data directory of the sketch * because other people might not have the font installed on their * computer. Only fonts that can legally be distributed should be included * with a sketch. * <br /><br /> * The <b>size</b> parameter states the font size you want to generate. The * <b>smooth</b> parameter specifies if the font should be antialiased or * not, and the <b>charset</b> parameter is an array of chars that * specifies the characters to generate. * <br /><br /> * This function creates a bitmapped version of a font in the same manner * as the Create Font tool. It loads a font by name, and converts it to a * series of images based on the size of the font. When possible, the * <b>text()</b> function will use a native font rather than the bitmapped * version created behind the scenes with <b>createFont()</b>. For * instance, when using P2D, the actual native version of the font will be * employed by the sketch, improving drawing quality and performance. With * the P3D renderer, the bitmapped version will be used. While this can * drastically improve speed and appearance, results are poor when * exporting if the sketch does not include the .otf or .ttf file, and the * requested font is not available on the machine running the sketch. * * ( end auto-generated ) * @webref typography:loading_displaying * @param name name of the font to load * @param size point size of the font * @param smooth true for an antialiased font, false for aliased * @param charset array containing characters to be generated * @see PFont * @see PGraphics#textFont(PFont, float) * @see PGraphics#text(String, float, float, float, float, float) * @see PApplet#loadFont(String) */ public PFont createFont(String name, float size, boolean smooth, char charset[]) { String lowerName = name.toLowerCase(); Font baseFont = null; try { InputStream stream = null; if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { stream = createInput(name); if (stream == null) { System.err.println("The font \"" + name + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name)); } else { baseFont = PFont.findFont(name); } return new PFont(baseFont.deriveFont(size), smooth, charset, stream != null); } catch (Exception e) { System.err.println("Problem createFont(" + name + ")"); e.printStackTrace(); return null; } } ////////////////////////////////////////////////////////////// // FILE/FOLDER SELECTION private Frame selectFrame; private Frame selectFrame() { if (frame != null) { selectFrame = frame; } else if (selectFrame == null) { Component comp = getParent(); while (comp != null) { if (comp instanceof Frame) { selectFrame = (Frame) comp; break; } comp = comp.getParent(); } // Who you callin' a hack? if (selectFrame == null) { selectFrame = new Frame(); } } return selectFrame; } /** * Open a platform-specific file chooser dialog to select a file for input. * After the selection is made, the selected File will be passed to the * 'callback' function. If the dialog is closed or canceled, null will be * sent to the function, so that the program is not waiting for additional * input. The callback is necessary because of how threading works. * * <pre> * void setup() { * selectInput("Select a file to process:", "fileSelected"); * } * * void fileSelected(File selection) { * if (selection == null) { * println("Window was closed or the user hit cancel."); * } else { * println("User selected " + fileSeleted.getAbsolutePath()); * } * } * </pre> * * For advanced users, the method must be 'public', which is true for all * methods inside a sketch when run from the PDE, but must explicitly be * set when using Eclipse or other development environments. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectInput(String prompt, String callback) { selectInput(prompt, callback, null); } public void selectInput(String prompt, String callback, File file) { selectInput(prompt, callback, file, this); } public void selectInput(String prompt, String callback, File file, Object callbackObject) { selectInput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectInput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD); } /** * See selectInput() for details. * * @webref output:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectOutput(String prompt, String callback) { selectOutput(prompt, callback, null); } public void selectOutput(String prompt, String callback, File file) { selectOutput(prompt, callback, file, this); } public void selectOutput(String prompt, String callback, File file, Object callbackObject) { selectOutput(prompt, callback, file, callbackObject, selectFrame()); } static public void selectOutput(String prompt, String callbackMethod, File file, Object callbackObject, Frame parent) { selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE); } static protected void selectImpl(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame, final int mode) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (useNativeSelect) { FileDialog dialog = new FileDialog(parentFrame, prompt, mode); if (defaultSelection != null) { dialog.setDirectory(defaultSelection.getParent()); dialog.setFile(defaultSelection.getName()); } dialog.setVisible(true); String directory = dialog.getDirectory(); String filename = dialog.getFile(); if (filename != null) { selectedFile = new File(directory, filename); } } else { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(prompt); if (defaultSelection != null) { chooser.setSelectedFile(defaultSelection); } int result = -1; if (mode == FileDialog.SAVE) { result = chooser.showSaveDialog(parentFrame); } else if (mode == FileDialog.LOAD) { result = chooser.showOpenDialog(parentFrame); } if (result == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } /** * See selectInput() for details. * * @webref input:files * @param prompt message to the user * @param callback name of the method to be called when the selection is made */ public void selectFolder(String prompt, String callback) { selectFolder(prompt, callback, null); } public void selectFolder(String prompt, String callback, File file) { selectFolder(prompt, callback, file, this); } public void selectFolder(String prompt, String callback, File file, Object callbackObject) { selectFolder(prompt, callback, file, callbackObject, selectFrame()); } static public void selectFolder(final String prompt, final String callbackMethod, final File defaultSelection, final Object callbackObject, final Frame parentFrame) { EventQueue.invokeLater(new Runnable() { public void run() { File selectedFile = null; if (platform == MACOSX && useNativeSelect != false) { FileDialog fileDialog = new FileDialog(parentFrame, prompt, FileDialog.LOAD); System.setProperty("apple.awt.fileDialogForDirectories", "true"); fileDialog.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); String filename = fileDialog.getFile(); if (filename != null) { selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile()); } } else { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(prompt); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (defaultSelection != null) { fileChooser.setSelectedFile(defaultSelection); } int result = fileChooser.showOpenDialog(parentFrame); if (result == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); } } selectCallback(selectedFile, callbackMethod, callbackObject); } }); } static private void selectCallback(File selectedFile, String callbackMethod, Object callbackObject) { try { Class<?> callbackClass = callbackObject.getClass(); Method selectMethod = callbackClass.getMethod(callbackMethod, new Class[] { File.class }); selectMethod.invoke(callbackObject, new Object[] { selectedFile }); } catch (IllegalAccessException iae) { System.err.println(callbackMethod + "() must be public"); } catch (InvocationTargetException ite) { ite.printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println(callbackMethod + "() could not be found"); } } ////////////////////////////////////////////////////////////// // EXTENSIONS /** * Get the compression-free extension for this filename. * @param filename The filename to check * @return an extension, skipping past .gz if it's present */ static public String checkExtension(String filename) { // Don't consider the .gz as part of the name, createInput() // and createOuput() will take care of fixing that up. if (filename.toLowerCase().endsWith(".gz")) { filename = filename.substring(0, filename.length() - 3); } int dotIndex = filename.lastIndexOf('.'); if (dotIndex != -1) { return filename.substring(dotIndex + 1).toLowerCase(); } return null; } ////////////////////////////////////////////////////////////// // READERS AND WRITERS /** * ( begin auto-generated from createReader.xml ) * * Creates a <b>BufferedReader</b> object that can be used to read files * line-by-line as individual <b>String</b> objects. This is the complement * to the <b>createWriter()</b> function. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref input:files * @param filename name of the file to be opened * @see BufferedReader * @see PApplet#createWriter(String) * @see PrintWriter */ public BufferedReader createReader(String filename) { try { InputStream is = createInput(filename); if (is == null) { System.err.println(filename + " does not exist or could not be read"); return null; } return createReader(is); } catch (Exception e) { if (filename == null) { System.err.println("Filename passed to reader() was null"); } else { System.err.println("Couldn't create a reader for " + filename); } } return null; } /** * @nowebref */ static public BufferedReader createReader(File file) { try { InputStream is = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { is = new GZIPInputStream(is); } return createReader(is); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createReader() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a reader for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to read lines from a stream. If I have to type the * following lines any more I'm gonna send Sun my medical bills. */ static public BufferedReader createReader(InputStream input) { InputStreamReader isr = null; try { isr = new InputStreamReader(input, "UTF-8"); } catch (UnsupportedEncodingException e) { } // not gonna happen return new BufferedReader(isr); } /** * ( begin auto-generated from createWriter.xml ) * * Creates a new file in the sketch folder, and a <b>PrintWriter</b> object * to write to it. For the file to be made correctly, it should be flushed * and must be closed with its <b>flush()</b> and <b>close()</b> methods * (see above example). * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to be created * @see PrintWriter * @see PApplet#createReader * @see BufferedReader */ public PrintWriter createWriter(String filename) { return createWriter(saveFile(filename)); } /** * @nowebref * I want to print lines to a file. I have RSI from typing these * eight lines of code so many times. */ static public PrintWriter createWriter(File file) { try { createPath(file); // make sure in-between folders exist OutputStream output = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { output = new GZIPOutputStream(output); } return createWriter(output); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createWriter() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a writer for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to print lines to a file. Why am I always explaining myself? * It's the JavaSoft API engineers who need to explain themselves. */ static public PrintWriter createWriter(OutputStream output) { try { BufferedOutputStream bos = new BufferedOutputStream(output, 8192); OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8"); return new PrintWriter(osw); } catch (UnsupportedEncodingException e) { } // not gonna happen return null; } ////////////////////////////////////////////////////////////// // FILE INPUT /** * @deprecated As of release 0136, use createInput() instead. */ public InputStream openStream(String filename) { return createInput(filename); } /** * ( begin auto-generated from createInput.xml ) * * This is a function for advanced programmers to open a Java InputStream. * It's useful if you want to use the facilities provided by PApplet to * easily open files from the data folder or from a URL, but want an * InputStream object so that you can use other parts of Java to take more * control of how the stream is read.<br /> * <br /> * The filename passed in can be:<br /> * - A URL, for instance <b>openStream("http://processing.org/")</b><br /> * - A file in the sketch's <b>data</b> folder<br /> * - The full path to a file to be opened locally (when running as an * application)<br /> * <br /> * If the requested item doesn't exist, null is returned. If not online, * this will also check to see if the user is asking for a file whose name * isn't properly capitalized. If capitalization is different, an error * will be printed to the console. This helps prevent issues that appear * when a sketch is exported to the web, where case sensitivity matters, as * opposed to running from inside the Processing Development Environment on * Windows or Mac OS, where case sensitivity is preserved but ignored.<br /> * <br /> * If the file ends with <b>.gz</b>, the stream will automatically be gzip * decompressed. If you don't want the automatic decompression, use the * related function <b>createInputRaw()</b>. * <br /> * In earlier releases, this function was called <b>openStream()</b>.<br /> * <br /> * * ( end auto-generated ) * * <h3>Advanced</h3> * Simplified method to open a Java InputStream. * <p> * This method is useful if you want to use the facilities provided * by PApplet to easily open things from the data folder or from a URL, * but want an InputStream object so that you can use other Java * methods to take more control of how the stream is read. * <p> * If the requested item doesn't exist, null is returned. * (Prior to 0096, die() would be called, killing the applet) * <p> * For 0096+, the "data" folder is exported intact with subfolders, * and openStream() properly handles subdirectories from the data folder * <p> * If not online, this will also check to see if the user is asking * for a file whose name isn't properly capitalized. This helps prevent * issues when a sketch is exported to the web, where case sensitivity * matters, as opposed to Windows and the Mac OS default where * case sensitivity is preserved but ignored. * <p> * It is strongly recommended that libraries use this method to open * data files, so that the loading sequence is handled in the same way * as functions like loadBytes(), loadImage(), etc. * <p> * The filename passed in can be: * <UL> * <LI>A URL, for instance openStream("http://processing.org/"); * <LI>A file in the sketch's data folder * <LI>Another file to be opened locally (when running as an application) * </UL> * * @webref input:files * @param filename the name of the file to use as input * @see PApplet#createOutput(String) * @see PApplet#selectOutput(String) * @see PApplet#selectInput(String) * */ public InputStream createInput(String filename) { InputStream input = createInputRaw(filename); if ((input != null) && filename.toLowerCase().endsWith(".gz")) { try { return new GZIPInputStream(input); } catch (IOException e) { e.printStackTrace(); return null; } } return input; } /** * Call openStream() without automatic gzip decompression. */ public InputStream createInputRaw(String filename) { InputStream stream = null; if (filename == null) return null; if (filename.length() == 0) { // an error will be called by the parent function //System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah if (filename.contains(":")) { // at least smells like URL try { URL url = new URL(filename); stream = url.openStream(); return stream; } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. (fix for 0119) // http://dev.processing.org/bugs/show_bug.cgi?id=403 } catch (IOException e) { // changed for 0117, shouldn't be throwing exception e.printStackTrace(); //System.err.println("Error downloading from URL " + filename); return null; //throw new RuntimeException("Error downloading from URL " + filename); } } // Moved this earlier than the getResourceAsStream() checks, because // calling getResourceAsStream() on a directory lists its contents. // http://dev.processing.org/bugs/show_bug.cgi?id=716 try { // First see if it's in a data folder. This may fail by throwing // a SecurityException. If so, this whole block will be skipped. File file = new File(dataPath(filename)); if (!file.exists()) { // next see if it's just in the sketch folder file = sketchFile(filename); } if (file.isDirectory()) { return null; } if (file.exists()) { try { // handle case sensitivity check String filePath = file.getCanonicalPath(); String filenameActual = new File(filePath).getName(); // make sure there isn't a subfolder prepended to the name String filenameShort = new File(filename).getName(); // if the actual filename is the same, but capitalized // differently, warn the user. //if (filenameActual.equalsIgnoreCase(filenameShort) && //!filenameActual.equals(filenameShort)) { if (!filenameActual.equals(filenameShort)) { throw new RuntimeException("This file is named " + filenameActual + " not " + filename + ". Rename the file " + "or change your code."); } } catch (IOException e) { } } // if this file is ok, may as well just load it stream = new FileInputStream(file); if (stream != null) return stream; // have to break these out because a general Exception might // catch the RuntimeException being thrown above } catch (IOException ioe) { } catch (SecurityException se) { } // Using getClassLoader() prevents java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) ClassLoader cl = getClass().getClassLoader(); // by default, data files are exported to the root path of the jar. // (not the data folder) so check there first. stream = cl.getResourceAsStream("data/" + filename); if (stream != null) { String cn = stream.getClass().getName(); // this is an irritation of sun's java plug-in, which will return // a non-null stream for an object that doesn't exist. like all good // things, this is probably introduced in java 1.5. awesome! // http://dev.processing.org/bugs/show_bug.cgi?id=359 if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // When used with an online script, also need to check without the // data folder, in case it's not in a subfolder called 'data'. // http://dev.processing.org/bugs/show_bug.cgi?id=389 stream = cl.getResourceAsStream(filename); if (stream != null) { String cn = stream.getClass().getName(); if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // Finally, something special for the Internet Explorer users. Turns out // that we can't get files that are part of the same folder using the // methods above when using IE, so we have to resort to the old skool // getDocumentBase() from teh applet dayz. 1996, my brotha. try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); // if (conn instanceof HttpURLConnection) { // HttpURLConnection httpConnection = (HttpURLConnection) conn; // // test for 401 result (HTTP only) // int responseCode = httpConnection.getResponseCode(); // } } } catch (Exception e) { } // IO or NPE or... // Now try it with a 'data' subfolder. getting kinda desperate for data... try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, "data/" + filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); } } catch (Exception e) { } try { // attempt to load from a local file, used when running as // an application, or as a signed applet try { // first try to catch any security exceptions try { stream = new FileInputStream(dataPath(filename)); if (stream != null) return stream; } catch (IOException e2) { } try { stream = new FileInputStream(sketchPath(filename)); if (stream != null) return stream; } catch (Exception e) { } // ignored try { stream = new FileInputStream(filename); if (stream != null) return stream; } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups } catch (Exception e) { //die(e.getMessage(), e); e.printStackTrace(); } return null; } /** * @nowebref */ static public InputStream createInput(File file) { if (file == null) { throw new IllegalArgumentException("File passed to createInput() was null"); } try { InputStream input = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPInputStream(input); } return input; } catch (IOException e) { System.err.println("Could not createInput() for " + file); e.printStackTrace(); return null; } } /** * ( begin auto-generated from loadBytes.xml ) * * Reads the contents of a file or url and places it in a byte array. If a * file is specified, it must be located in the sketch's "data" * directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * * ( end auto-generated ) * @webref input:files * @param filename name of a file in the data folder or a URL. * @see PApplet#loadStrings(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) * */ public byte[] loadBytes(String filename) { InputStream is = createInput(filename); if (is != null) { byte[] outgoing = loadBytes(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); // shouldn't happen } return outgoing; } System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public byte[] loadBytes(InputStream input) { try { BufferedInputStream bis = new BufferedInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { out.write(c); c = bis.read(); } return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Couldn't load bytes from stream"); } return null; } /** * @nowebref */ static public byte[] loadBytes(File file) { InputStream is = createInput(file); return loadBytes(is); } /** * @nowebref */ static public String[] loadStrings(File file) { InputStream is = createInput(file); if (is != null) { String[] outgoing = loadStrings(is); try { is.close(); } catch (IOException e) { e.printStackTrace(); } return outgoing; } return null; } /** * ( begin auto-generated from loadStrings.xml ) * * Reads the contents of a file or url and creates a String array of its * individual lines. If a file is specified, it must be located in the * sketch's "data" directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * <br /> * If the file is not available or an error occurs, <b>null</b> will be * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned is null. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * Load data from a file and shove it into a String array. * <p> * Exceptions are handled internally, when an error, occurs, an * exception is printed to the console and 'null' is returned, * but the program continues running. This is a tradeoff between * 1) showing the user that there was a problem but 2) not requiring * that all i/o code is contained in try/catch blocks, for the sake * of new users (or people who are just trying to get things done * in a "scripting" fashion. If you want to handle exceptions, * use Java methods for I/O. * * @webref input:files * @param filename name of the file or url to load * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) */ public String[] loadStrings(String filename) { InputStream is = createInput(filename); if (is != null) return loadStrings(is); System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public String[] loadStrings(InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); return loadStrings(reader); } catch (IOException e) { e.printStackTrace(); } return null; } static public String[] loadStrings(BufferedReader reader) { try { String lines[] = new String[100]; int lineCount = 0; String line = null; while ((line = reader.readLine()) != null) { if (lineCount == lines.length) { String temp[] = new String[lineCount << 1]; System.arraycopy(lines, 0, temp, 0, lineCount); lines = temp; } lines[lineCount++] = line; } reader.close(); if (lineCount == lines.length) { return lines; } // resize array to appropriate amount for these lines String output[] = new String[lineCount]; System.arraycopy(lines, 0, output, 0, lineCount); return output; } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Error inside loadStrings()"); } return null; } ////////////////////////////////////////////////////////////// // FILE OUTPUT /** * ( begin auto-generated from createOutput.xml ) * * Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b> * for a given filename or path. The file will be created in the sketch * folder, or in the same folder as an exported application. * <br /><br /> * If the path does not exist, intermediate folders will be created. If an * exception occurs, it will be printed to the console, and <b>null</b> * will be returned. * <br /><br /> * This function is a convenience over the Java approach that requires you * to 1) create a FileOutputStream object, 2) determine the exact file * location, and 3) handle exceptions. Exceptions are handled internally by * the function, which is more appropriate for "sketch" projects. * <br /><br /> * If the output filename ends with <b>.gz</b>, the output will be * automatically GZIP compressed as it is written. * * ( end auto-generated ) * @webref output:files * @param filename name of the file to open * @see PApplet#createInput(String) * @see PApplet#selectOutput() */ public OutputStream createOutput(String filename) { return createOutput(saveFile(filename)); } /** * @nowebref */ static public OutputStream createOutput(File file) { try { createPath(file); // make sure the path exists FileOutputStream fos = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPOutputStream(fos); } return fos; } catch (IOException e) { e.printStackTrace(); } return null; } /** * ( begin auto-generated from saveStream.xml ) * * Save the contents of a stream to a file in the sketch folder. This is * basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently * (and with less confusing syntax).<br /> * <br /> * When using the <b>targetFile</b> parameter, it writes to a <b>File</b> * object for greater control over the file location. (Note that unlike * some other functions, this will not automatically compress or uncompress * gzip files.) * * ( end auto-generated ) * * @webref output:files * @param target name of the file to write to * @param source location to read from (a filename, path, or URL) * @see PApplet#createOutput(String) */ public boolean saveStream(String target, String source) { return saveStream(saveFile(target), source); } /** * Identical to the other saveStream(), but writes to a File * object, for greater control over the file location. * <p/> * Note that unlike other api methods, this will not automatically * compress or uncompress gzip files. */ public boolean saveStream(File target, String source) { return saveStream(target, createInputRaw(source)); } /** * @nowebref */ public boolean saveStream(String target, InputStream source) { return saveStream(saveFile(target), source); } /** * @nowebref */ static public boolean saveStream(File target, InputStream source) { File tempFile = null; try { File parentDir = target.getParentFile(); // make sure that this path actually exists before writing createPath(target); tempFile = File.createTempFile(target.getName(), null, parentDir); FileOutputStream targetStream = new FileOutputStream(tempFile); saveStream(targetStream, source); targetStream.close(); targetStream = null; if (target.exists()) { if (!target.delete()) { System.err.println("Could not replace " + target.getAbsolutePath() + "."); } } if (!tempFile.renameTo(target)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); return false; } return true; } catch (IOException e) { if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); return false; } } /** * @nowebref */ static public void saveStream(OutputStream target, InputStream source) throws IOException { BufferedInputStream bis = new BufferedInputStream(source, 16384); BufferedOutputStream bos = new BufferedOutputStream(target); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); } /** * ( begin auto-generated from saveBytes.xml ) * * Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a * file. The data is saved in binary format. This file is saved to the * sketch's folder, which is opened by selecting "Show sketch folder" from * the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to write to * @param data array of bytes to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) */ public void saveBytes(String filename, byte[] data) { saveBytes(saveFile(filename), data); } /** * @nowebref * Saves bytes to a specific File location specified by the user. */ static public void saveBytes(File file, byte[] data) { File tempFile = null; try { File parentDir = file.getParentFile(); tempFile = File.createTempFile(file.getName(), null, parentDir); OutputStream output = createOutput(tempFile); saveBytes(output, data); output.close(); output = null; if (file.exists()) { if (!file.delete()) { System.err.println("Could not replace " + file.getAbsolutePath()); } } if (!tempFile.renameTo(file)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); } } catch (IOException e) { System.err.println("error saving bytes to " + file); if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); } } /** * @nowebref * Spews a buffer of bytes to an OutputStream. */ static public void saveBytes(OutputStream output, byte[] data) { try { output.write(data); output.flush(); } catch (IOException e) { e.printStackTrace(); } } // /** * ( begin auto-generated from saveStrings.xml ) * * Writes an array of strings to a file, one line per string. This file is * saved to the sketch's folder, which is opened by selecting "Show sketch * folder" from the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * Starting with Processing 1.0, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref output:files * @param filename filename for output * @param data string array to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveBytes(String, byte[]) */ public void saveStrings(String filename, String data[]) { saveStrings(saveFile(filename), data); } /** * @nowebref */ static public void saveStrings(File file, String data[]) { saveStrings(createOutput(file), data); } /** * @nowebref */ static public void saveStrings(OutputStream output, String[] data) { PrintWriter writer = createWriter(output); for (int i = 0; i < data.length; i++) { writer.println(data[i]); } writer.flush(); writer.close(); } ////////////////////////////////////////////////////////////// /** * Prepend the sketch folder path to the filename (or path) that is * passed in. External libraries should use this function to save to * the sketch folder. * <p/> * Note that when running as an applet inside a web browser, * the sketchPath will be set to null, because security restrictions * prevent applets from accessing that information. * <p/> * This will also cause an error if the sketch is not inited properly, * meaning that init() was never called on the PApplet when hosted * my some other main() or by other code. For proper use of init(), * see the examples in the main description text for PApplet. */ public String sketchPath(String where) { if (sketchPath == null) { return where; // throw new RuntimeException("The applet was not inited properly, " + // "or security restrictions prevented " + // "it from determining its path."); } // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. // for 0120, added a try/catch anyways. try { if (new File(where).isAbsolute()) return where; } catch (Exception e) { } return sketchPath + File.separator + where; } public File sketchFile(String where) { return new File(sketchPath(where)); } /** * Returns a path inside the applet folder to save to. Like sketchPath(), * but creates any in-between folders so that things save properly. * <p/> * All saveXxxx() functions use the path to the sketch folder, rather than * its data folder. Once exported, the data folder will be found inside the * jar file of the exported application or applet. In this case, it's not * possible to save data into the jar file, because it will often be running * from a server, or marked in-use if running from a local file system. * With this in mind, saving to the data path doesn't make sense anyway. * If you know you're running locally, and want to save to the data folder, * use <TT>saveXxxx("data/blah.dat")</TT>. */ public String savePath(String where) { if (where == null) return null; String filename = sketchPath(where); createPath(filename); return filename; } /** * Identical to savePath(), but returns a File object. */ public File saveFile(String where) { return new File(savePath(where)); } static File desktopFolder; /** Not a supported function. For testing use only. */ static public File desktopFile(String what) { if (desktopFolder == null) { // Should work on Linux and OS X (on OS X, even with the localized version). desktopFolder = new File(System.getProperty("user.home"), "Desktop"); if (!desktopFolder.exists()) { if (platform == WINDOWS) { FileSystemView filesys = FileSystemView.getFileSystemView(); desktopFolder = filesys.getHomeDirectory(); } else { throw new UnsupportedOperationException("Could not find a suitable desktop foldder"); } } } return new File(desktopFolder, what); } /** Not a supported function. For testing use only. */ static public String desktopPath(String what) { return desktopFile(what).getAbsolutePath(); } /** * Return a full path to an item in the data folder. * <p> * This is only available with applications, not applets or Android. * On Windows and Linux, this is simply the data folder, which is located * in the same directory as the EXE file and lib folders. On Mac OS X, this * is a path to the data folder buried inside Contents/Java. * For the latter point, that also means that the data folder should not be * considered writable. Use sketchPath() for now, or inputPath() and * outputPath() once they're available in the 2.0 release. * <p> * dataPath() is not supported with applets because applets have their data * folder wrapped into the JAR file. To read data from the data folder that * works with an applet, you should use other methods such as createInput(), * createReader(), or loadStrings(). */ public String dataPath(String where) { return dataFile(where).getAbsolutePath(); } /** * Return a full path to an item in the data folder as a File object. * See the dataPath() method for more information. */ public File dataFile(String where) { // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. File why = new File(where); if (why.isAbsolute()) return why; String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); if (jarPath.contains("Contents/Java/")) { // The path will be URL encoded (%20 for spaces) coming from above // http://code.google.com/p/processing/issues/detail?id=1073 File containingFolder = new File(urlDecode(jarPath)).getParentFile(); File dataFolder = new File(containingFolder, "data"); System.out.println(dataFolder); return new File(dataFolder, where); } // Windows, Linux, or when not using a Mac OS X .app file return new File(sketchPath + File.separator + "data" + File.separator + where); } /** * On Windows and Linux, this is simply the data folder. On Mac OS X, this is * the path to the data folder buried inside Contents/Java */ // public File inputFile(String where) { // } // public String inputPath(String where) { // } /** * Takes a path and creates any in-between folders if they don't * already exist. Useful when trying to save to a subfolder that * may not actually exist. */ static public void createPath(String path) { createPath(new File(path)); } static public void createPath(File file) { try { String parent = file.getParent(); if (parent != null) { File unit = new File(parent); if (!unit.exists()) unit.mkdirs(); } } catch (SecurityException se) { System.err.println("You don't have permissions to create " + file.getAbsolutePath()); } } static public String getExtension(String filename) { String extension; String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } return extension; } ////////////////////////////////////////////////////////////// // URL ENCODING static public String urlEncode(String str) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // oh c'mon return null; } } static public String urlDecode(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { // safe per the JDK source return null; } } ////////////////////////////////////////////////////////////// // SORT /** * ( begin auto-generated from sort.xml ) * * Sorts an array of numbers from smallest to largest and puts an array of * words in alphabetical order. The original array is not modified, a * re-ordered array is returned. The <b>count</b> parameter states the * number of elements to sort. For example if there are 12 elements in an * array and if count is the value 5, only the first five elements on the * array will be sorted. <!--As of release 0126, the alphabetical ordering * is case insensitive.--> * * ( end auto-generated ) * @webref data:array_functions * @param list array to sort * @see PApplet#reverse(boolean[]) */ static public byte[] sort(byte list[]) { return sort(list, list.length); } /** * @param count number of elements to sort, starting from 0 */ static public byte[] sort(byte[] list, int count) { byte[] outgoing = new byte[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public char[] sort(char list[]) { return sort(list, list.length); } static public char[] sort(char[] list, int count) { char[] outgoing = new char[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public int[] sort(int list[]) { return sort(list, list.length); } static public int[] sort(int[] list, int count) { int[] outgoing = new int[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public float[] sort(float list[]) { return sort(list, list.length); } static public float[] sort(float[] list, int count) { float[] outgoing = new float[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public String[] sort(String list[]) { return sort(list, list.length); } static public String[] sort(String[] list, int count) { String[] outgoing = new String[list.length]; System.arraycopy(list, 0, outgoing, 0, list.length); Arrays.sort(outgoing, 0, count); return outgoing; } ////////////////////////////////////////////////////////////// // ARRAY UTILITIES /** * ( begin auto-generated from arrayCopy.xml ) * * Copies an array (or part of an array) to another array. The <b>src</b> * array is copied to the <b>dst</b> array, beginning at the position * specified by <b>srcPos</b> and into the position specified by * <b>dstPos</b>. The number of elements to copy is determined by * <b>length</b>. The simplified version with two arguments copies an * entire array to another of the same size. It is equivalent to * "arrayCopy(src, 0, dst, 0, src.length)". This function is far more * efficient for copying array data than iterating through a <b>for</b> and * copying each element. * * ( end auto-generated ) * @webref data:array_functions * @param src the source array * @param srcPosition starting position in the source array * @param dst the destination array of the same data type as the source array * @param dstPosition starting position in the destination array * @param length number of array elements to be copied * @see PApplet#concat(boolean[], boolean[]) */ static public void arrayCopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * Convenience method for arraycopy(). * Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE> */ static public void arrayCopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * Shortcut to copy the entire contents of * the source into the destination array. * Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE> */ static public void arrayCopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } // /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } /** * ( begin auto-generated from expand.xml ) * * Increases the size of an array. By default, this function doubles the * size of the array, but the optional <b>newSize</b> parameter provides * precise control over the increase in size. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) expand(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list the array to expand * @see PApplet#shorten(boolean[]) */ static public boolean[] expand(boolean list[]) { return expand(list, list.length << 1); } /** * @param newSize new size for the array */ static public boolean[] expand(boolean list[], int newSize) { boolean temp[] = new boolean[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public byte[] expand(byte list[]) { return expand(list, list.length << 1); } static public byte[] expand(byte list[], int newSize) { byte temp[] = new byte[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public char[] expand(char list[]) { return expand(list, list.length << 1); } static public char[] expand(char list[], int newSize) { char temp[] = new char[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public int[] expand(int list[]) { return expand(list, list.length << 1); } static public int[] expand(int list[], int newSize) { int temp[] = new int[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public long[] expand(long list[]) { return expand(list, list.length << 1); } static public long[] expand(long list[], int newSize) { long temp[] = new long[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public float[] expand(float list[]) { return expand(list, list.length << 1); } static public float[] expand(float list[], int newSize) { float temp[] = new float[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public double[] expand(double list[]) { return expand(list, list.length << 1); } static public double[] expand(double list[], int newSize) { double temp[] = new double[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public String[] expand(String list[]) { return expand(list, list.length << 1); } static public String[] expand(String list[], int newSize) { String temp[] = new String[newSize]; // in case the new size is smaller than list.length System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } /** * @nowebref */ static public Object expand(Object array) { return expand(array, Array.getLength(array) << 1); } static public Object expand(Object list, int newSize) { Class<?> type = list.getClass().getComponentType(); Object temp = Array.newInstance(type, newSize); System.arraycopy(list, 0, temp, 0, Math.min(Array.getLength(list), newSize)); return temp; } // contract() has been removed in revision 0124, use subset() instead. // (expand() is also functionally equivalent) /** * ( begin auto-generated from append.xml ) * * Expands an array by one element and adds data to the new position. The * datatype of the <b>element</b> parameter must be the same as the * datatype of the array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) append(originalArray, element)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param array array to append * @param value new data for the array * @see PApplet#shorten(boolean[]) * @see PApplet#expand(boolean[]) */ static public byte[] append(byte array[], byte value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public char[] append(char array[], char value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public int[] append(int array[], int value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public float[] append(float array[], float value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public String[] append(String array[], String value) { array = expand(array, array.length + 1); array[array.length-1] = value; return array; } static public Object append(Object array, Object value) { int length = Array.getLength(array); array = expand(array, length + 1); Array.set(array, length, value); return array; } /** * ( begin auto-generated from shorten.xml ) * * Decreases an array by one element and returns the shortened array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) shorten(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list array to shorten * @see PApplet#append(byte[], byte) * @see PApplet#expand(boolean[]) */ static public boolean[] shorten(boolean list[]) { return subset(list, 0, list.length-1); } static public byte[] shorten(byte list[]) { return subset(list, 0, list.length-1); } static public char[] shorten(char list[]) { return subset(list, 0, list.length-1); } static public int[] shorten(int list[]) { return subset(list, 0, list.length-1); } static public float[] shorten(float list[]) { return subset(list, 0, list.length-1); } static public String[] shorten(String list[]) { return subset(list, 0, list.length-1); } static public Object shorten(Object list) { int length = Array.getLength(list); return subset(list, 0, length - 1); } /** * ( begin auto-generated from splice.xml ) * * Inserts a value or array of values into an existing array. The first two * parameters must be of the same datatype. The <b>array</b> parameter * defines the array which will be modified and the second parameter * defines the data which will be inserted. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) splice(array1, array2, index)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to splice into * @param value value to be spliced in * @param index position in the array from which to insert data * @see PApplet#concat(boolean[], boolean[]) * @see PApplet#subset(boolean[], int, int) */ static final public boolean[] splice(boolean list[], boolean value, int index) { boolean outgoing[] = new boolean[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public boolean[] splice(boolean list[], boolean value[], int index) { boolean outgoing[] = new boolean[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value, int index) { byte outgoing[] = new byte[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte value[], int index) { byte outgoing[] = new byte[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public char[] splice(char list[], char value, int index) { char outgoing[] = new char[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public char[] splice(char list[], char value[], int index) { char outgoing[] = new char[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public int[] splice(int list[], int value, int index) { int outgoing[] = new int[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public int[] splice(int list[], int value[], int index) { int outgoing[] = new int[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public float[] splice(float list[], float value, int index) { float outgoing[] = new float[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public float[] splice(float list[], float value[], int index) { float outgoing[] = new float[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public String[] splice(String list[], String value, int index) { String outgoing[] = new String[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = value; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public String[] splice(String list[], String value[], int index) { String outgoing[] = new String[list.length + value.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, value.length); System.arraycopy(list, index, outgoing, index + value.length, list.length - index); return outgoing; } static final public Object splice(Object list, Object value, int index) { Object[] outgoing = null; int length = Array.getLength(list); // check whether item being spliced in is an array if (value.getClass().getName().charAt(0) == '[') { int vlength = Array.getLength(value); outgoing = new Object[length + vlength]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(value, 0, outgoing, index, vlength); System.arraycopy(list, index, outgoing, index + vlength, length - index); } else { outgoing = new Object[length + 1]; System.arraycopy(list, 0, outgoing, 0, index); Array.set(outgoing, index, value); System.arraycopy(list, index, outgoing, index + 1, length - index); } return outgoing; } static public boolean[] subset(boolean list[], int start) { return subset(list, start, list.length - start); } /** * ( begin auto-generated from subset.xml ) * * Extracts an array of elements from an existing array. The <b>array</b> * parameter defines the array from which the elements will be copied and * the <b>offset</b> and <b>length</b> parameters determine which elements * to extract. If no <b>length</b> is given, elements will be extracted * from the <b>offset</b> to the end of the array. When specifying the * <b>offset</b> remember the first array element is 0. This function does * not change the source array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) subset(originalArray, 0, 4)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to extract from * @param start position to begin * @param count number of values to extract * @see PApplet#splice(boolean[], boolean, int) */ static public boolean[] subset(boolean list[], int start, int count) { boolean output[] = new boolean[count]; System.arraycopy(list, start, output, 0, count); return output; } static public byte[] subset(byte list[], int start) { return subset(list, start, list.length - start); } static public byte[] subset(byte list[], int start, int count) { byte output[] = new byte[count]; System.arraycopy(list, start, output, 0, count); return output; } static public char[] subset(char list[], int start) { return subset(list, start, list.length - start); } static public char[] subset(char list[], int start, int count) { char output[] = new char[count]; System.arraycopy(list, start, output, 0, count); return output; } static public int[] subset(int list[], int start) { return subset(list, start, list.length - start); } static public int[] subset(int list[], int start, int count) { int output[] = new int[count]; System.arraycopy(list, start, output, 0, count); return output; } static public float[] subset(float list[], int start) { return subset(list, start, list.length - start); } static public float[] subset(float list[], int start, int count) { float output[] = new float[count]; System.arraycopy(list, start, output, 0, count); return output; } static public String[] subset(String list[], int start) { return subset(list, start, list.length - start); } static public String[] subset(String list[], int start, int count) { String output[] = new String[count]; System.arraycopy(list, start, output, 0, count); return output; } static public Object subset(Object list, int start) { int length = Array.getLength(list); return subset(list, start, length - start); } static public Object subset(Object list, int start, int count) { Class<?> type = list.getClass().getComponentType(); Object outgoing = Array.newInstance(type, count); System.arraycopy(list, start, outgoing, 0, count); return outgoing; } /** * ( begin auto-generated from concat.xml ) * * Concatenates two arrays. For example, concatenating the array { 1, 2, 3 * } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters * must be arrays of the same datatype. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) concat(array1, array2)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param a first array to concatenate * @param b second array to concatenate * @see PApplet#splice(boolean[], boolean, int) * @see PApplet#arrayCopy(Object, int, Object, int, int) */ static public boolean[] concat(boolean a[], boolean b[]) { boolean c[] = new boolean[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public byte[] concat(byte a[], byte b[]) { byte c[] = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public char[] concat(char a[], char b[]) { char c[] = new char[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public int[] concat(int a[], int b[]) { int c[] = new int[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public float[] concat(float a[], float b[]) { float c[] = new float[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public String[] concat(String a[], String b[]) { String c[] = new String[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public Object concat(Object a, Object b) { Class<?> type = a.getClass().getComponentType(); int alength = Array.getLength(a); int blength = Array.getLength(b); Object outgoing = Array.newInstance(type, alength + blength); System.arraycopy(a, 0, outgoing, 0, alength); System.arraycopy(b, 0, outgoing, alength, blength); return outgoing; } // /** * ( begin auto-generated from reverse.xml ) * * Reverses the order of an array. * * ( end auto-generated ) * @webref data:array_functions * @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[] * @see PApplet#sort(String[], int) */ static public boolean[] reverse(boolean list[]) { boolean outgoing[] = new boolean[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public byte[] reverse(byte list[]) { byte outgoing[] = new byte[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public char[] reverse(char list[]) { char outgoing[] = new char[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public int[] reverse(int list[]) { int outgoing[] = new int[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public float[] reverse(float list[]) { float outgoing[] = new float[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public String[] reverse(String list[]) { String outgoing[] = new String[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public Object reverse(Object list) { Class<?> type = list.getClass().getComponentType(); int length = Array.getLength(list); Object outgoing = Array.newInstance(type, length); for (int i = 0; i < length; i++) { Array.set(outgoing, i, Array.get(list, (length - 1) - i)); } return outgoing; } ////////////////////////////////////////////////////////////// // STRINGS /** * ( begin auto-generated from trim.xml ) * * Removes whitespace characters from the beginning and end of a String. In * addition to standard whitespace characters such as space, carriage * return, and tab, this function also removes the Unicode "nbsp" character. * * ( end auto-generated ) * @webref data:string_functions * @param str any string * @see PApplet#split(String, String) * @see PApplet#join(String[], char) */ static public String trim(String str) { return str.replace('\u00A0', ' ').trim(); } /** * @param array a String array */ static public String[] trim(String[] array) { String[] outgoing = new String[array.length]; for (int i = 0; i < array.length; i++) { if (array[i] != null) { outgoing[i] = array[i].replace('\u00A0', ' ').trim(); } } return outgoing; } /** * ( begin auto-generated from join.xml ) * * Combines an array of Strings into one String, each separated by the * character(s) used for the <b>separator</b> parameter. To join arrays of * ints or floats, it's necessary to first convert them to strings using * <b>nf()</b> or <b>nfs()</b>. * * ( end auto-generated ) * @webref data:string_functions * @param list array of Strings * @param separator char or String to be placed between each item * @see PApplet#split(String, String) * @see PApplet#trim(String) * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) */ static public String join(String[] list, char separator) { return join(list, String.valueOf(separator)); } static public String join(String[] list, String separator) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < list.length; i++) { if (i != 0) buffer.append(separator); buffer.append(list[i]); } return buffer.toString(); } static public String[] splitTokens(String value) { return splitTokens(value, WHITESPACE); } /** * ( begin auto-generated from splitTokens.xml ) * * The splitTokens() function splits a String at one or many character * "tokens." The <b>tokens</b> parameter specifies the character or * characters to be used as a boundary. * <br/> <br/> * If no <b>tokens</b> character is specified, any whitespace character is * used to split. Whitespace characters include tab (\\t), line feed (\\n), * carriage return (\\r), form feed (\\f), and space. To convert a String * to an array of integers or floats, use the datatype conversion functions * <b>int()</b> and <b>float()</b> to convert the array of Strings. * * ( end auto-generated ) * @webref data:string_functions * @param value the String to be split * @param delim list of individual characters that will be used as separators * @see PApplet#split(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] splitTokens(String value, String delim) { StringTokenizer toker = new StringTokenizer(value, delim); String pieces[] = new String[toker.countTokens()]; int index = 0; while (toker.hasMoreTokens()) { pieces[index++] = toker.nextToken(); } return pieces; } /** * ( begin auto-generated from split.xml ) * * The split() function breaks a string into pieces using a character or * string as the divider. The <b>delim</b> parameter specifies the * character or characters that mark the boundaries between each piece. A * String[] array is returned that contains each of the pieces. * <br/> <br/> * If the result is a set of numbers, you can convert the String[] array to * to a float[] or int[] array using the datatype conversion functions * <b>int()</b> and <b>float()</b> (see example above). * <br/> <br/> * The <b>splitTokens()</b> function works in a similar fashion, except * that it splits using a range of characters instead of a specific * character or sequence. * <!-- /><br /> * This function uses regular expressions to determine how the <b>delim</b> * parameter divides the <b>str</b> parameter. Therefore, if you use * characters such parentheses and brackets that are used with regular * expressions as a part of the <b>delim</b> parameter, you'll need to put * two blackslashes (\\\\) in front of the character (see example above). * You can read more about <a * href="http://en.wikipedia.org/wiki/Regular_expression">regular * expressions</a> and <a * href="http://en.wikipedia.org/wiki/Escape_character">escape * characters</a> on Wikipedia. * --> * * ( end auto-generated ) * @webref data:string_functions * @usage web_application * @param value the String to be split * @param delim the character or String used to separate the data */ static public String[] split(String value, char delim) { // do this so that the exception occurs inside the user's // program, rather than appearing to be a bug inside split() if (value == null) return null; //return split(what, String.valueOf(delim)); // huh char chars[] = value.toCharArray(); int splitCount = 0; //1; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) splitCount++; } // make sure that there is something in the input string //if (chars.length > 0) { // if the last char is a delimeter, get rid of it.. //if (chars[chars.length-1] == delim) splitCount--; // on second thought, i don't agree with this, will disable //} if (splitCount == 0) { String splits[] = new String[1]; splits[0] = new String(value); return splits; } //int pieceCount = splitCount + 1; String splits[] = new String[splitCount + 1]; int splitIndex = 0; int startIndex = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) { splits[splitIndex++] = new String(chars, startIndex, i-startIndex); startIndex = i + 1; } } //if (startIndex != chars.length) { splits[splitIndex] = new String(chars, startIndex, chars.length-startIndex); //} return splits; } static public String[] split(String value, String delim) { ArrayList<String> items = new ArrayList<String>(); int index; int offset = 0; while ((index = value.indexOf(delim, offset)) != -1) { items.add(value.substring(offset, index)); offset = index + delim.length(); } items.add(value.substring(offset)); String[] outgoing = new String[items.size()]; items.toArray(outgoing); return outgoing; } static protected HashMap<String, Pattern> matchPatterns; static Pattern matchPattern(String regexp) { Pattern p = null; if (matchPatterns == null) { matchPatterns = new HashMap<String, Pattern>(); } else { p = matchPatterns.get(regexp); } if (p == null) { if (matchPatterns.size() == 10) { // Just clear out the match patterns here if more than 10 are being // used. It's not terribly efficient, but changes that you have >10 // different match patterns are very slim, unless you're doing // something really tricky (like custom match() methods), in which // case match() won't be efficient anyway. (And you should just be // using your own Java code.) The alternative is using a queue here, // but that's a silly amount of work for negligible benefit. matchPatterns.clear(); } p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); matchPatterns.put(regexp, p); } return p; } /** * ( begin auto-generated from match.xml ) * * The match() function is used to apply a regular expression to a piece of * text, and return matching groups (elements found inside parentheses) as * a String array. No match will return null. If no groups are specified in * the regexp, but the sequence matches, an array of length one (with the * matched text as the first element of the array) will be returned.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match. If the sequence did * match, an array is returned. * If there are groups (specified by sets of parentheses) in the regexp, * then the contents of each will be returned in the array. * Element [0] of a regexp match returns the entire matching string, and * the match groups start at element [1] (the first group is [1], the * second [2], and so on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#matchAll(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] match(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); if (m.find()) { int count = m.groupCount() + 1; String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } return groups; } return null; } /** * ( begin auto-generated from matchAll.xml ) * * This function is used to apply a regular expression to a piece of text, * and return a list of matching groups (elements found inside parentheses) * as a two-dimensional String array. No matches will return null. If no * groups are specified in the regexp, but the sequence matches, a two * dimensional array is still returned, but the second dimension is only of * length one.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, a 2D array is returned. If there are groups (specified by * sets of parentheses) in the regexp, then the contents of each will be * returned in the array. * Assuming, a loop with counter variable i, element [i][0] of a regexp * match returns the entire matching string, and the match groups start at * element [i][1] (the first group is [i][1], the second [i][2], and so * on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param str the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#match(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[][] matchAll(String str, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(str); ArrayList<String[]> results = new ArrayList<String[]>(); int count = m.groupCount() + 1; while (m.find()) { String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } results.add(groups); } if (results.isEmpty()) { return null; } String[][] matches = new String[results.size()][count]; for (int i = 0; i < matches.length; i++) { matches[i] = results.get(i); } return matches; } ////////////////////////////////////////////////////////////// // CASTING FUNCTIONS, INSERTED BY PREPROC /** * Convert a char to a boolean. 'T', 't', and '1' will become the * boolean value true, while 'F', 'f', or '0' will become false. */ /* static final public boolean parseBoolean(char what) { return ((what == 't') || (what == 'T') || (what == '1')); } */ /** * <p>Convert an integer to a boolean. Because of how Java handles upgrading * numbers, this will also cover byte and char (as they will upgrade to * an int without any sort of explicit cast).</p> * <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p> * @return false if 0, true if any other number */ static final public boolean parseBoolean(int what) { return (what != 0); } /* // removed because this makes no useful sense static final public boolean parseBoolean(float what) { return (what != 0); } */ /** * Convert the string "true" or "false" to a boolean. * @return true if 'what' is "true" or "TRUE", false otherwise */ static final public boolean parseBoolean(String what) { return new Boolean(what).booleanValue(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* // removed, no need to introduce strange syntax from other languages static final public boolean[] parseBoolean(char what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1')); } return outgoing; } */ /** * Convert a byte array to a boolean array. Each element will be * evaluated identical to the integer case, where a byte equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ /* static final public boolean[] parseBoolean(byte what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ /** * Convert an int array to a boolean array. An int equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ static final public boolean[] parseBoolean(int what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } /* // removed, not necessary... if necessary, convert to int array first static final public boolean[] parseBoolean(float what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ static final public boolean[] parseBoolean(String what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = new Boolean(what[i]).booleanValue(); } return outgoing; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte parseByte(boolean what) { return what ? (byte)1 : 0; } static final public byte parseByte(char what) { return (byte) what; } static final public byte parseByte(int what) { return (byte) what; } static final public byte parseByte(float what) { return (byte) what; } /* // nixed, no precedent static final public byte[] parseByte(String what) { // note: array[] return what.getBytes(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte[] parseByte(boolean what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? (byte)1 : 0; } return outgoing; } static final public byte[] parseByte(char what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(int what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(float what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } /* static final public byte[][] parseByte(String what[]) { // note: array[][] byte outgoing[][] = new byte[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].getBytes(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char parseChar(boolean what) { // 0/1 or T/F ? return what ? 't' : 'f'; } */ static final public char parseChar(byte what) { return (char) (what & 0xff); } static final public char parseChar(int what) { return (char) what; } /* static final public char parseChar(float what) { // nonsensical return (char) what; } static final public char[] parseChar(String what) { // note: array[] return what.toCharArray(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ? char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? 't' : 'f'; } return outgoing; } */ static final public char[] parseChar(byte what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) (what[i] & 0xff); } return outgoing; } static final public char[] parseChar(int what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } /* static final public char[] parseChar(float what[]) { // nonsensical char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } static final public char[][] parseChar(String what[]) { // note: array[][] char outgoing[][] = new char[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].toCharArray(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int parseInt(boolean what) { return what ? 1 : 0; } /** * Note that parseInt() will un-sign a signed byte value. */ static final public int parseInt(byte what) { return what & 0xff; } /** * Note that parseInt('5') is unlike String in the sense that it * won't return 5, but the ascii value. This is because ((int) someChar) * returns the ascii value, and parseInt() is just longhand for the cast. */ static final public int parseInt(char what) { return what; } /** * Same as floor(), or an (int) cast. */ static final public int parseInt(float what) { return (int) what; } /** * Parse a String into an int value. Returns 0 if the value is bad. */ static final public int parseInt(String what) { return parseInt(what, 0); } /** * Parse a String to an int, and provide an alternate value that * should be used when the number is invalid. */ static final public int parseInt(String what, int otherwise) { try { int offset = what.indexOf('.'); if (offset == -1) { return Integer.parseInt(what); } else { return Integer.parseInt(what.substring(0, offset)); } } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int[] parseInt(boolean what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i] ? 1 : 0; } return list; } static final public int[] parseInt(byte what[]) { // note this unsigns int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = (what[i] & 0xff); } return list; } static final public int[] parseInt(char what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i]; } return list; } static public int[] parseInt(float what[]) { int inties[] = new int[what.length]; for (int i = 0; i < what.length; i++) { inties[i] = (int)what[i]; } return inties; } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, it will be set to zero. * * String s[] = { "1", "300", "44" }; * int numbers[] = parseInt(s); * * numbers will contain { 1, 300, 44 } */ static public int[] parseInt(String what[]) { return parseInt(what, 0); } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, its entry in the * array will be set to the value of the "missing" parameter. * * String s[] = { "1", "300", "apple", "44" }; * int numbers[] = parseInt(s, 9999); * * numbers will contain { 1, 300, 9999, 44 } */ static public int[] parseInt(String what[], int missing) { int output[] = new int[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = Integer.parseInt(what[i]); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float parseFloat(boolean what) { return what ? 1 : 0; } */ /** * Convert an int to a float value. Also handles bytes because of * Java's rules for upgrading values. */ static final public float parseFloat(int what) { // also handles byte return what; } static final public float parseFloat(String what) { return parseFloat(what, Float.NaN); } static final public float parseFloat(String what, float otherwise) { try { return new Float(what).floatValue(); } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float[] parseFloat(boolean what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i] ? 1 : 0; } return floaties; } static final public float[] parseFloat(char what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = (char) what[i]; } return floaties; } */ static final public float[] parseByte(byte what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(int what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(String what[]) { return parseFloat(what, Float.NaN); } static final public float[] parseFloat(String what[], float missing) { float output[] = new float[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = new Float(what[i]).floatValue(); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String str(boolean x) { return String.valueOf(x); } static final public String str(byte x) { return String.valueOf(x); } static final public String str(char x) { return String.valueOf(x); } static final public String str(int x) { return String.valueOf(x); } static final public String str(float x) { return String.valueOf(x); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String[] str(boolean x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(byte x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(char x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(int x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(float x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } ////////////////////////////////////////////////////////////// // INT NUMBER FORMATTING /** * Integer number formatter. */ static private NumberFormat int_nf; static private int int_nf_digits; static private boolean int_nf_commas; static public String[] nf(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], digits); } return formatted; } /** * ( begin auto-generated from nf.xml ) * * Utility function for formatting numbers into strings. There are two * versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers.<br /><br />As shown in the above * example, <b>nf()</b> is used to add zeros to the left and/or right of a * number. This is typically for aligning a list of numbers. To * <em>remove</em> digits from a floating-point number, use the * <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b> * functions. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zero * @see PApplet#nfs(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) * @see PApplet#int(float) */ static public String nf(int num, int digits) { if ((int_nf != null) && (int_nf_digits == digits) && !int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(false); // no commas int_nf_commas = false; int_nf.setMinimumIntegerDigits(digits); int_nf_digits = digits; return int_nf.format(num); } /** * ( begin auto-generated from nfc.xml ) * * Utility function for formatting numbers into strings and placing * appropriate commas to mark units of 1000. There are two versions, one * for formatting ints and one for formatting an array of ints. The value * for the <b>digits</b> parameter should always be a positive integer. * <br/> <br/> * For a non-US locale, this will insert periods instead of commas, or * whatever is apprioriate for that region. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String[] nfc(int num[]) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i]); } return formatted; } /** * nfc() or "number format with commas". This is an unfortunate misnomer * because in locales where a comma is not the separator for numbers, it * won't actually be outputting a comma, it'll use whatever makes sense for * the locale. */ static public String nfc(int num) { if ((int_nf != null) && (int_nf_digits == 0) && int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(true); int_nf_commas = true; int_nf.setMinimumIntegerDigits(0); int_nf_digits = 0; return int_nf.format(num); } /** * number format signed (or space) * Formats a number but leaves a blank space in the front * when it's positive so that it can be properly aligned with * numbers that have a negative sign in front of them. */ /** * ( begin auto-generated from nfs.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but leaves a blank space in front of positive numbers so * they align with negative numbers in spite of the minus symbol. There are * two versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfs(int num, int digits) { return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits)); } static public String[] nfs(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], digits); } return formatted; } // /** * number format positive (or plus) * Formats a number, always placing a - or + sign * in the front when it's negative or positive. */ /** * ( begin auto-generated from nfp.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in * front of negative numbers. There are two versions, one for formatting * floats and one for formatting ints. The values for the <b>digits</b>, * <b>left</b>, and <b>right</b> parameters should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfp(int num, int digits) { return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits)); } static public String[] nfp(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], digits); } return formatted; } ////////////////////////////////////////////////////////////// // FLOAT NUMBER FORMATTING static private NumberFormat float_nf; static private int float_nf_left, float_nf_right; static private boolean float_nf_commas; static public String[] nf(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], left, right); } return formatted; } /** * @param num[] the number(s) to format * @param left number of digits to the left of the decimal point * @param right number of digits to the right of the decimal point */ static public String nf(float num, int left, int right) { if ((float_nf != null) && (float_nf_left == left) && (float_nf_right == right) && !float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(false); float_nf_commas = false; if (left != 0) float_nf.setMinimumIntegerDigits(left); if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = left; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param right number of digits to the right of the decimal point */ static public String[] nfc(float num[], int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i], right); } return formatted; } static public String nfc(float num, int right) { if ((float_nf != null) && (float_nf_left == 0) && (float_nf_right == right) && float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(true); float_nf_commas = true; if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = 0; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfs(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], left, right); } return formatted; } static public String nfs(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right)); } /** * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfp(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], left, right); } return formatted; } static public String nfp(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right)); } ////////////////////////////////////////////////////////////// // HEX/BINARY CONVERSION /** * ( begin auto-generated from hex.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent hexadecimal notation. For example color(0, 102, 153) will * convert to the String "FF006699". This function can help make your geeky * debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 8, because an int value can * only represent up to 32 bits. Specifying more than eight digits will * simply shorten the string to eight anyway. * * ( end auto-generated ) * @webref data:conversion * @param value the value to convert * @see PApplet#unhex(String) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public String hex(byte value) { return hex(value, 2); } static final public String hex(char value) { return hex(value, 4); } static final public String hex(int value) { return hex(value, 8); } /** * @param digits the number of digits (maximum 8) */ static final public String hex(int value, int digits) { String stuff = Integer.toHexString(value).toUpperCase(); if (digits > 8) { digits = 8; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { return "00000000".substring(8 - (digits-length)) + stuff; } return stuff; } /** * ( begin auto-generated from unhex.xml ) * * Converts a String representation of a hexadecimal number to its * equivalent integer value. * * ( end auto-generated ) * * @webref data:conversion * @param value String to convert to an integer * @see PApplet#hex(int, int) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public int unhex(String value) { // has to parse as a Long so that it'll work for numbers bigger than 2^31 return (int) (Long.parseLong(value, 16)); } // /** * Returns a String that contains the binary value of a byte. * The returned value will always have 8 digits. */ static final public String binary(byte value) { return binary(value, 8); } /** * Returns a String that contains the binary value of a char. * The returned value will always have 16 digits because chars * are two bytes long. */ static final public String binary(char value) { return binary(value, 16); } /** * Returns a String that contains the binary value of an int. The length * depends on the size of the number itself. If you want a specific number * of digits use binary(int what, int digits) to specify how many. */ static final public String binary(int value) { return binary(value, 32); } /* * Returns a String that contains the binary value of an int. * The digits parameter determines how many digits will be used. */ /** * ( begin auto-generated from binary.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent binary notation. For example color(0, 102, 153, 255) will * convert to the String "11111111000000000110011010011001". This function * can help make your geeky debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 32, because an int value can * only represent up to 32 bits. Specifying more than 32 digits will simply * shorten the string to 32 anyway. * * ( end auto-generated ) * @webref data:conversion * @param value value to convert * @param digits number of digits to return * @see PApplet#unbinary(String) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public String binary(int value, int digits) { String stuff = Integer.toBinaryString(value); if (digits > 32) { digits = 32; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { int offset = 32 - (digits-length); return "00000000000000000000000000000000".substring(offset) + stuff; } return stuff; } /** * ( begin auto-generated from unbinary.xml ) * * Converts a String representation of a binary number to its equivalent * integer value. For example, unbinary("00001000") will return 8. * * ( end auto-generated ) * @webref data:conversion * @param value String to convert to an integer * @see PApplet#binary(byte) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public int unbinary(String value) { return Integer.parseInt(value, 2); } ////////////////////////////////////////////////////////////// // COLOR FUNCTIONS // moved here so that they can work without // the graphics actually being instantiated (outside setup) /** * ( begin auto-generated from color.xml ) * * Creates colors for storing in variables of the <b>color</b> datatype. * The parameters are interpreted as RGB or HSB values depending on the * current <b>colorMode()</b>. The default mode is RGB values from 0 to 255 * and therefore, the function call <b>color(255, 204, 0)</b> will return a * bright yellow color. More about how colors are stored can be found in * the reference for the <a href="color_datatype.html">color</a> datatype. * * ( end auto-generated ) * @webref color:creating_reading * @param gray number specifying value between white and black * @see PApplet#colorMode(int) */ public final int color(int gray) { if (g == null) { if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(gray); } /** * @nowebref * @param fgray number specifying value between white and black */ public final int color(float fgray) { if (g == null) { int gray = (int) fgray; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray); } /** * As of 0116 this also takes color(#FF8800, alpha) * @param alpha relative to current color range */ public final int color(int gray, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (gray > 255) { // then assume this is actually a #FF8800 return (alpha << 24) | (gray & 0xFFFFFF); } else { //if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return (alpha << 24) | (gray << 16) | (gray << 8) | gray; } } return g.color(gray, alpha); } /** * @nowebref */ public final int color(float fgray, float falpha) { if (g == null) { int gray = (int) fgray; int alpha = (int) falpha; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray, falpha); } /** * @param v1 red or hue values relative to the current color range * @param v2 green or saturation values relative to the current color range * @param v3 blue or brightness values relative to the current color range */ public final int color(int v1, int v2, int v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3); } public final int color(int v1, int v2, int v3, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3; } return g.color(v1, v2, v3, alpha); } public final int color(float v1, float v2, float v3) { if (g == null) { if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3); } public final int color(float v1, float v2, float v3, float alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0; if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0; if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0; return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3; } return g.color(v1, v2, v3, alpha); } static public int blendColor(int c1, int c2, int mode) { return PImage.blendColor(c1, c2, mode); } ////////////////////////////////////////////////////////////// // MAIN /** * Set this sketch to communicate its state back to the PDE. * <p/> * This uses the stderr stream to write positions of the window * (so that it will be saved by the PDE for the next run) and * notify on quit. See more notes in the Worker class. */ public void setupExternalMessages() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { Point where = ((Frame) e.getSource()).getLocation(); System.err.println(PApplet.EXTERNAL_MOVE + " " + where.x + " " + where.y); System.err.flush(); // doesn't seem to help or hurt } }); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // System.err.println(PApplet.EXTERNAL_QUIT); // System.err.flush(); // important // System.exit(0); exit(); // don't quit, need to just shut everything down (0133) } }); } /** * Set up a listener that will fire proper component resize events * in cases where frame.setResizable(true) is called. */ public void setupFrameResizeListener() { frame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Ignore bad resize events fired during setup to fix // http://dev.processing.org/bugs/show_bug.cgi?id=341 // This should also fix the blank screen on Linux bug // http://dev.processing.org/bugs/show_bug.cgi?id=282 if (frame.isResizable()) { // might be multiple resize calls before visible (i.e. first // when pack() is called, then when it's resized for use). // ignore them because it's not the user resizing things. Frame farm = (Frame) e.getComponent(); if (farm.isVisible()) { Insets insets = farm.getInsets(); Dimension windowSize = farm.getSize(); // JFrame (unlike java.awt.Frame) doesn't include the left/top // insets for placement (though it does seem to need them for // overall size of the window. Perhaps JFrame sets its coord // system so that (0, 0) is always the upper-left of the content // area. Which seems nice, but breaks any f*ing AWT-based code. Rectangle newBounds = new Rectangle(0, 0, //insets.left, insets.top, windowSize.width - insets.left - insets.right, windowSize.height - insets.top - insets.bottom); Rectangle oldBounds = getBounds(); if (!newBounds.equals(oldBounds)) { // the ComponentListener in PApplet will handle calling size() setBounds(newBounds); revalidate(); // let the layout manager do its work } } } } }); } // /** // * GIF image of the Processing logo. // */ // static public final byte[] ICON_IMAGE = { // 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12, // 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117, // 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37, // 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16, // 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45, // 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100, // 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48, // -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25, // 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2, // 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62, // 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102, // 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59 // }; static ArrayList<Image> iconImages; protected void setIconImage(Frame frame) { // On OS X, this only affects what shows up in the dock when minimized. // So this is actually a step backwards. Brilliant. if (platform != MACOSX) { //Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); //frame.setIconImage(image); try { if (iconImages == null) { iconImages = new ArrayList<Image>(); final int[] sizes = { 16, 32, 48, 64 }; for (int sz : sizes) { URL url = getClass().getResource("/icon/icon-" + sz + ".png"); Image image = Toolkit.getDefaultToolkit().getImage(url); iconImages.add(image); //iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame)); } } frame.setIconImages(iconImages); } catch (Exception e) { //e.printStackTrace(); // more or less harmless; don't spew errors } } } // Not gonna do this dynamically, only on startup. Too much headache. // public void fullscreen() { // if (frame != null) { // if (PApplet.platform == MACOSX) { // japplemenubar.JAppleMenuBar.hide(); // } // GraphicsConfiguration gc = frame.getGraphicsConfiguration(); // Rectangle rect = gc.getBounds(); //// GraphicsDevice device = gc.getDevice(); // frame.setBounds(rect.x, rect.y, rect.width, rect.height); // } // } /** * main() method for running this class from the command line. * <p> * <B>The options shown here are not yet finalized and will be * changing over the next several releases.</B> * <p> * The simplest way to turn and applet into an application is to * add the following code to your program: * <PRE>static public void main(String args[]) { * PApplet.main("YourSketchName", args); * }</PRE> * This will properly launch your applet from a double-clickable * .jar or from the command line. * <PRE> * Parameters useful for launching or also used by the PDE: * * --location=x,y upper-lefthand corner of where the applet * should appear on screen. if not used, * the default is to center on the main screen. * * --full-screen put the applet into full screen "present" mode. * * --hide-stop use to hide the stop button in situations where * you don't want to allow users to exit. also * see the FAQ on information for capturing the ESC * key when running in presentation mode. * * --stop-color=#xxxxxx color of the 'stop' text used to quit an * sketch when it's in present mode. * * --bgcolor=#xxxxxx background color of the window. * * --sketch-path location of where to save files from functions * like saveStrings() or saveFrame(). defaults to * the folder that the java application was * launched from, which means if this isn't set by * the pde, everything goes into the same folder * as processing.exe. * * --display=n set what display should be used by this sketch. * displays are numbered starting from 0. * * Parameters used by Processing when running via the PDE * * --external set when the applet is being used by the PDE * * --editor-location=x,y position of the upper-lefthand corner of the * editor window, for placement of applet window * </PRE> */ static public void main(final String[] args) { runSketch(args, null); } /** * Convenience method so that PApplet.main("YourSketch") launches a sketch, * rather than having to wrap it into a String array. * @param mainClass name of the class to load (with package if any) */ static public void main(final String mainClass) { main(mainClass, null); } /** * Convenience method so that PApplet.main("YourSketch", args) launches a * sketch, rather than having to wrap it into a String array, and appending * the 'args' array when not null. * @param mainClass name of the class to load (with package if any) * @param args command line arguments to pass to the sketch */ static public void main(final String mainClass, final String[] passedArgs) { String[] args = new String[] { mainClass }; if (passedArgs != null) { args = concat(args, passedArgs); } runSketch(args, null); } static public void runSketch(final String args[], final PApplet constructedApplet) { // Disable abyssmally slow Sun renderer on OS X 10.5. if (platform == MACOSX) { // Only run this on OS X otherwise it can cause a permissions error. // http://dev.processing.org/bugs/show_bug.cgi?id=976 System.setProperty("apple.awt.graphics.UseQuartz", String.valueOf(useQuartz)); } // Doesn't seem to do much to help avoid flicker System.setProperty("sun.awt.noerasebackground", "true"); // This doesn't do anything. // if (platform == WINDOWS) { // // For now, disable the D3D renderer on Java 6u10 because // // it causes problems with Present mode. // // http://dev.processing.org/bugs/show_bug.cgi?id=1009 // System.setProperty("sun.java2d.d3d", "false"); // } if (args.length < 1) { System.err.println("Usage: PApplet <appletname>"); System.err.println("For additional options, " + "see the Javadoc for PApplet"); System.exit(1); } // EventQueue.invokeLater(new Runnable() { // public void run() { // runSketchEDT(args, constructedApplet); // } // }); // } // // // static public void runSketchEDT(final String args[], final PApplet constructedApplet) { boolean external = false; int[] location = null; int[] editorLocation = null; String name = null; boolean present = false; // boolean exclusive = false; // Color backgroundColor = Color.BLACK; Color backgroundColor = null; //Color.BLACK; Color stopColor = Color.GRAY; GraphicsDevice displayDevice = null; boolean hideStop = false; String param = null, value = null; // try to get the user folder. if running under java web start, // this may cause a security exception if the code is not signed. // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 String folder = null; try { folder = System.getProperty("user.dir"); } catch (Exception e) { } int argIndex = 0; while (argIndex < args.length) { int equals = args[argIndex].indexOf('='); if (equals != -1) { param = args[argIndex].substring(0, equals); value = args[argIndex].substring(equals + 1); if (param.equals(ARGS_EDITOR_LOCATION)) { external = true; editorLocation = parseInt(split(value, ',')); } else if (param.equals(ARGS_DISPLAY)) { int deviceIndex = Integer.parseInt(value); GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice devices[] = environment.getScreenDevices(); if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { displayDevice = devices[deviceIndex]; } else { System.err.println("Display " + value + " does not exist, " + "using the default display instead."); for (int i = 0; i < devices.length; i++) { System.err.println(i + " is " + devices[i]); } } } else if (param.equals(ARGS_BGCOLOR)) { if (value.charAt(0) == '#') value = value.substring(1); backgroundColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_STOP_COLOR)) { if (value.charAt(0) == '#') value = value.substring(1); stopColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_SKETCH_FOLDER)) { folder = value; } else if (param.equals(ARGS_LOCATION)) { location = parseInt(split(value, ',')); } } else { if (args[argIndex].equals(ARGS_PRESENT)) { // keep for compatability present = true; } else if (args[argIndex].equals(ARGS_FULL_SCREEN)) { present = true; // } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { // exclusive = true; } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { hideStop = true; } else if (args[argIndex].equals(ARGS_EXTERNAL)) { external = true; } else { name = args[argIndex]; break; // because of break, argIndex won't increment again } } argIndex++; } // Now that sketch path is passed in args after the sketch name // it's not set in the above loop(the above loop breaks after // finding sketch name). So setting sketch path here. for (int i = 0; i < args.length; i++) { if(args[i].startsWith(ARGS_SKETCH_FOLDER)){ folder = args[i].substring(args[i].indexOf('=') + 1); //System.err.println("SF set " + folder); } } // Set this property before getting into any GUI init code //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); // This )*)(*@#$ Apple crap don't work no matter where you put it // (static method of the class, at the top of main, wherever) if (displayDevice == null) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); displayDevice = environment.getDefaultScreenDevice(); } // Using a JFrame fixes a Windows problem with Present mode. This might // be our error, but usually this is the sort of crap we usually get from // OS X. It's time for a turnaround: Redmond is thinking different too! // https://github.com/processing/processing/issues/1955 Frame frame = new JFrame(displayDevice.getDefaultConfiguration()); // Default Processing gray, which will be replaced below if another // color is specified on the command line (i.e. in the prefs). final Color defaultGray = new Color(0xCC, 0xCC, 0xCC); ((JFrame) frame).getContentPane().setBackground(defaultGray); // Cannot call setResizable(false) until later due to OS X (issue #467) final PApplet applet; if (constructedApplet != null) { applet = constructedApplet; } else { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name); applet = (PApplet) c.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } // Set the trimmings around the image applet.setIconImage(frame); frame.setTitle(name); // frame.setIgnoreRepaint(true); // does nothing // frame.addComponentListener(new ComponentAdapter() { // public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); //// Rectangle bounds = c.getBounds(); // System.out.println(" " + c.getName() + " wants to be: " + c.getSize()); // } // }); // frame.addComponentListener(new ComponentListener() { // // public void componentShown(ComponentEvent e) { // debug("frame: " + e); // debug(" applet valid? " + applet.isValid()); //// ((PGraphicsJava2D) applet.g).redraw(); // } // // public void componentResized(ComponentEvent e) { // println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentResized() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentMoved(ComponentEvent e) { // //println("frame: " + e + " " + applet.frame.getInsets()); // Insets insets = applet.frame.getInsets(); // int wide = e.getComponent().getWidth() - (insets.left + insets.right); // int high = e.getComponent().getHeight() - (insets.top + insets.bottom); // //applet.g.setsi // if (applet.getWidth() != wide || applet.getHeight() != high) { // debug("Frame.componentMoved() setting applet size " + wide + " " + high); // applet.setSize(wide, high); // } // } // // public void componentHidden(ComponentEvent e) { // debug("frame: " + e); // } // }); // A handful of things that need to be set before init/start. applet.frame = frame; applet.sketchPath = folder; // If the applet doesn't call for full screen, but the command line does, // enable it. Conversely, if the command line does not, don't disable it. // applet.fullScreen |= present; // Query the applet to see if it wants to be full screen all the time. present |= applet.sketchFullScreen(); // pass everything after the class name in as args to the sketch itself // (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts) applet.args = PApplet.subset(args, argIndex + 1); applet.external = external; // Need to save the window bounds at full screen, // because pack() will cause the bounds to go to zero. // http://dev.processing.org/bugs/show_bug.cgi?id=923 Rectangle screenRect = displayDevice.getDefaultConfiguration().getBounds(); // DisplayMode doesn't work here, because we can't get the upper-left // corner of the display, which is important for multi-display setups. // Sketch has already requested to be the same as the screen's // width and height, so let's roll with full screen mode. if (screenRect.width == applet.sketchWidth() && screenRect.height == applet.sketchHeight()) { present = true; } // For 0149, moving this code (up to the pack() method) before init(). // For OpenGL (and perhaps other renderers in the future), a peer is // needed before a GLDrawable can be created. So pack() needs to be // called on the Frame before applet.init(), which itself calls size(), // and launches the Thread that will kick off setup(). // http://dev.processing.org/bugs/show_bug.cgi?id=891 // http://dev.processing.org/bugs/show_bug.cgi?id=908 if (present) { // if (platform == MACOSX) { // // Call some native code to remove the menu bar on OS X. Not necessary // // on Linux and Windows, who are happy to make full screen windows. // japplemenubar.JAppleMenuBar.hide(); // } // Tried to use this to fix the 'present' mode issue. // Did not help, and the screenRect setup seems to work fine. //frame.setExtendedState(Frame.MAXIMIZED_BOTH); frame.setUndecorated(true); if (backgroundColor != null) { ((JFrame) frame).getContentPane().setBackground(backgroundColor); } // if (exclusive) { // displayDevice.setFullScreenWindow(frame); // // this trashes the location of the window on os x // //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); // fullScreenRect = frame.getBounds(); // } else { frame.setBounds(screenRect); frame.setVisible(true); // } } frame.setLayout(null); frame.add(applet); if (present) { frame.invalidate(); } else { frame.pack(); } // insufficient, places the 100x100 sketches offset strangely //frame.validate(); // disabling resize has to happen after pack() to avoid apparent Apple bug // http://code.google.com/p/processing/issues/detail?id=467 frame.setResizable(false); applet.init(); // applet.start(); // Wait until the applet has figured out its width. // In a static mode app, this will be after setup() has completed, // and the empty draw() has set "finished" to true. // TODO make sure this won't hang if the applet has an exception. while (applet.defaultSize && !applet.finished) { //System.out.println("default size"); try { Thread.sleep(5); } catch (InterruptedException e) { //System.out.println("interrupt"); } } // // If 'present' wasn't already set, but the applet initializes // // to full screen, attempt to make things full screen anyway. // if (!present && // applet.width == screenRect.width && // applet.height == screenRect.height) { // // bounds will be set below, but can't change to setUndecorated() now // present = true; // } // // Opting not to do this, because we can't remove the decorations on the // // window at this point. And re-opening a new winodw is a lot of mess. // // Better all around to just encourage the use of sketchFullScreen() // // or cmd/ctrl-shift-R in the PDE. if (present) { if (platform == MACOSX) { // Call some native code to remove the menu bar on OS X. Not necessary // on Linux and Windows, who are happy to make full screen windows. japplemenubar.JAppleMenuBar.hide(); } // After the pack(), the screen bounds are gonna be 0s frame.setBounds(screenRect); applet.setBounds((screenRect.width - applet.width) / 2, (screenRect.height - applet.height) / 2, applet.width, applet.height); if (!hideStop) { Label label = new Label("stop"); label.setForeground(stopColor); label.addMouseListener(new MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { System.exit(0); } }); frame.add(label); Dimension labelSize = label.getPreferredSize(); // sometimes shows up truncated on mac //System.out.println("label width is " + labelSize.width); labelSize = new Dimension(100, labelSize.height); label.setSize(labelSize); label.setLocation(20, screenRect.height - labelSize.height - 20); } // not always running externally when in present mode if (external) { applet.setupExternalMessages(); } } else { // if not presenting // can't do pack earlier cuz present mode don't like it // (can't go full screen with a frame after calling pack) // frame.pack(); // get insets. get more. Insets insets = frame.getInsets(); int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; int contentW = Math.max(applet.width, MIN_WINDOW_WIDTH); int contentH = Math.max(applet.height, MIN_WINDOW_HEIGHT); frame.setSize(windowW, windowH); if (location != null) { // a specific location was received from the Runner // (applet has been run more than once, user placed window) frame.setLocation(location[0], location[1]); } else if (external && editorLocation != null) { int locationX = editorLocation[0] - 20; int locationY = editorLocation[1]; if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // doesn't fit // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = editorLocation[0] + 66; locationY = editorLocation[1] + 66; if ((locationX + windowW > applet.displayWidth - 33) || (locationY + windowH > applet.displayHeight - 33)) { // otherwise center on screen locationX = (applet.displayWidth - windowW) / 2; locationY = (applet.displayHeight - windowH) / 2; } frame.setLocation(locationX, locationY); } } else { // just center on screen // Can't use frame.setLocationRelativeTo(null) because it sends the // frame to the main display, which undermines the --display setting. frame.setLocation(screenRect.x + (screenRect.width - applet.width) / 2, screenRect.y + (screenRect.height - applet.height) / 2); } Point frameLoc = frame.getLocation(); if (frameLoc.y < 0) { // Windows actually allows you to place frames where they can't be // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 frame.setLocation(frameLoc.x, 30); } if (backgroundColor != null) { // if (backgroundColor == Color.black) { //BLACK) { // // this means no bg color unless specified // backgroundColor = SystemColor.control; // } ((JFrame) frame).getContentPane().setBackground(backgroundColor); } // int usableWindowH = windowH - insets.top - insets.bottom; // applet.setBounds((windowW - applet.width)/2, // insets.top + (usableWindowH - applet.height)/2, // applet.width, applet.height); applet.setBounds((contentW - applet.width)/2, (contentH - applet.height)/2, applet.width, applet.height); if (external) { applet.setupExternalMessages(); } else { // !external frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); } // handle frame resizing events applet.setupFrameResizeListener(); // all set for rockin if (applet.displayable()) { frame.setVisible(true); // Linux doesn't deal with insets the same way. We get fake insets // earlier, and then the window manager will slap its own insets // onto things once the frame is realized on the screen. Awzm. if (platform == LINUX) { Insets irlInsets = frame.getInsets(); if (!irlInsets.equals(insets)) { insets = irlInsets; windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; frame.setSize(windowW, windowH); } } } } // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // (Although this doesn't seem to be the one that was causing problems.) //applet.requestFocus(); // ask for keydowns } /** * These methods provide a means for running an already-constructed * sketch. In particular, it makes it easy to launch a sketch in * Jython: * * <pre>class MySketch(PApplet): * pass * *MySketch().runSketch();</pre> */ protected void runSketch(final String[] args) { final String[] argsWithSketchName = new String[args.length + 1]; System.arraycopy(args, 0, argsWithSketchName, 0, args.length); final String className = this.getClass().getSimpleName(); final String cleanedClass = className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); argsWithSketchName[args.length] = cleanedClass; runSketch(argsWithSketchName, this); } protected void runSketch() { runSketch(new String[0]); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from beginRecord.xml ) * * Opens a new file and all subsequent drawing functions are echoed to this * file as well as the display window. The <b>beginRecord()</b> function * requires two parameters, the first is the renderer and the second is the * file name. This function is always used with <b>endRecord()</b> to stop * the recording process and close the file. * <br /> <br /> * Note that beginRecord() will only pick up any settings that happen after * it has been called. For instance, if you call textFont() before * beginRecord(), then that font will not be set for the file that you're * recording to. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF * @param filename filename for output * @see PApplet#endRecord() */ public PGraphics beginRecord(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); beginRecord(rec); return rec; } /** * @nowebref * Begin recording (echoing) commands to the specified PGraphics object. */ public void beginRecord(PGraphics recorder) { this.recorder = recorder; recorder.beginDraw(); } /** * ( begin auto-generated from endRecord.xml ) * * Stops the recording process started by <b>beginRecord()</b> and closes * the file. * * ( end auto-generated ) * @webref output:files * @see PApplet#beginRecord(String, String) */ public void endRecord() { if (recorder != null) { recorder.endDraw(); recorder.dispose(); recorder = null; } } /** * ( begin auto-generated from beginRaw.xml ) * * To create vectors from 3D data, use the <b>beginRaw()</b> and * <b>endRaw()</b> commands. These commands will grab the shape data just * before it is rendered to the screen. At this stage, your entire scene is * nothing but a long list of individual lines and triangles. This means * that a shape created with <b>sphere()</b> function will be made up of * hundreds of triangles, rather than a single object. Or that a * multi-segment line shape (such as a curve) will be rendered as * individual segments. * <br /><br /> * When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write * to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the * PDF library will write the geometry as flattened triangles and lines, * even if recording from the <b>P3D</b> renderer. * <br /><br /> * If you want a background to show up in your files, use <b>rect(0, 0, * width, height)</b> after setting the <b>fill()</b> to the background * color. Otherwise the background will not be rendered to the file because * the background is not shape. * <br /><br /> * Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D * geometry drawn to 2D file formats. See the <b>hint()</b> reference for * more details. * <br /><br /> * See examples in the reference for the <b>PDF</b> and <b>DXF</b> * libraries for more information. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF or DXF * @param filename filename for output * @see PApplet#endRaw() * @see PApplet#hint(int) */ public PGraphics beginRaw(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); g.beginRaw(rec); return rec; } /** * @nowebref * Begin recording raw shape data to the specified renderer. * * This simply echoes to g.beginRaw(), but since is placed here (rather than * generated by preproc.pl) for clarity and so that it doesn't echo the * command should beginRecord() be in use. * * @param rawGraphics ??? */ public void beginRaw(PGraphics rawGraphics) { g.beginRaw(rawGraphics); } /** * ( begin auto-generated from endRaw.xml ) * * Complement to <b>beginRaw()</b>; they must always be used together. See * the <b>beginRaw()</b> reference for details. * * ( end auto-generated ) * * @webref output:files * @see PApplet#beginRaw(String, String) */ public void endRaw() { g.endRaw(); } /** * Starts shape recording and returns the PShape object that will * contain the geometry. */ /* public PShape beginRecord() { return g.beginRecord(); } */ ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from loadPixels.xml ) * * Loads the pixel data for the display window into the <b>pixels[]</b> * array. This function must always be called before reading from or * writing to <b>pixels[]</b>. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * * ( end auto-generated ) * <h3>Advanced</h3> * Override the g.pixels[] function to set the pixels[] array * that's part of the PApplet object. Allows the use of * pixels[] in the code, rather than g.pixels[]. * * @webref image:pixels * @see PApplet#pixels * @see PApplet#updatePixels() */ public void loadPixels() { g.loadPixels(); pixels = g.pixels; } /** * ( begin auto-generated from updatePixels.xml ) * * Updates the display window with the data in the <b>pixels[]</b> array. * Use in conjunction with <b>loadPixels()</b>. If you're only reading * pixels from the array, there's no need to call <b>updatePixels()</b> * unless there are changes. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * <br/> <br/> * Currently, none of the renderers use the additional parameters to * <b>updatePixels()</b>, however this may be implemented in the future. * * ( end auto-generated ) * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#pixels */ public void updatePixels() { g.updatePixels(); } /** * @nowebref * @param x1 x-coordinate of the upper-left corner * @param y1 y-coordinate of the upper-left corner * @param x2 width of the region * @param y2 height of the region */ public void updatePixels(int x1, int y1, int x2, int y2) { g.updatePixels(x1, y1, x2, y2); } ////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! // This includes the Javadoc comments, which are automatically copied from // the PImage and PGraphics source code files. // public functions for processing.core /** * Store data of some kind for the renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. * @param renderer The PGraphics renderer associated to the image * @param storage The metadata required by the renderer */ public void setCache(PImage image, Object storage) { if (recorder != null) recorder.setCache(image, storage); g.setCache(image, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param renderer The PGraphics renderer associated to the image * @return metadata stored for the specified renderer */ public Object getCache(PImage image) { return g.getCache(image); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose cache data should be removed */ public void removeCache(PImage image) { if (recorder != null) recorder.removeCache(image); g.removeCache(image); } public PGL beginPGL() { return g.beginPGL(); } public void endPGL() { if (recorder != null) recorder.endPGL(); g.endPGL(); } public void flush() { if (recorder != null) recorder.flush(); g.flush(); } public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } /** * Start a new shape of type POLYGON */ public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } /** * ( begin auto-generated from beginShape.xml ) * * Using the <b>beginShape()</b> and <b>endShape()</b> functions allow * creating more complex forms. <b>beginShape()</b> begins recording * vertices for a shape and <b>endShape()</b> stops recording. The value of * the <b>MODE</b> parameter tells it which types of shapes to create from * the provided vertices. With no mode specified, the shape can be any * irregular polygon. The parameters available for beginShape() are POINTS, * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. * After calling the <b>beginShape()</b> function, a series of * <b>vertex()</b> commands must follow. To stop drawing the shape, call * <b>endShape()</b>. The <b>vertex()</b> function with two parameters * specifies a position in 2D and the <b>vertex()</b> function with three * parameters specifies a position in 3D. Each shape will be outlined with * the current stroke color and filled with the fill color. * <br/> <br/> * Transformations such as <b>translate()</b>, <b>rotate()</b>, and * <b>scale()</b> do not work within <b>beginShape()</b>. It is also not * possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b> * within <b>beginShape()</b>. * <br/> <br/> * The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b> * settings to be altered per-vertex, however the default P2D renderer does * not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and * <b>strokeJoin()</b> cannot be changed while inside a * <b>beginShape()</b>/<b>endShape()</b> block with any renderer. * * ( end auto-generated ) * @webref shape:vertex * @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP * @see PShape * @see PGraphics#endShape() * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) */ public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } /** * Sets whether the upcoming vertex is part of an edge. * Equivalent to glEdgeFlag(), for people familiar with OpenGL. */ public void edge(boolean edge) { if (recorder != null) recorder.edge(edge); g.edge(edge); } /** * ( begin auto-generated from normal.xml ) * * Sets the current normal vector. This is for drawing three dimensional * shapes and surfaces and specifies a vector perpendicular to the surface * of the shape which determines how lighting affects it. Processing * attempts to automatically assign normals to shapes, but since that's * imperfect, this is a better option when you want more control. This * function is identical to glNormal3f() in OpenGL. * * ( end auto-generated ) * @webref lights_camera:lights * @param nx x direction * @param ny y direction * @param nz z direction * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#lights() */ public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } /** * ( begin auto-generated from textureMode.xml ) * * Sets the coordinate space for texture mapping. There are two options, * IMAGE, which refers to the actual coordinates of the image, and * NORMAL, which refers to a normalized space of values ranging from 0 * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200 * pixels, mapping the image onto the entire size of a quad would require * the points (0,0) (0,100) (100,200) (0,200). The same mapping in * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). * * ( end auto-generated ) * @webref image:textures * @param mode either IMAGE or NORMAL * @see PGraphics#texture(PImage) * @see PGraphics#textureWrap(int) */ public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } /** * ( begin auto-generated from textureWrap.xml ) * * Description to come... * * ( end auto-generated from textureWrap.xml ) * * @webref image:textures * @param wrap Either CLAMP (default) or REPEAT * @see PGraphics#texture(PImage) * @see PGraphics#textureMode(int) */ public void textureWrap(int wrap) { if (recorder != null) recorder.textureWrap(wrap); g.textureWrap(wrap); } /** * ( begin auto-generated from texture.xml ) * * Sets a texture to be applied to vertex points. The <b>texture()</b> * function must be called between <b>beginShape()</b> and * <b>endShape()</b> and before any calls to <b>vertex()</b>. * <br/> <br/> * When textures are in use, the fill color is ignored. Instead, use tint() * to specify the color of the texture as it is applied to the shape. * * ( end auto-generated ) * @webref image:textures * @param image reference to a PImage object * @see PGraphics#textureMode(int) * @see PGraphics#textureWrap(int) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) */ public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } /** * Removes texture image for current shape. * Needs to be called between beginShape and endShape * */ public void noTexture() { if (recorder != null) recorder.noTexture(); g.noTexture(); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } /** * Used by renderer subclasses or PShape to efficiently pass in already * formatted vertex information. * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT */ public void vertex(float[] v) { if (recorder != null) recorder.vertex(v); g.vertex(v); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } /** * ( begin auto-generated from vertex.xml ) * * All shapes are constructed by connecting a series of vertices. * <b>vertex()</b> is used to specify the vertex coordinates for points, * lines, triangles, quads, and polygons and is used exclusively within the * <b>beginShape()</b> and <b>endShape()</b> function.<br /> * <br /> * Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D * parameter in combination with size as shown in the above example.<br /> * <br /> * This function is also used to map a texture onto the geometry. The * <b>texture()</b> function declares the texture to apply to the geometry * and the <b>u</b> and <b>v</b> coordinates set define the mapping of this * texture to the form. By default, the coordinates used for <b>u</b> and * <b>v</b> are specified in relation to the image's size in pixels, but * this relation can be changed with <b>textureMode()</b>. * * ( end auto-generated ) * @webref shape:vertex * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex * @param z z-coordinate of the vertex * @param u horizontal coordinate for the texture mapping * @param v vertical coordinate for the texture mapping * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#texture(PImage) */ public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } /** * @webref shape:vertex */ public void beginContour() { if (recorder != null) recorder.beginContour(); g.beginContour(); } /** * @webref shape:vertex */ public void endContour() { if (recorder != null) recorder.endContour(); g.endContour(); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } /** * ( begin auto-generated from endShape.xml ) * * The <b>endShape()</b> function is the companion to <b>beginShape()</b> * and may only be called after <b>beginShape()</b>. When <b>endshape()</b> * is called, all of image data defined since the previous call to * <b>beginShape()</b> is written into the image buffer. The constant CLOSE * as the value for the MODE parameter to close the shape (to connect the * beginning and the end). * * ( end auto-generated ) * @webref shape:vertex * @param mode use CLOSE to close the shape * @see PShape * @see PGraphics#beginShape(int) */ public void endShape(int mode) { if (recorder != null) recorder.endShape(mode); g.endShape(mode); } /** * @webref shape * @param filename name of file to load, can be .svg or .obj * @see PShape * @see PApplet#createShape() */ public PShape loadShape(String filename) { return g.loadShape(filename); } public PShape loadShape(String filename, String options) { return g.loadShape(filename, options); } /** * @webref shape * @see PShape * @see PShape#endShape() * @see PApplet#loadShape(String) */ public PShape createShape() { return g.createShape(); } public PShape createShape(PShape source) { return g.createShape(source); } /** * @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP */ public PShape createShape(int type) { return g.createShape(type); } /** * @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX * @param p parameters that match the kind of shape */ public PShape createShape(int kind, float... p) { return g.createShape(kind, p); } /** * ( begin auto-generated from loadShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param fragFilename name of fragment shader file */ public PShader loadShader(String fragFilename) { return g.loadShader(fragFilename); } /** * @param vertFilename name of vertex shader file */ public PShader loadShader(String fragFilename, String vertFilename) { return g.loadShader(fragFilename, vertFilename); } /** * ( begin auto-generated from shader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders * @param shader name of shader file */ public void shader(PShader shader) { if (recorder != null) recorder.shader(shader); g.shader(shader); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void shader(PShader shader, int kind) { if (recorder != null) recorder.shader(shader, kind); g.shader(shader, kind); } /** * ( begin auto-generated from resetShader.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref rendering:shaders */ public void resetShader() { if (recorder != null) recorder.resetShader(); g.resetShader(); } /** * @param kind type of shader, either POINTS, LINES, or TRIANGLES */ public void resetShader(int kind) { if (recorder != null) recorder.resetShader(kind); g.resetShader(kind); } /** * @param shader the fragment shader to apply */ public void filter(PShader shader) { if (recorder != null) recorder.filter(shader); g.filter(shader); } /* * @webref rendering:shaders * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default */ public void clip(float a, float b, float c, float d) { if (recorder != null) recorder.clip(a, b, c, d); g.clip(a, b, c, d); } /* * @webref rendering:shaders */ public void noClip() { if (recorder != null) recorder.noClip(); g.noClip(); } /** * ( begin auto-generated from blendMode.xml ) * * This is a new reference entry for Processing 2.0. It will be updated shortly. * * ( end auto-generated ) * * @webref Rendering * @param mode the blending mode to use */ public void blendMode(int mode) { if (recorder != null) recorder.blendMode(mode); g.blendMode(mode); } public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); g.bezierVertex(x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezierVertex.xml ) * * Specifies vertex coordinates for Bezier curves. Each call to * <b>bezierVertex()</b> defines the position of two control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time <b>bezierVertex()</b> is used within a * <b>beginShape()</b> call, it must be prefaced with a call to * <b>vertex()</b> to set the first anchor point. This function must be * used between <b>beginShape()</b> and <b>endShape()</b> and only when * there is no MODE parameter specified to <b>beginShape()</b>. Using the * 3D version requires rendering with P3D (see the Environment reference * for more information). * * ( end auto-generated ) * @webref shape:vertex * @param x2 the x-coordinate of the 1st control point * @param y2 the y-coordinate of the 1st control point * @param z2 the z-coordinate of the 1st control point * @param x3 the x-coordinate of the 2nd control point * @param y3 the y-coordinate of the 2nd control point * @param z3 the z-coordinate of the 2nd control point * @param x4 the x-coordinate of the anchor point * @param y4 the y-coordinate of the anchor point * @param z4 the z-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * @webref shape:vertex * @param cx the x-coordinate of the control point * @param cy the y-coordinate of the control point * @param x3 the x-coordinate of the anchor point * @param y3 the y-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void quadraticVertex(float cx, float cy, float x3, float y3) { if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3); g.quadraticVertex(cx, cy, x3, y3); } /** * @param cz the z-coordinate of the control point * @param z3 the z-coordinate of the anchor point */ public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3); g.quadraticVertex(cx, cy, cz, x3, y3, z3); } /** * ( begin auto-generated from curveVertex.xml ) * * Specifies vertex coordinates for curves. This function may only be used * between <b>beginShape()</b> and <b>endShape()</b> and only when there is * no MODE parameter specified to <b>beginShape()</b>. The first and last * points in a series of <b>curveVertex()</b> lines will be used to guide * the beginning and end of a the curve. A minimum of four points is * required to draw a tiny curve between the second and third points. * Adding a fifth point with <b>curveVertex()</b> will draw the curve * between the second, third, and fourth points. The <b>curveVertex()</b> * function is an implementation of Catmull-Rom splines. Using the 3D * version requires rendering with P3D (see the Environment reference for * more information). * * ( end auto-generated ) * * @webref shape:vertex * @param x the x-coordinate of the vertex * @param y the y-coordinate of the vertex * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) */ public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } /** * @param z the z-coordinate of the vertex */ public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } /** * ( begin auto-generated from point.xml ) * * Draws a point, a coordinate in space at the dimension of one pixel. The * first parameter is the horizontal value for the point, the second value * is the vertical value for the point, and the optional third value is the * depth value. Drawing this shape in 3D with the <b>z</b> parameter * requires the P3D parameter in combination with <b>size()</b> as shown in * the above example. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param x x-coordinate of the point * @param y y-coordinate of the point */ public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } /** * @param z z-coordinate of the point */ public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } /** * ( begin auto-generated from line.xml ) * * Draws a line (a direct path between two points) to the screen. The * version of <b>line()</b> with four parameters draws the line in 2D. To * color a line, use the <b>stroke()</b> function. A line cannot be filled, * therefore the <b>fill()</b> function will not affect the color of a * line. 2D lines are drawn with a width of one pixel by default, but this * can be changed with the <b>strokeWeight()</b> function. The version with * six parameters allows the line to be placed anywhere within XYZ space. * Drawing this shape in 3D with the <b>z</b> parameter requires the P3D * parameter in combination with <b>size()</b> as shown in the above example. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) * @see PGraphics#beginShape() */ public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } /** * @param z1 z-coordinate of the first point * @param z2 z-coordinate of the second point */ public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } /** * ( begin auto-generated from triangle.xml ) * * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param x3 x-coordinate of the third point * @param y3 y-coordinate of the third point * @see PApplet#beginShape() */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } /** * ( begin auto-generated from quad.xml ) * * A quad is a quadrilateral, a four sided polygon. It is similar to a * rectangle, but the angles between its edges are not constrained to * ninety degrees. The first pair of parameters (x1,y1) sets the first * vertex and the subsequent pairs should proceed clockwise or * counter-clockwise around the defined shape. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first corner * @param y1 y-coordinate of the first corner * @param x2 x-coordinate of the second corner * @param y2 y-coordinate of the second corner * @param x3 x-coordinate of the third corner * @param y3 y-coordinate of the third corner * @param x4 x-coordinate of the fourth corner * @param y4 y-coordinate of the fourth corner */ public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from rectMode.xml ) * * Modifies the location from which rectangles draw. The default mode is * <b>rectMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>rect()</b> to specify the width and height. The syntax * <b>rectMode(CORNERS)</b> uses the first and second parameters of * <b>rect()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>rectMode(CENTER)</b> draws the image from its center point and uses * the third and forth parameters of <b>rect()</b> to specify the image's * width and height. The syntax <b>rectMode(RADIUS)</b> draws the image * from its center point and uses the third and forth parameters of * <b>rect()</b> to specify half of the image's width and height. The * parameter must be written in ALL CAPS because Processing is a case * sensitive language. Note: In version 125, the mode named CENTER_RADIUS * was shortened to RADIUS. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CORNER, CORNERS, CENTER, or RADIUS * @see PGraphics#rect(float, float, float, float) */ public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } /** * ( begin auto-generated from rect.xml ) * * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. These parameters may be changed with the * <b>rectMode()</b> function. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default * @see PGraphics#rectMode(int) * @see PGraphics#quad(float, float, float, float, float, float, float, float) */ public void rect(float a, float b, float c, float d) { if (recorder != null) recorder.rect(a, b, c, d); g.rect(a, b, c, d); } /** * @param r radii for all four corners */ public void rect(float a, float b, float c, float d, float r) { if (recorder != null) recorder.rect(a, b, c, d, r); g.rect(a, b, c, d, r); } /** * @param tl radius for top-left corner * @param tr radius for top-right corner * @param br radius for bottom-right corner * @param bl radius for bottom-left corner */ public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl); g.rect(a, b, c, d, tl, tr, br, bl); } /** * ( begin auto-generated from ellipseMode.xml ) * * The origin of the ellipse is modified by the <b>ellipseMode()</b> * function. The default configuration is <b>ellipseMode(CENTER)</b>, which * specifies the location of the ellipse as the center of the shape. The * <b>RADIUS</b> mode is the same, but the width and height parameters to * <b>ellipse()</b> specify the radius of the ellipse, rather than the * diameter. The <b>CORNER</b> mode draws the shape from the upper-left * corner of its bounding box. The <b>CORNERS</b> mode uses the four * parameters to <b>ellipse()</b> to set two opposing corners of the * ellipse's bounding box. The parameter must be written in ALL CAPS * because Processing is a case-sensitive language. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CENTER, RADIUS, CORNER, or CORNERS * @see PApplet#ellipse(float, float, float, float) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } /** * ( begin auto-generated from ellipse.xml ) * * Draws an ellipse (oval) in the display window. An ellipse with an equal * <b>width</b> and <b>height</b> is a circle. The first two parameters set * the location, the third sets the width, and the fourth sets the height. * The origin may be changed with the <b>ellipseMode()</b> function. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the ellipse * @param b y-coordinate of the ellipse * @param c width of the ellipse by default * @param d height of the ellipse by default * @see PApplet#ellipseMode(int) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } /** * ( begin auto-generated from arc.xml ) * * Draws an arc in the display window. Arcs are drawn along the outer edge * of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and * <b>height</b> parameters. The origin or the arc's ellipse may be changed * with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b> * parameters specify the angles at which to draw the arc. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the arc's ellipse * @param b y-coordinate of the arc's ellipse * @param c width of the arc's ellipse by default * @param d height of the arc's ellipse by default * @param start angle to start the arc, specified in radians * @param stop angle to stop the arc, specified in radians * @see PApplet#ellipse(float, float, float, float) * @see PApplet#ellipseMode(int) * @see PApplet#radians(float) * @see PApplet#degrees(float) */ public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } /* * @param mode either OPEN, CHORD, or PIE */ public void arc(float a, float b, float c, float d, float start, float stop, int mode) { if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode); g.arc(a, b, c, d, start, stop, mode); } /** * ( begin auto-generated from box.xml ) * * A box is an extruded rectangle. A box with equal dimension on all sides * is a cube. * * ( end auto-generated ) * * @webref shape:3d_primitives * @param size dimension of the box in all dimensions (creates a cube) * @see PGraphics#sphere(float) */ public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } /** * @param w dimension of the box in the x-dimension * @param h dimension of the box in the y-dimension * @param d dimension of the box in the z-dimension */ public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } /** * ( begin auto-generated from sphereDetail.xml ) * * Controls the detail used to render a sphere by adjusting the number of * vertices of the sphere mesh. The default resolution is 30, which creates * a fairly detailed sphere definition with vertices every 360/30 = 12 * degrees. If you're going to render a great number of spheres per frame, * it is advised to reduce the level of detail using this function. The * setting stays active until <b>sphereDetail()</b> is called again with a * new parameter and so should <i>not</i> be called prior to every * <b>sphere()</b> statement, unless you wish to render spheres with * different settings, e.g. using less detail for smaller spheres or ones * further away from the camera. To control the detail of the horizontal * and vertical resolution independently, use the version of the functions * with two parameters. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code for sphereDetail() submitted by toxi [031031]. * Code for enhanced u/v version from davbol [080801]. * * @param res number of segments (minimum 3) used per full circle revolution * @webref shape:3d_primitives * @see PGraphics#sphere(float) */ public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } /** * @param ures number of segments used longitudinally per full circle revolutoin * @param vres number of segments used latitudinally from top to bottom */ public void sphereDetail(int ures, int vres) { if (recorder != null) recorder.sphereDetail(ures, vres); g.sphereDetail(ures, vres); } /** * ( begin auto-generated from sphere.xml ) * * A sphere is a hollow ball made from tessellated triangles. * * ( end auto-generated ) * * <h3>Advanced</h3> * <P> * Implementation notes: * <P> * cache all the points of the sphere in a static array * top and bottom are just a bunch of triangles that land * in the center point * <P> * sphere is a series of concentric circles who radii vary * along the shape, based on, er.. cos or something * <PRE> * [toxi 031031] new sphere code. removed all multiplies with * radius, as scale() will take care of that anyway * * [toxi 031223] updated sphere code (removed modulos) * and introduced sphereAt(x,y,z,r) * to avoid additional translate()'s on the user/sketch side * * [davbol 080801] now using separate sphereDetailU/V * </PRE> * * @webref shape:3d_primitives * @param r the radius of the sphere * @see PGraphics#sphereDetail(int) */ public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } /** * ( begin auto-generated from bezierPoint.xml ) * * Evaluates the Bezier at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a bezier curve * at t. * * ( end auto-generated ) * * <h3>Advanced</h3> * For instance, to convert the following example:<PRE> * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * * // draw it in gray, using 10 steps instead of the default 20 * // this is a slower way to do it, but useful if you need * // to do things with the coordinates at each step * stroke(128); * beginShape(LINE_STRIP); * for (int i = 0; i <= 10; i++) { * float t = i / 10.0f; * float x = bezierPoint(85, 10, 90, 15, t); * float y = bezierPoint(20, 10, 90, 80, t); * vertex(x, y); * } * endShape();</PRE> * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } /** * ( begin auto-generated from bezierTangent.xml ) * * Calculates the tangent of a point on a Bezier curve. There is a good * definition of <a href="http://en.wikipedia.org/wiki/Tangent" * target="new"><em>tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code submitted by Dave Bollinger (davol) for release 0136. * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } /** * ( begin auto-generated from bezierDetail.xml ) * * Sets the resolution at which Beziers display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#curveTightness(float) */ public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezier.xml ) * * Draws a Bezier curve on the screen. These curves are defined by a series * of anchor and control points. The first two parameters specify the first * anchor point and the last two parameters specify the other anchor point. * The middle parameters specify the control points which define the shape * of the curve. Bezier curves were developed by French engineer Pierre * Bezier. Using the 3D version requires rendering with P3D (see the * Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * Draw a cubic bezier curve. The first and last points are * the on-curve points. The middle two are the 'control' points, * or 'handles' in an application like Illustrator. * <P> * Identical to typing: * <PRE>beginShape(); * vertex(x1, y1); * bezierVertex(x2, y2, x3, y3, x4, y4); * endShape(); * </PRE> * In Postscript-speak, this would be: * <PRE>moveto(x1, y1); * curveto(x2, y2, x3, y3, x4, y4);</PRE> * If you were to try and continue that curve like so: * <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE> * This would be done in processing by adding these statements: * <PRE>bezierVertex(x5, y5, x6, y6, x7, y7) * </PRE> * To draw a quadratic (instead of cubic) curve, * use the control point twice by doubling it: * <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE> * * @webref shape:curves * @param x1 coordinates for the first anchor point * @param y1 coordinates for the first anchor point * @param z1 coordinates for the first anchor point * @param x2 coordinates for the first control point * @param y2 coordinates for the first control point * @param z2 coordinates for the first control point * @param x3 coordinates for the second control point * @param y3 coordinates for the second control point * @param z3 coordinates for the second control point * @param x4 coordinates for the second anchor point * @param y4 coordinates for the second anchor point * @param z4 coordinates for the second anchor point * * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from curvePoint.xml ) * * Evalutes the curve at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a curve at t. * * ( end auto-generated ) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of second point on the curve * @param c coordinate of third point on the curve * @param d coordinate of fourth point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } /** * ( begin auto-generated from curveTangent.xml ) * * Calculates the tangent of a point on a curve. There's a good definition * of <em><a href="http://en.wikipedia.org/wiki/Tangent" * target="new">tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code thanks to Dave Bollinger (Bug #715) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierTangent(float, float, float, float, float) */ public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } /** * ( begin auto-generated from curveDetail.xml ) * * Sets the resolution at which curves display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) */ public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } /** * ( begin auto-generated from curveTightness.xml ) * * Modifies the quality of forms created with <b>curve()</b> and * <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the * curve fits to the vertex points. The value 0.0 is the default value for * <b>squishy</b> (this value defines the curves to be Catmull-Rom splines) * and the value 1.0 connects all the points with straight lines. Values * within the range -5.0 and 5.0 will deform the curves but will leave them * recognizable and as values increase in magnitude, they will continue to deform. * * ( end auto-generated ) * * @webref shape:curves * @param tightness amount of deformation from the original vertices * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) */ public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } /** * ( begin auto-generated from curve.xml ) * * Draws a curved line on the screen. The first and second parameters * specify the beginning control point and the last two parameters specify * the ending control point. The middle parameters specify the start and * stop of the curve. Longer curves can be created by putting a series of * <b>curve()</b> functions together or using <b>curveVertex()</b>. An * additional function called <b>curveTightness()</b> provides control for * the visual quality of the curve. The <b>curve()</b> function is an * implementation of Catmull-Rom splines. Using the 3D version requires * rendering with P3D (see the Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * As of revision 0070, this function no longer doubles the first * and last points. The curves are a bit more boring, but it's more * mathematically correct, and properly mirrored in curvePoint(). * <P> * Identical to typing out:<PRE> * beginShape(); * curveVertex(x1, y1); * curveVertex(x2, y2); * curveVertex(x3, y3); * curveVertex(x4, y4); * endShape(); * </PRE> * * @webref shape:curves * @param x1 coordinates for the beginning control point * @param y1 coordinates for the beginning control point * @param x2 coordinates for the first point * @param y2 coordinates for the first point * @param x3 coordinates for the second point * @param y3 coordinates for the second point * @param x4 coordinates for the ending control point * @param y4 coordinates for the ending control point * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } /** * @param z1 coordinates for the beginning control point * @param z2 coordinates for the first point * @param z3 coordinates for the second point * @param z4 coordinates for the ending control point */ public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from smooth.xml ) * * Draws all geometry with smooth (anti-aliased) edges. This will sometimes * slow down the frame rate of the application, but will enhance the visual * refinement. Note that <b>smooth()</b> will also improve image quality of * resized images, and <b>noSmooth()</b> will disable image (and font) * smoothing altogether. * * ( end auto-generated ) * * @webref shape:attributes * @see PGraphics#noSmooth() * @see PGraphics#hint(int) * @see PApplet#size(int, int, String) */ public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } /** * * @param level either 2, 4, or 8 */ public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); } /** * ( begin auto-generated from noSmooth.xml ) * * Draws all geometry with jagged (aliased) edges. * * ( end auto-generated ) * @webref shape:attributes * @see PGraphics#smooth() */ public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } /** * ( begin auto-generated from imageMode.xml ) * * Modifies the location from which images draw. The default mode is * <b>imageMode(CORNER)</b>, which specifies the location to be the upper * left corner and uses the fourth and fifth parameters of <b>image()</b> * to set the image's width and height. The syntax * <b>imageMode(CORNERS)</b> uses the second and third parameters of * <b>image()</b> to set the location of one corner of the image and uses * the fourth and fifth parameters to set the opposite corner. Use * <b>imageMode(CENTER)</b> to draw images centered at the given x and y * position.<br /> * <br /> * The parameter to <b>imageMode()</b> must be written in ALL CAPS because * Processing is a case-sensitive language. * * ( end auto-generated ) * * @webref image:loading_displaying * @param mode either CORNER, CORNERS, or CENTER * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#background(float, float, float, float) */ public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } /** * ( begin auto-generated from image.xml ) * * Displays images to the screen. The images must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the image. Processing currently works with GIF, JPEG, and Targa * images. The <b>img</b> parameter specifies the image to display and the * <b>x</b> and <b>y</b> parameters define the location of the image from * its upper-left corner. The image is displayed at its original size * unless the <b>width</b> and <b>height</b> parameters specify a different * size.<br /> * <br /> * The <b>imageMode()</b> function changes the way the parameters work. For * example, a call to <b>imageMode(CORNERS)</b> will change the * <b>width</b> and <b>height</b> parameters to define the x and y values * of the opposite corner of the image.<br /> * <br /> * The color of an image may be modified with the <b>tint()</b> function. * This function will maintain transparency for GIF and PNG images. * * ( end auto-generated ) * * <h3>Advanced</h3> * Starting with release 0124, when using the default (JAVA2D) renderer, * smooth() will also improve image quality of resized images. * * @webref image:loading_displaying * @param img the image to display * @param a x-coordinate of the image * @param b y-coordinate of the image * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#imageMode(int) * @see PGraphics#tint(float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#alpha(int) */ public void image(PImage img, float a, float b) { if (recorder != null) recorder.image(img, a, b); g.image(img, a, b); } /** * @param c width to display the image * @param d height to display the image */ public void image(PImage img, float a, float b, float c, float d) { if (recorder != null) recorder.image(img, a, b, c, d); g.image(img, a, b, c, d); } /** * Draw an image(), also specifying u/v coordinates. * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). * * @nowebref */ public void image(PImage img, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, v2); g.image(img, a, b, c, d, u1, v1, u2, v2); } /** * ( begin auto-generated from shapeMode.xml ) * * Modifies the location from which shapes draw. The default mode is * <b>shapeMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>shape()</b> to specify the width and height. The syntax * <b>shapeMode(CORNERS)</b> uses the first and second parameters of * <b>shape()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>shapeMode(CENTER)</b> draws the shape from its center point and uses * the third and forth parameters of <b>shape()</b> to specify the width * and height. The parameter must be written in "ALL CAPS" because * Processing is a case sensitive language. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param mode either CORNER, CORNERS, CENTER * @see PShape * @see PGraphics#shape(PShape) * @see PGraphics#rectMode(int) */ public void shapeMode(int mode) { if (recorder != null) recorder.shapeMode(mode); g.shapeMode(mode); } public void shape(PShape shape) { if (recorder != null) recorder.shape(shape); g.shape(shape); } /** * ( begin auto-generated from shape.xml ) * * Displays shapes to the screen. The shapes must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the shape. Processing currently works with SVG shapes only. The * <b>sh</b> parameter specifies the shape to display and the <b>x</b> and * <b>y</b> parameters define the location of the shape from its upper-left * corner. The shape is displayed at its original size unless the * <b>width</b> and <b>height</b> parameters specify a different size. The * <b>shapeMode()</b> function changes the way the parameters work. A call * to <b>shapeMode(CORNERS)</b>, for example, will change the width and * height parameters to define the x and y values of the opposite corner of * the shape. * <br /><br /> * Note complex shapes may draw awkwardly with P3D. This renderer does not * yet support shapes that have holes or complicated breaks. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param shape the shape to display * @param x x-coordinate of the shape * @param y y-coordinate of the shape * @see PShape * @see PApplet#loadShape(String) * @see PGraphics#shapeMode(int) * * Convenience method to draw at a particular location. */ public void shape(PShape shape, float x, float y) { if (recorder != null) recorder.shape(shape, x, y); g.shape(shape, x, y); } /** * @param a x-coordinate of the shape * @param b y-coordinate of the shape * @param c width to display the shape * @param d height to display the shape */ public void shape(PShape shape, float a, float b, float c, float d) { if (recorder != null) recorder.shape(shape, a, b, c, d); g.shape(shape, a, b, c, d); } public void textAlign(int alignX) { if (recorder != null) recorder.textAlign(alignX); g.textAlign(alignX); } /** * ( begin auto-generated from textAlign.xml ) * * Sets the current alignment for drawing text. The parameters LEFT, * CENTER, and RIGHT set the display characteristics of the letters in * relation to the values for the <b>x</b> and <b>y</b> parameters of the * <b>text()</b> function. * <br/> <br/> * In Processing 0125 and later, an optional second parameter can be used * to vertically align the text. BASELINE is the default, and the vertical * alignment will be reset to BASELINE if the second parameter is not used. * The TOP and CENTER parameters are straightforward. The BOTTOM parameter * offsets the line based on the current <b>textDescent()</b>. For multiple * lines, the final line will be aligned to the bottom, with the previous * lines appearing above it. * <br/> <br/> * When using <b>text()</b> with width and height parameters, BASELINE is * ignored, and treated as TOP. (Otherwise, text would by default draw * outside the box, since BASELINE is the default setting. BASELINE is not * a useful drawing mode for text drawn in a rectangle.) * <br/> <br/> * The vertical alignment is based on the value of <b>textAscent()</b>, * which many fonts do not specify correctly. It may be necessary to use a * hack and offset by a few pixels by hand so that the offset looks * correct. To do this as less of a hack, use some percentage of * <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even * if you change the size of the font. * * ( end auto-generated ) * * @webref typography:attributes * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textAlign(int alignX, int alignY) { if (recorder != null) recorder.textAlign(alignX, alignY); g.textAlign(alignX, alignY); } /** * ( begin auto-generated from textAscent.xml ) * * Returns ascent of the current font at its current size. This information * is useful for determining the height of the font above the baseline. For * example, adding the <b>textAscent()</b> and <b>textDescent()</b> values * will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textDescent() */ public float textAscent() { return g.textAscent(); } /** * ( begin auto-generated from textDescent.xml ) * * Returns descent of the current font at its current size. This * information is useful for determining the height of the font below the * baseline. For example, adding the <b>textAscent()</b> and * <b>textDescent()</b> values will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textAscent() */ public float textDescent() { return g.textDescent(); } /** * ( begin auto-generated from textFont.xml ) * * Sets the current font that will be drawn with the <b>text()</b> * function. Fonts must be loaded with <b>loadFont()</b> before it can be * used. This font will be used in all subsequent calls to the * <b>text()</b> function. If no <b>size</b> parameter is input, the font * will appear at its original size (the size it was created at with the * "Create Font..." tool) until it is changed with <b>textSize()</b>. <br * /> <br /> Because fonts are usually bitmaped, you should create fonts at * the sizes that will be used most commonly. Using <b>textFont()</b> * without the size parameter will result in the cleanest-looking text. <br * /><br /> With the default (JAVA2D) and PDF renderers, it's also possible * to enable the use of native fonts via the command * <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in * JAVA2D sketches and PDF output in cases where the vector data is * available: when the font is still installed, or the font is created via * the <b>createFont()</b> function (rather than the Create Font tool). * * ( end auto-generated ) * * @webref typography:loading_displaying * @param which any variable of the type PFont * @see PApplet#createFont(String, float, boolean) * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float) */ public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } /** * @param size the size of the letters in units of pixels */ public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } /** * ( begin auto-generated from textLeading.xml ) * * Sets the spacing between lines of text in units of pixels. This setting * will be used in all subsequent calls to the <b>text()</b> function. * * ( end auto-generated ) * * @webref typography:attributes * @param leading the size in pixels for spacing between lines * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } /** * ( begin auto-generated from textMode.xml ) * * Sets the way text draws to the screen. In the default configuration, the * <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in * two and three dimensional space.<br /> * <br /> * The <b>SHAPE</b> mode draws text using the the glyph outlines of * individual characters rather than as textures. This mode is only * supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the * <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any * other drawing occurs. If the outlines are not available, then * <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will * be used instead.<br /> * <br /> * The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with * <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output * files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is * not currently optimized for <b>P3D</b>, so if recording shape data, use * <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>. * * ( end auto-generated ) * * @webref typography:attributes * @param mode either MODEL or SHAPE * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) * @see PGraphics#beginRaw(PGraphics) * @see PApplet#createFont(String, float, boolean) */ public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } /** * ( begin auto-generated from textSize.xml ) * * Sets the current font size. This size will be used in all subsequent * calls to the <b>text()</b> function. Font size is measured in units of pixels. * * ( end auto-generated ) * * @webref typography:attributes * @param size the size of the letters in units of pixels * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } /** * @param c the character to measure */ public float textWidth(char c) { return g.textWidth(c); } /** * ( begin auto-generated from textWidth.xml ) * * Calculates and returns the width of any character or text string. * * ( end auto-generated ) * * @webref typography:attributes * @param str the String of characters to measure * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float) * @see PGraphics#textFont(PFont) */ public float textWidth(String str) { return g.textWidth(str); } /** * @nowebref */ public float textWidth(char[] chars, int start, int length) { return g.textWidth(chars, start, length); } /** * ( begin auto-generated from text.xml ) * * Draws text to the screen. Displays the information specified in the * <b>data</b> or <b>stringdata</b> parameters on the screen in the * position specified by the <b>x</b> and <b>y</b> parameters and the * optional <b>z</b> parameter. A default font will be used unless a font * is set with the <b>textFont()</b> function. Change the color of the text * with the <b>fill()</b> function. The text displays in relation to the * <b>textAlign()</b> function, which gives the option to draw to the left, * right, and center of the coordinates. * <br /><br /> * The <b>x2</b> and <b>y2</b> parameters define a rectangular area to * display within and may only be used with string data. For text drawn * inside a rectangle, the coordinates are interpreted based on the current * <b>rectMode()</b> setting. * * ( end auto-generated ) * * @webref typography:loading_displaying * @param c the alphanumeric character to be displayed * @param x x-coordinate of text * @param y y-coordinate of text * @see PGraphics#textAlign(int, int) * @see PGraphics#textMode(int) * @see PApplet#loadFont(String) * @see PGraphics#textFont(PFont) * @see PGraphics#rectMode(int) * @see PGraphics#fill(int, float) * @see_external String */ public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } /** * @param z z-coordinate of text */ public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } /** * <h3>Advanced</h3> * Draw a chunk of text. * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, but \r (carriage return, Windows and Mac OS) are * ignored. */ public void text(String str, float x, float y) { if (recorder != null) recorder.text(str, x, y); g.text(str, x, y); } /** * <h3>Advanced</h3> * Method to draw text from an array of chars. This method will usually be * more efficient than drawing from a String object, because the String will * not be converted to a char array before drawing. * @param chars the alphanumberic symbols to be displayed * @param start array index at which to start writing characters * @param stop array index at which to stop writing characters */ public void text(char[] chars, int start, int stop, float x, float y) { if (recorder != null) recorder.text(chars, start, stop, x, y); g.text(chars, start, stop, x, y); } /** * Same as above but with a z coordinate. */ public void text(String str, float x, float y, float z) { if (recorder != null) recorder.text(str, x, y, z); g.text(str, x, y, z); } public void text(char[] chars, int start, int stop, float x, float y, float z) { if (recorder != null) recorder.text(chars, start, stop, x, y, z); g.text(chars, start, stop, x, y, z); } /** * <h3>Advanced</h3> * Draw text in a box that is constrained to a particular size. * The current rectMode() determines what the coordinates mean * (whether x1/y1/x2/y2 or x/y/w/h). * <P/> * Note that the x,y coords of the start of the box * will align with the *ascent* of the text, not the baseline, * as is the case for the other text() functions. * <P/> * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, and \r (carriage return, Windows and Mac OS) are * ignored. * * @param x1 by default, the x-coordinate of text, see rectMode() for more info * @param y1 by default, the x-coordinate of text, see rectMode() for more info * @param x2 by default, the width of the text box, see rectMode() for more info * @param y2 by default, the height of the text box, see rectMode() for more info */ public void text(String str, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(str, x1, y1, x2, y2); g.text(str, x1, y1, x2, y2); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * This does a basic number formatting, to avoid the * generally ugly appearance of printing floats. * Users who want more control should use their own nf() cmmand, * or if they want the long, ugly version of float, * use String.valueOf() to convert the float to a String first. * * @param num the numeric value to be displayed */ public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * ( begin auto-generated from pushMatrix.xml ) * * Pushes the current transformation matrix onto the matrix stack. * Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires * understanding the concept of a matrix stack. The <b>pushMatrix()</b> * function saves the current coordinate system to the stack and * <b>popMatrix()</b> restores the prior coordinate system. * <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with * the other transformation functions and may be embedded to control the * scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void pushMatrix() { if (recorder != null) recorder.pushMatrix(); g.pushMatrix(); } /** * ( begin auto-generated from popMatrix.xml ) * * Pops the current transformation matrix off the matrix stack. * Understanding pushing and popping requires understanding the concept of * a matrix stack. The <b>pushMatrix()</b> function saves the current * coordinate system to the stack and <b>popMatrix()</b> restores the prior * coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used * in conjuction with the other transformation functions and may be * embedded to control the scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() */ public void popMatrix() { if (recorder != null) recorder.popMatrix(); g.popMatrix(); } /** * ( begin auto-generated from translate.xml ) * * Specifies an amount to displace objects within the display window. The * <b>x</b> parameter specifies left/right translation, the <b>y</b> * parameter specifies up/down translation, and the <b>z</b> parameter * specifies translations toward/away from the screen. Using this function * with the <b>z</b> parameter requires using P3D as a parameter in * combination with size as shown in the above example. Transformations * apply to everything that happens after and subsequent calls to the * function accumulates the effect. For example, calling <b>translate(50, * 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70, * 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the * transformation is reset when the loop begins again. This function can be * further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param x left/right translation * @param y up/down translation * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) */ public void translate(float x, float y) { if (recorder != null) recorder.translate(x, y); g.translate(x, y); } /** * @param z forward/backward translation */ public void translate(float x, float y, float z) { if (recorder != null) recorder.translate(x, y, z); g.translate(x, y, z); } /** * ( begin auto-generated from rotate.xml ) * * Rotates a shape the amount specified by the <b>angle</b> parameter. * Angles should be specified in radians (values from 0 to TWO_PI) or * converted to radians with the <b>radians()</b> function. * <br/> <br/> * Objects are always rotated around their relative position to the origin * and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as * <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b> * begins again. * <br/> <br/> * Technically, <b>rotate()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PApplet#radians(float) */ public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } /** * ( begin auto-generated from rotateX.xml ) * * Rotates a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same * as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the example above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } /** * ( begin auto-generated from rotateY.xml ) * * Rotates a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same * as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } /** * ( begin auto-generated from rotateZ.xml ) * * Rotates a shape around the z-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same * as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } /** * <h3>Advanced</h3> * Rotate about a vector in space. Same as the glRotatef() function. * @param x * @param y * @param z */ public void rotate(float angle, float x, float y, float z) { if (recorder != null) recorder.rotate(angle, x, y, z); g.rotate(angle, x, y, z); } /** * ( begin auto-generated from scale.xml ) * * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call <b>scale(2.0)</b> increases the dimension * of a shape by 200%. Transformations apply to everything that happens * after and subsequent calls to the function multiply the effect. For * example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the * same as <b>scale(3.0)</b>. If <b>scale()</b> is called within * <b>draw()</b>, the transformation is reset when the loop begins again. * Using this fuction with the <b>z</b> parameter requires using P3D as a * parameter for <b>size()</b> as shown in the example above. This function * can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param s percentage to scale the object * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } /** * <h3>Advanced</h3> * Scale in X and Y. Equivalent to scale(sx, sy, 1). * * Not recommended for use in 3D, because the z-dimension is just * scaled by 1, since there's no way to know what else to scale it by. * * @param x percentage to scale the object in the x-axis * @param y percentage to scale the object in the y-axis */ public void scale(float x, float y) { if (recorder != null) recorder.scale(x, y); g.scale(x, y); } /** * @param z percentage to scale the object in the z-axis */ public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } /** * ( begin auto-generated from shearX.xml ) * * Shears a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as * <b>shearX(PI)</b>. If <b>shearX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearX()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearX(float angle) { if (recorder != null) recorder.shearX(angle); g.shearX(angle); } /** * ( begin auto-generated from shearY.xml ) * * Shears a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as * <b>shearY(PI)</b>. If <b>shearY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearY()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearX(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearY(float angle) { if (recorder != null) recorder.shearY(angle); g.shearY(angle); } /** * ( begin auto-generated from resetMatrix.xml ) * * Replaces the current matrix with the identity matrix. The equivalent * function in OpenGL is glLoadIdentity(). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#printMatrix() */ public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } /** * ( begin auto-generated from applyMatrix.xml ) * * Multiplies the current matrix by the one specified through the * parameters. This is very slow because it will try to calculate the * inverse of the transform, so avoid it whenever possible. The equivalent * function in OpenGL is glMultMatrix(). * * ( end auto-generated ) * * @webref transform * @source * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#printMatrix() */ public void applyMatrix(PMatrix source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } public void applyMatrix(PMatrix2D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n00 numbers which define the 4x4 matrix to be multiplied * @param n01 numbers which define the 4x4 matrix to be multiplied * @param n02 numbers which define the 4x4 matrix to be multiplied * @param n10 numbers which define the 4x4 matrix to be multiplied * @param n11 numbers which define the 4x4 matrix to be multiplied * @param n12 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(PMatrix3D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n03 numbers which define the 4x4 matrix to be multiplied * @param n13 numbers which define the 4x4 matrix to be multiplied * @param n20 numbers which define the 4x4 matrix to be multiplied * @param n21 numbers which define the 4x4 matrix to be multiplied * @param n22 numbers which define the 4x4 matrix to be multiplied * @param n23 numbers which define the 4x4 matrix to be multiplied * @param n30 numbers which define the 4x4 matrix to be multiplied * @param n31 numbers which define the 4x4 matrix to be multiplied * @param n32 numbers which define the 4x4 matrix to be multiplied * @param n33 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public PMatrix getMatrix() { return g.getMatrix(); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix2D getMatrix(PMatrix2D target) { return g.getMatrix(target); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix3D getMatrix(PMatrix3D target) { return g.getMatrix(target); } /** * Set the current transformation matrix to the contents of another. */ public void setMatrix(PMatrix source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix2D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * ( begin auto-generated from printMatrix.xml ) * * Prints the current matrix to the Console (the text window at the bottom * of Processing). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#applyMatrix(PMatrix) */ public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } /** * ( begin auto-generated from beginCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. The functions are useful if * you want to more control over camera movement, however for most users, * the <b>camera()</b> function will be sufficient.<br /><br />The camera * functions will replace any transformations (such as <b>rotate()</b> or * <b>translate()</b>) that occur before them in <b>draw()</b>, but they * will not automatically replace the camera transform itself. For this * reason, camera functions should be placed at the beginning of * <b>draw()</b> (so that transformations happen afterwards), and the * <b>camera()</b> function can be used after <b>beginCamera()</b> if you * want to reset the camera before applying transformations.<br /><br * />This function sets the matrix mode to the camera matrix so calls such * as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix() * affect the camera. <b>beginCamera()</b> should always be used with a * following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and * <b>endCamera()</b> cannot be nested. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera() * @see PGraphics#endCamera() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#resetMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#scale(float, float, float) */ public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } /** * ( begin auto-generated from endCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. Please see the reference for * <b>beginCamera()</b> for a description of how the functions are used. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } /** * ( begin auto-generated from camera.xml ) * * Sets the position of the camera through setting the eye position, the * center of the scene, and which axis is facing upward. Moving the eye * position and the direction it is pointing (the center of the scene) * allows the images to be seen from different angles. The version without * any parameters sets the camera to the default position, pointing to the * center of the display window with the Y axis as up. The default values * are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / * 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar * to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#endCamera() * @see PGraphics#frustum(float, float, float, float, float, float) */ public void camera() { if (recorder != null) recorder.camera(); g.camera(); } /** * @param eyeX x-coordinate for the eye * @param eyeY y-coordinate for the eye * @param eyeZ z-coordinate for the eye * @param centerX x-coordinate for the center of the scene * @param centerY y-coordinate for the center of the scene * @param centerZ z-coordinate for the center of the scene * @param upX usually 0.0, 1.0, or -1.0 * @param upY usually 0.0, 1.0, or -1.0 * @param upZ usually 0.0, 1.0, or -1.0 */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } /** * ( begin auto-generated from printCamera.xml ) * * Prints the current camera matrix to the Console (the text window at the * bottom of Processing). * * ( end auto-generated ) * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } /** * ( begin auto-generated from ortho.xml ) * * Sets an orthographic projection and defines a parallel clipping volume. * All objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the clipping volume where left and right are the * minimum and maximum x values, top and bottom are the minimum and maximum * y values, and near and far are the minimum and maximum z values. If no * parameters are given, the default is used: ortho(0, width, 0, height, * -10, 10). * * ( end auto-generated ) * * @webref lights_camera:camera */ public void ortho() { if (recorder != null) recorder.ortho(); g.ortho(); } /** * @param left left plane of the clipping volume * @param right right plane of the clipping volume * @param bottom bottom plane of the clipping volume * @param top top plane of the clipping volume */ public void ortho(float left, float right, float bottom, float top) { if (recorder != null) recorder.ortho(left, right, bottom, top); g.ortho(left, right, bottom, top); } /** * @param near maximum distance from the origin to the viewer * @param far maximum distance from the origin away from the viewer */ public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } /** * ( begin auto-generated from perspective.xml ) * * Sets a perspective projection applying foreshortening, making distant * objects appear smaller than closer ones. The parameters define a viewing * volume with the shape of truncated pyramid. Objects near to the front of * the volume appear their actual size, while farther objects appear * smaller. This projection simulates the perspective of the world more * accurately than orthographic projection. The version of perspective * without parameters sets the default perspective and the version with * four parameters allows the programmer to set the area precisely. The * default values are: perspective(PI/3.0, width/height, cameraZ/10.0, * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * * ( end auto-generated ) * * @webref lights_camera:camera */ public void perspective() { if (recorder != null) recorder.perspective(); g.perspective(); } /** * @param fovy field-of-view angle (in radians) for vertical direction * @param aspect ratio of width to height * @param zNear z-position of nearest clipping plane * @param zFar z-position of farthest clipping plane */ public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } /** * ( begin auto-generated from frustum.xml ) * * Sets a perspective matrix defined through the parameters. Works like * glFrustum, except it wipes out the current perspective matrix rather * than muliplying itself with it. * * ( end auto-generated ) * * @webref lights_camera:camera * @param left left coordinate of the clipping plane * @param right right coordinate of the clipping plane * @param bottom bottom coordinate of the clipping plane * @param top top coordinate of the clipping plane * @param near near component of the clipping plane; must be greater than zero * @param far far component of the clipping plane; must be greater than the near value * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) * @see PGraphics#endCamera() * @see PGraphics#perspective(float, float, float, float) */ public void frustum(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); g.frustum(left, right, bottom, top, near, far); } /** * ( begin auto-generated from printProjection.xml ) * * Prints the current projection matrix to the Console (the text window at * the bottom of Processing). * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printProjection() { if (recorder != null) recorder.printProjection(); g.printProjection(); } /** * ( begin auto-generated from screenX.xml ) * * Takes a three-dimensional X, Y, Z position and returns the X value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenY(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenX(float x, float y) { return g.screenX(x, y); } /** * ( begin auto-generated from screenY.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Y value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenY(float x, float y) { return g.screenY(x, y); } /** * @param z 3D z-coordinate to be mapped */ public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } /** * @param z 3D z-coordinate to be mapped */ public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } /** * ( begin auto-generated from screenZ.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Z value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenY(float, float, float) */ public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } /** * ( begin auto-generated from modelX.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the X value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The X value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use. * <br/> <br/> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelY(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelX(float x, float y, float z) { return g.modelX(x, y, z); } /** * ( begin auto-generated from modelY.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Y value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Y value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelY(float x, float y, float z) { return g.modelY(x, y, z); } /** * ( begin auto-generated from modelZ.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Z value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Z value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelY(float, float, float) */ public float modelZ(float x, float y, float z) { return g.modelZ(x, y, z); } /** * ( begin auto-generated from pushStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings. Note that these functions * are always used together. They allow you to change the style settings * and later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * <br /><br /> * The style information controlled by the following functions are included * in the style: * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), * textAlign(), textFont(), textMode(), textSize(), textLeading(), * emissive(), specular(), shininess(), ambient() * * ( end auto-generated ) * * @webref structure * @see PGraphics#popStyle() */ public void pushStyle() { if (recorder != null) recorder.pushStyle(); g.pushStyle(); } /** * ( begin auto-generated from popStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings; these functions are * always used together. They allow you to change the style settings and * later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * * ( end auto-generated ) * * @webref structure * @see PGraphics#pushStyle() */ public void popStyle() { if (recorder != null) recorder.popStyle(); g.popStyle(); } public void style(PStyle s) { if (recorder != null) recorder.style(s); g.style(s); } /** * ( begin auto-generated from strokeWeight.xml ) * * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * <br/> <br/> * When drawing with P3D, series of connected lines (such as the stroke * around a polygon, triangle, or ellipse) produce unattractive results * when a thick stroke weight is set (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). With P3D, the minimum and maximum values for * <b>strokeWeight()</b> are controlled by the graphics card and the * operating system's OpenGL implementation. For instance, the thickness * may not go higher than 10 pixels. * * ( end auto-generated ) * * @webref shape:attributes * @param weight the weight (in pixels) of the stroke * @see PGraphics#stroke(int, float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) */ public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } /** * ( begin auto-generated from strokeJoin.xml ) * * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * <br/> <br/> * This function is not available with the P3D renderer, (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param join either MITER, BEVEL, ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeCap(int) */ public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } /** * ( begin auto-generated from strokeCap.xml ) * * Sets the style for rendering line endings. These ends are either * squared, extended, or rounded and specified with the corresponding * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. * <br/> <br/> * This function is not available with the P3D renderer (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param cap either SQUARE, PROJECT, or ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PApplet#size(int, int, String, String) */ public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } /** * ( begin auto-generated from noStroke.xml ) * * Disables drawing the stroke (outline). If both <b>noStroke()</b> and * <b>noFill()</b> are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @see PGraphics#stroke(float, float, float, float) */ public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } /** * ( begin auto-generated from stroke.xml ) * * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <b>colorMode()</b> (the default color space is RGB, with each * value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * * ( end auto-generated ) * * @param rgb color value in hexadecimal notation * @see PGraphics#noStroke() * @see PGraphics#fill(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } /** * @param alpha opacity of the stroke */ public void stroke(int rgb, float alpha) { if (recorder != null) recorder.stroke(rgb, alpha); g.stroke(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @webref color:setting */ public void stroke(float v1, float v2, float v3) { if (recorder != null) recorder.stroke(v1, v2, v3); g.stroke(v1, v2, v3); } public void stroke(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.stroke(v1, v2, v3, alpha); g.stroke(v1, v2, v3, alpha); } /** * ( begin auto-generated from noTint.xml ) * * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @see PGraphics#tint(float, float, float, float) * @see PGraphics#image(PImage, float, float, float, float) */ public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } /** * ( begin auto-generated from tint.xml ) * * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by setting the alpha.<br /> * <br /> * To make an image transparent, but not change it's color, use white as * the tint color and specify an alpha value. For instance, tint(255, 128) * will make an image 50% transparent (unless <b>colorMode()</b> has been * used).<br /> * <br /> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components.<br /> * <br /> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255.<br /> * <br /> * The <b>tint()</b> function is also used to control the coloring of * textures in 3D. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @param rgb color value in hexadecimal notation * @see PGraphics#noTint() * @see PGraphics#image(PImage, float, float, float, float) */ public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } /** * @param alpha opacity of the image */ public void tint(int rgb, float alpha) { if (recorder != null) recorder.tint(rgb, alpha); g.tint(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void tint(float v1, float v2, float v3) { if (recorder != null) recorder.tint(v1, v2, v3); g.tint(v1, v2, v3); } public void tint(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.tint(v1, v2, v3, alpha); g.tint(v1, v2, v3, alpha); } /** * ( begin auto-generated from noFill.xml ) * * Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b> * are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @see PGraphics#fill(float, float, float, float) */ public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } /** * ( begin auto-generated from fill.xml ) * * Sets the color used to fill shapes. For example, if you run <b>fill(204, * 102, 0)</b>, all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <b>colorMode()</b> (the default color space is RGB, with * each value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * <br/> <br/> * To change the color of an image (or a texture), use tint(). * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param rgb color variable or hex value * @see PGraphics#noFill() * @see PGraphics#stroke(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } /** * @param alpha opacity of the fill */ public void fill(int rgb, float alpha) { if (recorder != null) recorder.fill(rgb, alpha); g.fill(rgb, alpha); } /** * @param gray number specifying value between white and black */ public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void fill(float v1, float v2, float v3) { if (recorder != null) recorder.fill(v1, v2, v3); g.fill(v1, v2, v3); } public void fill(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.fill(v1, v2, v3, alpha); g.fill(v1, v2, v3, alpha); } /** * ( begin auto-generated from ambient.xml ) * * Sets the ambient reflectance for shapes drawn to the screen. This is * combined with the ambient light component of environment. The color * components set through the parameters define the reflectance. For * example in the default color mode, setting v1=255, v2=126, v3=0, would * cause all the red light to reflect and half of the green light to * reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>, * and <b>shininess()</b> in setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#emissive(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void ambient(int rgb) { if (recorder != null) recorder.ambient(rgb); g.ambient(rgb); } /** * @param gray number specifying value between white and black */ public void ambient(float gray) { if (recorder != null) recorder.ambient(gray); g.ambient(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void ambient(float v1, float v2, float v3) { if (recorder != null) recorder.ambient(v1, v2, v3); g.ambient(v1, v2, v3); } /** * ( begin auto-generated from specular.xml ) * * Sets the specular color of the materials used for shapes drawn to the * screen, which sets the color of hightlights. Specular refers to light * which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light). Used in combination * with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#lightSpecular(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#emissive(float, float, float) * @see PGraphics#shininess(float) */ public void specular(int rgb) { if (recorder != null) recorder.specular(rgb); g.specular(rgb); } /** * gray number specifying value between white and black */ public void specular(float gray) { if (recorder != null) recorder.specular(gray); g.specular(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void specular(float v1, float v2, float v3) { if (recorder != null) recorder.specular(v1, v2, v3); g.specular(v1, v2, v3); } /** * ( begin auto-generated from shininess.xml ) * * Sets the amount of gloss in the surface of shapes. Used in combination * with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param shine degree of shininess * @see PGraphics#emissive(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) */ public void shininess(float shine) { if (recorder != null) recorder.shininess(shine); g.shininess(shine); } /** * ( begin auto-generated from emissive.xml ) * * Sets the emissive color of the material used for drawing shapes drawn to * the screen. Used in combination with <b>ambient()</b>, * <b>specular()</b>, and <b>shininess()</b> in setting the material * properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void emissive(int rgb) { if (recorder != null) recorder.emissive(rgb); g.emissive(rgb); } /** * gray number specifying value between white and black */ public void emissive(float gray) { if (recorder != null) recorder.emissive(gray); g.emissive(gray); } /** * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) */ public void emissive(float v1, float v2, float v3) { if (recorder != null) recorder.emissive(v1, v2, v3); g.emissive(v1, v2, v3); } /** * ( begin auto-generated from lights.xml ) * * Sets the default ambient light, directional light, falloff, and specular * values. The defaults are ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and * lightSpecular(0, 0, 0). Lights need to be included in the draw() to * remain persistent in a looping program. Placing them in the setup() of a * looping program will cause them to only have an effect the first time * through the loop. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#noLights() */ public void lights() { if (recorder != null) recorder.lights(); g.lights(); } /** * ( begin auto-generated from noLights.xml ) * * Disable all lighting. Lighting is turned off by default and enabled with * the <b>lights()</b> function. This function can be used to disable * lighting so that 2D geometry (which does not require lighting) can be * drawn after a set of lighted 3D geometry. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#lights() */ public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } /** * ( begin auto-generated from ambientLight.xml ) * * Adds an ambient light. Ambient light doesn't come from a specific * direction, the rays have light have bounced around so much that objects * are evenly lit from all sides. Ambient lights are almost always used in * combination with other types of lights. Lights need to be included in * the <b>draw()</b> to remain persistent in a looping program. Placing * them in the <b>setup()</b> of a looping program will cause them to only * have an effect the first time through the loop. The effect of the * parameters is determined by the current color mode. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void ambientLight(float v1, float v2, float v3) { if (recorder != null) recorder.ambientLight(v1, v2, v3); g.ambientLight(v1, v2, v3); } /** * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light */ public void ambientLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, z); g.ambientLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from directionalLight.xml ) * * Adds a directional light. Directional light comes from one direction and * is stronger when hitting a surface squarely and weaker if it hits at a a * gentle angle. After hitting a surface, a directional lights scatters in * all directions. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the * direction the light is facing. For example, setting <b>ny</b> to -1 will * cause the geometry to be lit from below (the light is facing directly upward). * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param nx direction along the x-axis * @param ny direction along the y-axis * @param nz direction along the z-axis * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void directionalLight(float v1, float v2, float v3, float nx, float ny, float nz) { if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, nz); g.directionalLight(v1, v2, v3, nx, ny, nz); } /** * ( begin auto-generated from pointLight.xml ) * * Adds a point light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position * of the light. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void pointLight(float v1, float v2, float v3, float x, float y, float z) { if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, z); g.pointLight(v1, v2, v3, x, y, z); } /** * ( begin auto-generated from spotLight.xml ) * * Adds a spot light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the * position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the * direction or light. The <b>angle</b> parameter affects angle of the * spotlight cone. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @param nx direction along the x axis * @param ny direction along the y axis * @param nz direction along the z axis * @param angle angle of the spotlight cone * @param concentration exponent determining the center bias of the cone * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) */ public void spotLight(float v1, float v2, float v3, float x, float y, float z, float nx, float ny, float nz, float angle, float concentration) { if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration); } /** * ( begin auto-generated from lightFalloff.xml ) * * Sets the falloff rates for point lights, spot lights, and ambient * lights. The parameters are used to determine the falloff with the * following equation:<br /><br />d = distance from light position to * vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * * QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements * which are created after it in the code. The default value if * <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with * a falloff can be tricky. It is used, for example, if you wanted a region * of your scene to be lit ambiently one color and another region to be lit * ambiently by another color, you would use an ambient light with location * and falloff. You can think of it as a point light that doesn't care * which direction a surface is facing. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param constant constant value or determining falloff * @param linear linear value for determining falloff * @param quadratic quadratic value for determining falloff * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#lightSpecular(float, float, float) */ public void lightFalloff(float constant, float linear, float quadratic) { if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); g.lightFalloff(constant, linear, quadratic); } /** * ( begin auto-generated from lightSpecular.xml ) * * Sets the specular color for lights. Like <b>fill()</b>, it affects only * the elements which are created after it in the code. Specular refers to * light which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light) and is used for * creating highlights. The specular quality of a light interacts with the * specular material qualities set through the <b>specular()</b> and * <b>shininess()</b> functions. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param v1 red or hue value (depending on current color mode) * @param v2 green or saturation value (depending on current color mode) * @param v3 blue or brightness value (depending on current color mode) * @see PGraphics#specular(float, float, float) * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void lightSpecular(float v1, float v2, float v3) { if (recorder != null) recorder.lightSpecular(v1, v2, v3); g.lightSpecular(v1, v2, v3); } /** * ( begin auto-generated from background.xml ) * * The <b>background()</b> function sets the color used for the background * of the Processing window. The default background is light gray. In the * <b>draw()</b> function, the background color is used to clear the * display window at the beginning of each frame. * <br/> <br/> * An image can also be used as the background for a sketch, however its * width and height must be the same size as the sketch window. To resize * an image 'b' to the size of the sketch window, use b.resize(width, height). * <br/> <br/> * Images used as background will ignore the current <b>tint()</b> setting. * <br/> <br/> * It is not possible to use transparency (alpha) in background colors with * the main drawing surface, however they will work properly with <b>createGraphics()</b>. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p>Clear the background with a color that includes an alpha value. This can * only be used with objects created by createGraphics(), because the main * drawing surface cannot be set transparent.</p> * <p>It might be tempting to use this function to partially clear the screen * on each frame, however that's not how this function works. When calling * background(), the pixels will be replaced with pixels that have that level * of transparency. To do a semi-transparent overlay, use fill() with alpha * and draw a rectangle.</p> * * @webref color:setting * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#stroke(float) * @see PGraphics#fill(float) * @see PGraphics#tint(float) * @see PGraphics#colorMode(int) */ public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } /** * @param alpha opacity of the background */ public void background(int rgb, float alpha) { if (recorder != null) recorder.background(rgb, alpha); g.background(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float gray, float alpha) { if (recorder != null) recorder.background(gray, alpha); g.background(gray, alpha); } /** * @param v1 red or hue value (depending on the current color mode) * @param v2 green or saturation value (depending on the current color mode) * @param v3 blue or brightness value (depending on the current color mode) */ public void background(float v1, float v2, float v3) { if (recorder != null) recorder.background(v1, v2, v3); g.background(v1, v2, v3); } public void background(float v1, float v2, float v3, float alpha) { if (recorder != null) recorder.background(v1, v2, v3, alpha); g.background(v1, v2, v3, alpha); } /** * @webref color:setting */ public void clear() { if (recorder != null) recorder.clear(); g.clear(); } /** * Takes an RGB or ARGB image and sets it as the background. * The width and height of the image must be the same size as the sketch. * Use image.resize(width, height) to make short work of such a task.<br/> * <br/> * Note that even if the image is set as RGB, the high 8 bits of each pixel * should be set opaque (0xFF000000) because the image data will be copied * directly to the screen, and non-opaque background images may have strange * behavior. Use image.filter(OPAQUE) to handle this easily.<br/> * <br/> * When using 3D, this will also clear the zbuffer (if it exists). * * @param image PImage to set as background (must be same size as the sketch window) */ public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } /** * ( begin auto-generated from colorMode.xml ) * * Changes the way Processing interprets color data. By default, the * parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and * <b>color()</b> are defined by values between 0 and 255 using the RGB * color model. The <b>colorMode()</b> function is used to change the * numerical range used for specifying colors and to switch color systems. * For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values * are specified between 0 and 1. The limits for defining colors are * altered by setting the parameters range1, range2, range3, and range 4. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness * @see PGraphics#background(float) * @see PGraphics#fill(float) * @see PGraphics#stroke(float) */ public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } /** * @param max range for all color elements */ public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } /** * @param max1 range for the red or hue depending on the current color mode * @param max2 range for the green or saturation depending on the current color mode * @param max3 range for the blue or brightness depending on the current color mode */ public void colorMode(int mode, float max1, float max2, float max3) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3); g.colorMode(mode, max1, max2, max3); } /** * @param maxA range for the alpha */ public void colorMode(int mode, float max1, float max2, float max3, float maxA) { if (recorder != null) recorder.colorMode(mode, max1, max2, max3, maxA); g.colorMode(mode, max1, max2, max3, maxA); } /** * ( begin auto-generated from alpha.xml ) * * Extracts the alpha value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float alpha(int rgb) { return g.alpha(rgb); } /** * ( begin auto-generated from red.xml ) * * Extracts the red value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The red() function * is easy to use and undestand, but is slower than another technique. To * achieve the same results when working in <b>colorMode(RGB, 255)</b>, but * with greater speed, use the &gt;&gt; (right shift) operator with a bit * mask. For example, the following two lines of code are equivalent:<br * /><pre>float r1 = red(myColor);<br />float r2 = myColor &gt;&gt; 16 * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float red(int rgb) { return g.red(rgb); } /** * ( begin auto-generated from green.xml ) * * Extracts the green value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>green()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use the &gt;&gt; (right shift) * operator with a bit mask. For example, the following two lines of code * are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 = * myColor &gt;&gt; 8 &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float green(int rgb) { return g.green(rgb); } /** * ( begin auto-generated from blue.xml ) * * Extracts the blue value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>blue()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use a bit mask to remove the other * color components. For example, the following two lines of code are * equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float blue(int rgb) { return g.blue(rgb); } /** * ( begin auto-generated from hue.xml ) * * Extracts the hue value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float hue(int rgb) { return g.hue(rgb); } /** * ( begin auto-generated from saturation.xml ) * * Extracts the saturation value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#brightness(int) */ public final float saturation(int rgb) { return g.saturation(rgb); } /** * ( begin auto-generated from brightness.xml ) * * Extracts the brightness value from a color. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) */ public final float brightness(int rgb) { return g.brightness(rgb); } /** * ( begin auto-generated from lerpColor.xml ) * * Calculates a color or colors between two color at a specific increment. * The <b>amt</b> parameter is the amount to interpolate between the two * values where 0.0 equal to the first point, 0.1 is very near the first * point, 0.5 is half-way in between, etc. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param c1 interpolate from this color * @param c2 interpolate to this color * @param amt between 0.0 and 1.0 * @see PImage#blendColor(int, int, int) * @see PGraphics#color(float, float, float, float) */ public int lerpColor(int c1, int c2, float amt) { return g.lerpColor(c1, c2, amt); } /** * @nowebref * Interpolate between two colors. Like lerp(), but for the * individual color components of a color supplied as an int value. */ static public int lerpColor(int c1, int c2, float amt, int mode) { return PGraphics.lerpColor(c1, c2, amt, mode); } /** * Display a warning that the specified method is only available with 3D. * @param method The method name (no parentheses) */ static public void showDepthWarning(String method) { PGraphics.showDepthWarning(method); } /** * Display a warning that the specified method that takes x, y, z parameters * can only be used with x and y parameters in this renderer. * @param method The method name (no parentheses) */ static public void showDepthWarningXYZ(String method) { PGraphics.showDepthWarningXYZ(method); } /** * Display a warning that the specified method is simply unavailable. */ static public void showMethodWarning(String method) { PGraphics.showMethodWarning(method); } /** * Error that a particular variation of a method is unavailable (even though * other variations are). For instance, if vertex(x, y, u, v) is not * available, but vertex(x, y) is just fine. */ static public void showVariationWarning(String str) { PGraphics.showVariationWarning(str); } /** * Display a warning that the specified method is not implemented, meaning * that it could be either a completely missing function, although other * variations of it may still work properly. */ static public void showMissingWarning(String method) { PGraphics.showMissingWarning(method); } /** * Return true if this renderer should be drawn to the screen. Defaults to * returning true, since nearly all renderers are on-screen beasts. But can * be overridden for subclasses like PDF so that a window doesn't open up. * <br/> <br/> * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, * what to call this? */ public boolean displayable() { return g.displayable(); } /** * Return true if this renderer does rendering through OpenGL. Defaults to false. */ public boolean isGL() { return g.isGL(); } /** * ( begin auto-generated from PImage_get.xml ) * * Reads the color of any pixel or grabs a section of an image. If no * parameters are specified, the entire image is returned. Use the <b>x</b> * and <b>y</b> parameters to get the value of one pixel. Get a section of * the display window by specifying an additional <b>width</b> and * <b>height</b> parameter. When getting an image, the <b>x</b> and * <b>y</b> parameters define the coordinates for the upper-left corner of * the image, regardless of the current <b>imageMode()</b>.<br /> * <br /> * If the pixel requested is outside of the image window, black is * returned. The numbers returned are scaled according to the current color * ranges, but only RGB values are returned by this function. For example, * even though you may have drawn a shape with <b>colorMode(HSB)</b>, the * numbers returned will be in RGB format.<br /> * <br /> * Getting the color of a single pixel with <b>get(x, y)</b> is easy, but * not as fast as grabbing the data directly from <b>pixels[]</b>. The * equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is * <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information. * * ( end auto-generated ) * * <h3>Advanced</h3> * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. * * @webref image:pixels * @brief Reads the color of any pixel or grabs a rectangle of pixels * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @see PApplet#set(int, int, int) * @see PApplet#pixels * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int) */ public int get(int x, int y) { return g.get(x, y); } /** * @param w width of pixel rectangle to get * @param h height of pixel rectangle to get */ public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { return g.get(); } /** * ( begin auto-generated from PImage_set.xml ) * * Changes the color of any pixel or writes an image directly into the * display window.<br /> * <br /> * The <b>x</b> and <b>y</b> parameters specify the pixel to change and the * <b>color</b> parameter specifies the color value. The color parameter is * affected by the current color mode (the default is RGB values from 0 to * 255). When setting an image, the <b>x</b> and <b>y</b> parameters define * the coordinates for the upper-left corner of the image, regardless of * the current <b>imageMode()</b>. * <br /><br /> * Setting the color of a single pixel with <b>set(x, y)</b> is easy, but * not as fast as putting the data directly into <b>pixels[]</b>. The * equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b> * is <b>pixels[y*width+x] = #000000</b>. See the reference for * <b>pixels[]</b> for more information. * * ( end auto-generated ) * * @webref image:pixels * @brief writes a color to any pixel or writes an image into another * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @param c any value of the color datatype * @see PImage#get(int, int, int, int) * @see PImage#pixels * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) */ public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } /** * <h3>Advanced</h3> * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. * * @param img image to copy into the original image */ public void set(int x, int y, PImage img) { if (recorder != null) recorder.set(x, y, img); g.set(x, y, img); } /** * ( begin auto-generated from PImage_mask.xml ) * * Masks part of an image from displaying by loading another image and * using it as an alpha channel. This mask image should only contain * grayscale data, but only the blue color channel is used. The mask image * needs to be the same size as the image to which it is applied.<br /> * <br /> * In addition to using a mask image, an integer array containing the alpha * channel data can be specified directly. This method is useful for * creating dynamically generated alpha masks. This array must be of the * same length as the target image's pixels array and should contain only * grayscale data of values between 0-255. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscale by * performing a proper luminance-based conversion. * * @webref pimage:method * @usage web_application * @brief Masks part of an image with another image as an alpha channel * @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array */ public void mask(PImage img) { if (recorder != null) recorder.mask(img); g.mask(img); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } /** * ( begin auto-generated from PImage_filter.xml ) * * Filters an image as defined by one of the following modes:<br /><br * />THRESHOLD - converts the image to black and white pixels depending if * they are above or below the threshold defined by the level parameter. * The level must be between 0.0 (black) and 1.0(white). If no level is * specified, 0.5 is used.<br /> * <br /> * GRAY - converts any colors in the image to grayscale equivalents<br /> * <br /> * INVERT - sets each pixel to its inverse value<br /> * <br /> * POSTERIZE - limits each channel of the image to the number of colors * specified as the level parameter<br /> * <br /> * BLUR - executes a Guassian blur with the level parameter specifying the * extent of the blurring. If no level parameter is used, the blur is * equivalent to Guassian blur of radius 1<br /> * <br /> * OPAQUE - sets the alpha channel to entirely opaque<br /> * <br /> * ERODE - reduces the light areas with the amount defined by the level * parameter<br /> * <br /> * DILATE - increases the light areas with the amount defined by the level parameter * * ( end auto-generated ) * * <h3>Advanced</h3> * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * * @webref image:pixels * @brief Converts the image to grayscale or black and white * @usage web_application * @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE * @param param unique for each, see above */ public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } /** * ( begin auto-generated from PImage_copy.xml ) * * Copies a region of pixels from one image into another. If the source and * destination regions aren't the same size, it will automatically resize * source pixels to fit the specified target region. No alpha information * is used in the process, however if the source image has an alpha channel * set, it will be copied as well. * <br /><br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies the entire image * @usage web_application * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destination's upper left corner * @param dy Y coordinate of the destination's upper left corner * @param dw destination image width * @param dh destination image height * @see PGraphics#alpha(int) * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); g.copy(sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param src an image variable referring to the source image. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); } public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * ( begin auto-generated from PImage_blend.xml ) * * Blends a region of pixels into the image specified by the <b>img</b> * parameter. These copies utilize full alpha channel support and a choice * of the following modes to blend the colors of source pixels (A) with the * ones of pixels in the destination image (B):<br /> * <br /> * BLEND - linear interpolation of colours: C = A*factor + B<br /> * <br /> * ADD - additive blending with white clip: C = min(A*factor + B, 255)<br /> * <br /> * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, * 0)<br /> * <br /> * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br /> * <br /> * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br /> * <br /> * DIFFERENCE - subtract colors from underlying image.<br /> * <br /> * EXCLUSION - similar to DIFFERENCE, but less extreme.<br /> * <br /> * MULTIPLY - Multiply the colors, result will always be darker.<br /> * <br /> * SCREEN - Opposite multiply, uses inverse values of the colors.<br /> * <br /> * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values.<br /> * <br /> * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br /> * <br /> * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh.<br /> * <br /> * DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop.<br /> * <br /> * BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop.<br /> * <br /> * All modes use the alpha information (highest byte) of source image * pixels as the blending factor. If the source and destination regions are * different sizes, the image will be automatically resized to match the * destination size. If the <b>srcImg</b> parameter is not used, the * display window is used as the source image.<br /> * <br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies a pixel or rectangle of pixels using different blending modes * @param src an image variable referring to the source image * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destinations's upper left corner * @param dy Y coordinate of the destinations's upper left corner * @param dw destination image width * @param dh destination image height * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN * * @see PApplet#alpha(int) * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) * @see PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); } }
ellipse + Projectable2D
src/main/java/processing/core/PApplet.java
ellipse + Projectable2D
Java
mit
ff59daa5ae2c942ccd7d1ee61c0aa035478557dd
0
JackMc/snipes
package org.ossnipes.snipes.lib.events; /* * * Copyright 2010 Jack McCracken * This file is part of The Snipes IRC Framework. * * The Snipes IRC Framework is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * The Snipes IRC Framework is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * Although this project was created for use within The Open Source Snipes Project, it is legally * a completely different project. This means that you may distribute it (along with * the source) with your own GPL-compatible projects without having to distribute the actual * Implementation project (The Open Source Snipes Project) with it. * * Note for other developers of this project: Please include this in any files you create, so that it * may be made "legally" a part of the project. * * You should have received a copy of the GNU General Public License along with The Snipes IRC Framework. * If not, see http://www.gnu.org/licenses/. */ import java.util.HashMap; import java.util.Map; import java.util.Set; /** Wrapper class for arguments to Snipes events. * @author jack */ public class EventArgs { private Map<String,Object> _params = null; /** Constructs a event arguments object with no keys. */ public EventArgs(String line) { _params = new HashMap<String,Object>(); _params.put("line", line); } /** Converts the two specified arrays and uses the keys array as the keys for the parameters, and * uses the values array as the values of the Strings of the keys array with the same index. * @param keys An array of keys, must be the same size as values. * @param values An array of values, must be the same size as keys. * @throws IllegalArgumentException If keys.length != values.length or if keys ==null || values == null. */ public EventArgs(String line, String[] keys, String[] values) { if (keys == null || values == null) throw new IllegalArgumentException("Keys/values cannot be null."); _params = BotUtils.stringObjectArraysToStringObjectMap(keys, values); _params.put("line", line); } public boolean containsKey(String key) { return _params.containsKey(key); } /** Creates a EventArgs object with the specified arguments as it's parameters. * @param args The String Object map of the arguments. */ public EventArgs(String line, Map<String, Object> args) { if (args == null) { throw new IllegalArgumentException("args cannot be null."); } this._params = args; _params.put("line", line); } /** Gets the parameter with the specified key. * @return The value of the parameter. Null if there's no mapping. */ public Object getParam(String key) { return _params.get(key); } /** Gets all the keys in this args set.<BR/> * A common use of this would be: <BR/><BR/> * <code>for (String s : args.getKeySet()) {<BR/> * someList.add(args.getParam(s));<BR/> * }<BR/><BR/> * </code> * Which would add all the values in the args set to someList (or whatever list * you replaced it with.) * @return A set of all the keys in the args set. */ public Set<String> getKeySet() { return _params.keySet(); } /** Retrieves a event parameter as a String, using the {@link Object#toString()} method (so that it is more typesafe than * casting to a String). This is just a convenience method, and is the same as {@link #getParam(String)}.toString(). * * @param key The key to retrieve the value of. * @return The value of the parameter with the specified key. */ public String getParamAsString(String key) { Object o = getParam(key); if (o == null) { return null; } return o.toString(); } }
testing/lib/irc/src/org/ossnipes/snipes/lib/events/EventArgs.java
package org.ossnipes.snipes.lib.events; /* * * Copyright 2010 Jack McCracken * This file is part of The Snipes IRC Framework. * * The Snipes IRC Framework is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * The Snipes IRC Framework is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * Although this project was created for use within The Open Source Snipes Project, it is legally * a completely different project. This means that you may distribute it (along with * the source) with your own GPL-compatible projects without having to distribute the actual * Implementation project (The Open Source Snipes Project) with it. * * Note for other developers of this project: Please include this in any files you create, so that it * may be made "legally" a part of the project. * * You should have received a copy of the GNU General Public License along with The Snipes IRC Framework. * If not, see http://www.gnu.org/licenses/. */ import java.util.HashMap; import java.util.Map; import java.util.Set; /** Wrapper class for arguments to Snipes events. * @author jack */ public class EventArgs { private Map<String,Object> _params = null; /** Constructs a event arguments object with no keys. */ public EventArgs(String line) { _params = new HashMap<String,Object>(); _params.put("line", line); } /** Converts the two specified arrays and uses the keys array as the keys for the parameters, and * uses the values array as the values of the Strings of the keys array with the same index. * @param keys An array of keys, must be the same size as values. * @param values An array of values, must be the same size as keys. * @throws IllegalArgumentException If keys.length != values.length or if keys ==null || values == null. */ public EventArgs(String line, String[] keys, String[] values) { if (keys == null || values == null) throw new IllegalArgumentException("Keys/values cannot be null."); _params = BotUtils.stringObjectArraysToStringObjectMap(keys, values); _params.put("line", line); } /** Creates a EventArgs object with the specified arguments as it's parameters. * @param args The String Object map of the arguments. */ public EventArgs(String line, Map<String, Object> args) { if (args == null) { throw new IllegalArgumentException("args cannot be null."); } this._params = args; _params.put("line", line); } /** Gets the parameter with the specified key. * @return The value of the parameter. Null if there's no mapping. */ public Object getParam(String key) { return _params.get(key); } /** Gets all the keys in this args set.<BR/> * A common use of this would be: <BR/><BR/> * <code>for (String s : args.getKeySet()) {<BR/> * someList.add(args.getParam(s));<BR/> * }<BR/><BR/> * </code> * Which would add all the values in the args set to someList (or whatever list * you replaced it with.) * @return A set of all the keys in the args set. */ public Set<String> getKeySet() { return _params.keySet(); } /** Retrieves a event parameter as a String, using the {@link Object#toString()} method (so that it is more typesafe than * casting to a String). This is just a convenience method, and is the same as {@link #getParam(String)}.toString(). * * @param key The key to retrieve the value of. * @return The value of the parameter with the specified key. */ public String getParamAsString(String key) { Object o = getParam(key); if (o == null) { return null; } return o.toString(); } }
Added a containsKey method to EventArgs.
testing/lib/irc/src/org/ossnipes/snipes/lib/events/EventArgs.java
Added a containsKey method to EventArgs.
Java
mit
0df77c7861b8177c0062e84cd50097646d129e4f
0
Mohammad-Khan/sharedhere,Mohammad-Khan/sharedhere,shamidi/SharedHereFork,Mohammad-Khan/sharedhere,shamidi/SharedHereFork
package com.sharedhere.model; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Environment; import android.util.Log; public class SHClientServer { public static final int REQUEST_POI_DOWNLOAD = 0; public static final int REQUEST_DATA_UPLOAD = 1; public static final int REQUEST_DATA_DOWNLOAD = 2; private String serverAddress = null; private HttpClient httpClient = null; private HttpPost httpPost = null; private HttpResponse httpResponse = null; HttpEntity responseEntity = null; public SHClientServer (String server) { this.serverAddress = server; } /** * Request the server for "points of interest" * * @return List of GeoPoint objects */ public List<SHLocation> getPoi() { httpClient = new DefaultHttpClient(); String serverPage = serverAddress+"poi.php"; httpPost = new HttpPost(serverPage); List<SHLocation> locations = null; JSONArray jsonArray = null; JSONObject jsonObject = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = null; String line = null; String result = null; try { List<NameValuePair> requestEntity = new ArrayList<NameValuePair>(); requestEntity.add(new BasicNameValuePair ("request_id", Integer.toString(REQUEST_POI_DOWNLOAD))); httpPost.setEntity(new UrlEncodedFormEntity(requestEntity)); httpResponse = httpClient.execute(httpPost); responseEntity = httpResponse.getEntity(); inputStream = responseEntity.getContent(); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); stringBuilder = new StringBuilder(); while ((line=bufferedReader.readLine()) != null) { stringBuilder.append(line+"\n"); } inputStream.close(); result = stringBuilder.toString(); jsonArray = new JSONArray(result); locations = new ArrayList<SHLocation>(); for(int i=0; i<jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); double lat = (double)jsonObject.getDouble("latitude"); double lon = (double)jsonObject.getDouble("longitude"); locations.add(new SHLocation(lat, lon)); } } catch (ClientProtocolException e) { Log.e("getPoi_Err", "HTTP Protocol Exception: "+e.getMessage()); } catch (IOException e) { Log.e("getPoi_Err", "IO Exception: "+e.getMessage()); } catch (JSONException e) { Log.e("getPoi_Err", "JSON Exceptoin: "+e.getMessage()); } catch (Exception e) { Log.e("getPoi_Err", "Other Exceptoin: "+e.getMessage()); } return locations; } /** * Lists the files that are available for a particular POI * * @param poi The point of Interest for which files available are desired * @return List of available files with their details in a JSONArray */ public JSONArray listContent(SHLocation location) { String serverPage = serverAddress + "download.php"; httpClient = new DefaultHttpClient(); httpPost = new HttpPost(serverPage); InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = null; String line = null; String result = null; JSONArray jContentArray = null; JSONObject jsonObject = null; try { List<NameValuePair> requestEntity = new ArrayList<NameValuePair>(); requestEntity.add(new BasicNameValuePair ("request_id", Integer.toString(REQUEST_POI_DOWNLOAD))); requestEntity.add(new BasicNameValuePair ("latitude", Double.toString(location.getLatitude()))); requestEntity.add(new BasicNameValuePair ("longitude", Double.toString(location.getLongitude()))); httpPost.setEntity(new UrlEncodedFormEntity(requestEntity)); httpResponse = httpClient.execute(httpPost); responseEntity = httpResponse.getEntity(); inputStream = responseEntity.getContent(); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); stringBuilder = new StringBuilder(); while ((line=bufferedReader.readLine()) != null) { stringBuilder.append(line+"\n"); } inputStream.close(); result = stringBuilder.toString(); Log.i("HTTP_Info", "Result: "+result); jContentArray = new JSONArray(result); for(int i=0; i<jContentArray.length(); i++) { jsonObject = jContentArray.getJSONObject(i); String filename = (String)jsonObject.getString("filename"); String size = (String)jsonObject.getString("size"); String timestamp = (String)jsonObject.getString("timestamp"); String description = (String)jsonObject.getString("description"); String latitude = (String)jsonObject.getString("latitude"); String longitude = (String)jsonObject.getString("longitude"); Log.i("download_info", filename+","+size+","+timestamp+","+description+","+latitude+","+longitude); } } catch (ClientProtocolException cpeException) { Log.e("download_error", "HTTP Protocol Exception: "+cpeException.getMessage()); } catch (IOException ioException) { Log.e("download_error", "IO Exception: "+ioException.getMessage()); } catch (JSONException jsonException) { Log.e("download_error", "JSON Exceptoin: "+jsonException.getMessage()); } catch (Exception exception) { Log.e("download_error", "Other Exceptoin: "+exception.getMessage()); } return jContentArray; } /** * Download file given the URL for the file. * It opens up a stream of bytes, read them into memory and saves the file locally. * * @param filename to be downloaded * */ public void download(String filename, SHLocation location) { String serverFileLocation = serverAddress+"content/"+location.getLatitude()+"/"+location.getLongitude()+"/"; File sdCardRoot = Environment.getExternalStorageDirectory(); try { //this is the file to be downloaded URL url = new URL(serverFileLocation+filename); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); File file = new File(sdCardRoot, filename); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ( (bufferLength = inputStream.read(buffer)) > 0 ) { fileOutput.write(buffer, 0, bufferLength); } fileOutput.close(); } catch (MalformedURLException e) { Log.e("download", e.getMessage()); } catch (IOException e) { Log.e("SH_download", e.getMessage()); } } /** * Upload file to the server * Uses a multipart form and posts the file with meta data to the webserver. * The web server saves the file on file system and stores meta data into a database * * @param pathname - file to be upload * @param latitude - latitude associated with file * @param longitude - longitude associated with file * */ public boolean upload(String pathname, SHLocation location, String description) { String serverPage = serverAddress + "upload.php"; httpClient = new DefaultHttpClient(); StringBody requestId=null; MultipartEntity requestEntity = null; FileBody inputFile = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = null; String line = null; String result; int responseCode = 0; try { httpPost = new HttpPost(serverPage); inputFile = new FileBody(new File(pathname)); requestEntity = new MultipartEntity(); requestEntity.addPart("sharedfile", inputFile); requestId = new StringBody(String.valueOf(REQUEST_DATA_UPLOAD)); requestEntity.addPart("request_id", requestId); requestEntity.addPart("latitude", new StringBody(String.valueOf(location.getLatitude()))); requestEntity.addPart("longitude", new StringBody(String.valueOf(location.getLongitude()))); requestEntity.addPart("description", new StringBody(description)); httpPost.setEntity(requestEntity); httpResponse = httpClient.execute(httpPost); responseEntity = httpResponse.getEntity(); /* TODO The code below is unused now. * Use it to check if upload succeeded or not */ inputStream = responseEntity.getContent(); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); stringBuilder = new StringBuilder(); while ((line=bufferedReader.readLine()) != null) { stringBuilder.append(line+"\n"); } inputStream.close(); result = stringBuilder.toString(); } catch (Exception e){ Log.e("upload_error", e.getMessage()); } responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) return false; return true; } }
client/android/main/src/com/sharedhere/model/SHClientServer.java
package com.sharedhere.model; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Environment; import android.util.Log; public class SHClientServer { public static final int REQUEST_POI_DOWNLOAD = 0; public static final int REQUEST_DATA_UPLOAD = 1; public static final int REQUEST_DATA_DOWNLOAD = 2; private String serverAddress = null; private HttpClient httpClient = null; private HttpPost httpPost = null; private HttpResponse httpResponse = null; public SHClientServer (String server) { this.serverAddress = server; } /** * Request the server for "points of interest" * * @author naser * * @return List of GeoPoint objects */ public List<SHLocation> getPoi() { httpClient = new DefaultHttpClient(); String serverPage = serverAddress+"poi.php"; httpPost = new HttpPost(serverPage); List<SHLocation> locations = null; JSONArray jsonArray = null; JSONObject jsonObject = null; HttpEntity responseEntity = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = null; String line = null; String result = null; try { List<NameValuePair> requestEntity = new ArrayList<NameValuePair>(); requestEntity.add(new BasicNameValuePair ("request_id", Integer.toString(REQUEST_POI_DOWNLOAD))); httpPost.setEntity(new UrlEncodedFormEntity(requestEntity)); httpResponse = httpClient.execute(httpPost); responseEntity = httpResponse.getEntity(); inputStream = responseEntity.getContent(); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); stringBuilder = new StringBuilder(); while ((line=bufferedReader.readLine()) != null) { stringBuilder.append(line+"\n"); } inputStream.close(); result = stringBuilder.toString(); //Log.i("getPoi", "Result: "+result); jsonArray = new JSONArray(result); locations = new ArrayList<SHLocation>(); for(int i=0; i<jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); double lat = (double)jsonObject.getDouble("latitude"); double lon = (double)jsonObject.getDouble("longitude"); locations.add(new SHLocation(lat, lon)); } } catch (ClientProtocolException e) { Log.e("getPoi_Err", "HTTP Protocol Exception: "+e.getMessage()); } catch (IOException e) { Log.e("getPoi_Err", "IO Exception: "+e.getMessage()); } catch (JSONException e) { Log.e("getPoi_Err", "JSON Exceptoin: "+e.getMessage()); } catch (Exception e) { Log.e("getPoi_Err", "Other Exceptoin: "+e.getMessage()); } return locations; } /** * Lists the files that are available for a particular POI * * @author naser * * @param poi The point of Interest for which files available are desired * @return List of available files with their details in a JSONArray */ public JSONArray listContent(SHLocation location) { String serverPage = serverAddress + "download.php"; httpClient = new DefaultHttpClient(); httpPost = new HttpPost(serverPage); HttpEntity responseEntity = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = null; String line = null; String result = null; JSONArray jContentArray = null; JSONObject jsonObject = null; try { List<NameValuePair> requestEntity = new ArrayList<NameValuePair>(); requestEntity.add(new BasicNameValuePair ("request_id", Integer.toString(REQUEST_POI_DOWNLOAD))); requestEntity.add(new BasicNameValuePair ("latitude", Double.toString(location.getLatitude()))); requestEntity.add(new BasicNameValuePair ("longitude", Double.toString(location.getLongitude()))); httpPost.setEntity(new UrlEncodedFormEntity(requestEntity)); httpResponse = httpClient.execute(httpPost); responseEntity = httpResponse.getEntity(); inputStream = responseEntity.getContent(); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); stringBuilder = new StringBuilder(); while ((line=bufferedReader.readLine()) != null) { stringBuilder.append(line+"\n"); } inputStream.close(); result = stringBuilder.toString(); Log.i("HTTP_Info", "Result: "+result); jContentArray = new JSONArray(result); for(int i=0; i<jContentArray.length(); i++) { jsonObject = jContentArray.getJSONObject(i); String filename = (String)jsonObject.getString("filename"); String size = (String)jsonObject.getString("size"); String timestamp = (String)jsonObject.getString("timestamp"); String description = (String)jsonObject.getString("description"); String latitude = (String)jsonObject.getString("latitude"); String longitude = (String)jsonObject.getString("longitude"); Log.i("download_info", filename+","+size+","+timestamp+","+description+","+latitude+","+longitude); } } catch (ClientProtocolException cpeException) { Log.e("download_error", "HTTP Protocol Exception: "+cpeException.getMessage()); } catch (IOException ioException) { Log.e("download_error", "IO Exception: "+ioException.getMessage()); } catch (JSONException jsonException) { Log.e("download_error", "JSON Exceptoin: "+jsonException.getMessage()); } catch (Exception exception) { Log.e("download_error", "Other Exceptoin: "+exception.getMessage()); } return jContentArray; } /** * Download file * * @author naser * * @param filename to be downloaded * @return * */ public void download(String filename, SHLocation location) { String serverFileLocation = serverAddress+"content/"+location.getLatitude()+"/"+location.getLongitude()+"/"; File sdCardRoot = Environment.getExternalStorageDirectory(); try { //this is the file to be downloaded URL url = new URL(serverFileLocation+filename); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); File file = new File(sdCardRoot, filename); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ( (bufferLength = inputStream.read(buffer)) > 0 ) { fileOutput.write(buffer, 0, bufferLength); } Log.i("DownloadInfo", "at: "+file.toString()); fileOutput.close(); } catch (MalformedURLException e) { Log.e("download", e.getMessage()); } catch (IOException e) { Log.e("SH_download", e.getMessage()); } } /** * Upload file * * @author naser * * @param pathname - file to be upload * @param latitude - latitude associated with file * @param longitude - longitude associated with file * * @return */ public void upload(String pathname, SHLocation location, String description) { String serverPage = serverAddress + "upload.php"; HttpClient httpclient = new DefaultHttpClient(); HttpEntity responseEntity = null; StringBody requestId=null; MultipartEntity requestEntity = null; FileBody inputFile = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = null; String line = null; String result = null; try { httpPost = new HttpPost(serverPage); inputFile = new FileBody(new File(pathname)); requestEntity = new MultipartEntity(); requestEntity.addPart("sharedfile", inputFile); requestId = new StringBody(String.valueOf(REQUEST_DATA_UPLOAD)); requestEntity.addPart("request_id", requestId); requestEntity.addPart("latitude", new StringBody(String.valueOf(location.getLatitude()))); requestEntity.addPart("longitude", new StringBody(String.valueOf(location.getLongitude()))); requestEntity.addPart("description", new StringBody(description)); httpPost.setEntity(requestEntity); Log.i("upload_info","executing request " + httpPost.getRequestLine()); httpResponse = httpclient.execute(httpPost); responseEntity = httpResponse.getEntity(); Log.i("upload_info", responseEntity.toString()); inputStream = responseEntity.getContent(); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); stringBuilder = new StringBuilder(); while ((line=bufferedReader.readLine()) != null) { stringBuilder.append(line+"\n"); } inputStream.close(); result = stringBuilder.toString(); Log.i("upload_info", "Result: "+result); } catch (Exception e){ Log.e("upload_error", e.getMessage()); } } }
* Change upload method so as to return upload status (boolean) * Make minor changes into SHClientServer to make it more readable
client/android/main/src/com/sharedhere/model/SHClientServer.java
* Change upload method so as to return upload status (boolean) * Make minor changes into SHClientServer to make it more readable
Java
epl-1.0
e4837431a265efe96d05d2edf414c55031ebd725
0
cstultz/cis234
package cis234a.nsort.controller; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import cis234a.nsort.model.*; import cis234a.nsort.view.*; /** * The AdminTestSetupController handles the logic for creating a user test, on/off state of the progress indicator during the user test, and * the access to the test results reporting for all users. * * @author (Chris.Stultz, John.Loranger, Ryan.Reams, Josh.Eads) * @version (5/8/2015) */ public class AdminTestSetupController { protected RankingSystemController controller; protected AdminTestSetupModel model; protected AdminTestSetupView view; protected SqlUser_234a_t1 sqlUser; /** * Constructor for the class. * @param RankingSystemController for communication back. * @param AdminTestSetupModel will directly manage the data, logic and rules of the admin test setup. * @param AdminTestSetupView output representation of the admin test setup information. */ public AdminTestSetupController(RankingSystemController controller, AdminTestSetupModel model, AdminTestSetupView view) { this.controller = controller; this.model = model; this.view = view; sqlUser = SqlUser_234a_t1.INSTANCE; updateView(); } /** * update the view. populates the existing items list, the test items list, and updates the progress meter check box selected state. */ private void updateView() { populateExistingItemsToTheDefaultListModel(); populateTestItemsToTheDefaultListModel(); updateProgressMeterCheckBoxSetSelected(); view.updateAdminTestSetupFrame(model.getAdminTestSetupState()); } /** * populate the Items from the model to the Existing Items List in the view. */ public void populateExistingItemsToTheDefaultListModel() { view.setExistingItemsList(model.getExistingItemsList()); } /** * populate the Items from the model to the Test Items List in the view. */ public void populateTestItemsToTheDefaultListModel() { view.setTestItemsList(model.getTestItemsList()); } /** * remove an item from the Test Items list. * * @param selectedValue of the item being removed */ public void removeItemFromTestItemList(String selectedValue) { model.removeItemFromTestItemList(selectedValue); } /** * add an item from the Existing Items List to the Test Items List * * @param selectedValue being added to the Test Items List from the Existing Items List */ public void addExistingItemToTestItemsList(String selectedValue) { if (! model.checkTestItemsListMatch(selectedValue)) { Item item = new Item(); //create the new Item item.setValue(selectedValue); //set the value of the item model.addExistingItemToTestItemsList(selectedValue); //update the model view.updateTestItemsList(selectedValue); //update the view } else { view.showDuplicateTestItemsMessage(selectedValue); } } /** * save the Test Items List to the database and the model. logs out the administrator. * * @param items Item List being saved */ public void saveTestItemsList(ItemList items) { sqlUser.saveTest(items); model.saveTestList(items); logoutAdmin(); } /** * log out the administrator. sets login state to false; set user access role to Unassigned. */ public void logoutAdmin() { model.setLoginState(false); model.setUserAccessRole(Role.UserAccessRole.Unassigned); } /** * hide the admin test setup frame (admin logged off) and launch the login frame */ public void hideAdminTestSetup() { logoutAdmin(); controller.launchLogin(); } /** * Checks to see if the Test Item List meets the minimum requirements for a test (test items list >= 2) * * @param testItemsListModel the items on the test being checked * @return true if minimum requirements of the test are met; false if not. */ public boolean checkItemsListMeetsMinimumRequirements() { return model.checkItemsListMeetsMinimumRequirements(); } /** * check to see if the new item value being added is an empty string * * @param value of the item being added * @return true if the value is empty; false if not. */ public boolean checkAddAnItemTextFieldIsEmpty(String value) { if (value.trim().equals("")) {return true;} else {return false;} } /** * check to see if the new item value being added is unique to the Existing Items List * * @param existingItemsListModel being checked * @param value of the item being added * @return true if the value of the item is unique; false if not. */ public boolean checkAddAnItemTextFieldIsUnique(String selectedValue) { if (! model.checkExistingItemsListMatch(selectedValue)) {return true;} else {return false;} } /** * add a new item to the Existing Items List in the database and the model. * * @param existingItemsListModel the value will be added to * @param value of the item being added */ public void addNewItemToExistingItemsList(String newItemValue) { if (checkAddAnItemTextFieldIsEmpty(newItemValue)) { view.showEmptyItemMessage(); } else { if (checkAddAnItemTextFieldIsUnique(newItemValue)) { model.addNewItemToExistingItemsList(newItemValue); sqlUser.addNewItem(newItemValue); view.updateExistingItemsList(newItemValue); } else { view.showExistingItemMatchMessage(model.getExistingItemsListModelMatch(newItemValue)); } } } /** * get the Existing Items List item value that matches the new item value being added * * @param existingItemsListModel that contains the item value that matches * @param value of the new item being added * @return the value of the item match from the Existing Items List */ public String getExistingItemsListModelMatch(String value) { return model.getExistingItemsListModelMatch(value); } /** * gets the persisted progress meter selected state from the database and updates the model and view. */ public void updateProgressMeterCheckBoxSetSelected() { boolean selectedState = sqlUser.getProgressMeterSelectedState(); model.setProgressMeterSelectedState(selectedState); view.setProgressMeterSelectedState(selectedState); } /** * sets the progress meter selected state in the database and the model. * * @param progressMeterSelectedState */ public void setProgressMeterSelectedState(boolean progressMeterSelectedState) { sqlUser.setProgressBarSelectedState(progressMeterSelectedState); model.setProgressMeterSelectedState(progressMeterSelectedState); } /** * launch the test results reporting view */ public void launchReport() { Report model = new Report(); ReportView view = new ReportView(model.getUsers()); @SuppressWarnings("unused") ReportController controlsler = new ReportController(view, model); view.setVisible(true); } public void updateItemImage(String value) { byte[] data = sqlUser.getValueImageByteArray(value); view.updateImage(data); } /** * populate th e Items from the model to the Existing Items List in the view. */ public void associateImageToExistingItem(String currentSelection) { File selectedFile = null; byte[] data = null; JFileChooser openFile = new JFileChooser(System.getProperty("user.home") + System.getProperty("file.separator")+ "Pictures"); FileFilter filter = new FileNameExtensionFilter(".png, .jpg", new String[] {"png", "jpg"}); openFile.setFileFilter(filter); openFile.addChoosableFileFilter(filter); openFile.setCurrentDirectory(new File("User.dir"));; int returnVal = openFile.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = new File(openFile.getSelectedFile().getAbsolutePath()); try { data = convertFileToByteArray(selectedFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (sqlUser.getValueImageByteArray(currentSelection) == null) { sqlUser.addImage(currentSelection, data); sqlUser.associateImageToExistingItem(currentSelection); } else { sqlUser.updateImage(currentSelection, data); } } } public byte[] convertFileToByteArray(File file) throws IOException { ByteArrayOutputStream ous = null; InputStream ios = null; try { byte[] buffer = new byte[4096]; ous = new ByteArrayOutputStream(); ios = new FileInputStream(file); int read = 0; while ( (read = ios.read(buffer)) != -1 ) { ous.write(buffer, 0, read); } } finally { try { if ( ous != null ) ous.close(); } catch ( IOException e) { } try { if ( ios != null ) ios.close(); } catch ( IOException e) { } } return ous.toByteArray(); } public void deleteExistingItem(String currentSelection) { JOptionPane.showMessageDialog(null, "Delete Item " + currentSelection + " from Existing Items List","Delete Existing Item",JOptionPane.WARNING_MESSAGE); } }
projects/nsort/src/cis234a/nsort/controller/AdminTestSetupController.java
package cis234a.nsort.controller; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import cis234a.nsort.model.*; import cis234a.nsort.view.*; /** * The AdminTestSetupController handles the logic for creating a user test, on/off state of the progress indicator during the user test, and * the access to the test results reporting for all users. * * @author (Chris.Stultz, John.Loranger, Ryan.Reams, Josh.Eads) * @version (5/8/2015) */ public class AdminTestSetupController { protected RankingSystemController controller; protected AdminTestSetupModel model; protected AdminTestSetupView view; protected SqlUser_234a_t1 sqlUser; /** * Constructor for the class. * @param RankingSystemController for communication back. * @param AdminTestSetupModel will directly manage the data, logic and rules of the admin test setup. * @param AdminTestSetupView output representation of the admin test setup information. */ public AdminTestSetupController(RankingSystemController controller, AdminTestSetupModel model, AdminTestSetupView view) { this.controller = controller; this.model = model; this.view = view; sqlUser = SqlUser_234a_t1.INSTANCE; updateView(); } /** * update the view. populates the existing items list, the test items list, and updates the progress meter check box selected state. */ private void updateView() { populateExistingItemsToTheDefaultListModel(); populateTestItemsToTheDefaultListModel(); updateProgressMeterCheckBoxSetSelected(); view.updateAdminTestSetupFrame(model.getAdminTestSetupState()); } /** * populate the Items from the model to the Existing Items List in the view. */ public void populateExistingItemsToTheDefaultListModel() { view.setExistingItemsList(model.getExistingItemsList()); } /** * populate the Items from the model to the Test Items List in the view. */ public void populateTestItemsToTheDefaultListModel() { view.setTestItemsList(model.getTestItemsList()); } /** * remove an item from the Test Items list. * * @param selectedValue of the item being removed */ public void removeItemFromTestItemList(String selectedValue) { model.removeItemFromTestItemList(selectedValue); } /** * add an item from the Existing Items List to the Test Items List * * @param selectedValue being added to the Test Items List from the Existing Items List */ public void addExistingItemToTestItemsList(String selectedValue) { if (! model.checkTestItemsListMatch(selectedValue)) { Item item = new Item(); //create the new Item item.setValue(selectedValue); //set the value of the item model.addExistingItemToTestItemsList(selectedValue); //update the model view.updateTestItemsList(selectedValue); //update the view } else { view.showDuplicateTestItemsMessage(selectedValue); } } /** * save the Test Items List to the database and the model. logs out the administrator. * * @param items Item List being saved */ public void saveTestItemsList(ItemList items) { sqlUser.saveTest(items); model.saveTestList(items); logoutAdmin(); } /** * log out the administrator. sets login state to false; set user access role to Unassigned. */ public void logoutAdmin() { model.setLoginState(false); model.setUserAccessRole(Role.UserAccessRole.Unassigned); } /** * hide the admin test setup frame (admin logged off) and launch the login frame */ public void hideAdminTestSetup() { logoutAdmin(); controller.launchLogin(); } /** * Checks to see if the Test Item List meets the minimum requirements for a test (test items list >= 2) * * @param testItemsListModel the items on the test being checked * @return true if minimum requirements of the test are met; false if not. */ public boolean checkItemsListMeetsMinimumRequirements() { return model.checkItemsListMeetsMinimumRequirements(); } /** * check to see if the new item value being added is an empty string * * @param value of the item being added * @return true if the value is empty; false if not. */ public boolean checkAddAnItemTextFieldIsEmpty(String value) { if (value.trim().equals("")) {return true;} else {return false;} } /** * check to see if the new item value being added is unique to the Existing Items List * * @param existingItemsListModel being checked * @param value of the item being added * @return true if the value of the item is unique; false if not. */ public boolean checkAddAnItemTextFieldIsUnique(String selectedValue) { if (! model.checkExistingItemsListMatch(selectedValue)) {return true;} else {return false;} } /** * add a new item to the Existing Items List in the database and the model. * * @param existingItemsListModel the value will be added to * @param value of the item being added */ public void addNewItemToExistingItemsList(String newItemValue) { if (checkAddAnItemTextFieldIsEmpty(newItemValue)) { view.showEmptyItemMessage(); } else { if (checkAddAnItemTextFieldIsUnique(newItemValue)) { model.addNewItemToExistingItemsList(newItemValue); sqlUser.addNewItem(newItemValue); view.updateExistingItemsList(newItemValue); } else { view.showExistingItemMatchMessage(model.getExistingItemsListModelMatch(newItemValue)); } } } /** * get the Existing Items List item value that matches the new item value being added * * @param existingItemsListModel that contains the item value that matches * @param value of the new item being added * @return the value of the item match from the Existing Items List */ public String getExistingItemsListModelMatch(String value) { return model.getExistingItemsListModelMatch(value); } /** * gets the persisted progress meter selected state from the database and updates the model and view. */ public void updateProgressMeterCheckBoxSetSelected() { boolean selectedState = sqlUser.getProgressMeterSelectedState(); model.setProgressMeterSelectedState(selectedState); view.setProgressMeterSelectedState(selectedState); } /** * sets the progress meter selected state in the database and the model. * * @param progressMeterSelectedState */ public void setProgressMeterSelectedState(boolean progressMeterSelectedState) { sqlUser.setProgressBarSelectedState(progressMeterSelectedState); model.setProgressMeterSelectedState(progressMeterSelectedState); } /** * launch the test results reporting view */ public void launchReport() { Report model = new Report(); ReportView view = new ReportView(model.getUsers()); @SuppressWarnings("unused") ReportController controlsler = new ReportController(view, model); view.setVisible(true); } public void updateItemImage(String value) { byte[] data = sqlUser.getValueImageByteArray(value); view.updateImage(data); } /** * populate th e Items from the model to the Existing Items List in the view. */ public void associateImageToExistingItem(String currentSelection) { File selectedFile = null; byte[] data = null; JFileChooser openFile = new JFileChooser(); FileFilter filter = new FileNameExtensionFilter(".png, .jpg", new String[] {"png", "jpg"}); openFile.setFileFilter(filter); openFile.addChoosableFileFilter(filter); openFile.setCurrentDirectory(new File("User.dir"));; int returnVal = openFile.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = new File(openFile.getSelectedFile().getAbsolutePath()); try { data = convertFileToByteArray(selectedFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (sqlUser.getValueImageByteArray(currentSelection) == null) { sqlUser.addImage(currentSelection, data); sqlUser.associateImageToExistingItem(currentSelection); } else { sqlUser.updateImage(currentSelection, data); } } } public byte[] convertFileToByteArray(File file) throws IOException { ByteArrayOutputStream ous = null; InputStream ios = null; try { byte[] buffer = new byte[4096]; ous = new ByteArrayOutputStream(); ios = new FileInputStream(file); int read = 0; while ( (read = ios.read(buffer)) != -1 ) { ous.write(buffer, 0, read); } } finally { try { if ( ous != null ) ous.close(); } catch ( IOException e) { } try { if ( ios != null ) ios.close(); } catch ( IOException e) { } } return ous.toByteArray(); } public void deleteExistingItem(String currentSelection) { JOptionPane.showMessageDialog(null, "Delete Item " + currentSelection + " from Existing Items List","Delete Existing Item",JOptionPane.WARNING_MESSAGE); } }
set the system pictures folder as the default directory when editing an image
projects/nsort/src/cis234a/nsort/controller/AdminTestSetupController.java
set the system pictures folder as the default directory when editing an image
Java
epl-1.0
f21993e93d0c970f76c90d8e2b370855db6358a9
0
ctron/kura,ctron/kura,gavinying/kura,gavinying/kura,markoer/kura,cdealti/kura,markoer/kura,markoer/kura,darionct/kura,cdealti/kura,cdealti/kura,darionct/kura,markoer/kura,nicolatimeus/kura,nicolatimeus/kura,gavinying/kura,darionct/kura,darionct/kura,cdealti/kura,nicolatimeus/kura,nicolatimeus/kura,cdealti/kura,gavinying/kura,darionct/kura,ymai/kura,darionct/kura,gavinying/kura,ctron/kura,ctron/kura,ymai/kura,markoer/kura,ymai/kura,ymai/kura,gavinying/kura,cdealti/kura,ctron/kura,nicolatimeus/kura,nicolatimeus/kura,ymai/kura,ymai/kura,ctron/kura,markoer/kura
/******************************************************************************* * Copyright (c) 2011, 2017 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.net.admin.monitor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.kura.KuraException; import org.eclipse.kura.comm.CommURI; import org.eclipse.kura.core.net.NetworkConfiguration; import org.eclipse.kura.linux.net.ConnectionInfoImpl; import org.eclipse.kura.linux.net.modem.SupportedSerialModemInfo; import org.eclipse.kura.linux.net.modem.SupportedSerialModemsInfo; import org.eclipse.kura.linux.net.modem.SupportedUsbModemInfo; import org.eclipse.kura.linux.net.modem.SupportedUsbModemsInfo; import org.eclipse.kura.linux.net.util.LinuxNetworkUtil; import org.eclipse.kura.net.ConnectionInfo; import org.eclipse.kura.net.NetConfig; import org.eclipse.kura.net.NetConfigIP4; import org.eclipse.kura.net.NetInterface; import org.eclipse.kura.net.NetInterfaceAddress; import org.eclipse.kura.net.NetInterfaceAddressConfig; import org.eclipse.kura.net.NetInterfaceConfig; import org.eclipse.kura.net.NetInterfaceStatus; import org.eclipse.kura.net.NetworkService; import org.eclipse.kura.net.admin.NetworkConfigurationService; import org.eclipse.kura.net.admin.event.NetworkConfigurationChangeEvent; import org.eclipse.kura.net.admin.event.NetworkStatusChangeEvent; import org.eclipse.kura.net.admin.modem.CellularModemFactory; import org.eclipse.kura.net.admin.modem.EvdoCellularModem; import org.eclipse.kura.net.admin.modem.HspaCellularModem; import org.eclipse.kura.net.admin.modem.IModemLinkService; import org.eclipse.kura.net.admin.modem.PppFactory; import org.eclipse.kura.net.admin.modem.PppState; import org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo.SerialModemFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo.UsbModemFactoryInfo; import org.eclipse.kura.net.admin.visitor.linux.util.KuranetConfig; import org.eclipse.kura.net.modem.CellularModem; import org.eclipse.kura.net.modem.ModemAddedEvent; import org.eclipse.kura.net.modem.ModemConfig; import org.eclipse.kura.net.modem.ModemDevice; import org.eclipse.kura.net.modem.ModemGpsDisabledEvent; import org.eclipse.kura.net.modem.ModemGpsEnabledEvent; import org.eclipse.kura.net.modem.ModemInterface; import org.eclipse.kura.net.modem.ModemManagerService; import org.eclipse.kura.net.modem.ModemMonitorListener; import org.eclipse.kura.net.modem.ModemMonitorService; import org.eclipse.kura.net.modem.ModemReadyEvent; import org.eclipse.kura.net.modem.ModemRemovedEvent; import org.eclipse.kura.net.modem.ModemTechnologyType; import org.eclipse.kura.net.modem.SerialModemDevice; import org.eclipse.kura.system.SystemService; import org.eclipse.kura.usb.UsbDeviceEvent; import org.eclipse.kura.usb.UsbModemDevice; import org.osgi.service.component.ComponentContext; import org.osgi.service.event.Event; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ModemMonitorServiceImpl implements ModemMonitorService, ModemManagerService, EventHandler { private static final Logger logger = LoggerFactory.getLogger(ModemMonitorServiceImpl.class); private static final String[] EVENT_TOPICS = new String[] { NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC, ModemAddedEvent.MODEM_EVENT_ADDED_TOPIC, ModemRemovedEvent.MODEM_EVENT_REMOVED_TOPIC, }; private static final long THREAD_INTERVAL = 30000; private static final long THREAD_TERMINATION_TOUT = 1; // in seconds private static Object lock = new Object(); private Future<?> task; private static AtomicBoolean stopThread; private SystemService systemService; private NetworkService networkService; private NetworkConfigurationService netConfigService; private EventAdmin eventAdmin; private List<ModemMonitorListener> listeners; private ExecutorService executor; private Map<String, CellularModem> modems; private Map<String, InterfaceState> interfaceStatuses; private NetworkConfiguration networkConfig; private boolean serviceActivated; private PppState pppState; private long resetTimerStart; public void setNetworkService(NetworkService networkService) { this.networkService = networkService; } public void unsetNetworkService(NetworkService networkService) { this.networkService = null; } public void setEventAdmin(EventAdmin eventAdmin) { this.eventAdmin = eventAdmin; } public void unsetEventAdmin(EventAdmin eventAdmin) { this.eventAdmin = null; } public void setNetworkConfigurationService(NetworkConfigurationService netConfigService) { this.netConfigService = netConfigService; } public void unsetNetworkConfigurationService(NetworkConfigurationService netConfigService) { this.netConfigService = null; } public void setSystemService(SystemService systemService) { this.systemService = systemService; } public void unsetSystemService(SystemService systemService) { this.systemService = null; } protected void activate(ComponentContext componentContext) { this.pppState = PppState.NOT_CONNECTED; this.resetTimerStart = 0L; Dictionary<String, String[]> d = new Hashtable<>(); d.put(EventConstants.EVENT_TOPIC, EVENT_TOPICS); componentContext.getBundleContext().registerService(EventHandler.class.getName(), this, d); this.modems = new HashMap<>(); this.interfaceStatuses = new HashMap<>(); this.listeners = new ArrayList<>(); stopThread = new AtomicBoolean(); // must be initialized before trackModem() is called; risk of NPE otherwise this.executor = Executors.newSingleThreadExecutor(); // track currently installed modems try { this.networkConfig = this.netConfigService.getNetworkConfiguration(); for (NetInterface<? extends NetInterfaceAddress> netInterface : this.networkService .getNetworkInterfaces()) { if (netInterface instanceof ModemInterface) { ModemDevice modemDevice = ((ModemInterface<?>) netInterface).getModemDevice(); trackModem(modemDevice); } } } catch (Exception e) { logger.error("Error getting installed modems", e); } submitMonitorTask(); this.serviceActivated = true; logger.debug("ModemMonitor activated and ready to receive events"); } private Future<?> submitMonitorTask() { stopThread.set(false); // is task already prepared? if (task != null) { return task; } // is executor ready? if (this.executor == null) { return null; } task = this.executor.submit(() -> { while (!stopThread.get()) { Thread.currentThread().setName("ModemMonitor"); try { monitor(); monitorWait(); } catch (InterruptedException interruptedException) { Thread.interrupted(); logger.debug("modem monitor interrupted", interruptedException); } catch (Throwable t) { logger.error("Exception while monitoring cellular connection", t); } } }); return task; } protected void deactivate(ComponentContext componentContext) { this.listeners = null; PppFactory.releaseAllPppServices(); if (task != null && !task.isDone()) { stopThread.set(true); monitorNotity(); logger.debug("Cancelling ModemMonitor task ..."); task.cancel(true); logger.info("ModemMonitor task cancelled? = {}", task.isDone()); task = null; } if (this.executor != null) { logger.debug("Terminating ModemMonitor Thread ..."); this.executor.shutdownNow(); try { this.executor.awaitTermination(THREAD_TERMINATION_TOUT, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.warn("Interrupted", e); } logger.info("ModemMonitor Thread terminated? - {}", this.executor.isTerminated()); this.executor = null; } this.serviceActivated = false; this.networkConfig = null; } @Override public void handleEvent(Event event) { logger.debug("handleEvent - topic: {}", event.getTopic()); String topic = event.getTopic(); if (topic.equals(NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC)) { NetworkConfigurationChangeEvent netConfigChangedEvent = (NetworkConfigurationChangeEvent) event; String[] propNames = netConfigChangedEvent.getPropertyNames(); if (propNames != null && propNames.length > 0) { Map<String, Object> props = new HashMap<>(); for (String propName : propNames) { Object prop = netConfigChangedEvent.getProperty(propName); if (prop != null) { props.put(propName, prop); } } try { final NetworkConfiguration newNetworkConfig = new NetworkConfiguration(props); ExecutorService ex = Executors.newSingleThreadExecutor(); ex.submit(() -> processNetworkConfigurationChangeEvent(newNetworkConfig)); } catch (Exception e) { logger.error("Failed to handle the NetworkConfigurationChangeEvent ", e); } } } else if (topic.equals(ModemAddedEvent.MODEM_EVENT_ADDED_TOPIC)) { ModemAddedEvent modemAddedEvent = (ModemAddedEvent) event; final ModemDevice modemDevice = modemAddedEvent.getModemDevice(); if (this.serviceActivated) { ExecutorService ex = Executors.newSingleThreadExecutor(); ex.submit(() -> trackModem(modemDevice)); } } else if (topic.equals(ModemRemovedEvent.MODEM_EVENT_REMOVED_TOPIC)) { ModemRemovedEvent modemRemovedEvent = (ModemRemovedEvent) event; String usbPort = (String) modemRemovedEvent.getProperty(UsbDeviceEvent.USB_EVENT_USB_PORT_PROPERTY); this.modems.remove(usbPort); } } @Override public CellularModem getModemService(String usbPort) { return this.modems.get(usbPort); } @Override public Collection<CellularModem> getAllModemServices() { return this.modems.values(); } private NetInterfaceStatus getNetInterfaceStatus(List<NetConfig> netConfigs) { NetInterfaceStatus interfaceStatus = NetInterfaceStatus.netIPv4StatusUnknown; if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { interfaceStatus = ((NetConfigIP4) netConfig).getStatus(); break; } } } return interfaceStatus; } private void setNetInterfaceStatus(NetInterfaceStatus netInterfaceStatus, List<NetConfig> netConfigs) { if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { ((NetConfigIP4) netConfig).setStatus(netInterfaceStatus); break; } } } } @Override public void registerListener(ModemMonitorListener newListener) { boolean found = false; if (this.listeners == null) { this.listeners = new ArrayList<>(); } if (!this.listeners.isEmpty()) { for (ModemMonitorListener listener : this.listeners) { if (listener.equals(newListener)) { found = true; break; } } } if (!found) { this.listeners.add(newListener); } } @Override public void unregisterListener(ModemMonitorListener listenerToUnregister) { if (this.listeners != null && !this.listeners.isEmpty()) { for (int i = 0; i < this.listeners.size(); i++) { if (this.listeners.get(i).equals(listenerToUnregister)) { this.listeners.remove(i); } } } } private void processNetworkConfigurationChangeEvent(NetworkConfiguration newNetworkConfig) { synchronized (lock) { if (this.modems == null || this.modems.isEmpty()) { return; } for (Map.Entry<String, CellularModem> modemEntry : this.modems.entrySet()) { String usbPort = modemEntry.getKey(); CellularModem modem = modemEntry.getValue(); try { String ifaceName = null; if (this.networkService != null) { ifaceName = this.networkService.getModemPppPort(modem.getModemDevice()); } if (ifaceName != null) { List<NetConfig> oldNetConfigs = modem.getConfiguration(); NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = newNetworkConfig .getNetInterfaceConfig(ifaceName); if (netInterfaceConfig == null) { netInterfaceConfig = newNetworkConfig.getNetInterfaceConfig(usbPort); } List<NetConfig> newNetConfigs = null; IModemLinkService pppService = null; int ifaceNo = getInterfaceNumber(oldNetConfigs); if (ifaceNo >= 0) { pppService = PppFactory.obtainPppService(ifaceNo, modem.getDataPort()); } if (netInterfaceConfig != null) { newNetConfigs = getNetConfigs(netInterfaceConfig); } else { if (oldNetConfigs != null && pppService != null) { if (!ifaceName.equals(pppService.getIfaceName())) { StringBuilder key = new StringBuilder().append("net.interface.").append(ifaceName) .append(".config.ip4.status"); String statusString = KuranetConfig.getProperty(key.toString()); NetInterfaceStatus netInterfaceStatus = NetInterfaceStatus.netIPv4StatusDisabled; if (statusString != null && !statusString.isEmpty()) { netInterfaceStatus = NetInterfaceStatus.valueOf(statusString); } newNetConfigs = oldNetConfigs; oldNetConfigs = null; try { setInterfaceNumber(ifaceName, newNetConfigs); setNetInterfaceStatus(netInterfaceStatus, newNetConfigs); } catch (NumberFormatException e) { logger.error("failed to set new interface number ", e); } } } } if (oldNetConfigs == null || !isConfigsEqual(oldNetConfigs, newNetConfigs)) { logger.info("new configuration for cellular modem on usb port {} netinterface {}", usbPort, ifaceName); this.networkConfig = newNetworkConfig; if (pppService != null) { PppState pppState = pppService.getPppState(); if (pppState == PppState.CONNECTED || pppState == PppState.IN_PROGRESS) { logger.info("disconnecting " + pppService.getIfaceName()); pppService.disconnect(); } PppFactory.releasePppService(pppService.getIfaceName()); } if (modem.isGpsEnabled()) { if (!disableModemGps(modem)) { logger.error( "processNetworkConfigurationChangeEvent() :: Failed to disable modem GPS"); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } } modem.setConfiguration(newNetConfigs); if (modem instanceof EvdoCellularModem) { NetInterfaceStatus netIfaceStatus = getNetInterfaceStatus(newNetConfigs); if (netIfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) { if (!((EvdoCellularModem) modem).isProvisioned()) { logger.info( "NetworkConfigurationChangeEvent :: The {} is not provisioned, will try to provision it ...", modem.getModel()); if (task != null && !task.isCancelled()) { logger.info("NetworkConfigurationChangeEvent :: Cancelling monitor task"); stopThread.set(true); monitorNotity(); task.cancel(true); task = null; } ((EvdoCellularModem) modem).provision(); if (task == null) { logger.info("NetworkConfigurationChangeEvent :: Restarting monitor task"); submitMonitorTask(); } else { monitorNotity(); } } else { logger.info("NetworkConfigurationChangeEvent :: The {} is provisioned", modem.getModel()); } } if (modem.isGpsSupported()) { if (isGpsEnabledInConfig(newNetConfigs) && !modem.isGpsEnabled()) { modem.enableGps(); postModemGpsEvent(modem, true); } } } } } } catch (KuraException e) { logger.error("NetworkConfigurationChangeEvent :: Failed to process ", e); } } } } private boolean isConfigsEqual(List<NetConfig> oldConfig, List<NetConfig> newConfig) { if (oldConfig == null && newConfig == null || oldConfig == null && newConfig != null || oldConfig != null && newConfig == null) { return false; } boolean ret = false; ModemConfig oldModemConfig = getModemConfig(oldConfig); ModemConfig newModemConfig = getModemConfig(newConfig); NetConfigIP4 oldNetConfigIP4 = getNetConfigIp4(oldConfig); NetConfigIP4 newNetConfigIP4 = getNetConfigIp4(newConfig); if (oldNetConfigIP4.equals(newNetConfigIP4) && oldModemConfig.equals(newModemConfig)) { ret = true; } return ret; } private List<NetConfig> getNetConfigs(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) { List<NetConfig> netConfigs = null; if (netInterfaceConfig != null) { List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig .getNetInterfaceAddresses(); if (netInterfaceAddressConfigs != null && !netInterfaceAddressConfigs.isEmpty()) { for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { netConfigs = netInterfaceAddressConfig.getConfigs(); } } } return netConfigs; } private ModemConfig getModemConfig(List<NetConfig> netConfigs) { ModemConfig modemConfig = null; for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { modemConfig = (ModemConfig) netConfig; } } return modemConfig; } private NetConfigIP4 getNetConfigIp4(List<NetConfig> netConfigs) { NetConfigIP4 netConfigIP4 = null; for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { netConfigIP4 = (NetConfigIP4) netConfig; } } return netConfigIP4; } private int getInterfaceNumber(List<NetConfig> netConfigs) { int ifaceNo = -1; if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { ifaceNo = ((ModemConfig) netConfig).getPppNumber(); break; } } } return ifaceNo; } private int getInterfaceNumber(String ifaceName) { return Integer.parseInt(ifaceName.replaceAll("[^0-9]", "")); } private void setInterfaceNumber(String ifaceName, List<NetConfig> netConfigs) { if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { ((ModemConfig) netConfig).setPppNumber(getInterfaceNumber(ifaceName)); break; } } } } private long getModemResetTimeoutMsec(String ifaceName, List<NetConfig> netConfigs) { long resetToutMsec = 0L; if (ifaceName != null && netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { resetToutMsec = ((ModemConfig) netConfig).getResetTimeout() * 60000; break; } } } return resetToutMsec; } private boolean isGpsEnabledInConfig(List<NetConfig> netConfigs) { boolean isGpsEnabled = false; if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { isGpsEnabled = ((ModemConfig) netConfig).isGpsEnabled(); break; } } } return isGpsEnabled; } private void monitor() { synchronized (lock) { HashMap<String, InterfaceState> newInterfaceStatuses = new HashMap<>(); if (this.modems == null || this.modems.isEmpty()) { return; } for (Map.Entry<String, CellularModem> modemEntry : this.modems.entrySet()) { CellularModem modem = modemEntry.getValue(); // get signal strength only if somebody needs it if (this.listeners != null && !this.listeners.isEmpty()) { for (ModemMonitorListener listener : this.listeners) { try { int rssi = modem.getSignalStrength(); listener.setCellularSignalLevel(rssi); } catch (KuraException e) { listener.setCellularSignalLevel(0); logger.error("monitor() :: Failed to obtain signal strength - {}", e); } } } IModemLinkService pppService = null; PppState pppState = null; NetInterfaceStatus netInterfaceStatus = getNetInterfaceStatus(modem.getConfiguration()); try { String ifaceName = this.networkService.getModemPppPort(modem.getModemDevice()); if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN && ifaceName != null) { pppService = PppFactory.obtainPppService(ifaceName, modem.getDataPort()); pppState = pppService.getPppState(); if (this.pppState != pppState) { logger.info("monitor() :: previous PppState={}", this.pppState); logger.info("monitor() :: current PppState={}", pppState); } if (pppState == PppState.NOT_CONNECTED) { boolean checkIfSimCardReady = false; List<ModemTechnologyType> modemTechnologyTypes = modem.getTechnologyTypes(); for (ModemTechnologyType modemTechnologyType : modemTechnologyTypes) { if (modemTechnologyType == ModemTechnologyType.GSM_GPRS || modemTechnologyType == ModemTechnologyType.UMTS || modemTechnologyType == ModemTechnologyType.HSDPA || modemTechnologyType == ModemTechnologyType.HSPA) { checkIfSimCardReady = true; break; } } if (checkIfSimCardReady) { if (((HspaCellularModem) modem).isSimCardReady()) { logger.info("monitor() :: !!! SIM CARD IS READY !!! connecting ..."); pppService.connect(); if (this.pppState == PppState.NOT_CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } } else { logger.warn("monitor() :: ! SIM CARD IS NOT READY !"); } } else { logger.info("monitor() :: connecting ..."); pppService.connect(); if (this.pppState == PppState.NOT_CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } } } else if (pppState == PppState.IN_PROGRESS) { long modemResetTout = getModemResetTimeoutMsec(ifaceName, modem.getConfiguration()); if (modemResetTout > 0) { long timeElapsed = System.currentTimeMillis() - this.resetTimerStart; if (timeElapsed > modemResetTout) { // reset modem logger.info("monitor() :: Modem Reset TIMEOUT !!!"); pppService.disconnect(); if (modem.isGpsEnabled() && !disableModemGps(modem)) { logger.error("monitor() :: Failed to disable modem GPS"); } modem.reset(); pppState = PppState.NOT_CONNECTED; this.resetTimerStart = System.currentTimeMillis(); } else { int timeTillReset = (int) (modemResetTout - timeElapsed) / 1000; logger.info( "monitor() :: PPP connection in progress. Modem will be reset in {} sec if not connected", timeTillReset); } } } else if (pppState == PppState.CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } this.pppState = pppState; ConnectionInfo connInfo = new ConnectionInfoImpl(ifaceName); InterfaceState interfaceState = new InterfaceState(ifaceName, LinuxNetworkUtil.hasAddress(ifaceName), pppState == PppState.CONNECTED, connInfo.getIpAddress()); newInterfaceStatuses.put(ifaceName, interfaceState); } if (modem.isGpsSupported()) { if (isGpsEnabledInConfig(modem.getConfiguration())) { if (modem instanceof HspaCellularModem) { if (!modem.isGpsEnabled()) { modem.enableGps(); } } postModemGpsEvent(modem, true); } } } catch (Exception e) { logger.error("monitor() :: Exception", e); if (pppService != null && pppState != null) { try { logger.info("monitor() :: Exception :: PPPD disconnect"); pppService.disconnect(); } catch (KuraException e1) { logger.error("monitor() :: Exception while disconnect", e1); } this.pppState = pppState; } if (modem.isGpsEnabled()) { try { if (!disableModemGps(modem)) { logger.error("monitor() :: Failed to disable modem GPS"); } } catch (KuraException e1) { logger.error("monitor() :: Exception disableModemGps", e1); } } try { logger.info("monitor() :: Exception :: modem reset"); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } catch (KuraException e1) { logger.error("monitor() :: Exception modem.reset", e1); } } } // post event for any status changes checkStatusChange(this.interfaceStatuses, newInterfaceStatuses); this.interfaceStatuses = newInterfaceStatuses; } } private void checkStatusChange(Map<String, InterfaceState> oldStatuses, Map<String, InterfaceState> newStatuses) { if (newStatuses != null) { // post NetworkStatusChangeEvent on current and new interfaces for (String interfaceName : newStatuses.keySet()) { if (oldStatuses != null && oldStatuses.containsKey(interfaceName)) { if (!newStatuses.get(interfaceName).equals(oldStatuses.get(interfaceName))) { logger.debug("Posting NetworkStatusChangeEvent on interface: {}", interfaceName); this.eventAdmin.postEvent( new NetworkStatusChangeEvent(interfaceName, newStatuses.get(interfaceName), null)); } } else { logger.debug("Posting NetworkStatusChangeEvent on enabled interface: {}", interfaceName); this.eventAdmin.postEvent( new NetworkStatusChangeEvent(interfaceName, newStatuses.get(interfaceName), null)); } } // post NetworkStatusChangeEvent on interfaces that are no longer there if (oldStatuses != null) { for (String interfaceName : oldStatuses.keySet()) { if (!newStatuses.containsKey(interfaceName)) { logger.debug("Posting NetworkStatusChangeEvent on disabled interface: {}", interfaceName); this.eventAdmin.postEvent( new NetworkStatusChangeEvent(interfaceName, oldStatuses.get(interfaceName), null)); } } } } } private void trackModem(ModemDevice modemDevice) { Class<? extends CellularModemFactory> modemFactoryClass = getModemFactoryClass(modemDevice); if (modemFactoryClass != null) { CellularModemFactory modemFactoryService = null; try { try { Method getInstanceMethod = modemFactoryClass.getDeclaredMethod("getInstance", (Class<?>[]) null); getInstanceMethod.setAccessible(true); modemFactoryService = (CellularModemFactory) getInstanceMethod.invoke(null, (Object[]) null); } catch (Exception e) { logger.error("Error calling getInstance() method on {}", modemFactoryClass.getName(), e); } // if unsuccessful in calling getInstance() if (modemFactoryService == null) { modemFactoryService = modemFactoryClass.newInstance(); } String platform = null; if (this.systemService != null) { platform = this.systemService.getPlatform(); } CellularModem modem = modemFactoryService.obtainCellularModemService(modemDevice, platform); try { HashMap<String, String> modemInfoMap = new HashMap<>(); modemInfoMap.put(ModemReadyEvent.IMEI, modem.getSerialNumber()); modemInfoMap.put(ModemReadyEvent.IMSI, modem.getMobileSubscriberIdentity()); modemInfoMap.put(ModemReadyEvent.ICCID, modem.getIntegratedCirquitCardId()); modemInfoMap.put(ModemReadyEvent.RSSI, Integer.toString(modem.getSignalStrength())); logger.info("posting ModemReadyEvent on topic {}", ModemReadyEvent.MODEM_EVENT_READY_TOPIC); this.eventAdmin.postEvent(new ModemReadyEvent(modemInfoMap)); } catch (Exception e) { logger.error("Failed to post the ModemReadyEvent", e); } String ifaceName = this.networkService.getModemPppPort(modemDevice); List<NetConfig> netConfigs = null; if (ifaceName != null) { NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = this.networkConfig .getNetInterfaceConfig(ifaceName); if (netInterfaceConfig == null) { this.networkConfig = this.netConfigService.getNetworkConfiguration(); netInterfaceConfig = this.networkConfig.getNetInterfaceConfig(ifaceName); } if (netInterfaceConfig != null) { netConfigs = getNetConfigs(netInterfaceConfig); if (netConfigs != null && !netConfigs.isEmpty()) { modem.setConfiguration(netConfigs); } } } if (modemDevice instanceof UsbModemDevice) { this.modems.put(((UsbModemDevice) modemDevice).getUsbPort(), modem); } else if (modemDevice instanceof SerialModemDevice) { this.modems.put(modemDevice.getProductName(), modem); } if (modem instanceof EvdoCellularModem) { NetInterfaceStatus netIfaceStatus = getNetInterfaceStatus(netConfigs); if (netIfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) { if (modem.isGpsEnabled()) { if (!disableModemGps(modem)) { logger.error("trackModem() :: Failed to disable modem GPS, resetting modem ..."); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } } if (!((EvdoCellularModem) modem).isProvisioned()) { logger.info("trackModem() :: The {} is not provisioned, will try to provision it ...", modem.getModel()); if (task != null && !task.isCancelled()) { logger.info("trackModem() :: Cancelling monitor task"); stopThread.set(true); monitorNotity(); task.cancel(true); task = null; } ((EvdoCellularModem) modem).provision(); if (task == null) { logger.info("trackModem() :: Restarting monitor task"); submitMonitorTask(); } else { monitorNotity(); } } else { logger.info("trackModem() :: The {} is provisioned", modem.getModel()); } } if (modem.isGpsSupported()) { if (isGpsEnabledInConfig(netConfigs) && !modem.isGpsEnabled()) { modem.enableGps(); postModemGpsEvent(modem, true); } } } } catch (Exception e) { logger.error("trackModem() :: {}", e.getMessage(), e); } } } protected Class<? extends CellularModemFactory> getModemFactoryClass(ModemDevice modemDevice) { Class<? extends CellularModemFactory> modemFactoryClass = null; if (modemDevice instanceof UsbModemDevice) { SupportedUsbModemInfo supportedUsbModemInfo = SupportedUsbModemsInfo.getModem((UsbModemDevice) modemDevice); UsbModemFactoryInfo usbModemFactoryInfo = SupportedUsbModemsFactoryInfo.getModem(supportedUsbModemInfo); modemFactoryClass = usbModemFactoryInfo.getModemFactoryClass(); } else if (modemDevice instanceof SerialModemDevice) { SupportedSerialModemInfo supportedSerialModemInfo = SupportedSerialModemsInfo.getModem(); SerialModemFactoryInfo serialModemFactoryInfo = SupportedSerialModemsFactoryInfo .getModem(supportedSerialModemInfo); modemFactoryClass = serialModemFactoryInfo.getModemFactoryClass(); } return modemFactoryClass; } private boolean disableModemGps(CellularModem modem) throws KuraException { postModemGpsEvent(modem, false); boolean portIsReachable = false; long startTimer = System.currentTimeMillis(); do { try { Thread.sleep(3000); if (modem.isPortReachable(modem.getAtPort())) { logger.debug("disableModemGps() modem is now reachable ..."); portIsReachable = true; break; } else { logger.debug("disableModemGps() waiting for PositionService to release serial port ..."); } } catch (Exception e) { logger.debug("disableModemGps() waiting for PositionService to release serial port ", e); } } while (System.currentTimeMillis() - startTimer < 20000L); modem.disableGps(); try { Thread.sleep(1000); } catch (InterruptedException e) { } boolean ret = false; if (portIsReachable && !modem.isGpsEnabled()) { logger.error("disableModemGps() :: Modem GPS is disabled :: portIsReachable={}, modem.isGpsEnabled()={}", portIsReachable, modem.isGpsEnabled()); ret = true; } return ret; } private void postModemGpsEvent(CellularModem modem, boolean enabled) throws KuraException { if (enabled) { CommURI commUri = modem.getSerialConnectionProperties(CellularModem.SerialPortType.GPSPORT); if (commUri != null) { logger.trace("postModemGpsEvent() :: Modem SeralConnectionProperties: {}", commUri.toString()); HashMap<String, Object> modemInfoMap = new HashMap<>(); modemInfoMap.put(ModemGpsEnabledEvent.Port, modem.getGpsPort()); modemInfoMap.put(ModemGpsEnabledEvent.BaudRate, Integer.valueOf(commUri.getBaudRate())); modemInfoMap.put(ModemGpsEnabledEvent.DataBits, Integer.valueOf(commUri.getDataBits())); modemInfoMap.put(ModemGpsEnabledEvent.StopBits, Integer.valueOf(commUri.getStopBits())); modemInfoMap.put(ModemGpsEnabledEvent.Parity, Integer.valueOf(commUri.getParity())); logger.debug("postModemGpsEvent() :: posting ModemGpsEnabledEvent on topic {}", ModemGpsEnabledEvent.MODEM_EVENT_GPS_ENABLED_TOPIC); this.eventAdmin.postEvent(new ModemGpsEnabledEvent(modemInfoMap)); } } else { logger.debug("postModemGpsEvent() :: posting ModemGpsDisableEvent on topic {}", ModemGpsDisabledEvent.MODEM_EVENT_GPS_DISABLED_TOPIC); HashMap<String, Object> modemInfoMap = new HashMap<>(); this.eventAdmin.postEvent(new ModemGpsDisabledEvent(modemInfoMap)); } } private void monitorNotity() { if (stopThread != null) { synchronized (stopThread) { stopThread.notifyAll(); } } } private void monitorWait() throws InterruptedException { if (stopThread != null) { synchronized (stopThread) { stopThread.wait(THREAD_INTERVAL); } } } }
kura/org.eclipse.kura.net.admin/src/main/java/org/eclipse/kura/net/admin/monitor/ModemMonitorServiceImpl.java
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.net.admin.monitor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.kura.KuraException; import org.eclipse.kura.comm.CommURI; import org.eclipse.kura.core.net.NetworkConfiguration; import org.eclipse.kura.linux.net.ConnectionInfoImpl; import org.eclipse.kura.linux.net.modem.SupportedSerialModemInfo; import org.eclipse.kura.linux.net.modem.SupportedSerialModemsInfo; import org.eclipse.kura.linux.net.modem.SupportedUsbModemInfo; import org.eclipse.kura.linux.net.modem.SupportedUsbModemsInfo; import org.eclipse.kura.linux.net.util.LinuxNetworkUtil; import org.eclipse.kura.net.ConnectionInfo; import org.eclipse.kura.net.NetConfig; import org.eclipse.kura.net.NetConfigIP4; import org.eclipse.kura.net.NetInterface; import org.eclipse.kura.net.NetInterfaceAddress; import org.eclipse.kura.net.NetInterfaceAddressConfig; import org.eclipse.kura.net.NetInterfaceConfig; import org.eclipse.kura.net.NetInterfaceStatus; import org.eclipse.kura.net.NetworkService; import org.eclipse.kura.net.admin.NetworkConfigurationService; import org.eclipse.kura.net.admin.event.NetworkConfigurationChangeEvent; import org.eclipse.kura.net.admin.event.NetworkStatusChangeEvent; import org.eclipse.kura.net.admin.modem.CellularModemFactory; import org.eclipse.kura.net.admin.modem.EvdoCellularModem; import org.eclipse.kura.net.admin.modem.HspaCellularModem; import org.eclipse.kura.net.admin.modem.IModemLinkService; import org.eclipse.kura.net.admin.modem.PppFactory; import org.eclipse.kura.net.admin.modem.PppState; import org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo.SerialModemFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo.UsbModemFactoryInfo; import org.eclipse.kura.net.admin.visitor.linux.util.KuranetConfig; import org.eclipse.kura.net.modem.CellularModem; import org.eclipse.kura.net.modem.ModemAddedEvent; import org.eclipse.kura.net.modem.ModemConfig; import org.eclipse.kura.net.modem.ModemDevice; import org.eclipse.kura.net.modem.ModemGpsDisabledEvent; import org.eclipse.kura.net.modem.ModemGpsEnabledEvent; import org.eclipse.kura.net.modem.ModemInterface; import org.eclipse.kura.net.modem.ModemManagerService; import org.eclipse.kura.net.modem.ModemMonitorListener; import org.eclipse.kura.net.modem.ModemMonitorService; import org.eclipse.kura.net.modem.ModemReadyEvent; import org.eclipse.kura.net.modem.ModemRemovedEvent; import org.eclipse.kura.net.modem.ModemTechnologyType; import org.eclipse.kura.net.modem.SerialModemDevice; import org.eclipse.kura.system.SystemService; import org.eclipse.kura.usb.UsbDeviceEvent; import org.eclipse.kura.usb.UsbModemDevice; import org.osgi.service.component.ComponentContext; import org.osgi.service.event.Event; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ModemMonitorServiceImpl implements ModemMonitorService, ModemManagerService, EventHandler { private static final Logger logger = LoggerFactory.getLogger(ModemMonitorServiceImpl.class); private static final String[] EVENT_TOPICS = new String[] { NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC, ModemAddedEvent.MODEM_EVENT_ADDED_TOPIC, ModemRemovedEvent.MODEM_EVENT_REMOVED_TOPIC, }; private static final long THREAD_INTERVAL = 30000; private static final long THREAD_TERMINATION_TOUT = 1; // in seconds private static Object lock = new Object(); private static Future<?> task; private static AtomicBoolean stopThread; private ComponentContext ctx; private SystemService systemService; private NetworkService networkService; private NetworkConfigurationService netConfigService; private EventAdmin eventAdmin; private List<ModemMonitorListener> listeners; private ExecutorService executor; private Map<String, CellularModem> modems; private Map<String, InterfaceState> interfaceStatuses; private NetworkConfiguration networkConfig; private boolean serviceActivated; private PppState pppState; private long resetTimerStart; public void setNetworkService(NetworkService networkService) { this.networkService = networkService; } public void unsetNetworkService(NetworkService networkService) { this.networkService = null; } public void setEventAdmin(EventAdmin eventAdmin) { this.eventAdmin = eventAdmin; } public void unsetEventAdmin(EventAdmin eventAdmin) { this.eventAdmin = null; } public void setNetworkConfigurationService(NetworkConfigurationService netConfigService) { this.netConfigService = netConfigService; } public void unsetNetworkConfigurationService(NetworkConfigurationService netConfigService) { this.netConfigService = null; } public void setSystemService(SystemService systemService) { this.systemService = systemService; } public void unsetSystemService(SystemService systemService) { this.systemService = null; } protected void activate(ComponentContext componentContext) { // save the bundle context this.ctx = componentContext; this.pppState = PppState.NOT_CONNECTED; this.resetTimerStart = 0L; Dictionary<String, String[]> d = new Hashtable<>(); d.put(EventConstants.EVENT_TOPIC, EVENT_TOPICS); this.ctx.getBundleContext().registerService(EventHandler.class.getName(), this, d); this.modems = new HashMap<>(); this.interfaceStatuses = new HashMap<>(); this.listeners = new ArrayList<>(); stopThread = new AtomicBoolean(); // must be initialized before trackModem() is called; risk of NPE otherwise this.executor = Executors.newSingleThreadExecutor(); // track currently installed modems try { this.networkConfig = this.netConfigService.getNetworkConfiguration(); for (NetInterface<? extends NetInterfaceAddress> netInterface : this.networkService .getNetworkInterfaces()) { if (netInterface instanceof ModemInterface) { ModemDevice modemDevice = ((ModemInterface<?>) netInterface).getModemDevice(); trackModem(modemDevice); } } } catch (Exception e) { logger.error("Error getting installed modems", e); } submitMonitorTask(); this.serviceActivated = true; logger.debug("ModemMonitor activated and ready to receive events"); } private Future<?> submitMonitorTask() { stopThread.set(false); // is task already prepared? if (task != null) { return task; } // is executor ready? if (this.executor == null) { return null; } task = this.executor.submit(new Runnable() { @Override public void run() { while (!stopThread.get()) { Thread.currentThread().setName("ModemMonitor"); try { monitor(); monitorWait(); } catch (InterruptedException interruptedException) { Thread.interrupted(); logger.debug("modem monitor interrupted", interruptedException); } catch (Throwable t) { logger.error("Exception while monitoring cellular connection", t); } } } }); return task; } protected void deactivate(ComponentContext componentContext) { this.listeners = null; PppFactory.releaseAllPppServices(); if (task != null && !task.isDone()) { stopThread.set(true); monitorNotity(); logger.debug("Cancelling ModemMonitor task ..."); task.cancel(true); logger.info("ModemMonitor task cancelled? = {}", task.isDone()); task = null; } if (this.executor != null) { logger.debug("Terminating ModemMonitor Thread ..."); this.executor.shutdownNow(); try { this.executor.awaitTermination(THREAD_TERMINATION_TOUT, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.warn("Interrupted", e); } logger.info("ModemMonitor Thread terminated? - {}", this.executor.isTerminated()); this.executor = null; } this.serviceActivated = false; this.networkConfig = null; } @Override public void handleEvent(Event event) { logger.debug("handleEvent - topic: {}", event.getTopic()); String topic = event.getTopic(); if (topic.equals(NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC)) { NetworkConfigurationChangeEvent netConfigChangedEvent = (NetworkConfigurationChangeEvent) event; String[] propNames = netConfigChangedEvent.getPropertyNames(); if (propNames != null && propNames.length > 0) { Map<String, Object> props = new HashMap<>(); for (String propName : propNames) { Object prop = netConfigChangedEvent.getProperty(propName); if (prop != null) { props.put(propName, prop); } } try { final NetworkConfiguration newNetworkConfig = new NetworkConfiguration(props); ExecutorService ex = Executors.newSingleThreadExecutor(); ex.submit(new Runnable() { @Override public void run() { processNetworkConfigurationChangeEvent(newNetworkConfig); } }); } catch (Exception e) { logger.error("Failed to handle the NetworkConfigurationChangeEvent - {}", e); } } } else if (topic.equals(ModemAddedEvent.MODEM_EVENT_ADDED_TOPIC)) { ModemAddedEvent modemAddedEvent = (ModemAddedEvent) event; final ModemDevice modemDevice = modemAddedEvent.getModemDevice(); if (this.serviceActivated) { ExecutorService ex = Executors.newSingleThreadExecutor(); ex.submit(new Runnable() { @Override public void run() { trackModem(modemDevice); } }); } } else if (topic.equals(ModemRemovedEvent.MODEM_EVENT_REMOVED_TOPIC)) { ModemRemovedEvent modemRemovedEvent = (ModemRemovedEvent) event; String usbPort = (String) modemRemovedEvent.getProperty(UsbDeviceEvent.USB_EVENT_USB_PORT_PROPERTY); this.modems.remove(usbPort); } } @Override public CellularModem getModemService(String usbPort) { return this.modems.get(usbPort); } @Override public Collection<CellularModem> getAllModemServices() { return this.modems.values(); } private NetInterfaceStatus getNetInterfaceStatus(List<NetConfig> netConfigs) { NetInterfaceStatus interfaceStatus = NetInterfaceStatus.netIPv4StatusUnknown; if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { interfaceStatus = ((NetConfigIP4) netConfig).getStatus(); break; } } } return interfaceStatus; } private void setNetInterfaceStatus(NetInterfaceStatus netInterfaceStatus, List<NetConfig> netConfigs) { if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { ((NetConfigIP4) netConfig).setStatus(netInterfaceStatus); break; } } } } @Override public void registerListener(ModemMonitorListener newListener) { boolean found = false; if (this.listeners == null) { this.listeners = new ArrayList<>(); } if (!this.listeners.isEmpty()) { for (ModemMonitorListener listener : this.listeners) { if (listener.equals(newListener)) { found = true; break; } } } if (!found) { this.listeners.add(newListener); } } @Override public void unregisterListener(ModemMonitorListener listenerToUnregister) { if (this.listeners != null && !this.listeners.isEmpty()) { for (int i = 0; i < this.listeners.size(); i++) { if (this.listeners.get(i).equals(listenerToUnregister)) { this.listeners.remove(i); } } } } private void processNetworkConfigurationChangeEvent(NetworkConfiguration newNetworkConfig) { synchronized (lock) { if (this.modems == null || this.modems.isEmpty()) { return; } for (Map.Entry<String, CellularModem> modemEntry : this.modems.entrySet()) { String usbPort = modemEntry.getKey(); CellularModem modem = modemEntry.getValue(); try { String ifaceName = null; if (this.networkService != null) { ifaceName = this.networkService.getModemPppPort(modem.getModemDevice()); } if (ifaceName != null) { List<NetConfig> oldNetConfigs = modem.getConfiguration(); NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = newNetworkConfig .getNetInterfaceConfig(ifaceName); if (netInterfaceConfig == null) { netInterfaceConfig = newNetworkConfig.getNetInterfaceConfig(usbPort); } List<NetConfig> newNetConfigs = null; IModemLinkService pppService = null; int ifaceNo = getInterfaceNumber(oldNetConfigs); if (ifaceNo >= 0) { pppService = PppFactory.obtainPppService(ifaceNo, modem.getDataPort()); } if (netInterfaceConfig != null) { newNetConfigs = getNetConfigs(netInterfaceConfig); } else { if (oldNetConfigs != null && pppService != null) { if (!ifaceName.equals(pppService.getIfaceName())) { StringBuilder key = new StringBuilder().append("net.interface.").append(ifaceName) .append(".config.ip4.status"); String statusString = KuranetConfig.getProperty(key.toString()); NetInterfaceStatus netInterfaceStatus = NetInterfaceStatus.netIPv4StatusDisabled; if (statusString != null && !statusString.isEmpty()) { netInterfaceStatus = NetInterfaceStatus.valueOf(statusString); } newNetConfigs = oldNetConfigs; oldNetConfigs = null; try { setInterfaceNumber(ifaceName, newNetConfigs); setNetInterfaceStatus(netInterfaceStatus, newNetConfigs); } catch (NumberFormatException e) { logger.error("failed to set new interface number - {}", e); } } } } if (oldNetConfigs == null || !isConfigsEqual(oldNetConfigs, newNetConfigs)) { logger.info("new configuration for cellular modem on usb port {} netinterface {}", usbPort, ifaceName); this.networkConfig = newNetworkConfig; if (pppService != null) { PppState pppState = pppService.getPppState(); if (pppState == PppState.CONNECTED || pppState == PppState.IN_PROGRESS) { logger.info("disconnecting " + pppService.getIfaceName()); pppService.disconnect(); } PppFactory.releasePppService(pppService.getIfaceName()); } if (modem.isGpsEnabled()) { if (!disableModemGps(modem)) { logger.error( "processNetworkConfigurationChangeEvent() :: Failed to disable modem GPS"); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } } modem.setConfiguration(newNetConfigs); if (modem instanceof EvdoCellularModem) { NetInterfaceStatus netIfaceStatus = getNetInterfaceStatus(newNetConfigs); if (netIfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) { if (!((EvdoCellularModem) modem).isProvisioned()) { logger.info( "NetworkConfigurationChangeEvent :: The {} is not provisioned, will try to provision it ...", modem.getModel()); if (task != null && !task.isCancelled()) { logger.info("NetworkConfigurationChangeEvent :: Cancelling monitor task"); stopThread.set(true); monitorNotity(); task.cancel(true); task = null; } ((EvdoCellularModem) modem).provision(); if (task == null) { logger.info("NetworkConfigurationChangeEvent :: Restarting monitor task"); submitMonitorTask(); } else { monitorNotity(); } } else { logger.info("NetworkConfigurationChangeEvent :: The " + modem.getModel() + " is provisioned"); } } if (modem.isGpsSupported()) { if (isGpsEnabledInConfig(newNetConfigs) && !modem.isGpsEnabled()) { modem.enableGps(); postModemGpsEvent(modem, true); } } } } } } catch (KuraException e) { logger.error("NetworkConfigurationChangeEvent :: Failed to process - {}", e); } } } } private boolean isConfigsEqual(List<NetConfig> oldConfig, List<NetConfig> newConfig) { if (oldConfig == null && newConfig == null || oldConfig == null && newConfig != null || oldConfig != null && newConfig == null) { return false; } boolean ret = false; ModemConfig oldModemConfig = getModemConfig(oldConfig); ModemConfig newModemConfig = getModemConfig(newConfig); NetConfigIP4 oldNetConfigIP4 = getNetConfigIp4(oldConfig); NetConfigIP4 newNetConfigIP4 = getNetConfigIp4(newConfig); if (oldNetConfigIP4.equals(newNetConfigIP4) && oldModemConfig.equals(newModemConfig)) { ret = true; } return ret; } private List<NetConfig> getNetConfigs(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) { List<NetConfig> netConfigs = null; if (netInterfaceConfig != null) { List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig .getNetInterfaceAddresses(); if (netInterfaceAddressConfigs != null && !netInterfaceAddressConfigs.isEmpty()) { for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { netConfigs = netInterfaceAddressConfig.getConfigs(); } } } return netConfigs; } private ModemConfig getModemConfig(List<NetConfig> netConfigs) { ModemConfig modemConfig = null; for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { modemConfig = (ModemConfig) netConfig; } } return modemConfig; } private NetConfigIP4 getNetConfigIp4(List<NetConfig> netConfigs) { NetConfigIP4 netConfigIP4 = null; for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { netConfigIP4 = (NetConfigIP4) netConfig; } } return netConfigIP4; } private int getInterfaceNumber(List<NetConfig> netConfigs) { int ifaceNo = -1; if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { ifaceNo = ((ModemConfig) netConfig).getPppNumber(); break; } } } return ifaceNo; } private int getInterfaceNumber(String ifaceName) { return Integer.parseInt(ifaceName.replaceAll("[^0-9]", "")); } private void setInterfaceNumber(String ifaceName, List<NetConfig> netConfigs) { if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { ((ModemConfig) netConfig).setPppNumber(getInterfaceNumber(ifaceName)); break; } } } } private long getModemResetTimeoutMsec(String ifaceName, List<NetConfig> netConfigs) { long resetToutMsec = 0L; if (ifaceName != null && netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { resetToutMsec = ((ModemConfig) netConfig).getResetTimeout() * 60000; break; } } } return resetToutMsec; } private boolean isGpsEnabledInConfig(List<NetConfig> netConfigs) { boolean isGpsEnabled = false; if (netConfigs != null && !netConfigs.isEmpty()) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { isGpsEnabled = ((ModemConfig) netConfig).isGpsEnabled(); break; } } } return isGpsEnabled; } private void monitor() { synchronized (lock) { HashMap<String, InterfaceState> newInterfaceStatuses = new HashMap<>(); if (this.modems == null || this.modems.isEmpty()) { return; } for (Map.Entry<String, CellularModem> modemEntry : this.modems.entrySet()) { CellularModem modem = modemEntry.getValue(); // get signal strength only if somebody needs it if (this.listeners != null && !this.listeners.isEmpty()) { for (ModemMonitorListener listener : this.listeners) { try { int rssi = modem.getSignalStrength(); listener.setCellularSignalLevel(rssi); } catch (KuraException e) { listener.setCellularSignalLevel(0); logger.error("monitor() :: Failed to obtain signal strength - {}", e); } } } IModemLinkService pppService = null; PppState pppState = null; NetInterfaceStatus netInterfaceStatus = getNetInterfaceStatus(modem.getConfiguration()); try { String ifaceName = this.networkService.getModemPppPort(modem.getModemDevice()); if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN && ifaceName != null) { pppService = PppFactory.obtainPppService(ifaceName, modem.getDataPort()); pppState = pppService.getPppState(); if (this.pppState != pppState) { logger.info("monitor() :: previous PppState={}", this.pppState); logger.info("monitor() :: current PppState={}", pppState); } if (pppState == PppState.NOT_CONNECTED) { boolean checkIfSimCardReady = false; List<ModemTechnologyType> modemTechnologyTypes = modem.getTechnologyTypes(); for (ModemTechnologyType modemTechnologyType : modemTechnologyTypes) { if (modemTechnologyType == ModemTechnologyType.GSM_GPRS || modemTechnologyType == ModemTechnologyType.UMTS || modemTechnologyType == ModemTechnologyType.HSDPA || modemTechnologyType == ModemTechnologyType.HSPA) { checkIfSimCardReady = true; break; } } if (checkIfSimCardReady) { if (((HspaCellularModem) modem).isSimCardReady()) { logger.info("monitor() :: !!! SIM CARD IS READY !!! connecting ..."); pppService.connect(); if (this.pppState == PppState.NOT_CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } } else { logger.warn("monitor() :: ! SIM CARD IS NOT READY !"); } } else { logger.info("monitor() :: connecting ..."); pppService.connect(); if (this.pppState == PppState.NOT_CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } } } else if (pppState == PppState.IN_PROGRESS) { long modemResetTout = getModemResetTimeoutMsec(ifaceName, modem.getConfiguration()); if (modemResetTout > 0) { long timeElapsed = System.currentTimeMillis() - this.resetTimerStart; if (timeElapsed > modemResetTout) { // reset modem logger.info("monitor() :: Modem Reset TIMEOUT !!!"); pppService.disconnect(); if (modem.isGpsEnabled() && !disableModemGps(modem)) { logger.error("monitor() :: Failed to disable modem GPS"); } modem.reset(); pppState = PppState.NOT_CONNECTED; this.resetTimerStart = System.currentTimeMillis(); } else { int timeTillReset = (int) (modemResetTout - timeElapsed) / 1000; logger.info( "monitor() :: PPP connection in progress. Modem will be reset in {} sec if not connected", timeTillReset); } } } else if (pppState == PppState.CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } this.pppState = pppState; ConnectionInfo connInfo = new ConnectionInfoImpl(ifaceName); InterfaceState interfaceState = new InterfaceState(ifaceName, LinuxNetworkUtil.hasAddress(ifaceName), pppState == PppState.CONNECTED, connInfo.getIpAddress()); newInterfaceStatuses.put(ifaceName, interfaceState); } if (modem.isGpsSupported()) { if (isGpsEnabledInConfig(modem.getConfiguration())) { if (modem instanceof HspaCellularModem) { if (!modem.isGpsEnabled()) { modem.enableGps(); } } postModemGpsEvent(modem, true); } } } catch (Exception e) { logger.error("monitor() :: Exception", e); if (pppService != null && pppState != null) { try { logger.info("monitor() :: Exception :: PPPD disconnect"); pppService.disconnect(); } catch (KuraException e1) { logger.error("monitor() :: Exception while disconnect", e1); } this.pppState = pppState; } if (modem.isGpsEnabled()) { try { if (!disableModemGps(modem)) { logger.error("monitor() :: Failed to disable modem GPS"); } } catch (KuraException e1) { logger.error("monitor() :: Exception disableModemGps", e1); } } try { logger.info("monitor() :: Exception :: modem reset"); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } catch (KuraException e1) { logger.error("monitor() :: Exception modem.reset", e1); } } } // post event for any status changes checkStatusChange(this.interfaceStatuses, newInterfaceStatuses); this.interfaceStatuses = newInterfaceStatuses; } } private void checkStatusChange(Map<String, InterfaceState> oldStatuses, Map<String, InterfaceState> newStatuses) { if (newStatuses != null) { // post NetworkStatusChangeEvent on current and new interfaces for (String interfaceName : newStatuses.keySet()) { if (oldStatuses != null && oldStatuses.containsKey(interfaceName)) { if (!newStatuses.get(interfaceName).equals(oldStatuses.get(interfaceName))) { logger.debug("Posting NetworkStatusChangeEvent on interface: {}", interfaceName); this.eventAdmin.postEvent( new NetworkStatusChangeEvent(interfaceName, newStatuses.get(interfaceName), null)); } } else { logger.debug("Posting NetworkStatusChangeEvent on enabled interface: {}", interfaceName); this.eventAdmin.postEvent( new NetworkStatusChangeEvent(interfaceName, newStatuses.get(interfaceName), null)); } } // post NetworkStatusChangeEvent on interfaces that are no longer there if (oldStatuses != null) { for (String interfaceName : oldStatuses.keySet()) { if (!newStatuses.containsKey(interfaceName)) { logger.debug("Posting NetworkStatusChangeEvent on disabled interface: {}", interfaceName); this.eventAdmin.postEvent( new NetworkStatusChangeEvent(interfaceName, oldStatuses.get(interfaceName), null)); } } } } } private void trackModem(ModemDevice modemDevice) { Class<? extends CellularModemFactory> modemFactoryClass = getModemFactoryClass(modemDevice); if (modemFactoryClass != null) { CellularModemFactory modemFactoryService = null; try { try { Method getInstanceMethod = modemFactoryClass.getDeclaredMethod("getInstance", (Class<?>[]) null); getInstanceMethod.setAccessible(true); modemFactoryService = (CellularModemFactory) getInstanceMethod.invoke(null, (Object[]) null); } catch (Exception e) { logger.error("Error calling getInstance() method on {}", modemFactoryClass.getName(), e); } // if unsuccessful in calling getInstance() if (modemFactoryService == null) { modemFactoryService = modemFactoryClass.newInstance(); } String platform = null; if (this.systemService != null) { platform = this.systemService.getPlatform(); } CellularModem modem = modemFactoryService.obtainCellularModemService(modemDevice, platform); try { HashMap<String, String> modemInfoMap = new HashMap<>(); modemInfoMap.put(ModemReadyEvent.IMEI, modem.getSerialNumber()); modemInfoMap.put(ModemReadyEvent.IMSI, modem.getMobileSubscriberIdentity()); modemInfoMap.put(ModemReadyEvent.ICCID, modem.getIntegratedCirquitCardId()); modemInfoMap.put(ModemReadyEvent.RSSI, Integer.toString(modem.getSignalStrength())); logger.info("posting ModemReadyEvent on topic {}", ModemReadyEvent.MODEM_EVENT_READY_TOPIC); this.eventAdmin.postEvent(new ModemReadyEvent(modemInfoMap)); } catch (Exception e) { logger.error("Failed to post the ModemReadyEvent", e); } String ifaceName = this.networkService.getModemPppPort(modemDevice); List<NetConfig> netConfigs = null; if (ifaceName != null) { NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = this.networkConfig .getNetInterfaceConfig(ifaceName); if (netInterfaceConfig == null) { this.networkConfig = this.netConfigService.getNetworkConfiguration(); netInterfaceConfig = this.networkConfig.getNetInterfaceConfig(ifaceName); } if (netInterfaceConfig != null) { netConfigs = getNetConfigs(netInterfaceConfig); if (netConfigs != null && !netConfigs.isEmpty()) { modem.setConfiguration(netConfigs); } } } if (modemDevice instanceof UsbModemDevice) { this.modems.put(((UsbModemDevice) modemDevice).getUsbPort(), modem); } else if (modemDevice instanceof SerialModemDevice) { this.modems.put(modemDevice.getProductName(), modem); } if (modem instanceof EvdoCellularModem) { NetInterfaceStatus netIfaceStatus = getNetInterfaceStatus(netConfigs); if (netIfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) { if (modem.isGpsEnabled()) { if (!disableModemGps(modem)) { logger.error("trackModem() :: Failed to disable modem GPS, resetting modem ..."); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } } if (!((EvdoCellularModem) modem).isProvisioned()) { logger.info("trackModem() :: The {} is not provisioned, will try to provision it ...", modem.getModel()); if (task != null && !task.isCancelled()) { logger.info("trackModem() :: Cancelling monitor task"); stopThread.set(true); monitorNotity(); task.cancel(true); task = null; } ((EvdoCellularModem) modem).provision(); if (task == null) { logger.info("trackModem() :: Restarting monitor task"); submitMonitorTask(); } else { monitorNotity(); } } else { logger.info("trackModem() :: The {} is provisioned", modem.getModel()); } } if (modem.isGpsSupported()) { if (isGpsEnabledInConfig(netConfigs) && !modem.isGpsEnabled()) { modem.enableGps(); postModemGpsEvent(modem, true); } } } } catch (Exception e) { logger.error("trackModem() :: {}", e.getMessage(), e); } } } protected Class<? extends CellularModemFactory> getModemFactoryClass(ModemDevice modemDevice) { Class<? extends CellularModemFactory> modemFactoryClass = null; if (modemDevice instanceof UsbModemDevice) { SupportedUsbModemInfo supportedUsbModemInfo = SupportedUsbModemsInfo.getModem((UsbModemDevice) modemDevice); UsbModemFactoryInfo usbModemFactoryInfo = SupportedUsbModemsFactoryInfo.getModem(supportedUsbModemInfo); modemFactoryClass = usbModemFactoryInfo.getModemFactoryClass(); } else if (modemDevice instanceof SerialModemDevice) { SupportedSerialModemInfo supportedSerialModemInfo = SupportedSerialModemsInfo.getModem(); SerialModemFactoryInfo serialModemFactoryInfo = SupportedSerialModemsFactoryInfo .getModem(supportedSerialModemInfo); modemFactoryClass = serialModemFactoryInfo.getModemFactoryClass(); } return modemFactoryClass; } private boolean disableModemGps(CellularModem modem) throws KuraException { postModemGpsEvent(modem, false); boolean portIsReachable = false; long startTimer = System.currentTimeMillis(); do { try { Thread.sleep(3000); if (modem.isPortReachable(modem.getAtPort())) { logger.debug("disableModemGps() modem is now reachable ..."); portIsReachable = true; break; } else { logger.debug("disableModemGps() waiting for PositionService to release serial port ..."); } } catch (Exception e) { logger.debug("disableModemGps() waiting for PositionService to release serial port: ex={}", e); } } while (System.currentTimeMillis() - startTimer < 20000L); modem.disableGps(); try { Thread.sleep(1000); } catch (InterruptedException e) { } boolean ret = false; if (portIsReachable && !modem.isGpsEnabled()) { logger.error("disableModemGps() :: Modem GPS is disabled :: portIsReachable={}, modem.isGpsEnabled()={}", portIsReachable, modem.isGpsEnabled()); ret = true; } return ret; } private void postModemGpsEvent(CellularModem modem, boolean enabled) throws KuraException { if (enabled) { CommURI commUri = modem.getSerialConnectionProperties(CellularModem.SerialPortType.GPSPORT); if (commUri != null) { logger.trace("postModemGpsEvent() :: Modem SeralConnectionProperties: {}", commUri.toString()); HashMap<String, Object> modemInfoMap = new HashMap<>(); modemInfoMap.put(ModemGpsEnabledEvent.Port, modem.getGpsPort()); modemInfoMap.put(ModemGpsEnabledEvent.BaudRate, Integer.valueOf(commUri.getBaudRate())); modemInfoMap.put(ModemGpsEnabledEvent.DataBits, Integer.valueOf(commUri.getDataBits())); modemInfoMap.put(ModemGpsEnabledEvent.StopBits, Integer.valueOf(commUri.getStopBits())); modemInfoMap.put(ModemGpsEnabledEvent.Parity, Integer.valueOf(commUri.getParity())); logger.debug("postModemGpsEvent() :: posting ModemGpsEnabledEvent on topic {}", ModemGpsEnabledEvent.MODEM_EVENT_GPS_ENABLED_TOPIC); this.eventAdmin.postEvent(new ModemGpsEnabledEvent(modemInfoMap)); } } else { logger.debug("postModemGpsEvent() :: posting ModemGpsDisableEvent on topic {}", ModemGpsDisabledEvent.MODEM_EVENT_GPS_DISABLED_TOPIC); HashMap<String, Object> modemInfoMap = new HashMap<>(); this.eventAdmin.postEvent(new ModemGpsDisabledEvent(modemInfoMap)); } } private void monitorNotity() { if (stopThread != null) { synchronized (stopThread) { stopThread.notifyAll(); } } } private void monitorWait() throws InterruptedException { if (stopThread != null) { synchronized (stopThread) { stopThread.wait(THREAD_INTERVAL); } } } }
Replaced 'new Runnable' with Lambda; fixed a few log messages. Signed-off-by: ibinshtok <c352e7adbda108f549a573171733f5c1cb00bc26@eurotech.com>
kura/org.eclipse.kura.net.admin/src/main/java/org/eclipse/kura/net/admin/monitor/ModemMonitorServiceImpl.java
Replaced 'new Runnable' with Lambda; fixed a few log messages.
Java
epl-1.0
c6bec4c97e9f250958d8054d3c3077b45d18de1a
0
eclipse/hawkbit,bsinno/hawkbit,eclipse/hawkbit,bsinno/hawkbit,eclipse/hawkbit,bsinno/hawkbit,eclipse/hawkbit
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.repository.jpa; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; import org.springframework.lang.Nullable; import org.springframework.stereotype.Repository; /** * Workaround as spring data does not provide a {@link Slice} based * {@link JpaRepository#findAll()}. * */ @Repository public class NoCountPagingRepository { @Autowired protected EntityManager em; /** * Searches without the need for an extra count query. * * @param spec * to search for * @param pageable * information * @param domainClass * of the {@link Entity} * * @return {@link Slice} of data * * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#findAll(org.springframework * .data.jpa.domain.Specification, * org.springframework.data.domain.Pageable) */ public <T, I extends Serializable> Slice<T> findAll(final Specification<T> spec, final Pageable pageable, final Class<T> domainClass) { final SimpleJpaNoCountRepository<T, I> noCountDao = new SimpleJpaNoCountRepository<>(domainClass, em); return noCountDao.findAll(spec, pageable); } /** * Searches without the need for an extra count query. * * @param pageable * information * @param domainClass * of the {@link Entity} * * @return {@link Slice} of data * * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#findAll(org.springframework * .data.jpa.domain.Specification, * org.springframework.data.domain.Pageable) */ public <T, I extends Serializable> Slice<T> findAll(final Pageable pageable, final Class<T> domainClass) { final SimpleJpaNoCountRepository<T, I> noCountDao = new SimpleJpaNoCountRepository<>(domainClass, em); return noCountDao.findAll(pageable); } /** * Repository implementation with disabled count query. * * * * @param <T> * entity type * @param <I> * key or ID type */ public static class SimpleJpaNoCountRepository<T, I extends Serializable> extends SimpleJpaRepository<T, I> { /** * Constructor. * * @param domainClass * of the {@link Entity} * @param em * {@link EntityManager} instance for the queries */ public SimpleJpaNoCountRepository(final Class<T> domainClass, final EntityManager em) { super(domainClass, em); } @Override protected <S extends T> Page<S> readPage(final TypedQuery<S> query, final Class<S> domainClass, final Pageable pageable, @Nullable final Specification<S> spec) { query.setFirstResult((int) pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); final List<S> content = query.getResultList(); return new PageImpl<>(content, pageable, content.size()); } } }
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/NoCountPagingRepository.java
/** * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.hawkbit.repository.jpa; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; import org.springframework.stereotype.Repository; /** * Workaround as spring data does not provide a {@link Slice} based * {@link JpaRepository#findAll()}. * */ @Repository public class NoCountPagingRepository { @Autowired protected EntityManager em; /** * Searches without the need for an extra count query. * * @param spec * to search for * @param pageable * information * @param domainClass * of the {@link Entity} * * @return {@link Slice} of data * * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#findAll(org.springframework * .data.jpa.domain.Specification, * org.springframework.data.domain.Pageable) */ public <T, I extends Serializable> Slice<T> findAll(final Specification<T> spec, final Pageable pageable, final Class<T> domainClass) { final SimpleJpaNoCountRepository<T, I> noCountDao = new SimpleJpaNoCountRepository<>(domainClass, em); return noCountDao.findAll(spec, pageable); } /** * Searches without the need for an extra count query. * * @param pageable * information * @param domainClass * of the {@link Entity} * * @return {@link Slice} of data * * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#findAll(org.springframework * .data.jpa.domain.Specification, * org.springframework.data.domain.Pageable) */ public <T, I extends Serializable> Slice<T> findAll(final Pageable pageable, final Class<T> domainClass) { final SimpleJpaNoCountRepository<T, I> noCountDao = new SimpleJpaNoCountRepository<>(domainClass, em); return noCountDao.findAll(pageable); } /** * Repository implementation with disabled count query. * * * * @param <T> * entity type * @param <I> * key or ID type */ public static class SimpleJpaNoCountRepository<T, I extends Serializable> extends SimpleJpaRepository<T, I> { /** * Constructor. * * @param domainClass * of the {@link Entity} * @param em * {@link EntityManager} instance for the queries */ public SimpleJpaNoCountRepository(final Class<T> domainClass, final EntityManager em) { super(domainClass, em); } @Override protected Page<T> readPage(final TypedQuery<T> query, final Pageable pageable, final Specification<T> spec) { query.setFirstResult((int) pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); final List<T> content = query.getResultList(); return new PageImpl<>(content, pageable, content.size()); } } }
fixed overriding deprecated method on no count repository (#1032) Signed-off-by: Bogdan Bondar <2ecb6e90714a7bed706e5861ae196b21c1d5ffd5@bosch.io>
hawkbit-repository/hawkbit-repository-jpa/src/main/java/org/eclipse/hawkbit/repository/jpa/NoCountPagingRepository.java
fixed overriding deprecated method on no count repository (#1032)
Java
mpl-2.0
27e7e9d396bffb0581a7a9e1ab95f44000fc743f
0
joansmith/RoyalCommands,RoyalDev/RoyalCommands
package org.royaldev.royalcommands.rcommands; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.royaldev.royalcommands.PConfManager; import org.royaldev.royalcommands.RUtils; import org.royaldev.royalcommands.RoyalCommands; public class Reply implements CommandExecutor { RoyalCommands plugin; public Reply(RoyalCommands plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("reply")) { if (!plugin.isAuthorized(cs, "rcmds.reply")) { RUtils.dispNoPerms(cs); return true; } if (args.length < 1) { cs.sendMessage(cmd.getDescription()); return false; } if (Message.replydb.containsKey(cs)) { CommandSender t = Message.replydb.get(cs); if (!Message.replydb.containsKey(t)) { Message.replydb.put(t, cs); } else if (Message.replydb.containsKey(t)) { if (Message.replydb.get(t) != cs) { Message.replydb.remove(t); Message.replydb.put(t, cs); } } if ((t instanceof Player) && !((Player) t).isOnline()) { cs.sendMessage(ChatColor.RED + "That player is offline!"); return true; } String m = plugin.getFinalArg(args, 0).trim(); cs.sendMessage(ChatColor.GRAY + "[" + ChatColor.BLUE + "You" + ChatColor.GRAY + " -> " + ChatColor.BLUE + t.getName() + ChatColor.GRAY + "] " + m); t.sendMessage(ChatColor.GRAY + "[" + ChatColor.BLUE + cs.getName() + ChatColor.GRAY + " -> " + ChatColor.BLUE + "You" + ChatColor.GRAY + "] " + m); Player[] ps = plugin.getServer().getOnlinePlayers(); for (Player p1 : ps) { if (PConfManager.getPValBoolean(p1, "spy")) { if (t == p1 || cs == p1) { continue; } p1.sendMessage(ChatColor.GRAY + "[" + ChatColor.BLUE + cs.getName() + ChatColor.GRAY + " -> " + ChatColor.BLUE + t.getName() + ChatColor.GRAY + "] " + m); } } return true; } else { cs.sendMessage(ChatColor.RED + "You have no one to reply to!"); return true; } } return false; } }
src/org/royaldev/royalcommands/rcommands/Reply.java
package org.royaldev.royalcommands.rcommands; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.royaldev.royalcommands.PConfManager; import org.royaldev.royalcommands.RUtils; import org.royaldev.royalcommands.RoyalCommands; public class Reply implements CommandExecutor { RoyalCommands plugin; public Reply(RoyalCommands plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("reply")) { if (!plugin.isAuthorized(cs, "rcmds.reply")) { RUtils.dispNoPerms(cs); return true; } if (args.length < 1) { cs.sendMessage(cmd.getDescription()); return false; } if (Message.replydb.containsKey(cs)) { CommandSender t = Message.replydb.get(cs); if (!Message.replydb.containsKey(t)) { Message.replydb.put(t, cs); } else if (Message.replydb.containsKey(t)) { if (Message.replydb.get(t) != cs) { Message.replydb.remove(t); Message.replydb.put(t, cs); } } String m = plugin.getFinalArg(args, 0).trim(); cs.sendMessage(ChatColor.GRAY + "[" + ChatColor.BLUE + "You" + ChatColor.GRAY + " -> " + ChatColor.BLUE + t.getName() + ChatColor.GRAY + "] " + m); t.sendMessage(ChatColor.GRAY + "[" + ChatColor.BLUE + cs.getName() + ChatColor.GRAY + " -> " + ChatColor.BLUE + "You" + ChatColor.GRAY + "] " + m); Player[] ps = plugin.getServer().getOnlinePlayers(); for (Player p1 : ps) { if (PConfManager.getPValBoolean(p1, "spy")) { if (t == p1 || cs == p1) { continue; } p1.sendMessage(ChatColor.GRAY + "[" + ChatColor.BLUE + cs.getName() + ChatColor.GRAY + " -> " + ChatColor.BLUE + t.getName() + ChatColor.GRAY + "] " + m); } } return true; } else { cs.sendMessage(ChatColor.RED + "You have no one to reply to!"); return true; } } return false; } }
Fixed: Reply fixed with offline players
src/org/royaldev/royalcommands/rcommands/Reply.java
Fixed: Reply fixed with offline players
Java
agpl-3.0
39168246a36cca30d36930055f2b3d54a9d4cd4f
0
n1zea144/cbioportal,sheridancbio/cbioportal,shrumit/cbioportal-gsoc-final,pughlab/cbioportal,pughlab/cbioportal,jjgao/cbioportal,bengusty/cbioportal,pughlab/cbioportal,fcriscuo/cbioportal,pughlab/cbioportal,zhx828/cbioportal,kalletlak/cbioportal,zhx828/cbioportal,kalletlak/cbioportal,bengusty/cbioportal,n1zea144/cbioportal,leedonghn4/cbio-portal-webgl,cBioPortal/cbioportal,cBioPortal/cbioportal,gsun83/cbioportal,inodb/cbioportal,onursumer/cbioportal,jjgao/cbioportal,d3b-center/pedcbioportal,leedonghn4/cbio-portal-webgl,mandawilson/cbioportal,inodb/cbioportal,onursumer/cbioportal,angelicaochoa/cbioportal,angelicaochoa/cbioportal,angelicaochoa/cbioportal,bengusty/cbioportal,IntersectAustralia/cbioportal,IntersectAustralia/cbioportal,zheins/cbioportal,inodb/cbioportal,HectorWon/cbioportal,j-hudecek/cbioportal,shrumit/cbioportal-gsoc-final,yichaoS/cbioportal,IntersectAustralia/cbioportal,jjgao/cbioportal,cBioPortal/cbioportal,gsun83/cbioportal,mandawilson/cbioportal,bihealth/cbioportal,fcriscuo/cbioportal,j-hudecek/cbioportal,angelicaochoa/cbioportal,istemi-bahceci/cbioportal,cBioPortal/cbioportal,d3b-center/pedcbioportal,xmao/cbioportal,fcriscuo/cbioportal,zhx828/cbioportal,leedonghn4/cbioportal,n1zea144/cbioportal,jjgao/cbioportal,kalletlak/cbioportal,zheins/cbioportal,xmao/cbioportal,angelicaochoa/cbioportal,HectorWon/cbioportal,jjgao/cbioportal,adamabeshouse/cbioportal,mandawilson/cbioportal,n1zea144/cbioportal,holtgrewe/cbioportal,d3b-center/pedcbioportal,angelicaochoa/cbioportal,jjgao/cbioportal,mandawilson/cbioportal,istemi-bahceci/cbioportal,inodb/cbioportal,yichaoS/cbioportal,yichaoS/cbioportal,shrumit/cbioportal-gsoc-final,holtgrewe/cbioportal,zheins/cbioportal,n1zea144/cbioportal,bihealth/cbioportal,cBioPortal/cbioportal,xmao/cbioportal,bihealth/cbioportal,leedonghn4/cbioportal,xmao/cbioportal,jjgao/cbioportal,leedonghn4/cbio-portal-webgl,zhx828/cbioportal,sheridancbio/cbioportal,gsun83/cbioportal,istemi-bahceci/cbioportal,zhx828/cbioportal,leedonghn4/cbio-portal-webgl,bengusty/cbioportal,HectorWon/cbioportal,bengusty/cbioportal,fcriscuo/cbioportal,HectorWon/cbioportal,onursumer/cbioportal,IntersectAustralia/cbioportal,mandawilson/cbioportal,istemi-bahceci/cbioportal,j-hudecek/cbioportal,holtgrewe/cbioportal,cBioPortal/cbioportal,onursumer/cbioportal,yichaoS/cbioportal,kalletlak/cbioportal,gsun83/cbioportal,HectorWon/cbioportal,gsun83/cbioportal,leedonghn4/cbioportal,leedonghn4/cbioportal,j-hudecek/cbioportal,d3b-center/pedcbioportal,zhx828/cbioportal,kalletlak/cbioportal,angelicaochoa/cbioportal,sheridancbio/cbioportal,j-hudecek/cbioportal,IntersectAustralia/cbioportal,zheins/cbioportal,d3b-center/pedcbioportal,bihealth/cbioportal,istemi-bahceci/cbioportal,bengusty/cbioportal,fcriscuo/cbioportal,j-hudecek/cbioportal,inodb/cbioportal,adamabeshouse/cbioportal,holtgrewe/cbioportal,zhx828/cbioportal,adamabeshouse/cbioportal,shrumit/cbioportal-gsoc-final,adamabeshouse/cbioportal,xmao/cbioportal,leedonghn4/cbioportal,adamabeshouse/cbioportal,shrumit/cbioportal-gsoc-final,leedonghn4/cbioportal,n1zea144/cbioportal,IntersectAustralia/cbioportal,shrumit/cbioportal-gsoc-final,yichaoS/cbioportal,adamabeshouse/cbioportal,mandawilson/cbioportal,kalletlak/cbioportal,gsun83/cbioportal,IntersectAustralia/cbioportal,fcriscuo/cbioportal,onursumer/cbioportal,bihealth/cbioportal,adamabeshouse/cbioportal,gsun83/cbioportal,sheridancbio/cbioportal,pughlab/cbioportal,sheridancbio/cbioportal,leedonghn4/cbio-portal-webgl,onursumer/cbioportal,sheridancbio/cbioportal,zheins/cbioportal,pughlab/cbioportal,holtgrewe/cbioportal,yichaoS/cbioportal,leedonghn4/cbio-portal-webgl,n1zea144/cbioportal,kalletlak/cbioportal,bihealth/cbioportal,inodb/cbioportal,d3b-center/pedcbioportal,yichaoS/cbioportal,shrumit/cbioportal-gsoc-final,inodb/cbioportal,pughlab/cbioportal,mandawilson/cbioportal,d3b-center/pedcbioportal,bihealth/cbioportal,zheins/cbioportal,holtgrewe/cbioportal,istemi-bahceci/cbioportal,HectorWon/cbioportal,xmao/cbioportal
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.mskcc.cbio.portal.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mskcc.cbio.cgds.dao.DaoException; import org.mskcc.cbio.cgds.model.CancerStudy; import org.mskcc.cbio.cgds.util.AccessControl; import org.mskcc.cbio.cgds.web_api.ProtocolException; import org.mskcc.cbio.portal.util.SkinUtil; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.json.simple.JSONArray; import org.json.simple.JSONValue; import org.mskcc.cbio.cgds.dao.DaoCase; import org.mskcc.cbio.cgds.dao.DaoCaseProfile; import org.mskcc.cbio.cgds.dao.DaoCopyNumberSegment; import org.mskcc.cbio.cgds.dao.DaoMutationEvent; import org.mskcc.cbio.cgds.model.GeneticProfile; /** * * @author jgao */ public class TumorMapServlet extends HttpServlet { // ref to our access control object private static AccessControl accessControl = null; /** * Initializes the AccessControl member. */ private static synchronized AccessControl getaccessControl() { if (accessControl==null) {ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext-security.xml"); accessControl = (AccessControl)context.getBean("accessControl"); } return accessControl; } public static final String CMD = "cmd"; public static final String GET_STUDY_STATISTICS_CMD = "statistics"; public static final String GET_STUDY_STATISTICS_TYPE = "type"; /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cmd = request.getParameter(CMD); if (null!=cmd) { if (cmd.equalsIgnoreCase(GET_STUDY_STATISTICS_CMD)) { String type = request.getParameter(GET_STUDY_STATISTICS_TYPE); processRequestStatistics(request, response, type); return; } } processRequestDefault(request, response); } private void processRequestDefault(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(QueryBuilder.HTML_TITLE, SkinUtil.getTumorMapTitle()); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/tumormap/tumormap.jsp"); dispatcher.forward(request, response); } private void processRequestStatistics(HttpServletRequest request, HttpServletResponse response, String type) throws ServletException, IOException { try { boolean includeMut = "mut".equalsIgnoreCase(type); boolean includeCna = "cna".equalsIgnoreCase(type); Map<String,Map<String,Object>> data = new HashMap<String,Map<String,Object>>(); // get list of cancer studies List<CancerStudy> cancerStudies = getaccessControl().getCancerStudies(); for (CancerStudy cancerStudy : cancerStudies) { if (cancerStudy.getCancerStudyStableId().equalsIgnoreCase("all")) { continue; } Map<String,Object> row = new HashMap<String,Object>(); data.put(cancerStudy.getCancerStudyStableId(),row); if (!includeMut&&!includeMut) { row.put("name",cancerStudy.getName()); row.put("ref",null); row.put("cases",DaoCase.countCases(cancerStudy.getInternalId())); } if (includeMut) { GeneticProfile mutProfile = cancerStudy.getMutationProfile(); if (mutProfile==null) { row.put("mut",0); } else { int mutEvents = DaoMutationEvent.countMutationEvents(mutProfile.getGeneticProfileId()); int samplesWithMut = DaoCaseProfile.countCasesInProfile(mutProfile.getGeneticProfileId()); row.put("mut",1.0*mutEvents/samplesWithMut); } } if (includeCna) { GeneticProfile cnaProfile = cancerStudy.getCopyNumberAlterationProfile(false); if (cnaProfile==null) { row.put("cna",0); } else { List<String> cases = DaoCaseProfile.getAllCaseIdsInProfile(cnaProfile.getGeneticProfileId()); Map<String,Double> fracs = DaoCopyNumberSegment.getCopyNumberActeredFraction(cases, SkinUtil.getPatientViewGenomicOverviewCnaCutoff()[0]); double aveFrac = 0; for (double frac : fracs.values()) { aveFrac += frac; } aveFrac /= cases.size(); row.put("cna",aveFrac); } } } response.setContentType("application/json"); PrintWriter out = response.getWriter(); try { JSONValue.writeJSONString(data, out); } finally { out.close(); } } catch (DaoException ex) { throw new ServletException(ex); } catch (ProtocolException ex) { throw new ServletException(ex); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
portal/src/main/java/org/mskcc/cbio/portal/servlet/TumorMapServlet.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.mskcc.cbio.portal.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mskcc.cbio.cgds.dao.DaoException; import org.mskcc.cbio.cgds.model.CancerStudy; import org.mskcc.cbio.cgds.util.AccessControl; import org.mskcc.cbio.cgds.web_api.ProtocolException; import org.mskcc.cbio.portal.util.SkinUtil; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.json.simple.JSONArray; import org.json.simple.JSONValue; import org.mskcc.cbio.cgds.dao.DaoCase; import org.mskcc.cbio.cgds.dao.DaoCaseProfile; import org.mskcc.cbio.cgds.dao.DaoCopyNumberSegment; import org.mskcc.cbio.cgds.dao.DaoMutationEvent; import org.mskcc.cbio.cgds.model.GeneticProfile; /** * * @author jgao */ public class TumorMapServlet extends HttpServlet { // ref to our access control object private static AccessControl accessControl = null; /** * Initializes the AccessControl member. */ private static synchronized AccessControl getaccessControl() { if (accessControl==null) {ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext-security.xml"); accessControl = (AccessControl)context.getBean("accessControl"); } return accessControl; } public static final String CMD = "cmd"; public static final String GET_STUDY_STATISTICS_CMD = "statistics"; public static final String GET_STUDY_STATISTICS_TYPE = "type"; /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cmd = request.getParameter(CMD); if (null!=cmd) { if (cmd.equalsIgnoreCase(GET_STUDY_STATISTICS_CMD)) { String type = request.getParameter(GET_STUDY_STATISTICS_TYPE); processRequestStatistics(request, response, type); return; } } processRequestDefault(request, response); } private void processRequestDefault(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(QueryBuilder.HTML_TITLE, SkinUtil.getTumorMapTitle()); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/tumormap/tumormap.jsp"); dispatcher.forward(request, response); } private void processRequestStatistics(HttpServletRequest request, HttpServletResponse response, String type) throws ServletException, IOException { try { boolean includeMut = "mut".equalsIgnoreCase(type); boolean includeCna = "cna".equalsIgnoreCase(type); Map<String,Map<String,Object>> data = new HashMap<String,Map<String,Object>>(); // get list of cancer studies List<CancerStudy> cancerStudies = getaccessControl().getCancerStudies(); for (CancerStudy cancerStudy : cancerStudies) { if (cancerStudy.getCancerStudyStableId().equalsIgnoreCase("all")) { continue; } Map<String,Object> row = new HashMap<String,Object>(); data.put(cancerStudy.getCancerStudyStableId(),row); if (!includeMut&&!includeMut) { row.put("name",cancerStudy.getName()); row.put("ref",null); row.put("cases",DaoCase.countCases(cancerStudy.getInternalId())); } if (includeMut) { GeneticProfile mutProfile = cancerStudy.getMutationProfile(); if (mutProfile==null) { row.put("mut",0); } else { int mutEvents = DaoMutationEvent.countMutationEvents(mutProfile.getGeneticProfileId()); int samplesWithMut = DaoCaseProfile.countCasesInProfile(mutProfile.getGeneticProfileId()); row.put("mut",1.0*mutEvents/samplesWithMut); } } if (includeCna) { GeneticProfile cnaProfile = cancerStudy.getCopyNumberAlterationProfile(false); if (cnaProfile==null) { row.put("cna",0); } else { List<String> cases = DaoCaseProfile.getAllCaseIdsInProfile(cnaProfile.getCancerStudyId()); Map<String,Double> fracs = DaoCopyNumberSegment.getCopyNumberActeredFraction(cases, SkinUtil.getPatientViewGenomicOverviewCnaCutoff()[0]); double aveFrac = 0; for (double frac : fracs.values()) { aveFrac += frac; } aveFrac /= cases.size(); row.put("cna",aveFrac); } } } response.setContentType("application/json"); PrintWriter out = response.getWriter(); try { JSONValue.writeJSONString(data, out); } finally { out.close(); } } catch (DaoException ex) { throw new ServletException(ex); } catch (ProtocolException ex) { throw new ServletException(ex); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
tumormap: fixed wrong copy number frac issue
portal/src/main/java/org/mskcc/cbio/portal/servlet/TumorMapServlet.java
tumormap: fixed wrong copy number frac issue
Java
lgpl-2.1
96cd9c7c9eeaff8620490432577360efae039d8c
0
BEAST2-Dev/bModelTest,BEAST2-Dev/bModelTest,BEAST2-Dev/bModelTest
package beast.evolution.substitutionmodel; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import beast.core.Description; import beast.core.Function; import beast.core.Input; import beast.core.Loggable; import beast.core.Input.Validate; import beast.core.parameter.IntegerParameter; import beast.evolution.datatype.DataType; import beast.evolution.datatype.Nucleotide; import beast.evolution.substitutionmodel.GeneralSubstitutionModel; @Description("Reversible jump based substitution model that can jump between all " + "reversible nucleotide substitution models") public class NucleotideRevJumpSubstModel extends GeneralSubstitutionModel implements Loggable { public enum ModelSet {allreversible, transitionTransversionSplit, namedSimple, namedExtended, namedExtended2}; public Input<ModelSet> modelChoiseInput = new Input<ModelSet>("modelSet", "Which set of models to choose, one of " + Arrays.toString(ModelSet.values()), ModelSet.transitionTransversionSplit, ModelSet.values()); public Input<IntegerParameter> modelIndicatorInput = new Input<IntegerParameter>("modelIndicator", "number of the model to be used", Validate.REQUIRED); // public NucleotideRevJumpSubstModel() throws Exception { // Frequencies frequencies = new Frequencies(); // frequencies.initByName("frequencies", "0.25 0.25 0.25 0.25"); // // initByName("rates", new RealParameter("1.0 1.0 1.0 1.0 1.0 1.0"), // "modelIndicator", new IntegerParameter("0"), // "frequencies", frequencies // ); // } /** sorted list of model indicators we jump between**/ public static int [][] MODELS = new int[][]{ {0,0,0,0,0,0}, // Jukes Cantor F81 /* M1 */ {0,0,0,0,0,1}, /* M7 */ {0,0,0,0,1,0}, /* M6 */ {0,0,0,0,1,1}, /* M22 */ {0,0,0,0,1,2}, /* M47 */ {0,0,0,1,0,0}, /* M5 */ {0,0,0,1,0,1}, /* M21 */ {0,0,0,1,0,2}, /* M46 */ {0,0,0,1,1,0}, /* M20 */ {0,0,0,1,1,1}, /* M23 */ {0,0,0,1,1,2}, /* M107 */ {0,0,0,1,2,0}, /* M45 */ {0,0,0,1,2,1}, /* M106 */ {0,0,0,1,2,2}, /* M105 */ {0,0,0,1,2,3}, /* M142 */ {0,0,1,0,0,0}, /* M4 */ {0,0,1,0,0,1}, /* M19 */ {0,0,1,0,0,2}, /* M44 */ {0,0,1,0,1,0}, /* M18 */ {0,0,1,0,1,1}, /* M24 */ {0,0,1,0,1,2}, /* M104 */ {0,0,1,0,2,0}, /* M43 */ {0,0,1,0,2,1}, /* M103 */ {0,0,1,0,2,2}, /* M98 */ {0,0,1,0,2,3}, /* M141 */ {0,0,1,1,0,0}, /* M17 */ {0,0,1,1,0,1}, /* M25 */ {0,0,1,1,0,2}, /* M102 */ {0,0,1,1,1,0}, /* M26 */ {0,0,1,1,1,1}, /* M8 */ {0,0,1,1,1,2}, /* M65 */ {0,0,1,1,2,0}, /* M101 */ {0,0,1,1,2,1}, /* M64 */ {0,0,1,1,2,2}, /* M108 */ {0,0,1,1,2,3}, /* M175 */ {0,0,1,2,0,0}, /* M42 */ {0,0,1,2,0,1}, /* M100 */ {0,0,1,2,0,2}, /* M97 */ {0,0,1,2,0,3}, /* M140 */ {0,0,1,2,1,0}, /* M99 */ {0,0,1,2,1,1}, /* M63 */ {0,0,1,2,1,2}, /* M109 */ {0,0,1,2,1,3}, /* M174 */ {0,0,1,2,2,0}, /* M96 */ {0,0,1,2,2,1}, /* M110 */ {0,0,1,2,2,2}, /* M62 */ {0,0,1,2,2,3}, /* M172 */ {0,0,1,2,3,0}, /* M139 */ {0,0,1,2,3,1}, /* M173 */ {0,0,1,2,3,2}, /* M171 */ {0,0,1,2,3,3}, /* M170 */ {0,0,1,2,3,4}, /* M202 */ {0,1,0,0,0,0}, /* M3 */ {0,1,0,0,0,1}, /* M16 */ {0,1,0,0,0,2}, /* M41 */ {0,1,0,0,1,0}, // HKY F84 /* M15 */ {0,1,0,0,1,1}, /* M27 */ {0,1,0,0,1,2}, /* M95 */ {0,1,0,0,2,0}, // TN93 /* M40 */ {0,1,0,0,2,1}, /* M94 */ {0,1,0,0,2,2}, /* M83 */ {0,1,0,0,2,3}, /* M138 */ {0,1,0,1,0,0}, /* M14 */ {0,1,0,1,0,1}, /* M28 */ {0,1,0,1,0,2}, /* M93 */ {0,1,0,1,1,0}, /* M29 */ {0,1,0,1,1,1}, /* M9 */ {0,1,0,1,1,2}, /* M71 */ {0,1,0,1,2,0}, /* M92 */ {0,1,0,1,2,1}, /* M70 */ {0,1,0,1,2,2}, /* M111 */ {0,1,0,1,2,3}, /* M184 */ {0,1,0,2,0,0}, /* M39 */ {0,1,0,2,0,1}, /* M91 */ {0,1,0,2,0,2}, /* M82 */ {0,1,0,2,0,3}, /* M137 */ {0,1,0,2,1,0}, /* M90 */ {0,1,0,2,1,1}, /* M69 */ {0,1,0,2,1,2}, /* M112 */ {0,1,0,2,1,3}, /* M183 */ {0,1,0,2,2,0}, /* M81 */ {0,1,0,2,2,1}, /* M113 */ {0,1,0,2,2,2}, /* M58 */ {0,1,0,2,2,3}, /* M163 */ {0,1,0,2,3,0}, /* M136 */ {0,1,0,2,3,1}, /* M182 */ {0,1,0,2,3,2}, /* M162 */ {0,1,0,2,3,3}, /* M161 */ {0,1,0,2,3,4}, /* M201 */ {0,1,1,0,0,0}, /* M13 */ {0,1,1,0,0,1}, /* M30 */ {0,1,1,0,0,2}, /* M89 */ {0,1,1,0,1,0}, /* M31 */ {0,1,1,0,1,1}, /* M10 */ {0,1,1,0,1,2}, /* M75 */ {0,1,1,0,2,0}, /* M88 */ {0,1,1,0,2,1}, /* M74 */ {0,1,1,0,2,2}, /* M114 */ {0,1,1,0,2,3}, /* M187 */ {0,1,1,1,0,0}, /* M32 */ {0,1,1,1,0,1}, /* M11 */ {0,1,1,1,0,2}, /* M77 */ {0,1,1,1,1,0}, /* M12 */ {0,1,1,1,1,1}, /* M2 */ {0,1,1,1,1,2}, /* M37 */ {0,1,1,1,2,0}, /* M76 */ {0,1,1,1,2,1}, /* M36 */ {0,1,1,1,2,2}, /* M57 */ {0,1,1,1,2,3}, /* M132 */ {0,1,1,2,0,0}, /* M87 */ {0,1,1,2,0,1}, /* M72 */ {0,1,1,2,0,2}, /* M115 */ {0,1,1,2,0,3}, /* M186 */ {0,1,1,2,1,0}, /* M73 */ {0,1,1,2,1,1}, /* M35 */ {0,1,1,2,1,2}, /* M56 */ {0,1,1,2,1,3}, /* M131 */ {0,1,1,2,2,0}, /* M116 */ {0,1,1,2,2,1}, /* M55 */ {0,1,1,2,2,2}, /* M48 */ {0,1,1,2,2,3}, /* M151 */ {0,1,1,2,3,0}, /* M185 */ {0,1,1,2,3,1}, /* M130 */ {0,1,1,2,3,2}, /* M150 */ {0,1,1,2,3,3}, /* M149 */ {0,1,1,2,3,4}, /* M197 */ {0,1,2,0,0,0}, /* M38 */ {0,1,2,0,0,1}, /* M86 */ {0,1,2,0,0,2}, /* M80 */ {0,1,2,0,0,3}, /* M135 */ {0,1,2,0,1,0}, /* M85 */ {0,1,2,0,1,1}, /* M66 */ {0,1,2,0,1,2}, /* M117 */ {0,1,2,0,1,3}, /* M179 */ {0,1,2,0,2,0}, /* M79 */ {0,1,2,0,2,1}, /* M118 */ {0,1,2,0,2,2}, /* M59 */ {0,1,2,0,2,3}, /* M167 */ {0,1,2,0,3,0}, /* M134 */ {0,1,2,0,3,1}, /* M178 */ {0,1,2,0,3,2}, /* M166 */ {0,1,2,0,3,3}, /* M158 */ {0,1,2,0,3,4}, /* M200 */ {0,1,2,1,0,0}, /* M84 */ {0,1,2,1,0,1}, /* M67 */ {0,1,2,1,0,2}, /* M119 */ {0,1,2,1,0,3}, /* M181 */ {0,1,2,1,1,0}, /* M68 */ {0,1,2,1,1,1}, /* M34 */ {0,1,2,1,1,2}, /* M54 */ {0,1,2,1,1,3}, /* M129 */ {0,1,2,1,2,0}, /* M120 */ {0,1,2,1,2,1}, /* M53 */ {0,1,2,1,2,2}, /* M49 */ {0,1,2,1,2,3}, /* M155 */ {0,1,2,1,3,0}, /* M180 */ {0,1,2,1,3,1}, /* M128 */ {0,1,2,1,3,2}, /* M154 */ {0,1,2,1,3,3}, /* M146 */ {0,1,2,1,3,4}, /* M196 */ {0,1,2,2,0,0}, /* M78 */ {0,1,2,2,0,1}, /* M121 */ {0,1,2,2,0,2}, /* M60 */ {0,1,2,2,0,3}, /* M169 */ {0,1,2,2,1,0}, // Kimura 81 /* M122 */ {0,1,2,2,1,1}, /* M52 */ {0,1,2,2,1,2}, /* M50 */ {0,1,2,2,1,3}, /* M157 */ {0,1,2,2,2,0}, /* M61 */ {0,1,2,2,2,1}, /* M51 */ {0,1,2,2,2,2}, /* M33 */ {0,1,2,2,2,3}, /* M126 */ {0,1,2,2,3,0}, // Posada 03 /* M168 */ {0,1,2,2,3,1}, /* M156 */ {0,1,2,2,3,2}, /* M125 */ {0,1,2,2,3,3}, /* M143 */ {0,1,2,2,3,4}, /* M193 TVM */ {0,1,2,3,0,0}, /* M133 */ {0,1,2,3,0,1}, /* M176 */ {0,1,2,3,0,2}, /* M164 */ {0,1,2,3,0,3}, /* M159 */ {0,1,2,3,0,4}, /* M199 */ {0,1,2,3,1,0}, /* M177 */ {0,1,2,3,1,1}, /* M127 */ {0,1,2,3,1,2}, /* M152 */ {0,1,2,3,1,3}, /* M147 */ {0,1,2,3,1,4}, // Posada 03 /* M195 */ {0,1,2,3,2,0}, /* M165 */ {0,1,2,3,2,1}, /* M153 */ {0,1,2,3,2,2}, /* M124 */ {0,1,2,3,2,3}, /* M144 */ {0,1,2,3,2,4}, /* M192 */ {0,1,2,3,3,0}, /* M160 */ {0,1,2,3,3,1}, /* M148 */ {0,1,2,3,3,2}, /* M145 */ {0,1,2,3,3,3}, /* M123 */ {0,1,2,3,3,4}, /* M190 */ {0,1,2,3,4,0}, /* M198 */ {0,1,2,3,4,1}, /* M194 */ {0,1,2,3,4,2}, /* M191 */ {0,1,2,3,4,3}, /* M189 */ {0,1,2,3,4,4}, /* M188 */ {0,1,2,3,4,5} // GTR /* M203 */ }; final static int JC69 = 0; final static int HKY = 55; final static int TN93 = 58; final static int TIM = 172; final static int NEW = 197; final static int NEW2 = 176; final static int GTR = 202; final static int TVM = 176; final static int K81 = 164; // number of groups within a model int [] groupCount; // number of items in group int [][] subgroupCount; // integer number representing the model // e.g for model M191 = {1,2,3,4,5,3}, modelID = 123453 int [] modelID; int [][] models; IntegerParameter modelIndicator; @Override public void initAndValidate() { MODELS = generateAllModels(); switch (modelChoiseInput.get()) { case allreversible: models = MODELS; break; case transitionTransversionSplit: models = MODELS; calcSubGroupCount(models); calcDag(); setChildren(JC69, HKY); models = filterModels(); break; case namedSimple: models = MODELS; calcSubGroupCount(models); calcDag(); setChildren(JC69, HKY); setChildren(HKY, TN93); setChildren(TN93, GTR); models = filterModels(); mergedModels = new List[models.length]; splitModels = new List[models.length]; for (int i = 0; i < 3; i++) { mergedModels[i+1] = new ArrayList<>(); splitModels[i] = new ArrayList<>(); mergedModels[i+1].add(i); splitModels[i].add(i + 1); } splitModels[3] = new ArrayList<>(); mergedModels[0] = new ArrayList<>(); break; case namedExtended: models = MODELS; calcSubGroupCount(models); calcDag(); setChildren(JC69, HKY); setChildren(HKY, TN93); setChildren(TN93, TIM); setChildren(TIM, NEW); splitModels[TIM].add(NEW2); setChildren(NEW, GTR); models = filterModels(); break; case namedExtended2: models = MODELS; calcSubGroupCount(models); calcDag(); setChildren(JC69, HKY); setChildren(HKY, TN93); splitModels[HKY].add(K81); setChildren(TN93, TIM); setChildren(K81, TVM); setChildren(TIM, NEW); splitModels[TIM].add(NEW2); setChildren(TVM, GTR); setChildren(NEW, GTR); models = filterModels(); break; } frequencies = frequenciesInput.get(); updateMatrix = true; nrOfStates = frequencies.getFreqs().length; if (nrOfStates != 4) { throw new IllegalArgumentException("Frequencies has wrong size. Expected 4, but got " + nrOfStates); } try { eigenSystem = createEigenSystem(); } catch (SecurityException | ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e); } rateMatrix = new double[nrOfStates][nrOfStates]; relativeRates = new double[nrOfStates * (nrOfStates - 1)]; storedRelativeRates = new double[nrOfStates * (nrOfStates - 1)]; calcSubGroupCount(models); calcDag(); if (modelChoiseInput.get() == ModelSet.namedSimple) { splitModels[2].add(3); mergedModels[3].add(2); } modelIndicator = modelIndicatorInput.get(); // required for testing purposes eigenDecomposition = eigenSystem.decomposeMatrix(rateMatrix); } protected int[][] generateAllModels() { return generateAllReversibleModels(new int[6]); } int[][] generateAllReversibleModels(int [] model) { List<int []> modelset = new ArrayList<>(); while (model != null) { int [] nextmodel = model.clone(); boolean [] done = new boolean[6]; int groupcount = 0; int max = 0; for (int d : nextmodel) { max = Math.max(d + 1, max); if (!done[d]) { done[d] = true; groupcount++; } } if (max == groupcount) { normaliseModel(nextmodel); modelset.add(nextmodel); } model = nextModel(model); } Collections.sort(modelset , new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { for (int i = 0; i < o1.length; i++) { if (o1[i] != o2[i]) { if (o1[i] > o2[i]) { return 1; } else { return -1; } } } return 0; } }); for (int i = modelset.size() - 1; i > 0; i--) { int [] model1 = modelset.get(i); int [] model2 = modelset.get(i - 1); boolean equals = true; for (int k = 0; k < model1.length; k++) { if (model1[k] != model2[k]) { equals = false; break; } } if (equals) { modelset.remove(i); } } return modelset.toArray(new int[][]{}); } private int [] nextModel(int[] model) { int [] nextmodel = model.clone(); int pos = 5; while (pos >= 0 && nextmodel[pos] == pos) { nextmodel[pos] = 0; pos--; } if (pos == -1) { return null; } nextmodel[pos]++; return nextmodel; } public static void normaliseModel(int[] newmodel) { // sort the group numbers int [] shouldbe = new int[newmodel.length]; Arrays.fill(shouldbe, -1); int k = 0; for (int i = 0; i < newmodel.length; i++) { if (shouldbe[newmodel[i]] == -1) { shouldbe[newmodel[i]] = k++; } } for (int i = 0; i < newmodel.length; i++) { newmodel[i] = shouldbe[newmodel[i]]; } } private int[][] filterModels() { Set<Integer> filtered = new HashSet<>(); filtered.add(0); Set<Integer> candidates = new HashSet<>(); candidates.add(0); boolean [] done = new boolean[models.length]; while (candidates.size() > 0) { int i = (Integer) candidates.toArray()[0]; if (!done[i]) { for (int child : splitModels[i]) { candidates.add(child); filtered.add(child); } done[i] = true; } candidates.remove(i); } int [][] filteredModels = new int[filtered.size()][]; List<Integer> f = new ArrayList<>(); f.addAll(filtered); Collections.sort(f); int k = 0; for (int i : f) { filteredModels[k++] = models[i]; } splitModels = null; mergedModels = null; return filteredModels; } private void setChildren(int parent, int child) { splitModels[parent].clear(); splitModels[parent].add(child); } public int getModelCount() { return models.length; } public int[] getModel(int i) { return models[i]; } public int getGroupCount(int i) { return groupCount[i]; } public int[] getSubGroupCount(int i) { return subgroupCount[i]; } public int getMaxGroupCount() { return 6; } public int getModelNumber(int[] model) { int _modelID = calcModelID(model); int i = Arrays.binarySearch(modelID, _modelID); return i; } private void calcSubGroupCount(int[][] models) { groupCount = new int [models.length]; subgroupCount = new int [models.length][6]; for (int i = 0; i < models.length; i++) { for (int j = 0; j < 6; j++) { int m = models[i][j]; groupCount[i] = Math.max(groupCount[i], m + 1); subgroupCount[i][m]++; } } modelID = new int [models.length]; for (int i = 0; i < models.length; i++) { modelID[i] = calcModelID(models[i]); } } private int calcModelID(int[] model) { int modelID = 0; int k = 1; for (int j = model.length - 1; j >= 0; j--) { modelID += model[j] * k; k = k * 10; } return modelID; } @Override protected void setupRelativeRates() { Function rates = this.ratesInput.get(); int [] model = getModel(modelIndicator.getValue()); relativeRates[0] = rates.getArrayValue(model[0]); // A->C relativeRates[1] = rates.getArrayValue(model[1]); // A->G relativeRates[2] = rates.getArrayValue(model[2]); // A->T relativeRates[3] = relativeRates[0]; // C->A relativeRates[4] = rates.getArrayValue(model[3]); // C->G relativeRates[5] = rates.getArrayValue(model[4]); // C->T relativeRates[6] = relativeRates[1]; // G->A relativeRates[7] = relativeRates[4]; // G->C relativeRates[8] = rates.getArrayValue(model[5]); // G->T relativeRates[9] = relativeRates[2]; // T->A relativeRates[10] = relativeRates[5]; //T->C relativeRates[11] = relativeRates[8]; //T->G } @Override public boolean canHandleDataType(DataType dataType) { return dataType instanceof Nucleotide; } @Override public void init(PrintStream out) { String partition = (getID().contains(".") ? getID().substring(getID().lastIndexOf('.')) : ""); out.append("rateAC" + partition + "\t"); out.append("rateAG" + partition + "\t"); out.append("rateAT" + partition + "\t"); out.append("rateCG" + partition + "\t"); out.append("rateCT" + partition + "\t"); out.append("rateGT" + partition + "\t"); out.append("substmodel" + partition + "\t"); } @Override public void log(int nSample, PrintStream out) { Function rates = this.ratesInput.get(); int [] model = getModel(modelIndicator.getValue()); for (int i = 0; i < 6 ;i++) { out.append(rates.getArrayValue(model[i]) + "\t"); } for (int i = 0; i < 6 ;i++) { out.append((char)(model[i] + '1')); } out.append('\t'); } List<Integer> [] mergedModels; List<Integer> [] splitModels; public String toDotty() { if (splitModels == null) { calcDag(); } String [] labels = new String[models.length]; for (int i = 0; i < models.length; i++) { labels[i] = ""; for (int j : getModel(i)) { labels[i] += (j+1); } } StringBuilder sb = new StringBuilder(); sb.append("digraph {\n node [shape=plaintext];\n"); for (int i = 0; i < models.length; i++) { sb.append(labels[i] + " -> {"); for (int j : splitModels[i]) { sb.append(labels[j]); sb.append(','); } if (splitModels[i].size() > 0) { sb.delete(sb.length()-1, sb.length()); } sb.append("};\n"); } sb.append("}\n"); return sb.toString(); } private void calcDag() { mergedModels = new List[models.length]; splitModels = new List[models.length]; for (int i = 0; i < models.length; i++) { mergedModels[i] = new ArrayList<Integer>(); splitModels[i] = new ArrayList<Integer>(); } for (int i = 0; i < models.length; i++) { for (int j = 0; j < models.length; j++) { if (isSplit(j, i)) { mergedModels[i].add(j); boolean todo = isSplit(i, j); splitModels[j].add(i); } } } } /** return whether is model1 nested in model2, eg, HKY is nested in JC96 **/ public boolean isSplit(int m1, int m2) { if (getGroupCount(m1) + 1 != (getGroupCount(m2))) { return false; } int [] model1 = models[m1]; int [] model2 = models[m2]; int [] map = new int[model1.length]; Arrays.fill(map, -1); int [] revmap = new int[model1.length]; Arrays.fill(revmap, -1); int k1 = -1, k2 = -1; for (int i = 0; i < model1.length; i++) { if (map[model1[i]] != model2[i]) { if (map[model1[i]] < 0 && revmap[model2[i]] < 0) { map[model1[i]] = model2[i]; revmap[model2[i]] = model1[i]; } else if (k2 < 0) { k1 = model1[i]; k2 = model2[i]; } else if (model1[i] != k1 || model2[i] != k2) { return false; } } } return k2 >= 0; } public List<Integer> getSplitCanditates(int modelID) { return splitModels[modelID]; } public List<Integer> getMergeCanditates(int modelID) { return mergedModels[modelID]; } @Override public void close(PrintStream out) { // nothing to do } }
src/beast/evolution/substitutionmodel/NucleotideRevJumpSubstModel.java
package beast.evolution.substitutionmodel; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import beast.core.Description; import beast.core.Function; import beast.core.Input; import beast.core.Loggable; import beast.core.Input.Validate; import beast.core.parameter.IntegerParameter; import beast.evolution.datatype.DataType; import beast.evolution.datatype.Nucleotide; import beast.evolution.substitutionmodel.GeneralSubstitutionModel; @Description("Reversible jump based substitution model that can jump between all " + "reversible nucleotide substitution models") public class NucleotideRevJumpSubstModel extends GeneralSubstitutionModel implements Loggable { public enum ModelSet {allreversible, transitionTransversionSplit, namedSimple, namedExtended}; public Input<ModelSet> modelChoiseInput = new Input<ModelSet>("modelSet", "Which set of models to choose, one of " + Arrays.toString(ModelSet.values()), ModelSet.transitionTransversionSplit, ModelSet.values()); public Input<IntegerParameter> modelIndicatorInput = new Input<IntegerParameter>("modelIndicator", "number of the model to be used", Validate.REQUIRED); // public NucleotideRevJumpSubstModel() throws Exception { // Frequencies frequencies = new Frequencies(); // frequencies.initByName("frequencies", "0.25 0.25 0.25 0.25"); // // initByName("rates", new RealParameter("1.0 1.0 1.0 1.0 1.0 1.0"), // "modelIndicator", new IntegerParameter("0"), // "frequencies", frequencies // ); // } /** sorted list of model indicators we jump between**/ public static int [][] MODELS = new int[][]{ {0,0,0,0,0,0}, // Jukes Cantor F81 /* M1 */ {0,0,0,0,0,1}, /* M7 */ {0,0,0,0,1,0}, /* M6 */ {0,0,0,0,1,1}, /* M22 */ {0,0,0,0,1,2}, /* M47 */ {0,0,0,1,0,0}, /* M5 */ {0,0,0,1,0,1}, /* M21 */ {0,0,0,1,0,2}, /* M46 */ {0,0,0,1,1,0}, /* M20 */ {0,0,0,1,1,1}, /* M23 */ {0,0,0,1,1,2}, /* M107 */ {0,0,0,1,2,0}, /* M45 */ {0,0,0,1,2,1}, /* M106 */ {0,0,0,1,2,2}, /* M105 */ {0,0,0,1,2,3}, /* M142 */ {0,0,1,0,0,0}, /* M4 */ {0,0,1,0,0,1}, /* M19 */ {0,0,1,0,0,2}, /* M44 */ {0,0,1,0,1,0}, /* M18 */ {0,0,1,0,1,1}, /* M24 */ {0,0,1,0,1,2}, /* M104 */ {0,0,1,0,2,0}, /* M43 */ {0,0,1,0,2,1}, /* M103 */ {0,0,1,0,2,2}, /* M98 */ {0,0,1,0,2,3}, /* M141 */ {0,0,1,1,0,0}, /* M17 */ {0,0,1,1,0,1}, /* M25 */ {0,0,1,1,0,2}, /* M102 */ {0,0,1,1,1,0}, /* M26 */ {0,0,1,1,1,1}, /* M8 */ {0,0,1,1,1,2}, /* M65 */ {0,0,1,1,2,0}, /* M101 */ {0,0,1,1,2,1}, /* M64 */ {0,0,1,1,2,2}, /* M108 */ {0,0,1,1,2,3}, /* M175 */ {0,0,1,2,0,0}, /* M42 */ {0,0,1,2,0,1}, /* M100 */ {0,0,1,2,0,2}, /* M97 */ {0,0,1,2,0,3}, /* M140 */ {0,0,1,2,1,0}, /* M99 */ {0,0,1,2,1,1}, /* M63 */ {0,0,1,2,1,2}, /* M109 */ {0,0,1,2,1,3}, /* M174 */ {0,0,1,2,2,0}, /* M96 */ {0,0,1,2,2,1}, /* M110 */ {0,0,1,2,2,2}, /* M62 */ {0,0,1,2,2,3}, /* M172 */ {0,0,1,2,3,0}, /* M139 */ {0,0,1,2,3,1}, /* M173 */ {0,0,1,2,3,2}, /* M171 */ {0,0,1,2,3,3}, /* M170 */ {0,0,1,2,3,4}, /* M202 */ {0,1,0,0,0,0}, /* M3 */ {0,1,0,0,0,1}, /* M16 */ {0,1,0,0,0,2}, /* M41 */ {0,1,0,0,1,0}, // HKY F84 /* M15 */ {0,1,0,0,1,1}, /* M27 */ {0,1,0,0,1,2}, /* M95 */ {0,1,0,0,2,0}, // TN93 /* M40 */ {0,1,0,0,2,1}, /* M94 */ {0,1,0,0,2,2}, /* M83 */ {0,1,0,0,2,3}, /* M138 */ {0,1,0,1,0,0}, /* M14 */ {0,1,0,1,0,1}, /* M28 */ {0,1,0,1,0,2}, /* M93 */ {0,1,0,1,1,0}, /* M29 */ {0,1,0,1,1,1}, /* M9 */ {0,1,0,1,1,2}, /* M71 */ {0,1,0,1,2,0}, /* M92 */ {0,1,0,1,2,1}, /* M70 */ {0,1,0,1,2,2}, /* M111 */ {0,1,0,1,2,3}, /* M184 */ {0,1,0,2,0,0}, /* M39 */ {0,1,0,2,0,1}, /* M91 */ {0,1,0,2,0,2}, /* M82 */ {0,1,0,2,0,3}, /* M137 */ {0,1,0,2,1,0}, /* M90 */ {0,1,0,2,1,1}, /* M69 */ {0,1,0,2,1,2}, /* M112 */ {0,1,0,2,1,3}, /* M183 */ {0,1,0,2,2,0}, /* M81 */ {0,1,0,2,2,1}, /* M113 */ {0,1,0,2,2,2}, /* M58 */ {0,1,0,2,2,3}, /* M163 */ {0,1,0,2,3,0}, /* M136 */ {0,1,0,2,3,1}, /* M182 */ {0,1,0,2,3,2}, /* M162 */ {0,1,0,2,3,3}, /* M161 */ {0,1,0,2,3,4}, /* M201 */ {0,1,1,0,0,0}, /* M13 */ {0,1,1,0,0,1}, /* M30 */ {0,1,1,0,0,2}, /* M89 */ {0,1,1,0,1,0}, /* M31 */ {0,1,1,0,1,1}, /* M10 */ {0,1,1,0,1,2}, /* M75 */ {0,1,1,0,2,0}, /* M88 */ {0,1,1,0,2,1}, /* M74 */ {0,1,1,0,2,2}, /* M114 */ {0,1,1,0,2,3}, /* M187 */ {0,1,1,1,0,0}, /* M32 */ {0,1,1,1,0,1}, /* M11 */ {0,1,1,1,0,2}, /* M77 */ {0,1,1,1,1,0}, /* M12 */ {0,1,1,1,1,1}, /* M2 */ {0,1,1,1,1,2}, /* M37 */ {0,1,1,1,2,0}, /* M76 */ {0,1,1,1,2,1}, /* M36 */ {0,1,1,1,2,2}, /* M57 */ {0,1,1,1,2,3}, /* M132 */ {0,1,1,2,0,0}, /* M87 */ {0,1,1,2,0,1}, /* M72 */ {0,1,1,2,0,2}, /* M115 */ {0,1,1,2,0,3}, /* M186 */ {0,1,1,2,1,0}, /* M73 */ {0,1,1,2,1,1}, /* M35 */ {0,1,1,2,1,2}, /* M56 */ {0,1,1,2,1,3}, /* M131 */ {0,1,1,2,2,0}, /* M116 */ {0,1,1,2,2,1}, /* M55 */ {0,1,1,2,2,2}, /* M48 */ {0,1,1,2,2,3}, /* M151 */ {0,1,1,2,3,0}, /* M185 */ {0,1,1,2,3,1}, /* M130 */ {0,1,1,2,3,2}, /* M150 */ {0,1,1,2,3,3}, /* M149 */ {0,1,1,2,3,4}, /* M197 */ {0,1,2,0,0,0}, /* M38 */ {0,1,2,0,0,1}, /* M86 */ {0,1,2,0,0,2}, /* M80 */ {0,1,2,0,0,3}, /* M135 */ {0,1,2,0,1,0}, /* M85 */ {0,1,2,0,1,1}, /* M66 */ {0,1,2,0,1,2}, /* M117 */ {0,1,2,0,1,3}, /* M179 */ {0,1,2,0,2,0}, /* M79 */ {0,1,2,0,2,1}, /* M118 */ {0,1,2,0,2,2}, /* M59 */ {0,1,2,0,2,3}, /* M167 */ {0,1,2,0,3,0}, /* M134 */ {0,1,2,0,3,1}, /* M178 */ {0,1,2,0,3,2}, /* M166 */ {0,1,2,0,3,3}, /* M158 */ {0,1,2,0,3,4}, /* M200 */ {0,1,2,1,0,0}, /* M84 */ {0,1,2,1,0,1}, /* M67 */ {0,1,2,1,0,2}, /* M119 */ {0,1,2,1,0,3}, /* M181 */ {0,1,2,1,1,0}, /* M68 */ {0,1,2,1,1,1}, /* M34 */ {0,1,2,1,1,2}, /* M54 */ {0,1,2,1,1,3}, /* M129 */ {0,1,2,1,2,0}, /* M120 */ {0,1,2,1,2,1}, /* M53 */ {0,1,2,1,2,2}, /* M49 */ {0,1,2,1,2,3}, /* M155 */ {0,1,2,1,3,0}, /* M180 */ {0,1,2,1,3,1}, /* M128 */ {0,1,2,1,3,2}, /* M154 */ {0,1,2,1,3,3}, /* M146 */ {0,1,2,1,3,4}, /* M196 */ {0,1,2,2,0,0}, /* M78 */ {0,1,2,2,0,1}, /* M121 */ {0,1,2,2,0,2}, /* M60 */ {0,1,2,2,0,3}, /* M169 */ {0,1,2,2,1,0}, // Kimura 81 /* M122 */ {0,1,2,2,1,1}, /* M52 */ {0,1,2,2,1,2}, /* M50 */ {0,1,2,2,1,3}, /* M157 */ {0,1,2,2,2,0}, /* M61 */ {0,1,2,2,2,1}, /* M51 */ {0,1,2,2,2,2}, /* M33 */ {0,1,2,2,2,3}, /* M126 */ {0,1,2,2,3,0}, // Posada 03 /* M168 */ {0,1,2,2,3,1}, /* M156 */ {0,1,2,2,3,2}, /* M125 */ {0,1,2,2,3,3}, /* M143 */ {0,1,2,2,3,4}, /* M193 */ {0,1,2,3,0,0}, /* M133 */ {0,1,2,3,0,1}, /* M176 */ {0,1,2,3,0,2}, /* M164 */ {0,1,2,3,0,3}, /* M159 */ {0,1,2,3,0,4}, /* M199 */ {0,1,2,3,1,0}, /* M177 */ {0,1,2,3,1,1}, /* M127 */ {0,1,2,3,1,2}, /* M152 */ {0,1,2,3,1,3}, /* M147 */ {0,1,2,3,1,4}, // Posada 03 /* M195 */ {0,1,2,3,2,0}, /* M165 */ {0,1,2,3,2,1}, /* M153 */ {0,1,2,3,2,2}, /* M124 */ {0,1,2,3,2,3}, /* M144 */ {0,1,2,3,2,4}, /* M192 */ {0,1,2,3,3,0}, /* M160 */ {0,1,2,3,3,1}, /* M148 */ {0,1,2,3,3,2}, /* M145 */ {0,1,2,3,3,3}, /* M123 */ {0,1,2,3,3,4}, /* M190 */ {0,1,2,3,4,0}, /* M198 */ {0,1,2,3,4,1}, /* M194 */ {0,1,2,3,4,2}, /* M191 */ {0,1,2,3,4,3}, /* M189 */ {0,1,2,3,4,4}, /* M188 */ {0,1,2,3,4,5} // GTR /* M203 */ }; final static int JC69 = 0; final static int HKY = 55; final static int TN93 = 58; final static int TIM = 172; final static int NEW = 197; final static int NEW2 = 176; final static int GTR = 202; // number of groups within a model int [] groupCount; // number of items in group int [][] subgroupCount; // integer number representing the model // e.g for model M191 = {1,2,3,4,5,3}, modelID = 123453 int [] modelID; int [][] models; IntegerParameter modelIndicator; @Override public void initAndValidate() { MODELS = generateAllModels(); switch (modelChoiseInput.get()) { case allreversible: models = MODELS; break; case transitionTransversionSplit: models = MODELS; calcSubGroupCount(models); calcDag(); setChildren(JC69, HKY); models = filterModels(); break; case namedSimple: models = MODELS; calcSubGroupCount(models); calcDag(); setChildren(JC69, HKY); setChildren(HKY, TN93); setChildren(TN93, GTR); models = filterModels(); mergedModels = new List[models.length]; splitModels = new List[models.length]; for (int i = 0; i < 3; i++) { mergedModels[i+1] = new ArrayList<>(); splitModels[i] = new ArrayList<>(); mergedModels[i+1].add(i); splitModels[i].add(i + 1); } splitModels[3] = new ArrayList<>(); mergedModels[0] = new ArrayList<>(); break; case namedExtended: models = MODELS; calcSubGroupCount(models); calcDag(); setChildren(JC69, HKY); setChildren(HKY, TN93); setChildren(TN93, TIM); setChildren(TIM, NEW); splitModels[TIM].add(NEW2); setChildren(NEW, GTR); models = filterModels(); break; } frequencies = frequenciesInput.get(); updateMatrix = true; nrOfStates = frequencies.getFreqs().length; if (nrOfStates != 4) { throw new IllegalArgumentException("Frequencies has wrong size. Expected 4, but got " + nrOfStates); } try { eigenSystem = createEigenSystem(); } catch (SecurityException | ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e); } rateMatrix = new double[nrOfStates][nrOfStates]; relativeRates = new double[nrOfStates * (nrOfStates - 1)]; storedRelativeRates = new double[nrOfStates * (nrOfStates - 1)]; calcSubGroupCount(models); calcDag(); if (modelChoiseInput.get() == ModelSet.namedSimple) { splitModels[2].add(3); mergedModels[3].add(2); } modelIndicator = modelIndicatorInput.get(); // required for testing purposes eigenDecomposition = eigenSystem.decomposeMatrix(rateMatrix); } protected int[][] generateAllModels() { return generateAllReversibleModels(new int[6]); } int[][] generateAllReversibleModels(int [] model) { List<int []> modelset = new ArrayList<>(); while (model != null) { int [] nextmodel = model.clone(); boolean [] done = new boolean[6]; int groupcount = 0; int max = 0; for (int d : nextmodel) { max = Math.max(d + 1, max); if (!done[d]) { done[d] = true; groupcount++; } } if (max == groupcount) { normaliseModel(nextmodel); modelset.add(nextmodel); } model = nextModel(model); } Collections.sort(modelset , new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { for (int i = 0; i < o1.length; i++) { if (o1[i] != o2[i]) { if (o1[i] > o2[i]) { return 1; } else { return -1; } } } return 0; } }); for (int i = modelset.size() - 1; i > 0; i--) { int [] model1 = modelset.get(i); int [] model2 = modelset.get(i - 1); boolean equals = true; for (int k = 0; k < model1.length; k++) { if (model1[k] != model2[k]) { equals = false; break; } } if (equals) { modelset.remove(i); } } return modelset.toArray(new int[][]{}); } private int [] nextModel(int[] model) { int [] nextmodel = model.clone(); int pos = 5; while (pos >= 0 && nextmodel[pos] == pos) { nextmodel[pos] = 0; pos--; } if (pos == -1) { return null; } nextmodel[pos]++; return nextmodel; } public static void normaliseModel(int[] newmodel) { // sort the group numbers int [] shouldbe = new int[newmodel.length]; Arrays.fill(shouldbe, -1); int k = 0; for (int i = 0; i < newmodel.length; i++) { if (shouldbe[newmodel[i]] == -1) { shouldbe[newmodel[i]] = k++; } } for (int i = 0; i < newmodel.length; i++) { newmodel[i] = shouldbe[newmodel[i]]; } } private int[][] filterModels() { Set<Integer> filtered = new HashSet<>(); filtered.add(0); Set<Integer> candidates = new HashSet<>(); candidates.add(0); boolean [] done = new boolean[models.length]; while (candidates.size() > 0) { int i = (Integer) candidates.toArray()[0]; if (!done[i]) { for (int child : splitModels[i]) { candidates.add(child); filtered.add(child); } done[i] = true; } candidates.remove(i); } int [][] filteredModels = new int[filtered.size()][]; List<Integer> f = new ArrayList<>(); f.addAll(filtered); Collections.sort(f); int k = 0; for (int i : f) { filteredModels[k++] = models[i]; } splitModels = null; mergedModels = null; return filteredModels; } private void setChildren(int parent, int child) { splitModels[parent].clear(); splitModels[parent].add(child); } public int getModelCount() { return models.length; } public int[] getModel(int i) { return models[i]; } public int getGroupCount(int i) { return groupCount[i]; } public int[] getSubGroupCount(int i) { return subgroupCount[i]; } public int getMaxGroupCount() { return 6; } public int getModelNumber(int[] model) { int _modelID = calcModelID(model); int i = Arrays.binarySearch(modelID, _modelID); return i; } private void calcSubGroupCount(int[][] models) { groupCount = new int [models.length]; subgroupCount = new int [models.length][6]; for (int i = 0; i < models.length; i++) { for (int j = 0; j < 6; j++) { int m = models[i][j]; groupCount[i] = Math.max(groupCount[i], m + 1); subgroupCount[i][m]++; } } modelID = new int [models.length]; for (int i = 0; i < models.length; i++) { modelID[i] = calcModelID(models[i]); } } private int calcModelID(int[] model) { int modelID = 0; int k = 1; for (int j = model.length - 1; j >= 0; j--) { modelID += model[j] * k; k = k * 10; } return modelID; } @Override protected void setupRelativeRates() { Function rates = this.ratesInput.get(); int [] model = getModel(modelIndicator.getValue()); relativeRates[0] = rates.getArrayValue(model[0]); // A->C relativeRates[1] = rates.getArrayValue(model[1]); // A->G relativeRates[2] = rates.getArrayValue(model[2]); // A->T relativeRates[3] = relativeRates[0]; // C->A relativeRates[4] = rates.getArrayValue(model[3]); // C->G relativeRates[5] = rates.getArrayValue(model[4]); // C->T relativeRates[6] = relativeRates[1]; // G->A relativeRates[7] = relativeRates[4]; // G->C relativeRates[8] = rates.getArrayValue(model[5]); // G->T relativeRates[9] = relativeRates[2]; // T->A relativeRates[10] = relativeRates[5]; //T->C relativeRates[11] = relativeRates[8]; //T->G } @Override public boolean canHandleDataType(DataType dataType) { return dataType instanceof Nucleotide; } @Override public void init(PrintStream out) { String partition = (getID().contains(".") ? getID().substring(getID().lastIndexOf('.')) : ""); out.append("rateAC" + partition + "\t"); out.append("rateAG" + partition + "\t"); out.append("rateAT" + partition + "\t"); out.append("rateCG" + partition + "\t"); out.append("rateCT" + partition + "\t"); out.append("rateGT" + partition + "\t"); out.append("substmodel" + partition + "\t"); } @Override public void log(int nSample, PrintStream out) { Function rates = this.ratesInput.get(); int [] model = getModel(modelIndicator.getValue()); for (int i = 0; i < 6 ;i++) { out.append(rates.getArrayValue(model[i]) + "\t"); } for (int i = 0; i < 6 ;i++) { out.append((char)(model[i] + '1')); } out.append('\t'); } List<Integer> [] mergedModels; List<Integer> [] splitModels; String toDotty() { if (splitModels == null) { calcDag(); } String [] labels = new String[models.length]; for (int i = 0; i < models.length; i++) { labels[i] = ""; for (int j : getModel(i)) { labels[i] += (j+1); } } StringBuilder sb = new StringBuilder(); sb.append("digraph {\n node [shape=plaintext];\n"); for (int i = 0; i < models.length; i++) { sb.append(labels[i] + " -> {"); for (int j : splitModels[i]) { sb.append(labels[j]); sb.append(','); } if (splitModels[i].size() > 0) { sb.delete(sb.length()-1, sb.length()); } sb.append("};\n"); } sb.append("}\n"); return sb.toString(); } private void calcDag() { mergedModels = new List[models.length]; splitModels = new List[models.length]; for (int i = 0; i < models.length; i++) { mergedModels[i] = new ArrayList<Integer>(); splitModels[i] = new ArrayList<Integer>(); } for (int i = 0; i < models.length; i++) { for (int j = 0; j < models.length; j++) { if (isSplit(j, i)) { mergedModels[i].add(j); boolean todo = isSplit(i, j); splitModels[j].add(i); } } } } /** return whether is model1 nested in model2, eg, HKY is nested in JC96 **/ boolean isSplit(int m1, int m2) { if (getGroupCount(m1) + 1 != (getGroupCount(m2))) { return false; } int [] model1 = models[m1]; int [] model2 = models[m2]; int [] map = new int[model1.length]; Arrays.fill(map, -1); int [] revmap = new int[model1.length]; Arrays.fill(revmap, -1); int k1 = -1, k2 = -1; for (int i = 0; i < model1.length; i++) { if (map[model1[i]] != model2[i]) { if (map[model1[i]] < 0 && revmap[model2[i]] < 0) { map[model1[i]] = model2[i]; revmap[model2[i]] = model1[i]; } else if (k2 < 0) { k1 = model1[i]; k2 = model2[i]; } else if (model1[i] != k1 || model2[i] != k2) { return false; } } } return k2 >= 0; } public List<Integer> getSplitCanditates(int modelID) { return splitModels[modelID]; } public List<Integer> getMergeCanditates(int modelID) { return mergedModels[modelID]; } @Override public void close(PrintStream out) { // nothing to do } }
added alternative named set of subst models
src/beast/evolution/substitutionmodel/NucleotideRevJumpSubstModel.java
added alternative named set of subst models
Java
lgpl-2.1
7a935fe1de70039bbb15520c000012fe4c9587c0
0
ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS
/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package alma.ACS.impl; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import alma.acs.container.ContainerServices; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.NO_RESOURCES; import org.omg.PortableServer.Servant; import alma.ACS.CBDescIn; import alma.ACS.CBvoid; import alma.ACS.Callback; import alma.ACS.Monitor; import alma.ACS.MonitorHelper; import alma.ACS.MonitorOperations; import alma.ACS.NoSuchCharacteristic; import alma.ACS.TimeSeqHolder; import alma.ACS.jbaci.BACIAction; import alma.ACS.jbaci.BACIPriority; import alma.ACS.jbaci.CallbackDispatcher; import alma.ACS.jbaci.CompletionUtil; import alma.ACS.jbaci.DataAccess; import alma.ACS.jbaci.MemoryDataAccess; import alma.ACS.jbaci.PropertyInitializationFailed; import alma.ACSErr.Completion; import alma.ACSErr.CompletionHolder; import alma.ACSErrTypeCommon.wrappers.AcsJCouldntPerformActionEx; import alma.ACSErrTypeCommon.wrappers.AcsJUnknownEx; import alma.acs.exceptions.AcsJException; /** * Implementation of common property, i.e. type of <code>java.lang.Object</code>. * @author <a href="mailto:matej.sekoranjaATcosylab.com">Matej Sekoranja</a> * @version $id$ */ public abstract class CommonPropertyImpl extends TypelessPropertyImpl implements CallbackDispatcher { /** * Logger variable */ private Logger m_logger; /** * Default timer trigger (in 100ns units). */ protected long defaultTimerTrigger; /** * Min timer trigger (in 100ns units). */ protected long minTimerTrigger; /** * Default value. */ protected Object defaultValue; /** * Read-only data access. */ protected DataAccess dataAccess; /** * Property <code>Class</code> type. */ protected Class propertyType; /** * History size, if 0 history is disabled. */ protected int historySize; /** * Pointer in history arrays, points to first empty element. */ protected int historyPosition; /** * <code>true</code>, if values in history arrays exceed end of arrays (circular arrays). */ protected boolean historyTurnaround; /** * Array of history values. */ protected Object historyValue; /** * Array of history times (OMG standard time). */ protected long[] historyTime; /** * List of all property monitors (needed on property destruction). */ protected Map monitors; /************ [ Mnemonic value retrival mechanism ] ************/ /** * Mnemonic read time key of (last) pending read. */ protected long mnemonicReadPending = 0; /** * Mnemonic read lock (dummy object). */ protected Object mnemonicValueRetrival = new Object(); /** * Mnemonic variables lock. */ protected ReadWriteLock mnemonicDataLock = new ReentrantReadWriteLock(); /** * Time "key" (Java) if when last mnemonic retrival. */ protected long mnemonicTime; /** * Value of latest mnemonic value retrival. */ protected Object mnemonicValue; /** * Completion of latest mnemonic value retrival. */ protected Completion mnemonicCompletion; /***************************************************************/ /** * Constructor with memory data access. * @param propertyType property <code>Class</code> type, non-<code>null</code>. * @param name property name, non-<code>null</code>. * @param parentComponent parent component, non-<code>null</code>. * @throws PropertyInitializationFailed exception is thrown on failure */ public CommonPropertyImpl( Class propertyType, String name, CharacteristicComponentImpl parentComponent) throws PropertyInitializationFailed { this(propertyType, name, parentComponent, new MemoryDataAccess()); m_logger = parentComponent.getComponentContainerServices().getLogger(); } /** * Constructor. * @param propertyType property <code>Class</code> type, non-<code>null</code>. * @param name property name, non-<code>null</code>. * @param parentComponent parent component, non-<code>null</code>. * @param dataAccess read-write data access to be use, non-<code>null</code>. * @throws PropertyInitializationFailed exception is thrown on failure */ public CommonPropertyImpl( Class propertyType, String name, CharacteristicComponentImpl parentComponent, DataAccess dataAccess) throws PropertyInitializationFailed { super(name, parentComponent); this.propertyType = propertyType; this.dataAccess = dataAccess; m_logger = parentComponent.getComponentContainerServices().getLogger(); // TODO to be configurable historySize = 32; historyPosition = 0; historyTurnaround = false; historyTime = new long[historySize]; historyValue = Array.newInstance(propertyType, historySize); // initialize data access, if required if (dataAccess.initializeValue()) { try { CompletionHolder completionHolder = CompletionUtil.createCompletionHolder(); dataAccess.set(defaultValue, completionHolder); } catch (Throwable th) { // TODO log m_logger.log(Level.WARNING, "jBaci::CommonPropertyImpl::CommonPropertyImpl - Cannot create Completion Holder"); throw new NO_RESOURCES(th.getMessage()); } } // create monitor data structure monitors = new HashMap(); // create history monitor registerMonitor(new HistoryMonitorImpl(this), null); } /** * Read property characteristics. * @throws PropertyInitializationFailed exception is thrown on failure */ public void readCharacteristics() throws PropertyInitializationFailed { super.readCharacteristics(); try { // defaultTimerTrigger = characteristicModelImpl.getLong("default_timer_trig"); // minTimerTrigger = characteristicModelImpl.getLong("min_timer_trig"); defaultTimerTrigger = (long)(characteristicModelImpl.getDouble("default_timer_trig")*10000000L); minTimerTrigger = (long)(characteristicModelImpl.getDouble("min_timer_trig")*10000000L); defaultValue = readPropertyTypeCharacteristic("default_value"); } catch (Throwable t) { throw new PropertyInitializationFailed("Failed to read all property characteristics.", t); } } /** * Get property data access layer. * @return property data access. */ public DataAccess getDataAccess() { return dataAccess; } /** * @see alma.ACS.PropertyImpl#destroy() */ public void destroy() { super.destroy(); // destroy all monitors if (monitors.size() != 0) { MonitorOperations[] monitorArray = null; synchronized (monitors) { monitorArray = new MonitorOperations[monitors.size()]; monitors.keySet().toArray(monitorArray); } for (int i = 0; i < monitorArray.length; i++) { try { monitorArray[i].destroy(); } catch (Throwable th) { // TODO log m_logger.log(Level.WARNING, "jBaci::CommonPropertyImpl::destroy - cannot destroy monitorArray[]."); throw new NO_RESOURCES(th.getMessage()); } } } } /*********************** [ P<type> ] ***********************/ /** * @see alma.ACS.P<type>Operations#default_timer_trigger() */ public long default_timer_trigger() { return defaultTimerTrigger; } /** * @see alma.ACS.P<type>Operations#min_timer_trigger() */ public long min_timer_trigger() { return minTimerTrigger; } /*********************** [ P<type> helpers ] ***********************/ /** * Read property type characteristic. * @throws NoSuchCharacteristic is thrown if characterstic does not exist. */ public abstract Object readPropertyTypeCharacteristic(String name) throws NoSuchCharacteristic; /** * Add value to the history. * @param value value to be added to the history. * @param timestamp value timestamp (OMG) to be added to the history. */ protected void addValueToHistory(Object value, long timestamp) { // if history is disabled if (historySize == 0) return; synchronized (historyValue) { // add historyTime[historyPosition] = timestamp; // historyValue[historyPosition] = value; if (propertyType.isPrimitive()) { // primitives are really ugly to handle // order must match probability... if (propertyType.isAssignableFrom(double.class)) Array.setDouble(historyValue, historyPosition, ((Double)value).doubleValue()); else if (propertyType.isAssignableFrom(int.class)) Array.setInt(historyValue, historyPosition, ((Integer)value).intValue()); else if (propertyType.isAssignableFrom(long.class)) Array.setLong(historyValue, historyPosition, ((Long)value).longValue()); else if (propertyType.isAssignableFrom(short.class)) Array.setShort(historyValue, historyPosition, ((Short)value).shortValue()); else if (propertyType.isAssignableFrom(boolean.class)) Array.setBoolean(historyValue, historyPosition, ((Boolean)value).booleanValue()); else if (propertyType.isAssignableFrom(byte.class)) Array.setByte(historyValue, historyPosition, ((Byte)value).byteValue()); else if (propertyType.isAssignableFrom(float.class)) Array.setFloat(historyValue, historyPosition, ((Float)value).floatValue()); else if (propertyType.isAssignableFrom(char.class)) Array.setChar(historyValue, historyPosition, ((Character)value).charValue()); else // TODO log "Unhandled primitive" m_logger.log(Level.WARNING, "jBaci::CommonPropertyImpl::addValueToHistory - Unhandled primitive."); throw new NO_RESOURCES("Unhandled primitive"); } else Array.set(historyValue, historyPosition, value); // manage control variables historyPosition = ++historyPosition % historySize; if (!historyTurnaround && historyPosition == 0) historyTurnaround = true; } } protected Object getHistory(int lastValues, TimeSeqHolder timeSeqHolder) { // check bad parameter if (lastValues < 0) throw new BAD_PARAM("lastValues < 0"); synchronized (historyValue) { int length, first; if (historyTurnaround) { length = historySize; first = historyPosition; } else { length = historyPosition; first = 0; } // last n values (and not first n values) if (lastValues > length) lastValues = length; first = (first + length - lastValues) % historySize; // get required number of values if (lastValues < length) length = lastValues; timeSeqHolder.value = new long[length]; Object values = Array.newInstance(propertyType, length); // no history case if (length == 0) return values; // copy if (first + length < historySize) { System.arraycopy(historyTime, first, timeSeqHolder.value, 0, length); System.arraycopy(historyValue, first, values, 0, length); } else { int split = historySize - first; System.arraycopy(historyTime, first, timeSeqHolder.value, 0, split); System.arraycopy(historyValue, first, values, 0, split); System.arraycopy(historyTime, 0, timeSeqHolder.value, split, length - split); System.arraycopy(historyValue, 0, values, split, length - split); } return values; } } /** * @see alma.ACS.P<type>Operations#get_sync(alma.ACSErr.CompletionHolder) */ protected Object getSync(CompletionHolder completionHolder) throws AcsJException { try { Object retVal = dataAccess.get(completionHolder); // generate no-error completion, if not generated if (completionHolder.value == null) completionHolder.value = CompletionUtil.generateNoErrorCompletion(); return retVal; } catch (AcsJException acsex) { throw new AcsJCouldntPerformActionEx("Failed to retrieve value.", acsex); } } /** * BACI action to invoke <code>getSync</code> asynchroniously. */ protected class GetAsyncAction extends BACIAction { /** * @see alma.ACS.jbaci.BACIAction */ public GetAsyncAction(Callback callback, CBDescIn descIn) { super(getParentComponent(), callback, descIn, CommonPropertyImpl.this); } /** * @see alma.ACS.jbaci.BACIAction */ public GetAsyncAction( Callback callback, CBDescIn descIn, BACIPriority priority) { super(getParentComponent(), callback, descIn, CommonPropertyImpl.this, priority); } /** * @see alma.ACS.jbaci.BACIAction#execute() */ public Object execute() throws AcsJException { try { CompletionHolder completionHolder = CompletionUtil.createCompletionHolder(); Object retVal = getSync(completionHolder); // set completion this.completion = completionHolder.value; return retVal; } catch (AcsJException acsex) { // send default value in case of failure this.returnValue = defaultValue; throw new AcsJCouldntPerformActionEx("Failed to retrieve value asynchroniously.", acsex); } } } /** * @see alma.ACS.P<type>Operations#get_async(alma.ACS.CB<type>, alma.ACS.CBDescIn) */ protected void getAsync(Callback callback, CBDescIn desc) { new GetAsyncAction(callback, desc).submit(); } /** * Register monitor on this property (and optionally CORBA activate). * Registration is needed for monitor destruction on property destruction. * @param monitorImpl monitor implementation (e.g. class implementing <code>MonitorOperations</code> interface). * @param monitorServant monitor CORBA servant (e.g. Monitor<type>POATie class). If <code>null</code> monitor will * be threated as non-CORBA monitor and no CORBA activation will be done. * @return CORBA activated monitor reference, <code>null</code> if <code>monitorServant == null</code>. */ public Monitor registerMonitor(MonitorOperations monitorImpl, Servant monitorServant) { // allow activation if already in monitor list... Monitor monitor = null; if (monitorServant != null) { try { // TODO pesistent, user ID activation monitor = MonitorHelper.narrow( parentComponent.getComponentContainerServices().activateOffShoot(monitorServant) ); } catch (Throwable th) { // TODO log m_logger.log(Level.WARNING, "jBaci::CommonPropertyImpl::registerMonitor - Cannot activate Off Shoot with the monitorServant."); throw new NO_RESOURCES(th.getMessage()); } } // add to list synchronized (monitors) { if (!monitors.containsKey(monitorImpl)) monitors.put(monitorImpl, monitorServant); } return monitor; } /** * Unregister monitor on this property (and optionally CORBA deactivate). * Should be called by <code>MonitorOperations.destroy()</code> method. */ public void unregisterMonitor(MonitorOperations monitorImpl) { Servant monitorServant = null; // remove from list synchronized (monitors) { monitorServant = (Servant)monitors.remove(monitorImpl); } // deativate CORBA monitor servant if (monitorServant != null) { try { parentComponent.getComponentContainerServices().deactivateOffShoot(monitorServant); } catch (Throwable th) { // TODO log m_logger.log(Level.WARNING, "jBaci::CommonPropertyImpl::unregisterMonitor - Cannot deactivate Off Shoot with monitorServant"); throw new NO_RESOURCES(th.getMessage()); } } } /*********************** [ RW<type> helpers ] ***********************/ /** * @see alma.ACSErr.Completion alma.ACS.RW<type>Operations#set_sync(<type>) */ protected Completion setSync(Object value) throws AcsJException { // TODO should we check limits here try { CompletionHolder completionHolder = CompletionUtil.createCompletionHolder(); dataAccess.set(value, completionHolder); // generate no-error completion, if not generated if (completionHolder.value == null) completionHolder.value = CompletionUtil.generateNoErrorCompletion(); return completionHolder.value; } catch (AcsJException acsex) { throw new AcsJCouldntPerformActionEx("Failed to set value.", acsex); } } /** * BACI action to invoke <code>setSync</code> asynchroniously. */ protected class SetAsyncAction extends BACIAction { /** * Value to be set. */ Object value; /** * @see alma.ACS.jbaci.BACIAction */ public SetAsyncAction(Object value, Callback callback, CBDescIn descIn) { super(getParentComponent(), callback, descIn, CommonPropertyImpl.this); this.value = value; } /** * @see alma.ACS.jbaci.BACIAction */ public SetAsyncAction( Object value, Callback callback, CBDescIn descIn, BACIPriority priority) { super(getParentComponent(), callback, descIn, CommonPropertyImpl.this, priority); this.value = value; } /** * @see alma.ACS.jbaci.BACIAction#execute() */ public Object execute() throws AcsJException { try { completion = setSync(value); } catch (AcsJException acsex) { throw new AcsJCouldntPerformActionEx("Failed to set value asynchroniously.", acsex); } // no return value return null; } } /** * @see alma.ACS.RW<type>Operations#get_async(<type>, alma.ACS.CBvoid, alma.ACS.CBDescIn) */ protected void setAsync(Object value, CBvoid callback, CBDescIn desc) { new SetAsyncAction(value, callback, desc).submit(); } /** * @see void alma.ACS.RW<type>Operations#set_nonblocking(<type>) */ protected void setNonblocking(Object value) { try { setSync(value); } catch (Throwable th) { // TODO log m_logger.log(Level.WARNING, "jBaci::CommonPropertyImpl::setNonblocking - Cannot setSync the value."); throw new NO_RESOURCES(th.getMessage()); } } /** * Mnemonic value retrival. * If <code>keyTime == mnemonicTime</code> cached mnemonic value is returned. * @param keyTime time (java) of mnemonic request. * @param completionHolder completion holder that will be given completion. * NOTE: completion is passsed by reference, so do not change its value, * copy its value before and do it on a local copy * @return current property value. * @see getSync */ // TODO implement test with many threads calling this method... public Object mnemonicValue(long keyTime, CompletionHolder completionHolder) { // // cache lookup // for (;;) { // read mnemonic data lock try { mnemonicDataLock.readLock().lock(); } catch (Throwable th) { completionHolder.value = mnemonicCompletion; return mnemonicValue; /* return old */ } try { // if same time or newer exist return cached value if (keyTime <= mnemonicTime) { completionHolder.value = mnemonicCompletion; return mnemonicValue; } } finally { mnemonicDataLock.readLock().unlock(); } // read value wait, if reading is already pending synchronized (mnemonicValueRetrival) { // lock if not newer read if (keyTime <= mnemonicReadPending) { try { mnemonicValueRetrival.wait(); } catch (InterruptedException ie) {} // re-read again continue; } else { mnemonicReadPending = keyTime; break; } } } // // value retrival // Object retValue = null; try { retValue = getSync(completionHolder); } catch (AcsJException acsex) { retValue = defaultValue; completionHolder.value = CompletionUtil.generateCompletion(acsex); } catch (Throwable th) { retValue = defaultValue; completionHolder.value = CompletionUtil.generateCompletion( new AcsJUnknownEx("Failed to retrieve value.", th)); } // // value memorization // // write mnemonic data lock try { mnemonicDataLock.writeLock().lock(); } catch (Throwable th) { return mnemonicValue; /* return old */ } try { if (keyTime > mnemonicTime) { mnemonicTime = keyTime; mnemonicValue = retValue; mnemonicCompletion = completionHolder.value; } return mnemonicValue; } finally { mnemonicDataLock.writeLock().unlock(); // read value wait release synchronized (mnemonicValueRetrival) { mnemonicValueRetrival.notifyAll(); } } } }
LGPL/CommonSoftware/jbaci/src/alma/ACS/impl/CommonPropertyImpl.java
/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package alma.ACS.impl; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.NO_RESOURCES; import org.omg.PortableServer.Servant; import alma.ACS.CBDescIn; import alma.ACS.CBvoid; import alma.ACS.Callback; import alma.ACS.Monitor; import alma.ACS.MonitorHelper; import alma.ACS.MonitorOperations; import alma.ACS.NoSuchCharacteristic; import alma.ACS.TimeSeqHolder; import alma.ACS.jbaci.BACIAction; import alma.ACS.jbaci.BACIPriority; import alma.ACS.jbaci.CallbackDispatcher; import alma.ACS.jbaci.CompletionUtil; import alma.ACS.jbaci.DataAccess; import alma.ACS.jbaci.MemoryDataAccess; import alma.ACS.jbaci.PropertyInitializationFailed; import alma.ACSErr.Completion; import alma.ACSErr.CompletionHolder; import alma.ACSErrTypeCommon.wrappers.AcsJCouldntPerformActionEx; import alma.ACSErrTypeCommon.wrappers.AcsJUnknownEx; import alma.acs.exceptions.AcsJException; /** * Implementation of common property, i.e. type of <code>java.lang.Object</code>. * @author <a href="mailto:matej.sekoranjaATcosylab.com">Matej Sekoranja</a> * @version $id$ */ public abstract class CommonPropertyImpl extends TypelessPropertyImpl implements CallbackDispatcher { /** * Default timer trigger (in 100ns units). */ protected long defaultTimerTrigger; /** * Min timer trigger (in 100ns units). */ protected long minTimerTrigger; /** * Default value. */ protected Object defaultValue; /** * Read-only data access. */ protected DataAccess dataAccess; /** * Property <code>Class</code> type. */ protected Class propertyType; /** * History size, if 0 history is disabled. */ protected int historySize; /** * Pointer in history arrays, points to first empty element. */ protected int historyPosition; /** * <code>true</code>, if values in history arrays exceed end of arrays (circular arrays). */ protected boolean historyTurnaround; /** * Array of history values. */ protected Object historyValue; /** * Array of history times (OMG standard time). */ protected long[] historyTime; /** * List of all property monitors (needed on property destruction). */ protected Map monitors; /************ [ Mnemonic value retrival mechanism ] ************/ /** * Mnemonic read time key of (last) pending read. */ protected long mnemonicReadPending = 0; /** * Mnemonic read lock (dummy object). */ protected Object mnemonicValueRetrival = new Object(); /** * Mnemonic variables lock. */ protected ReadWriteLock mnemonicDataLock = new ReentrantReadWriteLock(); /** * Time "key" (Java) if when last mnemonic retrival. */ protected long mnemonicTime; /** * Value of latest mnemonic value retrival. */ protected Object mnemonicValue; /** * Completion of latest mnemonic value retrival. */ protected Completion mnemonicCompletion; /***************************************************************/ /** * Constructor with memory data access. * @param propertyType property <code>Class</code> type, non-<code>null</code>. * @param name property name, non-<code>null</code>. * @param parentComponent parent component, non-<code>null</code>. * @throws PropertyInitializationFailed exception is thrown on failure */ public CommonPropertyImpl( Class propertyType, String name, CharacteristicComponentImpl parentComponent) throws PropertyInitializationFailed { this(propertyType, name, parentComponent, new MemoryDataAccess()); } /** * Constructor. * @param propertyType property <code>Class</code> type, non-<code>null</code>. * @param name property name, non-<code>null</code>. * @param parentComponent parent component, non-<code>null</code>. * @param dataAccess read-write data access to be use, non-<code>null</code>. * @throws PropertyInitializationFailed exception is thrown on failure */ public CommonPropertyImpl( Class propertyType, String name, CharacteristicComponentImpl parentComponent, DataAccess dataAccess) throws PropertyInitializationFailed { super(name, parentComponent); this.propertyType = propertyType; this.dataAccess = dataAccess; // TODO to be configurable historySize = 32; historyPosition = 0; historyTurnaround = false; historyTime = new long[historySize]; historyValue = Array.newInstance(propertyType, historySize); // initialize data access, if required if (dataAccess.initializeValue()) { try { CompletionHolder completionHolder = CompletionUtil.createCompletionHolder(); dataAccess.set(defaultValue, completionHolder); // TODO error log (only warning) } catch (Throwable th) { // TODO error log (only warning) } } // create monitor data structure monitors = new HashMap(); // create history monitor registerMonitor(new HistoryMonitorImpl(this), null); } /** * Read property characteristics. * @throws PropertyInitializationFailed exception is thrown on failure */ public void readCharacteristics() throws PropertyInitializationFailed { super.readCharacteristics(); try { // defaultTimerTrigger = characteristicModelImpl.getLong("default_timer_trig"); // minTimerTrigger = characteristicModelImpl.getLong("min_timer_trig"); defaultTimerTrigger = (long)(characteristicModelImpl.getDouble("default_timer_trig")*10000000L); minTimerTrigger = (long)(characteristicModelImpl.getDouble("min_timer_trig")*10000000L); defaultValue = readPropertyTypeCharacteristic("default_value"); } catch (Throwable t) { throw new PropertyInitializationFailed("Failed to read all property characteristics.", t); } } /** * Get property data access layer. * @return property data access. */ public DataAccess getDataAccess() { return dataAccess; } /** * @see alma.ACS.PropertyImpl#destroy() */ public void destroy() { super.destroy(); // destroy all monitors if (monitors.size() != 0) { MonitorOperations[] monitorArray = null; synchronized (monitors) { monitorArray = new MonitorOperations[monitors.size()]; monitors.keySet().toArray(monitorArray); } for (int i = 0; i < monitorArray.length; i++) { try { monitorArray[i].destroy(); } catch (Throwable th) { // TODO or even log here th.printStackTrace(); } } } } /*********************** [ P<type> ] ***********************/ /** * @see alma.ACS.P<type>Operations#default_timer_trigger() */ public long default_timer_trigger() { return defaultTimerTrigger; } /** * @see alma.ACS.P<type>Operations#min_timer_trigger() */ public long min_timer_trigger() { return minTimerTrigger; } /*********************** [ P<type> helpers ] ***********************/ /** * Read property type characteristic. * @throws NoSuchCharacteristic is thrown if characterstic does not exist. */ public abstract Object readPropertyTypeCharacteristic(String name) throws NoSuchCharacteristic; /** * Add value to the history. * @param value value to be added to the history. * @param timestamp value timestamp (OMG) to be added to the history. */ protected void addValueToHistory(Object value, long timestamp) { // if history is disabled if (historySize == 0) return; synchronized (historyValue) { // add historyTime[historyPosition] = timestamp; // historyValue[historyPosition] = value; if (propertyType.isPrimitive()) { // primitives are really ugly to handle // order must match probability... if (propertyType.isAssignableFrom(double.class)) Array.setDouble(historyValue, historyPosition, ((Double)value).doubleValue()); else if (propertyType.isAssignableFrom(int.class)) Array.setInt(historyValue, historyPosition, ((Integer)value).intValue()); else if (propertyType.isAssignableFrom(long.class)) Array.setLong(historyValue, historyPosition, ((Long)value).longValue()); else if (propertyType.isAssignableFrom(short.class)) Array.setShort(historyValue, historyPosition, ((Short)value).shortValue()); else if (propertyType.isAssignableFrom(boolean.class)) Array.setBoolean(historyValue, historyPosition, ((Boolean)value).booleanValue()); else if (propertyType.isAssignableFrom(byte.class)) Array.setByte(historyValue, historyPosition, ((Byte)value).byteValue()); else if (propertyType.isAssignableFrom(float.class)) Array.setFloat(historyValue, historyPosition, ((Float)value).floatValue()); else if (propertyType.isAssignableFrom(char.class)) Array.setChar(historyValue, historyPosition, ((Character)value).charValue()); else // TODO log "Unhandled primitive" error - should never happen System.err.println("Unhandled primitive."); } else Array.set(historyValue, historyPosition, value); // manage control variables historyPosition = ++historyPosition % historySize; if (!historyTurnaround && historyPosition == 0) historyTurnaround = true; } } protected Object getHistory(int lastValues, TimeSeqHolder timeSeqHolder) { // check bad parameter if (lastValues < 0) throw new BAD_PARAM("lastValues < 0"); synchronized (historyValue) { int length, first; if (historyTurnaround) { length = historySize; first = historyPosition; } else { length = historyPosition; first = 0; } // last n values (and not first n values) if (lastValues > length) lastValues = length; first = (first + length - lastValues) % historySize; // get required number of values if (lastValues < length) length = lastValues; timeSeqHolder.value = new long[length]; Object values = Array.newInstance(propertyType, length); // no history case if (length == 0) return values; // copy if (first + length < historySize) { System.arraycopy(historyTime, first, timeSeqHolder.value, 0, length); System.arraycopy(historyValue, first, values, 0, length); } else { int split = historySize - first; System.arraycopy(historyTime, first, timeSeqHolder.value, 0, split); System.arraycopy(historyValue, first, values, 0, split); System.arraycopy(historyTime, 0, timeSeqHolder.value, split, length - split); System.arraycopy(historyValue, 0, values, split, length - split); } return values; } } /** * @see alma.ACS.P<type>Operations#get_sync(alma.ACSErr.CompletionHolder) */ protected Object getSync(CompletionHolder completionHolder) throws AcsJException { try { Object retVal = dataAccess.get(completionHolder); // generate no-error completion, if not generated if (completionHolder.value == null) completionHolder.value = CompletionUtil.generateNoErrorCompletion(); return retVal; } catch (AcsJException acsex) { throw new AcsJCouldntPerformActionEx("Failed to retrieve value.", acsex); } } /** * BACI action to invoke <code>getSync</code> asynchroniously. */ protected class GetAsyncAction extends BACIAction { /** * @see alma.ACS.jbaci.BACIAction */ public GetAsyncAction(Callback callback, CBDescIn descIn) { super(getParentComponent(), callback, descIn, CommonPropertyImpl.this); } /** * @see alma.ACS.jbaci.BACIAction */ public GetAsyncAction( Callback callback, CBDescIn descIn, BACIPriority priority) { super(getParentComponent(), callback, descIn, CommonPropertyImpl.this, priority); } /** * @see alma.ACS.jbaci.BACIAction#execute() */ public Object execute() throws AcsJException { try { CompletionHolder completionHolder = CompletionUtil.createCompletionHolder(); Object retVal = getSync(completionHolder); // set completion this.completion = completionHolder.value; return retVal; } catch (AcsJException acsex) { // send default value in case of failure this.returnValue = defaultValue; throw new AcsJCouldntPerformActionEx("Failed to retrieve value asynchroniously.", acsex); } } } /** * @see alma.ACS.P<type>Operations#get_async(alma.ACS.CB<type>, alma.ACS.CBDescIn) */ protected void getAsync(Callback callback, CBDescIn desc) { new GetAsyncAction(callback, desc).submit(); } /** * Register monitor on this property (and optionally CORBA activate). * Registration is needed for monitor destruction on property destruction. * @param monitorImpl monitor implementation (e.g. class implementing <code>MonitorOperations</code> interface). * @param monitorServant monitor CORBA servant (e.g. Monitor<type>POATie class). If <code>null</code> monitor will * be threated as non-CORBA monitor and no CORBA activation will be done. * @return CORBA activated monitor reference, <code>null</code> if <code>monitorServant == null</code>. */ public Monitor registerMonitor(MonitorOperations monitorImpl, Servant monitorServant) { // allow activation if already in monitor list... Monitor monitor = null; if (monitorServant != null) { try { // TODO pesistent, user ID activation monitor = MonitorHelper.narrow( parentComponent.getComponentContainerServices().activateOffShoot(monitorServant) ); } catch (Throwable th) { // TODO log throw new NO_RESOURCES(th.getMessage()); } } // add to list synchronized (monitors) { if (!monitors.containsKey(monitorImpl)) monitors.put(monitorImpl, monitorServant); } return monitor; } /** * Unregister monitor on this property (and optionally CORBA deactivate). * Should be called by <code>MonitorOperations.destroy()</code> method. */ public void unregisterMonitor(MonitorOperations monitorImpl) { Servant monitorServant = null; // remove from list synchronized (monitors) { monitorServant = (Servant)monitors.remove(monitorImpl); } // deativate CORBA monitor servant if (monitorServant != null) { try { parentComponent.getComponentContainerServices().deactivateOffShoot(monitorServant); } catch (Throwable th) { // TODO log th.printStackTrace(); } } } /*********************** [ RW<type> helpers ] ***********************/ /** * @see alma.ACSErr.Completion alma.ACS.RW<type>Operations#set_sync(<type>) */ protected Completion setSync(Object value) throws AcsJException { // TODO should we check limits here try { CompletionHolder completionHolder = CompletionUtil.createCompletionHolder(); dataAccess.set(value, completionHolder); // generate no-error completion, if not generated if (completionHolder.value == null) completionHolder.value = CompletionUtil.generateNoErrorCompletion(); return completionHolder.value; } catch (AcsJException acsex) { throw new AcsJCouldntPerformActionEx("Failed to set value.", acsex); } } /** * BACI action to invoke <code>setSync</code> asynchroniously. */ protected class SetAsyncAction extends BACIAction { /** * Value to be set. */ Object value; /** * @see alma.ACS.jbaci.BACIAction */ public SetAsyncAction(Object value, Callback callback, CBDescIn descIn) { super(getParentComponent(), callback, descIn, CommonPropertyImpl.this); this.value = value; } /** * @see alma.ACS.jbaci.BACIAction */ public SetAsyncAction( Object value, Callback callback, CBDescIn descIn, BACIPriority priority) { super(getParentComponent(), callback, descIn, CommonPropertyImpl.this, priority); this.value = value; } /** * @see alma.ACS.jbaci.BACIAction#execute() */ public Object execute() throws AcsJException { try { completion = setSync(value); } catch (AcsJException acsex) { throw new AcsJCouldntPerformActionEx("Failed to set value asynchroniously.", acsex); } // no return value return null; } } /** * @see alma.ACS.RW<type>Operations#get_async(<type>, alma.ACS.CBvoid, alma.ACS.CBDescIn) */ protected void setAsync(Object value, CBvoid callback, CBDescIn desc) { new SetAsyncAction(value, callback, desc).submit(); } /** * @see void alma.ACS.RW<type>Operations#set_nonblocking(<type>) */ protected void setNonblocking(Object value) { try { setSync(value); } catch (Throwable th) { // TODO log } } /** * Mnemonic value retrival. * If <code>keyTime == mnemonicTime</code> cached mnemonic value is returned. * @param keyTime time (java) of mnemonic request. * @param completionHolder completion holder that will be given completion. * NOTE: completion is passsed by reference, so do not change its value, * copy its value before and do it on a local copy * @return current property value. * @see getSync */ // TODO implement test with many threads calling this method... public Object mnemonicValue(long keyTime, CompletionHolder completionHolder) { // // cache lookup // for (;;) { // read mnemonic data lock try { mnemonicDataLock.readLock().lock(); } catch (Throwable th) { completionHolder.value = mnemonicCompletion; return mnemonicValue; /* return old */ } try { // if same time or newer exist return cached value if (keyTime <= mnemonicTime) { completionHolder.value = mnemonicCompletion; return mnemonicValue; } } finally { mnemonicDataLock.readLock().unlock(); } // read value wait, if reading is already pending synchronized (mnemonicValueRetrival) { // lock if not newer read if (keyTime <= mnemonicReadPending) { try { mnemonicValueRetrival.wait(); } catch (InterruptedException ie) {} // re-read again continue; } else { mnemonicReadPending = keyTime; break; } } } // // value retrival // Object retValue = null; try { retValue = getSync(completionHolder); } catch (AcsJException acsex) { retValue = defaultValue; completionHolder.value = CompletionUtil.generateCompletion(acsex); } catch (Throwable th) { retValue = defaultValue; completionHolder.value = CompletionUtil.generateCompletion( new AcsJUnknownEx("Failed to retrieve value.", th)); } // // value memorization // // write mnemonic data lock try { mnemonicDataLock.writeLock().lock(); } catch (Throwable th) { return mnemonicValue; /* return old */ } try { if (keyTime > mnemonicTime) { mnemonicTime = keyTime; mnemonicValue = retValue; mnemonicCompletion = completionHolder.value; } return mnemonicValue; } finally { mnemonicDataLock.writeLock().unlock(); // read value wait release synchronized (mnemonicValueRetrival) { mnemonicValueRetrival.notifyAll(); } } } }
jbaci: some logs git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@103571 523d945c-050c-4681-91ec-863ad3bb968a
LGPL/CommonSoftware/jbaci/src/alma/ACS/impl/CommonPropertyImpl.java
jbaci: some logs
Java
apache-2.0
ced0bfba2f7af45ded23629f3639d065289d7380
0
AmauryEsparza/retrofit,hgl888/retrofit,pitatensai/retrofit,dlew/retrofit,Heart2009/retrofit,maduhu/retrofit,viacheslavokolitiy/retrofit,xfumihiro/retrofit,JunyiZhou/retrofit,dmitryustimov/retrofit,sarvex/retrofit,nsmolenskii/retrofit,messipuyol/retrofit,shauvik/retrofit,pmk2429/retrofit,juliendn/retrofit,checkdroid/retrofit,Gaantz/retrofit,bestwpw/retrofit,MaTriXy/retrofit,jimxj/retrofit,ggchxx/retrofit,bestwpw/retrofit,ltshddx/retrofit,promeG/retrofit,ajju4455/retrofit,MaTriXy/retrofit,lncosie/retrofit,lncosie/retrofit,segmentio/retrofit,NightlyNexus/retrofit,YlJava110/retrofit,mbStavola/retrofit,msdgwzhy6/retrofit,ChinaKim/retrofit,sunios/retrofit,Pannarrow/retrofit,junenn/retrofit,melbic/retrofit,andypliu/retrofit,wanjingyan001/retrofit,aurae/retrofit,wlrhnh-David/retrofit,pmk2429/retrofit,davidcrotty/retrofit,viacheslavokolitiy/retrofit,java02014/retrofit,iagreen/retrofit,c0deh4xor/retrofit,ruhaly/retrofit,messipuyol/retrofit,leasual/retrofit,sunios/retrofit,cnso/retrofit,larsgrefer/retrofit,dmitryustimov/retrofit,YOLOSPAGHETTI/final-project,guoGavin/retrofit,Heart2009/retrofit,larsgrefer/retrofit,Sellegit/retrofit,Gaantz/retrofit,leasual/retrofit,geekinpink/retrofit,shauvik/retrofit,zero21ke/retrofit,ltshddx/retrofit,siilobv/retrofit,ianrumac/retrofit,shihabmi7/retrofit,wlrhnh-David/retrofit,AungWinnHtut/retrofit,airbnb/retrofit,ianrumac/retrofit,AungWinnHtut/retrofit,xfumihiro/retrofit,davidcrotty/retrofit,mbStavola/retrofit,tmxdyf/retrofit,andforce/retrofit,jimxj/retrofit,thangtc/retrofit,promeG/retrofit,zace-yuan/retrofit,elijah513/retrofit,c0deh4xor/retrofit,jianxiansining/retrofit,messipuyol/retrofit,nsmolenskii/retrofit,lemaiyan/retrofit,zero21ke/retrofit,timehop/retrofit,JunyiZhou/retrofit,b-cuts/retrofit,yuhuayi/retrofit,andforce/retrofit,pitatensai/retrofit,lncosie/retrofit,airbnb/retrofit,J-Sizzle/retrofit,zhupengGitHub/retrofit,WiiliamChik/retrofit,YlJava110/retrofit,vignesh-iopex/retrofit,f2prateek/retrofit,Appstrakt/retrofit,xsingHu/retrofit,elijah513/retrofit,sunios/retrofit,murat8505/REST_client_retrofit,google/retrofit,Gary111/retrofit,c0deh4xor/retrofit,iagreen/retrofit,chundongwang/retrofit,dlew/retrofit,yongjhih/retrofit2,barodapride/retrofit,iagreen/retrofit,sarvex/retrofit,YOLOSPAGHETTI/final-project,murat8505/REST_client_retrofit,murat8505/REST_client_retrofit,junenn/retrofit,zhupengGitHub/retrofit,Appstrakt/retrofit,loiclefloch/retrofit,maduhu/retrofit,squery/retrofit,loiclefloch/retrofit,aurae/retrofit,barodapride/retrofit,timehop/retrofit,noikiy/retrofit,xsingHu/retrofit,J-Sizzle/retrofit,xiaomeixw/NotRetrofit,enieber/retrofit,zace-yuan/retrofit,bhargav1/retrofit,andforce/retrofit,ChinaKim/retrofit,f2prateek/retrofit,equinoxel/retrofit,avbk/retrofit,xiaozuzu/retrofit,GovindaPaliwal/retrofit,java02014/retrofit,PlumaBrava/retrofit,janzoner/retrofit,sitexa/retrofit,xfumihiro/retrofit,b-cuts/retrofit,davidcrotty/retrofit,siilobv/retrofit,deshion/retrofit,TomkeyZhang/retrofit,cnso/retrofit,chundongwang/retrofit,square/retrofit,lichblitz/retrofit,shihabmi7/retrofit,shermax/retrofit,AungWinnHtut/retrofit,zhupengGitHub/retrofit,maany/retrofit,renatohsc/retrofit,YlJava110/retrofit,yuhuayi/retrofit,Pannarrow/retrofit,yoslabs/retrofit,msdgwzhy6/retrofit,zheng1733/retrofit,aurae/retrofit,juliendn/retrofit,mbStavola/retrofit,jimxj/retrofit,sitexa/retrofit,deshion/retrofit,dlew/retrofit,xsingHu/retrofit,enieber/retrofit,squery/retrofit,msdgwzhy6/retrofit,FilippoMito/retrofit,java02014/retrofit,square/retrofit,checkdroid/retrofit,guoGavin/retrofit,bhargav1/retrofit,yoslabs/retrofit,squery/retrofit,junenn/retrofit,thangtc/retrofit,renatohsc/retrofit,zheng1733/retrofit,cnso/retrofit,janzoner/retrofit,vignesh-iopex/retrofit,Sellegit/retrofit,segmentio/retrofit,WiiliamChik/retrofit,melbic/retrofit,hgl888/retrofit,ztelur/retrofit,yoslabs/retrofit,wlrhnh-David/retrofit,vignesh-iopex/retrofit,andypliu/retrofit,shermax/retrofit,GovindaPaliwal/retrofit,geekinpink/retrofit,zheng1733/retrofit,vamsirajendra/retrofit,equinoxel/retrofit,huihui4045/retrofit,10045125/retrofit,loiclefloch/retrofit,Gaantz/retrofit,Jackear/retrofit,jianxiansining/retrofit,checkdroid/retrofit,f2prateek/retrofit,b-cuts/retrofit,square/retrofit,J-Sizzle/retrofit,andypliu/retrofit,viacheslavokolitiy/retrofit,xiaozuzu/retrofit,melbic/retrofit,dmitryustimov/retrofit,ztelur/retrofit,ajju4455/retrofit,sitexa/retrofit,ggchxx/retrofit,jianxiansining/retrofit,barodapride/retrofit,janzoner/retrofit,lgx0955/retrofit,siilobv/retrofit,google/retrofit,ChinaKim/retrofit,nsmolenskii/retrofit,tmxdyf/retrofit,larsgrefer/retrofit,fjg1989/retrofit,noikiy/retrofit,wanjingyan001/retrofit,GovindaPaliwal/retrofit,lgx0955/retrofit,maany/retrofit,vamsirajendra/retrofit,ztelur/retrofit,square/retrofit,avbk/retrofit,WiiliamChik/retrofit,PlumaBrava/retrofit,maany/retrofit,lemaiyan/retrofit,Pannarrow/retrofit,equinoxel/retrofit,chundongwang/retrofit,NightlyNexus/retrofit,leasual/retrofit,ianrumac/retrofit,NikoYuwono/retrofit,ggchxx/retrofit,ze-pequeno/retrofit,enieber/retrofit,lichblitz/retrofit,bestwpw/retrofit,sarvex/retrofit,lemaiyan/retrofit,yongjhih/NotRetrofit,zero21ke/retrofit,promeG/retrofit,artem-zinnatullin/retrofit,ze-pequeno/retrofit,NikoYuwono/retrofit,pmk2429/retrofit,noikiy/retrofit,shauvik/retrofit,ruhaly/retrofit,lichblitz/retrofit,michelangelo13/retrofit,MaTriXy/retrofit,artem-zinnatullin/retrofit,FilippoMito/retrofit,YOLOSPAGHETTI/final-project,FilippoMito/retrofit,deshion/retrofit,fjg1989/retrofit,geekinpink/retrofit,Appstrakt/retrofit,vabym8/NotRetrofit,thangtc/retrofit,AmauryEsparza/retrofit,michelangelo13/retrofit,maduhu/retrofit,renatohsc/retrofit,guoGavin/retrofit,huihui4045/retrofit,ajju4455/retrofit,fjg1989/retrofit,Jackear/retrofit,Jackear/retrofit,wanjingyan001/retrofit,michelangelo13/retrofit,Gary111/retrofit,shermax/retrofit,artem-zinnatullin/retrofit,Sellegit/retrofit,yuhuayi/retrofit,NightlyNexus/retrofit,zace-yuan/retrofit,ze-pequeno/retrofit,ze-pequeno/retrofit,tmxdyf/retrofit,hgl888/retrofit,juliendn/retrofit,Heart2009/retrofit,ltshddx/retrofit,avbk/retrofit,bhargav1/retrofit,TomkeyZhang/retrofit,huihui4045/retrofit,xiaozuzu/retrofit,segmentio/retrofit,10045125/retrofit,vamsirajendra/retrofit,shihabmi7/retrofit,lgx0955/retrofit,elijah513/retrofit,Gary111/retrofit,airbnb/retrofit,ruhaly/retrofit,pitatensai/retrofit,PlumaBrava/retrofit,NikoYuwono/retrofit,JunyiZhou/retrofit
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit.mime; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.UUID; public final class MultipartTypedOutput implements TypedOutput { private static final class MimePart { private final TypedOutput body; private final String name; private final boolean isFirst; private final String boundary; private byte[] partBoundary; private byte[] partHeader; private boolean isBuilt; public MimePart(String name, TypedOutput body, String boundary, boolean isFirst) { this.name = name; this.body = body; this.isFirst = isFirst; this.boundary = boundary; } public void writeTo(OutputStream out) throws IOException { build(); out.write(partBoundary); out.write(partHeader); body.writeTo(out); } public long size() { build(); if (body.length() > -1) { return body.length() + partBoundary.length + partHeader.length; } else { return -1; } } private void build() { if (isBuilt) return; partBoundary = buildBoundary(boundary, isFirst, false); partHeader = buildHeader(name, body); isBuilt = true; } } private final List<MimePart> mimeParts = new LinkedList<MimePart>(); private final byte[] footer; private final String boundary; private long length; public MultipartTypedOutput() { this(UUID.randomUUID().toString()); } MultipartTypedOutput(String boundary) { this.boundary = boundary; footer = buildBoundary(boundary, false, true); length = footer.length; } List<byte[]> getParts() throws IOException { List<byte[]> parts = new ArrayList<byte[]>(mimeParts.size()); for (MimePart part : mimeParts) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); part.writeTo(bos); parts.add(bos.toByteArray()); } return parts; } public void addPart(String name, TypedOutput body) { if (name == null) { throw new NullPointerException("Part name must not be null."); } if (body == null) { throw new NullPointerException("Part body must not be null."); } MimePart part = new MimePart(name, body, boundary, mimeParts.isEmpty()); mimeParts.add(part); length += part.size(); } public int getPartCount() { return mimeParts.size(); } @Override public String fileName() { return null; } @Override public String mimeType() { return "multipart/form-data; boundary=" + boundary; } @Override public long length() { return length; } @Override public void writeTo(OutputStream out) throws IOException { for (MimePart part : mimeParts) { part.writeTo(out); } out.write(footer); } private static byte[] buildBoundary(String boundary, boolean first, boolean last) { try { StringBuilder sb = new StringBuilder(); if (!first) { sb.append("\r\n"); } sb.append("--"); sb.append(boundary); if (last) { sb.append("--"); } else { sb.append("\r\n"); } return sb.toString().getBytes("UTF-8"); } catch (IOException ex) { throw new RuntimeException("Unable to write multipart boundary", ex); } } private static byte[] buildHeader(String name, TypedOutput value) { try { StringBuilder headers = new StringBuilder(); headers.append("Content-Disposition: form-data; name=\""); headers.append(name); if (value.fileName() != null) { headers.append("\"; filename=\""); headers.append(value.fileName()); } headers.append("\"\r\nContent-Type: "); headers.append(value.mimeType()); if (value.length() != -1) { headers.append("\r\nContent-Length: ").append(value.length()); } headers.append("\r\nContent-Transfer-Encoding: binary\r\n\r\n"); return headers.toString().getBytes("UTF-8"); } catch (IOException ex) { throw new RuntimeException("Unable to write multipart header", ex); } } }
retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit.mime; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.UUID; public final class MultipartTypedOutput implements TypedOutput { private static final class MimePart { private final TypedOutput body; private final String name; private final boolean isFirst; private final String boundary; private byte[] partBoundary; private byte[] partHeader; private boolean isBuilt; public MimePart(String name, TypedOutput body, String boundary, boolean isFirst) { this.name = name; this.body = body; this.isFirst = isFirst; this.boundary = boundary; } public void writeTo(OutputStream out) throws IOException { build(); out.write(partBoundary); out.write(partHeader); body.writeTo(out); } public long size() { build(); if (body.length() > -1) { return body.length() + partBoundary.length + partHeader.length; } else { return -1; } } private void build() { if (isBuilt) return; partBoundary = buildBoundary(boundary, isFirst, false); partHeader = buildHeader(name, body); isBuilt = true; } } private final List<MimePart> mimeParts = new LinkedList<MimePart>(); private final byte[] footer; private final String boundary; private long length; public MultipartTypedOutput() { this(UUID.randomUUID().toString()); } MultipartTypedOutput(String boundary) { this.boundary = boundary; footer = buildBoundary(boundary, false, true); length = footer.length; } public List<byte[]> getParts() throws IOException { List<byte[]> parts = new ArrayList<byte[]>(mimeParts.size()); for (MimePart part : mimeParts) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); part.writeTo(bos); parts.add(bos.toByteArray()); } return parts; } public void addPart(String name, TypedOutput body) { if (name == null) { throw new NullPointerException("Part name must not be null."); } if (body == null) { throw new NullPointerException("Part body must not be null."); } MimePart part = new MimePart(name, body, boundary, mimeParts.isEmpty()); mimeParts.add(part); length += part.size(); } public int getPartCount() { return mimeParts.size(); } @Override public String fileName() { return null; } @Override public String mimeType() { return "multipart/form-data; boundary=" + boundary; } @Override public long length() { return length; } @Override public void writeTo(OutputStream out) throws IOException { for (MimePart part : mimeParts) { part.writeTo(out); } out.write(footer); } private static byte[] buildBoundary(String boundary, boolean first, boolean last) { try { StringBuilder sb = new StringBuilder(); if (!first) { sb.append("\r\n"); } sb.append("--"); sb.append(boundary); if (last) { sb.append("--"); } else { sb.append("\r\n"); } return sb.toString().getBytes("UTF-8"); } catch (IOException ex) { throw new RuntimeException("Unable to write multipart boundary", ex); } } private static byte[] buildHeader(String name, TypedOutput value) { try { StringBuilder headers = new StringBuilder(); headers.append("Content-Disposition: form-data; name=\""); headers.append(name); if (value.fileName() != null) { headers.append("\"; filename=\""); headers.append(value.fileName()); } headers.append("\"\r\nContent-Type: "); headers.append(value.mimeType()); if (value.length() != -1) { headers.append("\r\nContent-Length: ").append(value.length()); } headers.append("\r\nContent-Transfer-Encoding: binary\r\n\r\n"); return headers.toString().getBytes("UTF-8"); } catch (IOException ex) { throw new RuntimeException("Unable to write multipart header", ex); } } }
using package scope for method
retrofit/src/main/java/retrofit/mime/MultipartTypedOutput.java
using package scope for method
Java
apache-2.0
68edfd56919528f200b771f858acb3b125c17097
0
jentrialgo/imovil2014
/* Copyright 2014 Profesores y alumnos de la asignatura Informática Móvil de la EPI de Gijón Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package es.uniovi.imovil.fcrtrainer; import com.google.android.gms.analytics.GoogleAnalytics; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.widget.DrawerLayout; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { /** * Nombre del fichero de preferencias. */ private static final String PREFERENCES = "preferences"; /** * Preferencia donde se almacena el último ejercicio accedido. */ private static final String LAST_EXERCISE = "last_exercise"; /** * Preferencia que indica que el usuario sabe manejar el drawer. La guía de * Android recomienda mostrar el Drawer abierto hasta que el usuario lo haya * desplegado al menos una vez. */ private static final String USER_LEARNED_DRAWER = "user_learned_drawer"; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; private Screen mExercise; private boolean mUserLearnedDrawer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mTitle = getTitle(); mDrawerTitle = mTitle; boolean fromSavedInstanceState = false; int exerciseOrdinal; if (savedInstanceState != null) { // Recuperar el estado tras una interrupción exerciseOrdinal= savedInstanceState.getInt(LAST_EXERCISE); mUserLearnedDrawer = savedInstanceState.getBoolean(USER_LEARNED_DRAWER); fromSavedInstanceState = true; } else { // Restaurar el estado desde las preferencias SharedPreferences prefs = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); exerciseOrdinal = prefs.getInt(LAST_EXERCISE, Screen.BINARY.ordinal()); mUserLearnedDrawer = prefs.getBoolean(USER_LEARNED_DRAWER, false); } if (exerciseOrdinal >= Screen.values().length) { // Esto puede ocurrir cuando cambia el número de ejercicios en una actualización exerciseOrdinal = Screen.BINARY.ordinal(); } mExercise = Screen.values()[exerciseOrdinal]; // Cargo el fragmento con el contenido if (savedInstanceState == null) updateContentFragment(); initializeDrawer(fromSavedInstanceState); } @Override public void onPause() { super.onPause(); // Guardar las preferencias SharedPreferences prefs = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putInt(LAST_EXERCISE, mExercise.ordinal()); prefsEditor.putBoolean(USER_LEARNED_DRAWER, mUserLearnedDrawer); prefsEditor.apply(); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); // Guardar el estado de la actividad savedInstanceState.putInt(LAST_EXERCISE, mExercise.ordinal()); savedInstanceState.putBoolean(USER_LEARNED_DRAWER, mUserLearnedDrawer); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflar el menú if (isDrawerOpen()) { // TODO: Si el Drawer está desplegado no deben mostrarse iconos de // acción getMenuInflater().inflate(R.menu.main, menu); } else { getMenuInflater().inflate(R.menu.main, menu); } return true; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } switch(item.getItemId()){ case R.id.action_settings: Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); break; case R.id.action_help: Intent goToHelp = new Intent(this, HelpActivity.class); startActivity(goToHelp); break; } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } @Override public void setTitle(CharSequence title) { mTitle = title; getSupportActionBar().setTitle(mTitle); } public boolean isDrawerOpen() { return mDrawerLayout.isDrawerOpen(GravityCompat.START); } private void updateContentFragment() { Fragment fragment = mExercise.toFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.content_frame, fragment, "Hola"); fragmentTransaction.commit(); } private void initializeDrawer(boolean fromSavedState) { mDrawerLayout = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); // Mostrar el icono del drawer final ActionBar actionBar = getSupportActionBar(); mDrawerToggle = new ActionBarDrawerToggle(this, // Actividad que lo aloja mDrawerLayout, // El layout R.string.drawer_open, R.string.drawer_close) { // Se llama cuando el Drawer se acaba de cerrar public void onDrawerClosed(View view) { super.onDrawerClosed(view); actionBar.setTitle(mTitle); // Actualizar las acciones en el Action Bar supportInvalidateOptionsMenu(); } // Se llama cuando el Drawer se acaba de abrir public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); actionBar.setTitle(mDrawerTitle); // Actualizar las acciones en el Action Bar mUserLearnedDrawer = true; supportInvalidateOptionsMenu(); } }; // Si el usuario no ha desplegado alguna vez el Drawer mTitle = mExercise.toString(); if (!mUserLearnedDrawer && !fromSavedState) { mDrawerLayout.openDrawer(GravityCompat.START); actionBar.setTitle(mDrawerTitle); } else { setTitle(mTitle); } mDrawerLayout.addDrawerListener(mDrawerToggle); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } @Override protected void onStart() { super.onStart(); GoogleAnalytics.getInstance(this).reportActivityStart(this); } @Override protected void onStop() { super.onStop(); GoogleAnalytics.getInstance(this).reportActivityStop(this); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { mExercise = Screen.fromNavId(item.getItemId()); mTitle = mExercise.toString(); updateContentFragment(); mDrawerLayout.closeDrawer(GravityCompat.START); return false; } }
app/src/main/java/es/uniovi/imovil/fcrtrainer/MainActivity.java
/* Copyright 2014 Profesores y alumnos de la asignatura Informática Móvil de la EPI de Gijón Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package es.uniovi.imovil.fcrtrainer; import com.google.android.gms.analytics.GoogleAnalytics; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.widget.DrawerLayout; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { /** * Nombre del fichero de preferencias. */ private static final String PREFERENCES = "preferences"; /** * Preferencia donde se almacena el último ejercicio accedido. */ private static final String LAST_EXERCISE = "last_exercise"; /** * Preferencia que indica que el usuario sabe manejar el drawer. La guía de * Android recomienda mostrar el Drawer abierto hasta que el usuario lo haya * desplegado al menos una vez. */ private static final String USER_LEARNED_DRAWER = "user_learned_drawer"; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; private Screen mExercise; private boolean mUserLearnedDrawer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mTitle = getTitle(); mDrawerTitle = mTitle; boolean fromSavedInstanceState = false; int exerciseOrdinal; if (savedInstanceState != null) { // Recuperar el estado tras una interrupción exerciseOrdinal= savedInstanceState.getInt(LAST_EXERCISE); mUserLearnedDrawer = savedInstanceState.getBoolean(USER_LEARNED_DRAWER); fromSavedInstanceState = true; } else { // Restaurar el estado desde las preferencias SharedPreferences prefs = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); exerciseOrdinal = prefs.getInt(LAST_EXERCISE, Screen.BINARY.ordinal()); mUserLearnedDrawer = prefs.getBoolean(USER_LEARNED_DRAWER, false); } if (exerciseOrdinal > Screen.values().length) { // Esto puede ocurrir cuando cambia el número de ejercicios en una actualización exerciseOrdinal = Screen.BINARY.ordinal(); } mExercise = Screen.values()[exerciseOrdinal]; // Cargo el fragmento con el contenido if (savedInstanceState == null) updateContentFragment(); initializeDrawer(fromSavedInstanceState); } @Override public void onPause() { super.onPause(); // Guardar las preferencias SharedPreferences prefs = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putInt(LAST_EXERCISE, mExercise.ordinal()); prefsEditor.putBoolean(USER_LEARNED_DRAWER, mUserLearnedDrawer); prefsEditor.apply(); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); // Guardar el estado de la actividad savedInstanceState.putInt(LAST_EXERCISE, mExercise.ordinal()); savedInstanceState.putBoolean(USER_LEARNED_DRAWER, mUserLearnedDrawer); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflar el menú if (isDrawerOpen()) { // TODO: Si el Drawer está desplegado no deben mostrarse iconos de // acción getMenuInflater().inflate(R.menu.main, menu); } else { getMenuInflater().inflate(R.menu.main, menu); } return true; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } switch(item.getItemId()){ case R.id.action_settings: Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); break; case R.id.action_help: Intent goToHelp = new Intent(this, HelpActivity.class); startActivity(goToHelp); break; } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } @Override public void setTitle(CharSequence title) { mTitle = title; getSupportActionBar().setTitle(mTitle); } public boolean isDrawerOpen() { return mDrawerLayout.isDrawerOpen(GravityCompat.START); } private void updateContentFragment() { Fragment fragment = mExercise.toFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.content_frame, fragment, "Hola"); fragmentTransaction.commit(); } private void initializeDrawer(boolean fromSavedState) { mDrawerLayout = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); // Mostrar el icono del drawer final ActionBar actionBar = getSupportActionBar(); mDrawerToggle = new ActionBarDrawerToggle(this, // Actividad que lo aloja mDrawerLayout, // El layout R.string.drawer_open, R.string.drawer_close) { // Se llama cuando el Drawer se acaba de cerrar public void onDrawerClosed(View view) { super.onDrawerClosed(view); actionBar.setTitle(mTitle); // Actualizar las acciones en el Action Bar supportInvalidateOptionsMenu(); } // Se llama cuando el Drawer se acaba de abrir public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); actionBar.setTitle(mDrawerTitle); // Actualizar las acciones en el Action Bar mUserLearnedDrawer = true; supportInvalidateOptionsMenu(); } }; // Si el usuario no ha desplegado alguna vez el Drawer mTitle = mExercise.toString(); if (!mUserLearnedDrawer && !fromSavedState) { mDrawerLayout.openDrawer(GravityCompat.START); actionBar.setTitle(mDrawerTitle); } else { setTitle(mTitle); } mDrawerLayout.addDrawerListener(mDrawerToggle); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } @Override protected void onStart() { super.onStart(); GoogleAnalytics.getInstance(this).reportActivityStart(this); } @Override protected void onStop() { super.onStop(); GoogleAnalytics.getInstance(this).reportActivityStop(this); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { mExercise = Screen.fromNavId(item.getItemId()); mTitle = mExercise.toString(); updateContentFragment(); mDrawerLayout.closeDrawer(GravityCompat.START); return false; } }
Bugfix: un índice que estaba mal (se pasaba por uno)
app/src/main/java/es/uniovi/imovil/fcrtrainer/MainActivity.java
Bugfix: un índice que estaba mal (se pasaba por uno)
Java
apache-2.0
fb5ccc7d14003101c5df6832d5fb0ff7929de448
0
scorpionvicky/elasticsearch,gfyoung/elasticsearch,robin13/elasticsearch,uschindler/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra,GlenRSmith/elasticsearch,HonzaKral/elasticsearch,vroyer/elassandra,gingerwizard/elasticsearch,robin13/elasticsearch,gfyoung/elasticsearch,robin13/elasticsearch,vroyer/elassandra,scorpionvicky/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,nknize/elasticsearch,strapdata/elassandra,HonzaKral/elasticsearch,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,gfyoung/elasticsearch,nknize/elasticsearch,coding0011/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,HonzaKral/elasticsearch,gingerwizard/elasticsearch,gfyoung/elasticsearch,uschindler/elasticsearch,robin13/elasticsearch,uschindler/elasticsearch,HonzaKral/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra,nknize/elasticsearch,vroyer/elassandra,strapdata/elassandra,gingerwizard/elasticsearch,coding0011/elasticsearch,uschindler/elasticsearch,coding0011/elasticsearch,uschindler/elasticsearch,scorpionvicky/elasticsearch,coding0011/elasticsearch,strapdata/elassandra,scorpionvicky/elasticsearch,gingerwizard/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,nknize/elasticsearch,coding0011/elasticsearch
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.license; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.action.support.PlainListenableActionFuture; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.license.License.OperationMode; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.transport.Transport; import org.elasticsearch.xpack.TestXPackTransportClient; import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.ml.action.CloseJobAction; import org.elasticsearch.xpack.ml.action.DeleteDatafeedAction; import org.elasticsearch.xpack.ml.action.DeleteJobAction; import org.elasticsearch.xpack.ml.action.GetJobsStatsAction; import org.elasticsearch.xpack.ml.action.OpenJobAction; import org.elasticsearch.xpack.ml.action.PutDatafeedAction; import org.elasticsearch.xpack.ml.action.PutJobAction; import org.elasticsearch.xpack.ml.action.StartDatafeedAction; import org.elasticsearch.xpack.ml.action.StopDatafeedAction; import org.elasticsearch.xpack.ml.client.MachineLearningClient; import org.elasticsearch.xpack.ml.datafeed.DatafeedState; import org.elasticsearch.xpack.ml.job.config.JobState; import org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase; import org.elasticsearch.xpack.persistent.PersistentTasksCustomMetaData; import org.junit.Before; import java.util.Collections; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; @TestLogging("org.elasticsearch.xpack.ml.action:DEBUG") public class MachineLearningLicensingTests extends BaseMlIntegTestCase { @Before public void resetLicensing() { enableLicensing(); ensureStableCluster(1); ensureYellow(); } public void testMachineLearningPutJobActionRestricted() throws Exception { // Pick a license that does not allow machine learning License.OperationMode mode = randomInvalidLicenseType(); enableLicensing(mode); assertMLAllowed(false); // test that license restricted apis do not work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), listener); listener.actionGet(); fail("put job action should not be enabled!"); } catch (ElasticsearchSecurityException e) { assertThat(e.status(), is(RestStatus.FORBIDDEN)); assertThat(e.getMessage(), containsString("non-compliant")); assertThat(e.getMetadata(LicenseUtils.EXPIRED_FEATURE_METADATA), hasItem(XPackPlugin.MACHINE_LEARNING)); } // Pick a license that does allow machine learning mode = randomValidLicenseType(); enableLicensing(mode); assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), listener); PutJobAction.Response response = listener.actionGet(); assertNotNull(response); } } public void testMachineLearningOpenJobActionRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response response = putJobListener.actionGet(); assertNotNull(response); } // Pick a license that does not allow machine learning License.OperationMode mode = randomInvalidLicenseType(); enableLicensing(mode); assertMLAllowed(false); // test that license restricted apis do not work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<OpenJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), listener); listener.actionGet(); fail("open job action should not be enabled!"); } catch (ElasticsearchSecurityException e) { assertThat(e.status(), is(RestStatus.FORBIDDEN)); assertThat(e.getMessage(), containsString("non-compliant")); assertThat(e.getMetadata(LicenseUtils.EXPIRED_FEATURE_METADATA), hasItem(XPackPlugin.MACHINE_LEARNING)); } // Pick a license that does allow machine learning mode = randomValidLicenseType(); enableLicensing(mode); assertMLAllowed(true); // now that the license is invalid, the job should get closed: assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.CLOSED, jobState); }); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<OpenJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), listener); OpenJobAction.Response response = listener.actionGet(); assertNotNull(response); } } public void testMachineLearningPutDatafeedActionRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); } // Pick a license that does not allow machine learning License.OperationMode mode = randomInvalidLicenseType(); enableLicensing(mode); assertMLAllowed(false); // test that license restricted apis do not work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), listener); listener.actionGet(); fail("put datafeed action should not be enabled!"); } catch (ElasticsearchSecurityException e) { assertThat(e.status(), is(RestStatus.FORBIDDEN)); assertThat(e.getMessage(), containsString("non-compliant")); assertThat(e.getMetadata(LicenseUtils.EXPIRED_FEATURE_METADATA), hasItem(XPackPlugin.MACHINE_LEARNING)); } // Pick a license that does allow machine learning mode = randomValidLicenseType(); enableLicensing(mode); assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), listener); PutDatafeedAction.Response response = listener.actionGet(); assertNotNull(response); } } public void testAutoCloseJobWithDatafeed() throws Exception { assertMLAllowed(true); try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); // put job PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); // put datafeed PlainListenableActionFuture<PutDatafeedAction.Response> putDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), putDatafeedListener); PutDatafeedAction.Response putDatafeedResponse = putDatafeedListener.actionGet(); assertNotNull(putDatafeedResponse); // open job PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); // start datafeed PlainListenableActionFuture<StartDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), listener); listener.actionGet(); } if (randomBoolean()) { enableLicensing(randomInvalidLicenseType()); } else { disableLicensing(); } assertMLAllowed(false); // now that the license is invalid, the job should be closed and datafeed stopped: assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.CLOSED, jobState); DatafeedState datafeedState = getDatafeedStats("foobar").getDatafeedState(); assertEquals(DatafeedState.STOPPED, datafeedState); ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(0, tasks.taskMap().size()); }); enableLicensing(randomValidLicenseType()); assertMLAllowed(true); try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); // open job PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); // start datafeed PlainListenableActionFuture<StartDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), listener); listener.actionGet(); } assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.OPENED, jobState); DatafeedState datafeedState = getDatafeedStats("foobar").getDatafeedState(); assertEquals(DatafeedState.STARTED, datafeedState); ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(2, tasks.taskMap().size()); }); if (randomBoolean()) { enableLicensing(randomInvalidLicenseType()); } else { disableLicensing(); } assertMLAllowed(false); // now that the license is invalid, the job should be closed and datafeed stopped: assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.CLOSED, jobState); DatafeedState datafeedState = getDatafeedStats("foobar").getDatafeedState(); assertEquals(DatafeedState.STOPPED, datafeedState); ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(0, tasks.taskMap().size()); }); } public void testMachineLearningStartDatafeedActionRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); PlainListenableActionFuture<PutDatafeedAction.Response> putDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), putDatafeedListener); PutDatafeedAction.Response putDatafeedResponse = putDatafeedListener.actionGet(); assertNotNull(putDatafeedResponse); PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); } // Pick a license that does not allow machine learning License.OperationMode mode = randomInvalidLicenseType(); enableLicensing(mode); assertMLAllowed(false); // now that the license is invalid, the job should get closed: assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.CLOSED, jobState); ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(0, tasks.taskMap().size()); }); // test that license restricted apis do not work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<StartDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), listener); listener.actionGet(); fail("start datafeed action should not be enabled!"); } catch (ElasticsearchSecurityException e) { assertThat(e.status(), is(RestStatus.FORBIDDEN)); assertThat(e.getMessage(), containsString("non-compliant")); assertThat(e.getMetadata(LicenseUtils.EXPIRED_FEATURE_METADATA), hasItem(XPackPlugin.MACHINE_LEARNING)); } // Pick a license that does allow machine learning mode = randomValidLicenseType(); enableLicensing(mode); assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); // re-open job now that the license is valid again PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); PlainListenableActionFuture<StartDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), listener); StartDatafeedAction.Response response = listener.actionGet(); assertNotNull(response); } } public void testMachineLearningStopDatafeedActionNotRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); PlainListenableActionFuture<PutDatafeedAction.Response> putDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), putDatafeedListener); PutDatafeedAction.Response putDatafeedResponse = putDatafeedListener.actionGet(); assertNotNull(putDatafeedResponse); PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); PlainListenableActionFuture<StartDatafeedAction.Response> startDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), startDatafeedListener); StartDatafeedAction.Response startDatafeedResponse = startDatafeedListener.actionGet(); assertNotNull(startDatafeedResponse); } boolean invalidLicense = randomBoolean(); if (invalidLicense) { enableLicensing(randomInvalidLicenseType()); } else { enableLicensing(randomValidLicenseType()); } try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<StopDatafeedAction.Response> listener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).stopDatafeed(new StopDatafeedAction.Request("foobar"), listener); if (invalidLicense) { // expected to because datafeeds is automatically stopped in case of invalid license, // a license error should not be returned Exception e = expectThrows(ElasticsearchStatusException.class, listener::actionGet); assertEquals("Cannot stop datafeed [foobar] because it has already been stopped", e.getMessage()); } else { listener.actionGet(); } } } public void testMachineLearningCloseJobActionNotRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); } boolean invalidLicense = randomBoolean(); if (invalidLicense) { enableLicensing(randomInvalidLicenseType()); } else { enableLicensing(randomValidLicenseType()); } try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<CloseJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); CloseJobAction.Request request = new CloseJobAction.Request("foo"); request.setTimeout(TimeValue.timeValueSeconds(30)); if (invalidLicense) { // the close due to invalid license happens async, so check if the job turns into closed state: assertBusy(() -> { GetJobsStatsAction.Response response = new MachineLearningClient(client).getJobsStats(new GetJobsStatsAction.Request("foo")).actionGet(); assertEquals(JobState.CLOSED, response.getResponse().results().get(0).getState()); }); } else { new MachineLearningClient(client).closeJob(request, listener); listener.actionGet(); } } } public void testMachineLearningDeleteJobActionNotRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); } // Pick a random license License.OperationMode mode = randomLicenseType(); enableLicensing(mode); try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<DeleteJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).deleteJob(new DeleteJobAction.Request("foo"), listener); listener.actionGet(); } } public void testMachineLearningDeleteDatafeedActionNotRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); PlainListenableActionFuture<PutDatafeedAction.Response> putDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), putDatafeedListener); PutDatafeedAction.Response putDatafeedResponse = putDatafeedListener.actionGet(); assertNotNull(putDatafeedResponse); } // Pick a random license License.OperationMode mode = randomLicenseType(); enableLicensing(mode); try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<DeleteDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).deleteDatafeed(new DeleteDatafeedAction.Request("foobar"), listener); listener.actionGet(); } } private static OperationMode randomInvalidLicenseType() { return randomFrom(License.OperationMode.GOLD, License.OperationMode.STANDARD, License.OperationMode.BASIC); } private static OperationMode randomValidLicenseType() { return randomFrom(License.OperationMode.TRIAL, License.OperationMode.PLATINUM); } private static OperationMode randomLicenseType() { return randomFrom(License.OperationMode.values()); } private static void assertMLAllowed(boolean expected) { for (XPackLicenseState licenseState : internalCluster().getInstances(XPackLicenseState.class)) { assertEquals(licenseState.isMachineLearningAllowed(), expected); } } public static void disableLicensing() { disableLicensing(randomValidLicenseType()); } public static void disableLicensing(License.OperationMode operationMode) { for (XPackLicenseState licenseState : internalCluster().getInstances(XPackLicenseState.class)) { licenseState.update(operationMode, false); } } public static void enableLicensing() { enableLicensing(randomValidLicenseType()); } public static void enableLicensing(License.OperationMode operationMode) { for (XPackLicenseState licenseState : internalCluster().getInstances(XPackLicenseState.class)) { licenseState.update(operationMode, true); } } }
plugin/src/test/java/org/elasticsearch/license/MachineLearningLicensingTests.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.license; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.action.support.PlainListenableActionFuture; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.license.License.OperationMode; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.transport.Transport; import org.elasticsearch.xpack.TestXPackTransportClient; import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.ml.action.CloseJobAction; import org.elasticsearch.xpack.ml.action.DeleteDatafeedAction; import org.elasticsearch.xpack.ml.action.DeleteJobAction; import org.elasticsearch.xpack.ml.action.GetJobsStatsAction; import org.elasticsearch.xpack.ml.action.OpenJobAction; import org.elasticsearch.xpack.ml.action.PutDatafeedAction; import org.elasticsearch.xpack.ml.action.PutJobAction; import org.elasticsearch.xpack.ml.action.StartDatafeedAction; import org.elasticsearch.xpack.ml.action.StopDatafeedAction; import org.elasticsearch.xpack.ml.client.MachineLearningClient; import org.elasticsearch.xpack.ml.datafeed.DatafeedState; import org.elasticsearch.xpack.ml.job.config.JobState; import org.elasticsearch.xpack.ml.support.BaseMlIntegTestCase; import org.elasticsearch.xpack.persistent.PersistentTasksCustomMetaData; import org.junit.Before; import java.util.Collections; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; public class MachineLearningLicensingTests extends BaseMlIntegTestCase { @Before public void resetLicensing() { enableLicensing(); ensureStableCluster(1); ensureYellow(); } public void testMachineLearningPutJobActionRestricted() throws Exception { // Pick a license that does not allow machine learning License.OperationMode mode = randomInvalidLicenseType(); enableLicensing(mode); assertMLAllowed(false); // test that license restricted apis do not work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), listener); listener.actionGet(); fail("put job action should not be enabled!"); } catch (ElasticsearchSecurityException e) { assertThat(e.status(), is(RestStatus.FORBIDDEN)); assertThat(e.getMessage(), containsString("non-compliant")); assertThat(e.getMetadata(LicenseUtils.EXPIRED_FEATURE_METADATA), hasItem(XPackPlugin.MACHINE_LEARNING)); } // Pick a license that does allow machine learning mode = randomValidLicenseType(); enableLicensing(mode); assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), listener); PutJobAction.Response response = listener.actionGet(); assertNotNull(response); } } public void testMachineLearningOpenJobActionRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response response = putJobListener.actionGet(); assertNotNull(response); } // Pick a license that does not allow machine learning License.OperationMode mode = randomInvalidLicenseType(); enableLicensing(mode); assertMLAllowed(false); // test that license restricted apis do not work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<OpenJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), listener); listener.actionGet(); fail("open job action should not be enabled!"); } catch (ElasticsearchSecurityException e) { assertThat(e.status(), is(RestStatus.FORBIDDEN)); assertThat(e.getMessage(), containsString("non-compliant")); assertThat(e.getMetadata(LicenseUtils.EXPIRED_FEATURE_METADATA), hasItem(XPackPlugin.MACHINE_LEARNING)); } // Pick a license that does allow machine learning mode = randomValidLicenseType(); enableLicensing(mode); assertMLAllowed(true); // now that the license is invalid, the job should get closed: assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.CLOSED, jobState); }); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<OpenJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), listener); OpenJobAction.Response response = listener.actionGet(); assertNotNull(response); } } public void testMachineLearningPutDatafeedActionRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); } // Pick a license that does not allow machine learning License.OperationMode mode = randomInvalidLicenseType(); enableLicensing(mode); assertMLAllowed(false); // test that license restricted apis do not work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), listener); listener.actionGet(); fail("put datafeed action should not be enabled!"); } catch (ElasticsearchSecurityException e) { assertThat(e.status(), is(RestStatus.FORBIDDEN)); assertThat(e.getMessage(), containsString("non-compliant")); assertThat(e.getMetadata(LicenseUtils.EXPIRED_FEATURE_METADATA), hasItem(XPackPlugin.MACHINE_LEARNING)); } // Pick a license that does allow machine learning mode = randomValidLicenseType(); enableLicensing(mode); assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), listener); PutDatafeedAction.Response response = listener.actionGet(); assertNotNull(response); } } public void testAutoCloseJobWithDatafeed() throws Exception { assertMLAllowed(true); try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); // put job PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); // put datafeed PlainListenableActionFuture<PutDatafeedAction.Response> putDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), putDatafeedListener); PutDatafeedAction.Response putDatafeedResponse = putDatafeedListener.actionGet(); assertNotNull(putDatafeedResponse); // open job PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); // start datafeed PlainListenableActionFuture<StartDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), listener); listener.actionGet(); } if (randomBoolean()) { enableLicensing(randomInvalidLicenseType()); } else { disableLicensing(); } assertMLAllowed(false); // now that the license is invalid, the job should be closed and datafeed stopped: assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.CLOSED, jobState); DatafeedState datafeedState = getDatafeedStats("foobar").getDatafeedState(); assertEquals(DatafeedState.STOPPED, datafeedState); ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(0, tasks.taskMap().size()); }); enableLicensing(randomValidLicenseType()); assertMLAllowed(true); try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); // open job PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); // start datafeed PlainListenableActionFuture<StartDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), listener); listener.actionGet(); } assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.OPENED, jobState); DatafeedState datafeedState = getDatafeedStats("foobar").getDatafeedState(); assertEquals(DatafeedState.STARTED, datafeedState); ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(2, tasks.taskMap().size()); }); if (randomBoolean()) { enableLicensing(randomInvalidLicenseType()); } else { disableLicensing(); } assertMLAllowed(false); // now that the license is invalid, the job should be closed and datafeed stopped: assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.CLOSED, jobState); DatafeedState datafeedState = getDatafeedStats("foobar").getDatafeedState(); assertEquals(DatafeedState.STOPPED, datafeedState); ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(0, tasks.taskMap().size()); }); } public void testMachineLearningStartDatafeedActionRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); PlainListenableActionFuture<PutDatafeedAction.Response> putDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), putDatafeedListener); PutDatafeedAction.Response putDatafeedResponse = putDatafeedListener.actionGet(); assertNotNull(putDatafeedResponse); PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); } // Pick a license that does not allow machine learning License.OperationMode mode = randomInvalidLicenseType(); enableLicensing(mode); assertMLAllowed(false); // now that the license is invalid, the job should get closed: assertBusy(() -> { JobState jobState = getJobStats("foo").getState(); assertEquals(JobState.CLOSED, jobState); ClusterState state = client().admin().cluster().prepareState().get().getState(); PersistentTasksCustomMetaData tasks = state.metaData().custom(PersistentTasksCustomMetaData.TYPE); assertEquals(0, tasks.taskMap().size()); }); // test that license restricted apis do not work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<StartDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), listener); listener.actionGet(); fail("start datafeed action should not be enabled!"); } catch (ElasticsearchSecurityException e) { assertThat(e.status(), is(RestStatus.FORBIDDEN)); assertThat(e.getMessage(), containsString("non-compliant")); assertThat(e.getMetadata(LicenseUtils.EXPIRED_FEATURE_METADATA), hasItem(XPackPlugin.MACHINE_LEARNING)); } // Pick a license that does allow machine learning mode = randomValidLicenseType(); enableLicensing(mode); assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); // re-open job now that the license is valid again PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); PlainListenableActionFuture<StartDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), listener); StartDatafeedAction.Response response = listener.actionGet(); assertNotNull(response); } } public void testMachineLearningStopDatafeedActionNotRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); PlainListenableActionFuture<PutDatafeedAction.Response> putDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), putDatafeedListener); PutDatafeedAction.Response putDatafeedResponse = putDatafeedListener.actionGet(); assertNotNull(putDatafeedResponse); PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); PlainListenableActionFuture<StartDatafeedAction.Response> startDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).startDatafeed(new StartDatafeedAction.Request("foobar", 0L), startDatafeedListener); StartDatafeedAction.Response startDatafeedResponse = startDatafeedListener.actionGet(); assertNotNull(startDatafeedResponse); } boolean invalidLicense = randomBoolean(); if (invalidLicense) { enableLicensing(randomInvalidLicenseType()); } else { enableLicensing(randomValidLicenseType()); } try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<StopDatafeedAction.Response> listener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).stopDatafeed(new StopDatafeedAction.Request("foobar"), listener); if (invalidLicense) { // expected to because datafeeds is automatically stopped in case of invalid license, // a license error should not be returned Exception e = expectThrows(ElasticsearchStatusException.class, listener::actionGet); assertEquals("Cannot stop datafeed [foobar] because it has already been stopped", e.getMessage()); } else { listener.actionGet(); } } } public void testMachineLearningCloseJobActionNotRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); PlainListenableActionFuture<OpenJobAction.Response> openJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).openJob(new OpenJobAction.Request("foo"), openJobListener); OpenJobAction.Response openJobResponse = openJobListener.actionGet(); assertNotNull(openJobResponse); } boolean invalidLicense = randomBoolean(); if (invalidLicense) { enableLicensing(randomInvalidLicenseType()); } else { enableLicensing(randomValidLicenseType()); } try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<CloseJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); CloseJobAction.Request request = new CloseJobAction.Request("foo"); request.setTimeout(TimeValue.timeValueSeconds(30)); if (invalidLicense) { // the close due to invalid license happens async, so check if the job turns into closed state: assertBusy(() -> { GetJobsStatsAction.Response response = new MachineLearningClient(client).getJobsStats(new GetJobsStatsAction.Request("foo")).actionGet(); assertEquals(JobState.CLOSED, response.getResponse().results().get(0).getState()); }); } else { new MachineLearningClient(client).closeJob(request, listener); listener.actionGet(); } } } public void testMachineLearningDeleteJobActionNotRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); } // Pick a random license License.OperationMode mode = randomLicenseType(); enableLicensing(mode); try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<DeleteJobAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).deleteJob(new DeleteJobAction.Request("foo"), listener); listener.actionGet(); } } public void testMachineLearningDeleteDatafeedActionNotRestricted() throws Exception { assertMLAllowed(true); // test that license restricted apis do now work try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<PutJobAction.Response> putJobListener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).putJob(new PutJobAction.Request(createJob("foo").build()), putJobListener); PutJobAction.Response putJobResponse = putJobListener.actionGet(); assertNotNull(putJobResponse); PlainListenableActionFuture<PutDatafeedAction.Response> putDatafeedListener = new PlainListenableActionFuture<>( client.threadPool()); new MachineLearningClient(client).putDatafeed( new PutDatafeedAction.Request(createDatafeed("foobar", "foo", Collections.singletonList("foo"))), putDatafeedListener); PutDatafeedAction.Response putDatafeedResponse = putDatafeedListener.actionGet(); assertNotNull(putDatafeedResponse); } // Pick a random license License.OperationMode mode = randomLicenseType(); enableLicensing(mode); try (TransportClient client = new TestXPackTransportClient(internalCluster().transportClient().settings())) { client.addTransportAddress(internalCluster().getDataNodeInstance(Transport.class).boundAddress().publishAddress()); PlainListenableActionFuture<DeleteDatafeedAction.Response> listener = new PlainListenableActionFuture<>(client.threadPool()); new MachineLearningClient(client).deleteDatafeed(new DeleteDatafeedAction.Request("foobar"), listener); listener.actionGet(); } } private static OperationMode randomInvalidLicenseType() { return randomFrom(License.OperationMode.GOLD, License.OperationMode.STANDARD, License.OperationMode.BASIC); } private static OperationMode randomValidLicenseType() { return randomFrom(License.OperationMode.TRIAL, License.OperationMode.PLATINUM); } private static OperationMode randomLicenseType() { return randomFrom(License.OperationMode.values()); } private static void assertMLAllowed(boolean expected) { for (XPackLicenseState licenseState : internalCluster().getInstances(XPackLicenseState.class)) { assertEquals(licenseState.isMachineLearningAllowed(), expected); } } public static void disableLicensing() { disableLicensing(randomValidLicenseType()); } public static void disableLicensing(License.OperationMode operationMode) { for (XPackLicenseState licenseState : internalCluster().getInstances(XPackLicenseState.class)) { licenseState.update(operationMode, false); } } public static void enableLicensing() { enableLicensing(randomValidLicenseType()); } public static void enableLicensing(License.OperationMode operationMode) { for (XPackLicenseState licenseState : internalCluster().getInstances(XPackLicenseState.class)) { licenseState.update(operationMode, true); } } }
[TEST] increased log level Original commit: elastic/x-pack-elasticsearch@a8ea83dca06f7f4076c3e50aa960db7eb30ce4a0
plugin/src/test/java/org/elasticsearch/license/MachineLearningLicensingTests.java
[TEST] increased log level
Java
apache-2.0
019d5cefa95e20351dc07d9ee21b51aaca4fbfda
0
wangdan/DownloadManager
package org.aiwen.downloader; import android.net.Uri; import android.os.SystemClock; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Response; import org.aiwen.downloader.utils.Constants; import org.aiwen.downloader.utils.Utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * 下载线程 * * Created by wangdan on 16/11/18. */ public class DownloadThread implements Runnable { private final static OkHttpClient mOkHttpClient = new OkHttpClient(); private final static int CONN_TIMEOUT = 30000; private final static int READ_TIMEOUT = 30000; static { try { mOkHttpClient.setConnectTimeout(CONN_TIMEOUT, TimeUnit.MILLISECONDS); mOkHttpClient.setReadTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext e = SSLContext.getInstance("TLS"); e.init(null, new TrustManager[]{tm}, null); mOkHttpClient.setSslSocketFactory(e.getSocketFactory()); } catch (Exception e) { throw new RuntimeException("supportHttps failed", e); } } private final Request mRequest; private final DownloadService mService; private final DownloadNotifier mNotifier; private final Hawk mHawk; private File mTempFile; private File mSaveFile; /** * Details from the last time we pushed a database update. */ private long mLastUpdateBytes = 0; private long mLastUpdateTime = 0; public DownloadThread(Hawk hawk, Request request, DownloadService service) { mHawk = hawk; mNotifier = hawk.notifier; mRequest = request; mRequest.thread = this; mRequest.downloadInfo.status = Downloads.Status.STATUS_PENDING; mRequest.downloadInfo.writeToDatabase(); mHawk.trace.peddingThread.incrementAndGet(); mService = service; mService.threadIncrement(); } @Override public void run() { mHawk.trace.peddingThread.decrementAndGet(); mHawk.trace.concurrentThread.incrementAndGet(); final DownloadInfo downloadInfo = mRequest.downloadInfo; try { do { mRequest.trace = new ThreadTrace(mRequest); // 创建临时文件 mTempFile = FileManager.createFile(mRequest, true); mSaveFile = FileManager.createFile(mRequest, false);; // 验证文件 if (checkFile()) { DLogger.w(Utils.getDownloaderTAG(mRequest), "文件校验成功,完成下载"); downloadInfo.status = Downloads.Status.STATUS_SUCCESS; downloadInfo.rangeBytes = downloadInfo.fileBytes; downloadInfo.numFailed = 0; break; } downloadInfo.status = Downloads.Status.STATUS_RUNNING; downloadInfo.writeToDatabase(); DLogger.d(Utils.getDownloaderTAG(mRequest), "开始下载(%s)", mRequest.uri); executeDownload(mRequest); DLogger.d(Utils.getDownloaderTAG(mRequest), "结束下载(%s)", mRequest.uri); downloadInfo.status = Downloads.Status.STATUS_SUCCESS; } while (false); } catch (DownloadException e) { e.printStackTrace(); // 处理错误状态 switch (e.getStatus()) { case Downloads.Status.STATUS_HTTP_EXCEPTION: case Downloads.Status.STATUS_HTTP_DATA_ERROR: // 网络正常连接,尝试重连 if (Utils.isNetworkActive()) { int numFailed = ++downloadInfo.numFailed; if (numFailed <= Constants.MAX_RETRIES) { downloadInfo.retryAfter = (numFailed << 2) * 1000; downloadInfo.status = Downloads.Status.STATUS_WAITING_TO_RETRY; mService.setRetryAlarm(mRequest); } else { downloadInfo.retryAfter = 0; downloadInfo.status = e.getStatus(); } } // 没有网络连接 else { downloadInfo.retryAfter = 0; downloadInfo.status = Downloads.Status.STATUS_WAITING_FOR_NETWORK; } break; default: downloadInfo.status = e.getStatus(); break; } downloadInfo.error = Downloads.Status.statusToString(downloadInfo.status); } finally { mHawk.trace.concurrentThread.decrementAndGet(); downloadInfo.lastMod = Utils.realtime(); mRequest.trace.speed = 0l; mNotifier.notifyDownloadSpeed(mRequest.id, 0); downloadInfo.writeToDatabase(); } mRequest.thread = null; mService.threadDecrement(); mService.stopIfNeed(); } // 开始下载 private void executeDownload(Request request) throws DownloadException { final Uri uri = request.uri; final DownloadInfo downloadInfo = request.downloadInfo; final ThreadTrace trace = request.trace; com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder(); final String url; if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) { url = uri.toString(); } else { url = uri.getPath(); } builder.url(url); // 断点下载 if (downloadInfo.rangeBytes > 0) { DLogger.i(Utils.getDownloaderTAG(request), "set range header = %d", downloadInfo.rangeBytes); builder.addHeader("Range", "bytes="+ downloadInfo.rangeBytes + "-"); } final Response response; // 开始请求数据 try { trace.beginConnect(); response = mOkHttpClient.newCall(builder.build()).execute(); if (!response.isSuccessful()) { throw new DownloadException(Downloads.Status.STATUS_HTTP_EXCEPTION); } trace.endConnect(); } catch (IOException e) { DLogger.printStackTrace(e); trace.endConnect(); trace.endRead(); throw new DownloadException(Downloads.Status.STATUS_HTTP_EXCEPTION); } try { // 开始解析数据 transferData(request, response); // 临时文件copy成目标文件 copyFile(); } catch (IOException e) { DLogger.printStackTrace(e); trace.endSpeedCount(); trace.computeSpeed(); trace.endRead(); throw new DownloadException(Downloads.Status.STATUS_HTTP_DATA_ERROR); } } // 缓存数据 private void transferData(Request request, Response response) throws IOException, DownloadException { final DownloadInfo downloadInfo = request.downloadInfo; final ThreadTrace trace = request.trace; // Content-Length long contentLen = -1; long totalLen = -1; try { String header = response.header("Content-Length"); contentLen = Long.parseLong(header); totalLen = contentLen + downloadInfo.rangeBytes;// 文件大小 } catch (Exception e) { e.printStackTrace(); } DLogger.d(Utils.getDownloaderTAG(request), "fileBytes(%d), rangeBytes(%d), Content-Length(%d)", totalLen, downloadInfo.rangeBytes, contentLen); if (totalLen != -1) { downloadInfo.fileBytes = totalLen; } downloadInfo.writeToDatabase(); InputStream in = null; final FileOutputStream out; try { out = new FileOutputStream(mTempFile, true); } catch (FileNotFoundException e) { DLogger.printStackTrace(e); throw new DownloadException(Downloads.Status.STATUS_FILE_ERROR); } try { in = response.body().byteStream(); byte[] readBuffer = new byte[8 * 1024]; int readLen = -1; trace.benginRead(); trace.beginSpeedCount(); byte[] largeBuffer = new byte[1024 * 128]; byte[] midBuffer = new byte[1024 * 32]; byte[] smallBuffer = new byte[1024 * 16]; byte[] b = smallBuffer; ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); int count = 0; long begin = Utils.now(); long writeTime = 0; while (true) { count++; long start = Utils.now(); // readLen = in.read(readBuffer); // if (readLen > 0) { // out.write(readBuffer, 0, readLen); // // downloadInfo.rangeBytes += readLen; // trace.receive(readLen); // } byteArrayOut.reset(); do { readLen = in.read(readBuffer); if (readLen > 0) { byteArrayOut.write(readBuffer, 0, readLen); } } while (readLen > 0 && byteArrayOut.size() < b.length); byte[] writeBuffer = byteArrayOut.toByteArray(); out.write(writeBuffer, 0, writeBuffer.length); out.flush(); downloadInfo.rangeBytes += writeBuffer.length; trace.receive(writeBuffer.length); final long now = SystemClock.elapsedRealtime(); final long currentBytes = downloadInfo.rangeBytes; // 更新DB下载进度 final long bytesDelta = currentBytes - mLastUpdateBytes; final long timeDelta = now - mLastUpdateTime; if (bytesDelta > Constants.MIN_PROGRESS_STEP && timeDelta > Constants.MIN_PROGRESS_TIME) { mLastUpdateBytes = currentBytes; mLastUpdateTime = now; trace.endSpeedCount(); trace.computeSpeed(); mNotifier.notifyDownloadSpeed(mRequest.id, (long) trace.getSpeed()); trace.beginSpeedCount(); // 正常下载数据后,将下载失败次数清零 if (downloadInfo.numFailed > 0) { downloadInfo.numFailed = 0; downloadInfo.retryAfter = 0; } downloadInfo.writeToDatabase(); } long time = Utils.now() - start; if (time > 0) { DLogger.e("DownloadTime", time + ", readLen = " + readLen); writeTime += time; } if (readLen == -1) { out.flush(); break; } } DLogger.e("DownloadTime", "count = %d, 耗时 %d ms, writeTime = %d ms", count, Utils.now() - begin, writeTime); trace.endRead(); out.flush(); } finally { Utils.close(in); Utils.close(out); } } // 重新获取文件的长度,目前仅支持使用文件长度校验文件合法性 private boolean checkFile() { // 目标文件存在 if (mSaveFile.exists()) { if (mSaveFile.length() == mRequest.downloadInfo.fileBytes) { DLogger.w(Utils.getDownloaderTAG(mRequest), "目标文件已存在"); return mHawk.getConfiguration().fileCheckCallback.onFileCheck(mRequest, mSaveFile); } else { DLogger.w(Utils.getDownloaderTAG(mRequest), "删除目标文件,FileBytes(%d), File(%s)", mRequest.downloadInfo.fileBytes, mSaveFile.getAbsolutePath()); mSaveFile.delete(); } } // 临时文件存在 if (mTempFile.exists()) { if (mTempFile.length() > 0) { try { // 已下载完 if (mTempFile.length() == mRequest.downloadInfo.fileBytes) { if (copyFile()) { DLogger.w(Utils.getDownloaderTAG(mRequest), "临时文件存在且copy为目标文件"); return mHawk.getConfiguration().fileCheckCallback.onFileCheck(mRequest, mSaveFile); } } // 断点下载 else if (mTempFile.length() == mRequest.downloadInfo.rangeBytes) { return true; } } catch (DownloadException e){ e.printStackTrace(); } } DLogger.w(Utils.getDownloaderTAG(mRequest), "删除临时文件(%s)", mTempFile.getAbsolutePath()); mTempFile.delete(); mRequest.downloadInfo.rangeBytes = 0; } else { mRequest.downloadInfo.rangeBytes = 0; } return false; } private boolean copyFile() throws DownloadException { try { return mTempFile.renameTo(mSaveFile); } catch (Exception e) { e.printStackTrace(); } DLogger.w(Utils.getDownloaderTAG(mRequest), "重命名临时文件出错, save file = %s", mSaveFile.getAbsolutePath()); throw new DownloadException(Downloads.Status.STATUS_FILE_ERROR); } @Override protected void finalize() throws Throwable { super.finalize(); DLogger.w(Utils.getDownloaderTAG(mRequest), "Thread finalize()"); } }
aisen_downloader/src/main/java/org/aiwen/downloader/DownloadThread.java
package org.aiwen.downloader; import android.net.Uri; import android.os.SystemClock; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Response; import org.aiwen.downloader.utils.Constants; import org.aiwen.downloader.utils.Utils; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * 下载线程 * * Created by wangdan on 16/11/18. */ public class DownloadThread implements Runnable { private final static OkHttpClient mOkHttpClient = new OkHttpClient(); private final static int CONN_TIMEOUT = 30000; private final static int READ_TIMEOUT = 30000; static { try { mOkHttpClient.setConnectTimeout(CONN_TIMEOUT, TimeUnit.MILLISECONDS); mOkHttpClient.setReadTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext e = SSLContext.getInstance("TLS"); e.init(null, new TrustManager[]{tm}, null); mOkHttpClient.setSslSocketFactory(e.getSocketFactory()); } catch (Exception e) { throw new RuntimeException("supportHttps failed", e); } } private final Request mRequest; private final DownloadService mService; private final DownloadNotifier mNotifier; private final Hawk mHawk; private File mTempFile; private File mSaveFile; /** * Details from the last time we pushed a database update. */ private long mLastUpdateBytes = 0; private long mLastUpdateTime = 0; public DownloadThread(Hawk hawk, Request request, DownloadService service) { mHawk = hawk; mNotifier = hawk.notifier; mRequest = request; mRequest.thread = this; mRequest.downloadInfo.status = Downloads.Status.STATUS_PENDING; mRequest.downloadInfo.writeToDatabase(); mHawk.trace.peddingThread.incrementAndGet(); mService = service; mService.threadIncrement(); } @Override public void run() { mHawk.trace.peddingThread.decrementAndGet(); mHawk.trace.concurrentThread.incrementAndGet(); final DownloadInfo downloadInfo = mRequest.downloadInfo; try { do { mRequest.trace = new ThreadTrace(mRequest); // 创建临时文件 mTempFile = FileManager.createFile(mRequest, true); mSaveFile = FileManager.createFile(mRequest, false);; // 验证文件 if (checkFile()) { DLogger.w(Utils.getDownloaderTAG(mRequest), "文件校验成功,完成下载"); downloadInfo.status = Downloads.Status.STATUS_SUCCESS; downloadInfo.rangeBytes = downloadInfo.fileBytes; downloadInfo.numFailed = 0; break; } downloadInfo.status = Downloads.Status.STATUS_RUNNING; downloadInfo.writeToDatabase(); DLogger.d(Utils.getDownloaderTAG(mRequest), "开始下载(%s)", mRequest.uri); executeDownload(mRequest); DLogger.d(Utils.getDownloaderTAG(mRequest), "结束下载(%s)", mRequest.uri); downloadInfo.status = Downloads.Status.STATUS_SUCCESS; } while (false); } catch (DownloadException e) { e.printStackTrace(); // 处理错误状态 switch (e.getStatus()) { case Downloads.Status.STATUS_HTTP_EXCEPTION: case Downloads.Status.STATUS_HTTP_DATA_ERROR: // 网络正常连接,尝试重连 if (Utils.isNetworkActive()) { int numFailed = ++downloadInfo.numFailed; if (numFailed <= Constants.MAX_RETRIES) { downloadInfo.retryAfter = (numFailed << 2) * 1000; downloadInfo.status = Downloads.Status.STATUS_WAITING_TO_RETRY; mService.setRetryAlarm(mRequest); } else { downloadInfo.retryAfter = 0; downloadInfo.status = e.getStatus(); } } // 没有网络连接 else { downloadInfo.retryAfter = 0; downloadInfo.status = Downloads.Status.STATUS_WAITING_FOR_NETWORK; } break; default: downloadInfo.status = e.getStatus(); break; } downloadInfo.error = Downloads.Status.statusToString(downloadInfo.status); } finally { mHawk.trace.concurrentThread.decrementAndGet(); downloadInfo.lastMod = Utils.realtime(); mRequest.trace.speed = 0l; mNotifier.notifyDownloadSpeed(mRequest.id, 0); downloadInfo.writeToDatabase(); } mRequest.thread = null; mService.threadDecrement(); mService.stopIfNeed(); } // 开始下载 private void executeDownload(Request request) throws DownloadException { final Uri uri = request.uri; final DownloadInfo downloadInfo = request.downloadInfo; final ThreadTrace trace = request.trace; com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder(); final String url; if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) { url = uri.toString(); } else { url = uri.getPath(); } builder.url(url); // 断点下载 if (downloadInfo.rangeBytes > 0) { DLogger.i(Utils.getDownloaderTAG(request), "set range header = %d", downloadInfo.rangeBytes); builder.addHeader("Range", "bytes="+ downloadInfo.rangeBytes + "-"); } final Response response; // 开始请求数据 try { trace.beginConnect(); response = mOkHttpClient.newCall(builder.build()).execute(); if (!response.isSuccessful()) { throw new DownloadException(Downloads.Status.STATUS_HTTP_EXCEPTION); } trace.endConnect(); } catch (IOException e) { DLogger.printStackTrace(e); trace.endConnect(); trace.endRead(); throw new DownloadException(Downloads.Status.STATUS_HTTP_EXCEPTION); } try { // 开始解析数据 transferData(request, response); // 临时文件copy成目标文件 copyFile(); } catch (IOException e) { DLogger.printStackTrace(e); trace.endSpeedCount(); trace.computeSpeed(); trace.endRead(); throw new DownloadException(Downloads.Status.STATUS_HTTP_DATA_ERROR); } } // 缓存数据 private void transferData(Request request, Response response) throws IOException, DownloadException { final DownloadInfo downloadInfo = request.downloadInfo; final ThreadTrace trace = request.trace; // Content-Length long contentLen = -1; long totalLen = -1; try { String header = response.header("Content-Length"); contentLen = Long.parseLong(header); totalLen = contentLen + downloadInfo.rangeBytes;// 文件大小 } catch (Exception e) { e.printStackTrace(); } DLogger.d(Utils.getDownloaderTAG(request), "fileBytes(%d), rangeBytes(%d), Content-Length(%d)", totalLen, downloadInfo.rangeBytes, contentLen); if (totalLen != -1) { downloadInfo.fileBytes = totalLen; } downloadInfo.writeToDatabase(); InputStream in = null; final FileOutputStream out; try { out = new FileOutputStream(mTempFile, true); } catch (FileNotFoundException e) { DLogger.printStackTrace(e); throw new DownloadException(Downloads.Status.STATUS_FILE_ERROR); } try { in = response.body().byteStream(); byte[] readBuffer = new byte[8 * 1024]; int readLen = -1; trace.benginRead(); trace.beginSpeedCount(); while ((readLen = in.read(readBuffer)) != -1) { out.write(readBuffer, 0, readLen); downloadInfo.rangeBytes += readLen; trace.receive(readLen); final long now = SystemClock.elapsedRealtime(); final long currentBytes = downloadInfo.rangeBytes; // 更新DB下载进度 final long bytesDelta = currentBytes - mLastUpdateBytes; final long timeDelta = now - mLastUpdateTime; if (bytesDelta > Constants.MIN_PROGRESS_STEP && timeDelta > Constants.MIN_PROGRESS_TIME) { mLastUpdateBytes = currentBytes; mLastUpdateTime = now; trace.endSpeedCount(); trace.computeSpeed(); mNotifier.notifyDownloadSpeed(mRequest.id, (long) trace.getSpeed()); trace.beginSpeedCount(); // 正常下载数据后,将下载失败次数清零 if (downloadInfo.numFailed > 0) { downloadInfo.numFailed = 0; downloadInfo.retryAfter = 0; } downloadInfo.writeToDatabase(); } } trace.endRead(); out.flush(); } finally { Utils.close(in); Utils.close(out); } } // 重新获取文件的长度,目前仅支持使用文件长度校验文件合法性 private boolean checkFile() { // 目标文件存在 if (mSaveFile.exists()) { if (mSaveFile.length() == mRequest.downloadInfo.fileBytes) { DLogger.w(Utils.getDownloaderTAG(mRequest), "目标文件已存在"); return mHawk.getConfiguration().fileCheckCallback.onFileCheck(mRequest, mSaveFile); } else { DLogger.w(Utils.getDownloaderTAG(mRequest), "删除目标文件,FileBytes(%d), File(%s)", mRequest.downloadInfo.fileBytes, mSaveFile.getAbsolutePath()); mSaveFile.delete(); } } // 临时文件存在 if (mTempFile.exists()) { if (mTempFile.length() > 0) { try { // 已下载完 if (mTempFile.length() == mRequest.downloadInfo.fileBytes) { if (copyFile()) { DLogger.w(Utils.getDownloaderTAG(mRequest), "临时文件存在且copy为目标文件"); return mHawk.getConfiguration().fileCheckCallback.onFileCheck(mRequest, mSaveFile); } } // 断点下载 else if (mTempFile.length() == mRequest.downloadInfo.rangeBytes) { return true; } } catch (DownloadException e){ e.printStackTrace(); } } DLogger.w(Utils.getDownloaderTAG(mRequest), "删除临时文件(%s)", mTempFile.getAbsolutePath()); mTempFile.delete(); mRequest.downloadInfo.rangeBytes = 0; } else { mRequest.downloadInfo.rangeBytes = 0; } return false; } private boolean copyFile() throws DownloadException { try { return mTempFile.renameTo(mSaveFile); } catch (Exception e) { e.printStackTrace(); } DLogger.w(Utils.getDownloaderTAG(mRequest), "重命名临时文件出错, save file = %s", mSaveFile.getAbsolutePath()); throw new DownloadException(Downloads.Status.STATUS_FILE_ERROR); } @Override protected void finalize() throws Throwable { super.finalize(); DLogger.w(Utils.getDownloaderTAG(mRequest), "Thread finalize()"); } }
优化下载速度
aisen_downloader/src/main/java/org/aiwen/downloader/DownloadThread.java
优化下载速度
Java
apache-2.0
4ee45f1d93bf9ce61f70ba6b5830dfde074685f0
0
otto-de/edison-microservice,otto-de/edison-microservice,otto-de/edison-microservice,otto-de/edison-microservice
package de.otto.edison.mongo; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoDatabase; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static com.mongodb.MongoCredential.createCredential; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.slf4j.LoggerFactory.getLogger; @Configuration public class MongoConfiguration { private static final Logger LOG = getLogger(MongoConfiguration.class); private List<ServerAddress> databaseServers; @Value("${edison.mongo.maxWaitTime:5000}") private int maxWaitTime = 5000; @Value("${edison.mongo.connectTimeout:5000}") private int connectTimeout = 5000; @Value("${edison.mongo.socketTimeout:2000}") private int socketTimeout = 10000; @Value("${edison.mongo.serverSelectionTimeout:30000}") private int serverSelectionTimeout; @Value("${edison.mongo.connectionpool.maxSize:100}") private int connectionsPerHostMax = 100; @Value("${edison.mongo.connectionpool.minSize:2}") private int connectionsPerHostMin = 2; @Value("${edison.mongo.blockedConnectionMultiplier:2}") private int blockedConnectionMultiplier = 2; @Value("${edison.mongo.connectionpool.maxLifeTime:100000}") private int maxConnectionLifeTime = 100000; @Value("${edison.mongo.connectionpool.maxIdleTime:10000}") private int maxConnectionIdleTime = 10000; @Value("${edison.mongo.db}") private String databaseName = ""; @Value("${edison.mongo.user:}") private String databaseUser = ""; @Value("${edison.mongo.passwd:}") private String databasePasswd; @Value("${edison.mongo.host:localhost}") public void setDatabaseServers(String[] servers) { this.databaseServers = Stream.of(servers) .filter(s -> s != null) .map(this::toServerAddress) .filter(s -> s != null) .collect(toList()); } @Bean @ConditionalOnMissingBean(value = MongoClient.class) public MongoClient mongoClient() { LOG.info("Creating MongoClient"); final MongoClientOptions settings = MongoClientOptions.builder() .minConnectionsPerHost(connectionsPerHostMin) .connectionsPerHost(connectionsPerHostMax) .connectTimeout(connectTimeout) .serverSelectionTimeout(serverSelectionTimeout) .cursorFinalizerEnabled(true) .maxConnectionIdleTime(maxConnectionIdleTime) .maxConnectionLifeTime(maxConnectionLifeTime) .maxWaitTime(maxWaitTime) .socketTimeout(socketTimeout) .threadsAllowedToBlockForConnectionMultiplier(blockedConnectionMultiplier) .build(); return new MongoClient(databaseServers, getMongoCredentials(), settings); } @Bean @ConditionalOnMissingBean(MongoDatabase.class) public MongoDatabase mongoDatabase() { return mongoClient().getDatabase(databaseName); } private List<MongoCredential> getMongoCredentials() { if (useUnauthorizedConnection()) { return Collections.emptyList(); } return asList( createCredential( databaseUser, databaseName, databasePasswd.toCharArray())); } private boolean useUnauthorizedConnection() { return databaseUser.isEmpty() || databasePasswd.isEmpty(); } private ServerAddress toServerAddress(String server) { try { if (server.contains(":")) { String[] hostNamePortPair = server.split(":"); return new ServerAddress(hostNamePortPair[0], Integer.parseInt(hostNamePortPair[1])); } else { return new ServerAddress(server); } } catch (final NumberFormatException e) { LOG.warn("Invalid portNumber: " + e.getMessage(), e); return null; } } }
edison-mongo/src/main/java/de/otto/edison/mongo/MongoConfiguration.java
package de.otto.edison.mongo; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoDatabase; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static com.mongodb.MongoCredential.createCredential; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.slf4j.LoggerFactory.getLogger; @Configuration public class MongoConfiguration { private static final Logger LOG = getLogger(MongoConfiguration.class); private List<ServerAddress> databaseServers; @Value("${edison.mongo.maxWaitTime:5000}") private int maxWaitTime = 5000; @Value("${edison.mongo.connectTimeout:5000}") private int connectTimeout = 5000; @Value("${edison.mongo.socketTimeout:2000}") private int socketTimeout = 10000; @Value("${edison.mongo.connectionpool.maxSize:100}") private int connectionsPerHostMax = 100; @Value("${edison.mongo.connectionpool.minSize:2}") private int connectionsPerHostMin = 2; @Value("${edison.mongo.blockedConnectionMultiplier:2}") private int blockedConnectionMultiplier = 2; @Value("${edison.mongo.connectionpool.maxLifeTime:100000}") private int maxConnectionLifeTime = 100000; @Value("${edison.mongo.connectionpool.maxIdleTime:10000}") private int maxConnectionIdleTime = 10000; @Value("${edison.mongo.db}") private String databaseName = ""; @Value("${edison.mongo.user:}") private String databaseUser = ""; @Value("${edison.mongo.passwd:}") private String databasePasswd; @Value("${edison.mongo.host:localhost}") public void setDatabaseServers(String[] servers) { this.databaseServers = Stream.of(servers) .filter(s -> s != null) .map(this::toServerAddress) .filter(s -> s != null) .collect(toList()); } @Bean @ConditionalOnMissingBean(value = MongoClient.class) public MongoClient mongoClient() { LOG.info("Creating MongoClient"); final MongoClientOptions settings = MongoClientOptions.builder() .minConnectionsPerHost(connectionsPerHostMin) .connectionsPerHost(connectionsPerHostMax) .connectTimeout(connectTimeout) .cursorFinalizerEnabled(true) .maxConnectionIdleTime(maxConnectionIdleTime) .maxConnectionLifeTime(maxConnectionLifeTime) .maxWaitTime(maxWaitTime) .socketTimeout(socketTimeout) .threadsAllowedToBlockForConnectionMultiplier(blockedConnectionMultiplier) .build(); return new MongoClient(databaseServers, getMongoCredentials(), settings); } @Bean @ConditionalOnMissingBean(MongoDatabase.class) public MongoDatabase mongoDatabase() { return mongoClient().getDatabase(databaseName); } private List<MongoCredential> getMongoCredentials() { if (useUnauthorizedConnection()) { return Collections.emptyList(); } return asList( createCredential( databaseUser, databaseName, databasePasswd.toCharArray())); } private boolean useUnauthorizedConnection() { return databaseUser.isEmpty() || databasePasswd.isEmpty(); } private ServerAddress toServerAddress(String server) { try { if (server.contains(":")) { String[] hostNamePortPair = server.split(":"); return new ServerAddress(hostNamePortPair[0], Integer.parseInt(hostNamePortPair[1])); } else { return new ServerAddress(server); } } catch (final NumberFormatException e) { LOG.warn("Invalid portNumber: " + e.getMessage(), e); return null; } } }
add serverSelectionTimeout to mongo config
edison-mongo/src/main/java/de/otto/edison/mongo/MongoConfiguration.java
add serverSelectionTimeout to mongo config
Java
apache-2.0
eec60ba9780d2046f728f454b0966ec6423c17b5
0
jitsi/jicofo,jitsi/jicofo,aaronkvanmeerten/jicofo,jitsi/jicofo,jitsi/jicofo,aaronkvanmeerten/jicofo,aaronkvanmeerten/jicofo
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.recording.jibri; import net.java.sip.communicator.impl.protocol.jabber.extensions.colibri.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.jibri.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.util.Logger; import org.jitsi.assertions.*; import org.jitsi.jicofo.*; import org.jitsi.jicofo.recording.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.protocol.xmpp.util.*; import org.jitsi.util.*; import org.jitsi.xmpp.util.*; import org.jivesoftware.smack.packet.*; import java.util.concurrent.*; /** * Handles conference recording through Jibri. * Waits for updates from {@link JibriDetector} about recorder instance * availability and publishes that information in Jicofo's MUC presence. * Handles incoming Jibri IQs coming from conference moderator to * start/stop the recording. * * @author Pawel Domas * @author Sam Whited */ public class JibriRecorder extends Recorder implements JibriListener { /** * The logger. */ static private final Logger logger = Logger.getLogger(JibriRecorder.class); /** * The number of times to retry connecting to a Jibri. */ static private final int NUM_RETRIES = 3; /** * Returns <tt>true> if given <tt>status</tt> precedes the <tt>RETRYING</tt> * status or <tt>false</tt> otherwise. */ static private boolean isPreRetryStatus(JibriIq.Status status) { return JibriIq.Status.ON.equals(status) || JibriIq.Status.RETRYING.equals(status); } /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status) || JibriIq.Status.RETRYING.equals(status); } /** * Recorded <tt>JitsiMeetConference</tt>. */ private final JitsiMeetConference conference; /** * The global config used by this instance. */ private final JitsiMeetGlobalConfig globalConfig; /** * Meet tools instance used to inject packet extensions to Jicofo's MUC * presence. */ private final OperationSetJitsiMeetTools meetTools; /** * Jibri detector which notifies about Jibri status changes. */ private final JibriDetector jibriDetector; /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * Counts retry attempts. * FIXME it makes sense to retry as long as there are Jibris available, but * currently if one Jibri will not go offline, but keep returning some error * JibriDetector may keep selecting it infinitely, as we do not blacklist * such instances yet */ private int retryAttempt = 0; /** * The stream ID received in the first Start IQ. */ private String streamID; /** * Stores reference to the reply timeout task, so that it can be cancelled * once becomes irrelevant. */ private Future<?> timeoutTrigger; /** * Creates new instance of <tt>JibriRecorder</tt>. * @param conference <tt>JitsiMeetConference</tt> to be recorded by new * instance. * @param xmpp XMPP operation set which wil be used to send XMPP queries. * @param scheduledExecutor the executor service used by this instance * @param globalConfig the global config that provides some values required * by <tt>JibriRecorder</tt> to work. */ public JibriRecorder(JitsiMeetConference conference, OperationSetDirectSmackXmpp xmpp, ScheduledExecutorService scheduledExecutor, JitsiMeetGlobalConfig globalConfig) { super(null, xmpp); this.conference = conference; this.scheduledExecutor = scheduledExecutor; this.globalConfig = globalConfig; Assert.notNull(conference, "conference"); Assert.notNull(globalConfig, "globalConfig"); Assert.notNull(scheduledExecutor, "scheduledExecutor"); ProtocolProviderService protocolService = conference.getXmppProvider(); meetTools = protocolService.getOperationSet(OperationSetJitsiMeetTools.class); jibriDetector = conference.getServices().getJibriDetector(); } /** * Starts listening for Jibri updates and initializes Jicofo presence. * * {@inheritDoc} */ @Override public void init() { super.init(); jibriDetector.addJibriListener(this); updateJibriAvailability(); } /** * {@inheritDoc} */ @Override public void dispose() { XMPPError error = sendStopIQ(); if (error != null) { logger.error("Error when sending stop request: " + error.toXML()); } jibriDetector.removeJibriListener(this); super.dispose(); } /** * {@inheritDoc} */ @Override public boolean isRecording() { return JibriIq.Status.ON.equals(jibriStatus); } /** * Not implemented in Jibri Recorder * * {@inheritDoc} */ @Override public boolean setRecording(String from, String token, ColibriConferenceIQ.Recording.State doRecord, String path) { // NOT USED return false; } private String getRoomName() { return conference.getRoomName(); } /** * Accepts only {@link JibriIq} * {@inheritDoc} */ @Override public boolean accept(Packet packet) { return packet instanceof JibriIq || (packet instanceof IQ && recorderComponentJid != null && recorderComponentJid.equals(packet.getFrom())); } /** * Sends an IQ to the given Jibri instance and asks it to start recording. */ private void startJibri(final String jibriJid) { logger.info("Starting Jibri " + jibriJid + " for stream ID: " + streamID + " in room: " + getRoomName()); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.SET); startIq.setAction(JibriIq.Action.START); startIq.setStreamId(streamID); // Insert name of the room into Jibri START IQ startIq.setRoom(getRoomName()); // Store Jibri JID to make the packet filter accept the response recorderComponentJid = jibriJid; // We're now in PENDING state(waiting for Jibri ON update) // Setting PENDING status also blocks from accepting // new start requests setJibriStatus(isPreRetryStatus(jibriStatus) ? JibriIq.Status.RETRYING : JibriIq.Status.PENDING); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); // Clear the old timeout trigger if any cancelTimeoutTrigger(); // Send start IQ on separate thread to not block, the packet processor // thread and still be able to detect eventual timeout. The response is // processed in processPacket(). timeoutTrigger = scheduledExecutor.submit(new Runnable() { @Override public void run() { final IQ startReply = (IQ) xmpp.getXmppConnection() .sendPacketAndGetReply(startIq); if (startReply == null) { synchronized (JibriRecorder.this) { // Trigger request timeout logger.info( "Will trigger timeout in room: " + getRoomName()); processJibriError(new XMPPError( XMPPError.Condition.request_timeout)); } } //else the response will be handled in processPacket() } }); } private void cancelTimeoutTrigger() { if (timeoutTrigger != null) { timeoutTrigger.cancel(false); timeoutTrigger = null; } } /** * <tt>JibriIq</tt> processing. * * {@inheritDoc} */ @Override synchronized public void processPacket(Packet packet) { if (logger.isDebugEnabled()) { logger.debug("Processing an IQ from Jibri: " + packet.toXML()); } IQ iq = (IQ) packet; String from = iq.getFrom(); if (iq instanceof JibriIq) { JibriIq jibriIq = (JibriIq) iq; if (recorderComponentJid != null && (from.equals(recorderComponentJid) || (from + "/").startsWith(recorderComponentJid))) { processJibriIqFromJibri(jibriIq); } else { String roomName = MucUtil.extractRoomNameFromMucJid(from); if (roomName == null) { logger.warn("Could not extract room name from jid:" + from); return; } String actualRoomName = getRoomName(); if (!actualRoomName.equals(roomName)) { logger.warn( "Ignored packet from: " + roomName + ", my room: " + actualRoomName + " p: " + packet.toXML()); return; } XmppChatMember chatMember = conference.findMember(from); if (chatMember == null) { logger.warn("ERROR chat member not found for: " + from + " in " + roomName); return; } processJibriIqFromMeet(jibriIq, chatMember); } } else { // We're processing Jibri response, probably an error if (IQ.Type.ERROR.equals(iq.getType())) { processJibriError(iq.getError()); } } } private void processJibriIqFromMeet(final JibriIq iq, final XmppChatMember sender) { String senderMucJid = sender.getContactAddress(); if (logger.isDebugEnabled()) { logger.debug( "Jibri request from " + senderMucJid + " iq: " + iq.toXML()); } JibriIq.Action action = iq.getAction(); if (JibriIq.Action.UNDEFINED.equals(action)) return; // verifyModeratorRole sends 'not_allowed' error on false if (!verifyModeratorRole(iq)) { logger.warn( "Ignored Jibri request from non-moderator: " + senderMucJid); return; } // start ? if (JibriIq.Action.START.equals(action) && JibriIq.Status.OFF.equals(jibriStatus) && recorderComponentJid == null) { // Store stream ID streamID = iq.getStreamId(); // Proceed if not empty if (!StringUtils.isNullOrEmpty(streamID)) { // ACK the request immediately to simplify the flow, // any error will be passed with the FAILED state sendResultResponse(iq); // Try starting Jibri on separate thread with retries tryStartRestartJibri(null); return; } else { // Bad request - no stream ID sendErrorResponse( iq, XMPPError.Condition.bad_request, "Stream ID is empty or undefined"); return; } } // stop ? else if (JibriIq.Action.STOP.equals(action) && recorderComponentJid != null && (JibriIq.Status.ON.equals(jibriStatus) || isStartingStatus(jibriStatus))) { // XXX FIXME: this is synchronous and will probably block the smack // thread that executes processPacket(). XMPPError error = sendStopIQ(); sendPacket( error == null ? IQ.createResultIQ(iq) : IQ.createErrorResponse(iq, error)); return; } logger.warn( "Discarded: " + iq.toXML() + " - nothing to be done, " + "recording status:" + jibriStatus); // Bad request sendErrorResponse( iq, XMPPError.Condition.bad_request, "Unable to handle: '" + action + "' in state: '" + jibriStatus + "'"); } /** * Processes an error received from Jibri. */ private void processJibriError(XMPPError error) { if (recorderComponentJid != null) { logger.info(recorderComponentJid + " failed for room " + getRoomName() + " with " + (error != null ? error.toXML() : "null")); tryStartRestartJibri(error); } else { logger.warn("Triggered error while not recording: " + error.toXML() + " in: " + getRoomName()); } } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info("Rescheduling pending timeout task for room: " + getRoomName()); pendingTimeoutTask.cancel(false); } int pendingTimeout = globalConfig.getJibriPendingTimeout(); if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } private boolean verifyModeratorRole(JibriIq iq) { String from = iq.getFrom(); ChatRoomMemberRole role = conference.getRoleForMucJid(from); if (role == null) { // Only room members are allowed to send requests sendErrorResponse(iq, XMPPError.Condition.forbidden, null); return false; } if (ChatRoomMemberRole.MODERATOR.compareTo(role) < 0) { // Moderator permission is required sendErrorResponse(iq, XMPPError.Condition.not_allowed, null); return false; } return true; } private void sendPacket(Packet packet) { xmpp.getXmppConnection().sendPacket(packet); } private void sendResultResponse(IQ request) { sendPacket( IQ.createResultIQ(request)); } private void sendErrorResponse(IQ request, XMPPError.Condition condition, String msg) { sendPacket( IQ.createErrorResponse( request, new XMPPError(condition, msg) ) ); } private void processJibriIqFromJibri(JibriIq iq) { if (IQ.Type.RESULT.equals(iq.getType())) return; // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { String roomName = getRoomName(); logger.info("Updating status from Jibri: " + iq.toXML() + " for " + roomName); // We stop either on "off" or on "failed" if ((JibriIq.Status.OFF.equals(status) || JibriIq.Status.FAILED.equals(status)) && recorderComponentJid != null/* This means we're recording */) { // Make sure that there is XMPPError for eventual ERROR status XMPPError error = iq.getError(); if (JibriIq.Status.FAILED.equals(status) && error == null) { error = new XMPPError( XMPPError.Condition.interna_server_error, "Unknown error"); } processJibriError(error); } else { setJibriStatus(status); } } sendResultResponse(iq); } private void setJibriStatus(JibriIq.Status newStatus) { setJibriStatus(newStatus, null); } private void setJibriStatus(JibriIq.Status newStatus, XMPPError error) { jibriStatus = newStatus; // Clear "pending" status timeout if we enter state other than "pending" if (pendingTimeoutTask != null && !JibriIq.Status.PENDING.equals(newStatus)) { pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } if (JibriIq.Status.ON.equals(newStatus)) { // Reset retry counter retryAttempt = 0; } RecordingStatus recordingStatus = new RecordingStatus(); recordingStatus.setStatus(newStatus); recordingStatus.setError(error); logger.info( "Publish new Jibri status: " + recordingStatus.toXML() + " in: " + getRoomName()); ChatRoom2 chatRoom2 = conference.getChatRoom(); // Publish that in the presence if (chatRoom2 != null) { meetTools.sendPresenceExtension( chatRoom2, recordingStatus); } } /** * Sends a "stop" command to jibri. */ private XMPPError sendStopIQ() { if (recorderComponentJid == null) return null; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.SET); stopRequest.setTo(recorderComponentJid); stopRequest.setAction(JibriIq.Action.STOP); logger.debug("Trying to stop: " + stopRequest.toXML()); IQ stopReply = (IQ) xmpp.getXmppConnection() .sendPacketAndGetReply(stopRequest); logger.debug("Stop response: " + IQUtils.responseToXML(stopReply)); if (stopReply == null) { return new XMPPError(XMPPError.Condition.request_timeout, null); } if (IQ.Type.RESULT.equals(stopReply.getType())) { logger.info( "Recording stopped on user request in " + getRoomName()); recordingStopped(null); return null; } else { XMPPError error = stopReply.getError(); if (error == null) { error = new XMPPError(XMPPError.Condition.interna_server_error); } return error; } } /** * Methods clears {@link #recorderComponentJid} which means we're no longer * recording nor in contact with any Jibri instance. * Refreshes recording status in the room based on Jibri availability. * * @param error if the recording stopped because of an error it should be * passed as an argument here which will result in stopping with * the {@link JibriIq.Status#FAILED} status passed to the application. */ private void recordingStopped(XMPPError error) { logger.info("Recording stopped for: " + getRoomName()); recorderComponentJid = null; retryAttempt = 0; cancelTimeoutTrigger(); // First we'll send an error and then follow with availability status if (error != null) { setJibriStatus(JibriIq.Status.FAILED, error); } // Update based on availability updateJibriAvailability(); } /** * The method is supposed to update Jibri availability status to OFF if we * have any Jibris available or to UNDEFINED if there are no any. */ private void updateJibriAvailability() { if (jibriDetector.selectJibri() != null) { setJibriStatus(JibriIq.Status.OFF); } else if (jibriDetector.isAnyJibriConnected()) { setJibriStatus(JibriIq.Status.BUSY); } else { setJibriStatus(JibriIq.Status.UNDEFINED); } } @Override synchronized public void onJibriStatusChanged(String jibriJid, boolean idle) { // We listen to status updates coming from our Jibri through IQs // if recording is in progress(recorder JID is not null), // otherwise it is fine to update Jibri recording availability here if (recorderComponentJid == null) { updateJibriAvailability(); } } @Override synchronized public void onJibriOffline(final String jibriJid) { if (jibriJid.equals(recorderComponentJid)) { logger.warn("Jibri went offline: " + recorderComponentJid + " for room: " + getRoomName()); tryStartRestartJibri( new XMPPError( XMPPError.Condition.remote_server_error, "Jibri disconnected unexpectedly")); } else if (recorderComponentJid == null) { updateJibriAvailability(); } } /** * Will try to start Jibri recording if {@link #retryAttempt} < * {@link #NUM_RETRIES}. If retry limit is exceeded then will fail with * the given <tt>error</tt>. If <tt>error</tt> is <tt>null</tt> either * "service unavailable"(no Jibri available) or "retry limit exceeded" * will be used. * @param error optional <tt>XMPPError</tt> to fail with if the retry count * limit has been exceeded or there are no more Jibris to try with. */ private void tryStartRestartJibri(XMPPError error) { if (retryAttempt++ < NUM_RETRIES) { final String newJibriJid = jibriDetector.selectJibri(); if (newJibriJid != null) { startJibri(newJibriJid); return; } else if (error == null) { // Classify this failure as 'service not available' error = new XMPPError(XMPPError.Condition.service_unavailable); } } if (error == null) { error = new XMPPError( XMPPError.Condition.interna_server_error, "Retry limit exceeded"); } // No more retries, stop either with the error passed as an argument // or with one defined here in this method, which will provide more // details about the reason recordingStopped(error); } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriRecorder.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error("Jibri pending timeout! " + getRoomName()); XMPPError error = new XMPPError( XMPPError.Condition.remote_server_timeout); recordingStopped(error); } } } } }
src/main/java/org/jitsi/jicofo/recording/jibri/JibriRecorder.java
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.recording.jibri; import net.java.sip.communicator.impl.protocol.jabber.extensions.colibri.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.jibri.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.util.Logger; import org.jitsi.assertions.*; import org.jitsi.jicofo.*; import org.jitsi.jicofo.recording.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.protocol.xmpp.util.*; import org.jitsi.util.*; import org.jitsi.xmpp.util.*; import org.jivesoftware.smack.packet.*; import java.util.concurrent.*; /** * Handles conference recording through Jibri. * Waits for updates from {@link JibriDetector} about recorder instance * availability and publishes that information in Jicofo's MUC presence. * Handles incoming Jibri IQs coming from conference moderator to * start/stop the recording. * * @author Pawel Domas * @author Sam Whited */ public class JibriRecorder extends Recorder implements JibriListener { /** * The logger. */ static private final Logger logger = Logger.getLogger(JibriRecorder.class); /** * The number of times to retry connecting to a Jibri. */ static private final int NUM_RETRIES = 3; /** * Returns <tt>true> if given <tt>status</tt> precedes the <tt>RETRYING</tt> * status or <tt>false</tt> otherwise. */ static private boolean isPreRetryStatus(JibriIq.Status status) { return JibriIq.Status.ON.equals(status) || JibriIq.Status.RETRYING.equals(status); } /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status) || JibriIq.Status.RETRYING.equals(status); } /** * Recorded <tt>JitsiMeetConference</tt>. */ private final JitsiMeetConference conference; /** * The global config used by this instance. */ private final JitsiMeetGlobalConfig globalConfig; /** * Meet tools instance used to inject packet extensions to Jicofo's MUC * presence. */ private final OperationSetJitsiMeetTools meetTools; /** * Jibri detector which notifies about Jibri status changes. */ private final JibriDetector jibriDetector; /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * Counts retry attempts. * FIXME it makes sense to retry as long as there are Jibris available, but * currently if one Jibri will not go offline, but keep returning some error * JibriDetector may keep selecting it infinitely, as we do not blacklist * such instances yet */ private int retryAttempt = 0; /** * The stream ID received in the first Start IQ. */ private String streamID; /** * Stores reference to the reply timeout task, so that it can be cancelled * once becomes irrelevant. */ private Future<?> timeoutTrigger; /** * Creates new instance of <tt>JibriRecorder</tt>. * @param conference <tt>JitsiMeetConference</tt> to be recorded by new * instance. * @param xmpp XMPP operation set which wil be used to send XMPP queries. * @param scheduledExecutor the executor service used by this instance * @param globalConfig the global config that provides some values required * by <tt>JibriRecorder</tt> to work. */ public JibriRecorder(JitsiMeetConference conference, OperationSetDirectSmackXmpp xmpp, ScheduledExecutorService scheduledExecutor, JitsiMeetGlobalConfig globalConfig) { super(null, xmpp); this.conference = conference; this.scheduledExecutor = scheduledExecutor; this.globalConfig = globalConfig; Assert.notNull(conference, "conference"); Assert.notNull(globalConfig, "globalConfig"); Assert.notNull(scheduledExecutor, "scheduledExecutor"); ProtocolProviderService protocolService = conference.getXmppProvider(); meetTools = protocolService.getOperationSet(OperationSetJitsiMeetTools.class); jibriDetector = conference.getServices().getJibriDetector(); } /** * Starts listening for Jibri updates and initializes Jicofo presence. * * {@inheritDoc} */ @Override public void init() { super.init(); jibriDetector.addJibriListener(this); updateJibriAvailability(); } /** * {@inheritDoc} */ @Override public void dispose() { XMPPError error = sendStopIQ(); if (error != null) { logger.error("Error when sending stop request: " + error.toXML()); } jibriDetector.removeJibriListener(this); super.dispose(); } /** * {@inheritDoc} */ @Override public boolean isRecording() { return JibriIq.Status.ON.equals(jibriStatus); } /** * Not implemented in Jibri Recorder * * {@inheritDoc} */ @Override public boolean setRecording(String from, String token, ColibriConferenceIQ.Recording.State doRecord, String path) { // NOT USED return false; } private String getRoomName() { return conference.getRoomName(); } /** * Accepts only {@link JibriIq} * {@inheritDoc} */ @Override public boolean accept(Packet packet) { return packet instanceof JibriIq || (packet instanceof IQ && recorderComponentJid != null && recorderComponentJid.equals(packet.getFrom())); } /** * Sends an IQ to the given Jibri instance and asks it to start recording. */ private void startJibri(final String jibriJid) { logger.info("Starting Jibri " + jibriJid + " for stream ID: " + streamID + " in room: " + getRoomName()); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.SET); startIq.setAction(JibriIq.Action.START); startIq.setStreamId(streamID); // Insert name of the room into Jibri START IQ startIq.setRoom(getRoomName()); // Store Jibri JID to make the packet filter accept the response recorderComponentJid = jibriJid; // We're now in PENDING state(waiting for Jibri ON update) // Setting PENDING status also blocks from accepting // new start requests setJibriStatus(isPreRetryStatus(jibriStatus) ? JibriIq.Status.RETRYING : JibriIq.Status.PENDING); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); // Clear the old timeout trigger if any cancelTimeoutTrigger(); // Send start IQ on separate thread to not block, the packet processor // thread and still be able to detect eventual timeout. The response is // processed in processPacket(). timeoutTrigger = scheduledExecutor.submit(new Runnable() { @Override public void run() { final IQ startReply = (IQ) xmpp.getXmppConnection() .sendPacketAndGetReply(startIq); if (startReply == null) { synchronized (JibriRecorder.this) { // Trigger request timeout logger.info( "Will trigger timeout in room: " + getRoomName()); processError(new XMPPError( XMPPError.Condition.request_timeout)); } } //else the response will be handled in processPacket() } }); } private void cancelTimeoutTrigger() { if (timeoutTrigger != null) { timeoutTrigger.cancel(false); timeoutTrigger = null; } } /** * <tt>JibriIq</tt> processing. * * {@inheritDoc} */ @Override synchronized public void processPacket(Packet packet) { if (logger.isDebugEnabled()) { logger.debug("Processing an IQ from Jibri: " + packet.toXML()); } IQ iq = (IQ) packet; String from = iq.getFrom(); if (iq instanceof JibriIq) { JibriIq jibriIq = (JibriIq) iq; if (recorderComponentJid != null && (from.equals(recorderComponentJid) || (from + "/").startsWith(recorderComponentJid))) { processJibriIqFromJibri(jibriIq); } else { String roomName = MucUtil.extractRoomNameFromMucJid(from); if (roomName == null) { logger.warn("Could not extract room name from jid:" + from); return; } String actualRoomName = getRoomName(); if (!actualRoomName.equals(roomName)) { logger.warn( "Ignored packet from: " + roomName + ", my room: " + actualRoomName + " p: " + packet.toXML()); return; } XmppChatMember chatMember = conference.findMember(from); if (chatMember == null) { logger.warn("ERROR chat member not found for: " + from + " in " + roomName); return; } processJibriIqFromMeet(jibriIq, chatMember); } } else { // We're processing Jibri response, probably an error if (IQ.Type.ERROR.equals(iq.getType())) { processJibriError(iq.getError()); } } } private void processJibriIqFromMeet(final JibriIq iq, final XmppChatMember sender) { String senderMucJid = sender.getContactAddress(); if (logger.isDebugEnabled()) { logger.debug( "Jibri request from " + senderMucJid + " iq: " + iq.toXML()); } JibriIq.Action action = iq.getAction(); if (JibriIq.Action.UNDEFINED.equals(action)) return; // verifyModeratorRole sends 'not_allowed' error on false if (!verifyModeratorRole(iq)) { logger.warn( "Ignored Jibri request from non-moderator: " + senderMucJid); return; } // start ? if (JibriIq.Action.START.equals(action) && JibriIq.Status.OFF.equals(jibriStatus) && recorderComponentJid == null) { // Store stream ID streamID = iq.getStreamId(); // Proceed if not empty if (!StringUtils.isNullOrEmpty(streamID)) { // ACK the request immediately to simplify the flow, // any error will be passed with the FAILED state sendResultResponse(iq); // Try starting Jibri on separate thread with retries tryStartRestartJibri(null); return; } else { // Bad request - no stream ID sendErrorResponse( iq, XMPPError.Condition.bad_request, "Stream ID is empty or undefined"); return; } } // stop ? else if (JibriIq.Action.STOP.equals(action) && recorderComponentJid != null && (JibriIq.Status.ON.equals(jibriStatus) || isStartingStatus(jibriStatus))) { // XXX FIXME: this is synchronous and will probably block the smack // thread that executes processPacket(). XMPPError error = sendStopIQ(); sendPacket( error == null ? IQ.createResultIQ(iq) : IQ.createErrorResponse(iq, error)); return; } logger.warn( "Discarded: " + iq.toXML() + " - nothing to be done, " + "recording status:" + jibriStatus); // Bad request sendErrorResponse( iq, XMPPError.Condition.bad_request, "Unable to handle: '" + action + "' in state: '" + jibriStatus + "'"); } /** * Processes an error received from Jibri. */ private void processJibriError(XMPPError error) { if (recorderComponentJid != null) { logger.info(recorderComponentJid + " failed for room " + getRoomName() + " with " + (error != null ? error.toXML() : "null")); tryStartRestartJibri(error); } else { logger.warn("Triggered error while not recording: " + error.toXML() + " in: " + getRoomName()); } } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info("Rescheduling pending timeout task for room: " + getRoomName()); pendingTimeoutTask.cancel(false); } int pendingTimeout = globalConfig.getJibriPendingTimeout(); if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } private boolean verifyModeratorRole(JibriIq iq) { String from = iq.getFrom(); ChatRoomMemberRole role = conference.getRoleForMucJid(from); if (role == null) { // Only room members are allowed to send requests sendErrorResponse(iq, XMPPError.Condition.forbidden, null); return false; } if (ChatRoomMemberRole.MODERATOR.compareTo(role) < 0) { // Moderator permission is required sendErrorResponse(iq, XMPPError.Condition.not_allowed, null); return false; } return true; } private void sendPacket(Packet packet) { xmpp.getXmppConnection().sendPacket(packet); } private void sendResultResponse(IQ request) { sendPacket( IQ.createResultIQ(request)); } private void sendErrorResponse(IQ request, XMPPError.Condition condition, String msg) { sendPacket( IQ.createErrorResponse( request, new XMPPError(condition, msg) ) ); } private void processJibriIqFromJibri(JibriIq iq) { if (IQ.Type.RESULT.equals(iq.getType())) return; // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { String roomName = getRoomName(); logger.info("Updating status from Jibri: " + iq.toXML() + " for " + roomName); // We stop either on "off" or on "failed" if ((JibriIq.Status.OFF.equals(status) || JibriIq.Status.FAILED.equals(status)) && recorderComponentJid != null/* This means we're recording */) { // Make sure that there is XMPPError for eventual ERROR status XMPPError error = iq.getError(); if (JibriIq.Status.FAILED.equals(status) && error == null) { error = new XMPPError( XMPPError.Condition.interna_server_error, "Unknown error"); } processJibriError(error); } else { setJibriStatus(status); } } sendResultResponse(iq); } private void setJibriStatus(JibriIq.Status newStatus) { setJibriStatus(newStatus, null); } private void setJibriStatus(JibriIq.Status newStatus, XMPPError error) { jibriStatus = newStatus; // Clear "pending" status timeout if we enter state other than "pending" if (pendingTimeoutTask != null && !JibriIq.Status.PENDING.equals(newStatus)) { pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } if (JibriIq.Status.ON.equals(newStatus)) { // Reset retry counter retryAttempt = 0; } RecordingStatus recordingStatus = new RecordingStatus(); recordingStatus.setStatus(newStatus); recordingStatus.setError(error); logger.info( "Publish new Jibri status: " + recordingStatus.toXML() + " in: " + getRoomName()); ChatRoom2 chatRoom2 = conference.getChatRoom(); // Publish that in the presence if (chatRoom2 != null) { meetTools.sendPresenceExtension( chatRoom2, recordingStatus); } } /** * Sends a "stop" command to jibri. */ private XMPPError sendStopIQ() { if (recorderComponentJid == null) return null; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.SET); stopRequest.setTo(recorderComponentJid); stopRequest.setAction(JibriIq.Action.STOP); logger.debug("Trying to stop: " + stopRequest.toXML()); IQ stopReply = (IQ) xmpp.getXmppConnection() .sendPacketAndGetReply(stopRequest); logger.debug("Stop response: " + IQUtils.responseToXML(stopReply)); if (stopReply == null) { return new XMPPError(XMPPError.Condition.request_timeout, null); } if (IQ.Type.RESULT.equals(stopReply.getType())) { logger.info( "Recording stopped on user request in " + getRoomName()); recordingStopped(null); return null; } else { XMPPError error = stopReply.getError(); if (error == null) { error = new XMPPError(XMPPError.Condition.interna_server_error); } return error; } } /** * Methods clears {@link #recorderComponentJid} which means we're no longer * recording nor in contact with any Jibri instance. * Refreshes recording status in the room based on Jibri availability. * * @param error if the recording stopped because of an error it should be * passed as an argument here which will result in stopping with * the {@link JibriIq.Status#FAILED} status passed to the application. */ private void recordingStopped(XMPPError error) { logger.info("Recording stopped for: " + getRoomName()); recorderComponentJid = null; retryAttempt = 0; cancelTimeoutTrigger(); // First we'll send an error and then follow with availability status if (error != null) { setJibriStatus(JibriIq.Status.FAILED, error); } // Update based on availability updateJibriAvailability(); } /** * The method is supposed to update Jibri availability status to OFF if we * have any Jibris available or to UNDEFINED if there are no any. */ private void updateJibriAvailability() { if (jibriDetector.selectJibri() != null) { setJibriStatus(JibriIq.Status.OFF); } else if (jibriDetector.isAnyJibriConnected()) { setJibriStatus(JibriIq.Status.BUSY); } else { setJibriStatus(JibriIq.Status.UNDEFINED); } } @Override synchronized public void onJibriStatusChanged(String jibriJid, boolean idle) { // We listen to status updates coming from our Jibri through IQs // if recording is in progress(recorder JID is not null), // otherwise it is fine to update Jibri recording availability here if (recorderComponentJid == null) { updateJibriAvailability(); } } @Override synchronized public void onJibriOffline(final String jibriJid) { if (jibriJid.equals(recorderComponentJid)) { logger.warn("Jibri went offline: " + recorderComponentJid + " for room: " + getRoomName()); tryStartRestartJibri( new XMPPError( XMPPError.Condition.remote_server_error, "Jibri disconnected unexpectedly")); } else if (recorderComponentJid == null) { updateJibriAvailability(); } } /** * Will try to start Jibri recording if {@link #retryAttempt} < * {@link #NUM_RETRIES}. If retry limit is exceeded then will fail with * the given <tt>error</tt>. If <tt>error</tt> is <tt>null</tt> either * "service unavailable"(no Jibri available) or "retry limit exceeded" * will be used. * @param error optional <tt>XMPPError</tt> to fail with if the retry count * limit has been exceeded or there are no more Jibris to try with. */ private void tryStartRestartJibri(XMPPError error) { if (retryAttempt++ < NUM_RETRIES) { final String newJibriJid = jibriDetector.selectJibri(); if (newJibriJid != null) { startJibri(newJibriJid); return; } else if (error == null) { // Classify this failure as 'service not available' error = new XMPPError(XMPPError.Condition.service_unavailable); } } if (error == null) { error = new XMPPError( XMPPError.Condition.interna_server_error, "Retry limit exceeded"); } // No more retries, stop either with the error passed as an argument // or with one defined here in this method, which will provide more // details about the reason recordingStopped(error); } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriRecorder.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error("Jibri pending timeout! " + getRoomName()); XMPPError error = new XMPPError( XMPPError.Condition.remote_server_timeout); recordingStopped(error); } } } } }
Fix a compilation error.
src/main/java/org/jitsi/jicofo/recording/jibri/JibriRecorder.java
Fix a compilation error.