answer stringlengths 17 10.2M |
|---|
package tigase.net;
import tigase.cert.CertCheckResult;
import tigase.io.BufferUnderflowException;
import tigase.io.IOInterface;
import tigase.io.SocketIO;
import tigase.io.TLSEventHandler;
import tigase.io.TLSIO;
import tigase.io.TLSUtil;
import tigase.io.TLSWrapper;
import tigase.io.ZLibIO;
import tigase.stats.StatisticsList;
import tigase.xmpp.JID;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.MalformedInputException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <code>IOService</code> offers thread safe <code>call()</code> method
* execution, however you must be prepared that other methods can be called
* simultaneously like <code>stop()</code>, <code>getProtocol()</code> or
* <code>isConnected()</code>. <br/>
* It is recommended that developers extend <code>AbsractServerService</code>
* rather then implement <code>ServerService</code> interface directly.
* <p>
* If you directly implement <code>ServerService</code> interface you must take
* care about <code>SocketChannel</code> I/O, queuing tasks, processing results
* and thread safe execution of <code>call()</code> method. If you however
* extend <code>IOService</code> class all this basic operation are implemented
* and you have only to take care about parsing data received from network
* socket. Parsing data is expected to be implemented in
* <code>parseData(char[] data)</code> method.
* </p>
*
* <p>
* Created: Tue Sep 28 23:00:34 2004
* </p>
*
* @param <RefObject>
* is a reference object stored by this service. This is e reference to
* higher level data object keeping more information about the
* connection.
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public abstract class IOService<RefObject> implements Callable<IOService<?>>,
TLSEventHandler {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger(IOService.class.getName());
/**
* This is key used to store session ID in temporary session data storage. As
* it is used by many components it is required that all components access
* session ID with this constant.
*/
public static final String SESSION_ID_KEY = "sessionID";
/** Field description */
public static final String PORT_TYPE_PROP_KEY = "type";
/** Field description */
public static final String HOSTNAME_KEY = "hostname-key";
private static final long MAX_ALLOWED_EMPTY_CALLS = 1000;
/** Field description */
public static final String CERT_CHECK_RESULT = "cert-check-result";
private ConnectionType connectionType = null;
private JID dataReceiver = null;
/** Field description */
private long empty_read_call_count = 0;
private String id = null;
/**
* This variable keeps the time of last transfer in any direction it is used
* to help detect dead connections.
*/
private long lastTransferTime = 0;
private String local_address = null;
private long[] rdData = new long[60];
private RefObject refObject = null;
private String remote_address = null;
private IOServiceListener<IOService<RefObject>> serviceListener = null;
private IOInterface socketIO = null;
/** The saved partial bytes for multi-byte UTF-8 characters between reads */
private byte[] partialCharacterBytes = null;
/**
* <code>socketInput</code> buffer keeps data read from socket.
*/
private ByteBuffer socketInput = null;
private int socketInputSize = 2048;
private boolean stopping = false;
private long[] wrData = new long[60];
private ConcurrentMap<String, Object> sessionData =
new ConcurrentHashMap<String, Object>(4, 0.75f, 4);
private CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
private CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
private CharBuffer cb = CharBuffer.allocate(2048);
private final ReentrantLock writeInProgress = new ReentrantLock();
private final ReentrantLock readInProgress = new ReentrantLock();
/**
* Method description
*
*
* @throws IOException
*/
public abstract void processWaitingPackets() throws IOException;
protected abstract void processSocketData() throws IOException;
protected abstract int receivedPackets();
/**
* Method <code>accept</code> is used to perform
*
* @param socketChannel
* a <code>SocketChannel</code> value
*
* @throws IOException
*/
public void accept(final SocketChannel socketChannel) throws IOException {
try {
if (socketChannel.isConnectionPending()) {
socketChannel.finishConnect();
} // end of if (socketChannel.isConnecyionPending())
socketIO = new SocketIO(socketChannel);
} catch (IOException e) {
String host = (String) sessionData.get("remote-hostname");
if (host == null) {
host = (String) sessionData.get("remote-host");
}
log.log(Level.INFO,
"Problem connecting to remote host: {0}, address: {1} - exception: {2}",
new Object[] { host, remote_address, e });
throw e;
}
socketInputSize = socketIO.getSocketChannel().socket().getReceiveBufferSize();
socketInput = ByteBuffer.allocate(socketInputSize);
Socket sock = socketIO.getSocketChannel().socket();
local_address = sock.getLocalAddress().getHostAddress();
remote_address = sock.getInetAddress().getHostAddress();
id =
local_address + "_" + sock.getLocalPort() + "_" + remote_address + "_"
+ sock.getPort();
setLastTransferTime();
}
/**
* Method <code>run</code> is used to perform
*
*
* @return
* @throws IOException
*/
@Override
public IOService<?> call() throws IOException {
writeData(null);
boolean readLock = true;
if (stopping) {
stop();
} else {
readLock = readInProgress.tryLock();
if (readLock) {
try {
processSocketData();
if ((receivedPackets() > 0) && (serviceListener != null)) {
serviceListener.packetsReady(this);
} // end of if (receivedPackets.size() > 0)
} finally {
readInProgress.unlock();
}
}
}
return readLock ? this : null;
}
/**
* Method description
*
*
* @return
*/
public ConnectionType connectionType() {
return this.connectionType;
}
/**
* Method description
*
*/
public void forceStop() {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Socket: {0}, Force stop called...", socketIO);
}
try {
if ((socketIO != null) && socketIO.isConnected()) {
synchronized (socketIO) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Calling stop on: {0}", socketIO);
}
socketIO.stop();
}
}
} catch (Exception e) {
// Well, do nothing, we are closing the connection anyway....
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Socket: " + socketIO
+ ", Exception while stopping service: " + getUniqueId(), e);
}
} finally {
if (serviceListener != null) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Calling stop on the listener: {0}", serviceListener);
}
IOServiceListener<IOService<RefObject>> tmp = serviceListener;
serviceListener = null;
// The temp can still be null if the forceStop is called concurrently
if (tmp != null) {
tmp.serviceStopped(this);
}
} else {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Service listener is null: {0}", socketIO);
}
}
}
}
/**
* Method description
*
*
* @return
*/
public JID getDataReceiver() {
return this.dataReceiver;
}
/**
* This method returns the time of last transfer in any direction through this
* service. It is used to help detect dead connections.
*
* @return
*/
public long getLastTransferTime() {
return lastTransferTime;
}
/**
* Method description
*
*
* @return
*/
public String getLocalAddress() {
return local_address;
}
/**
* Method description
*
*
* @return
*/
public long[] getReadCounters() {
return rdData;
}
/**
* Method description
*
*
* @return
*/
public RefObject getRefObject() {
return refObject;
}
/**
* Returns a remote IP address for the TCP/IP connection.
*
*
* @return a remote IP address for the TCP/IP connection.
*/
public String getRemoteAddress() {
return remote_address;
}
/**
* Method description
*
*
* @return
*/
public ConcurrentMap<String, Object> getSessionData() {
return sessionData;
}
/**
* Method <code>getSocketChannel</code> is used to perform
*
* @return a <code>SocketChannel</code> value
*/
public SocketChannel getSocketChannel() {
return socketIO.getSocketChannel();
}
/**
* Method description
*
*
* @param list
* @param reset
*/
public void getStatistics(StatisticsList list, boolean reset) {
if (socketIO != null) {
socketIO.getStatistics(list, reset);
}
}
/**
* Method description
*
*
* @return
*/
public String getUniqueId() {
return id;
}
/**
* Method description
*
*
* @return
*/
public long[] getWriteCounters() {
return wrData;
}
/**
* Method description
*
*
* @param wrapper
*/
@Override
public void handshakeCompleted(TLSWrapper wrapper) {
CertCheckResult certCheckResult = wrapper.getCertificateStatus(false);
sessionData.put(CERT_CHECK_RESULT, certCheckResult);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0}, TLS handshake completed: {1}", new Object[] { this,
certCheckResult });
}
serviceListener.tlsHandshakeCompleted(this);
}
/**
* Describe <code>isConnected</code> method here.
*
* @return a <code>boolean</code> value
*/
public boolean isConnected() {
boolean result = (socketIO == null) ? false : socketIO.isConnected();
if (log.isLoggable(Level.FINEST)) {
// if (socketIO.getSocketChannel().socket().getLocalPort() == 5269) {
// Throwable thr = new Throwable();
// thr.fillInStackTrace();
// log.log(Level.FINEST, "Socket: " + socketIO + ", Connected: " + result,
// thr);
log.log(Level.FINEST, "Socket: {0}, Connected: {1}, id: {2}", new Object[] {
socketIO, result, id });
}
return result;
}
/**
* Method description
*
*
* @param address
*/
public void setDataReceiver(JID address) {
this.dataReceiver = address;
}
/**
* Method description
*
*
* @param sl
*/
// @SuppressWarnings("unchecked")
public void setIOServiceListener(IOServiceListener<IOService<RefObject>> sl) {
this.serviceListener = sl;
}
/**
* Method description
*
*
* @param refObject
*/
public void setRefObject(RefObject refObject) {
this.refObject = refObject;
}
/**
* Method description
*
*
* @param props
*/
public void setSessionData(Map<String, Object> props) {
sessionData = new ConcurrentHashMap<String, Object>(props);
connectionType =
ConnectionType.valueOf(sessionData.get(PORT_TYPE_PROP_KEY).toString());
}
/**
* Method description
*
*
* @param clientMode
*
* @throws IOException
*/
public void startSSL(boolean clientMode) throws IOException {
if (socketIO instanceof TLSIO) {
throw new IllegalStateException("SSL mode is already activated.");
}
TLSWrapper wrapper =
new TLSWrapper(TLSUtil.getSSLContext("SSL",
(String) sessionData.get(HOSTNAME_KEY)), this, clientMode);
socketIO = new TLSIO(socketIO, wrapper);
setLastTransferTime();
encoder.reset();
decoder.reset();
}
/**
* Method description
*
*
* @param clientMode
*
* @throws IOException
*/
public void startTLS(boolean clientMode) throws IOException {
if (socketIO.checkCapabilities(TLSIO.TLS_CAPS)) {
throw new IllegalStateException("TLS mode is already activated.");
}
// This should not take more then 100ms
int counter = 0;
while (isConnected() && waitingToSend() && (++counter < 10)) {
writeData(null);
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
}
}
if (counter >= 10) {
stop();
} else {
String tls_hostname = (String) sessionData.get(HOSTNAME_KEY);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "{0}, Starting TLS for domain: {1}", new Object[] { this,
tls_hostname });
}
TLSWrapper wrapper =
new TLSWrapper(TLSUtil.getSSLContext("TLS", tls_hostname), this, clientMode);
socketIO = new TLSIO(socketIO, wrapper);
setLastTransferTime();
encoder.reset();
decoder.reset();
}
}
/**
* Method description
*
*
* @param level
*/
public void startZLib(int level) {
if (socketIO.checkCapabilities(ZLibIO.ZLIB_CAPS)) {
throw new IllegalStateException("ZLIB mode is already activated.");
}
socketIO = new ZLibIO(socketIO, level);
}
/**
* Describe <code>stop</code> method here.
*
*/
public void stop() {
if ((socketIO != null) && socketIO.waitingToSend()) {
stopping = true;
} else {
forceStop();
}
}
/**
* Method description
*
*
* @return
*/
@Override
public String toString() {
return this.getUniqueId() + ", type: " + connectionType + ", Socket: " + socketIO;
}
/**
* Method description
*
*
* @return
*/
public boolean waitingToSend() {
return socketIO.waitingToSend();
}
/**
* Method description
*
*
* @return
*/
public int waitingToSendSize() {
return socketIO.waitingToSendSize();
}
/**
* Describe <code>debug</code> method here.
*
* @param msg
* a <code>char[]</code> value
* @return a <code>boolean</code> value
*/
protected boolean debug(final char[] msg) {
if (msg != null) {
System.out.print(new String(msg));
// log.finest("\n" + new String(msg) + "\n");
} // end of if (msg != null)
return true;
}
/**
* Describe <code>debug</code> method here.
*
* @param msg
* a <code>String</code> value
* @return a <code>boolean</code> value
*/
protected boolean debug(final String msg, final String prefix) {
if (log.isLoggable(Level.FINEST)) {
if ((msg != null) && (msg.trim().length() > 0)) {
String log_msg =
"\n"
+ ((connectionType() != null) ? connectionType().toString() : "null-type")
+ " " + prefix + "\n" + msg + "\n";
// System.out.print(log_msg);
log.finest(log_msg);
}
}
return true;
}
protected void readCompleted() {
decoder.reset();
}
/**
* Describe <code>readData</code> method here.
*
* @return a <code>char[]</code> value
* @exception IOException
* if an error occurs
*/
protected char[] readData() throws IOException {
setLastTransferTime();
if (log.isLoggable(Level.FINEST) && (empty_read_call_count > 10)) {
Throwable thr = new Throwable();
thr.fillInStackTrace();
log.log(Level.FINEST, "Socket: " + socketIO, thr);
}
// Generally it should not happen as it is called only in
// call() which has concurrent call protection.
// synchronized (socketIO) {
try {
// resizeInputBuffer();
// Maybe we can shrink the input buffer??
if ((socketInput.capacity() > socketInputSize)
&& (socketInput.remaining() == socketInput.capacity())) {
// Yes, looks like we can
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Socket: {0}, Resizing socketInput down to {1} bytes.",
new Object[] { socketIO, socketInputSize });
}
socketInput = ByteBuffer.allocate(socketInputSize);
cb = CharBuffer.allocate(socketInputSize * 4);
}
// if (log.isLoggable(Level.FINEST)) {
// log.finer("Before read from socket.");
// log.finer("socketInput.capacity()=" + socketInput.capacity());
// log.finer("socketInput.remaining()=" + socketInput.remaining());
// log.finer("socketInput.limit()=" + socketInput.limit());
// log.finer("socketInput.position()=" + socketInput.position());
ByteBuffer tmpBuffer = socketIO.read(socketInput);
if (socketIO.bytesRead() > 0) {
empty_read_call_count = 0;
char[] result = null;
// There might be some characters read from the network
// but the buffer may still be null or empty because there might
// be not enough data to decode TLS or compressed buffer.
if (tmpBuffer != null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Socket: {0}, Reading network binary data: {1}",
new Object[] { socketIO, socketIO.bytesRead() });
}
// Restore the partial bytes for multibyte UTF8 characters
if (partialCharacterBytes != null) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Reloading partial bytes " + partialCharacterBytes.length);
}
ByteBuffer oldTmpBuffer = tmpBuffer;
tmpBuffer =
ByteBuffer.allocate(partialCharacterBytes.length
+ oldTmpBuffer.remaining() + 2);
tmpBuffer.put(partialCharacterBytes);
tmpBuffer.put(oldTmpBuffer);
tmpBuffer.flip();
oldTmpBuffer.clear();
partialCharacterBytes = null;
}
// if (log.isLoggable(Level.FINEST)) {
// log.finer("Before decoding data");
// log.finer("socketInput.capacity()=" + socketInput.capacity());
// log.finer("socketInput.remaining()=" + socketInput.remaining());
// log.finer("socketInput.limit()=" + socketInput.limit());
// log.finer("socketInput.position()=" + socketInput.position());
// log.finer("tmpBuffer.capacity()=" + tmpBuffer.capacity());
// log.finer("tmpBuffer.remaining()=" + tmpBuffer.remaining());
// log.finer("tmpBuffer.limit()=" + tmpBuffer.limit());
// log.finer("tmpBuffer.position()=" + tmpBuffer.position());
// log.finer("cb.capacity()=" + cb.capacity());
// log.finer("cb.remaining()=" + cb.remaining());
// log.finer("cb.limit()=" + cb.limit());
// log.finer("cb.position()=" + cb.position());
// tmpBuffer.flip();
if (cb.capacity() < tmpBuffer.remaining() * 4) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Socket: {0}, resizing character buffer to: {1}",
new Object[] { socketIO, tmpBuffer.remaining() });
}
cb = CharBuffer.allocate(tmpBuffer.remaining() * 4);
}
CoderResult cr = decoder.decode(tmpBuffer, cb, false);
if (cr.isMalformed()) {
throw new MalformedInputException(tmpBuffer.remaining());
}
if (cb.remaining() > 0) {
cb.flip();
result = new char[cb.remaining()];
cb.get(result);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Socket: {0}, Decoded character data: {1}",
new Object[] { socketIO, new String(result) });
}
// if (log.isLoggable(Level.FINEST)) {
// log.finer("Just after decoding.");
// log.finer("tmpBuffer.capacity()=" + tmpBuffer.capacity());
// log.finer("tmpBuffer.remaining()=" + tmpBuffer.remaining());
// log.finer("tmpBuffer.limit()=" + tmpBuffer.limit());
// log.finer("tmpBuffer.position()=" + tmpBuffer.position());
// log.finer("cb.capacity()=" + cb.capacity());
// log.finer("cb.remaining()=" + cb.remaining());
// log.finer("cb.limit()=" + cb.limit());
// log.finer("cb.position()=" + cb.position());
}
if (cr.isUnderflow() && (tmpBuffer.remaining() > 0)) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Socket: {0}, UTF-8 decoder data underflow: {1}",
new Object[] { socketIO, tmpBuffer.remaining() });
}
// Save the partial bytes of a multibyte character such that they
// can be restored on the next read.
partialCharacterBytes = new byte[tmpBuffer.remaining()];
tmpBuffer.get(partialCharacterBytes);
}
tmpBuffer.clear();
cb.clear();
// if (log.isLoggable(Level.FINEST)) {
// log.finer("Before return from method.");
// log.finer("tmpBuffer.capacity()=" + tmpBuffer.capacity());
// log.finer("tmpBuffer.remaining()=" + tmpBuffer.remaining());
// log.finer("tmpBuffer.limit()=" + tmpBuffer.limit());
// log.finer("tmpBuffer.position()=" + tmpBuffer.position());
// log.finer("cb.capacity()=" + cb.capacity());
// log.finer("cb.remaining()=" + cb.remaining());
// log.finer("cb.limit()=" + cb.limit());
// log.finer("cb.position()=" + cb.position());
return result;
}
} else {
// Detecting infinite read 0 bytes
// sometimes it happens that the connection has been lost
// and the select thinks there are some bytes waiting for reading
// and 0 bytes are read
if ((++empty_read_call_count) > MAX_ALLOWED_EMPTY_CALLS
&& (!writeInProgress.isLocked())) {
log.log(Level.WARNING,
"Socket: {0}, Max allowed empty calls excceeded, closing connection.",
socketIO);
forceStop();
}
}
} catch (BufferUnderflowException ex) {
// Obtain more inbound network data for src,
// then retry the operation.
resizeInputBuffer();
return null;
// } catch (MalformedInputException ex) {
// // This happens after TLS initialization sometimes, maybe reset helps
// decoder.reset();
} catch (Exception eof) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Socket: " + socketIO + ", Exception reading data", eof);
}
// eof.printStackTrace();
forceStop();
} // end of try-catch
return null;
}
/**
* Describe <code>writeData</code> method here.
*
* @param data
* a <code>String</code> value
*/
protected void writeData(final String data) {
// Try to lock the data writing method
boolean locked = writeInProgress.tryLock();
// If cannot lock and nothing to send, just leave
if (!locked && (data == null)) {
return;
}
// Otherwise wait.....
if (!locked) {
writeInProgress.lock();
}
// Avoid concurrent calls here (one from call() and another from
// application)
try {
if ((data != null) && (data.length() > 0)) {
if (log.isLoggable(Level.FINEST)) {
if (data.length() < 256) {
log.log(Level.FINEST, "Socket: {0}, Writing data ({1}): {2}", new Object[] {
socketIO, data.length(), data });
} else {
log.log(Level.FINEST, "Socket: {0}, Writing data: {1}", new Object[] {
socketIO, data.length() });
}
}
ByteBuffer dataBuffer = null;
// int out_buff_size = data.length();
// int idx_start = 0;
// int idx_offset = Math.min(idx_start + out_buff_size, data.length());
// while (idx_start < data.length()) {
// String data_str = data.substring(idx_start, idx_offset);
// if (log.isLoggable(Level.FINEST)) {
// log.finest("Writing data_str (" + data_str.length() + "), idx_start="
// + idx_start + ", idx_offset=" + idx_offset + ": " + data_str);
encoder.reset();
// dataBuffer = encoder.encode(CharBuffer.wrap(data, idx_start,
// idx_offset));
dataBuffer = encoder.encode(CharBuffer.wrap(data));
encoder.flush(dataBuffer);
socketIO.write(dataBuffer);
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Socket: {0}, wrote: {1}",
new Object[] { socketIO, data.length() });
}
// idx_start = idx_offset;
// idx_offset = Math.min(idx_start + out_buff_size, data.length());
setLastTransferTime();
// addWritten(data.length());
empty_read_call_count = 0;
} else {
if (socketIO.waitingToSend()) {
socketIO.write(null);
setLastTransferTime();
empty_read_call_count = 0;
}
}
} catch (Exception e) {
if (log.isLoggable(Level.FINER)) {
log.log(Level.FINER, "Data writing exception", e);
}
forceStop();
} finally {
writeInProgress.unlock();
}
}
private void resizeInputBuffer() throws IOException {
int netSize = socketIO.getInputPacketSize();
// Resize buffer if needed.
// if (netSize > socketInput.remaining()) {
if (netSize > socketInput.capacity() - socketInput.remaining()) {
// int newSize = netSize + socketInput.capacity();
int newSize = socketInput.capacity() + socketInputSize;
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Socket: {0}, Resizing socketInput to {1} bytes.",
new Object[] { socketIO, newSize });
}
ByteBuffer b = ByteBuffer.allocate(newSize);
b.put(socketInput);
socketInput = b;
} else {
// if (log.isLoggable(Level.FINEST)) {
// log.finer(" Before flip()");
// log.finer("input.capacity()=" + socketInput.capacity());
// log.finer("input.remaining()=" + socketInput.remaining());
// log.finer("input.limit()=" + socketInput.limit());
// log.finer("input.position()=" + socketInput.position());
// socketInput.flip();
// if (log.isLoggable(Level.FINEST)) {
// log.finer(" Before compact()");
// log.finer("input.capacity()=" + socketInput.capacity());
// log.finer("input.remaining()=" + socketInput.remaining());
// log.finer("input.limit()=" + socketInput.limit());
// log.finer("input.position()=" + socketInput.position());
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Socket: {0}, Compacting socketInput.", socketIO);
}
socketInput.compact();
// if (log.isLoggable(Level.FINEST)) {
// log.finer(" After compact()");
// log.finer("input.capacity()=" + socketInput.capacity());
// log.finer("input.remaining()=" + socketInput.remaining());
// log.finer("input.limit()=" + socketInput.limit());
// log.finer("input.position()=" + socketInput.position());
}
}
private void setLastTransferTime() {
lastTransferTime = System.currentTimeMillis();
}
} // IOService
// ~ Formatted in Sun Code Convention |
package tmp;
import java.util.concurrent.ThreadLocalRandom;
/**
* Implements the classic partitioning routine. Chooses a pivot and partitions the given
* array of integers around that.
*/
public class ClassicPartition {
/**
* Partitions the given array in place in O(n) time. Chooses a random pivot which is placed at the 0th index.
* The invariant maintained is that after every number (starting from index 1) is read, the pivot could
* be placed at the index that is its correctly sorted position in the subarray examined until then.
*
* @param a an integer array that is partitioned in place
* @return integer representing the index of the pivot; if this method returns a number i, then the following holds:
* <pre>
* a[j] < pivot for all 0 <= j < i, and
* a[j] >= pivot for all i+1 <= j < a.length
* </pre>
* I believe Nick Lomuto has a very similar routine, but I can say that I came up with this independently.
*/
static int partition(int[] a, int lo, int hi) {
setPivot(a, lo, hi);
int pivot = a[lo];
// System.out.println("pivot: " + pivot);
int pi = 0; //pi is the sorted index of the pivot
for (int i = lo + 1; i < hi; i++) {
if (a[i] < pivot) {
a[pi] = a[i];
a[i] = a[pi + 1];
pi += 1;
}
}
a[pi] = pivot;
return pi;
}
static int partition(int[]a) {
return partition(a, 0, a.length);
}
private static int setPivot(int[] a, int lo, int hi, int... defaultIndex) {
// remember: li is inclusive and hi is exclusive
if (hi - lo < 1) {
throw new IllegalArgumentException("low: " + lo + ", high: " + hi + " fail the contract");
}
int i;
if (defaultIndex.length == 1) {
int defi = defaultIndex[0];
if (defi < lo || defi >= hi) {
throw new IllegalArgumentException("defaultIndex: " + defi + " invalid for given low (incl): " + lo + " and high (excl): " + hi);
}
i = defi;
} else {
i = ThreadLocalRandom.current().nextInt(lo, hi);
}
int t = a[0];
a[0] = a[i];
a[i] = t;
return i;
}
} |
package watodo.ui;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextInputControl;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import watodo.commons.core.Config;
import watodo.commons.core.GuiSettings;
import watodo.commons.events.ui.ExitAppRequestEvent;
import watodo.commons.util.FxViewUtil;
import watodo.logic.Logic;
import watodo.model.UserPrefs;
/**
* The Main Window. Provides the basic application layout containing
* a menu bar and space where other JavaFX elements can be placed.
*/
public class MainWindow extends UiPart<Region> {
private static final String ICON = "/images/taskmanager.png";
private static final String FXML = "MainWindow.fxml";
private static final int MIN_HEIGHT = 600;
private static final int MIN_WIDTH = 450;
private Stage primaryStage;
private Logic logic;
// Independent Ui parts residing in this Ui container
private TaskListPanel taskListPanel;
private Config config;
@FXML
private AnchorPane commandBoxPlaceholder;
@FXML
private MenuItem helpMenuItem;
@FXML
private AnchorPane taskListPanelPlaceholder;
@FXML
private AnchorPane resultDisplayPlaceholder;
@FXML
private AnchorPane statusbarPlaceholder;
public MainWindow(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
super(FXML);
// Set dependencies
this.primaryStage = primaryStage;
this.logic = logic;
this.config = config;
// Configure the UI
setTitle(config.getAppTitle());
setIcon(ICON);
setWindowMinSize();
setWindowDefaultSize(prefs);
Scene scene = new Scene(getRoot());
primaryStage.setScene(scene);
setAccelerators();
}
public Stage getPrimaryStage() {
return primaryStage;
}
private void setAccelerators() {
setAccelerator(helpMenuItem, KeyCombination.valueOf("F1"));
}
/**
* Sets the accelerator of a MenuItem.
* @param keyCombination the KeyCombination value of the accelerator
*/
private void setAccelerator(MenuItem menuItem, KeyCombination keyCombination) {
menuItem.setAccelerator(keyCombination);
getRoot().addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getTarget() instanceof TextInputControl && keyCombination.match(event)) {
menuItem.getOnAction().handle(new ActionEvent());
event.consume();
}
});
}
void fillInnerParts() {
taskListPanel = new TaskListPanel(getTaskListPlaceholder(), logic.getFilteredTaskList());
new ResultDisplay(getResultDisplayPlaceholder());
new StatusBarFooter(getStatusbarPlaceholder(), config.getTaskManagerFilePath());
new CommandBox(getCommandBoxPlaceholder(), logic);
}
private AnchorPane getCommandBoxPlaceholder() {
return commandBoxPlaceholder;
}
private AnchorPane getStatusbarPlaceholder() {
return statusbarPlaceholder;
}
private AnchorPane getResultDisplayPlaceholder() {
return resultDisplayPlaceholder;
}
private AnchorPane getTaskListPlaceholder() {
return taskListPanelPlaceholder;
}
void hide() {
primaryStage.hide();
}
private void setTitle(String appTitle) {
primaryStage.setTitle(appTitle);
}
/**
* Sets the given image as the icon of the main window.
* @param iconSource e.g. {@code "/images/help_icon.png"}
*/
private void setIcon(String iconSource) {
FxViewUtil.setStageIcon(primaryStage, iconSource);
}
/**
* Sets the default size based on user preferences.
*/
private void setWindowDefaultSize(UserPrefs prefs) {
primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight());
primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth());
if (prefs.getGuiSettings().getWindowCoordinates() != null) {
primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX());
primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY());
}
}
private void setWindowMinSize() {
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setMinWidth(MIN_WIDTH);
}
/**
* Returns the current size and the position of the main Window.
*/
GuiSettings getCurrentGuiSetting() {
return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(),
(int) primaryStage.getX(), (int) primaryStage.getY());
}
@FXML
public void handleHelp() {
HelpWindow helpWindow = new HelpWindow();
helpWindow.show();
}
void show() {
primaryStage.show();
}
/**
* Closes the application.
*/
@FXML
private void handleExit() {
raise(new ExitAppRequestEvent());
}
public TaskListPanel getTaskListPanel() {
return this.taskListPanel;
}
} |
package webmon.core;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import org.glassfish.jersey.server.mvc.Viewable;
import webmon.models.Website;
import webmon.models.ResponseInfo;
import webmon.models.User;
import webmon.utils.Constants;
import webmon.utils.DatastoreUtils;
//Map this class to /websites route
@Path("/websites")
public class Websites {
// Allows to insert contextual objects into the class,
// e.g. ServletContext, Request, Response, UriInfo
@Context
UriInfo uriInfo;
@Context
Request request;
@Context
HttpServletRequest httpRequest;
@GET
@Path("/add")
@Produces(MediaType.TEXT_HTML)
public Response addWebsite() {
return Response.ok(new Viewable(Constants.jspRoot + "addWebsite.jsp", null)).build();
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Website getWebsite(@PathParam("id") long id) {
Website website = DatastoreUtils.getWebsite(id);
User user = DatastoreUtils.getUser(String.valueOf(httpRequest.getSession(false).getAttribute("user")));
int index = website.getUsers().indexOf(Long.valueOf(user.getId()));
website.setUsers(null);
List<Boolean> notifyWhenResponseIsHigh = new ArrayList<Boolean>();
notifyWhenResponseIsHigh.add(website.getNotifyWhenResponseIsHigh().get(index));
List<Boolean> notifyWhenDown = new ArrayList<Boolean>();
notifyWhenDown.add(website.getNotifyWhenDown().get(index));
website.setNotifyWhenResponseIsHigh(notifyWhenResponseIsHigh);
website.setNotifyWhenDown(notifyWhenDown);
int websiteIndex = user.getMonitoredWebsites().indexOf(website.getId());
int websiteIndexInUser = 0;
if(user.getMonitorWebsiteStart().get(websiteIndex) instanceof Integer) {
websiteIndexInUser = user.getMonitorWebsiteStart().get(websiteIndex);
}
List<ResponseInfo> responseInfo = new ArrayList<ResponseInfo>();
if(websiteIndexInUser < website.getResponseInfo().size())
responseInfo.addAll(website.getResponseInfo().subList(websiteIndexInUser, website.getResponseInfo().size()));
website.setResponseInfo(responseInfo);
return website;
}
@GET
@Path("{id}")
@Produces(MediaType.TEXT_HTML)
public Response getWebsiteHTML(@PathParam("id") int id) {
return Response.ok(new Viewable(Constants.jspRoot + "website.jsp", null)).build();
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String saveWebsite(@FormParam("name") String name,
@FormParam("url") String url,
@FormParam("notifyDown") String notifyDown,
@FormParam("notifyResponse") String notifyResponse) {
try {
User loggedInUser = DatastoreUtils.getUser(String.valueOf(httpRequest.getSession(false).getAttribute("user")));
Website website;
if(DatastoreUtils.checkWebsite(url)) {
website = DatastoreUtils.getWebsite(url);
if(website.getUsers().contains(loggedInUser.getId()))
return "{ \"result\": \"" + Constants.stringWebsiteExists + "\"}";
else
website.addUser(loggedInUser.getId(), (notifyDown != null), (notifyResponse != null));
} else {
website = new Website(url, name, loggedInUser.getId(), (notifyDown != null), (notifyResponse != null));
}
DatastoreUtils.putWebsite(website);
loggedInUser.getMonitoredWebsites().add(website.getId());
loggedInUser.getMonitorWebsiteStart().add(website.getResponseInfo().size());
DatastoreUtils.putUser(loggedInUser);
return "{ \"result\": \"" + Constants.stringWebsiteAdded + "\"}";
} catch (Exception e) {
e.printStackTrace();
return "{ \"result\": \"fail\"}";
}
}
@PUT
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public String updateWebsite(@FormParam("url") String url,
@FormParam("notifyDown") String notifyDown,
@FormParam("notifyResponse") String notifyResponse) {
try {
Website website = DatastoreUtils.getWebsite(url);
boolean notDown = true;
boolean notRes = true;
if(notifyDown == null || notifyDown.equals(""))
notDown = false;
if(notifyResponse == null || notifyResponse.equals(""))
notRes = false;
User user = DatastoreUtils.getUser(String.valueOf(httpRequest.getSession(false).getAttribute("user")));
int userid = website.getUsers().indexOf(Long.valueOf(user.getId()));
website.getNotifyWhenDown().set(userid, notDown);
website.getNotifyWhenResponseIsHigh().set(userid, notRes);
DatastoreUtils.putWebsite(website);
return "{ \"result\": \"Successfully updated website with email: " + website.getUrl() + "\", \"status\": 200}";
} catch (Exception e) {
e.printStackTrace();
}
return "{ \"result\": \"Updating website with given details failed.\", \"status\": 500}";
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public String deleteWebsite(@PathParam("id") long id) {
try {
Website website = DatastoreUtils.getWebsite(id);
User user = DatastoreUtils.getUser(String.valueOf(httpRequest.getSession(false).getAttribute("user")));
website.removeUser(user.getId());
int userIndex = user.getMonitoredWebsites().indexOf(id);
user.getMonitoredWebsites().remove(userIndex);
user.getMonitorWebsiteStart().remove(userIndex);
DatastoreUtils.putWebsite(website);
DatastoreUtils.putUser(user);
return "{ \"result\": \"Successfully deleted website with email: " + website.getUrl() + "\", \"status\": 200}";
} catch (Exception e) {
e.printStackTrace();
}
return "{ \"result\": \"Deleting website with given details failed.\", \"status\": 500}";
}
} |
package net.plastboks.gameobjects;
import com.badlogic.gdx.math.Vector2;
import net.plastboks.shared.Directions;
import java.util.LinkedList;
public class Snake extends Creature {
private final int startBodySize = 4;
private LinkedList<Node> body;
private int bodySize = startBodySize;
private int collisions;
private float lvl = 0.8f;
private float lvlInc = 0.2f;
private float maxLvl = 1.6f;
public Snake(float x, float y, int width, int height, int gameHeight) {
super(x, y, width, height);
setGameHeight(gameHeight);
setAlive(true);
this.body = new LinkedList<Node>();
}
public void incrementBodySizeBy(int n) { bodySize += n; }
private void pushToBody(float delta, int max) {
if (body.size() >= max) { body.removeFirst(); }
body.add(new Node(new Vector2(getX(), getY()), getDir()));
}
public void changeDir(Directions d) {
switch (d) {
case NORTH:
if (getDir() != Directions.SOUTH) {
setDir(d);
setRotation(Directions.NORTH);
}
break;
case SOUTH:
if (getDir() != Directions.NORTH) {
setDir(d);
setRotation(Directions.SOUTH);
}
break;
case WEST:
if (getDir() != Directions.EAST) {
setDir(d);
setRotation(Directions.WEST);
}
break;
case EAST:
if (getDir() != Directions.WEST) {
setDir(d);
setRotation(Directions.EAST);
}
break;
}
}
public void incrementSpeed() {
if (lvl + lvlInc <= maxLvl) { lvl += lvlInc; }
}
public void update(float delta) {
pushToBody(delta, bodySize);
move(delta + lvl);
}
public void onClick(float x, float y) {
if (isAlive()) {
switch (getDir()) {
case EAST:
case WEST:
if (y > getY()) {
changeDir(Directions.SOUTH);
} else {
changeDir(Directions.NORTH);
}
break;
case NORTH:
case SOUTH:
if (x > getX()) {
changeDir(Directions.EAST);
} else {
changeDir(Directions.WEST);
}
break;
}
}
}
public void onRestart(int y) {
setRotation(Directions.WEST);
setY(y);
setAlive(true);
body = new LinkedList<Node>();
bodySize = startBodySize;
}
public LinkedList<Node> getBody() { return body; }
public void die() { setAlive(false); }
} |
package net.formula97.andorid.car_kei_bo;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
//import android.view.Menu;
//import android.view.MenuInflater;
//import android.view.MenuItem;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
/**
*
* @author kazutoshi
*
*/
public class AddMyCar extends Activity {
private DbManager dbman = new DbManager(this);
public static SQLiteDatabase db;
private static final boolean FLAG_DEFAULT_ON = true;
private static final boolean FLAG_DEFAULT_OFF = false;
TextView textview_addCarName;
CheckBox checkbox_setDefault;
Button button_addCar;
Button button_cancel_addCar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcar);
textview_addCarName = (TextView)findViewById(R.id.textview_addCarName);
checkbox_setDefault = (CheckBox)findViewById(R.id.checkBox_SetDefault);
button_addCar = (Button)findViewById(R.id.button_addCar);
button_cancel_addCar = (Button)findViewById(R.id.button_cancel_addCar);
}
/**
* Activity
* DBDB
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
// TODO
super.onPause();
dbman.close();
}
/**
*
*
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
// TODO
super.onResume();
/*
* 1/2
*
* onCreate()
* Android
*/
int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
button_addCar.setWidth(displayWidth / 2);
button_cancel_addCar.setWidth(displayWidth / 2);
}
/**
*
* OnClickListenerGUI
* public
* @param v ViewId
*/
public void onClickAddCar(View v) {
String carName;
boolean defaultFlags;
db = dbman.getWritableDatabase();
// TextView
// getText()CaheSequenceString
SpannableStringBuilder sp = (SpannableStringBuilder) textview_addCarName.getText();
carName = sp.toString();
Log.w("CarList", "New Car name = " + carName);
if (checkbox_setDefault.isChecked()) {
/*
*
* 1.
* 2.
*/
if (dbman.isExistDefaultCarFlag(db)) {
int iRet = dbman.clearAllDefaultFlags(db);
Log.w("CAR_MASTER", "Default Car flags cleared, " + String.valueOf(iRet) + "rows updated.");
}
defaultFlags = FLAG_DEFAULT_ON;
} else {
defaultFlags = FLAG_DEFAULT_OFF;
}
// CAR_MASTER
long lRet = dbman.addNewCar(db, carName, defaultFlags);
Log.i("CAR_MASTER", "Car record inserted, New Car Name = " + carName + " , New row ID = " + String.valueOf(lRet) );
dbman.close();
}
/**
*
* onClickAddCar()OnClickListener
* GUI
* public
* @param v ViewId
*/
public void onClickCancel(View v) {
textview_addCarName.setText("");
checkbox_setDefault.setChecked(false);
}
} |
package mondrian.gui;
import java.util.*;
import java.sql.*;
import org.apache.log4j.Logger;
/**
*
* @version $Id$
*/
public class JDBCMetaData {
private static final Logger LOGGER = Logger.getLogger(JDBCMetaData.class);
String jdbcDriverClassName = null; //"org.postgresql.Driver"
String jdbcConnectionUrl = null; // "jdbc:postgresql://localhost:5432/hello?user=postgres&password=post"
String jdbcUsername = null;
String jdbcPassword = null;
String jdbcSchema = null;
boolean requireSchema = false;
Connection conn = null;
DatabaseMetaData md = null;
Workbench workbench;
/* Map of Schema and its fact tables ::
* allFactTableDimensions = [Schema1, Schema2] -> [FactTableT8, FactTable9] -> [ForeignKeys -> PrimaryKeyTable]
*
* Map of Schema, its tables and their Primary Keys ::
* allTablesPKs = [Schema1, Schema2] -> [Tables -> PrimaryKey]
*
* Map of Schemas, its tables and their columns with their data types
* allTablesCols = [Schema1, Schema2] -> [Table1, Table2] -> [Columns -> DataType]
*
* Map of schemas and their tables
* allSchemasMap = [Schema1, Schema2] -> [Table1, Table2]
*
*/
private Map allFactTableDimensions = new HashMap(); //unsynchronized, permits null values and null key
private Map allTablesPKs = new HashMap();
private Map allTablesCols = new HashMap();
private Map allSchemasMap = new HashMap();
private Vector allSchemas = new Vector(); // Vector of all schemas in the connected database
private String errMsg = null;
private Database db = new Database();
public JDBCMetaData(Workbench wb, String jdbcDriverClassName,
String jdbcConnectionUrl, String jdbcUsername,
String jdbcPassword, String jdbcSchema, boolean requireSchema) {
this.workbench = wb;
this.jdbcConnectionUrl = jdbcConnectionUrl;
this.jdbcDriverClassName = jdbcDriverClassName;
this.jdbcUsername = jdbcUsername;
this.jdbcPassword = jdbcPassword;
this.jdbcSchema = jdbcSchema;
this.requireSchema = requireSchema;
if (initConnection() == null) {
setAllSchemas();
closeConnection();
}
}
public boolean getRequireSchema() {
return requireSchema;
}
/**
* @return the workbench i18n converter
*/
public I18n getResourceConverter() {
return workbench.getResourceConverter();
}
/* Creates a database connection and initializes the meta data details */
public String initConnection() {
LOGGER.debug("JDBCMetaData: initConnection");
try {
if (jdbcDriverClassName == null || jdbcDriverClassName.trim().length() == 0 ||
jdbcConnectionUrl == null || jdbcConnectionUrl.trim().length() == 0)
{
errMsg = getResourceConverter().getFormattedString("jdbcMetaData.blank.exception",
"Driver={0}\nConnection URL={1}\nUse Preferences to set Database Connection parameters first and then open a Schema",
new String[] { jdbcDriverClassName, jdbcConnectionUrl });
return errMsg;
}
Class.forName(jdbcDriverClassName);
if (jdbcUsername != null && jdbcUsername.length() > 0) {
conn = DriverManager.getConnection(jdbcConnectionUrl, jdbcUsername, jdbcPassword);
} else {
conn = DriverManager.getConnection(jdbcConnectionUrl);
}
LOGGER.debug("JDBC connection OPEN");
md = conn.getMetaData();
db.productName = md.getDatabaseProductName();
db.productVersion = md.getDatabaseProductVersion();
db.catalogName = conn.getCatalog();
LOGGER.debug("Catalog name = " + db.catalogName);
/*
ResultSet rsd = md.getSchemas();
while (rsd.next())
{ System.out.println(" Schema ="+rsd.getString("TABLE_SCHEM"));
System.out.println(" Schema ="+rsd.getString("TABLE_CATALOG"));
}
rsd = md.getCatalogs();
while (rsd.next())
System.out.println(" Catalog ="+rsd.getString("TABLE_CAT"));
*/
LOGGER.debug("Database Product Name: " + db.productName);
LOGGER.debug("Database Product Version: " + db.productVersion);
/*
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/demo","admin","admin");
*/
LOGGER.debug("JDBCMetaData: initConnection - no error");
return null;
} catch (Exception e) {
errMsg = e.getClass().getSimpleName() + " : " + e.getLocalizedMessage();
LOGGER.error("Database connection exception : " + errMsg, e);
return errMsg;
//e.printStackTrace();
}
}
public void closeConnection() {
try {
conn.close();
LOGGER.debug("JDBC connection CLOSE");
} catch (Exception e) {
LOGGER.error(e);
}
}
/**
* Check to see if the schemaName is in the list of allowed jdbc schemas
*
* @param schemaName the name of the schmea
*
* @return true if found, or if jdbcSchema is null
*/
private boolean inJdbcSchemas(String schemaName) {
if (jdbcSchema == null || jdbcSchema.trim().length() == 0) {
return true;
}
String schemas[] = jdbcSchema.split("[,;]");
for (String schema : schemas) {
if (schema.trim().equals(schemaName)) {
return true;
}
}
return false;
}
/* set all schemas in the currently connected database */
private void setAllSchemas() {
LOGGER.debug("JDBCMetaData: setAllSchemas");
ResultSet rs = null;
boolean gotSchema = false;
try {
rs = md.getSchemas();
/*
if (true)
throw new Exception("Schema concept not found in database");
*/
while (rs.next()) {
String schemaName = rs.getString("TABLE_SCHEM");
if (inJdbcSchemas(schemaName)) {
DbSchema dbs = new DbSchema();
dbs.name = schemaName;
LOGGER.debug("JDBCMetaData: setAllTables - " + dbs.name);
setAllTables(dbs);
db.addDbSchema(dbs);
gotSchema = true;
}
}
rs.close();
} catch (Exception e) {
LOGGER.debug("Exception : Database does not support schemas." + e.getMessage());
}
if (!gotSchema) {
LOGGER.debug("JDBCMetaData: setAllSchemas - tables with no schema name");
DbSchema dbs = new DbSchema();
dbs.name = null; //tables with no schema name
setAllTables(dbs);
db.addDbSchema(dbs);
}
}
/* set all tables in the currently connected database */
private void setAllTables(DbSchema dbs) {
LOGGER.debug("JDBCMetaData: Loading schema: '" + dbs.name + "'");
ResultSet rs = null;
try {
// Tables and views can be used
rs = md.getTables(null, dbs.name, null, new String[]{"TABLE", "VIEW"});
while (rs.next()) {
String tbname = rs.getString("TABLE_NAME");
DbTable dbt;
/* Note : Imported keys are foreign keys which are primary keys of in some other tables
* : Exported keys are primary keys which are referenced as foreign keys in other tables.
*/
ResultSet rs_fks = md.getImportedKeys(null, dbs.name, tbname);
if (rs_fks.next()) {
dbt = new FactTable();
do {
((FactTable) dbt).addFks(rs_fks.getString("FKCOLUMN_NAME"),rs_fks.getString("pktable_name"));
} while (rs_fks.next());
} else {
dbt = new DbTable();
}
rs_fks.close();
dbt.schemaName = dbs.name;
dbt.name = tbname;
setPKey(dbt);
setColumns(dbt);
dbs.addDbTable(dbt);
db.addDbTable(dbt);
}
rs.close();
} catch (Exception e) {
LOGGER.error("setAllTables", e);
}
}
/* get the Primary key name for a given table name
* This key may be a composite key made of multiple columns.
*/
private void setPKey(DbTable dbt) {
ResultSet rs = null;
try {
rs = md.getPrimaryKeys(null, dbt.schemaName, dbt.name);
/*
while(rs.next()) {
primKeys.add(rs.getString("COLUMN_NAME"));
}
**/
if (rs.next()) {
dbt.pk = rs.getString("column_name"); // we need the column name which is primary key for the given table.
}
rs.close();
} catch (Exception e) {
LOGGER.error("setPKey", e);
}
}
/* get all columns for a given table name */
private void setColumns(DbTable dbt) {
ResultSet rs = null;
try {
rs = md.getColumns(null, dbt.schemaName, dbt.name, null);
while (rs.next()) {
dbt.addColsDataType(rs.getString("COLUMN_NAME"), rs.getString("DATA_TYPE"));
}
rs.close();
} catch (Exception e) {
LOGGER.error("setColumns", e);
}
}
public Vector<String> getAllSchemas() {
return db.getAllSchemas();
}
/* get all tables in a given schema */
public Vector<String> getAllTables(String schemaName) {
return db.getAllTables(schemaName);
}
/* get all tables in given schema minus the given table name */
public Vector<String> getAllTables(String schemaName, String minusTable) {
if (minusTable == null) {
return getAllTables(schemaName);
} else {
Vector<String> allTablesMinusOne = new Vector<String>();
for (String s : getAllTables(schemaName)) {
if (s
.endsWith(minusTable)) { // startsWith and endsWith cannot be compared with null argument, throws exception
if ((schemaName == null) || s.startsWith(schemaName)) {
continue;
}
}
allTablesMinusOne.add(s);
}
return allTablesMinusOne;
}
}
/* get all possible cases of fact tables in a schema */
public Vector<String> getFactTables(String schemaName) {
return db.getFactTables(schemaName);
}
/* get all possible cases of dimension tables which are linked to given fact table by foreign keys */
public Vector<String> getDimensionTables(String schemaName, String factTable) {
Vector<String> dimeTables = new Vector<String>();
if (factTable == null) {
return dimeTables;
} else {
return db.getDimensionTables(schemaName, factTable);
}
}
public boolean isTableExists(String schemaName, String tableName) {
if (tableName == null) {
return true;
} else {
return db.tableExists(schemaName, tableName);
}
}
public boolean isColExists(String schemaName, String tableName, String colName) {
if (tableName == null || colName == null) {
return true;
} else {
return db.colExists(schemaName, tableName, colName);
}
}
/* get all foreign keys in given fact table */
public Vector<String> getFactTableFKs(String schemaName, String factTable) {
Vector<String> fks = new Vector<String>();
if (factTable == null) {
return fks;
} else {
return db.getFactTableFKs(schemaName, factTable);
}
}
public String getTablePK(String schemaName, String tableName) {
if (tableName == null) {
return null;
} else {
return db.getTablePK(schemaName, tableName);
}
}
/* get all columns of given table in schema */
public Vector<String> getAllColumns(String schemaName, String tableName) {
Vector<String> allcols = new Vector<String>();
if (tableName == null) {
Vector<String> allTables = getAllTables(schemaName);
for (int i = 0; i < allTables.size(); i++) {
String tab = allTables.get(i);
Vector<String> cols;
if (tab.indexOf("->") == -1) {
cols = getAllColumns(schemaName, tab);
} else {
String [] names = tab.split("->");
cols = getAllColumns(names[0], names[1]);
}
for (int j = 0; j < cols.size(); j++) {
String col = cols.get(j);
allcols.add(tab + "->" + col);
}
}
return allcols;
} else {
return db.getAllColumns(schemaName, tableName);
}
}
// get column data type of given table and its col
public int getColumnDataType(String schemaName, String tableName, String colName) {
if (tableName == null || colName == null) {
return -1;
} else {
return db.getColumnDataType(schemaName, tableName, colName);
}
}
public String getDbCatalogName() {
return db.catalogName;
}
public String getDatabaseProductName() {
return db.productName;
}
public String getErrMsg() {
return errMsg;
}
public static void main(String[] args) {
/*
JDBCMetaData sb = new JDBCMetaData("org.postgresql.Driver","jdbc:postgresql://localhost:5432/testdb?user=admin&password=admin");
System.out.println("allSchemas="+sb.allSchemas);
System.out.println("allSchemasMap="+sb.allSchemasMap);
System.out.println("allTablesCols="+sb.allTablesCols);
System.out.println("allTablesPKs="+sb.allTablesPKs);
System.out.println("allFactTableDimensions="+sb.allFactTableDimensions);
System.out.println("getAllTables(null, part)="+sb.getAllTables(null, "part"));
System.out.println("sb.getColumnDataType(null, part,part_nbr)="+sb.getColumnDataType(null, "part","part_nbr"));
*/
String s = "somita->namita";
String [] p = s.split("->");
if (LOGGER.isDebugEnabled()) {
if (p.length >= 2) {
LOGGER.debug("p0=" + p[0] + ", p1=" + p[1]);
}
}
}
class Database {
String catalogName = ""; // database name.
String productName = "Unknown";
String productVersion = "";
// list of all schemas in database
List<DbSchema> schemas = new ArrayList<DbSchema>(); //ordered collection, allows duplicates and null
List<DbTable> tables = new ArrayList<DbTable>(); // list of all tables in all schemas in database
Map<String, Integer> tablesCount = new TreeMap<String, Integer>(); // map of table names and the count of tables with this name in the database.
Vector<String> allSchemas ;
private void addDbSchema(DbSchema dbs) {
schemas.add(dbs);
}
private void addDbTable(DbTable dbs) {
tables.add(dbs);
Integer count = tablesCount.get(dbs.name);
if (count == null) {
count = Integer.valueOf(1);
} else {
count = Integer.valueOf(count.intValue() + 1);
}
tablesCount.put(dbs.name, count);
}
private boolean schemaNameEquals(String a, String b) {
return (a != null && a.equals(b));
}
private Vector<String> getAllSchemas() {
if (allSchemas == null) {
allSchemas = new Vector<String>();
if (schemas.size() > 0) {
for (DbSchema s : schemas) {
allSchemas.add((s).name);
}
}
}
return allSchemas;
}
private boolean tableExists(String sname, String tableName) {
if (sname == null || sname.equals("")) {
return tablesCount.containsKey(tableName);
} else {
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable d : s.tables) {
if (d.name.equals(tableName)) {
return true;
}
}
break;
}
}
}
return false;
}
private boolean colExists(String sname, String tableName, String colName) {
if (sname == null || sname.equals("")) {
Iterator<DbTable> ti = tables.iterator();
for (DbTable t : tables) {
if (t.name.equals(tableName)) {
return t.colsDataType.containsKey(colName);
}
}
} else {
// return a vector of "fk col name" string objects if schema is given
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable t : s.tables) {
if (t.name.equals(tableName)) {
return t.colsDataType.containsKey(colName);
}
}
break;
}
}
}
return false;
}
private Vector<String> getAllTables(String sname) {
Vector<String> v = new Vector<String>();
if (sname == null || sname.equals("")) {
// return a vector of "schemaname -> table name" string objects
for (DbTable d : tables) {
if (d.schemaName == null) {
v.add(d.name);
} else {
v.add(d.schemaName + "->" + d.name);
}
}
} else {
// return a vector of "tablename" string objects
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable d : s.tables) {
v.add(d.name);
}
break;
}
}
}
return v;
}
private Vector<String> getFactTables(String sname) {
Vector<String> f = new Vector<String>();
if (sname == null || sname.equals("")) {
// return a vector of "schemaname -> table name" string objects if schema is not given
Iterator<DbTable> ti = tables.iterator();
for (DbTable t : tables) {
if (t instanceof FactTable) {
if (t.schemaName == null) {
f.add(t.name);
} else {
f.add(t.schemaName + "->" + t.name);
}
}
}
} else {
// return a vector of "fact tablename" string objects if schema is given
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable t : s.tables) {
if (t instanceof FactTable) {
f.add(((FactTable) t).name);
}
}
break;
}
}
}
return f;
}
/* get all foreign keys in given fact table */
private Vector<String> getFactTableFKs(String sname, String factTable) {
Vector<String> f = new Vector<String>();
if (sname == null || sname.equals("")) {
// return a vector of "schemaname -> table name -> fk col" string objects if schema is not given
boolean duplicate = (tablesCount.containsKey(factTable)) && ((tablesCount.get(factTable)).intValue() > 1);
for (DbTable t : tables) {
if (t instanceof FactTable && t.name.equals(factTable)) {
if (duplicate) {
for (String fk : ((FactTable) t).fks.keySet()) {
if (t.schemaName == null) {
f.add(t.name + "->" + fk);
} else {
f.add(
t.schemaName
+ "->"
+ t.name
+ "->"
+ fk);
}
}
} else {
f.addAll(((FactTable) t).fks.keySet());
}
}
}
} else {
// return a vector of "fk col name" string objects if schema is given
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable t : s.tables) {
if (t instanceof FactTable && t.name
.equals(factTable)) {
f.addAll(((FactTable) t).fks.keySet());
break;
}
}
break;
}
}
}
return f;
}
private Vector<String> getDimensionTables(String sname, String factTable) {
Vector<String> f = new Vector<String>();
if (sname == null || sname.equals("")) {
// return a vector of "schemaname -> table name -> dimension table name" string objects if schema is not given
boolean duplicate = (tablesCount.containsKey(factTable)) && ((tablesCount.get(factTable)).intValue() > 1);
for (DbTable t : tables) {
if (t instanceof FactTable && t.name.equals(factTable)) {
if (duplicate) {
Iterator<String> fki =
((FactTable) t).fks.values().iterator();
for (String fkt : ((FactTable) t).fks.values()) {
if (t.schemaName == null) {
f.add(t.name + "->" + fkt);
} else {
f.add(
t
.schemaName
+ "->"
+ t
.name
+ "->"
+ fkt);
}
}
} else {
f.addAll(((FactTable) t).fks.values());
break;
}
}
}
} else {
// return a vector of "fk col name" string objects if schema is given
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable t : s.tables) {
if (t instanceof FactTable && t.name
.equals(factTable)) {
f.addAll(((FactTable) t).fks.values());
break;
}
}
break;
}
}
}
return f;
}
private String getTablePK(String sname, String tableName) {
if (sname == null || sname.equals("")) {
// return a vector of "schemaname -> table name -> dimension table name" string objects if schema is not given
for (DbTable t : tables) {
if (t.name.equals(tableName)) {
return t.pk;
}
}
} else {
// return a vector of "fk col name" string objects if schema is given
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable t : s.tables) {
if (t.name.equals(tableName)) {
return t.pk;
}
}
break;
}
}
}
return null;
}
private Vector<String> getAllColumns(String sname, String tableName) {
Vector<String> f = new Vector<String>();
if (sname == null || sname.equals("")) {
// return a vector of "schemaname -> table name -> cols" string objects if schema is not given
boolean duplicate = (tablesCount.containsKey(tableName)) && ((tablesCount.get(tableName)).intValue() > 1);
for (DbTable t : tables) {
if (t.name.equals(tableName)) {
if (duplicate) {
for (String c : t.colsDataType.keySet()) {
if (t.schemaName == null) {
f.add(t.name + "->" + c);
} else {
f.add(
t.schemaName
+ "->"
+ t.name
+ "->"
+ c);
}
}
} else {
f.addAll(t.colsDataType.keySet()); //display only col names
break;
}
}
}
} else {
// return a vector of "col name" string objects if schema is given
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable t : s.tables) {
if (t.name.equals(tableName)) {
f.addAll(t.colsDataType.keySet());
break;
}
}
break;
}
}
}
return f;
}
private int getColumnDataType(String sname, String tableName, String colName) {
if (sname == null || sname.equals("")) {
for (DbTable t : tables) {
if (t.name.equals(tableName)) {
return Integer.parseInt(t.colsDataType.get(colName));
}
}
} else {
// return a vector of "fk col name" string objects if schema is given
for (DbSchema s : schemas) {
if (schemaNameEquals(s.name, sname)) {
for (DbTable t : s.tables) {
if (t.name.equals(tableName)) {
return Integer.parseInt(
t.colsDataType.get(colName));
}
}
break;
}
}
}
return -1;
}
}
class DbSchema {
String name;
/** ordered collection, allows duplicates and null */
final List<DbTable> tables = new ArrayList<DbTable>();
private void addDbTable(DbTable dbt) {
tables.add(dbt);
}
}
class DbTable {
String schemaName;
String name;
String pk;
/** sorted map key=column, value=data type of column */
final Map<String, String> colsDataType = new TreeMap<String, String>();
private void addColsDataType(String col, String dataType) {
colsDataType.put(col, dataType);
}
}
class FactTable extends DbTable {
/** sorted map key = foreign key col, value=primary key table associated with this fk */
final Map<String, String> fks = new TreeMap<String, String>();
private void addFks(String fk, String pkt) {
fks.put(fk, pkt);
}
}
}
// End JDBCMetaData.java |
package codeine;
import java.util.List;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.DefaultIdentityService;
import org.eclipse.jetty.security.SpnegoLoginService;
import org.eclipse.jetty.security.authentication.FormAuthenticator;
import org.eclipse.jetty.security.authentication.SpnegoAuthenticator;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.security.Constraint;
import codeine.configuration.PathHelper;
import codeine.executer.PeriodicExecuter;
import codeine.jsons.auth.AuthenticationMethod;
import codeine.jsons.global.GlobalConfigurationJsonStore;
import codeine.jsons.peer_status.PeersProjectsStatus;
import codeine.model.Constants;
import codeine.servlet.UsersManager;
import codeine.statistics.IMonitorStatistics;
import codeine.statistics.MonitorsStatistics;
import codeine.users.LogoutServlet;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.google.inject.Module;
public class CodeineWebServerBootstrap extends AbstractCodeineBootstrap
{
public CodeineWebServerBootstrap(Injector injector) {
super(injector);
}
public CodeineWebServerBootstrap() {
}
public static void main(String[] args)
{
System.setProperty("org.eclipse.jetty.server.Request.maxFormContentSize", "10000000");
boot(Component.WEB, CodeineWebServerBootstrap.class);
}
@Override
protected void execute() {
log.info("executing web server bootstrap");
new PeriodicExecuter(PeersProjectsStatus.SLEEP_TIME ,injector().getInstance(PeersProjectsStatus.class)).runInThread();
try {
injector().getInstance(ConfigurationManagerServer.class).updateDb();
} catch (Exception e) {
log.error("fail to update projects in db", e);
}
new PeriodicExecuter(ProjectConfigurationInPeerUpdater.MAX_SLEEP_TIME_MILLI ,injector().getInstance(ProjectConfigurationInPeerUpdater.class)).runInThread();
new PeriodicExecuter(MonitorsStatistics.SLEEP_TIME ,injector().getInstance(IMonitorStatistics.class)).runInThreadSleepFirst();
}
@Override
protected void createMoreContext(ContextHandlerCollection contexts) {
ServletContextHandler handler = createServletContextHandler();
handler.setContextPath(Constants.ANGULAR_RESOURCES_CONTEXT_PATH);
handler.addServlet(AngularServlet.class, Constants.ANGULAR_WEB_URLS_PATH_SPEC);
contexts.addHandler(handler);
addHandler(Constants.ANGULAR_RESOURCES_CONTEXT_PATH, Constants.getAngularDir(), contexts);
log.info("context " + Constants.ANGULAR_WEB_URLS_PATH_SPEC + " is serving " + Constants.getAngularMainHtml());
}
@Override
protected List<Module> getGuiceModules() {
return Lists.<Module>newArrayList(new WebServerModule(), new ServerServletModule());
}
@Override
public int getHttpPort() {
return injector().getInstance(GlobalConfigurationJsonStore.class).get().web_server_port();
}
@Override
protected ServletContextHandler createServletContextHandler() {
AuthenticationMethod a = injector().getInstance(GlobalConfigurationJsonStore.class).get().authentication_method();
if (Boolean.getBoolean("ignoreSecurity")){
a = AuthenticationMethod.Disabled;
}
switch (a){
case Disabled:
return super.createServletContextHandler();
case WindowsCredentials:
return createServletContextHandlerSpnego();
case Builtin:
return createServletContextHandlerBasic();
}
throw new IllegalArgumentException("auth method not found " + a);
}
@Override
protected void specificCreateFileServer(ContextHandlerCollection contexts){
PathHelper pathHelper = injector().getInstance(PathHelper.class);
addHandler(Constants.PROJECT_FILES_CONTEXT, pathHelper.getProjectsDir() , contexts);
}
private ServletContextHandler createServletContextHandlerBasic(){
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS
| ServletContextHandler.SECURITY);
context.addServlet(new ServletHolder(injector().getInstance(LogoutServlet.class)), "/logout");
ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
UsersManager usersManager = injector().getInstance(UsersManager.class);
usersManager.initUsers();
securityHandler.setLoginService(usersManager.loginService());
FormAuthenticator authenticator = new FormAuthenticator();//"/login", "/login", false);
securityHandler.setAuthenticator(authenticator);
context.setSecurityHandler(securityHandler);
return context;
}
private ServletContextHandler createServletContextHandlerSpnego() {
GlobalConfigurationJsonStore config = injector().getInstance(GlobalConfigurationJsonStore.class);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS
| ServletContextHandler.SECURITY);
Constraint constraint = new Constraint();
constraint.setName(Constraint.__SPNEGO_AUTH);
constraint.setRoles(config.get().roles());
constraint.setAuthenticate(true);
ConstraintMapping constraintMapping = new ConstraintMapping();
constraintMapping.setConstraint(constraint); |
package codeine.mail;
import java.util.List;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.tz.FixedDateTimeZone;
import codeine.jsons.mails.AlertsCollectionType;
import com.google.common.collect.Lists;
public class CollectionTypeGetter {
private static final Logger log = Logger.getLogger(CollectionTypeGetter.class);
private static final int TIME_WINDOW_TO_REPORT_HOUR = 5;
private static final int TIME_WINDOW_TO_REPORT_DAY_MIN = 21;
private static final int TIME_WINDOW_TO_REPORT_DAY_MAX = 22;
private DateTime lastGet;
private DateTime lastDailyCollection;
private DateTime lastHourlyCollection;
public CollectionTypeGetter() {
this(FixedDateTimeZone.getDefault());
}
public CollectionTypeGetter(DateTimeZone tz) {
lastGet = new DateTime(0, tz);
lastHourlyCollection = new DateTime(0, tz);
lastDailyCollection = new DateTime(0, tz);
}
public List<AlertsCollectionType> getCollectionType(DateTime dateTime) {
if (!dateTime.isAfter(lastGet)){
throw new IllegalArgumentException("collection is not after previous " + lastGet + ", " + dateTime);
}
lastGet = dateTime;
if (dateTime.getHourOfDay() >= TIME_WINDOW_TO_REPORT_DAY_MIN
&& dateTime.getHourOfDay() <= TIME_WINDOW_TO_REPORT_DAY_MAX &&
Hours.hoursBetween(lastDailyCollection, dateTime).getHours() > reportingWindowDay()){
log.info("daily mail collection");
lastDailyCollection = dateTime;
lastHourlyCollection = dateTime;
return Lists.newArrayList(AlertsCollectionType.Immediately, AlertsCollectionType.Hourly, AlertsCollectionType.Daily);
}
if (dateTime.getMinuteOfHour() <= TIME_WINDOW_TO_REPORT_HOUR && Minutes.minutesBetween(lastHourlyCollection, dateTime).getMinutes() > TIME_WINDOW_TO_REPORT_HOUR){
log.info("hourly mail collection");
lastHourlyCollection = dateTime;
return Lists.newArrayList(AlertsCollectionType.Immediately, AlertsCollectionType.Hourly);
}
return Lists.newArrayList(AlertsCollectionType.Immediately);
}
private int reportingWindowDay() {
return TIME_WINDOW_TO_REPORT_DAY_MAX - TIME_WINDOW_TO_REPORT_DAY_MIN;
}
} |
package org.bdgp.OpenHiCAMM.Modules;
import java.awt.Component;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import javax.swing.JPanel;
import org.bdgp.OpenHiCAMM.Dao;
import org.bdgp.OpenHiCAMM.ImageLog;
import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRecord;
import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRunner;
import org.bdgp.OpenHiCAMM.Logger;
import org.bdgp.OpenHiCAMM.Util;
import org.bdgp.OpenHiCAMM.ValidationError;
import org.bdgp.OpenHiCAMM.WorkflowRunner;
import org.bdgp.OpenHiCAMM.DB.Acquisition;
import org.bdgp.OpenHiCAMM.DB.Config;
import org.bdgp.OpenHiCAMM.DB.Image;
import org.bdgp.OpenHiCAMM.DB.Task;
import org.bdgp.OpenHiCAMM.DB.Task.Status;
import org.bdgp.OpenHiCAMM.DB.TaskConfig;
import org.bdgp.OpenHiCAMM.DB.TaskDispatch;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.ImageLogger;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module;
import org.json.JSONArray;
import org.json.JSONException;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.api.ImageCache;
import org.micromanager.utils.ImageUtils;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.io.FileSaver;
import ij.macro.Interpreter;
import ij.process.ImageProcessor;
import mmcorej.TaggedImage;
import static org.bdgp.OpenHiCAMM.Util.where;
public class ImageStitcher implements Module, ImageLogger {
private static final String FUSION_METHOD = "Linear Blending";
private static final int CHECK_PEAKS = 5;
private static final boolean COMPUTE_OVERLAP = true;
private static final String REGISTRATION_CHANNEL_IMAGE_1 = "Average all channels";
private static final String REGISTRATION_CHANNEL_IMAGE_2 = "Average all channels";
private static final double OVERLAP_WIDTH = 0.25;
private static final double OVERLAP_HEIGHT = 0.25;
private static final String STITCHED_IMAGE_DIRECTORY_PREFIX = "stitched";
WorkflowRunner workflowRunner;
String moduleId;
@Override
public void initialize(WorkflowRunner workflowRunner, String moduleId) {
this.workflowRunner = workflowRunner;
this.moduleId = moduleId;
}
public static class TaskTile {
public Task task;
public Map<String,TaskConfig> taskConfig;
public int tileX;
public int tileY;
public ImagePlus image;
public TaskTile(Task task, Map<String,TaskConfig> taskConfig, int tileX, int tileY, ImagePlus image) {
this.task = task;
this.taskConfig = taskConfig;
this.tileX = tileX;
this.tileY = tileY;
this.image = image;
}
}
private void showImageTable(String message, Logger logger) {
List<String> imageTitles = new ArrayList<String>();
for (int id : Interpreter.getBatchModeImageIDs()) {
ImagePlus image = Interpreter.getBatchModeImage(id);
if (image != null) imageTitles.add(Util.escape(image.getTitle()));
}
String imageTitleList = Util.join(", ", imageTitles);
logger.fine(String.format(
"%s: Image Table (%d count): [%s]", message, imageTitles.size(), imageTitleList));
}
@Override
public Status run(Task task, Map<String,Config> config, Logger logger) {
Dao<TaskConfig> taskConfigDao = this.workflowRunner.getTaskConfig();
logger.fine(String.format("Running task %s: %s", task.getName(), task));
// get the stitch group name
Config stitchGroupConf = config.get("stitchGroup");
if (stitchGroupConf == null) throw new RuntimeException(String.format(
"%s: stitchGroup config not found!", task.getName()));
String stitchGroup = stitchGroupConf.getValue();
logger.fine(String.format("Stitching group: %s", stitchGroup));
// Run the stitching processing to produce a stitched image.
this.showImageTable("Before process()", logger);
ImagePlus stitchedImage = process(task, config, logger, new ImageLog.NullImageLogRunner());
this.showImageTable("After process()", logger);
// get the stitched folder
Config stitchedFolderConf = config.get("stitchedFolder");
if (stitchedFolderConf == null) throw new RuntimeException(String.format(
"%s: stitchedFolder config not found!", task.getName()));
String stitchedFolder = stitchedFolderConf.getValue();
logger.fine(String.format("Stitched folder: %s", stitchedFolder));
// save the stitched image to the stitched folder using the stitch group as the
// file name.
FileSaver fileSaver = new FileSaver(stitchedImage);
String imageFile = new File(stitchedFolder, String.format("%s.tif", stitchGroup)).getPath();
fileSaver.saveAsTiff(imageFile);
// write a task configuration for the stitched image location
TaskConfig imageFileConf = new TaskConfig(new Integer(task.getId()).toString(),
"stitchedImageFile", imageFile);
taskConfigDao.insertOrUpdate(imageFileConf, "id", "key");
return Status.SUCCESS;
}
public ImagePlus process(Task task, Map<String,Config> config, Logger logger, ImageLogRunner imageLogRunner) {
// get the stitch group name
Config stitchGroupConf = config.get("stitchGroup");
if (stitchGroupConf == null) throw new RuntimeException(String.format(
"%s: stitchGroup config not found!", task.getName()));
String stitchGroup = stitchGroupConf.getValue();
logger.fine(String.format("Stitching group: %s", stitchGroup));
// get the list of stitch task IDs
Config stitchTaskIdsConf = config.get("stitchTaskIds");
if (stitchTaskIdsConf == null) throw new RuntimeException(String.format(
"%s: stitchTaskIds config not found!", task.getName()));
// get the list of stitch task IDs from the JSON array
List<Integer> stitchTaskIds = new ArrayList<Integer>();
try {
JSONArray stitchTaskJson = new JSONArray(stitchTaskIdsConf.getValue());
for (int i=0; i<stitchTaskJson.length(); ++i) {
Integer stitchTaskId = stitchTaskJson.getInt(i);
stitchTaskIds.add(stitchTaskId);
}
}
catch (JSONException e) {throw new RuntimeException(e);}
Dao<Image> imageDao = this.workflowRunner.getInstanceDb().table(Image.class);
Dao<Acquisition> acqDao = workflowRunner.getInstanceDb().table(Acquisition.class);
// Organize the tasks into a grid of TaskTiles
Integer gridWidth = null;
Integer gridHeight = null;
List<TaskTile> taskTiles = new ArrayList<TaskTile>();
Integer frame = null;
Integer channel = null;
Integer slice = null;
for (Integer stitchTaskId : stitchTaskIds) {
Task stitchTask = this.workflowRunner.getTaskStatus().selectOne(where("id", stitchTaskId));
if (stitchTask == null) throw new RuntimeException(String.format(
"%s: Stitch task with ID %d not found in database!",
task.getName(), stitchTaskId));
// get the task config for each stitch task
List<TaskConfig> taskConfigs = this.workflowRunner.getTaskConfig().select(where("id", stitchTask.getId()));
Map<String,TaskConfig> taskConfig = new HashMap<String,TaskConfig>();
for (TaskConfig tc : taskConfigs) {
taskConfig.put(tc.getKey(), tc);
}
// get the tileX and tileY, figure out gridWidth and gridHeight
TaskConfig tileXConf = taskConfig.get("tileX");
if (tileXConf == null) throw new RuntimeException(String.format("Task %s: tileX is null!", stitchTask));
Integer tileX = new Integer(tileXConf.getValue());
TaskConfig tileYConf = taskConfig.get("tileY");
if (tileYConf == null) throw new RuntimeException(String.format("Task %s: tileY is null!", stitchTask));
Integer tileY = new Integer(tileYConf.getValue());
if (gridWidth == null || gridWidth < tileX+1) gridWidth = tileX+1;
if (gridHeight == null || gridHeight < tileY+1) gridHeight = tileY+1;
// get the image ID
TaskConfig imageId = taskConfig.get("imageId");
if (imageId == null) throw new RuntimeException(String.format("Task %s: imageId is null!", stitchTask));
// get the Image record
Image image = imageDao.selectOneOrDie(where("id", new Integer(imageId.getValue())));
if (frame == null) frame = image.getFrame();
if (channel == null) channel = image.getChannel();
if (slice == null) slice = image.getSlice();
// Initialize the acquisition
Acquisition acquisition = acqDao.selectOneOrDie(where("id",image.getAcquisitionId()));
MMAcquisition mmacquisition = acquisition.getAcquisition(acqDao);
// Get the image cache object
ImageCache imageCache = mmacquisition.getImageCache();
if (imageCache == null) throw new RuntimeException("Acquisition was not initialized; imageCache is null!");
// Get the tagged image from the image cache
TaggedImage taggedImage = image.getImage(imageCache);
if (taggedImage == null) throw new RuntimeException(String.format("Acqusition %s, Image %s is not in the image cache!",
acquisition, image));
// convert the tagged image into an ImagePlus object
ImageProcessor processor = ImageUtils.makeProcessor(taggedImage);
ImagePlus imp = new ImagePlus(image.getName(), processor);
imageLogRunner.addImage(imp, imp.getTitle());
// create the TaskTile object
TaskTile taskTile = new TaskTile(task, taskConfig, tileX, tileY, imp);
taskTiles.add(taskTile);
}
TaskTile[][] taskGrid = new TaskTile[gridHeight][gridWidth];
for (TaskTile taskTile : taskTiles) {
taskGrid[taskTile.tileY][taskTile.tileX] = taskTile;
}
// stitch the images into a single tagged image
ImagePlus stitchedImage = stitchGrid(taskGrid, logger);
imageLogRunner.addImage(stitchedImage, stitchedImage.getTitle());
// If a window is open, close it.
stitchedImage.changes = false;
stitchedImage.close();
return stitchedImage;
}
public ImagePlus stitchGrid(TaskTile[][] taskGrid, Logger logger) {
ImagePlus image1;
ImagePlus image2;
if (taskGrid.length > 1 || (taskGrid.length > 0 && taskGrid[0].length > 1)) {
TaskTile[][] grid1;
TaskTile[][] grid2;
// vertical split
if (taskGrid.length < taskGrid[0].length) {
int splitPoint = taskGrid[0].length / 2;
grid1 = new TaskTile[taskGrid.length][splitPoint];
for (int r=0; r<taskGrid.length; ++r) {
for (int c=0; c<splitPoint; ++c) {
grid1[r][c] = taskGrid[r][c];
}
}
grid2 = new TaskTile[taskGrid.length][taskGrid[0].length-splitPoint];
for (int r=0; r<taskGrid.length; ++r) {
for (int c=splitPoint; c<taskGrid[0].length; ++c) {
grid2[r][c-splitPoint] = taskGrid[r][c];
}
}
image1 = stitchGrid(grid1, logger);
image2 = stitchGrid(grid2, logger);
return stitchImages(image1, image2, false, logger);
}
// horizontal split
else {
int splitPoint = taskGrid.length / 2;
grid1 = new TaskTile[splitPoint][taskGrid[0].length];
for (int r=0; r<splitPoint; ++r) {
for (int c=0; c<taskGrid[0].length; ++c) {
grid1[r][c] = taskGrid[r][c];
}
}
grid2 = new TaskTile[taskGrid.length-splitPoint][taskGrid[0].length];
for (int r=splitPoint; r<taskGrid.length; ++r) {
for (int c=0; c<taskGrid[0].length; ++c) {
grid2[r-splitPoint][c] = taskGrid[r][c];
}
}
image1 = stitchGrid(grid1, logger);
image2 = stitchGrid(grid2, logger);
return stitchImages(image1, image2, true, logger);
}
}
else if (taskGrid.length > 1) {
image1 = taskGrid[0][0].image;
image2 = taskGrid[1][0].image;
return stitchImages(image1, image2, true, logger);
}
else if (taskGrid.length > 0 && taskGrid[0].length > 1) {
image1 = taskGrid[0][0].image;
image2 = taskGrid[0][1].image;
return stitchImages(image1, image2, false, logger);
}
else if (taskGrid.length == 1 && taskGrid[0].length == 1) {
return taskGrid[0][0].image;
}
else {
throw new RuntimeException("Empty TaskTile array passed to stitchGrid!");
}
}
public ImagePlus stitchImages(
ImagePlus image1,
ImagePlus image2,
boolean isVerticallyAligned,
Logger logger)
{
String fusion_method = FUSION_METHOD;
int check_peaks = CHECK_PEAKS;
boolean compute_overlap = COMPUTE_OVERLAP;
double overlapWidth = OVERLAP_WIDTH;
double overlapHeight = OVERLAP_HEIGHT;
double x = isVerticallyAligned? 0.0 : image1.getWidth() * (1.0 - overlapWidth);
double y = isVerticallyAligned? image1.getHeight() * (1.0 - overlapHeight) : 0.0;
String registration_channel_image_1 = REGISTRATION_CHANNEL_IMAGE_1;
String registration_channel_image_2 = REGISTRATION_CHANNEL_IMAGE_2;
// open the input images
this.showImageTable("Before show()", logger);
image1.show();
image2.show();
this.showImageTable("After show()", logger);
// run the pairwise stitching plugin
String fusedImageTitle = String.format("%s<->%s", image1.getTitle(), image2.getTitle());
String params = Util.join(" ",
String.format("first_image=%s", Util.macroEscape(image1.getTitle())),
String.format("second_image=%s", Util.macroEscape(image2.getTitle())),
String.format("fusion_method=%s", Util.macroEscape(fusion_method)),
String.format("fused_image=%s", Util.macroEscape(fusedImageTitle)),
String.format("check_peaks=%d", check_peaks),
compute_overlap? "compute_overlap" : null,
String.format("x=%.4f", x),
String.format("y=%.4f", y),
String.format("registration_channel_image_1=%s", Util.macroEscape(registration_channel_image_1)),
String.format("registration_channel_image_2=%s", Util.macroEscape(registration_channel_image_2)));
IJ.run(image1, "Pairwise stitching", params);
// Close the input images.
// The pairwise stitching module modifies then input images in-place, so
// closing them won't remove them from the image table. We have to find
// the modified images with the same title, and close those instead.
this.showImageTable("Before close()", logger);
ImagePlus modifiedImage1 = WindowManager.getImage(image1.getTitle());
if (modifiedImage1 == null) throw new RuntimeException(String.format(
"Pairwise Stitching: could not find modified input image 1 with title: %s", image1.getTitle()));
modifiedImage1.changes = false;
modifiedImage1.close();
ImagePlus modifiedImage2 = WindowManager.getImage(image2.getTitle());
if (modifiedImage2 == null) throw new RuntimeException(String.format(
"Pairwise Stitching: could not find modified input image 2 with title: %s", image2.getTitle()));
modifiedImage2.changes = false;
modifiedImage2.close();
this.showImageTable("After close()", logger);
// get the fused image
ImagePlus fusedImage = WindowManager.getImage(fusedImageTitle);
if (fusedImage == null) throw new RuntimeException(String.format(
"Pairwise Stitching: could not find fused image with title: %s", fusedImageTitle));
// convert stack to RGB
if (fusedImage.getNChannels() == 3) {
IJ.run(fusedImage, "Stack to RGB", "");
String rgbImageTitle = String.format("%s (RGB)", fusedImage.getTitle());
ImagePlus rgbImage = WindowManager.getImage(rgbImageTitle);
if (rgbImage == null) throw new RuntimeException(String.format(
"Pairwise Stitching: could not find RGB image with title: %s", rgbImageTitle));
// close the separate-channel fused image
fusedImage.changes = false;
fusedImage.close();
// return the RGB image
rgbImage.changes = false;
rgbImage.close();
return rgbImage;
}
// close the separate-channel fused image
fusedImage.changes = false;
fusedImage.close();
return fusedImage;
}
@Override
public String getTitle() {
return this.getClass().getName();
}
@Override
public String getDescription() {
return this.getClass().getName();
}
@Override
public Configuration configure() {
return new Configuration() {
@Override
public Config[] retrieve() {
return new Config[0];
}
@Override
public Component display(Config[] configs) {
return new JPanel();
}
@Override
public ValidationError[] validate() {
return null;
}
};
}
@Override
public List<Task> createTaskRecords(List<Task> parentTasks) {
Dao<Task> taskDao = this.workflowRunner.getTaskStatus();
Dao<TaskConfig> taskConfigDao = this.workflowRunner.getTaskConfig();
Dao<TaskDispatch> taskDispatchDao = this.workflowRunner.getTaskDispatch();
// Group the parent tasks by stitchGroup name
Map<String,List<Task>> stitchGroups = new LinkedHashMap<String,List<Task>>();
for (Task parentTask : parentTasks) {
TaskConfig stitchGroup = taskConfigDao.selectOne(where("id", parentTask.getId()).and("key", "stitchGroup"));
if (stitchGroup != null) {
// make sure tileX and tileY are set
TaskConfig tileX = taskConfigDao.selectOne(where("id", parentTask.getId()).and("key", "tileX"));
TaskConfig tileY = taskConfigDao.selectOne(where("id", parentTask.getId()).and("key", "tileY"));
if (tileX == null || tileY == null) {
throw new RuntimeException(String.format("tileX and tileY not defined for task: %s", parentTask));
}
// add the task to the stitch group
if (!stitchGroups.containsKey(stitchGroup.getValue())) {
stitchGroups.put(stitchGroup.getValue(), new ArrayList<Task>());
}
stitchGroups.get(stitchGroup.getValue()).add(parentTask);
}
}
// create a folder to store the stitched images
File stitchedFolder = createStitchedImageFolder();
List<Task> tasks = new ArrayList<Task>();
for (Map.Entry<String, List<Task>> entry : stitchGroups.entrySet()) {
String stitchGroup = entry.getKey();
List<Task> stitchTasks = entry.getValue();
// insert the task record
Task task = new Task(this.moduleId, Status.NEW);
taskDao.insert(task);
tasks.add(task);
// add the stitchedFolder task config
TaskConfig stitchedFolderConf = new TaskConfig(
new Integer(task.getId()).toString(),
"stitchedFolder", stitchedFolder.toString());
taskConfigDao.insert(stitchedFolderConf);
// add the stitchGroup task config
TaskConfig stitchGroupConf = new TaskConfig(
new Integer(task.getId()).toString(),
"stitchGroup", stitchGroup);
taskConfigDao.insert(stitchGroupConf);
// add the stitchTaskIds task config, a JSONArray of stitch task IDs.
JSONArray stitchTaskIds = new JSONArray();
for (Task stitchTask : stitchTasks) {
stitchTaskIds.put(stitchTask.getId());
}
TaskConfig stitchTaskIdsConf = new TaskConfig(
new Integer(task.getId()).toString(),
"stitchTaskIds", stitchTaskIds.toString());
taskConfigDao.insert(stitchTaskIdsConf);
// add the task dispatch records
for (Task stitchTask : stitchTasks) {
TaskDispatch td = new TaskDispatch(task.getId(), stitchTask.getId());
taskDispatchDao.insert(td);
}
}
return tasks;
}
private File createStitchedImageFolder() {
String rootDir = new File(
this.workflowRunner.getWorkflowDir(),
this.workflowRunner.getInstance().getStorageLocation()).getPath();
int count = 1;
File stitchedFolder = new File(rootDir, String.format("%s_%d", STITCHED_IMAGE_DIRECTORY_PREFIX, count));
while (!stitchedFolder.mkdirs()) {
++count;
stitchedFolder = new File(rootDir, String.format("%s_%d", STITCHED_IMAGE_DIRECTORY_PREFIX, count));
}
return stitchedFolder;
}
@Override
public TaskType getTaskType() {
return Module.TaskType.PARALLEL;
}
@Override public void cleanup(Task task) { }
@Override
public void runIntialize() { }
@Override
public List<ImageLogRecord> logImages(final Task task, final Map<String,Config> config, final Logger logger) {
List<ImageLogRecord> imageLogRecords = new ArrayList<ImageLogRecord>();
// Add an image logger instance to the workflow runner for this module
imageLogRecords.add(new ImageLogRecord(task.getName(), task.getName(),
new FutureTask<ImageLogRunner>(new Callable<ImageLogRunner>() {
@Override public ImageLogRunner call() throws Exception {
ImageLogRunner imageLogRunner = new ImageLogRunner(task.getName());
ImageStitcher.this.process(task, config, logger, imageLogRunner);
return imageLogRunner;
}
})));
return imageLogRecords;
}
} |
package org.biojava.bio.dist;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.biojava.bio.BioError;
import org.biojava.bio.Annotation;
import org.biojava.bio.symbol.Alphabet;
import org.biojava.bio.symbol.AlphabetIndex;
import org.biojava.bio.symbol.AlphabetManager;
import org.biojava.bio.symbol.AtomicSymbol;
import org.biojava.bio.symbol.FiniteAlphabet;
import org.biojava.bio.symbol.IllegalAlphabetException;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.biojava.bio.symbol.Symbol;
import org.biojava.utils.*;
/**
* An abstract implementation of Distribution.
* <p>
* You will need to override <code>getWeight()</code> for a simple
* implementation. You may also wish to override the other methods if the
* default implementation is not suitable.
* </p>
*
* <p>
* The <code>registerWithTrainer</code> method registers
* an <code>IgnoreCountsTrainer</code>. To make an <code>AbstractDistribution</code>
* subclass trainable, this method must be overridden.
* </p>
*
* @author Matthew Pocock
* @author Thomas Down
* @author Mark Schreiber (serialization support)
* @author Greg Cox
* @since 1.0
*/
public abstract class AbstractDistribution
extends
AbstractChangeable
implements
Distribution,
Serializable
{
/**
* Forwarder for modifications to the null model.
*/
protected transient ChangeForwarder nullModelForwarder = null;
/**
* Used for serialization.
*/
protected Map symbolIndices = null;
/**
* Governs serialization behaivour.
*
* @param stream the ObjectOutputStream to write to
*/
private void writeObject(ObjectOutputStream stream)throws IOException{
AlphabetIndex index = AlphabetManager.getAlphabetIndex((FiniteAlphabet)getAlphabet());
int size = ((FiniteAlphabet)getAlphabet()).size();
symbolIndices = new HashMap(size);
for(int i = 0; i < size; i++){
try{
symbolIndices.put(index.symbolForIndex(i).getName(),
new Double(getWeight(index.symbolForIndex(i))));
}catch(IllegalSymbolException e){
throw new BioError(e);
}
}
stream.defaultWriteObject();
}
protected ChangeSupport getChangeSupport(ChangeType ct) {
ChangeSupport changeSupport = super.getChangeSupport(ct);
if(
((Distribution.NULL_MODEL.isMatchingType(ct)) || (ct.isMatchingType(Distribution.NULL_MODEL))) &&
nullModelForwarder == null
) {
nullModelForwarder =
new ChangeForwarder.Retyper(this, changeSupport, Distribution.NULL_MODEL);
getNullModel().addChangeListener(nullModelForwarder, Distribution.WEIGHTS);
}
return changeSupport;
}
abstract protected void setWeightImpl(AtomicSymbol sym, double weight)
throws IllegalSymbolException, ChangeVetoException;
final public void setWeight(Symbol sym, double weight)
throws IllegalSymbolException, ChangeVetoException {
if(!hasListeners()) {
doSetWeight(sym, weight);
} else {
ChangeEvent ce = new ChangeEvent(
this,
Distribution.WEIGHTS,
new Object[] {sym, new Double(weight)},
new Object[] {sym, new Double(getWeight(sym))}
);
ChangeSupport changeSupport = super.getChangeSupport(Distribution.WEIGHTS);
synchronized(changeSupport) {
changeSupport.firePreChangeEvent(ce);
doSetWeight(sym, weight);
changeSupport.firePostChangeEvent(ce);
}
}
}
private void doSetWeight(Symbol sym, double weight)
throws IllegalSymbolException, ChangeVetoException {
if(sym instanceof AtomicSymbol) {
setWeightImpl((AtomicSymbol) sym, weight);
} else {
//need to divide the weight up amongst the atomic symbols according
//to the null model
FiniteAlphabet fa = (FiniteAlphabet) sym.getMatches();
double totalNullWeight = this.getNullModel().getWeight(sym);
for(Iterator si = fa.iterator(); si.hasNext(); ) {
AtomicSymbol as = (AtomicSymbol) si.next();
double symNullWeight = this.getNullModel().getWeight(as);
setWeightImpl(as, weight * symNullWeight / totalNullWeight);
}
}
}
abstract protected void setNullModelImpl(Distribution nullModel)
throws IllegalAlphabetException, ChangeVetoException;
final public void setNullModel(Distribution nullModel)
throws IllegalAlphabetException, ChangeVetoException {
if(nullModel.getAlphabet() != getAlphabet()) {
throw new IllegalAlphabetException(
"Could not use distribution " + nullModel +
" as its alphabet is " + nullModel.getAlphabet().getName() +
" and this distribution's alphabet is " + getAlphabet().getName()
);
}
Distribution oldModel = getNullModel();
if(nullModelForwarder != null) {
if(oldModel != null) {
oldModel.removeChangeListener(nullModelForwarder);
}
nullModel.addChangeListener(nullModelForwarder);
}
if(!hasListeners()) {
// if there are no listeners yet, don't go through the overhead of
// synchronized regions or of trying to inform them.
setNullModelImpl(nullModel);
} else {
// OK - so somebody is intereted in me. Do it properly this time.
ChangeEvent ce = new ChangeEvent(
this,
Distribution.NULL_MODEL,
nullModel,
oldModel
);
ChangeSupport changeSupport = super.getChangeSupport(Distribution.NULL_MODEL);
synchronized(changeSupport) {
changeSupport.firePreChangeEvent(ce);
setNullModelImpl(nullModel);
changeSupport.firePostChangeEvent(ce);
}
}
}
public final double getWeight(Symbol sym)
throws IllegalSymbolException {
if(sym instanceof AtomicSymbol) {
return getWeightImpl((AtomicSymbol) sym);
} else {
Alphabet ambA = sym.getMatches();
if(((FiniteAlphabet) ambA).size() == 0) {
getAlphabet().validate(sym);
return 0.0;
}
if(ambA instanceof FiniteAlphabet) {
FiniteAlphabet fa = (FiniteAlphabet) ambA;
double sum = 0.0;
for(Iterator i = fa.iterator(); i.hasNext(); ) {
Object obj = i.next();
if(!(obj instanceof AtomicSymbol)) {
throw new BioError(
"Assertion Failure: Not an instance of AtomicSymbol: " +
obj
);
}
AtomicSymbol as = (AtomicSymbol) obj;
sum += getWeightImpl(as);
}
return sum;
} else {
throw new IllegalSymbolException(
"Can't find weight for infinite set of symbols matched by " +
sym.getName()
);
}
}
}
protected abstract double getWeightImpl(AtomicSymbol sym)
throws IllegalSymbolException;
public Symbol sampleSymbol() {
double p = Math.random();
try {
for(Iterator i = ((FiniteAlphabet) getAlphabet()).iterator(); i.hasNext(); ) {
AtomicSymbol s = (AtomicSymbol) i.next();
p -= getWeight(s);
if( p <= 0) {
return s;
}
}
StringBuffer sb = new StringBuffer();
for(Iterator i = ((FiniteAlphabet) this.getAlphabet()).iterator(); i.hasNext(); ) {
AtomicSymbol s = (AtomicSymbol) i.next();
double w = getWeight(s);
sb.append("\t" + s.getName() + " -> " + w + "\n");
}
throw new BioError(
"Could not find a symbol to emit from alphabet " + getAlphabet() +
". Do the probabilities sum to 1?" + "\np=" + p + "\n" + sb.substring(0)
);
} catch (IllegalSymbolException ire) {
throw new BioError(
"Unable to iterate over all symbols in alphabet - " +
"things changed beneath me!", ire
);
}
}
/**
* Register an IgnoreCountsTrainer instance as the trainer for this
* distribution. Override this if you wish to implement a trainable
* distribution.
*
* @param dtc the context to register with
*/
public void registerWithTrainer(DistributionTrainerContext dtc) {
dtc.registerTrainer(this, IgnoreCountsTrainer.getInstance());
}
} |
package com.fatel.mamtv1;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* A simple {@link Fragment} subclass.
*/
public class AlarmFragment extends android.support.v4.app.Fragment {
private Spinner mStartHr;
private Spinner mStartMin;
private Spinner mStartAP;
private Spinner mFinishHr;
private Spinner mFinishMin;
private Spinner mFinishAP;
private CheckBox mChkboxMon;
private CheckBox mChkboxTue;
private CheckBox mChkboxWed;
private CheckBox mChkboxThu;
private CheckBox mChkboxFri;
private CheckBox mChkboxSat;
private CheckBox mChkboxSun;
private String mdays="";
private Spinner mFreq;
private DBAlarmHelper mAlarmHelper;
private int ID = -1;
private PendingIntent pendingIntent;
public AlarmFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_alarm, container, false);
mAlarmHelper = new DBAlarmHelper(getActivity());
mStartHr = createSpinner(12, R.id.start_hr,true,view,mAlarmHelper,true);
mStartMin = createSpinner(60, R.id.start_min,false,view,mAlarmHelper,true);
mFinishHr = createSpinner(12, R.id.fin_hr, true, view,mAlarmHelper,false);
mFinishMin = createSpinner(60, R.id.fin_min, false, view, mAlarmHelper, false);
mStartAP = createSpinnerAmPm(R.id.start_AP, view,mAlarmHelper,true);
mFinishAP = createSpinnerAmPm(R.id.fin_AP, view,mAlarmHelper,false);
mChkboxSun = (CheckBox)view.findViewById(R.id.chkboxSun);
mChkboxMon = (CheckBox)view.findViewById(R.id.chkboxMon);
mChkboxTue = (CheckBox)view.findViewById(R.id.chkboxTue);
mChkboxWed = (CheckBox)view.findViewById(R.id.chkboxWed);
mChkboxThu = (CheckBox)view.findViewById(R.id.chkboxThu);
mChkboxFri = (CheckBox)view.findViewById(R.id.chkboxFri);
mChkboxSat = (CheckBox)view.findViewById(R.id.chkboxSat);
mFreq = createSpinnerFrq(R.id.frq_min, view,mAlarmHelper);
//check checkbox tick
if(mAlarmHelper.checkdata()==1) {
DatabaseAlarm alarm = mAlarmHelper.getAlarm();
String day = alarm.getDay();
if(day.substring(0,1).equals("1"))
mChkboxSun.setChecked(true);
if(day.substring(1,2).equals("1"))
mChkboxMon.setChecked(true);
if(day.substring(2,3).equals("1"))
mChkboxTue.setChecked(true);
if(day.substring(3,4).equals("1"))
mChkboxWed.setChecked(true);
if(day.substring(4,5).equals("1"))
mChkboxThu.setChecked(true);
if(day.substring(5,6).equals("1"))
mChkboxFri.setChecked(true);
if(day.substring(6,7).equals("1"))
mChkboxSat.setChecked(true);
}
Button bt = (Button) view.findViewById(R.id.buttonSet);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mChkboxSun.isChecked()){
mdays += "1";
}
else{
mdays += "0";
}
if(mChkboxMon.isChecked()){
mdays += "1";
}
else{
mdays += "0";
}
if(mChkboxTue.isChecked()){
mdays += "1";
}
else{
mdays += "0";
}
if(mChkboxWed.isChecked()){
mdays += "1";
}
else{
mdays += "0";
}
if(mChkboxThu.isChecked()){
mdays += "1";
}
else{
mdays += "0";
}
if(mChkboxFri.isChecked()){
mdays += "1";
}
else{
mdays += "0";
}
if(mChkboxSat.isChecked()){
mdays += "1";
}
else{
mdays += "0";
}
//keep data
DatabaseAlarm alarm = new DatabaseAlarm();
alarm.setStarthr(mStartHr.getSelectedItem().toString());
alarm.setStartmin(mStartMin.getSelectedItem().toString());
alarm.setStophr(mFinishHr.getSelectedItem().toString());
alarm.setStopmin(mFinishMin.getSelectedItem().toString());
alarm.setStartinterval(mStartAP.getSelectedItem().toString());
alarm.setStopinterval(mFinishAP.getSelectedItem().toString());
alarm.setDay(mdays.toString());
alarm.setFrq(mFreq.getSelectedItem().toString());
if (ID == -1 && (mAlarmHelper.checkdata()==0)) {
mAlarmHelper.addAlarm(alarm);
} else {
mAlarmHelper.UpdateAlarm(alarm);
}
//finish();
Intent mServiceIntent = new Intent(getActivity(), AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity(),0,mServiceIntent,0);
start();
FragmentTransaction tx = getFragmentManager().beginTransaction();
tx.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
tx.replace(R.id.container, new MainFragment());
tx.addToBackStack(null);
tx.commit();
}
});
return view;
}
public Spinner createSpinner(int num,int id,boolean isHr,View view,DBAlarmHelper mAlarmHelper,boolean isStart)
{
Spinner spinner = (Spinner)view.findViewById(id);
String[] numm = new String[num];
ArrayAdapter<String> adapter;
if(isHr) {
for (int i = 1; i <= num; i++) {
if(i<10)
numm[i - 1] = "0" + i;
else
numm[i - 1] = "" + i;
}
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, numm);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
if(mAlarmHelper.checkdata()==0)
spinner.setSelection(11);
else
{
DatabaseAlarm alarm = mAlarmHelper.getAlarm();
if(isStart) {
String hr = alarm.getStarthr();
spinner.setSelection(Integer.parseInt(hr) - 1);
}
else
{
String hr = alarm.getStophr();
spinner.setSelection(Integer.parseInt(hr)-1);
}
}
}
else {
for (int i = 0; i < num; i++) {
if(i<10)
numm[i] = "0" + i;
else
numm[i] = "" + i;
}
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, numm);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
if(mAlarmHelper.checkdata()==1)
{
DatabaseAlarm alarm = mAlarmHelper.getAlarm();
if(isStart) {
String min = alarm.getStartmin();
spinner.setSelection(Integer.parseInt(min));
}
else
{
String min = alarm.getStopmin();
spinner.setSelection(Integer.parseInt(min));
}
}
}
return spinner;
}
public Spinner createSpinnerAmPm(int id,View view,DBAlarmHelper mAlarmHelper,boolean isStart)
{
Spinner spinner = (Spinner)view.findViewById(id);
String[] numm = new String[]{"AM","PM"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, numm);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
if(mAlarmHelper.checkdata()==1)
{
DatabaseAlarm alarm = mAlarmHelper.getAlarm();
if(isStart) {
String ap = alarm.getStartinterval();
if(ap.equals("AM"))
spinner.setSelection(0);
else
spinner.setSelection(1);
}
else
{
String ap = alarm.getStopinterval();
if(ap.equals("AM"))
spinner.setSelection(0);
else
spinner.setSelection(1);
}
}
return spinner;
}
public Spinner createSpinnerFrq(int id,View view,DBAlarmHelper mAlarmHelper)
{
Spinner spinner = (Spinner)view.findViewById(id);
String[] numm = new String[]{"15","30","45","60","75","90"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, numm);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
if(mAlarmHelper.checkdata()==1)
{
DatabaseAlarm alarm = mAlarmHelper.getAlarm();
String frq = alarm.getFrq();
int frqint = -1;
if(frq.equals("15"))
frqint = 0;
else if(frq.equals("30"))
frqint = 1;
else if(frq.equals("45"))
frqint = 2;
else if(frq.equals("60"))
frqint = 3;
else if(frq.equals("75"))
frqint = 4;
else if(frq.equals("90"))
frqint = 5;
spinner.setSelection(frqint);
}
return spinner;
}
public void start() {
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
int interval = 6000;
manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, pendingIntent);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
DatabaseAlarm alarm = mAlarmHelper.getAlarm();
Log.i("Day",sdf.format(calendar.getTime())+" "+calendar.get(Calendar.DAY_OF_WEEK)+" "+alarm.getDay()+" "
+calendar.get(Calendar.HOUR_OF_DAY)+" "+calendar.get(Calendar.MINUTE));
if(Integer.parseInt(alarm.getDay().substring(calendar.get(Calendar.DAY_OF_WEEK)-1,calendar.get(Calendar.DAY_OF_WEEK)))==1){
String startin = alarm.getStartinterval();
String stopin = alarm.getStopinterval();
int starthour = Integer.parseInt(alarm.getStarthr());
int startmin = Integer.parseInt(alarm.getStartmin());
int stophour = Integer.parseInt(alarm.getStophr());
int stopmin = Integer.parseInt(alarm.getStopmin());
int frequency = Integer.parseInt(alarm.getFrq());
if(startin.equalsIgnoreCase("am")){
if(starthour==12)
starthour = 0;
}
else{
if(starthour==12)
starthour=12;
else
starthour+=12;
}
if(stopin.equalsIgnoreCase("am")){
if(stophour==12)
stophour = 0;
}
else{
if(stophour==12)
stophour=12;
else
stophour+=12;
}
if(frequency+stopmin>59){
int tempmin = frequency+stopmin;
stopmin = tempmin-(60*(tempmin/60));
stophour += tempmin/60;
}
if(calendar.get(Calendar.HOUR_OF_DAY)>=starthour&&calendar.get(Calendar.MINUTE)>=startmin&&
calendar.get(Calendar.HOUR_OF_DAY)<=stophour&&calendar.get(Calendar.MINUTE)<=stopmin){
int tempminite = calendar.get(Calendar.MINUTE)+frequency;
int setmin = tempminite;
int sethr = calendar.get(Calendar.HOUR_OF_DAY);
if(tempminite>59){
setmin = tempminite-(60*(tempminite/60));
sethr += tempminite/60;
}
calendar.set(calendar.HOUR_OF_DAY,sethr);
calendar.set(calendar.MINUTE,setmin);
}
}
}
} |
package org.bouncycastle.asn1;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import org.bouncycastle.util.Arrays;
public class DERObjectIdentifier
extends ASN1Primitive
{
String identifier;
private byte[] body;
public static ASN1ObjectIdentifier getInstance(
Object obj)
{
if (obj == null || obj instanceof ASN1ObjectIdentifier)
{
return (ASN1ObjectIdentifier)obj;
}
if (obj instanceof DERObjectIdentifier)
{
return new ASN1ObjectIdentifier(((DERObjectIdentifier)obj).getId());
}
if (obj instanceof ASN1Encodable && ((ASN1Encodable)obj).toASN1Primitive() instanceof ASN1ObjectIdentifier)
{
return (ASN1ObjectIdentifier)((ASN1Encodable)obj).toASN1Primitive();
}
if (obj instanceof byte[])
{
return ASN1ObjectIdentifier.fromOctetString((byte[])obj);
}
throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
}
public static ASN1ObjectIdentifier getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
ASN1Primitive o = obj.getObject();
if (explicit || o instanceof DERObjectIdentifier)
{
return getInstance(o);
}
else
{
return ASN1ObjectIdentifier.fromOctetString(ASN1OctetString.getInstance(obj.getObject()).getOctets());
}
}
private static final long LONG_LIMIT = (Long.MAX_VALUE >> 7) - 0x7f;
DERObjectIdentifier(
byte[] bytes)
{
StringBuffer objId = new StringBuffer();
long value = 0;
BigInteger bigValue = null;
boolean first = true;
for (int i = 0; i != bytes.length; i++)
{
int b = bytes[i] & 0xff;
if (value <= LONG_LIMIT)
{
value += (b & 0x7f);
if ((b & 0x80) == 0) // end of number reached
{
if (first)
{
if (value < 40)
{
objId.append('0');
}
else if (value < 80)
{
objId.append('1');
value -= 40;
}
else
{
objId.append('2');
value -= 80;
}
first = false;
}
objId.append('.');
objId.append(value);
value = 0;
}
else
{
value <<= 7;
}
}
else
{
if (bigValue == null)
{
bigValue = BigInteger.valueOf(value);
}
bigValue = bigValue.or(BigInteger.valueOf(b & 0x7f));
if ((b & 0x80) == 0)
{
if (first)
{
objId.append('2');
bigValue = bigValue.subtract(BigInteger.valueOf(80));
first = false;
}
objId.append('.');
objId.append(bigValue);
bigValue = null;
value = 0;
}
else
{
bigValue = bigValue.shiftLeft(7);
}
}
}
this.identifier = objId.toString();
this.body = Arrays.clone(bytes);
}
public DERObjectIdentifier(
String identifier)
{
if (!isValidIdentifier(identifier))
{
throw new IllegalArgumentException("string " + identifier + " not an OID");
}
this.identifier = identifier;
}
public String getId()
{
return identifier;
}
private void writeField(
ByteArrayOutputStream out,
long fieldValue)
{
byte[] result = new byte[9];
int pos = 8;
result[pos] = (byte)((int)fieldValue & 0x7f);
while (fieldValue >= (1L << 7))
{
fieldValue >>= 7;
result[--pos] = (byte)((int)fieldValue & 0x7f | 0x80);
}
out.write(result, pos, 9 - pos);
}
private void writeField(
ByteArrayOutputStream out,
BigInteger fieldValue)
{
int byteCount = (fieldValue.bitLength()+6)/7;
if (byteCount == 0)
{
out.write(0);
}
else
{
BigInteger tmpValue = fieldValue;
byte[] tmp = new byte[byteCount];
for (int i = byteCount-1; i >= 0; i
{
tmp[i] = (byte) ((tmpValue.intValue() & 0x7f) | 0x80);
tmpValue = tmpValue.shiftRight(7);
}
tmp[byteCount-1] &= 0x7f;
out.write(tmp, 0, tmp.length);
}
}
private void doOutput(ByteArrayOutputStream aOut)
{
OIDTokenizer tok = new OIDTokenizer(identifier);
int first = Integer.parseInt(tok.nextToken()) * 40;
String secondToken = tok.nextToken();
if (secondToken.length() <= 18)
{
writeField(aOut, first + Long.parseLong(secondToken));
}
else
{
writeField(aOut, new BigInteger(secondToken).add(BigInteger.valueOf(first)));
}
while (tok.hasMoreTokens())
{
String token = tok.nextToken();
if (token.length() <= 18)
{
writeField(aOut, Long.parseLong(token));
}
else
{
writeField(aOut, new BigInteger(token));
}
}
}
protected synchronized byte[] getBody()
{
if (body == null)
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
doOutput(bOut);
body = bOut.toByteArray();
}
return body;
}
boolean isConstructed()
{
return false;
}
int encodedLength()
throws IOException
{
int length = getBody().length;
return 1 + StreamUtil.calculateBodyLength(length) + length;
}
void encode(
ASN1OutputStream out)
throws IOException
{
byte[] enc = getBody();
out.write(BERTags.OBJECT_IDENTIFIER);
out.writeLength(enc.length);
out.write(enc);
}
public int hashCode()
{
return identifier.hashCode();
}
boolean asn1Equals(
ASN1Primitive o)
{
if (!(o instanceof DERObjectIdentifier))
{
return false;
}
return identifier.equals(((DERObjectIdentifier)o).identifier);
}
public String toString()
{
return getId();
}
private static boolean isValidIdentifier(
String identifier)
{
if (identifier.length() < 3
|| identifier.charAt(1) != '.')
{
return false;
}
char first = identifier.charAt(0);
if (first < '0' || first > '2')
{
return false;
}
boolean periodAllowed = false;
for (int i = identifier.length() - 1; i >= 2; i
{
char ch = identifier.charAt(i);
// TODO Leading zeroes?
if ('0' <= ch && ch <= '9')
{
periodAllowed = true;
continue;
}
if (ch == '.')
{
if (!periodAllowed)
{
return false;
}
periodAllowed = false;
continue;
}
return false;
}
return periodAllowed;
}
private static ASN1ObjectIdentifier[][] cache = new ASN1ObjectIdentifier[256][];
static ASN1ObjectIdentifier fromOctetString(byte[] enc)
{
if (enc.length < 3)
{
return new ASN1ObjectIdentifier(enc);
}
int idx1 = enc[enc.length - 2] & 0xff;
// in this case top bit is always zero
int idx2 = enc[enc.length - 1] & 0x7f;
ASN1ObjectIdentifier possibleMatch;
synchronized (cache)
{
ASN1ObjectIdentifier[] first = cache[idx1];
if (first == null)
{
first = cache[idx1] = new ASN1ObjectIdentifier[128];
}
possibleMatch = first[idx2];
if (possibleMatch == null)
{
return first[idx2] = new ASN1ObjectIdentifier(enc);
}
if (Arrays.areEqual(enc, possibleMatch.getBody()))
{
return possibleMatch;
}
idx1 = (idx1 + 1) & 0xff;
first = cache[idx1];
if (first == null)
{
first = cache[idx1] = new ASN1ObjectIdentifier[128];
}
possibleMatch = first[idx2];
if (possibleMatch == null)
{
return first[idx2] = new ASN1ObjectIdentifier(enc);
}
if (Arrays.areEqual(enc, possibleMatch.getBody()))
{
return possibleMatch;
}
idx2 = (idx2 + 1) & 0x7f;
possibleMatch = first[idx2];
if (possibleMatch == null)
{
return first[idx2] = new ASN1ObjectIdentifier(enc);
}
}
if (Arrays.areEqual(enc, possibleMatch.getBody()))
{
return possibleMatch;
}
return new ASN1ObjectIdentifier(enc);
}
} |
package org.mtransit.android.data;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import org.mtransit.android.R;
import org.mtransit.android.commons.CollectionUtils;
import org.mtransit.android.commons.Constants;
import org.mtransit.android.commons.LocationUtils;
import org.mtransit.android.commons.MTLog;
import org.mtransit.android.commons.SensorUtils;
import org.mtransit.android.commons.TaskUtils;
import org.mtransit.android.commons.ThemeUtils;
import org.mtransit.android.commons.TimeUtils;
import org.mtransit.android.commons.api.SupportFactory;
import org.mtransit.android.commons.data.AppStatus;
import org.mtransit.android.commons.data.AvailabilityPercent;
import org.mtransit.android.commons.data.POI;
import org.mtransit.android.commons.data.POIStatus;
import org.mtransit.android.commons.data.Route;
import org.mtransit.android.commons.data.RouteTripStop;
import org.mtransit.android.commons.data.Schedule;
import org.mtransit.android.commons.data.ServiceUpdate;
import org.mtransit.android.commons.task.MTAsyncTask;
import org.mtransit.android.commons.ui.widget.MTArrayAdapter;
import org.mtransit.android.provider.FavoriteManager;
import org.mtransit.android.task.ServiceUpdateLoader;
import org.mtransit.android.task.StatusLoader;
import org.mtransit.android.ui.MainActivity;
import org.mtransit.android.ui.fragment.AgencyTypeFragment;
import org.mtransit.android.ui.fragment.NearbyFragment;
import org.mtransit.android.ui.fragment.RTSRouteFragment;
import org.mtransit.android.ui.view.MTCompassView;
import org.mtransit.android.ui.view.MTJPathsView;
import org.mtransit.android.ui.view.MTOnClickListener;
import org.mtransit.android.ui.view.MTOnItemClickListener;
import org.mtransit.android.ui.view.MTOnItemLongClickListener;
import org.mtransit.android.ui.view.MTOnLongClickListener;
import org.mtransit.android.ui.view.MTPieChartPercentView;
import org.mtransit.android.util.CrashUtils;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class POIArrayAdapter extends MTArrayAdapter<POIManager> implements SensorUtils.CompassListener, AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener, SensorEventListener, AbsListView.OnScrollListener, StatusLoader.StatusLoaderListener,
ServiceUpdateLoader.ServiceUpdateLoaderListener, FavoriteManager.FavoriteUpdateListener, SensorUtils.SensorTaskCompleted,
TimeUtils.TimeChangedReceiver.TimeChangedListener {
private static final String TAG = POIArrayAdapter.class.getSimpleName();
private String tag = TAG;
@Override
public String getLogTag() {
return tag;
}
public void setTag(String tag) {
this.tag = TAG + "-" + tag;
}
public static final int TYPE_HEADER_NONE = 0;
public static final int TYPE_HEADER_BASIC = 1;
public static final int TYPE_HEADER_ALL_NEARBY = 2;
public static final int TYPE_HEADER_MORE = 3;
private LayoutInflater layoutInflater;
private LinkedHashMap<Integer, ArrayList<POIManager>> poisByType;
private HashSet<String> favUUIDs;
private HashMap<String, Integer> favUUIDsFolderIds;
private WeakReference<Activity> activityWR;
private Location location;
private int lastCompassInDegree = -1;
private float locationDeclination;
private HashSet<String> closestPoiUuids;
private float[] accelerometerValues = new float[3];
private float[] magneticFieldValues = new float[3];
private boolean showStatus = true; // show times / availability
private boolean showServiceUpdate = true; // show warning icon
private boolean showFavorite = true; // show favorite star
private boolean showBrowseHeaderSection = false; // show header with shortcut to agency type screens
private int showTypeHeader = TYPE_HEADER_NONE;
private boolean showTypeHeaderNearby = false; // show nearby header instead of default type header
private boolean infiniteLoading = false; // infinite loading
private InfiniteLoadingListener infiniteLoadingListener;
private ViewGroup manualLayout;
private ScrollView manualScrollView;
private long lastNotifyDataSetChanged = -1L;
private int scrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
private long nowToTheMinute = -1L;
private boolean timeChangedReceiverEnabled = false;
private boolean compassUpdatesEnabled = false;
private long lastCompassChanged = -1L;
private FavoriteManager.FavoriteUpdateListener favoriteUpdateListener = this;
public POIArrayAdapter(Activity activity) {
super(activity, -1);
setActivity(activity);
this.layoutInflater = LayoutInflater.from(getContext());
}
public void setManualLayout(ViewGroup manualLayout) {
this.manualLayout = manualLayout;
}
public void setFavoriteUpdateListener(FavoriteManager.FavoriteUpdateListener favoriteUpdateListener) {
this.favoriteUpdateListener = favoriteUpdateListener;
}
public void setShowStatus(boolean showData) {
this.showStatus = showData;
}
public void setShowServiceUpdate(boolean showServiceUpdate) {
this.showServiceUpdate = showServiceUpdate;
}
public void setShowFavorite(boolean showFavorite) {
this.showFavorite = showFavorite;
}
public void setShowBrowseHeaderSection(boolean showBrowseHeaderSection) {
this.showBrowseHeaderSection = showBrowseHeaderSection;
}
public void setShowTypeHeader(int showTypeHeader) {
this.showTypeHeader = showTypeHeader;
}
public void setShowTypeHeaderNearby(boolean showTypeHeaderNearby) {
this.showTypeHeaderNearby = showTypeHeaderNearby;
}
public void setInfiniteLoading(boolean infiniteLoading) {
this.infiniteLoading = infiniteLoading;
}
public void setInfiniteLoadingListener(InfiniteLoadingListener infiniteLoadingListener) {
this.infiniteLoadingListener = infiniteLoadingListener;
}
public interface InfiniteLoadingListener {
boolean isLoadingMore();
boolean showingDone();
}
private static final int VIEW_TYPE_COUNT = 11;
/**
* @see #getItemViewType(int)
*/
@Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
/**
* @see #getViewTypeCount()
*/
@Override
public int getItemViewType(int position) {
POIManager poim = getItem(position);
if (poim == null) {
if (this.showBrowseHeaderSection && position == 0) {
return 0; // BROWSE SECTION
}
if (this.infiniteLoading && position + 1 == getCount()) {
return 9; // LOADING FOOTER
}
if (this.showTypeHeader != TYPE_HEADER_NONE) {
if (this.poisByType != null) {
Integer typeId = getItemTypeHeader(position);
if (typeId != null) {
if (FavoriteManager.isFavoriteDataSourceId(typeId)) {
return 10; // TYPE FAVORITE FOLDER
}
return 8; // TYPE HEADER
}
}
}
CrashUtils.w(this, "Cannot find type for at position '%s'!", position);
return IGNORE_ITEM_VIEW_TYPE;
}
int type = poim.poi.getType();
int statusType = poim.getStatusType();
switch (type) {
case POI.ITEM_VIEW_TYPE_TEXT_MESSAGE:
return 7; // TEXT MESSAGE
case POI.ITEM_VIEW_TYPE_MODULE:
switch (statusType) {
case POI.ITEM_STATUS_TYPE_SCHEDULE:
return 5; // MODULE & APP STATUS
default:
return 6; // MODULE
}
case POI.ITEM_VIEW_TYPE_ROUTE_TRIP_STOP:
switch (statusType) {
case POI.ITEM_STATUS_TYPE_SCHEDULE:
return 3; // RTS & SCHEDULE
default:
return 4; // RTS
}
case POI.ITEM_VIEW_TYPE_BASIC_POI:
switch (statusType) {
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
return 1; // DEFAULT & AVAILABILITY %
default:
return 2; // DEFAULT
}
default:
CrashUtils.w(this, "Cannot find POI type for at position '%s'!", position);
return 2; // DEFAULT
}
}
private int count = -1;
@Override
public int getCount() {
if (this.count < 0) {
initCount();
}
return this.count;
}
private void initCount() {
this.count = 0;
if (this.showBrowseHeaderSection) {
this.count++;
}
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
if (this.showTypeHeader != TYPE_HEADER_NONE) {
this.count++;
}
this.count += this.poisByType.get(type).size();
}
}
if (this.infiniteLoading) {
this.count++;
}
}
@Override
public int getPosition(POIManager item) {
int position = 0;
if (this.showBrowseHeaderSection) {
position++;
}
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
if (this.showTypeHeader != TYPE_HEADER_NONE) {
position++;
}
int indexOf = this.poisByType.get(type).indexOf(item);
if (indexOf >= 0) {
return position + indexOf;
}
position += this.poisByType.get(type).size();
}
}
return position;
}
@Nullable
@Override
public POIManager getItem(int position) {
int index = 0;
if (this.showBrowseHeaderSection) {
index++;
}
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
if (this.showTypeHeader != TYPE_HEADER_NONE) {
index++;
}
if (position >= index && position < index + this.poisByType.get(type).size()) {
return this.poisByType.get(type).get(position - index);
}
index += this.poisByType.get(type).size();
}
}
return null;
}
@Nullable
public POIManager getItem(String uuid) {
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
for (POIManager poim : this.poisByType.get(type)) {
if (poim.poi.getUUID().equals(uuid)) {
return poim;
}
}
}
}
return null;
}
@Nullable
private Integer getItemTypeHeader(int position) {
int index = 0;
if (this.showBrowseHeaderSection) {
index++;
}
if (this.showTypeHeader != TYPE_HEADER_NONE && this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
if (index == position) {
return type;
}
index++;
index += this.poisByType.get(type).size();
}
}
return null;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @Nullable ViewGroup parent) {
POIManager poim = getItem(position);
if (poim == null) {
if (this.showBrowseHeaderSection && position == 0) {
return getBrowseHeaderSectionView(convertView, parent);
}
if (this.infiniteLoading && position + 1 == getCount()) {
return getInfiniteLoadingView(convertView, parent);
}
if (this.showTypeHeader != TYPE_HEADER_NONE) {
Integer typeId = getItemTypeHeader(position);
if (typeId != null) {
if (FavoriteManager.isFavoriteDataSourceId(typeId)) {
int favoriteFolderId = FavoriteManager.extractFavoriteFolderId(typeId);
if (FavoriteManager.get(getContext()).hasFavoriteFolder(favoriteFolderId)) {
return getFavoriteFolderHeaderView(FavoriteManager.get(getContext()).getFolder(favoriteFolderId), convertView, parent);
}
}
DataSourceType dst = DataSourceType.parseId(typeId);
if (dst != null) {
return getTypeHeaderView(dst, convertView, parent);
}
}
}
CrashUtils.w(this, "getView() > Cannot create view for null poi at position '%s'!", position);
return getInfiniteLoadingView(convertView, parent);
}
switch (poim.poi.getType()) {
case POI.ITEM_VIEW_TYPE_TEXT_MESSAGE:
return getTextMessageView(poim, convertView, parent);
case POI.ITEM_VIEW_TYPE_MODULE:
return getModuleView(poim, convertView, parent);
case POI.ITEM_VIEW_TYPE_ROUTE_TRIP_STOP:
return getRouteTripStopView(poim, convertView, parent);
case POI.ITEM_VIEW_TYPE_BASIC_POI:
return getBasicPOIView(poim, convertView, parent);
default:
CrashUtils.w(this, "getView() > Unknown view type at position %s!", position);
return getBasicPOIView(poim, convertView, parent);
}
}
@NonNull
private View getInfiniteLoadingView(@Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_infinite_loading, parent, false);
InfiniteLoadingViewHolder holder = new InfiniteLoadingViewHolder();
holder.progressBar = convertView.findViewById(R.id.progress_bar);
holder.worldExplored = convertView.findViewById(R.id.worldExploredTv);
convertView.setTag(holder);
}
InfiniteLoadingViewHolder holder = (InfiniteLoadingViewHolder) convertView.getTag();
if (this.infiniteLoadingListener != null) {
if (this.infiniteLoadingListener.isLoadingMore()) {
holder.worldExplored.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.VISIBLE);
convertView.setVisibility(View.VISIBLE);
} else if (this.infiniteLoadingListener.showingDone()) {
holder.progressBar.setVisibility(View.GONE);
holder.worldExplored.setVisibility(View.VISIBLE);
convertView.setVisibility(View.VISIBLE);
} else {
convertView.setVisibility(View.GONE);
}
} else {
convertView.setVisibility(View.GONE);
}
return convertView;
}
private int nbAgencyTypes = -1;
private View getBrowseHeaderSectionView(@Nullable View convertView, @Nullable ViewGroup parent) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
DataSourceProvider dataSourceProvider = DataSourceProvider.get(activity);
int agenciesCount = dataSourceProvider == null ? 0 : dataSourceProvider.getAllAgenciesCount();
if (convertView == null || this.nbAgencyTypes != agenciesCount) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_list_browse_header, parent, false);
}
LinearLayout gridLL = (LinearLayout) convertView.findViewById(R.id.gridLL);
gridLL.removeAllViews();
ArrayList<DataSourceType> allAgencyTypes = dataSourceProvider == null ? null : dataSourceProvider.getAvailableAgencyTypes();
this.nbAgencyTypes = CollectionUtils.getSize(allAgencyTypes);
if (allAgencyTypes == null) {
gridLL.setVisibility(View.GONE);
} else {
int availableButtons = 0;
View gridLine = null;
View btn;
TextView btnTv;
for (final DataSourceType dst : allAgencyTypes) {
if (dst.getId() == DataSourceType.TYPE_MODULE.getId() && availableButtons == 0 && allAgencyTypes.size() > 2) {
continue;
}
if (dst.getId() == DataSourceType.TYPE_PLACE.getId()) {
continue;
}
if (availableButtons == 0) {
gridLine = this.layoutInflater.inflate(R.layout.layout_poi_list_browse_header_line, this.manualLayout, false);
gridLL.addView(gridLine);
availableButtons = 2;
}
btn = gridLine.findViewById(availableButtons == 2 ? R.id.btn1 : R.id.btn2);
btnTv = (TextView) gridLine.findViewById(availableButtons == 2 ? R.id.btn1Tv : R.id.btn2Tv);
btnTv.setText(dst.getAllStringResId());
if (dst.getWhiteIconResId() != -1) {
btnTv.setCompoundDrawablesWithIntrinsicBounds(dst.getWhiteIconResId(), 0, 0, 0);
} else {
btnTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
btn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
onTypeHeaderButtonClick(TypeHeaderButtonsClickListener.BUTTON_ALL, dst);
}
});
btn.setVisibility(View.VISIBLE);
availableButtons
}
if (gridLine != null && availableButtons == 1) {
gridLine.findViewById(R.id.btn2).setVisibility(View.GONE);
}
gridLL.setVisibility(View.VISIBLE);
}
}
return convertView;
}
@NonNull
private View updateCommonViewManual(@NonNull POIManager poim, @NonNull View convertView) {
if (!(convertView.getTag() instanceof CommonViewHolder)) {
return convertView;
}
CommonViewHolder holder = (CommonViewHolder) convertView.getTag();
updateCommonView(holder, poim);
updatePOIStatus(holder.statusViewHolder, poim);
return convertView;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MTOnItemClickListener.onItemClickS(parent, view, position, id, new MTOnItemClickListener() {
@Override
public void onItemClickMT(AdapterView<?> parent, View view, int position, long id) {
showPoiViewerScreen(position);
}
});
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return MTOnItemLongClickListener.onItemLongClickS(parent, view, position, id, new MTOnItemLongClickListener() {
@Override
public boolean onItemLongClickMT(AdapterView<?> parent, View view, int position, long id) {
return showPoiMenu(position);
}
});
}
public interface OnClickHandledListener {
void onLeaving();
}
private WeakReference<OnClickHandledListener> onClickHandledListenerWR;
public void setOnClickHandledListener(OnClickHandledListener onClickHandledListener) {
this.onClickHandledListenerWR = new WeakReference<OnClickHandledListener>(onClickHandledListener);
}
public interface OnPOISelectedListener {
boolean onPOISelected(POIManager poim);
boolean onPOILongSelected(POIManager poim);
}
private WeakReference<OnPOISelectedListener> onPoiSelectedListenerWR;
public void setOnPoiSelectedListener(OnPOISelectedListener onPoiSelectedListener) {
this.onPoiSelectedListenerWR = new WeakReference<OnPOISelectedListener>(onPoiSelectedListener);
}
public boolean showPoiViewerScreen(int position) {
boolean handled = false;
POIManager poim = getItem(position);
if (poim != null) {
OnPOISelectedListener listener = this.onPoiSelectedListenerWR == null ? null : this.onPoiSelectedListenerWR.get();
handled = listener != null && listener.onPOISelected(poim);
if (!handled) {
handled = showPoiViewerScreen(poim);
}
}
return handled;
}
private boolean showPoiMenu(int position) {
boolean handled = false;
POIManager poim = getItem(position);
if (poim != null) {
OnPOISelectedListener listener = this.onPoiSelectedListenerWR == null ? null : this.onPoiSelectedListenerWR.get();
handled = listener != null && listener.onPOILongSelected(poim);
if (!handled) {
handled = showPoiMenu(poim);
}
}
return handled;
}
@Override
public boolean areAllItemsEnabled() {
return false; // to hide divider around disabled items (list view background visible behind hidden divider)
// return true; // to show divider around disabled items
}
@Override
public boolean isEnabled(int position) {
return getItemTypeHeader(position) == null; // is NOT separator
}
public boolean showPoiViewerScreen(POIManager poim) {
if (poim == null) {
return false;
}
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity == null) {
return false;
}
OnClickHandledListener listener = this.onClickHandledListenerWR == null ? null : this.onClickHandledListenerWR.get();
return poim.onActionItemClick(activity, FavoriteManager.get(getContext()).getFavoriteFolders(), this.favoriteUpdateListener, listener);
}
private boolean showPoiMenu(POIManager poim) {
if (poim == null) {
return false;
}
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity == null) {
return false;
}
OnClickHandledListener listener = this.onClickHandledListenerWR == null ? null : this.onClickHandledListenerWR.get();
return poim.onActionItemLongClick(activity, FavoriteManager.get(getContext()).getFavoriteFolders(), this.favoriteUpdateListener, listener);
}
@Override
public void onFavoriteUpdated() {
refreshFavorites();
}
public void setPois(ArrayList<POIManager> pois) {
if (this.poisByType != null) {
this.poisByType.clear();
}
this.poiUUID.clear();
boolean dataSetChanged = append(pois, true);
if (dataSetChanged) {
notifyDataSetChanged();
}
}
private HashSet<String> poiUUID = new HashSet<String>();
public void appendPois(ArrayList<POIManager> pois) {
boolean dataSetChanged = append(pois, false);
if (dataSetChanged) {
notifyDataSetChanged();
}
}
private boolean append(ArrayList<POIManager> pois, boolean dataSetChanged) {
if (pois != null) {
if (this.poisByType == null) {
this.poisByType = new LinkedHashMap<Integer, ArrayList<POIManager>>();
}
for (POIManager poim : pois) {
if (!this.poisByType.containsKey(poim.poi.getDataSourceTypeId())) {
this.poisByType.put(poim.poi.getDataSourceTypeId(), new ArrayList<POIManager>());
}
if (!this.poiUUID.contains(poim.poi.getUUID())) {
this.poisByType.get(poim.poi.getDataSourceTypeId()).add(poim);
this.poiUUID.add(poim.poi.getUUID());
dataSetChanged = true;
}
}
}
if (dataSetChanged) {
this.lastNotifyDataSetChanged = -1; // last notify was with old data
initCount();
initPoisCount();
refreshFavorites();
updateClosestPoi();
}
return dataSetChanged;
}
private void resetCounts() {
this.count = -1;
this.poisCount = -1;
}
public boolean isInitialized() {
return this.poisByType != null;
}
private int poisCount = -1;
public int getPoisCount() {
if (this.poisCount < 0) {
initPoisCount();
}
return this.poisCount;
}
private void initPoisCount() {
this.poisCount = 0;
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
this.poisCount += this.poisByType.get(type).size();
}
}
}
public boolean hasPois() {
return getPoisCount() > 0;
}
private void updateClosestPoi() {
if (getPoisCount() == 0) {
this.closestPoiUuids = null;
return;
}
this.closestPoiUuids = new HashSet<String>();
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
ArrayList<POIManager> orderedPoims = new ArrayList<POIManager>(this.poisByType.get(type));
if (orderedPoims.size() > 0) {
CollectionUtils.sort(orderedPoims, LocationUtils.POI_DISTANCE_COMPARATOR);
POIManager theClosestOne = orderedPoims.get(0);
float theClosestDistance = theClosestOne.getDistance();
if (theClosestDistance > 0) {
for (POIManager poim : orderedPoims) {
if (poim.getDistance() <= theClosestDistance) {
this.closestPoiUuids.add(poim.poi.getUUID());
continue;
}
break;
}
}
}
}
}
}
public boolean hasClosestPOI() {
return this.closestPoiUuids != null && this.closestPoiUuids.size() > 0;
}
public boolean isClosestPOI(int position) {
if (this.closestPoiUuids == null) {
return false;
}
POIManager poim = getItem(position);
return poim != null && this.closestPoiUuids.contains(poim.poi.getUUID());
}
public POIManager getClosestPOI() {
if (this.closestPoiUuids == null || this.closestPoiUuids.size() == 0) {
return null;
}
String closestPOIUUID = this.closestPoiUuids.iterator().next();
return getItem(closestPOIUUID);
}
private MTAsyncTask<Location, Void, Void> updateDistanceWithStringTask;
private void updateDistances(Location currentLocation) {
TaskUtils.cancelQuietly(this.updateDistanceWithStringTask, true);
if (currentLocation != null && getPoisCount() > 0) {
this.updateDistanceWithStringTask = new MTAsyncTask<Location, Void, Void>() {
@Override
public String getLogTag() {
return POIArrayAdapter.class.getSimpleName() + ">updateDistanceWithStringTask";
}
@Override
protected Void doInBackgroundMT(Location... params) {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
try {
if (POIArrayAdapter.this.poisByType != null) {
Iterator<ArrayList<POIManager>> it = POIArrayAdapter.this.poisByType.values().iterator();
while (it.hasNext()) {
if (isCancelled()) {
break;
}
LocationUtils.updateDistanceWithString(POIArrayAdapter.this.getContext(), it.next(), params[0], this);
}
}
} catch (Exception e) {
MTLog.w(POIArrayAdapter.this, e, "Error while update POIs distance strings!");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (isCancelled()) {
return;
}
updateClosestPoi();
notifyDataSetChanged(true);
}
};
TaskUtils.execute(this.updateDistanceWithStringTask, currentLocation);
}
}
@Deprecated
public void updateDistancesNowSync(Location currentLocation) {
if (currentLocation != null) {
if (this.poisByType != null) {
Iterator<ArrayList<POIManager>> it = this.poisByType.values().iterator();
while (it.hasNext()) {
ArrayList<POIManager> pois = it.next();
LocationUtils.updateDistanceWithString(getContext(), pois, currentLocation, null);
}
}
updateClosestPoi();
}
setLocation(currentLocation);
}
public void updateDistanceNowAsync(Location currentLocation) {
this.location = null; // clear current location to force refresh
setLocation(currentLocation);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
setScrollState(scrollState);
}
private void setScrollState(int scrollState) {
this.scrollState = scrollState;
}
@Override
public void onStatusLoaded(POIStatus status) {
if (this.showStatus) {
CommonStatusViewHolder statusViewHolder = this.poiStatusViewHoldersWR.get(status.getTargetUUID());
if (statusViewHolder != null && status.getTargetUUID().equals(statusViewHolder.uuid)) {
updatePOIStatus(statusViewHolder, status);
} else {
notifyDataSetChanged(false);
}
}
}
@Override
public void onServiceUpdatesLoaded(String targetUUID, ArrayList<ServiceUpdate> serviceUpdates) {
if (this.showServiceUpdate) {
CommonStatusViewHolder statusViewHolder = this.poiStatusViewHoldersWR.get(targetUUID);
if (statusViewHolder != null && targetUUID.equals(statusViewHolder.uuid)) {
updateServiceUpdate(statusViewHolder, ServiceUpdate.isSeverityWarning(serviceUpdates));
} else {
notifyDataSetChanged(false);
}
}
}
public void notifyDataSetChanged(boolean force) {
notifyDataSetChanged(force, Constants.ADAPTER_NOTIFY_THRESHOLD_IN_MS);
}
private Handler handler = new Handler();
private Runnable notifyDataSetChangedLater = new Runnable() {
@Override
public void run() {
notifyDataSetChanged(true); // still really need to show new data
}
};
public void notifyDataSetChanged(boolean force, long minAdapterThresholdInMs) {
long now = TimeUtils.currentTimeMillis();
long adapterThreshold = Math.max(minAdapterThresholdInMs, Constants.ADAPTER_NOTIFY_THRESHOLD_IN_MS);
if (this.scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && (force || (now - this.lastNotifyDataSetChanged) > adapterThreshold)) {
notifyDataSetChanged();
notifyDataSetChangedManual();
this.lastNotifyDataSetChanged = now;
this.handler.removeCallbacks(this.notifyDataSetChangedLater);
} else {
if (force) {
this.handler.postDelayed(this.notifyDataSetChangedLater, adapterThreshold);
}
}
}
private void notifyDataSetChangedManual() {
if (this.manualLayout != null && hasPois()) {
int position = 0;
for (int i = 0; i < this.manualLayout.getChildCount(); i++) {
View view = this.manualLayout.getChildAt(i);
if (view instanceof FrameLayout) {
view = ((FrameLayout) view).getChildAt(0);
}
Object tag = view == null ? null : view.getTag();
if (tag != null && tag instanceof CommonViewHolder) {
POIManager poim = getItem(position);
if (poim != null) {
updateCommonViewManual(poim, view);
}
position++;
}
}
}
}
public void setListView(AbsListView listView) {
listView.setOnItemClickListener(this);
listView.setOnItemLongClickListener(this);
listView.setOnScrollListener(this);
listView.setAdapter(this);
}
public void initManual() {
if (this.manualLayout != null && hasPois()) {
this.manualLayout.removeAllViews(); // clear the previous list
for (int i = 0; i < getPoisCount(); i++) {
if (this.manualLayout.getChildCount() > 0) {
this.manualLayout.addView(this.layoutInflater.inflate(R.layout.list_view_divider, this.manualLayout, false));
}
View view = getView(i, null, this.manualLayout);
FrameLayout frameLayout = new FrameLayout(getContext());
frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
frameLayout.addView(view);
View selectorView = new View(getContext());
SupportFactory.get().setBackground(selectorView, ThemeUtils.obtainStyledDrawable(getContext(), R.attr.selectableItemBackground));
selectorView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
frameLayout.addView(selectorView);
final int position = i;
frameLayout.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
showPoiViewerScreen(position);
}
});
frameLayout.setOnLongClickListener(new MTOnLongClickListener() {
@Override
public boolean onLongClickkMT(View view) {
return showPoiMenu(position);
}
});
this.manualLayout.addView(frameLayout);
}
}
}
public void scrollManualScrollViewTo(int x, int y) {
if (this.manualScrollView != null) {
this.manualScrollView.scrollTo(x, y);
}
}
public void setManualScrollView(ScrollView scrollView) {
this.manualScrollView = scrollView;
if (scrollView == null) {
return;
}
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL:
case MotionEvent.ACTION_MOVE:
setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_FLING);
break;
case MotionEvent.ACTION_DOWN:
setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// scroll view can still by flying
setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
break;
default:
MTLog.v(POIArrayAdapter.this, "Unexpected event %s", event);
}
return false;
}
});
}
public void setLocation(Location newLocation) {
if (newLocation != null) {
if (this.location == null || LocationUtils.isMoreRelevant(getLogTag(), this.location, newLocation)) {
this.location = newLocation;
this.locationDeclination = SensorUtils.getLocationDeclination(this.location);
if (!this.compassUpdatesEnabled) {
SensorUtils.registerCompassListener(getContext(), this);
this.compassUpdatesEnabled = true;
}
updateDistances(this.location);
}
}
}
public void onPause() {
if (this.activityWR != null) {
this.activityWR.clear();
this.activityWR = null;
}
if (this.compassUpdatesEnabled) {
SensorUtils.unregisterSensorListener(getContext(), this);
this.compassUpdatesEnabled = false;
}
this.handler.removeCallbacks(this.notifyDataSetChangedLater);
TaskUtils.cancelQuietly(this.refreshFavoritesTask, true);
disableTimeChangedReceiver();
}
@Override
public String toString() {
return new StringBuilder().append(POIArrayAdapter.class.getSimpleName())
.append(getLogTag())
.toString();
}
public void onResume(Activity activity, Location userLocation) {
setActivity(activity);
this.location = null; // clear current location to force refresh
setLocation(userLocation);
refreshFavorites();
}
public void setActivity(Activity activity) {
this.activityWR = new WeakReference<Activity>(activity);
}
@Override
public void clear() {
if (this.poisByType != null) {
this.poisByType.clear();
this.poisByType = null; // not initialized
}
resetCounts();
if (this.poiUUID != null) {
this.poiUUID.clear();
}
if (this.closestPoiUuids != null) {
this.closestPoiUuids.clear();
this.closestPoiUuids = null;
}
disableTimeChangedReceiver();
if (this.compassImgsWR != null) {
this.compassImgsWR.clear();
}
this.lastCompassChanged = -1;
this.lastCompassInDegree = -1;
this.accelerometerValues = new float[3];
this.magneticFieldValues = new float[3];
this.lastNotifyDataSetChanged = -1L;
this.handler.removeCallbacks(this.notifyDataSetChangedLater);
this.poiStatusViewHoldersWR.clear();
TaskUtils.cancelQuietly(this.refreshFavoritesTask, true);
TaskUtils.cancelQuietly(this.updateDistanceWithStringTask, true);
this.location = null;
this.locationDeclination = 0f;
super.clear();
}
public void onDestroy() {
disableTimeChangedReceiver();
if (this.poisByType != null) {
this.poisByType.clear();
this.poisByType = null;
}
resetCounts();
if (this.poiUUID != null) {
this.poiUUID.clear();
}
if (this.compassImgsWR != null) {
this.compassImgsWR.clear();
}
this.poiStatusViewHoldersWR.clear();
if (this.onClickHandledListenerWR != null) {
this.onClickHandledListenerWR.clear();
}
if (this.onPoiSelectedListenerWR != null) {
this.onPoiSelectedListenerWR.clear();
}
}
@Override
public void updateCompass(float orientation, boolean force) {
if (getPoisCount() == 0) {
return;
}
long now = TimeUtils.currentTimeMillis();
int roundedOrientation = SensorUtils.convertToPosivite360Degree((int) orientation);
SensorUtils.updateCompass(force, this.location, roundedOrientation, now, this.scrollState, this.lastCompassChanged, this.lastCompassInDegree,
Constants.ADAPTER_NOTIFY_THRESHOLD_IN_MS, this);
}
@Override
public void onSensorTaskCompleted(boolean result, int roundedOrientation, long now) {
if (!result) {
return;
}
this.lastCompassInDegree = roundedOrientation;
this.lastCompassChanged = now;
if (!this.compassUpdatesEnabled || this.location == null || this.lastCompassInDegree < 0) {
return;
}
if (this.compassImgsWR == null) {
return;
}
for (WeakHashMap.Entry<MTCompassView, View> compassAndDistance : this.compassImgsWR.entrySet()) {
MTCompassView compassView = compassAndDistance.getKey();
if (compassView != null && compassView.isHeadingSet()) {
compassView.generateAndSetHeading(this.location, this.lastCompassInDegree, this.locationDeclination);
}
}
}
@Override
public void onSensorChanged(SensorEvent se) {
SensorUtils.checkForCompass(getContext(), se, this.accelerometerValues, this.magneticFieldValues, this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// DO NOTHING
}
private int getTypeHeaderLayoutResId() {
switch (this.showTypeHeader) {
case TYPE_HEADER_BASIC:
return R.layout.layout_poi_list_header;
case TYPE_HEADER_MORE:
return R.layout.layout_poi_list_header_with_more;
case TYPE_HEADER_ALL_NEARBY:
return R.layout.layout_poi_list_header_with_all_nearby;
default:
MTLog.w(this, "Unexpected header type '%s'!", this.showTypeHeader);
return R.layout.layout_poi_list_header;
}
}
private WeakReference<TypeHeaderButtonsClickListener> typeHeaderButtonsClickListenerWR;
public void setOnTypeHeaderButtonsClickListener(TypeHeaderButtonsClickListener listener) {
this.typeHeaderButtonsClickListenerWR = new WeakReference<TypeHeaderButtonsClickListener>(listener);
}
private void onTypeHeaderButtonClick(int buttonId, DataSourceType type) {
TypeHeaderButtonsClickListener listener = this.typeHeaderButtonsClickListenerWR == null ? null : this.typeHeaderButtonsClickListenerWR.get();
if (listener != null && listener.onTypeHeaderButtonClick(buttonId, type)) {
return;
}
switch (buttonId) {
case TypeHeaderButtonsClickListener.BUTTON_ALL:
if (type != null) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
leaving();
((MainActivity) activity).addFragmentToStack(AgencyTypeFragment.newInstance(type.getId(), type));
}
}
break;
case TypeHeaderButtonsClickListener.BUTTON_NEARBY:
if (type != null) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
leaving();
((MainActivity) activity).addFragmentToStack(NearbyFragment.newNearbyInstance(null, type.getId()));
}
}
break;
case TypeHeaderButtonsClickListener.BUTTON_MORE:
if (type != null) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
leaving();
((MainActivity) activity).addFragmentToStack(AgencyTypeFragment.newInstance(type.getId(), type));
}
}
break;
default:
MTLog.w(this, "Unexpected type header button %s'' click", type);
}
}
private void leaving() {
OnClickHandledListener onClickHandledListener = this.onClickHandledListenerWR == null ? null : this.onClickHandledListenerWR.get();
if (onClickHandledListener != null) {
onClickHandledListener.onLeaving();
}
}
@NonNull
private View getTypeHeaderView(final DataSourceType type, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
int layoutRes = getTypeHeaderLayoutResId();
convertView = this.layoutInflater.inflate(layoutRes, parent, false);
TypeHeaderViewHolder holder = new TypeHeaderViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.name);
holder.nearbyBtn = convertView.findViewById(R.id.nearbyBtn);
holder.allBtn = convertView.findViewById(R.id.allBtn);
holder.allBtnTv = (TextView) convertView.findViewById(R.id.allBtnTv);
holder.moreBtn = convertView.findViewById(R.id.moreBtn);
convertView.setTag(holder);
}
TypeHeaderViewHolder holder = (TypeHeaderViewHolder) convertView.getTag();
holder.nameTv.setText(this.showTypeHeaderNearby ? type.getNearbyNameResId() : type.getPoiShortNameResId());
if (type.getGrey600IconResId() != -1) {
holder.nameTv.setCompoundDrawablesWithIntrinsicBounds(type.getGrey600IconResId(), 0, 0, 0);
}
if (holder.allBtn != null) {
holder.allBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
onTypeHeaderButtonClick(TypeHeaderButtonsClickListener.BUTTON_ALL, type);
}
});
}
if (holder.nearbyBtn != null) {
holder.nearbyBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
onTypeHeaderButtonClick(TypeHeaderButtonsClickListener.BUTTON_NEARBY, type);
}
});
}
if (holder.moreBtn != null) {
holder.moreBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
onTypeHeaderButtonClick(TypeHeaderButtonsClickListener.BUTTON_MORE, type);
}
});
}
return convertView;
}
private View getFavoriteFolderHeaderView(final Favorite.Folder favoriteFolder, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_list_header_with_delete, parent, false);
FavoriteFolderHeaderViewHolder holder = new FavoriteFolderHeaderViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.name);
holder.renameBtn = convertView.findViewById(R.id.renameBtn);
holder.deleteBtn = convertView.findViewById(R.id.deleteBtn);
convertView.setTag(holder);
}
FavoriteFolderHeaderViewHolder holder = (FavoriteFolderHeaderViewHolder) convertView.getTag();
holder.nameTv.setText(favoriteFolder == null ? null : favoriteFolder.getName());
if (holder.renameBtn != null) {
holder.renameBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
FavoriteManager.showUpdateFolderDialog(getContext(), POIArrayAdapter.this.layoutInflater, favoriteFolder,
POIArrayAdapter.this.favoriteUpdateListener);
}
});
}
if (holder.deleteBtn != null) {
holder.deleteBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
FavoriteManager.showDeleteFolderDialog(POIArrayAdapter.this.getContext(), favoriteFolder, POIArrayAdapter.this.favoriteUpdateListener);
}
});
}
return convertView;
}
private WeakHashMap<String, CommonStatusViewHolder> poiStatusViewHoldersWR = new WeakHashMap<String, CommonStatusViewHolder>();
@NonNull
private View getBasicPOIView(@NonNull POIManager poim, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(getBasicPOILayout(poim.getStatusType()), parent, false);
BasicPOIViewHolder holder = new BasicPOIViewHolder();
initCommonViewHolder(holder, convertView, poim.poi.getUUID());
holder.statusViewHolder = initPOIStatusViewHolder(poim.getStatusType(), convertView);
convertView.setTag(holder);
}
updateBasicPOIView(poim, convertView);
return convertView;
}
private CommonStatusViewHolder initPOIStatusViewHolder(int status, View convertView) {
switch (status) {
case POI.ITEM_STATUS_TYPE_NONE:
return null;
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
return initAvailabilityPercentViewHolder(convertView);
case POI.ITEM_STATUS_TYPE_SCHEDULE:
return initScheduleViewHolder(convertView);
case POI.ITEM_STATUS_TYPE_APP:
return initAppStatusViewHolder(convertView);
default:
MTLog.w(this, "Unexpected status '%s' (no view holder)!", status);
return null;
}
}
private CommonStatusViewHolder initScheduleViewHolder(View convertView) {
ScheduleStatusViewHolder scheduleStatusViewHolder = new ScheduleStatusViewHolder();
initCommonStatusViewHolderHolder(scheduleStatusViewHolder, convertView);
scheduleStatusViewHolder.dataNextLine1Tv = (TextView) convertView.findViewById(R.id.data_next_line_1);
scheduleStatusViewHolder.dataNextLine2Tv = (TextView) convertView.findViewById(R.id.data_next_line_2);
return scheduleStatusViewHolder;
}
private CommonStatusViewHolder initAppStatusViewHolder(View convertView) {
AppStatusViewHolder appStatusViewHolder = new AppStatusViewHolder();
initCommonStatusViewHolderHolder(appStatusViewHolder, convertView);
appStatusViewHolder.textTv = (TextView) convertView.findViewById(R.id.textTv);
return appStatusViewHolder;
}
private CommonStatusViewHolder initAvailabilityPercentViewHolder(View convertView) {
AvailabilityPercentStatusViewHolder availabilityPercentStatusViewHolder = new AvailabilityPercentStatusViewHolder();
initCommonStatusViewHolderHolder(availabilityPercentStatusViewHolder, convertView);
availabilityPercentStatusViewHolder.textTv = (TextView) convertView.findViewById(R.id.textTv);
availabilityPercentStatusViewHolder.piePercentV = (MTPieChartPercentView) convertView.findViewById(R.id.pie);
return availabilityPercentStatusViewHolder;
}
@LayoutRes
private int getBasicPOILayout(int status) {
int layoutRes = R.layout.layout_poi_basic;
switch (status) {
case POI.ITEM_STATUS_TYPE_NONE:
break;
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
layoutRes = R.layout.layout_poi_basic_with_availability_percent;
break;
default:
MTLog.w(this, "Unexpected status '%s' (basic view w/o status)!", status);
break;
}
return layoutRes;
}
private WeakHashMap<MTCompassView, View> compassImgsWR = new WeakHashMap<MTCompassView, View>();
private void initCommonViewHolder(CommonViewHolder holder, View convertView, String poiUUID) {
holder.view = convertView;
holder.nameTv = (TextView) convertView.findViewById(R.id.name);
holder.favImg = (ImageView) convertView.findViewById(R.id.fav);
holder.locationTv = (TextView) convertView.findViewById(R.id.location);
holder.distanceTv = (TextView) convertView.findViewById(R.id.distance);
holder.compassV = (MTCompassView) convertView.findViewById(R.id.compass);
}
private static void initCommonStatusViewHolderHolder(CommonStatusViewHolder holder, View convertView) {
holder.statusV = convertView.findViewById(R.id.status);
holder.warningImg = (ImageView) convertView.findViewById(R.id.service_update_warning);
}
@NonNull
private View updateBasicPOIView(@NonNull POIManager poim, @NonNull View convertView) {
BasicPOIViewHolder holder = (BasicPOIViewHolder) convertView.getTag();
updateCommonView(holder, poim);
updatePOIStatus(holder.statusViewHolder, poim);
return convertView;
}
private void updateAppStatus(CommonStatusViewHolder statusViewHolder, POIManager poim) {
if (this.showStatus && poim != null && statusViewHolder instanceof AppStatusViewHolder) {
poim.setStatusLoaderListener(this);
updateAppStatus(statusViewHolder, poim.getStatus(getContext()));
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
if (poim != null) {
poim.setServiceUpdateLoaderListener(this);
updateServiceUpdate(statusViewHolder, poim.isServiceUpdateWarning(getContext()));
}
}
private void updateAppStatus(CommonStatusViewHolder statusViewHolder, POIStatus status) {
AppStatusViewHolder appStatusViewHolder = (AppStatusViewHolder) statusViewHolder;
if (status != null && status instanceof AppStatus) {
AppStatus appStatus = (AppStatus) status;
appStatusViewHolder.textTv.setText(appStatus.getStatusMsg(getContext()));
appStatusViewHolder.textTv.setVisibility(View.VISIBLE);
statusViewHolder.statusV.setVisibility(View.VISIBLE);
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
}
private void updateServiceUpdate(CommonStatusViewHolder statusViewHolder, Boolean isServiceUpdateWarning) {
if (statusViewHolder.warningImg == null) {
return;
}
if (this.showServiceUpdate && isServiceUpdateWarning != null) {
statusViewHolder.warningImg.setVisibility(isServiceUpdateWarning ? View.VISIBLE : View.GONE);
} else {
statusViewHolder.warningImg.setVisibility(View.GONE);
}
}
private void updateAvailabilityPercent(CommonStatusViewHolder statusViewHolder, POIManager poim) {
if (this.showStatus && poim != null && statusViewHolder instanceof AvailabilityPercentStatusViewHolder) {
poim.setStatusLoaderListener(this);
updateAvailabilityPercent(statusViewHolder, poim.getStatus(getContext()));
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
if (poim != null) {
poim.setServiceUpdateLoaderListener(this);
updateServiceUpdate(statusViewHolder, poim.isServiceUpdateWarning(getContext()));
}
}
private void updateAvailabilityPercent(CommonStatusViewHolder statusViewHolder, POIStatus status) {
AvailabilityPercentStatusViewHolder availabilityPercentStatusViewHolder = (AvailabilityPercentStatusViewHolder) statusViewHolder;
if (status != null && status instanceof AvailabilityPercent) {
AvailabilityPercent availabilityPercent = (AvailabilityPercent) status;
if (!availabilityPercent.isStatusOK()) {
availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.GONE);
availabilityPercentStatusViewHolder.textTv.setText(availabilityPercent.getStatusMsg(getContext()));
availabilityPercentStatusViewHolder.textTv.setVisibility(View.VISIBLE);
} else if (availabilityPercent.isShowingLowerValue()) {
availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.GONE);
availabilityPercentStatusViewHolder.textTv.setText(availabilityPercent.getLowerValueText(getContext()));
availabilityPercentStatusViewHolder.textTv.setVisibility(View.VISIBLE);
} else {
availabilityPercentStatusViewHolder.textTv.setVisibility(View.GONE);
availabilityPercentStatusViewHolder.piePercentV.setValueColors(
availabilityPercent.getValue1Color(),
availabilityPercent.getValue1ColorBg(),
availabilityPercent.getValue2Color(),
availabilityPercent.getValue2ColorBg()
);
availabilityPercentStatusViewHolder.piePercentV.setValues(availabilityPercent.getValue1(), availabilityPercent.getValue2());
availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.VISIBLE);
}
statusViewHolder.statusV.setVisibility(View.VISIBLE);
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
}
@LayoutRes
private int getRTSLayout(int status) {
int layoutRes = R.layout.layout_poi_rts;
switch (status) {
case POI.ITEM_STATUS_TYPE_NONE:
break;
case POI.ITEM_STATUS_TYPE_SCHEDULE:
if (this.showExtra) {
layoutRes = R.layout.layout_poi_rts_with_schedule;
} else {
layoutRes = R.layout.layout_poi_basic_with_schedule;
}
break;
default:
MTLog.w(this, "Unexpected status '%s' (rts view w/o status)!", status);
break;
}
return layoutRes;
}
@NonNull
private View getTextMessageView(@NonNull POIManager poim, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_basic, parent, false);
TextViewViewHolder holder = new TextViewViewHolder();
initCommonViewHolder(holder, convertView, poim.poi.getUUID());
convertView.setTag(holder);
}
updateTextMessageView(poim, convertView);
return convertView;
}
@NonNull
private View updateTextMessageView(@NonNull POIManager poim, @NonNull View convertView) {
TextViewViewHolder holder = (TextViewViewHolder) convertView.getTag();
updateCommonView(holder, poim);
return convertView;
}
@NonNull
private View getModuleView(@NonNull POIManager poim, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(getModuleLayout(poim.getStatusType()), parent, false);
ModuleViewHolder holder = new ModuleViewHolder();
initCommonViewHolder(holder, convertView, poim.poi.getUUID());
initModuleExtra(convertView, holder);
holder.statusViewHolder = initPOIStatusViewHolder(poim.getStatusType(), convertView);
convertView.setTag(holder);
}
updateModuleView(poim, convertView);
return convertView;
}
private void initModuleExtra(View convertView, ModuleViewHolder holder) {
holder.moduleExtraTypeImg = (ImageView) convertView.findViewById(R.id.extra);
}
@NonNull
private View updateModuleView(@NonNull POIManager poim, @NonNull View convertView) {
ModuleViewHolder holder = (ModuleViewHolder) convertView.getTag();
updateCommonView(holder, poim);
updateModuleExtra(poim, holder);
updatePOIStatus(holder.statusViewHolder, poim);
return convertView;
}
private void updateModuleExtra(POIManager poim, ModuleViewHolder holder) {
if (this.showExtra && poim.poi != null && poim.poi instanceof Module) {
Module module = (Module) poim.poi;
holder.moduleExtraTypeImg.setBackgroundColor(poim.getColor(getContext()));
DataSourceType moduleType = DataSourceType.parseId(module.getTargetTypeId());
if (moduleType != null) {
holder.moduleExtraTypeImg.setImageResource(moduleType.getWhiteIconResId());
} else {
holder.moduleExtraTypeImg.setImageResource(0);
}
holder.moduleExtraTypeImg.setVisibility(View.VISIBLE);
} else {
holder.moduleExtraTypeImg.setVisibility(View.GONE);
}
}
@LayoutRes
private int getModuleLayout(int status) {
int layoutRes = R.layout.layout_poi_module;
switch (status) {
case POI.ITEM_STATUS_TYPE_NONE:
break;
case POI.ITEM_STATUS_TYPE_APP:
layoutRes = R.layout.layout_poi_module_with_app_status;
break;
default:
MTLog.w(this, "Unexpected status '%s' (module view w/o status)!", status);
break;
}
return layoutRes;
}
@NonNull
private View getRouteTripStopView(@NonNull POIManager poim, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(getRTSLayout(poim.getStatusType()), parent, false);
RouteTripStopViewHolder holder = new RouteTripStopViewHolder();
initCommonViewHolder(holder, convertView, poim.poi.getUUID());
initRTSExtra(convertView, holder);
holder.statusViewHolder = initPOIStatusViewHolder(poim.getStatusType(), convertView);
convertView.setTag(holder);
}
updateRouteTripStopView(poim, convertView);
return convertView;
}
private void initRTSExtra(@NonNull View convertView, @NonNull RouteTripStopViewHolder holder) {
holder.rtsExtraV = convertView.findViewById(R.id.extra);
holder.routeFL = convertView.findViewById(R.id.route);
holder.routeShortNameTv = (TextView) convertView.findViewById(R.id.route_short_name);
holder.routeTypeImg = (MTJPathsView) convertView.findViewById(R.id.route_type_img);
holder.tripHeadingTv = (TextView) convertView.findViewById(R.id.trip_heading);
holder.tripHeadingBg = convertView.findViewById(R.id.trip_heading_bg);
}
@Nullable
private View updateRouteTripStopView(@NonNull POIManager poim, @NonNull View convertView) {
if (!(convertView.getTag() instanceof RouteTripStopViewHolder)) {
CrashUtils.w(this, "updateRouteTripStopView() > unexpected holder class '%s'! (%s)", convertView.getTag(), getLogTag());
return convertView;
}
RouteTripStopViewHolder holder = (RouteTripStopViewHolder) convertView.getTag();
updateCommonView(holder, poim);
updateRTSExtra(poim, holder);
updatePOIStatus(holder.statusViewHolder, poim);
return convertView;
}
private boolean showExtra = true;
public void setShowExtra(boolean showExtra) {
this.showExtra = showExtra;
}
private void updateRTSExtra(POIManager poim, RouteTripStopViewHolder holder) {
if (poim.poi instanceof RouteTripStop) {
RouteTripStop rts = (RouteTripStop) poim.poi;
if (!this.showExtra || rts.getRoute() == null) {
if (holder.rtsExtraV != null) {
holder.rtsExtraV.setVisibility(View.GONE);
}
if (holder.routeFL != null) {
holder.routeFL.setVisibility(View.GONE);
}
if (holder.tripHeadingBg != null) {
holder.tripHeadingBg.setVisibility(View.GONE);
}
} else {
final String authority = rts.getAuthority();
final Route route = rts.getRoute();
if (TextUtils.isEmpty(route.getShortName())) {
holder.routeShortNameTv.setVisibility(View.INVISIBLE);
if (holder.routeTypeImg.hasPaths() && poim.poi.getAuthority().equals(holder.routeTypeImg.getTag())) {
holder.routeTypeImg.setVisibility(View.VISIBLE);
} else {
AgencyProperties agency = DataSourceProvider.get(getContext()).getAgency(getContext(), poim.poi.getAuthority());
JPaths rtsRouteLogo = agency == null ? null : agency.getLogo(getContext());
if (rtsRouteLogo != null) {
holder.routeTypeImg.setJSON(rtsRouteLogo);
holder.routeTypeImg.setTag(poim.poi.getAuthority());
holder.routeTypeImg.setVisibility(View.VISIBLE);
} else {
holder.routeTypeImg.setVisibility(View.GONE);
}
}
} else {
holder.routeTypeImg.setVisibility(View.GONE);
holder.routeShortNameTv.setText(Route.setShortNameSize(route.getShortName()));
holder.routeShortNameTv.setVisibility(View.VISIBLE);
}
holder.routeFL.setVisibility(View.VISIBLE);
holder.rtsExtraV.setVisibility(View.VISIBLE);
final Long tripId;
if (rts.getTrip() == null) {
holder.tripHeadingBg.setVisibility(View.GONE);
tripId = null;
} else {
tripId = rts.getTrip().getId();
holder.tripHeadingTv.setText(rts.getTrip().getHeading(getContext()).toUpperCase(Locale.getDefault()));
holder.tripHeadingBg.setVisibility(View.VISIBLE);
}
holder.rtsExtraV.setBackgroundColor(poim.getColor(getContext()));
final Integer stopId = rts.getStop() == null ? null : rts.getStop().getId();
holder.rtsExtraV.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
Activity activity = POIArrayAdapter.this.activityWR == null ? null : POIArrayAdapter.this.activityWR.get();
if (activity == null || !(activity instanceof MainActivity)) {
MTLog.w(POIArrayAdapter.this, "No activity available to open RTS fragment!");
return;
}
leaving();
((MainActivity) activity).addFragmentToStack(RTSRouteFragment.newInstance(authority, route.getId(), tripId, stopId, route));
}
});
}
}
}
private void updatePOIStatus(CommonStatusViewHolder statusViewHolder, POIStatus status) {
if (!this.showStatus || status == null || statusViewHolder == null) {
if (statusViewHolder != null) {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
return;
}
switch (status.getType()) {
case POI.ITEM_STATUS_TYPE_NONE:
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
break;
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
updateAvailabilityPercent(statusViewHolder, status);
break;
case POI.ITEM_STATUS_TYPE_SCHEDULE:
updateRTSSchedule(statusViewHolder, status);
break;
case POI.ITEM_STATUS_TYPE_APP:
updateAppStatus(statusViewHolder, status);
break;
default:
MTLog.w(this, "Unexpected status type '%s'!", status.getType());
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
}
private void updatePOIStatus(CommonStatusViewHolder statusViewHolder, POIManager poim) {
if (!this.showStatus || poim == null || statusViewHolder == null) {
if (statusViewHolder != null) {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
return;
}
switch (poim.getStatusType()) {
case POI.ITEM_STATUS_TYPE_NONE:
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
break;
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
updateAvailabilityPercent(statusViewHolder, poim);
break;
case POI.ITEM_STATUS_TYPE_SCHEDULE:
updateRTSSchedule(statusViewHolder, poim);
break;
case POI.ITEM_STATUS_TYPE_APP:
updateAppStatus(statusViewHolder, poim);
break;
default:
MTLog.w(this, "Unexpected status type '%s'!", poim.getStatusType());
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
}
private void updateRTSSchedule(CommonStatusViewHolder statusViewHolder, POIManager poim) {
if (this.showStatus && poim != null && statusViewHolder instanceof ScheduleStatusViewHolder) {
poim.setStatusLoaderListener(this);
updateRTSSchedule(statusViewHolder, poim.getStatus(getContext()));
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
if (poim != null) {
poim.setServiceUpdateLoaderListener(this);
updateServiceUpdate(statusViewHolder, poim.isServiceUpdateWarning(getContext()));
}
}
private void updateRTSSchedule(CommonStatusViewHolder statusViewHolder, POIStatus status) {
CharSequence line1CS = null;
CharSequence line2CS = null;
if (status != null && status instanceof Schedule) {
Schedule schedule = (Schedule) status;
ArrayList<Pair<CharSequence, CharSequence>> lines = schedule.getStatus(getContext(), getNowToTheMinute(), TimeUnit.MINUTES.toMillis(30), null, 10,
null);
if (lines != null && lines.size() >= 1) {
line1CS = lines.get(0).first;
line2CS = lines.get(0).second;
}
}
ScheduleStatusViewHolder scheduleStatusViewHolder = (ScheduleStatusViewHolder) statusViewHolder;
scheduleStatusViewHolder.dataNextLine1Tv.setText(line1CS);
scheduleStatusViewHolder.dataNextLine2Tv.setText(line2CS);
scheduleStatusViewHolder.dataNextLine2Tv.setVisibility(line2CS != null && line2CS.length() > 0 ? View.VISIBLE : View.GONE);
statusViewHolder.statusV.setVisibility(line1CS != null && line1CS.length() > 0 ? View.VISIBLE : View.INVISIBLE);
}
private long getNowToTheMinute() {
if (this.nowToTheMinute < 0) {
resetNowToTheMinute();
enableTimeChangedReceiver();
}
return this.nowToTheMinute;
}
private void resetNowToTheMinute() {
this.nowToTheMinute = TimeUtils.currentTimeToTheMinuteMillis();
notifyDataSetChanged(false);
}
@Override
public void onTimeChanged() {
resetNowToTheMinute();
}
private final BroadcastReceiver timeChangedReceiver = new TimeUtils.TimeChangedReceiver(this);
private void enableTimeChangedReceiver() {
if (!this.timeChangedReceiverEnabled) {
getContext().registerReceiver(timeChangedReceiver, TimeUtils.TIME_CHANGED_INTENT_FILTER);
this.timeChangedReceiverEnabled = true;
}
}
private void disableTimeChangedReceiver() {
if (this.timeChangedReceiverEnabled) {
getContext().unregisterReceiver(this.timeChangedReceiver);
this.timeChangedReceiverEnabled = false;
this.nowToTheMinute = -1L;
}
}
private void updateCommonView(CommonViewHolder holder, POIManager poim) {
if (poim == null || poim.poi == null || holder == null) {
return;
}
final POI poi = poim.poi;
holder.uuid = poi.getUUID();
if (holder.statusViewHolder != null) {
holder.statusViewHolder.uuid = holder.uuid;
}
if (holder.uuid != null) {
this.poiStatusViewHoldersWR.put(holder.uuid, holder.statusViewHolder);
}
if (holder.compassV != null) {
holder.compassV.setLatLng(poim.getLat(), poim.getLng());
this.compassImgsWR.put(holder.compassV, holder.distanceTv);
}
holder.nameTv.setText(poi.getName());
if (holder.distanceTv != null) {
if (!TextUtils.isEmpty(poim.getDistanceString())) {
if (!poim.getDistanceString().equals(holder.distanceTv.getText())) {
holder.distanceTv.setText(poim.getDistanceString());
}
holder.distanceTv.setVisibility(View.VISIBLE);
} else {
holder.distanceTv.setVisibility(View.GONE);
holder.distanceTv.setText(null);
}
}
if (holder.compassV != null) {
if (holder.distanceTv != null && holder.distanceTv.getVisibility() == View.VISIBLE) {
if (this.location != null && this.lastCompassInDegree >= 0 && this.location.getAccuracy() <= poim.getDistance()) {
holder.compassV.generateAndSetHeading(this.location, this.lastCompassInDegree, this.locationDeclination);
} else {
holder.compassV.resetHeading();
}
holder.compassV.setVisibility(View.VISIBLE);
} else {
holder.compassV.resetHeading();
holder.compassV.setVisibility(View.GONE);
}
}
if (holder.locationTv != null) {
if (TextUtils.isEmpty(poim.getLocation())) {
holder.locationTv.setVisibility(View.GONE);
holder.locationTv.setText(null);
} else {
holder.locationTv.setText(poim.getLocation());
holder.locationTv.setVisibility(View.VISIBLE);
}
}
if (this.showFavorite && this.favUUIDs != null && this.favUUIDs.contains(poi.getUUID())) {
holder.favImg.setVisibility(View.VISIBLE);
} else {
holder.favImg.setVisibility(View.GONE);
}
int index;
if (this.closestPoiUuids != null && this.closestPoiUuids.contains(poi.getUUID())) {
index = 0;
} else {
index = -1;
}
switch (index) {
case 0:
holder.nameTv.setTypeface(Typeface.DEFAULT_BOLD);
if (holder.distanceTv != null) {
holder.distanceTv.setTypeface(Typeface.DEFAULT_BOLD);
}
break;
default:
holder.nameTv.setTypeface(Typeface.DEFAULT);
if (holder.distanceTv != null) {
holder.distanceTv.setTypeface(Typeface.DEFAULT);
}
break;
}
}
private MTAsyncTask<Integer, Void, ArrayList<Favorite>> refreshFavoritesTask;
private void refreshFavorites() {
if (this.refreshFavoritesTask != null && this.refreshFavoritesTask.getStatus() == MTAsyncTask.Status.RUNNING) {
return; // skipped, last refresh still in progress so probably good enough
}
this.refreshFavoritesTask = new MTAsyncTask<Integer, Void, ArrayList<Favorite>>() {
@Override
public String getLogTag() {
return POIArrayAdapter.class.getSimpleName() + ">refreshFavoritesTask";
}
@Override
protected ArrayList<Favorite> doInBackgroundMT(Integer... params) {
return FavoriteManager.findFavorites(POIArrayAdapter.this.getContext());
}
@Override
protected void onPostExecute(ArrayList<Favorite> result) {
setFavorites(result);
}
};
TaskUtils.execute(this.refreshFavoritesTask);
}
private void setFavorites(ArrayList<Favorite> favorites) {
boolean newFav = false; // don't trigger update if favorites are the same
boolean updatedFav = false; // don't trigger it favorites are the same OR were not set
if (this.favUUIDs == null) {
newFav = true; // favorite never set before
updatedFav = false; // never set before so not updated
} else if (CollectionUtils.getSize(favorites) != CollectionUtils.getSize(this.favUUIDs)) {
newFav = true; // different size => different favorites
updatedFav = true; // different size => different favorites
}
HashSet<String> newFavUUIDs = new HashSet<String>();
HashMap<String, Integer> newFavUUIDsFolderIds = new HashMap<String, Integer>();
if (favorites != null) {
for (Favorite favorite : favorites) {
String uid = favorite.getFkId();
if (!newFav && (
(this.favUUIDs != null && !this.favUUIDs.contains(uid)) ||
(this.favUUIDsFolderIds != null && this.favUUIDsFolderIds.containsKey(uid) && this.favUUIDsFolderIds.get(uid) != favorite.getFolderId())
)) {
newFav = true;
updatedFav = true;
}
newFavUUIDs.add(uid);
newFavUUIDsFolderIds.put(uid, favorite.getFolderId());
}
}
if (!newFav) {
if (this.favUUIDsFolderIds == null) {
newFav = true; // favorite never set before
updatedFav = false; // never set before so not updated
} else {
HashSet<Integer> oldFolderIds = new HashSet<Integer>();
for (Integer folderId : this.favUUIDsFolderIds.values()) {
oldFolderIds.add(folderId);
}
HashSet<Integer> newFolderIds = new HashSet<Integer>();
for (Integer folderId : newFavUUIDsFolderIds.values()) {
newFolderIds.add(folderId);
}
if (CollectionUtils.getSize(oldFolderIds) != CollectionUtils.getSize(newFolderIds)) {
newFav = true; // different size => different favorites
updatedFav = true; // different size => different favorites
}
}
}
this.favUUIDs = newFavUUIDs;
this.favUUIDsFolderIds = newFavUUIDsFolderIds;
if (newFav) {
notifyDataSetChanged(true);
}
if (updatedFav) {
if (this.favoriteUpdateListener != null) {
this.favoriteUpdateListener.onFavoriteUpdated();
}
}
}
private static class InfiniteLoadingViewHolder {
View progressBar;
View worldExplored;
}
private static class ModuleViewHolder extends CommonViewHolder {
ImageView moduleExtraTypeImg;
}
private static class RouteTripStopViewHolder extends CommonViewHolder {
TextView routeShortNameTv;
View routeFL;
View rtsExtraV;
MTJPathsView routeTypeImg;
TextView tripHeadingTv;
View tripHeadingBg;
}
private static class BasicPOIViewHolder extends CommonViewHolder {
}
private static class TextViewViewHolder extends CommonViewHolder {
}
public static class CommonViewHolder {
String uuid;
View view;
TextView nameTv;
TextView distanceTv;
TextView locationTv;
ImageView favImg;
MTCompassView compassV;
CommonStatusViewHolder statusViewHolder;
}
private static class AppStatusViewHolder extends CommonStatusViewHolder {
TextView textTv;
}
private static class ScheduleStatusViewHolder extends CommonStatusViewHolder {
TextView dataNextLine1Tv;
TextView dataNextLine2Tv;
}
private static class AvailabilityPercentStatusViewHolder extends CommonStatusViewHolder {
TextView textTv;
MTPieChartPercentView piePercentV;
}
public static class CommonStatusViewHolder {
String uuid;
View statusV;
ImageView warningImg;
}
private static class FavoriteFolderHeaderViewHolder {
TextView nameTv;
View deleteBtn;
View renameBtn;
}
private static class TypeHeaderViewHolder {
TextView nameTv;
TextView allBtnTv;
View allBtn;
View nearbyBtn;
View moreBtn;
}
public interface TypeHeaderButtonsClickListener {
int BUTTON_MORE = 0;
int BUTTON_NEARBY = 1;
int BUTTON_ALL = 2;
boolean onTypeHeaderButtonClick(int buttonId, DataSourceType type);
}
} |
package org.opencms.ade.publish;
import org.opencms.ade.publish.CmsPublishRelationFinder.ResourceMap;
import org.opencms.ade.publish.shared.CmsProjectBean;
import org.opencms.ade.publish.shared.CmsPublishData;
import org.opencms.ade.publish.shared.CmsPublishGroup;
import org.opencms.ade.publish.shared.CmsPublishGroupList;
import org.opencms.ade.publish.shared.CmsPublishListToken;
import org.opencms.ade.publish.shared.CmsPublishOptions;
import org.opencms.ade.publish.shared.CmsPublishResource;
import org.opencms.ade.publish.shared.CmsWorkflow;
import org.opencms.ade.publish.shared.CmsWorkflowAction;
import org.opencms.ade.publish.shared.CmsWorkflowActionParams;
import org.opencms.ade.publish.shared.CmsWorkflowResponse;
import org.opencms.ade.publish.shared.rpc.I_CmsPublishService;
import org.opencms.db.CmsUserSettings;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.CmsUser;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.CmsRpcException;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workflow.CmsWorkflowResources;
import org.opencms.workflow.I_CmsPublishResourceFormatter;
import org.opencms.workflow.I_CmsWorkflowManager;
import org.opencms.workplace.CmsDialog;
import org.opencms.workplace.CmsWorkplace;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* The implementation of the publish service. <p>
*
* @since 8.0.0
*
*/
public class CmsPublishService extends CmsGwtService implements I_CmsPublishService {
/** Name for the request parameter to control display of the confirmation dialog. */
public static final String PARAM_CONFIRM = "confirm";
/** The publish project id parameter name. */
public static final String PARAM_PUBLISH_PROJECT_ID = "publishProjectId";
/** The workflow id parameter name. */
public static final String PARAM_WORKFLOW_ID = "workflowId";
/** The logger for this class. */
private static final Log LOG = CmsLog.getLog(CmsPublishService.class);
/** The version id for serialization. */
private static final long serialVersionUID = 3852074177607037076L;
/** Session attribute name constant. */
private static final String SESSION_ATTR_ADE_PUB_OPTS_CACHE = "__OCMS_ADE_PUB_OPTS_CACHE__";
/**
* Fetches the publish data.<p>
*
* @param request the servlet request
*
* @return the publish data
*
* @throws CmsRpcException if something goes wrong
*/
public static CmsPublishData prefetch(HttpServletRequest request) throws CmsRpcException {
CmsPublishService srv = new CmsPublishService();
srv.setCms(CmsFlexController.getCmsObject(request));
srv.setRequest(request);
CmsPublishData result = null;
HashMap<String, String> params = Maps.newHashMap();
try {
result = srv.getInitData(params);
} finally {
srv.clearThreadStorage();
}
return result;
}
/**
* Wraps the project name in a message string.<p>
*
* @param cms the CMS context
* @param name the project name
*
* @return the message for the given project name
*/
public static String wrapProjectName(CmsObject cms, String name) {
return Messages.get().getBundle(OpenCms.getWorkplaceManager().getWorkplaceLocale(cms)).key(
Messages.GUI_NORMAL_PROJECT_1,
name);
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#executeAction(org.opencms.ade.publish.shared.CmsWorkflowAction, org.opencms.ade.publish.shared.CmsWorkflowActionParams)
*/
public CmsWorkflowResponse executeAction(CmsWorkflowAction action, CmsWorkflowActionParams params)
throws CmsRpcException {
CmsWorkflowResponse response = null;
try {
CmsObject cms = getCmsObject();
if (params.getToken() == null) {
CmsPublishOptions options = getCachedOptions();
CmsPublish pub = new CmsPublish(cms, options);
List<CmsResource> publishResources = idsToResources(cms, params.getPublishIds());
Set<CmsUUID> toRemove = new HashSet<CmsUUID>(params.getRemoveIds());
pub.removeResourcesFromPublishList(toRemove);
response = OpenCms.getWorkflowManager().executeAction(cms, action, options, publishResources);
} else {
response = OpenCms.getWorkflowManager().executeAction(cms, action, params.getToken());
}
} catch (Throwable e) {
error(e);
}
return response;
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getInitData(java.util.HashMap)
*/
public CmsPublishData getInitData(HashMap<String, String> params) throws CmsRpcException {
CmsPublishData result = null;
CmsObject cms = getCmsObject();
String closeLink = getRequest().getParameter(CmsDialog.PARAM_CLOSELINK);
String confirmStr = getRequest().getParameter(PARAM_CONFIRM);
boolean confirm = Boolean.parseBoolean(confirmStr);
String workflowId = getRequest().getParameter(PARAM_WORKFLOW_ID);
String projectParam = getRequest().getParameter(PARAM_PUBLISH_PROJECT_ID);
String filesParam = getRequest().getParameter(CmsWorkplace.PARAM_RESOURCELIST);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(filesParam)) {
filesParam = getRequest().getParameter(CmsDialog.PARAM_RESOURCE);
}
List<String> pathList = Lists.newArrayList();
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(filesParam)) {
pathList = CmsStringUtil.splitAsList(filesParam, "|");
}
try {
result = getPublishData(cms, params, workflowId, projectParam, pathList, closeLink, confirm);
} catch (Throwable e) {
error(e);
}
return result;
}
/**
* Gets the publish data for the given parameters.<p>
*
* @param cms the CMS context
* @param params other publish parameters
* @param workflowId the workflow id
* @param projectParam the project
* @param pathList the list of direct publish resource site paths
* @param closeLink the close link
* @param confirm true if confirmation dialog should be displayed after closing the dialog
*
* @return the publish data
*
* @throws Exception if something goes wrong
*/
public CmsPublishData getPublishData(
CmsObject cms,
HashMap<String, String> params,
String workflowId,
String projectParam,
List<String> pathList,
String closeLink,
boolean confirm)
throws Exception {
CmsPublishData result;
boolean canOverrideWorkflow = true;
Map<String, CmsWorkflow> workflows = OpenCms.getWorkflowManager().getWorkflows(cms);
if (workflows.isEmpty()) {
throw new Exception("No workflow available for the current user");
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(workflowId) || !workflows.containsKey(workflowId)) {
workflowId = getLastWorkflowForUser();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(workflowId) || !workflows.containsKey(workflowId)) {
workflowId = workflows.values().iterator().next().getId();
}
} else {
canOverrideWorkflow = false;
}
setLastWorkflowForUser(workflowId);
// need to put this into params here so that the virtual project for direct publishing is included in the result of getManageableProjects()
if (!pathList.isEmpty()) {
params.put(CmsPublishOptions.PARAM_FILES, CmsStringUtil.listAsString(pathList, "|"));
}
boolean useCurrentPageAsDefault = params.containsKey(CmsPublishOptions.PARAM_START_WITH_CURRENT_PAGE);
CmsPublishOptions options = getCachedOptions();
List<CmsProjectBean> projects = OpenCms.getWorkflowManager().getManageableProjects(cms, params);
Set<CmsUUID> availableProjectIds = Sets.newHashSet();
for (CmsProjectBean projectBean : projects) {
availableProjectIds.add(projectBean.getId());
}
CmsUUID defaultProjectId = CmsUUID.getNullUUID();
if (useCurrentPageAsDefault && availableProjectIds.contains(CmsCurrentPageProject.ID)) {
defaultProjectId = CmsCurrentPageProject.ID;
}
boolean foundProject = false;
CmsUUID selectedProject = null;
if (!pathList.isEmpty()) {
params.put(CmsPublishOptions.PARAM_ENABLE_INCLUDE_CONTENTS, Boolean.TRUE.toString());
params.put(CmsPublishOptions.PARAM_INCLUDE_CONTENTS, Boolean.TRUE.toString());
selectedProject = CmsDirectPublishProject.ID;
foundProject = true;
} else {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(projectParam) && CmsUUID.isValidUUID(projectParam)) {
selectedProject = new CmsUUID(projectParam);
// check if the selected project is a manageable project
for (CmsProjectBean project : projects) {
if (selectedProject.equals(project.getId())) {
foundProject = true;
if (project.isWorkflowProject()) {
canOverrideWorkflow = false;
workflowId = OpenCms.getWorkflowManager().getWorkflowForWorkflowProject(selectedProject);
}
break;
}
}
}
if (!foundProject) {
selectedProject = options.getProjectId();
if (selectedProject == null) {
selectedProject = defaultProjectId;
foundProject = true;
} else {
// check if the selected project is a manageable project
for (CmsProjectBean project : projects) {
if (selectedProject.equals(project.getId())) {
foundProject = true;
if (project.isWorkflowProject()) {
canOverrideWorkflow = false;
workflowId = OpenCms.getWorkflowManager().getWorkflowForWorkflowProject(
selectedProject);
}
break;
}
}
}
}
}
if (foundProject) {
options.setProjectId(selectedProject);
} else {
options.setProjectId(CmsUUID.getNullUUID());
}
options.setParameters(params);
result = new CmsPublishData(
options,
projects,
getResourceGroups(workflows.get(workflowId), options, canOverrideWorkflow),
workflows,
workflowId);
result.setCloseLink(closeLink);
result.setShowConfirmation(confirm);
return result;
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getResourceGroups(org.opencms.ade.publish.shared.CmsWorkflow, org.opencms.ade.publish.shared.CmsPublishOptions, boolean)
*/
public CmsPublishGroupList getResourceGroups(
CmsWorkflow workflow,
CmsPublishOptions options,
boolean projectChanged)
throws CmsRpcException {
List<CmsPublishGroup> results = null;
CmsObject cms = getCmsObject();
String overrideWorkflowId = null;
try {
Locale locale = OpenCms.getWorkplaceManager().getWorkplaceLocale(cms);
I_CmsWorkflowManager workflowManager = OpenCms.getWorkflowManager();
I_CmsPublishResourceFormatter formatter = workflowManager.createFormatter(cms, workflow, options);
CmsWorkflowResources workflowResources = workflowManager.getWorkflowResources(
cms,
workflow,
options,
projectChanged);
if (workflowResources.getOverrideWorkflow() != null) {
overrideWorkflowId = workflowResources.getOverrideWorkflow().getId();
formatter = workflowManager.createFormatter(cms, workflowResources.getOverrideWorkflow(), options);
}
List<CmsResource> resources = workflowResources.getWorkflowResources();
if (resources.size() > workflowManager.getResourceLimit()) {
// too many resources, send a publish list token to the client which can be used later to restore the resource list
CmsPublishListToken token = workflowManager.getPublishListToken(cms, workflow, options);
CmsPublishGroupList result = new CmsPublishGroupList(token);
result.setTooManyResourcesMessage(
Messages.get().getBundle(locale).key(
Messages.GUI_TOO_MANY_RESOURCES_2,
"" + resources.size(),
"" + OpenCms.getWorkflowManager().getResourceLimit()));
return result;
}
I_CmsVirtualProject virtualProject = workflowManager.getRealOrVirtualProject(options.getProjectId());
I_CmsPublishRelatedResourceProvider relProvider = virtualProject.getRelatedResourceProvider(
getCmsObject(),
options);
ResourceMap resourcesAndRelated = getResourcesAndRelated(
resources,
options.isIncludeRelated(),
options.isIncludeSiblings(),
(options.getProjectId() == null) || options.getProjectId().isNullUUID(),
relProvider);
formatter.initialize(options, resourcesAndRelated);
List<CmsPublishResource> publishResources = formatter.getPublishResources();
A_CmsPublishGroupHelper<CmsPublishResource, CmsPublishGroup> groupHelper;
boolean autoSelectable = true;
if ((options.getProjectId() == null) || options.getProjectId().isNullUUID()) {
groupHelper = new CmsDefaultPublishGroupHelper(locale);
} else {
String title = "";
CmsProjectBean projectBean = virtualProject.getProjectBean(cms, options.getParameters());
title = projectBean.getDefaultGroupName();
if (title == null) {
title = "";
}
autoSelectable = virtualProject.isAutoSelectable();
groupHelper = new CmsSinglePublishGroupHelper(locale, title);
}
results = groupHelper.getGroups(publishResources);
for (CmsPublishGroup group : results) {
group.setAutoSelectable(autoSelectable);
}
setCachedOptions(options);
setLastWorkflowForUser(workflow.getId());
} catch (Throwable e) {
error(e);
}
CmsPublishGroupList wrapper = new CmsPublishGroupList();
wrapper.setOverrideWorkflowId(overrideWorkflowId);
wrapper.setGroups(results);
return wrapper;
}
/**
* Retrieves the publish options.<p>
*
* @return the publish options last used
*
* @throws CmsRpcException if something goes wrong
*/
public CmsPublishOptions getResourceOptions() throws CmsRpcException {
CmsPublishOptions result = null;
try {
result = getCachedOptions();
} catch (Throwable e) {
error(e);
}
return result;
}
/**
* Adds siblings to a set of publish resources.<p>
*
* @param publishResources the set to which siblings should be added
*/
protected void addSiblings(Set<CmsResource> publishResources) {
List<CmsResource> toAdd = Lists.newArrayList();
for (CmsResource resource : publishResources) {
if (!resource.getState().isUnchanged()) {
try {
List<CmsResource> changedSiblings = getCmsObject().readSiblings(
resource,
CmsResourceFilter.ALL_MODIFIED);
toAdd.addAll(changedSiblings);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
publishResources.addAll(toAdd);
}
/**
* Returns the cached publish options, creating it if it doesn't already exist.<p>
*
* @return the cached publish options
*/
private CmsPublishOptions getCachedOptions() {
CmsPublishOptions cache = (CmsPublishOptions)getRequest().getSession().getAttribute(
SESSION_ATTR_ADE_PUB_OPTS_CACHE);
if (cache == null) {
CmsUserSettings settings = new CmsUserSettings(getCmsObject());
cache = new CmsPublishOptions();
cache.setIncludeSiblings(settings.getDialogPublishSiblings());
getRequest().getSession().setAttribute(SESSION_ATTR_ADE_PUB_OPTS_CACHE, cache);
}
return cache;
}
/**
* Returns the id of the last used workflow for the current user.<p>
*
* @return the workflow id
*/
private String getLastWorkflowForUser() {
CmsUser user = getCmsObject().getRequestContext().getCurrentUser();
return (String)user.getAdditionalInfo(PARAM_WORKFLOW_ID);
}
/**
* Gets the resource map containing the publish resources together with their related resources.<p>
*
* @param resources the base list of publish resources
* @param includeRelated flag to control whether related resources should be included
* @param includeSiblings flag to control whether siblings should be included
* @param keepOriginalUnchangedResources flag which determines whether unchanged resources in the original resource list should be kept or removed
* @param relProvider the provider for additional related resources
*
* @return the resources together with their related resources
*/
private ResourceMap getResourcesAndRelated(
List<CmsResource> resources,
boolean includeRelated,
boolean includeSiblings,
boolean keepOriginalUnchangedResources,
I_CmsPublishRelatedResourceProvider relProvider) {
Set<CmsResource> publishResources = new HashSet<CmsResource>();
publishResources.addAll(resources);
if (includeSiblings) {
addSiblings(publishResources);
}
ResourceMap result;
if (includeRelated) {
CmsPublishRelationFinder relationFinder = new CmsPublishRelationFinder(
getCmsObject(),
publishResources,
keepOriginalUnchangedResources,
relProvider);
result = relationFinder.getPublishRelatedResources();
} else {
result = new ResourceMap();
for (CmsResource resource : publishResources) {
if (keepOriginalUnchangedResources || !resource.getState().isUnchanged()) {
result.put(resource, new HashSet<CmsResource>());
}
}
}
return result;
}
/**
* Converts a list of IDs to resources.<p>
*
* @param cms the CmObject used for reading the resources
* @param ids the list of IDs
*
* @return a list of resources
*/
private List<CmsResource> idsToResources(CmsObject cms, List<CmsUUID> ids) {
List<CmsResource> result = new ArrayList<CmsResource>();
for (CmsUUID id : ids) {
try {
CmsResource resource = cms.readResource(id, CmsResourceFilter.ALL);
result.add(resource);
} catch (CmsException e) {
// should never happen
logError(e);
}
}
return result;
}
/**
* Saves the given options to the session.<p>
*
* @param options the options to save
*/
private void setCachedOptions(CmsPublishOptions options) {
getRequest().getSession().setAttribute(SESSION_ATTR_ADE_PUB_OPTS_CACHE, options);
}
/**
* Writes the id of the last used workflow to the current user.<p>
*
* @param workflowId the workflow id
*
* @throws CmsException if something goes wrong writing the user object
*/
private void setLastWorkflowForUser(String workflowId) throws CmsException {
CmsUser user = getCmsObject().getRequestContext().getCurrentUser();
user.setAdditionalInfo(PARAM_WORKFLOW_ID, workflowId);
getCmsObject().writeUser(user);
}
} |
package org.sotorrent.posthistoryextractor;
import org.sotorrent.util.MathUtils;
import java.util.function.BiFunction;
public class Config {
// configure post history processing
private final boolean extractUrls;
private final boolean computeDiffs;
private final boolean catchInputTooShortExceptions;
// metrics and threshold for text blocks
private final BiFunction<String, String, Double> textSimilarityMetric;
private final double textSimilarityThreshold;
private final BiFunction<String, String, Double> textBackupSimilarityMetric;
private final double textBackupSimilarityThreshold;
// metrics and threshold for code blocks
private final BiFunction<String, String, Double> codeSimilarityMetric;
private final double codeSimilarityThreshold;
private final BiFunction<String, String, Double> codeBackupSimilarityMetric;
private final double codeBackupSimilarityThreshold;
private Config(boolean extractUrls, boolean computeDiffs, boolean catchInputTooShortExceptions,
BiFunction<String, String, Double> textSimilarityMetric,
double textSimilarityThreshold,
BiFunction<String, String, Double> textBackupSimilarityMetric,
double textBackupSimilarityThreshold,
BiFunction<String, String, Double> codeSimilarityMetric,
double codeSimilarityThreshold,
BiFunction<String, String, Double> codeBackupSimilarityMetric,
double codeBackupSimilarityThreshold) {
this.extractUrls = extractUrls;
this.computeDiffs = computeDiffs;
this.catchInputTooShortExceptions = catchInputTooShortExceptions;
this.textSimilarityMetric = textSimilarityMetric;
this.textSimilarityThreshold = textSimilarityThreshold;
this.textBackupSimilarityMetric = textBackupSimilarityMetric;
this.textBackupSimilarityThreshold = textBackupSimilarityThreshold;
this.codeSimilarityMetric = codeSimilarityMetric;
this.codeSimilarityThreshold = codeSimilarityThreshold;
this.codeBackupSimilarityMetric = codeBackupSimilarityMetric;
this.codeBackupSimilarityThreshold = codeBackupSimilarityThreshold;
}
public static final Config EMPTY = new Config(
false,
false,
false,
(str1, str2) -> 0.0,
Double.POSITIVE_INFINITY,
null,
Double.POSITIVE_INFINITY,
(str1, str2) -> 0.0,
Double.POSITIVE_INFINITY,
null,
Double.POSITIVE_INFINITY
);
public static final Config METRICS_COMPARISON = new Config(
false,
false,
true,
(str1, str2) -> 0.0,
1.0,
null,
1.0,
(str1, str2) -> 0.0,
1.0,
null,
1.0
);
public static final Config DEFAULT = new Config(
true,
true,
false,
org.sotorrent.stringsimilarity.set.Variants::fiveGramDice,
0.04,
org.sotorrent.stringsimilarity.profile.Variants::cosineTokenNormalizedBool,
0.19,
org.sotorrent.stringsimilarity.set.Variants::tokenDiceNormalized,
0.1,
org.sotorrent.stringsimilarity.set.Variants::tokenDiceNormalized,
0.1
);
public BiFunction<String, String, Double> getTextSimilarityMetric() {
return textSimilarityMetric;
}
public BiFunction<String, String, Double> getTextBackupSimilarityMetric() {
return textBackupSimilarityMetric;
}
public double getTextSimilarityThreshold() {
return textSimilarityThreshold;
}
public double getTextBackupSimilarityThreshold() {
return textBackupSimilarityThreshold;
}
public BiFunction<String, String, Double> getCodeSimilarityMetric() {
return codeSimilarityMetric;
}
public BiFunction<String, String, Double> getCodeBackupSimilarityMetric() {
return codeBackupSimilarityMetric;
}
public double getCodeSimilarityThreshold() {
return codeSimilarityThreshold;
}
public double getCodeBackupSimilarityThreshold() {
return codeBackupSimilarityThreshold;
}
public boolean getExtractUrls() {
return extractUrls;
}
public boolean getComputeDiffs() {
return computeDiffs;
}
public boolean getCatchInputTooShortExceptions() {
return catchInputTooShortExceptions;
}
public Config withExtractUrls(boolean extractUrls) {
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withComputeDiffs(boolean computeDiffs) {
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withCatchInputTooShortExceptions(boolean catchInputTooShortExceptions) {
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withTextSimilarityMetric(BiFunction<String, String, Double> textSimilarityMetric){
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withTextSimilarityThreshold(double textSimilarityThreshold){
if (MathUtils.lessThan(textSimilarityThreshold, 0.0)
|| MathUtils.greaterThan(textSimilarityThreshold, 1.0)) {
throw new IllegalArgumentException("Similarity threshold must be in range [0.0, 1.0]");
}
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withTextBackupSimilarityMetric(BiFunction<String, String, Double> textBackupSimilarityMetric){
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withTextBackupSimilarityThreshold(double textBackupSimilarityThreshold){
if (MathUtils.lessThan(textBackupSimilarityThreshold, 0.0)
|| MathUtils.greaterThan(textBackupSimilarityThreshold, 1.0)) {
throw new IllegalArgumentException("Similarity threshold must be in range [0.0, 1.0]");
}
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withCodeSimilarityMetric(BiFunction<String, String, Double> codeSimilarityMetric){
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withCodeSimilarityThreshold(double codeSimilarityThreshold){
if (MathUtils.lessThan(codeSimilarityThreshold, 0.0)
|| MathUtils.greaterThan(codeSimilarityThreshold, 1.0)) {
throw new IllegalArgumentException("Similarity threshold must be in range [0.0, 1.0]");
}
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withCodeBackupSimilarityMetric(BiFunction<String, String, Double> codeBackupSimilarityMetric){
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
public Config withCodeBackupSimilarityThreshold(double codeBackupSimilarityThreshold){
if (MathUtils.lessThan(codeBackupSimilarityThreshold, 0.0)
|| MathUtils.greaterThan(codeBackupSimilarityThreshold, 1.0)) {
throw new IllegalArgumentException("Similarity threshold must be in range [0.0, 1.0]");
}
return new Config(extractUrls, computeDiffs, catchInputTooShortExceptions,
textSimilarityMetric, textSimilarityThreshold, textBackupSimilarityMetric, textBackupSimilarityThreshold,
codeSimilarityMetric, codeSimilarityThreshold, codeBackupSimilarityMetric, codeBackupSimilarityThreshold);
}
} |
/*
* $Id$
* $URL$
*/
package org.subethamail.web.action;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.java.Log;
import org.subethamail.core.lists.i.SubscriberData;
import org.subethamail.web.Backend;
import org.subethamail.web.action.auth.AuthAction;
import org.subethamail.web.model.PaginateModel;
/**
* Gets a list of subscribers to the list
*
* @author Jeff Schnitzer
* @author Jon Stevens
*/
@Log
public class GetSubscribers extends AuthAction
{
public static class Model extends PaginateModel
{
@Getter @Setter Long listId;
@Getter @Setter String query = "";
@Getter @Setter List<SubscriberData> subscribers;
}
public void initialize()
{
this.getCtx().setModel(new Model());
}
public void execute() throws Exception
{
Model model = (Model)this.getCtx().getModel();
if (model.query.trim().length() == 0)
{
model.subscribers = Backend.instance().getListMgr().getSubscribers(model.listId, model.getSkip(), model.getCount());
model.setTotalCount(Backend.instance().getListMgr().countSubscribers(model.listId));
}
else
{
model.subscribers = Backend.instance().getListMgr().searchSubscribers(model.listId, model.query, model.getSkip(), model.getCount());
model.setTotalCount(Backend.instance().getListMgr().countSubscribersQuery(model.listId, model.query));
// See the comment in GetLists
}
}
} |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc692.AerialAssist2014;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import org.usfirst.frc692.AerialAssist2014.commands.*;
import org.usfirst.frc692.AerialAssist2014.subsystems.*;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
Command autonomousCommand;
public static OI oi;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static DriveTrain driveTrain;
public static Shooter shooter;
public static Gatherer gatherer;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
AxisCamera camera;
Compressor compressor = new Compressor(1, 1, 1, 1);
public void robotInit() {
RobotMap.init();
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
driveTrain = new DriveTrain();
shooter = new Shooter();
gatherer = new Gatherer();
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
// This MUST be here. If the OI creates Commands (which it very likely
// will), constructing it during the construction of CommandBase (from
// which commands extend), subsystems are not guaranteed to be
// yet. Thus, their requires() statements may grab null pointers. Bad
// news. Don't move it.
oi = new OI();
compressor.start();
// instantiate the command used for the autonomous period
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS
autonomousCommand = new AutonomousCommand();
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS
camera = AxisCamera.getInstance();
//gets the image from the camera
//AC 1/18/14
camera.writeResolution(AxisCamera.ResolutionT.k320x240);
//sets resolution for camera image on driver station to 320x240
//AC 1/18/14
camera.writeBrightness(0);
//does not change brightness
//AC 1/18/14
}
public void autonomousInit() {
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
DriverStationLCD.getInstance().updateLCD();
//allows the driver station to be updated with the current image from the camera
//AC 1/18/14
}
/**
* This function called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
} |
package beast.core;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import beast.core.Input.Validate;
import beast.core.util.Log;
import beast.evolution.tree.Tree;
import beast.util.XMLProducer;
@Description("Logs results of a calculation processes on regular intervals.")
public class Logger extends BEASTObject {
/**
* currently supported modes *
*/
public enum LOGMODE {
autodetect, compound, tree
}
public enum SORTMODE {
none, alphabetic, smart
}
final public Input<String> fileNameInput = new Input<>("fileName", "Name of the file, or stdout if left blank");
final public Input<Integer> everyInput = new Input<>("logEvery", "Number of the samples logged", 1);
final public Input<BEASTObject> modelInput = new Input<>("model", "Model to log at the top of the log. " +
"If specified, XML will be produced for the model, commented out by # at the start of a line. " +
"Alignments are suppressed. This way, the log file documents itself. ");
final public Input<LOGMODE> modeInput = new Input<>("mode", "logging mode, one of " + Arrays.toString(LOGMODE.values()), LOGMODE.autodetect, LOGMODE.values());
final public Input<SORTMODE> sortModeInput = new Input<>("sort", "sort items to be logged, one of " + Arrays.toString(SORTMODE.values()), SORTMODE.none, SORTMODE.values());
final public Input<Boolean> sanitiseHeadersInput = new Input<>("sanitiseHeaders", "whether to remove any clutter introduced by Beauti" , false);
final public Input<List<BEASTObject>> loggersInput = new Input<>("log",
"Element in a log. This can be any plug in that is Loggable.",
new ArrayList<>(), Validate.REQUIRED, Loggable.class);
// the file name to log to, or null, or "" if logging to stdout
private String fileName;
/**
* list of loggers, if any
*/
List<Loggable> loggerList;
public enum LogFileMode {
only_new, overwrite, resume, only_new_or_exit
}
public static LogFileMode FILE_MODE = LogFileMode.only_new;
/**
* Compound loggers get a sample number printed at the beginning of the line,
* while tree loggers don't.
*/
public LOGMODE mode = LOGMODE.compound;
/**
* offset for the sample number, which is non-zero when a chain is resumed *
*/
static protected long sampleOffset = -1;
/**
* number of samples between logs *
*/
protected long every = 1;
/**
* stream to log to
*/
protected PrintStream m_out;
/**
* keep track of time taken between logs to estimate speed *
*/
long startLogTime = -5;
long startSample;
@Override
public void initAndValidate() {
fileName = fileNameInput.get();
final List<BEASTObject> loggers = loggersInput.get();
final int loggerCount = loggers.size();
if (loggerCount == 0) {
throw new RuntimeException("Logger with nothing to log specified");
}
loggerList = new ArrayList<>();
for (final BEASTObject logger : loggers) {
loggerList.add((Loggable) logger);
}
// determine logging mode
final LOGMODE mode = modeInput.get();
if (mode.equals(LOGMODE.autodetect)) {
this.mode = LOGMODE.compound;
if (loggerCount == 1 && loggerList.get(0) instanceof Tree) {
this.mode = LOGMODE.tree;
}
} else if (mode.equals(LOGMODE.tree)) {
this.mode = LOGMODE.tree;
} else if (mode.equals(LOGMODE.compound)) {
this.mode = LOGMODE.compound;
} else {
throw new IllegalArgumentException("Mode '" + mode + "' is not supported. Choose one of " + Arrays.toString(LOGMODE.values()));
}
if (everyInput.get() != null) {
every = everyInput.get();
}
if (this.mode == LOGMODE.compound) {
switch (sortModeInput.get()) {
case none:
// nothing to do
break;
case alphabetic:
// sort loggers by id
Collections.sort(loggerList, (Loggable o1, Loggable o2) -> {
final String id1 = ((BEASTObject)o1).getID();
final String id2 = ((BEASTObject)o2).getID(); //was o1, probably a bug, found by intelliJ
if (id1 == null || id2 == null) {return 0;}
return id1.compareTo(id2);
}
);
break;
case smart:
// Group loggers with same id-prefix, where the prefix of an id is
// defined as the part of an id before the first full stop.
// This way, multi-partition analysis generated by BEAUti get all
// related log items together in Tracer
final List<String> ids = new ArrayList<>();
final List<String> postfix = new ArrayList<>();
for (final Loggable aLoggerList : loggerList) {
String id = ((BEASTInterface) aLoggerList).getID();
if (id == null) {
id = "";
}
String post = id;
if (id.indexOf('.') > 0) {
id = id.substring(0, id.indexOf('.'));
post = post.substring(post.indexOf('.') + 1);
} else {
post = "";
}
ids.add(id);
postfix.add(post);
}
for (int i = 0; i < loggerList.size(); i++) {
int k = 1;
final String id = ids.get(i);
for (int j = i + 1; j < loggerList.size(); j++) {
if (ids.get(j).equals(id)) {
int m = k;
String post = postfix.get(j);
while (m >= 0 && id.equals(ids.get(i+m-1)) && postfix.get(i+m-1).compareTo(post) > 0) {
m
}
ids.remove(j);
ids.add(i + m, id);
String p = postfix.remove(j);
postfix.add(i + m, p);
final Loggable l = loggerList.remove(j);
loggerList.add(i + m, l);
k++;
}
}
}
break;
}
}
} // initAndValidate
/**
* @return true if this logger is logging to stdout.
*/
public boolean isLoggingToStdout() {
return (fileName == null || fileName.length() == 0);
}
/**
* initialise log, open file (if necessary) and produce header of log
*/
public void init() throws IOException {
final boolean needsHeader = openLogFile();
if (needsHeader) {
if (modelInput.get() != null) {
// print model at top of log
String xml = new XMLProducer().modelToXML(modelInput.get());
xml = "#" + xml.replaceAll("\\n", "\n#");
m_out.println("#\n#model:\n#");
m_out.println(xml);
m_out.println("
}
ByteArrayOutputStream baos = null;
PrintStream tmp = null;
if (m_out == System.out) {
tmp = m_out;
baos = new ByteArrayOutputStream();
m_out = new PrintStream(baos);
}
final ByteArrayOutputStream rawbaos = new ByteArrayOutputStream();
final PrintStream out = new PrintStream(rawbaos);
if (mode == LOGMODE.compound) {
out.print("Sample\t");
}
for (final Loggable m_logger : loggerList) {
m_logger.init(out);
}
// Remove trailing tab from header
String header = rawbaos.toString().trim();
if (sanitiseHeadersInput.get()) {
m_out.print(sanitiseHeader(header));
} else {
m_out.print(header);
}
if ( baos != null ) {
assert tmp == System.out;
m_out = tmp;
try {
String logContent = baos.toString("ASCII");
logContent = prettifyLogLine(logContent);
m_out.print(logContent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
m_out.println();
}
} // init
/** remove indicators of partition context from header of a log file **/
public String sanitiseHeader(String header) {
// collect partitions
String partitionPrefix = null, clockPrefix = null, sitePrefix = null, treePrefix = null;
for (int i = 0; i < header.length(); i++) {
char c = header.charAt(i);
if (c == '.') {
if (i < header.length() - 2 && header.charAt(i+2) == ':') {
final char c2 = header.charAt(++i);
i++;
String prefix = "";
while (i < header.length() - 1 && c != '\t') {
c = header.charAt(++i);
if (c != '\t') {
prefix += c;
}
}
switch (c2) {
case 'c':
clockPrefix = getprefix(clockPrefix, prefix);
break;
case 's':
sitePrefix = getprefix(sitePrefix, prefix);
break;
case 't':
treePrefix = getprefix(treePrefix, prefix);
break;
}
} else {
String prefix = "";
while (i < header.length() - 1 && c != '\t') {
c = header.charAt(++i);
if (c != '\t') {
prefix += c;
}
}
partitionPrefix = getprefix(partitionPrefix, prefix);
// get rid of braces
partitionPrefix = partitionPrefix.replaceAll("[\\(\\)]","");
}
}
}
// remove clock/site/tree info
header = header.replaceAll("\\." + partitionPrefix, ".");
header = header.replaceAll("\\.c:" + clockPrefix, ".");
header = header.replaceAll("\\.t:" + treePrefix, ".");
header = header.replaceAll("\\.s:" + sitePrefix, ".");
// remove trailing dots on labels
header = header.replaceAll("\\.\\.", ".");
header = header.replaceAll("\\.\t", "\t");
header = header.replaceAll("\\.$", "");
return header;
}
/** return longest common prefix of two strings, except when the first
* on is null, then it returns the second string.
*/
private String getprefix(final String str1, final String str2) {
if (str1 == null) {
return str2;
} else {
String prefix = "";
int i = 0;
while (i < str1.length() && i < str2.length() &&
str1.charAt(i) == str2.charAt(i)) {
prefix += str1.charAt(i++);
}
return prefix;
}
}
protected boolean openLogFile() throws IOException {
if (isLoggingToStdout()) {
m_out = System.out;
return true;
} else {
if (fileName.contains("$(tree)")) {
String treeName = "tree";
for (final Loggable logger : loggerList) {
if (logger instanceof BEASTObject) {
final String id = ((BEASTObject) logger).getID();
if (id.indexOf(".t:") > 0) {
treeName = id.substring(id.indexOf(".t:") + 3);
}
}
}
fileName = fileName.replace("$(tree)", treeName);
fileNameInput.setValue(fileName, this);
}
if (System.getProperty("file.name.prefix") != null) {
fileName = System.getProperty("file.name.prefix") + fileName;
}
switch (FILE_MODE) {
case only_new:// only open file if the file does not already exists
case only_new_or_exit: {
final File file = new File(fileName);
if (file.exists()) {
if (FILE_MODE == LogFileMode.only_new_or_exit) {
Log.err.println("Trying to write file " + fileName + " but the file already exists. Exiting now.");
throw new RuntimeException("Use overwrite or resume option, or remove the file");
//System.exit(0);
}
// Check with user what to do next
Log.info.println("Trying to write file " + fileName + " but the file already exists (perhaps use the -overwrite flag?).");
if (System.getProperty("beast.useWindow") != null) {
// we are using the BEAST console, so no input is possible
throw new IllegalArgumentException();
}
Log.info.println("Overwrite (Y=yes/N=no/A=overwrite all)?:");
Log.info.flush();
final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
final String msg = stdin.readLine();
if (msg.toLowerCase().equals("a")) {
FILE_MODE = LogFileMode.overwrite;
} else if (!msg.toLowerCase().equals("y")) {
Log.info.println("Exiting now.");
System.exit(0);
}
}
m_out = new PrintStream(fileName);
Log.info.println("Writing file " + fileName);
return true;
}
case overwrite:// (over)write log file
{
String msg = "Writing";
if (new File(fileName).exists()) {
msg = "Warning: Overwriting";
}
m_out = new PrintStream(fileName);
Log.warning.println(msg + " file " + fileName);
return true;
}
case resume:// append log file, pick up SampleOffset by reading existing log
{
final File file = new File(fileName);
if (file.exists()) {
if (mode == LOGMODE.compound) {
// first find the sample nr offset
Logger.sampleOffset = getLogOffset();
// open the file for appending
final FileOutputStream out2 = new FileOutputStream(fileName, true);
m_out = new PrintStream(out2);
} else {
// it is a tree logger, we may need to get rid of the last line!
// back up file in case something goes wrong (e.g. an out of memory error occurs)
final File treeFileBackup = new File(fileName);
//final boolean ok = treeFileBackup.renameTo(new File(fileName + ".bu")); assert ok;
Files.move(treeFileBackup.toPath(), new File(fileName+".bu").toPath(), StandardCopyOption.ATOMIC_MOVE);
// open the file and write back all but the last line
final BufferedReader fin = new BufferedReader(new FileReader(fileName+".bu"));
final FileOutputStream out2 = new FileOutputStream(fileName);
m_out = new PrintStream(out2);
//final StringBuilder buf = new StringBuilder();
String strLast = null;
//String str = fin.readLine();
boolean endSeen = false;
while (fin.ready()) {
if( endSeen ) {
m_out.println("End;");
endSeen = false;
}
final String str = fin.readLine();
if (!str.equals("End;")) {
m_out.println(str);
strLast = str;
} else {
endSeen = true;
}
}
fin.close();
// determine number of the last sample
if( strLast == null ) {
// empty log file?
throw new RuntimeException("Error 402: empty tree log file " + fileName + "? (check if there is a back up file " + fileName + ".bu)");
}
final String str = strLast.split("\\s+")[1];
final long sampleOffset = Long.parseLong(str.substring(6));
if (Logger.sampleOffset > 0 && sampleOffset != Logger.sampleOffset) {
//final boolean ok1 = treeFileBackup.renameTo(new File(fileName)); assert ok1;
Files.move(treeFileBackup.toPath(), new File(fileName).toPath(), StandardCopyOption.ATOMIC_MOVE);
throw new RuntimeException("Error 401: Cannot resume: log files do not end in same sample number");
}
Logger.sampleOffset = sampleOffset;
// it is safe to remove the backup file now
new File(fileName + ".bu").delete();
}
Log.info.println("Appending file " + fileName);
return false;
} else {
m_out = new PrintStream(fileName);
Log.warning.println("WARNING: Resuming, but file " + fileName + " does not exist yet (perhaps the seed number is not the same as before?).");
Log.info.println("Writing new file " + fileName);
return true;
}
}
default:
throw new RuntimeException("DEVELOPER ERROR: unknown file mode for logger " + FILE_MODE);
}
}
} // openLogFile
/**
* Determines the last state in a (trace or tree) log file
* Tries to detect if last line is corrupted and fixes it by removing the last line if so.
* Corruption is detected as follows:
* For trace logs, the number of columns in the header should be the same as in the log lines.
* For tree files, the last line (or one but last, if it ends with "End;") should end in a semi-column.
* @return last state of (corrected, if deemed corrupted) log file
* @throws IOException
*/
protected long getLogOffset() throws IOException {
final File file = new File(fileName);
if (file.exists()) {
final BufferedReader fin = new BufferedReader(new FileReader(fileName));
if (mode == LOGMODE.compound) {
// first find the sample nr offset
String str = null;
String prevStr = null;
int columnCount = -1;
while (fin.ready()) {
prevStr = str;
str = fin.readLine();
if (str.startsWith("Sample\t")) {
columnCount = str.split("\t").length;
}
}
fin.close();
assert str != null;
if (columnCount > 0 && columnCount != str.split("\t").length) {
// last trace log line does not have the same number of columns as header,
// so assume it was corrupted (e.g. disk full, or process aborted midway).
// Revert to previous line and fix file
try {
long offset = Long.parseLong(prevStr.split("\\s")[0]);
setLogOffset(offset);
return offset;
} catch (NumberFormatException e){
return 0;
}
}
try {
return Long.parseLong(str.split("\\s")[0]);
} catch (NumberFormatException e){
return 0;
}
} else {
// it is a tree logger
String str = null;
String prevStr = null;
while (fin.ready()) {
prevStr = str;
str = fin.readLine();
}
fin.close();
if( str == null ) {
// empty log file
return 0;
}
if (str.equals("End;")) {
str = prevStr;
}
if (!str.endsWith(";")) {
// file contains corrupted tree
// revert to previous line and fix file
final String str2 = prevStr.split("\\s+")[1];
try {
long offset = Long.parseLong(str2.substring(6));
setLogOffset(offset);
return offset;
} catch (NumberFormatException e){
return 0;
}
}
// determine number of the last sample
final String str2 = str.split("\\s+")[1];
try {
return Long.parseLong(str2.substring(6));
} catch (NumberFormatException e){
return 0;
}
}
}
return 0;
}
protected void setLogOffset(long offset) throws IOException {
final File file = new File(fileName);
if (file.exists()) {
// back up file in case something goes wrong (e.g. an out of memory error occurs)
final File treeFileBackup = new File(fileName);
//final boolean ok = treeFileBackup.renameTo(new File(fileName + ".bu")); assert ok;
Files.move(treeFileBackup.toPath(), new File(fileName+".bu").toPath(), StandardCopyOption.ATOMIC_MOVE);
// open the file and write back all but the last line
final BufferedReader fin = new BufferedReader(new FileReader(fileName+".bu"));
final PrintStream out2 = new PrintStream(fileName);
if (mode == LOGMODE.compound) {
// first find the sample nr offset
String str = null;
while (fin.ready()) {
str = fin.readLine();
out2.println(str);
if (!str.startsWith("
try {
final long sampleOffset = Long.parseLong(str.split("\\s")[0]);
if (offset == sampleOffset) {
break;
}
} catch (NumberFormatException e) {
// ignore
}
}
}
fin.close();
} else {
// it is a tree logger
String str = null;
while (fin.ready()) {
str = fin.readLine();
out2.println(str);
String [] strs = str.split("\\s+");
if (strs.length > 1 && strs[1].length() > 6) {
try {
final long sampleOffset = Long.parseLong(strs[1].substring(6));
if (offset == sampleOffset) {
break;
}
} catch (NumberFormatException e) {
// ignore
}
}
}
fin.close();
}
out2.close();
// it is safe to remove the backup file now
new File(fileName + ".bu").delete();
}
}
/**
* log the state for given sample nr
* *
* * @param sample
*/
public void log(long sampleNr) {
if ((sampleNr < 0) || (sampleNr % every > 0)) {
return;
}
if (sampleOffset >= 0) {
if (sampleNr == 0) {
// don't need to duplicate the last line in the log
return;
}
sampleNr += sampleOffset;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream out = new PrintStream(baos);
if (mode == LOGMODE.compound) {
out.print((sampleNr) + "\t");
}
for (final Loggable m_logger : loggerList) {
m_logger.log(sampleNr, out);
}
// Acquire log string and trim excess tab
String logContent;
try {
logContent = baos.toString("ASCII").trim();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("ASCII string encoding not supported: required for logging!");
}
// Include calculation speed estimate if this log is going to the terminal
if ( m_out == System.out ) {
logContent = prettifyLogLine(logContent);
m_out.print(logContent);
if (startLogTime < 0) {
if (sampleNr - sampleOffset > 6000) {
startLogTime++;
if (startLogTime == 0) {
startLogTime = System.currentTimeMillis();
startSample = sampleNr;
}
}
m_out.print("
} else {
final long logTime = System.currentTimeMillis();
final int secondsPerMSamples = (int) ((logTime - startLogTime) * 1000.0 / (sampleNr - startSample + 1.0));
final String timePerMSamples =
(secondsPerMSamples >= 3600 ? secondsPerMSamples / 3600 + "h" : "") +
(secondsPerMSamples >= 60 ? (secondsPerMSamples % 3600) / 60 + "m" : "") +
(secondsPerMSamples % 60 + "s");
m_out.print(" " + timePerMSamples + "/Msamples");
}
m_out.println();
} else {
m_out.println(logContent);
}
} // log
private String prettifyLogLine(String logContent) {
final String[] strs = logContent.split("\t");
logContent = "";
for (final String str : strs) {
logContent += prettifyLogEntry(str);
}
return logContent;
}
private String prettifyLogEntry(String str) {
// TODO Q2R intelliJ says \\ can't be used in a range ...
if (str.matches("[\\d-E]+\\.[\\d-E]+")) {
// format as double
if (str.contains("E")) {
if (str.length() > 15) {
final String[] strs = str.split("E");
return " " + strs[0].substring(0, 15 - strs[1].length() - 2) + "E" + strs[1];
} else {
return " ".substring(str.length()) + str;
}
}
final String s1 = str.substring(0, str.indexOf("."));
String s2 = str.substring(str.indexOf(".") + 1);
while (s2.length() < 4) {
s2 = s2 + " ";
}
s2 = s2.substring(0, 4);
str = s1 + "." + s2;
str = " ".substring(str.length()) + str;
} else if (str.length() < 15) {
// format integer, boolean
str = " ".substring(str.length()) + str;
} else {
str = " " + str;
}
int overShoot = str.length() - 15;
while (overShoot > 0 && str.length() > 2 && str.charAt(1) == ' ') {
str = str.substring(1);
overShoot
}
if (overShoot > 0) {
str = str.substring(0, 8) + "_" + str.substring(str.length() - 6);
}
return str;
}
/**
* stop logging, produce end of log message and close file (if necessary) *
*/
public void close() {
for (final Loggable m_logger : loggerList) {
m_logger.close(m_out);
}
if (m_out != System.out) {
// close all file, except stdout
m_out.close();
}
} // close
public PrintStream getM_out() {
return m_out;
}
public static long getSampleOffset() {
return sampleOffset < 0 ? 0 : sampleOffset;
}
public void setPrintStream(PrintStream m_out_alt){
m_out = new PrintStream(m_out_alt);
}
public PrintStream getPrintStream(){
PrintStream m_out_alt = new PrintStream(m_out);
return m_out_alt;
}
// Returns the file name
public String getFileName() {
return fileName;
}
} // class Logger |
package ch.openech.mj.db;
import java.sql.SQLException;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.minimalj.backend.db.DbPersistence;
import org.minimalj.backend.db.ImmutableTable;
import org.minimalj.backend.db.Table;
import ch.openech.model.common.Address;
import ch.openech.model.common.CountryIdentification;
import ch.openech.model.person.Occupation;
import ch.openech.model.person.Person;
import ch.openech.model.types.MrMrs;
import ch.openech.model.types.Sex;
public class DbPersonCrudTest {
private static DbPersistence persistence;
@BeforeClass
public static void setupDb() throws SQLException {
persistence = new DbPersistence(DbPersistence.embeddedDataSource(), Person.class);
}
@Test
public void testCrud() throws SQLException {
ImmutableTable<Address> addressTable = persistence.getImmutableTable(Address.class);
Address address = new Address();
address.street = "Grütstrasse";
address.mrMrs = MrMrs.Herr;
address.houseNumber.houseNumber = "10";
address.town = "Jona";
address.country = "CH";
long id = addressTable.getId(address);
Address readAddress = (Address)addressTable.read(id);
Assert.assertEquals(address.mrMrs, readAddress.mrMrs);
Assert.assertEquals(address.street, readAddress.street);
Assert.assertEquals(address.houseNumber.houseNumber, readAddress.houseNumber.houseNumber);
Assert.assertEquals(address.country, readAddress.country);
long id2 = addressTable.getId(address);
Assert.assertEquals(id, id2);
readAddress.houseNumber.houseNumber = "11";
long id3 = addressTable.getId(readAddress);
Assert.assertNotSame(id, id3);
}
@Test
public void testCrudCountry() throws SQLException {
ImmutableTable<CountryIdentification> countryTable = persistence.getImmutableTable(CountryIdentification.class);
CountryIdentification country = new CountryIdentification();
country.countryId = null;
country.countryIdISO2 = "DE";
country.countryNameShort = "Deutschland";
long id = countryTable.getId(country);
CountryIdentification readCountry = (CountryIdentification)countryTable.read(id);
Assert.assertEquals(country.countryId, readCountry.countryId);
Assert.assertEquals(country.countryIdISO2, readCountry.countryIdISO2);
Assert.assertEquals(country.countryNameShort, readCountry.countryNameShort);
long id2 = countryTable.getId(country);
Assert.assertEquals(id, id2);
readCountry.countryIdISO2 = "GE";
long id3 = countryTable.getId(readCountry);
Assert.assertNotSame(id, id3);
}
@Test
public void testCrudPerson() throws SQLException {
Table<Person> personTable = persistence.getTable(Person.class);
Person person = new Person();
person.officialName = "Eberhard";
person.firstName = "Bruno";
person.dateOfBirth.value = "1974-08-02";
person.vn.value = "123";
person.sex = Sex.maennlich;
person.aliasName = "Biwi";
long id = personTable.insert(person);
Person readPerson = (Person)personTable.read(id);
Assert.assertEquals(person.officialName, readPerson.officialName);
Assert.assertEquals(person.aliasName, readPerson.aliasName);
readPerson.aliasName = "Biwidus";
personTable.update(readPerson);
Person readPerson2 = (Person)personTable.read(id);
Assert.assertEquals(readPerson.aliasName, readPerson2.aliasName);
}
@Test
public void testInsertPerson2() throws SQLException {
Table<Person> personTable = persistence.getTable(Person.class);
Person person = new Person();
person.officialName = "Eberhard";
person.firstName = "Bruno";
person.dateOfBirth.value = "1974-08-02";
person.vn.value = "123";
person.sex = Sex.maennlich;
Occupation occupation = new Occupation();
occupation.jobTitle = "Gango";
person.occupation.add(occupation);
Occupation occupation2 = new Occupation();
occupation2.jobTitle = "Holmir";
Address address = new Address();
address.addressLine1 = "Ne Linie";
address.houseNumber.dwellingNumber = "5";
address.town = "Jona";
occupation2.placeOfEmployer = address;
person.occupation.add(occupation2);
long id = personTable.insert(person);
Person readPerson = personTable.read(id);
Assert.assertEquals(2, readPerson.occupation.size());
Occupation readOccupation1 = readPerson.occupation.get(0);
Assert.assertEquals(occupation.jobTitle, readOccupation1.jobTitle);
Occupation readOccupation2 = readPerson.occupation.get(1);
Assert.assertEquals(occupation2.placeOfEmployer.houseNumber.dwellingNumber, readOccupation2.placeOfEmployer.houseNumber.dwellingNumber);
Assert.assertEquals(occupation2.placeOfEmployer.addressLine1, readOccupation2.placeOfEmployer.addressLine1);
}
@Test
public void testUpdatePerson() throws SQLException {
Table<Person> personTable = persistence.getTable(Person.class);
Person person = new Person();
person.officialName = "Eberhard";
person.firstName = "Bruno";
person.dateOfBirth.value = "1974-08-02";
person.vn.value = "123";
person.sex = Sex.maennlich;
Occupation occupation = new Occupation();
occupation.jobTitle = "Gango";
person.occupation.add(occupation);
Occupation occupation2 = new Occupation();
occupation2.jobTitle = "Holmir";
Address address = new Address();
address.addressLine1 = "Ne Linie";
address.houseNumber.dwellingNumber = "5";
address.town = "Jona";
occupation2.placeOfEmployer = address;
person.occupation.add(occupation2);
long id = personTable.insert(person);
Person readPerson = personTable.read(id);
readPerson.aliasName = "biwi";
readPerson.occupation.remove(1);
personTable.update(readPerson);
Person readPerson2 = personTable.read(id);
Assert.assertEquals("biwi", readPerson2.aliasName);
Assert.assertEquals(1, readPerson2.occupation.size());
}
@Test
public void testUpdateSubTable() throws SQLException {
Table<Person> personTable = persistence.getTable(Person.class);
Person person = new Person();
person.officialName = "Eberhard";
person.firstName = "Bruno";
person.dateOfBirth.value = "1974-08-02";
person.vn.value = "123";
person.sex = Sex.maennlich;
Occupation occupation = new Occupation();
occupation.jobTitle = "Gango";
person.occupation.add(occupation);
Occupation occupation2 = new Occupation();
occupation2.jobTitle = "Holmir";
Address address = new Address();
address.addressLine1 = "Ne Linie";
address.houseNumber.dwellingNumber = "5";
address.town = "Jona";
occupation2.placeOfEmployer = address;
person.occupation.add(occupation2);
long id = personTable.insert(person);
Person readPerson = personTable.read(id);
Occupation readOccupation2 = readPerson.occupation.get(1);
readOccupation2.placeOfEmployer.addressLine1 = "Ne andere Line";
personTable.update(readPerson);
Person readPerson2 = personTable.read(id);
Assert.assertEquals(readOccupation2.placeOfEmployer.addressLine1, readPerson2.occupation.get(1).placeOfEmployer.addressLine1);
}
@Test
public void testChangePersonIdentification() throws SQLException {
Table<Person> personTable = persistence.getTable(Person.class);
Person person = new Person();
person.officialName = "Eberhard";
person.firstName = "Bruno";
person.dateOfBirth.value = "1974-08-02";
person.vn.value = "123";
person.sex = Sex.maennlich;
long id = personTable.insert(person);
Person readPerson = personTable.read(id);
readPerson.officialName = "Äberhard";
personTable.update(readPerson);
Person readPerson2 = personTable.read(id);
Assert.assertEquals(readPerson.officialName, readPerson2.officialName);
readPerson2.officialName = "Eberhardt";
personTable.update(readPerson2);
Person readPerson3 = personTable.read(id);
Assert.assertEquals(readPerson2.officialName, readPerson3.officialName);
}
@Test
public void testMaxPerson() throws SQLException {
int startMaxId = persistence.execute(Integer.class, "select max(id) from Person");
Table<Person> personTable = persistence.getTable(Person.class);
Person person = new Person();
person.officialName = "Eberhard";
person.firstName = "Bruno";
person.dateOfBirth.value = "1974-08-02";
person.vn.value = "123";
person.sex = Sex.maennlich;
person.aliasName = "Biwi";
personTable.insert(person);
int afterInsertMaxId = persistence.execute(Integer.class, "select max(id) from Person");
Assert.assertEquals(startMaxId + 1, afterInsertMaxId);
}
} |
import java.util.Vector;
import java.util.Hashtable;
import java.util.Date;
import org.tigris.subversion.lib.*;
/**
* This classed is used for the unit tests. All of the C helper
* functions for the Java Subversion binding should be reached
* with this class.
*
* Sometimes this is not possible, because
* the class needs non-trivial native parameters. In this case
* either simple type parameters are used or the methode
* here designs a special case with no parameter
*/
public class NativeWrapper
{
static
{
System.loadLibrary("svn_jni_nativewrapper");
}
/**
* Calls the function "vector__create" (vector.h)
*
* @return new, empty Vector instance
*/
public static native Vector vectorCreate();
/**
* Calls the function "vector__add" (vector.h)
*
* @param vector instance of a vector that should be used for
* the operation
* @param object
*/
public static native void vectorAdd(Vector vector, Object object);
/**
* Create a new date from a long value.
*
* @param date milliseconds since Januar 1, 1970 00:00:00
*/
public static native Date dateCreate(long date);
/**
* wrapper for function "date__create_from_apr_time_t" (date.h)
*/
public static native Date dateCreateFromAprTimeT(long time);
/**
* wrapper for function "entry__create" (entry.h)
*/
public static native Entry entryCreate();
/**
* wrapper for function "entry__create_from_svn_wc_entry_t" (entry.h)
* this function takes the entry parameter, converts it to
* a svn_wc_entry_t and uses this to call the function...
*/
public static native Entry entryCreateFromSvnWcEntryT(Entry entry);
/**
* wrapper for function "entry__set_url" (entry.h)
*/
public static native void entrySetUrl(Entry entry, String url);
/**
* wrapper for function "entry__get_url" (entry.h)
*/
public static native String entryGetUrl(Entry entry);
/**
* wrapper for "entry__set_revision" (entry.h)
*/
public static native void entrySetRevision(Entry entry, Revision revision);
/**
* wrapper for "entry__get_revision" (entry.h)
*/
public static native Revision entryGetRevision(Entry entry);
/**
* wrapper for "entry__set_kind" (entry.h)
*/
public static native void entrySetKind(Entry entry, Nodekind kind);
/**
* wrapper for "entry__get_kind" (entry.h)
*/
public static native Nodekind entryGetKind(Entry entry);
/**
* wrapper for "entry__set_schedule" (entry.h)
*/
public static native void entrySetSchedule(Entry entry, Schedule schedule);
/**
* wrapper for "entry__get_schedule" (entry.h)
*/
public static native Schedule entryGetSchedule(Entry entry);
/**
* wrapper for "entry__set_conflicted" (entry.h)
*/
public static native void entrySetConflicted(Entry entry, boolean conflicted);
/**
* wrapper for "entry__get_conflicted" (entry.h)
*/
public static native boolean entryGetConflicted(Entry entry);
/**
* wrapper for "entry__set_copied" (entry.h)
*/
public static native void entrySetCopied(Entry entry, boolean copied);
/**
* wrapper for "entry__get_copied (entry.h)
*/
public static native boolean entryGetCopied(Entry entry);
/**
* wrapper for "entry__set_texttime" (entry.h)
*/
public static native void entrySetTexttime(Entry entry, Date texttime);
/**
* wrapper for "entry__get_texttime" (entry.h)
*/
public static native Date entryGetTexttime(Entry entry);
/**
* wrapper for "entry__set_proptime" (entry.h)
*/
public static native void entrySetProptime(Entry entry, Date proptime);
/**
* wrapper for "entry__get_proptime" (entry.h)
*/
public static native Date entryGetProptime(Entry entry);
/**
* wrapper for "entry__set_attributes" (entry.h)
*/
public static native void entrySetAttributes(Entry entry, Hashtable attributes);
/**
* wrapper for "entry__get_attributes" (entry.h)
*/
public static native Hashtable entryGetAttributes(Entry entry);
/**
* wrapper for function "hashtable__create" (hashtable.h)
*/
public static native Hashtable hashtableCreate();
/**
* wrapper for function "hashtable__put" (hashtable.h)
*/
public static native void hashtablePut(Hashtable hashtable, Object key, Object value);
/**
* wrapper for function "misc__throw_exception_by_name" (misc.h)
*/
public static native void miscThrowExceptionByName(String name, String msg);
/**
* wrapper for function "status__create" (status.h)
*/
public static native Status statusCreate();
/**
* wrapper for function "status__set_entry" (status.h)
*/
public static native void statusSetEntry(Status status, Entry entry);
/**
* wrapper for function "status__set_text_status" (status.h)
*/
public static native void statusSetTextStatus(Status status, StatusKind text_status);
/**
* wrapper for function "status__set_prop_status" (status.h)
*/
public static native void statusSetPropStatus(Status status, StatusKind prop_status);
/**
* wrapper for function "status__set_copied" (status.h)
*/
public static native void statusSetCopied(Status status, boolean copied);
/**
* wrapper for function "status__set_locked" (status.h)
*/
public static native void statusSetLocked(Status status, boolean locked);
/**
* wrapper for function "status__set_repos_text_status" (status.h)
*/
public static native void statusSetReposTextStatus(Status status, StatusKind repos_text_status);
/**
* wrapper for function "status__set_repos_prop_status" (status.h)
*/
public static native void statusSetReposPropStatus(Status status, StatusKind repos_prop_status);
/**
* wrapper for function "nodekind__create" (nodekind.h)
*/
public static native Nodekind nodekindCreate(int kind);
/**
* wrapper for function "revision__create" (revision.h)
*/
public static native Revision revisionCreate(long rev);
/**
* wrapper for function "statuskind__create" (statuskind.h)
*/
public static native StatusKind statuskindCreate(int kind);
} |
package org.joni.test;
import java.util.Arrays;
import org.jcodings.Encoding;
import org.jcodings.specific.UTF8Encoding;
import org.joni.Option;
import org.joni.Syntax;
public class TestU8 extends Test {
@Override
public int option() {
return Option.DEFAULT;
}
@Override
public Encoding encoding() {
return UTF8Encoding.INSTANCE;
}
@Override
public String testEncoding() {
return "utf-8";
}
@Override
public Syntax syntax() {
return Syntax.TEST;
}
@Override
public void test() throws Exception {
xx("^\\d\\d\\d-".getBytes(), new byte []{-30, -126, -84, 48, 45}, 0, 0, 0, true);
x2s("x{2}", "xx", 0, 2, Option.IGNORECASE);
x2s("x{2}", "XX", 0, 2, Option.IGNORECASE);
x2s("x{3}", "XxX", 0, 3, Option.IGNORECASE);
ns("x{2}", "x", Option.IGNORECASE);
ns("x{2}", "X", Option.IGNORECASE);
byte[] pat = new byte[] {(byte)227, (byte)131, (byte)160, (byte)40, (byte)46, (byte)41};
byte[] str = new byte[]{(byte)227, (byte)130, (byte)185, (byte)227, (byte)131, (byte)145, (byte)227, (byte)131, (byte)160, (byte)227, (byte)131, (byte)143, (byte)227, (byte)131, (byte)179, (byte)227, (byte)130, (byte)175};
x2(pat, str, 6, 12);
x2s("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0, 35, Option.IGNORECASE);
x2s("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 0, 35, Option.IGNORECASE);
x2s("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaaaAAAAAAAAAAAAAAAAA", 0, 35, Option.IGNORECASE);
pat = new byte[]{94, 40, (byte)239, (byte)188, (byte)161, 41, 92, 49, 36};
str = new byte[]{(byte)239, (byte)188, (byte)161, 65};
n(pat, str, Option.IGNORECASE);
pat = new byte[]{94, (byte)195, (byte)159, 123, 50, 125, 36};
str = new byte[]{(byte)195, (byte)159, 115, 115};
x2(pat, str, 0, 4, Option.IGNORECASE);
String str2 = new String(new byte[]{-61, -123, -61, -123});
String pat2 = new String(new byte[]{'^', -61, -123, '{', '2', '}', '$'});
// x2s(pat2, str2, 4, 4);
// x2s(pat2, str2, 4, 4, Option.IGNORECASE);
ns("(?i-mx:ak)a", "ema");
x2s("(?i:!\\[CDAT)", "![CDAT", 0, 6);
x2s("(?i:\\!\\[CDAa)", "\\![CDAa", 1, 7);
x2s("(?i:\\!\\[CDAb)", "\\![CDAb", 1, 7);
x2s("\\R", "\u0085", 0, 2);
x2s("\\R", "\u2028", 0, 3);
x2s("\\R", "\u2029", 0, 3);
x2s("\\A\\R\\z", "\r", 0, 1);
x2s("\\A\\R\\z", "\n", 0, 1);
x2s("\\A\\R\\z", "\r\n", 0, 2);
x2s("foo\\b", "foo", 0, 3);
x2s("(x?)x*\\1", "x", 0, 1, Option.IGNORECASE);
x2s("(x?)x*\\k<1+0>", "x", 0, 1, Option.IGNORECASE);
x2s("(?<n>x?)(?<n>x?)\\k<n>", "x", 0, 1, Option.IGNORECASE);
x2s("(?=((?<x>)(\\k<x>)))", "", 0, 0);
x2s("a\\g<0>*z", "aaazzz", 0, 6);
x2s("ab\\Kcd", "abcd", 2, 4);
x2s("ab\\Kc(\\Kd|z)", "abcd", 3, 4);
x2s("ab\\Kc(\\Kz|d)", "abcd", 2, 4);
x2s("(a\\K)*", "aaab", 3, 3);
x3s("(a\\K)*", "aaab", 2, 3, 1);
// x2s("a\\K?a", "aa", 0, 2); // error: differ from perl
x2s("ab(?=c\\Kd)", "abcd", 2, 2); // This behaviour is currently not well defined. (see: perlre)
x2s("(?<=a\\Kb|aa)cd", "abcd", 1, 4);
x2s("(?<=ab|a\\Ka)cd", "abcd", 2, 4);
x2s("\\X", "\n", 0, 1);
x2s("\\X", "\r", 0, 1);
x2s("\\X{3}", "\r\r\n\n", 0, 4);
x2s("\\X", "\u306F\u309A\n", 0, 6);
x2s("\\A\\X\\z", "\u0020\u200d", 0, 4);
x2s("\\A\\X\\z", "\u0600\u0600", 0, 4);
x2s("\\A\\X\\z", "\u0600\u0020", 0, 3);
x2s("\\A\\X\\z", " ", 0, 4);
x2s("\\A\\X\\z", "", 0, 4);
x2s("\\A\\X\\z", "", 0, 2);
x2s("\\A\\X\\z", "", 0, 7);
x2s("\\A\\X\\z", "", 0, 4);
x2s("\\A\\X\\z", " ̈", 0, 3); // u{1f600}
// u{20 200d}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)32, (byte)226, (byte)128, (byte)141}, 0, 4);
// u{600 600}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)216, (byte)128, (byte)216, (byte)128}, 0, 4);
// u{600 20}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)216, (byte)128, (byte)32}, 0, 3);
// u{261d 1F3FB}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)226, (byte)152, (byte)157, (byte)240, (byte)159, (byte)143, (byte)187}, 0, 7);
// u{1f600}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)240, (byte)159, (byte)152, (byte)128}, 0, 4);
// u{20 308}
x2s("\\A\\X\\z", " \u0308", 0, 3);
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)32, (byte)204, (byte)136}, 0, 3);
// u{a 308}
x2s("\\A\\X\\z", "a\u0308", 0, 3);
x2("\\A\\X\\X\\z".getBytes(), new byte[] {(byte)10, (byte)204, (byte)136}, 0, 3);
// u{d 308}
x2s("\\A\\X\\z", "d\u0308", 0, 3);
x2("\\A\\X\\X\\z".getBytes(), new byte[] {(byte)13, (byte)204, (byte)136}, 0, 3);
// u{1F477 1F3FF 200D 2640 FE0F}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)240, (byte)159, (byte)145, (byte)183, (byte)240, (byte)159, (byte)143, (byte)191, (byte)226, (byte)128, (byte)141, (byte)226, (byte)153, (byte)128, (byte)239, (byte)184, (byte)143}, 0, 17);
// u{1F468 200D 1F393}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)240, (byte)159, (byte)145, (byte)168, (byte)226, (byte)128, (byte)141, (byte)240, (byte)159, (byte)142, (byte)147}, 0, 11);
// u{1F46F 200D 2642 FE0F}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)240, (byte)159, (byte)145, (byte)175, (byte)226, (byte)128, (byte)141, (byte)226, (byte)153, (byte)130, (byte)239, (byte)184, (byte)143}, 0, 13);
// u{1f469 200d 2764 fe0f 200d 1f469}
x2("\\A\\X\\z".getBytes(), new byte[] {(byte)240, (byte)159, (byte)145, (byte)169, (byte)226, (byte)128, (byte)141, (byte)226, (byte)157, (byte)164, (byte)239, (byte)184, (byte)143, (byte)226, (byte)128, (byte)141, (byte)240, (byte)159, (byte)145, (byte)169}, 0, 20);
x2s("\\A\\X\\X\\z", "\r\u0308", 0, 3);
x2s("\\A\\X\\X\\z", "\n\u0308", 0, 3);
x2s("[0-9-a]+", " 0123456789-a ", 1, 13);
x2s("[0-9-\\s]+", " 0123456789-a ", 0, 12);
x2s("[0-9-\\\\/\u0001]+", " 0123456789-\\/\u0001 ", 1, 18);
x2s("[a-b-]+", "ab-", 0, 3);
x2s("[a-b-&&-]+", "ab-", 2, 3);
x2s("(?i)[a[b-]]+", "ab", 0, 5);
x2s("(?i)[\\d[:^graph:]]+", "0", 0, 1);
x2s("(?ia)[\\d[:^print:]]+", "0", 0, 4);
x2s("(?i:a) B", "a B", 0, 3);
x2s("(?i:a )B", "a B", 0, 3);
x2s("B (?i:a)", "B a", 0, 3);
x2s("B(?i: a)", "B a", 0, 3);
x2s("(?a)[\\p{Space}\\d]", "\u00a0", 0, 2);
x2s("(?a)[\\d\\p{Space}]", "\u00a0", 0, 2);
ns("(?a)[^\\p{Space}\\d]", "\u00a0");
ns("(?a)[^\\d\\p{Space}]", "\u00a0");
x2s("(?d)[[:space:]\\d]", "\u00a0", 0, 2);
ns("(?d)[^\\d[:space:]]", "\u00a0");
x2s("\\p{In_Unified_Canadian_Aboriginal_Syllabics_Extended}+", "\u18B0\u18FF", 0, 6);
x2s("(?i)\u1ffc", "\u2126\u1fbe", 0, 6);
x2s("(?i)\u1ffc", "\u1ff3", 0, 3);
x2s("(?i)\u0390", "\u03b9\u0308\u0301", 0, 6);
x2s("(?i)\u03b9\u0308\u0301", "\u0390", 0, 2);
x2s("(?i)ff", "\ufb00", 0, 3);
x2s("(?i)\ufb01", "fi", 0, 2);
x2s("(?i)\u0149\u0149", "\u0149\u0149", 0, 4);
x2s("(?i)(?<=\u0149)a", "\u02bcna", 3, 4);
x2s("(?<=(?i)ab)cd", "ABcd", 2, 4);
x2s("(?<=(?i)ab)cd", "ABcd", 2, 4);
x2s("(?<=(?i:ab))cd", "ABcd", 2, 4);
ns("(?<=(?i)ab)cd", "ABCD");
ns("(?<=(?i:ab))cd", "ABCD");
x2s("(?<!(?i)ab)cd", "aacd", 2, 4);
x2s("(?<!(?i:ab))cd", "aacd", 2, 4);
ns("(?<!(?i)ab)cd", "ABcd");
ns("(?<!(?i:ab))cd", "ABcd");
// Fullwidth Alphabet
ns("", "");
x2s("(?i)", "", 0, 26 * 3);
x2s("(?i)", "", 0, 26 * 3);
x2s("(?i)", "", 0, 26 * 3);
x2s("(?i)", "", 0, 26 * 3);
// Greek
ns("αβγδεζηθικλμνξοπρστυφχψω", "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ");
x2s("(?i)αβγδεζηθικλμνξοπρστυφχψω", "αβγδεζηθικλμνξοπρστυφχψω", 0, 24 * 2);
x2s("(?i)αβγδεζηθικλμνξοπρστυφχψω", "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ", 0, 24 * 2);
x2s("(?i)ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ", "αβγδεζηθικλμνξοπρστυφχψω", 0, 24 * 2);
x2s("(?i)ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ", "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ", 0, 24 * 2);
// Cyrillic
ns("абвгдеёжзийклмнопрстуфхцчшщъыьэюя", "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ");
x2s("(?i)абвгдеёжзийклмнопрстуфхцчшщъыьэюя", "абвгдеёжзийклмнопрстуфхцчшщъыьэюя", 0, 33 * 2);
x2s("(?i)абвгдеёжзийклмнопрстуфхцчшщъыьэюя", "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", 0, 33 * 2);
x2s("(?i)АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", "абвгдеёжзийклмнопрстуфхцчшщъыьэюя", 0, 33 * 2);
x2s("(?i)АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", 0, 33 * 2);
x2s("(?u)\\w+", "a#", 0, 4);
x2s("(?a)\\w+", "a#", 3, 4);
x2s("(?u)\\W+", "a#", 4, 5);
x2s("(?a)\\W+", "a#", 0, 3);
x2s("(?a)\\b", "a", 3, 3);
x2s("(?a)\\w\\b", "a", 0, 1);
x2s("(?a)\\B", "a ", 2, 2);
x2s("(?u)\\B", " ", 4, 4);
x2s("(?a)\\B", " ", 0, 0);
x2s("(?a)\\B", "a ", 4, 4);
x2s("(?a)a\\b", " a", 1, 2);
x2s("(?u)a\\b", " a", 1, 2);
ns("(?a)a\\B", " a");
ns("(?a)\\b", " ");
x2s("(?u)\\b", " ", 1, 4);
x2s("(?a)\\B", " ", 1, 4);
ns("(?u)\\B", " ");
x2s("(?a)\\p{Alpha}\\P{Alpha}", "a", 0, 4);
x2s("(?u)\\p{Alpha}\\P{Alpha}", "a", 0, 4);
x2s("(?a)[[:word:]]+", "a", 0, 1);
x2s("(?a)[[:^word:]]+", "a", 1, 4);
x2s("(?u)[[:word:]]+", "a", 0, 4);
ns("(?u)[[:^word:]]+", "a");
x2s("(?iu)\\p{lower}\\p{upper}", "Ab", 0, 2);
x2s("(?ia)\\p{lower}\\p{upper}", "Ab", 0, 2);
x2s("(?iu)[[:lower:]][[:upper:]]", "Ab", 0, 2);
x2s("(?ia)[[:lower:]][[:upper:]]", "Ab", 0, 2);
ns("(?ia)\\w+", "\u212a\u017f");
ns("(?ia)[\\w]+", "\u212a\u017f");
ns("(?ia)[^\\W]+", "\u212a\u017f");
x2s("(?ia)[^\\W]+", "ks", 0, 2);
ns("(?iu)\\p{ASCII}", "\u212a");
ns("(?iu)\\P{ASCII}", "s");
ns("(?iu)[\\p{ASCII}]", "\u212a");
ns("(?iu)[\\P{ASCII}]", "s");
ns("(?ia)\\p{ASCII}", "\u212a");
ns("(?ia)\\P{ASCII}", "s");
ns("(?ia)[\\p{ASCII}]", "\u212a");
ns("(?ia)[\\P{ASCII}]", "s");
x2s("(?iu)[s]+", "Ss\u017f ", 0, 4);
x2s("(?ia)[s]+", "Ss\u017f ", 0, 4);
x2s("(?iu)[^s]+", "Ss\u017f ", 4, 5);
x2s("(?ia)[^s]+", "Ss\u017f ", 4, 5);
x2s("(?iu)[[:lower:]]", "\u017f", 0, 2);
ns("(?ia)[[:lower:]]", "\u017f");
x2s("(?u)[[:upper:]]", "\u212a", 0, 3);
ns("(?a)[[:upper:]]", "\u212a");
// ns("x.*\\b", "x");
// x2s("x.*\\B", "x", 0, 1);
x2s("c.*\\b", "abc", 2, 3); // Onigmo
x2s("abc.*\\b", "abc", 0, 3);
x2s("\\b.*abc.*\\b", "abc", 0, 3);
x2s("(?!a).*b", "ab", 1, 2);
x2s("(?!^a).*b", "ab", 1, 2);
x2s("<-(?~->)->", "<- ->->", 0, 5);
x2s("<-(?~->)->\n", "<-1->2<-3->\n", 6, 12);
x2s("<-(?~->)->.*<-(?~->)->", "<-1->2<-3->4<-5->", 0, 17);
x2s("<-(?~->)->.*?<-(?~->)->", "<-1->2<-3->4<-5->", 0, 11);
x2s("(?~abc)c", "abc", 0, 3);
x2s("(?~abc)bc", "abc", 0, 3);
x2s("(?~abc)abc", "abc", 0, 3);
ns("(?~)", "");
ns(" (?~)", " ");
ns(" (?~)", " ");
// x2s("(?~(?~))", "abc", 0, 3);
x2s("(?~a)", "", 0, 0);
x2s("(?~a)a", "a", 0, 1);
x2s("(?~a)", "x", 0, 1);
x2s("(?~a)a", "xa", 0, 2);
x2s("(?~.)", "", 0, 0);
x2s("(?~.)a", "a", 0, 1);
x2s("(?~.)", "x", 0, 0);
x2s("(?~.)a", "xa", 1, 2);
x2s("(?~abc)", "abc", 0, 2);
x2s("(?~b)", "abc", 0, 1);
x2s("(?~abc|b)", "abc", 0, 1);
// ns("(?~|abc)", "abc"); // ?
x2s("(?~abc|)", "abc", 0, 1);
x2s("(?~abc|def)x", "abcx", 1, 4);
x2s("(?~abc|def)x", "defx", 1, 4);
x2s("^(?~\\S+)TEST", "TEST", 0, 4);
x2s("𠜎𠜱", "𠜎𠜱", 0, 8);
x2s("𠜎?𠜱", "𠜎𠜱", 0, 8);
x2s("𠜎*𠜱", "𠜎𠜱", 0, 8);
x2s("𠜎{3}", "𠜎𠜎𠜎", 0, 12);
}
} |
package com.kuxhausen.huemore;
import java.util.ArrayList;
import java.util.PriorityQueue;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.util.Pair;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.kuxhausen.huemore.automation.FireReceiver;
import com.kuxhausen.huemore.network.NetworkMethods;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.InternalArguments;
import com.kuxhausen.huemore.persistence.HueUrlEncoder;
import com.kuxhausen.huemore.state.Event;
import com.kuxhausen.huemore.state.Mood;
import com.kuxhausen.huemore.state.QueueEvent;
import com.kuxhausen.huemore.state.api.BulbState;
import com.kuxhausen.huemore.timing.AlarmReciever;
public class MoodExecuterService extends Service {
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
MoodExecuterService getService() {
// Return this instance of LocalService so clients can call public
// methods
return MoodExecuterService.this;
}
}
MoodExecuterService me = this;
private RequestQueue volleyRQ;
int notificationId = 1337;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
private BulbState[] transientStateChanges = new BulbState[50];
{
for (int i = 0; i < transientStateChanges.length; i++)
transientStateChanges[i] = new BulbState();
}
private boolean[] flagTransientChanges = new boolean[50];
private Pair<Integer[], Mood> moodPair;
private CountDownTimer countDownTimer;
int time;
PriorityQueue<QueueEvent> queue = new PriorityQueue<QueueEvent>();
PriorityQueue<QueueEvent> highPriorityQueue = new PriorityQueue<QueueEvent>();
WakeLock wakelock;
int transientIndex = 0;
public MoodExecuterService() {
}
public void createNotification(String secondaryText) {
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this)
.setSmallIcon(R.drawable.huemore)
.setContentTitle(
this.getResources().getString(R.string.app_name))
.setContentText(secondaryText)
.setContentIntent(resultPendingIntent);
this.startForeground(notificationId, mBuilder.build());
}
public RequestQueue getRequestQueue() {
return volleyRQ;
}
private boolean hasTransientChanges() {
boolean result = false;
for (boolean b : flagTransientChanges)
result |= b;
return result;
}
private void loadMoodIntoQueue() {
Integer[] bulbS = moodPair.first;
Mood m = moodPair.second;
ArrayList<Integer>[] channels = new ArrayList[m.numChannels];
for (int i = 0; i < channels.length; i++)
channels[i] = new ArrayList<Integer>();
for (int i = 0; i < bulbS.length; i++) {
channels[i % m.numChannels].add(bulbS[i]);
}
for (Event e : m.events) {
e.time += (int) System.nanoTime() / 1000000;// divide by 1 million
// to convert to millis
for (Integer bNum : channels[e.channel]) {
QueueEvent qe = new QueueEvent(e);
qe.bulb = bNum;
queue.add(qe);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
volleyRQ = Volley.newRequestQueue(this);
restartCountDownTimer();
createNotification("");
//acquire wakelock
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
wakelock.acquire();
}
@Override
public void onDestroy() {
countDownTimer.cancel();
volleyRQ.cancelAll(InternalArguments.TRANSIENT_NETWORK_REQUEST);
volleyRQ.cancelAll(InternalArguments.PERMANENT_NETWORK_REQUEST);
wakelock.release();
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
//remove any possible launched wakelocks
AlarmReciever.completeWakefulIntent(intent);
FireReceiver.completeWakefulIntent(intent);
String encodedMood = intent
.getStringExtra(InternalArguments.ENCODED_MOOD);
String encodedTransientMood = intent
.getStringExtra(InternalArguments.ENCODED_TRANSIENT_MOOD);
if (encodedMood != null) {
moodPair = HueUrlEncoder.decode(encodedMood);
queue.clear();
loadMoodIntoQueue();
String moodName = intent
.getStringExtra(InternalArguments.MOOD_NAME);
moodName = (moodName == null) ? "Unknown Mood" : moodName;
createNotification(moodName);
} else if (encodedTransientMood != null) {
Pair<Integer[], Mood> decodedValues = HueUrlEncoder
.decode(encodedTransientMood);
Integer[] bulbS = decodedValues.first;
Mood m = decodedValues.second;
ArrayList<Integer>[] channels = new ArrayList[m.numChannels];
for (int i = 0; i < channels.length; i++)
channels[i] = new ArrayList<Integer>();
for (int i = 0; i < bulbS.length; i++) {
channels[i % m.numChannels].add(bulbS[i]);
}
for (Event e : m.events) {
for (Integer bNum : channels[e.channel]) {
BulbState toModify = transientStateChanges[bNum - 1];
toModify.merge(e.state);
if (toModify.toString() != e.state.toString())
flagTransientChanges[bNum - 1] = true;
}
}
}
}
restartCountDownTimer();
return super.onStartCommand(intent, flags, startId);
}
public void restartCountDownTimer() {
if (countDownTimer != null)
countDownTimer.cancel();
// runs at the rate to execute 15 op/sec
countDownTimer = new CountDownTimer(Integer.MAX_VALUE, (1000 / 15)) {
@Override
public void onFinish() {
}
@Override
public void onTick(long millisUntilFinished) {
Log.e("executor",
"highPriorityQueue:" + highPriorityQueue.size()
+ " queue:" + queue.size());
if (highPriorityQueue.peek() != null) {
QueueEvent e = highPriorityQueue.poll();
NetworkMethods.PreformTransmitGroupMood(getRequestQueue(),
me, null, e.bulb, e.state);
} else if (hasTransientChanges()) {
boolean addedSomethingToQueue = false;
while (!addedSomethingToQueue) {
if (flagTransientChanges[transientIndex]) {
// Note the +1 to account for the 1-based real bulb
// numbering
NetworkMethods.PreformTransmitGroupMood(
getRequestQueue(), me, null,
transientIndex + 1,
transientStateChanges[transientIndex]);
flagTransientChanges[transientIndex] = false;
addedSomethingToQueue = true;
}
transientIndex = (transientIndex + 1) % 50;
}
} else if (queue.peek() == null) {
if (moodPair != null && moodPair.second.isInfiniteLooping()) {
loadMoodIntoQueue();
} else {
createNotification("");
me.stopSelf();
}
} else if (queue.peek().time <= System.nanoTime() / 1000000) {
ArrayList<QueueEvent> eList = new ArrayList<QueueEvent>();
eList.add(queue.poll());
while (queue.peek() != null
&& queue.peek().compareTo(eList.get(0)) == 0) {
QueueEvent e = queue.poll();
eList.add(e);
}
for (QueueEvent e : eList)
highPriorityQueue.add(e);
}
}
};
countDownTimer.start();
}
} |
package com.heimcontrol.mobile;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.apache.http.Header;
import org.json.*;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import io.socket.*;
import static android.widget.Toast.makeText;
public class Switches extends Activity {
private SocketIO socket;
private String url;
private Context context;
private GPIOArrayAdapter listAdapter;
private ArrayList<GPIO> switchesList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
String key = ((Heimcontrol)getApplicationContext()).user.getKey();
if(switchesList == null)
switchesList = new ArrayList<GPIO>();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
this.url = prefs.getString("heimcontrol_url", "");
if (key.equals("") || this.url.equals(""))
{
CharSequence text = "No key available, please check heimcontrol url in settings and log in.";
int duration = Toast.LENGTH_SHORT;
Toast toast = makeText(context, text, duration);
toast.show();
this.logout();
}
RestClient.setBaseUrl(this.url, this);
setContentView(R.layout.activity_switches);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.commit();
}
this.connectToSocket();
this.setSwitches();
final ListView listview = (ListView) findViewById(R.id.switchesList);
listAdapter = new GPIOArrayAdapter(this, R.layout.fragment_switches, getSwitchesList());
listview.setAdapter(listAdapter);
}
public ArrayList<GPIO> getSwitchesList()
{
if(switchesList == null)
switchesList = new ArrayList<GPIO>();
return switchesList;
}
public void setSwitches()
{
final Switches that = this;
RestClient.get(
"api/gpio/get",
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONArray responseData)
{
try {
ArrayList<GPIO> list = new ArrayList<GPIO>();
for (int i = 0; i < responseData.length(); i++) {
JSONObject obj = responseData.getJSONObject(i);
String id = obj.getString("_id");
String value = obj.getString("value");
String direction = obj.getString("direction");
String description = obj.getString("description");
String pin = obj.getString("pin");
list.add(new GPIO(id, description, direction, isBoolean(value), pin));
}
setSwitches(list);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
if (statusCode == 401) {
that.logout();
}
CharSequence text = "Error " + statusCode + " while fetching toggles";
int duration = Toast.LENGTH_SHORT;
Toast toast = makeText(context, text, duration);
toast.show();
}
}
);
}
private synchronized void setSwitches(ArrayList<GPIO> list)
{
getSwitchesList().clear();
getSwitchesList().addAll(list);
listAdapter.notifyDataSetChanged();
}
private synchronized void refreshList()
{
this.setSwitches();
}
public void notifyHeimcontrol(GPIO obj, boolean on)
{
if(!socket.isConnected())
connectToSocket();
String value = "0";
if(obj.getValue())
{
value = "1";
}else
{
value = "0";
}
obj.setValue(!obj.getValue());
JSONObject params = new JSONObject();
try {
params.put("value", value);
params.put("id", obj.get_id());
} catch (JSONException e) {
e.printStackTrace();
}
socket.emit("gpio-toggle", params);
}
public void logout()
{
((Heimcontrol) getApplicationContext()).user.setKey("");
Intent intent = new Intent(this, Login.class);
startActivity(intent);
// finish the Switches Activity, so that we have no entry in the history
finish();
}
public void connectToSocket()
{
if(socket != null && socket.isConnected())
return;
try {
String authKey = User.getKey();
socket = new SocketIO(this.url);
socket.addHeader("authorization", authKey);
} catch (MalformedURLException e) {
e.printStackTrace();
}
socket.connect(new IOCallback() {
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println(data);
}
@Override
public void onError(SocketIOException socketIOException) {
/*CharSequence text = "Socketio error occurred";
int duration = Toast.LENGTH_SHORT;
Toast toast = makeText(context, text, duration);
toast.show();
socketIOException.printStackTrace();*/
}
@Override
public void onDisconnect() {
}
@Override
public void onConnect() {
System.out.println("Connection established");
}
@Override
public void on(String event, IOAcknowledge ack, Object... args)
{
JSONObject incoming = (JSONObject) args[0];
String id = null;
String value = null;
try {
id = incoming.getString("id");
value = incoming.getString("value");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < switchesList.size(); i++)
{
if(switchesList.get(i).get_id().equals(id))
{
switchesList.get(i).setValue(isBoolean(value));
switchesList.get(i).setDescription("blah");
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
copySwitchesList(switchesList);
}
});
}
});
}
//This is an ugly hack
private synchronized void copySwitchesList(ArrayList<GPIO> switches)
{
ArrayList<GPIO> s = new ArrayList<GPIO>();
s.addAll(switches);
this.setSwitches(s);
}
private synchronized boolean isBoolean(String value)
{
boolean val;
if(value.equals("0"))
{
val = false;
}else
{
val = true;
}
return val;
}
private synchronized void toastit(String ttext)
{
CharSequence text = ttext;
int duration = Toast.LENGTH_LONG;
Toast toast = makeText(context, text, duration);
toast.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.switches, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
if (id == R.id.action_logout) {
this.logout();
return true;
}
if (id == R.id.action_refresh) {
this.refreshList();
this.connectToSocket();
return true;
}
return super.onOptionsItemSelected(item);
}
private class GPIOArrayAdapter extends ArrayAdapter<GPIO> {
List<GPIO> objects;
public GPIOArrayAdapter(Context context, int textViewResourceId,
List<GPIO> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
GPIOHolder holder = null;
GPIO pos = objects.get(position);
if(row == null)
{
LayoutInflater inflater = ((Activity)getContext()).getLayoutInflater();
row = inflater.inflate(R.layout.fragment_switches, parent, false);
holder = new GPIOHolder();
holder.pin = (TextView)row.findViewById(R.id.pin);
holder.description = (TextView)row.findViewById(R.id.description);
row.setTag(holder);
holder.description.setText(pos.getDescription());
holder.pin.setText(pos.getPin());
Switch sswitch = (Switch)row.findViewById(R.id.pinSwitch);
sswitch.setChecked(pos.getValue());
sswitch.setTag(pos);
sswitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
GPIO item = (GPIO) buttonView.getTag();
notifyHeimcontrol(item, isChecked);
}
});
}
else
{
holder = (GPIOHolder)row.getTag();
Switch sswitch = (Switch)row.findViewById(R.id.pinSwitch);
//sswitch.setChecked(pos.getValue());
}
return row;
}
}
static class GPIOHolder
{
TextView _id;
TextView description;
TextView direction;
TextView value;
TextView pin;
}
} |
package com.ls.ui.adapter;
import com.ls.drupalcon.R;
import com.ls.drupalcon.app.App;
import com.ls.drupalcon.model.data.Event;
import com.ls.drupalcon.model.data.Level;
import com.ls.drupalcon.model.data.Type;
import com.ls.ui.adapter.item.BofsItem;
import com.ls.ui.adapter.item.EventListItem;
import com.ls.ui.adapter.item.HeaderItem;
import com.ls.ui.adapter.item.ProgramItem;
import com.ls.ui.adapter.item.SocialItem;
import com.ls.ui.adapter.item.TimeRangeItem;
import com.ls.ui.drawer.DrawerManager;
import com.ls.utils.DateUtils;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class EventsAdapter extends BaseAdapter {
private static final int TYPE_COUNT = 5;
private static final int SINGLE_LINE_COUNT = 1;
private static final int MULTI_LINE_COUNT = 3;
private Context mContext;
private List<EventListItem> mData;
private LayoutInflater mInflater;
private DrawerManager.EventMode mEventMode;
private Listener mListener;
public interface Listener {
void onClick(int position);
}
public EventsAdapter(Context context) {
mContext = context;
mInflater = LayoutInflater.from(context);
mData = new ArrayList<>();
}
@Override
public int getItemViewType(int position) {
return mData.get(position).getAdapterType();
}
@Override
public int getViewTypeCount() {
return TYPE_COUNT;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public EventListItem getItem(int position) {
return this.mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void setData(List<EventListItem> data, DrawerManager.EventMode mode) {
mData.clear();
mData.addAll(data);
mEventMode = mode;
notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
View resultView;
int itemViewType = getItemViewType(position);
if (itemViewType == EventListItem.TYPE_TIME_RANGE) {
resultView = initTimeRangeView(position, convertView, parent);
// } else if (itemViewType == EventListItem.TYPE_BOFS) {
// resultView = initBofsView(position, convertView, parent);
// } else if (itemViewType == EventListItem.TYPE_PROGRAM) {
// resultView = initProgramView(position, convertView, parent);
// } else if (itemViewType == EventListItem.TYPE_SOCIAL) {
// resultView = initSocialView(position, convertView, parent);
} else if (itemViewType == EventListItem.TYPE_SECTION_NAME) {
resultView = initSectionNameView(position, convertView, parent);
} else {
resultView = new View(mInflater.getContext());
}
return resultView;
}
public void setOnItemClickListener(Listener listener) {
mListener = listener;
}
public View initTimeRangeView(final int position, View convertView, ViewGroup parent) {
View resultView = convertView;
EventHolder holder;
if (resultView == null) {
resultView = mInflater.inflate(R.layout.item_event, parent, false);
holder = createEventHolder(resultView);
resultView.setTag(holder);
} else {
holder = (EventHolder) resultView.getTag();
}
TimeRangeItem timeRange = (TimeRangeItem) getItem(position);
Event event = timeRange.getEvent();
fillDate(holder, event);
fillIcon(holder, event.getType());
fillEventInfo(holder, event, timeRange.getTrack(), timeRange.getSpeakers());
fillDivider(holder, timeRange.isFirst());
fillFavorite(holder);
fillEventClickAbility(holder.layoutRoot, holder.txtPlace, event, position);
return resultView;
}
// public View initBofsView(final int position, View convertView, ViewGroup parent) {
// View resultView = convertView;
// EventHolder holder;
// if (resultView == null) {
// resultView = mInflater.inflate(R.layout.item_event, parent, false);
// holder = createEventHolder(resultView);
// resultView.setTag(holder);
// } else {
// holder = (EventHolder) resultView.getTag();
// BofsItem bofsItem = (BofsItem) getItem(position);
// Event event = bofsItem.getEvent();
// fillIcon(holder, event.getType());
// fillEventInfo(holder, event, null, bofsItem.getSpeakers());
// fillEventClickAbility(holder.layoutRoot, holder.txtPlace, event, position);
// fillDivider(holder, !bofsItem.isLast());
// return resultView;
// public View initProgramView(final int position, View convertView, ViewGroup parent) {
// View resultView = convertView;
// EventHolder holder;
// if (resultView == null) {
// resultView = mInflater.inflate(R.layout.item_event, parent, false);
// holder = createEventHolder(resultView);
// resultView.setTag(holder);
// resultView.setTag(holder);
// } else {
// holder = (EventHolder) resultView.getTag();
// ProgramItem programItem = (ProgramItem) getItem(position);
// Event event = programItem.getEvent();
// fillEventInfo(holder, event, programItem.getTrack(), programItem.getSpeakers());
// fillIcon(holder, event.getType());
// fillDivider(holder, !programItem.isLast());
// fillEventClickAbility(holder.layoutRoot, holder.txtPlace, event, position);
// return resultView;
// private View initSocialView(final int position, View convertView, ViewGroup parent) {
// View resultView = convertView;
// EventHolder holder;
// if (resultView == null) {
// resultView = mInflater.inflate(R.layout.item_event, parent, false);
// holder = createEventHolder(resultView);
// resultView.setTag(holder);
// resultView.setTag(holder);
// } else {
// holder = (EventHolder) resultView.getTag();
// SocialItem socialItem = (SocialItem) getItem(position);
// Event event = socialItem.getEvent();
// fillIcon(holder, event.getType());
// fillEventInfo(holder, event, null, socialItem.getSpeakers());
// fillEventClickAbility(holder.layoutRoot, holder.txtPlace, event, position);
// return resultView;
public View initSectionNameView(int position, View convertView, ViewGroup parent) {
View resultView = convertView;
HeaderHolder holder;
if (resultView == null) {
resultView = mInflater.inflate(R.layout.item_header, parent, false);
holder = new HeaderHolder();
holder.txtTitle = (TextView) resultView.findViewById(R.id.txtTitle);
resultView.setTag(holder);
} else {
holder = (HeaderHolder) resultView.getTag();
}
HeaderItem item = (HeaderItem) getItem(position);
holder.txtTitle.setText(item.getTitle());
holder.txtTitle.setVisibility(View.VISIBLE);
return resultView;
}
private void fillDate(EventHolder holder, Event event) {
String fromTime = DateUtils.getInstance().getTime(mContext, event.getFromMillis());
String toTime = DateUtils.getInstance().getTime(mContext, event.getToMillis());
if (!TextUtils.isEmpty(fromTime) && !TextUtils.isEmpty(toTime)) {
holder.txtFrom.setText(fromTime);
holder.txtTo.setText(String.format(mContext.getString(R.string.to), toTime));
} else {
holder.txtFrom.setText(App.getContext().getString(R.string.twenty_four_hours));
holder.txtFrom.setTextSize(TypedValue.COMPLEX_UNIT_PX, App.getContext().getResources().getDimension(R.dimen.text_size_micro));
holder.txtTo.setText(App.getContext().getString(R.string.access));
}
holder.txtFrom.setVisibility(View.VISIBLE);
holder.txtTo.setVisibility(View.VISIBLE);
}
private void fillIcon(EventHolder holder, long type) {
if (Type.getIcon(type) != 0) {
holder.icon.setVisibility(View.VISIBLE);
holder.icon.setImageResource(Type.getIcon(type));
} else {
holder.icon.setVisibility(View.GONE);
}
}
private void fillEventInfo(EventHolder holder, Event event, @Nullable String track, @Nullable List<String> speakerNameList) {
holder.txtTitle.setText(event.getName());
if (event.isFavorite()) {
holder.txtTitle.setTextColor(mContext.getResources().getColor(R.color.link));
} else {
holder.txtTitle.setTextColor(mContext.getResources().getColor(R.color.black_100));
}
if (!TextUtils.isEmpty(event.getPlace())) {
holder.txtPlace.setText(event.getPlace());
holder.layoutPlace.setVisibility(View.VISIBLE);
} else {
holder.layoutPlace.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(track)) {
holder.txtTrack.setText(track);
holder.txtTrack.setVisibility(View.VISIBLE);
} else {
holder.txtTrack.setVisibility(View.GONE);
}
if (speakerNameList != null && !speakerNameList.isEmpty()) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < speakerNameList.size(); i++) {
String name = speakerNameList.get(i);
builder.append(name);
if (i < speakerNameList.size() - 1) {
builder.append(mContext.getString(R.string.speaker_separator));
}
}
holder.txtSpeakers.setText(builder.toString());
holder.layoutSpeakers.setVisibility(View.VISIBLE);
} else {
holder.layoutSpeakers.setVisibility(View.GONE);
}
holder.expIcon.setImageResource(Level.getIcon(event.getExperienceLevel()));
}
private void fillDivider(EventHolder holder, boolean isFirst) {
if (isFirst) {
holder.divider.setVisibility(View.GONE);
holder.marginDivider.setVisibility(View.VISIBLE);
} else {
holder.divider.setVisibility(View.VISIBLE);
holder.marginDivider.setVisibility(View.GONE);
}
}
private void fillFavorite(EventHolder holder) {
if (mEventMode == DrawerManager.EventMode.Favorites) {
holder.layoutTime.setBackgroundColor(Color.TRANSPARENT);
} else {
holder.layoutTime.setBackgroundColor(mContext.getResources().getColor(R.color.grey_400_trans));
}
}
private void fillEventClickAbility(View layoutRoot, TextView txtPlace, Event event, final int position) {
Context context = layoutRoot.getContext();
layoutRoot.setBackgroundResource(R.drawable.selector_light);
txtPlace.setMaxLines(SINGLE_LINE_COUNT);
long eventType = event.getType();
if (eventType == Type.FREE_SLOT || eventType == Type.COFFEBREAK || eventType == Type.LUNCH || eventType == Type.REGISTRATION) {
layoutRoot.setBackgroundColor(context.getResources().getColor(R.color.black_20_trans));
txtPlace.setMaxLines(MULTI_LINE_COUNT);
layoutRoot.setClickable(false);
} else {
layoutRoot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onClick(position);
}
});
}
}
private static class HeaderHolder {
TextView txtTitle;
}
private EventHolder createEventHolder(View resultView) {
EventHolder holder = new EventHolder();
holder.layoutRoot = (LinearLayout) resultView.findViewById(R.id.layoutRoot);
holder.layoutTime = (LinearLayout) resultView.findViewById(R.id.timeLayout);
holder.divider = resultView.findViewById(R.id.divider);
holder.marginDivider = resultView.findViewById(R.id.margin_divider);
holder.icon = (ImageView) resultView.findViewById(R.id.imgEventIcon);
holder.expIcon = (ImageView) resultView.findViewById(R.id.imgExperience);
holder.txtTitle = (TextView) resultView.findViewById(R.id.txtTitle);
holder.txtFrom = (TextView) resultView.findViewById(R.id.txtFrom);
holder.txtTo = (TextView) resultView.findViewById(R.id.txtTo);
holder.layoutSpeakers = (LinearLayout) resultView.findViewById(R.id.layout_speakers);
holder.layoutPlace = (LinearLayout) resultView.findViewById(R.id.layout_place);
holder.txtSpeakers = (TextView) resultView.findViewById(R.id.txtSpeakers);
holder.txtTrack = (TextView) resultView.findViewById(R.id.txtTrack);
holder.txtPlace = (TextView) resultView.findViewById(R.id.txtPlace);
return holder;
}
private static class EventHolder {
LinearLayout layoutRoot;
ImageView icon;
ImageView expIcon;
View divider;
View marginDivider;
LinearLayout layoutTime;
LinearLayout layoutSpeakers;
LinearLayout layoutPlace;
TextView txtSpeakers;
TextView txtTrack;
TextView txtFrom;
TextView txtTo;
TextView txtTitle;
TextView txtPlace;
}
} |
package org.redcross.openmapkit;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.widget.Toast;
import com.mapbox.mapboxsdk.tileprovider.tilesource.MBTilesLayer;
import com.mapbox.mapboxsdk.tileprovider.tilesource.WebSourceTileLayer;
import com.mapbox.mapboxsdk.views.MapView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Basemap {
private static final String PREVIOUS_BASEMAP = "org.redcross.openmapkit.PREVIOUS_BASEMAP";
private MapActivity mapActivity;
private MapView mapView;
private Context context;
private static String selectedBasemap;
public Basemap(MapActivity mapActivity) {
this.mapActivity = mapActivity;
this.mapView = mapActivity.getMapView();
this.context = mapActivity.getApplicationContext();
if (selectedBasemap != null) {
addOfflineDataSources(selectedBasemap);
} else if (Connectivity.isConnected(context)) {
addOnlineDataSources();
} else {
presentBasemapsOptions();
}
}
private void addOnlineDataSources() {
//create OSM tile layer
String defaultTilePID = mapActivity.getString(R.string.defaultTileLayerPID);
String defaultTileURL = mapActivity.getString(R.string.defaultTileLayerURL);
String defaultTileName = mapActivity.getString(R.string.defaultTileLayerName);
String defaultTileAttribution = mapActivity.getString(R.string.defaultTileLayerAttribution);
WebSourceTileLayer ws = new WebSourceTileLayer(defaultTilePID, defaultTileURL);
ws.setName(defaultTileName).setAttribution(defaultTileAttribution);
selectedBasemap = null;
//add OSM tile layer to map
mapView.setTileSource(ws);
}
public void presentBasemapsOptions() {
//shared preferences private to mapActivity
final SharedPreferences sharedPreferences = mapActivity.getPreferences(Context.MODE_PRIVATE);
String previousBasemap = sharedPreferences.getString(PREVIOUS_BASEMAP, null);
//create an array of all mbtile options
final List<String> basemaps = new ArrayList<>();
//when device is connected, HOT OSM Basemap is the first option
if(Connectivity.isConnected(context)) {
basemaps.add(mapActivity.getString(R.string.hotOSMOptionTitle));
}
//add mbtiles names from external storage
File[] mbtiles = ExternalStorage.fetchMBTilesFiles();
if (mbtiles.length > 0) {
for (File file : mbtiles) {
String fileName = file.getName();
basemaps.add(fileName);
}
}
if (basemaps.size() == 0) {
Toast prompt = Toast.makeText(context, "Device is offline. Please add .mbtiles file to " + ExternalStorage.getMBTilesDir() + " or check out a deployment.", Toast.LENGTH_LONG);
prompt.show();
return;
}
//create dialog of mbtiles choices
AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity);
builder.setTitle(mapActivity.getString(R.string.mbtilesChooserDialogTitle));
String[] names = basemaps.toArray(new String[basemaps.size()]);
//default mbtiles option is based on previous selections (persisted in shared preferences) or connectivity state of device
int defaultRadioButtonIndex = 0;
if(previousBasemap == null) {
//if user DID NOT previously choose an mbtiles option...
if(Connectivity.isConnected(context)) {
//the first radio button (for HOT OSM) will be selected by default
defaultRadioButtonIndex = 0;
//the default selected option is HOT OSM
selectedBasemap = basemaps.get(0); //default choice
} else {
defaultRadioButtonIndex = -1; //no selected radio button by default
}
} else {
//if user previously chose an mbtiles option ...
for(int i = 0; i < basemaps.size(); ++i) {
String fileName = basemaps.get(i);
if(fileName.equals(previousBasemap)) {
defaultRadioButtonIndex = i;
selectedBasemap = fileName;
}
}
if (selectedBasemap == null) {
selectedBasemap = basemaps.get(0);
}
}
//add choices to dialog
builder.setSingleChoiceItems(names, defaultRadioButtonIndex, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//user tapped on radio button and changed previous choice or default
selectedBasemap = basemaps.get(which);
//add user's choice to shared preferences key
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PREVIOUS_BASEMAP, selectedBasemap);
editor.apply();
}
});
//handle OK tap event of dialog
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//user clicked OK
if(selectedBasemap.equals(mapActivity.getString(R.string.hotOSMOptionTitle))) {
addOnlineDataSources();
} else {
addOfflineDataSources(selectedBasemap);
}
}
});
//handle cancel button tap event of dialog
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//user clicked cancel
}
});
//present dialog to user
builder.show();
}
/**
* For instantiating a map (when the device is offline) and initializing the default mbtiles layer, extent, and zoom level
*/
private void addOfflineDataSources(String fileName) {
String filePath = ExternalStorage.getMBTilesDir();
if(ExternalStorage.isReadable()) {
//fetch mbtiles from application folder (e.g. openmapkit/mbtiles)
File targetMBTiles = ExternalStorage.fetchFileFromExternalStorage(filePath + fileName);
if(!targetMBTiles.exists()) {
//inform user if no mbtiles was found
AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity);
builder.setTitle("Device is Offline");
builder.setMessage("Please add mbtiles to " + filePath);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//placeholder
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
//add mbtiles to map
mapView.setTileSource(new MBTilesLayer(targetMBTiles));
}
}
}
} |
package org.wikipedia.gallery;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("unused")
public class MediaList {
@Nullable private String revision;
@Nullable private String tid;
@Nullable private List<MediaListItem> items;
@NonNull
public List<MediaListItem> getItems(@NonNull String... types) {
List<MediaListItem> list = new ArrayList<>();
if (items != null) {
for (MediaListItem item : items) {
if (item.showInGallery()) {
for (String type : types) {
if (item.getType().contains(type)) {
list.add(item);
}
}
}
}
}
return list;
}
} |
package net.i2p.router;
import net.i2p.data.Hash;
import net.i2p.data.i2np.TunnelCreateMessage;
import net.i2p.stat.Rate;
import net.i2p.util.Log;
/**
* Simple throttle that basically stops accepting messages or nontrivial
* requests if the jobQueue lag is too large.
*
*/
class RouterThrottleImpl implements RouterThrottle {
private RouterContext _context;
private Log _log;
/**
* arbitrary hard limit of 2 seconds - if its taking this long to get
* to a job, we're congested.
*
*/
private static int JOB_LAG_LIMIT = 2000;
/**
* Arbitrary hard limit - if we throttle our network connection this many
* times in the previous 10-20 minute period, don't accept requests to
* participate in tunnels.
*
*/
private static int THROTTLE_EVENT_LIMIT = 300;
public RouterThrottleImpl(RouterContext context) {
_context = context;
_log = context.logManager().getLog(RouterThrottleImpl.class);
_context.statManager().createRateStat("router.throttleNetworkCause", "How lagged the jobQueue was when an I2NP was throttled", "Throttle", new long[] { 60*1000, 10*60*1000, 60*60*1000, 24*60*60*1000 });
_context.statManager().createRateStat("router.throttleNetDbCause", "How lagged the jobQueue was when a networkDb request was throttled", "Throttle", new long[] { 60*1000, 10*60*1000, 60*60*1000, 24*60*60*1000 });
_context.statManager().createRateStat("router.throttleTunnelCause", "How lagged the jobQueue was when a tunnel request was throttled", "Throttle", new long[] { 60*1000, 10*60*1000, 60*60*1000, 24*60*60*1000 });
_context.statManager().createRateStat("tunnel.bytesAllocatedAtAccept", "How many bytes had been 'allocated' for participating tunnels when we accepted a request?", "Tunnels", new long[] { 10*60*1000, 60*60*1000, 24*60*60*1000 });
}
public boolean acceptNetworkMessage() {
long lag = _context.jobQueue().getMaxLag();
if (lag > JOB_LAG_LIMIT) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Throttling network reader, as the job lag is " + lag);
_context.statManager().addRateData("router.throttleNetworkCause", lag, lag);
return false;
} else {
return true;
}
}
public boolean acceptNetDbLookupRequest(Hash key) {
long lag = _context.jobQueue().getMaxLag();
if (lag > JOB_LAG_LIMIT) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Refusing netDb request, as the job lag is " + lag);
_context.statManager().addRateData("router.throttleNetDbCause", lag, lag);
return false;
} else {
return true;
}
}
public boolean acceptTunnelRequest(TunnelCreateMessage msg) {
long lag = _context.jobQueue().getMaxLag();
Rate throttleRate = _context.statManager().getRate("router.throttleNetworkCause").getRate(10*60*1000);
long throttleEvents = throttleRate.getCurrentEventCount() + throttleRate.getLastEventCount();
if (throttleEvents > THROTTLE_EVENT_LIMIT) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Refusing tunnel request with the job lag of " + lag
+ " since there have been " + throttleEvents
+ " throttle events in the last 15 minutes or so");
_context.statManager().addRateData("router.throttleTunnelCause", lag, lag);
return false;
}
// ok, we're not hosed, but can we handle the bandwidth requirements
// of another tunnel?
double msgsPerTunnel = _context.statManager().getRate("tunnel.participatingMessagesProcessed").getRate(10*60*1000).getAverageValue();
double bytesPerMsg = _context.statManager().getRate("tunnel.relayMessageSize").getRate(10*60*1000).getAverageValue();
double bytesPerTunnel = msgsPerTunnel * bytesPerMsg;
int numTunnels = _context.tunnelManager().getParticipatingCount();
double bytesAllocated = (numTunnels + 1) * bytesPerTunnel;
_context.statManager().addRateData("tunnel.bytesAllocatedAtAccept", (long)bytesAllocated, msg.getTunnelDurationSeconds()*1000);
// todo: um, throttle (include bw usage of the netDb, our own tunnels, the clients,
// and check to see that they are less than the bandwidth limits
if (_log.shouldLog(Log.DEBUG))
_log.debug("Accepting a new tunnel request (now allocating " + bytesAllocated + " bytes across " + numTunnels
+ " tunnels with lag of " + lag + " and " + throttleEvents + " throttle events)");
return true;
}
} |
package edisyn.synth.korgvolca;
import edisyn.*;
import edisyn.gui.*;
import edisyn.util.*;
import edisyn.synth.yamahadx7.*;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.sound.midi.*;
import java.util.zip.*;
/**
A patch editor for the Korg Volca series.
@author Sean Luke
*/
public class KorgVolca extends Synth
{
public static final int TYPE_VOLCA_BASS = 0;
public static final int TYPE_VOLCA_BEATS = 1;
public static final int TYPE_VOLCA_DRUM_SINGLE = 2;
public static final int TYPE_VOLCA_DRUM_SPLIT = 3;
public static final int TYPE_VOLCA_FM = 4;
public static final int TYPE_VOLCA_KEYS = 5;
public static final int TYPE_VOLCA_KICK = 6;
public static final int TYPE_VOLCA_NUBASS = 7;
public static final int TYPE_VOLCA_SAMPLE = 8;
//public static final int TYPE_VOLCA_SAMPLE_PAJEN_11 = 9;
public static final int TYPE_VOLCA_SAMPLE_2 = 9;
public static final int TYPE_VOLCA_MODULAR = 10; // No MIDI
public static final int TYPE_VOLCA_MIX = 11; // No MIDI
public static final int NUM_EDITABLE_VOLCAS = TYPE_VOLCA_MODULAR;
public static final String[] VOLCAS = { "Bass", "Beats", "Drum (Single)", "Drum (Split)", "FM", "Keys", "Kick", "NuBass", "Sample/Sample2 (Multi)", // "Sample (Pajen Ch 11)",
"Sample2 (Single)" };
public static final String[] PREFIXES = { "bass", "beats", "drumsingle", "drumsplit", "fm", "keys", "kick", "nubass", "sample1", // "samplepajen",
"sample2" };
// Minimum value corresponding to octaves 1-6
public static final int[] BASS_OCTAVES = { 00, 22, 44, 66, 88, 110 };
// Notes corresponding to kick, snare, lo tom, hi tom, cl hat, op hat, clap, claves, agogo, crash
public static final int[] BEATS_NOTES = { 36, 38, 43, 50, 42, 46, 39, 75, 67, 49 };
// Notes corresponding to kick, snare, lo tom, hi tom, cl hat, op hat, clap, claves, agogo, crash
public static final String[] BEATS_DRUMS = { "Kick", "Snare", "Lo Tom", "Hi Tom", "Closed Hat", "Open Hat", "Handclap", "Claves", "Agogo", "Crash" };
// Notes corresponding to 6 parts
public static final int[] DRUM_SINGLE_NOTES = { 60, 62, 64, 65, 67, 69 };
// The six parts
public static final String[] DRUM_SINGLE_PARTS = { "1", "2", "3", "4", "5", "6" };
// Notes corresponding to the Drum (split) parts
public static final String[] DRUM_SPLIT_PARTS = DRUM_SINGLE_PARTS;
// The ten parts
public static final String[] SAMPLE_PARTS = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
public static final String[] DRUM_SOURCES = { "Sine", "Saw", "H Noise", "L Noise", "B Noise" };
public static final String[] DRUM_MODULATORS = { "Rise-Fall", "Oscillate", "Random" };
public static final String[] DRUM_ENVELOPES = { "Lin AR", "Exp AR", "Mult AR" };
// Transpose values for the Volca FM
public static final int[] FM_TRANSPOSE =
{
-36, -36, -35, -35, -34, -34, -33, -32,
-32, -31, -31, -30, -29, -29, -28, -28,
-27, -26, -26, -25, -25, -24, -23, -23,
-22, -22, -21, -20, -20, -19, -19, -18,
-17, -17, -16, -16, -15, -14, -14, -13,
-13, -12, -11, -11, -10, -10, -9, -8,
-8, -7, -7, -6, -5, -5, -4, -4,
-3, -2, -2, -1, -1, 0, 0, 0,
0, 0, 0, 0, 1, 1, 2, 2,
3, 4, 4, 5, 5, 6, 7, 7,
8, 8, 9, 10, 10, 11, 11, 12,
13, 13, 14, 14, 15, 16, 16, 17,
17, 18, 19, 19, 20, 20, 21, 22,
22, 23, 23, 24, 25, 25, 26, 26,
27, 28, 28, 29, 29, 30, 31, 31,
32, 32, 33, 34, 34, 35, 35, 36
};
// LFO values for the Volca FM
public static final int[] FM_LFO =
{
0, 0, 1, 2, 3, 3, 4, 5,
6, 7, 7, 8, 9, 10, 10, 11,
12, 13, 14, 14, 15, 16, 17, 17,
18, 19, 20, 21, 21, 22, 23, 24,
25, 25, 26, 27, 28, 28, 29, 30,
31, 32, 32, 33, 34, 35, 35, 36,
37, 38, 39, 39, 40, 41, 42, 42,
43, 44, 45, 46, 46, 47, 48, 49,
50, 50, 51, 52, 53, 53, 54, 55,
56, 57, 57, 58, 59, 60, 60, 61,
62, 63, 64, 64, 65, 66, 67, 67,
68, 69, 70, 71, 71, 72, 73, 74,
75, 75, 76, 77, 78, 78, 79, 80,
81, 82, 82, 83, 84, 85, 85, 86,
87, 88, 89, 89, 90, 91, 92, 92,
93, 94, 95, 96, 96, 97, 98, 99,
};
// Attack and Release values for the Volca FM
public static final int[] FM_ATTACK =
{
-63, -63, -61, -60, -58, -57, -55, -54,
-52, -51, -49, -48, -46, -45, -43, -42,
-40, -39, -37, -36, -34, -33, -31, -30,
-28, -27, -25, -24, -22, -21, -19, -18,
-16, -15, -15, -14, -14, -13, -13, -12,
-12, -11, -11, -10, -10, -9, -9, -8,
-8, -7, -7, -6, -6, -5, -5, -4,
-4, -3, -3, -2, -2, -1, -1, 0,
0, 0, 1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 6, 6, 7, 7,
8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13, 14, 14, 15, 15,
16, 18, 19, 21, 22, 24, 25, 27,
28, 30, 31, 33, 34, 36, 37, 39,
40, 42, 43, 45, 46, 48, 49, 51,
52, 54, 55, 57, 58, 60, 61, 63,
};
// This is according to Dave Mac on the Volca Facebook, thanks Dave.
public static final int[] NUBASS_PITCH =
{
-1200,
-1200, -1175, -1150, -1125, -1100, -1075, -1050, -1025,
-1000, -975, -950, -925, -900, -875, -850, -825,
-800, -775, -750, -725, -700, -675, -650, -625,
-600, -575, -550, -525, -500, -475, -450, -425,
-400, -375, -350, -325, -300, -275, -250, -225,
-200, -180, -160, -140, -120, -100, -90, -72,
-64, -56, -48, -40, -32, -24, -16, -8,
0, 0, 0, 0, 0, 0, 0,
0,
0, 0, 0, 0, 0, 0, 0,
8, 16, 24, 32, 40, 48, 56, 64,
72, 90, 100, 120, 140, 160, 180, 200,
225, 250, 275, 300, 325, 350, 375, 400,
425, 450, 475, 500, 525, 550, 575, 600,
625, 650, 675, 700, 725, 750, 775, 800,
825, 850, 875, 900, 925, 950, 975, 1000,
1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200
};
// Various Volca Drum values that go -100...+100
public static final int[] DRUM_100 =
{
-100, -98, -97, -96, -93, -92, -90, -89,
-87, -86, -84, -83, -81, -79, -78, -76,
-75, -73, -72, -70, -68, -67, -65, -64,
-62, -61, -59, -58, -56, -54, -53, -51,
-50, -48, -47, -45, -43, -42, -40, -39,
-37, -36, -34, -33, -31, -29, -28, -26,
-25, -23, -22, -20, -18, -17, -15, -14,
-12, -11, -9, -8, -6, -4, -3, -1,
0, 2, 3, 5, 7, 8, 10, 11,
13, 14, 16, 17, 19, 21, 22, 24,
25, 27, 28, 30, 32, 33, 35, 36,
38, 39, 41, 42, 44, 46, 47, 49,
50, 52, 53, 55, 57, 58, 60, 61,
63, 64, 66, 67, 69, 71, 72, 74,
75, 77, 78, 80, 82, 83, 85, 86,
88, 89, 91, 92, 94, 96, 97, 100
};
// Volca Drum "Select" combinations. There are a 5 x 3 x 3 = 45 combinations total.
public static final int[] DRUM_SELECT =
{
0, 0, 0, 1, 1, 1, 2, 2,
2, 3, 3, 3, 4, 4, 4, 5,
5, 5, 6, 6, 7, 7, 7, 8,
8, 8, 9, 9, 9, 10, 10, 10,
11, 11, 11, 12, 12, 13, 13, 13,
14, 14, 14, 15, 15, 15, 16, 16,
16, 17, 17, 17, 18, 18, 18, 19,
19, 20, 20, 20, 21, 21, 21, 22,
22, 22, 23, 23, 23, 24, 24, 24,
25, 25, 25, 26, 26, 27, 27, 27,
28, 28, 28, 29, 29, 29, 30, 30,
30, 31, 31, 31, 32, 32, 32, 33,
33, 34, 34, 34, 35, 35, 35, 36,
36, 36, 37, 37, 37, 38, 38, 38,
39, 39, 39, 40, 40, 41, 41, 41,
42, 42, 42, 43, 43, 43, 44, 44,
};
public static final ImageIcon[] ALGORITHM_ICONS;
static
{
ALGORITHM_ICONS = new ImageIcon[128];
for(int i = 0; i < ALGORITHM_ICONS.length; i++)
{
ALGORITHM_ICONS[i] = edisyn.synth.yamahadx7.YamahaDX7.ALGORITHM_ICONS[i / 4];
}
}
public static final String TYPE_KEY = "type";
int synthType = TYPE_VOLCA_BASS;
JComboBox synthTypeCombo;
JComboBox beatsCombo; // which drum is beats playing?
JComboBox drumSingleCombo;
public int getTestNotePitch()
{
int type = getSynthType();
switch(type)
{
case TYPE_VOLCA_BEATS:
{
return BEATS_NOTES[beatsCombo.getSelectedIndex()];
}
case TYPE_VOLCA_DRUM_SINGLE:
{
return DRUM_SINGLE_NOTES[drumSingleCombo.getSelectedIndex()];
}
default: return super.getTestNotePitch();
}
}
JComboBox drumCombo; // which part is drum playing?
JComboBox sampleCombo; // which part is drum playing?
public int getTestNoteChannel()
{
int type = getSynthType();
switch(type)
{
case TYPE_VOLCA_DRUM_SPLIT:
{
return drumCombo.getSelectedIndex();
}
case TYPE_VOLCA_SAMPLE:
{
return sampleCombo.getSelectedIndex();
}
default: return super.getTestNoteChannel();
}
}
public int getSynthType() { return synthType; }
public void setSynthType(int val, boolean save)
{
if (save)
{
setLastX("" + val, TYPE_KEY, getSynthName(), true);
}
synthType = val;
if (synthTypeCombo != null)
{
synthTypeCombo.setSelectedIndex(val); // hopefully this isn't recursive
}
if (volcaPanel != null)
{
volcaPanel.removeAll();
volcaPanel.add(volcas[val], BorderLayout.CENTER);
}
revalidate();
repaint();
updateTitle();
}
public static String getSynthName() { return "Korg Volca Series"; }
public JComponent[] volcas = new JComponent[NUM_EDITABLE_VOLCAS];
public JPanel volcaPanel;
public KorgVolca()
{
if (allParametersToCC == null)
{
allParametersToCC = new HashMap();
for(int i = 0; i < allParameters.length; i++)
{
if (i == TYPE_VOLCA_SAMPLE)
{
int count = 0;
for(int j = 0; j < allParameters[i].length; j++)
{
allParametersToCC.put(allParameters[i][j], Integer.valueOf(CC[i][count++]));
if (count >= CC[i].length)
count = 0;
}
}
else if (i == TYPE_VOLCA_DRUM_SPLIT)
{
int count = 0;
for(int j = 0; j < allParameters[i].length - 4; j++) // we skip the last four
{
allParametersToCC.put(allParameters[i][j], Integer.valueOf(CC[i][count++]));
if (count >= CC[i].length - 4) // we skip the last four
count = 0;
}
allParametersToCC.put("drumsplitwaveguidemodel", Integer.valueOf(CC[i][CC[i].length - 4]));
allParametersToCC.put("drumsplitdecay", Integer.valueOf(CC[i][CC[i].length - 3]));
allParametersToCC.put("drumsplitbody", Integer.valueOf(CC[i][CC[i].length - 2]));
allParametersToCC.put("drumsplittune", Integer.valueOf(CC[i][CC[i].length - 1]));
}
else
{
for(int j = 0; j < allParameters[i].length; j++)
{
allParametersToCC.put(allParameters[i][j], Integer.valueOf(CC[i][j]));
}
}
}
}
String m = getLastX(TYPE_KEY, getSynthName());
try
{
synthType = (m == null ? TYPE_VOLCA_BASS : Integer.parseInt(m));
if (synthType < TYPE_VOLCA_BASS || synthType > TYPE_VOLCA_SAMPLE_2)
{
synthType = TYPE_VOLCA_BASS;
}
}
catch (NumberFormatException ex)
{
synthType = TYPE_VOLCA_BASS;
}
volcas[TYPE_VOLCA_BASS] = addVolcaBass(Style.COLOR_A());
volcas[TYPE_VOLCA_BEATS] = addVolcaBeats(Style.COLOR_B());
volcas[TYPE_VOLCA_DRUM_SINGLE] = addVolcaDrumSingle(Style.COLOR_A());
volcas[TYPE_VOLCA_DRUM_SPLIT] = addVolcaDrumSplit(Style.COLOR_B());
volcas[TYPE_VOLCA_FM] = addVolcaFM(Style.COLOR_A());
volcas[TYPE_VOLCA_KEYS] = addVolcaKeys(Style.COLOR_B());
volcas[TYPE_VOLCA_KICK] = addVolcaKick(Style.COLOR_A());
volcas[TYPE_VOLCA_NUBASS] = addVolcaNuBass(Style.COLOR_B());
volcas[TYPE_VOLCA_SAMPLE] = addVolcaSample(Style.COLOR_A());
//volcas[TYPE_VOLCA_SAMPLE_PAJEN_11] = addVolcaSamplePajen(Style.COLOR_A());
volcas[TYPE_VOLCA_SAMPLE_2] = addVolcaSample2(Style.COLOR_B());
JComponent soundPanel = new SynthPanel(this);
VBox vbox = new VBox();
vbox.add(addNameGlobal(Style.COLOR_GLOBAL()));
HBox outer = new HBox(HBox.LEFT_CONSUMES);
VBox inner = new VBox();
volcaPanel = new JPanel();
volcaPanel.setLayout(new BorderLayout());
setSynthType(getSynthType(), false); // load the panel
inner.add(Strut.makeHorizontalStrut(volcas[TYPE_VOLCA_SAMPLE].getPreferredSize().width));
inner.addLast(volcaPanel);
outer.add(Strut.makeVerticalStrut(volcas[TYPE_VOLCA_SAMPLE].getPreferredSize().height));
outer.addLast(inner);
vbox.addLast(outer);
soundPanel.add(vbox, BorderLayout.CENTER);
addTab("Volca", soundPanel);
loadDefaults();
}
public JFrame sprout()
{
JFrame frame = super.sprout();
transmitTo.setEnabled(false);
writeTo.setEnabled(false);
receiveCurrent.setEnabled(false);
receivePatch.setEnabled(false);
receiveNextPatch.setEnabled(false);
getAll.setEnabled(false);
merge.setEnabled(false);
blend.setEnabled(false);
return frame;
}
public String getDefaultResourceFileName() { return "KorgVolca.init"; }
public String getHTMLResourceFileName() { return "KorgVolca.html"; }
/** Add the global patch category (name, id, number, etc.) */
public JComponent addNameGlobal(Color color)
{
Category globalCategory = new Category(this, getSynthName(), color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
JLabel label = new JLabel(" Synth Type ");
label.setFont(Style.SMALL_FONT());
label.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label.setForeground(Style.TEXT_COLOR());
synthTypeCombo = new JComboBox(VOLCAS);
synthTypeCombo.setMaximumRowCount(NUM_EDITABLE_VOLCAS);
synthTypeCombo.setSelectedIndex(getSynthType());
synthTypeCombo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setSynthType(synthTypeCombo.getSelectedIndex(), true);
//pd.update("beatskicklevel", model); // doesn't matter what the key is, so I put in "beatskicklevel"
}
});
synthTypeCombo.putClientProperty("JComponent.sizeVariant", "small");
synthTypeCombo.setEditable(false);
synthTypeCombo.setFont(Style.SMALL_FONT());
VBox st = new VBox();
st.add(label);
st.addLast(synthTypeCombo);
hbox.add(st);
comp = new StringComponent("Patch Name", this, "name", 16, "Name must be up to 16 ASCII characters.")
{
public String replace(String val)
{
return revisePatchName(val);
}
public void update(String key, Model model)
{
super.update(key, model);
updateTitle();
}
};
hbox.add(comp); // doesn't work right :-(
//vbox.addBottom(Stretch.makeVerticalStretch());
//hbox.add(vbox);
hbox.addLast(Strut.makeHorizontalStrut(70));
globalCategory.add(hbox, BorderLayout.WEST);
return globalCategory;
}
public JComponent addVolcaBass(Color color)
{
Category category = new Category(this, "Bass", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
comp = new LabelledDial("Slide", this, "bassslidetime", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Time");
hbox.add(comp);
comp = new LabelledDial("Expression", this, "bassexpression", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Octave", this, "bassoctave", color, 0, 127)
{
public String map(int val)
{
if (val >= 110) return "6";
else if (val >= 88) return "5";
else if (val >= 66) return "4";
else if (val >= 44) return "3";
else if (val >= 22) return "2";
else // if (val >= 00)
return "1";
}
};
hbox.add(comp);
comp = new LabelledDial("LFO", this, "basslforate", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Rate");
hbox.add(comp);
comp = new LabelledDial("LFO", this, "basslfointensity", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Intensity");
hbox.add(comp);
for(int i = 1; i <= 3; i++)
{
comp = new LabelledDial("VCO " + i, this, "bassvco" + i + "pitch", color, 0, 127)
{
// The CC to pitch mapping is entirely undocumented. But I believe it is:
// 126, 127 12n
// 115-125 1n ... 11n
// 114 100c (1n)
// 113 98c
// 112 96c
// 66 4c
// 65 2c
// 64 OFF
// 63 OFF
// 62 -2c
// 61 -4c
// 15 -96c
// 14 -98c
// 13 -100c (-1n)
// 2-12 -11n ... -1n
// 0, 1 -12n
public boolean isSymmetric() { return true; }
public String map(int value)
{
if (value >= 126) return "+12n";
if (value >= 115) return "+" + (value - 114) + "n";
if (value == 114) return "+1n";
if (value >= 65) return "+" + ((value - 64) * 2) + "c";
if (value >= 63) return "Off";
if (value >= 14) return "-" + ((63 - value) * 2) + "c";
if (value == 13) return "-1n";
if (value >= 2) return "-" + (13 - value) + "n";
else return "-12n";
}
};
((LabelledDial)comp).addAdditionalLabel("Pitch");
hbox.add(comp);
}
vbox.add(hbox);
hbox = new HBox();
comp = new LabelledDial("Envelope", this, "bassegattack", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial("Envelope", this, "bassegdecayrelease", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay/Rel");
hbox.add(comp);
comp = new LabelledDial("Cutoff", this, "basscutoffegintensity", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("EG Intensity");
hbox.add(comp);
comp = new LabelledDial("Gate", this, "bassgatetime", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Time");
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "bassegattack", "bassegdecayrelease" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
vbox.add(hbox);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public JComponent addVolcaBeats(Color color)
{
Category category = new Category(this, "Beats", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
LabelledDial kick = new LabelledDial("Kick", this, "beatskicklevel", color, 0, 127);
comp = kick;
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Snare", this, "beatssnarelevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial(" Lo Tom ", this, "beatslotomlevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial(" Hi Tom ", this, "beatshitomlevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Closed Hat", this, "beatsclosedhatlevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Open Hat", this, "beatsopenhatlevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Clap", this, "beatsclaplevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Claves", this, "beatsclaveslevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Agogo", this, "beatsagogolevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Crash", this, "beatscrashlevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
vbox.add(hbox);
hbox = new HBox();
hbox.add(Strut.makeStrut(kick)); // kick
hbox.add(Strut.makeStrut(kick)); // snare
comp = new LabelledDial("Tom", this, "beatstomdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
hbox.add(Strut.makeStrut(kick)); // hi tom
comp = new LabelledDial("Closed Hat", this, "beatsclosedhatdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new LabelledDial("Open Hat", this, "beatsopenhatdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new LabelledDial("Clap", this, "beatsclappcmspeed", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("PCM Speed");
hbox.add(comp);
comp = new LabelledDial("Claves", this, "beatsclavespcmspeed", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("PCM Speed");
hbox.add(comp);
comp = new LabelledDial("Agogo", this, "beatsagogopcmspeed", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("PCM Speed");
hbox.add(comp);
comp = new LabelledDial("Crash", this, "beatscrashpcmspeed", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("PCM Speed");
hbox.add(comp);
vbox.add(hbox);
hbox = new HBox();
comp = new LabelledDial("Stutter", this, "beatsstuttertime", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Time");
hbox.add(comp);
vbox.add(hbox);
comp = new LabelledDial("Stutter", this, "beatsstutterdepth", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Depth");
hbox.add(comp);
vbox.add(hbox);
hbox.add(Strut.makeStrut(kick)); // lo tom
hbox.add(Strut.makeStrut(kick)); // hi tom
comp = new LabelledDial("Hat", this, "beatshatgrain", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Grain");
hbox.add(comp);
vbox.add(hbox);
JLabel label = new JLabel(" Test Notes Play ");
label.setFont(Style.SMALL_FONT());
label.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label.setForeground(Style.TEXT_COLOR());
beatsCombo = new JComboBox(BEATS_DRUMS);
beatsCombo.setMaximumRowCount(BEATS_DRUMS.length);
beatsCombo.setSelectedIndex(0);
beatsCombo.putClientProperty("JComponent.sizeVariant", "small");
beatsCombo.setEditable(false);
beatsCombo.setFont(Style.SMALL_FONT());
VBox st = new VBox();
st.add(label);
st.addLast(beatsCombo);
hbox = new HBox();
hbox.add(st);
vbox.add(Strut.makeVerticalStrut(8));
vbox.add(hbox);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public static final int[] KORG_VOLCA_SINGLE_PART_SELECT_CC = new int[] { 14, 23, 46, 55, 80, 89, 116 };
public static final int[] KORG_VOLCA_SPLIT_LAYER_SELECT_CC = new int[] { 14, 15, 16 };
public JComponent addVolcaDrumSinglePart(final int part, Color color)
{
JComponent comp;
String[] params;
HBox hbox = new HBox();
Category category = new Category(this, "Part " + part, color);
category.makePasteable("drumsinglepart");
comp = new LabelledDial("Select", this, "drumsinglepart" + part + "select", color, 0, 127)
{
public String map(int value)
{
int v = DRUM_SELECT[value];
int env = v % 3;
int mod = (v / 3) % 3;
int src = (v / 3) / 3;
return "<html><center><font size=-2>" + DRUM_SOURCES[src] + "<br>" + DRUM_MODULATORS[mod] + "<br>" + DRUM_ENVELOPES[env] + "</font></center></html>";
}
};
hbox.add(comp);
comp = new LabelledDial("Level", this, "drumsinglepart" + part + "level", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Pitch", this, "drumsinglepart" + part + "pitch", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Pan", this, "drumsinglepart" + part + "pan", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
int v = DRUM_100[value];
if (v == 0) return "
if (v < 0) return "< " + (0 - v);
else return "" + v + " >";
}
};
hbox.add(comp);
comp = new LabelledDial("Send", this, "drumsinglepart" + part + "send", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Mod Amt", this, "drumsinglepart" + part + "modamt", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
return "" + DRUM_100[value];
}
};
hbox.add(comp);
comp = new LabelledDial("Mod Rate", this, "drumsinglepart" + part + "modrate", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Attack", this, "drumsinglepart" + part + "attack", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Release", this, "drumsinglepart" + part + "release", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "drumsinglepart" + part + "attack", "drumsinglepart" + part + "release" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
category.add(hbox);
return category;
}
public JComponent addVolcaDrumSingle(Color color)
{
Category category = new Category(this, "Drum [Single]", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
comp = new LabelledDial("Waveguide", this, "drumsinglewaveguidemodel", color, 0, 127)
{
public String map(int value)
{
if (value < 64) return "1";
else return "2";
}
};
((LabelledDial)comp).addAdditionalLabel("Model");
hbox.add(comp);
comp = new LabelledDial("Decay", this, "drumsingledecay", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Body", this, "drumsinglebody", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Tune", this, "drumsingletune", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
JLabel label = new JLabel(" Test Notes Play Part ");
label.setFont(Style.SMALL_FONT());
label.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label.setForeground(Style.TEXT_COLOR());
drumSingleCombo = new JComboBox(DRUM_SINGLE_PARTS);
drumSingleCombo.setMaximumRowCount(DRUM_SINGLE_PARTS.length);
drumSingleCombo.setSelectedIndex(0);
drumSingleCombo.putClientProperty("JComponent.sizeVariant", "small");
drumSingleCombo.setEditable(false);
drumSingleCombo.setFont(Style.SMALL_FONT());
VBox st = new VBox();
HBox hbox2 = new HBox();
hbox2.add(label);
st.add(hbox2);
st.add(drumSingleCombo);
hbox.add(st);
vbox.add(hbox);
vbox.add(Strut.makeVerticalStrut(10));
vbox.add(new Category(this, "", Style.COLOR_A()));
vbox.add(Strut.makeVerticalStrut(10));
final JComponent typical = addVolcaDrumSinglePart(1, color);
final int h = typical.getPreferredSize().height;
final int w = typical.getPreferredSize().width;
VBox svbox = new VBox()
{
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
{
if (orientation == SwingConstants.VERTICAL)
return w;
else
return h;
}
public Dimension getPreferredScrollableViewportSize()
{
Dimension size = getPreferredSize();
size.height = h * 3;
return size;
}
};
JScrollPane pane = new JScrollPane(svbox, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.getViewport().setBackground(Style.BACKGROUND_COLOR());
pane.setBorder(null);
for(int part = 1; part <= 6; part++)
{
svbox.add(addVolcaDrumSinglePart(part, (part % 2 == 1 ? Style.COLOR_B() : Style.COLOR_A())));
}
vbox.addLast(pane);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public JComponent addVolcaDrumSplitLayer(int part, int layer, Color color)
{
JComponent comp;
String[] params;
HBox hbox = new HBox();
String[] label = new String[] { null, "1", "2", "1-2" };
comp = new LabelledDial("Select", this, "drumsplitpart" + part + "layer" + layer + "select", color, 0, 127)
{
public String map(int value)
{
int v = DRUM_SELECT[value];
int env = v % 3;
int mod = (v / 3) % 3;
int src = (v / 3) / 3;
return "<html><center><font size=-2>" + DRUM_SOURCES[src] + "<br>" + DRUM_MODULATORS[mod] + "<br>" + DRUM_ENVELOPES[env] + "</font></center></html>";
}
};
((LabelledDial)comp).addAdditionalLabel(label[layer]);
hbox.add(comp);
comp = new LabelledDial("Level", this, "drumsplitpart" + part + "layer" + layer + "level", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
((LabelledDial)comp).addAdditionalLabel(label[layer]);
hbox.add(comp);
comp = new LabelledDial("Pitch", this, "drumsplitpart" + part + "layer" + layer + "pitch", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
((LabelledDial)comp).addAdditionalLabel(label[layer]);
hbox.add(comp);
comp = new LabelledDial("Mod Amt", this, "drumsplitpart" + part + "layer" + layer + "modamt", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
return "" + DRUM_100[value];
}
};
((LabelledDial)comp).addAdditionalLabel(label[layer]);
hbox.add(comp);
comp = new LabelledDial("Mod Rate", this, "drumsplitpart" + part + "layer" + layer + "modrate", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
((LabelledDial)comp).addAdditionalLabel(label[layer]);
hbox.add(comp);
comp = new LabelledDial("Attack", this, "drumsplitpart" + part + "layer" + layer + "attack", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
((LabelledDial)comp).addAdditionalLabel(label[layer]);
hbox.add(comp);
comp = new LabelledDial("Release", this, "drumsplitpart" + part + "layer" + layer + "release", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
((LabelledDial)comp).addAdditionalLabel(label[layer]);
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "drumsplitpart" + part + "layer" + layer + "attack", "drumsplitpart" + part + "layer" + layer + "release" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
return hbox;
}
public JComponent addVolcaDrumSplitPart(final int part, Color color)
{
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
Category category = new Category(this, "Part " + part, color);
category.makePasteable("drumsplitpart");
vbox.add(addVolcaDrumSplitLayer(part, 3, color));
vbox.add(addVolcaDrumSplitLayer(part, 1, color));
vbox.add(addVolcaDrumSplitLayer(part, 2, color));
hbox.add(vbox);
// hbox.add(Strut.makeHorizontalStrut(10));
vbox = new VBox();
HBox hbox2 = new HBox();
comp = new LabelledDial("Pan", this, "drumsplitpart" + part + "pan", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
int v = DRUM_100[value];
if (v == 0) return "
if (v < 0) return "< " + (0 - v);
else return "" + v + " >";
}
};
hbox2.add(comp);
comp = new LabelledDial("Bit", this, "drumsplitpart" + part + "bitreduction", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
((LabelledDial)comp).addAdditionalLabel("Reduction");
hbox2.add(comp);
vbox.add(hbox2);
hbox2 = new HBox();
comp = new LabelledDial("Fold", this, "drumsplitpart" + part + "fold", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
((LabelledDial)comp).addAdditionalLabel(" "); // stub for spacing
hbox2.add(comp);
comp = new LabelledDial("Drive", this, "drumsplitpart" + part + "drive", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox2.add(comp);
vbox.add(hbox2);
hbox2 = new HBox();
comp = new LabelledDial("Dry", this, "drumsplitpart" + part + "drygain", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
return "" + DRUM_100[value];
}
};
((LabelledDial)comp).addAdditionalLabel("Gain");
hbox2.add(comp);
comp = new LabelledDial("Send", this, "drumsplitpart" + part + "send", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox2.add(comp);
vbox.add(hbox2);
hbox.add(vbox);
category.add(hbox);
return category;
}
public JComponent addVolcaDrumSplit(Color color)
{
Category category = new Category(this, "Drum [Split]", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
comp = new LabelledDial("Waveguide", this, "drumsplitwaveguidemodel", color, 0, 127)
{
public String map(int value)
{
if (value < 64) return "1";
else return "2";
}
};
((LabelledDial)comp).addAdditionalLabel("Model");
hbox.add(comp);
comp = new LabelledDial("Decay", this, "drumsplitdecay", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Body", this, "drumsplitbody", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
comp = new LabelledDial("Tune", this, "drumsplittune", color, 0, 127)
{
public String map(int value)
{
if (value == 127) return "255";
else return "" + (2 * value);
}
};
hbox.add(comp);
JLabel label = new JLabel(" Test Notes Play Part ");
label.setFont(Style.SMALL_FONT());
label.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label.setForeground(Style.TEXT_COLOR());
drumCombo = new JComboBox(DRUM_SPLIT_PARTS);
drumCombo.setMaximumRowCount(DRUM_SPLIT_PARTS.length);
drumCombo.setSelectedIndex(0);
drumCombo.putClientProperty("JComponent.sizeVariant", "small");
drumCombo.setEditable(false);
drumCombo.setFont(Style.SMALL_FONT());
VBox st = new VBox();
HBox stb = new HBox();
stb.add(label);
st.add(stb);
st.add(drumCombo);
hbox.add(st);
vbox.add(hbox);
vbox.add(Strut.makeVerticalStrut(10));
vbox.add(new Category(this, "", Style.COLOR_A()));
vbox.add(Strut.makeVerticalStrut(10));
final JComponent typical = addVolcaDrumSplitPart(1, color);
final int h = typical.getPreferredSize().height;
final int w = typical.getPreferredSize().width;
VBox svbox = new VBox()
{
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
{
if (orientation == SwingConstants.VERTICAL)
return w;
else
return h;
}
public Dimension getPreferredScrollableViewportSize()
{
Dimension size = getPreferredSize();
size.height = h;
return size;
}
};
JScrollPane pane = new JScrollPane(svbox, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.getViewport().setBackground(Style.BACKGROUND_COLOR());
pane.setBorder(null);
for(int part = 1; part <= 6; part++)
{
svbox.add(addVolcaDrumSplitPart(part, (part % 2 == 0 ? Style.COLOR_A() : Style.COLOR_B())));
}
vbox.addLast(pane);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public JComponent addVolcaFM(Color color)
{
Category category = new Category(this, "FM", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
comp = new LabelledDial("Algorithm", this, "fmalgorithm", color, 0, 127)
{
// The Volca FM MIDIImp documentation is very wrong here. It says that
// the values 0... 127 map to algorithms "0...32". But that's 33 algorithms
// and the DX7 obviously has only 32 algorithms. Thus they have this weird
// and incorrect offset mapping as shown below.
// *7 : [H] [D] [H] [D] : [D]
// 00 (0) ~ 07 (07) : 0, 0, 0, 0, 1, 1, 1, 1
// 08 (8) ~ 0F (15) : 2, 2, 2, 2, 3, 3, 3, 3
// 10 (16) ~ 17 (23) : 4, 4, 4, 4, 5, 5, 5, 5
// 18 (24) ~ 1B (27) : 6, 6, 6, 6, 7, 7, 7, 7
// 20 (32) ~ 27 (39) : 8, 8, 8, 9, 9, 9, 9, 10
// 28 (40) ~ 2F (47) : 10, 10, 10, 11, 11, 11, 11, 12
// 30 (48) ~ 37 (55) : 12, 12, 12, 13, 13, 13, 13, 14
// 38 (56) ~ 3F (63) : 14, 14, 14, 15, 15, 15, 15, 16
// 40 (64) ~ 47 (71) : 16, 16, 17, 17, 17, 17, 18, 18
// 48 (72) ~ 4F (79) : 18, 18, 19, 19, 19, 19, 20, 20
// 50 (80) ~ 57 (87) : 20, 20, 21, 21, 21, 21, 22, 22
// 58 (88) ~ 5F (95) : 22, 22, 23, 23, 23, 23, 24, 24
// 60 (96) ~ 67 (103) : 24, 25, 25, 25, 25, 26, 26, 26
// 68 (104) ~ 6F (111) : 26, 27, 27, 27, 27, 28, 28, 28
// 70 (112) ~ 77 (119) : 28, 29, 29, 29, 29, 30, 30, 30
// 78 (120) ~ 7F (127) : 30, 31, 31, 31, 31, 32, 32, 32
// However the correct answer appears to map
// 0...127 to algorithm 0...31 just by dividing the value by 4. This was
// the case at least as of firmware 004, and certainly by 007. So I dunno
// what this mapping is supposed to do, maybe it was an outdated internal
// test thing or something.
public String map(int value)
{
return "" + ((value / 4) + 1);
}
};
hbox.add(comp);
comp = new LabelledDial("Transpose", this, "fmtranspose", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
// Octave Transpose values
int oct = -3;
if (value >= 110) oct = 3;
else if (value >= 90) oct = 2;
else if (value >= 74) oct = 1;
else if (value >= 55) oct = 0;
else if (value >= 37) oct = -1;
else if (value >= 19) oct = -2;
// Semitone Transpose values
int semi = FM_TRANSPOSE[value];
if (oct == 0 && semi == 1) return "
else return "" + oct + ":" + semi;
}
};
hbox.add(comp);
comp = new LabelledDial("Velocity", this, "fmevelocity", color, 0, 127)
{
public String map(int value)
{
if (value == 0) value = 1; // no zero velocity
return "" + value;
}
};
hbox.add(comp);
comp = new LabelledDial("LFO", this, "fmlforate", color, 0, 127)
{
public String map(int value)
{
return "" + FM_LFO[value];
}
};
((LabelledDial)comp).addAdditionalLabel("Rate");
hbox.add(comp);
comp = new LabelledDial("LFO", this, "fmlfopitchdepth", color, 0, 127)
{
public String map(int value)
{
return "" + FM_LFO[value];
}
};
((LabelledDial)comp).addAdditionalLabel("Pitch Depth");
hbox.add(comp);
comp = new LabelledDial("Arpeggiator", this, "fmarpeggiatortype", color, 0, 127)
{
public String map(int value)
{
if (value >= 116) return "Rand3";
if (value >= 103) return "Rand2";
if (value >= 90) return "Rand1";
if (value >= 77) return "Fall3";
if (value >= 64) return "Fall2";
if (value >= 52) return "Fall1";
if (value >= 39) return "Rise3";
if (value >= 26) return "Rise2";
if (value >= 13) return "Rise1";
return "Off";
}
};
((LabelledDial)comp).addAdditionalLabel("Type");
hbox.add(comp);
comp = new LabelledDial("Arpeggiator", this, "fmarpeggiatordiv", color, 0, 127)
{
public String map(int value)
{
// bizarrely this is significantly different from Arpeggiator Type
if (value >= 117) return "4-1";
if (value >= 105) return "3-1";
if (value >= 94) return "2-1";
if (value >= 82) return "3-2";
if (value >= 70) return "1-1";
if (value >= 59) return "2-3";
if (value >= 47) return "1-2";
if (value >= 35) return "1-3";
if (value >= 24) return "1-4";
if (value >= 12) return "1-8";
return "1-12";
}
};
((LabelledDial)comp).addAdditionalLabel("Div");
hbox.add(comp);
comp = new LabelledDial("Modulator", this, "fmmodulatorattack", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
return "" + FM_ATTACK[value];
}
};
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial("Modulator", this, "fmmodulatordecay", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
return "" + FM_ATTACK[value];
}
};
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new LabelledDial("Carrier", this, "fmcarrierattack", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
return "" + FM_ATTACK[value];
}
};
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial("Carrier", this, "fmcarrierdecay", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
return "" + FM_ATTACK[value];
}
};
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
vbox.add(hbox);
vbox.add(Strut.makeVerticalStrut(10));
hbox = new HBox();
hbox.add(new TextLabel(" Algorithm Display "));
vbox.add(hbox);
vbox.add(Strut.makeVerticalStrut(6));
hbox = new HBox();
hbox.add(new TextLabel(" "));
comp = new IconDisplay(null, ALGORITHM_ICONS, this, "fmalgorithm", 104, 104);
hbox.add(comp);
vbox.add(hbox);
vbox.add(Strut.makeVerticalStrut(10));
hbox = new HBox();
comp = new PushButton("DX7 Editor")
{
public void perform()
{
final YamahaDX7 synth = new YamahaDX7();
if (tuple != null)
synth.tuple = tuple.copy(synth.buildInReceiver(), synth.buildKeyReceiver(), synth.buildKey2Receiver());
if (synth.tuple != null)
{
synth.sprout();
JFrame frame = ((JFrame)(SwingUtilities.getRoot(synth)));
frame.setVisible(true);
}
else
{
showSimpleError("Disconnected", "You can't show a patch when disconnected.");
}
}
};
hbox.add(comp);
hbox.add(new TextLabel(" The Yamaha DX7 editor can upload patches and banks to the Volca. See Volca and Yamaha DX7 About Panels. "));
vbox.add(hbox);
vbox.add(Strut.makeVerticalStrut(10));
Category category2 = new Category(this, "Pajen FM Firmware", Style.COLOR_B());
hbox = new HBox();
comp = new LabelledDial("Chorus", this, "fmpajenchorus", color, 0, 127)
{
public String map(int value)
{
if (value < 64) return "Off";
return "On";
}
};
hbox.add(comp);
comp = new LabelledDial("Chorus", this, "fmpajenchorusstereowidth", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Stereo Width");
hbox.add(comp);
comp = new LabelledDial("Chorus", this, "fmpajenchorusspeed", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Speed");
hbox.add(comp);
comp = new LabelledDial("Load", this, "fmpajenloadpatch", color, 0, 127)
{
// May be off by one. A fencepost error? Pajen semi-confirmed it to me.
public String map(int value)
{
return "" + ((value / 4) + 1);
}
};
((LabelledDial)comp).addAdditionalLabel("Patch");
hbox.add(comp);
comp = new LabelledDial("Load", this, "fmpajenloadpattern", color, 0, 127)
{
// May be off by one. A fencepost error? Pajen semi-confirmed it to me.
public String map(int value)
{
return "" + ((value / 8) + 1);
}
};
((LabelledDial)comp).addAdditionalLabel("Pattern");
hbox.add(comp);
comp = new LabelledDial("Tempo", this, "fmpajentempodivisor", color, 0, 127)
{
public String map(int value)
{
if (value < 32) return "1/1";
if (value < 64) return "1/2";
if (value < 96) return "1/4";
return "1/8";
}
};
((LabelledDial)comp).addAdditionalLabel("Divisor");
hbox.add(comp);
comp = new LabelledDial("Mod Wheel", this, "fmpajenmodwheelcc", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("CC");
hbox.add(comp);
category2.add(hbox);
vbox.add(category2);
vbox.add(Strut.makeVerticalStrut(10));
hbox = new HBox();
hbox.add(new TextLabel(" With the Pajen firmware you can also make real-time parameter changes via the Yamaha DX7 editor. "));
vbox.add(hbox);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public JComponent addVolcaKeys(Color color)
{
Category category = new Category(this, "Keys", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
comp = new LabelledDial("Portamento", this, "keysportamento", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Detune", this, "keysdetune", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("VCO", this, "keysenvelopeintensity", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("EG Int");
hbox.add(comp);
// default should be 127
comp = new LabelledDial("Expression", this, "keysexpression", color, 0, 127);
hbox.add(comp);
// eventually change this to a chooser?
comp = new LabelledDial("Voice", this, "keysvoice", color, 0, 127)
{
public String map(int val)
{
if (val >= 113) return "PolyR";
else if (val >= 88) return "UniR";
else if (val >= 63) return "5th";
else if (val >= 38) return "Oct";
else if (val >= 13) return "Uni";
else // if (val >= 00)
return "Poly";
}
};
hbox.add(comp);
comp = new LabelledDial("Octave", this, "keysoctave", color, 0, 127)
{
public String map(int val)
{
if (val >= 110) return "1'";
else if (val >= 88) return "2'";
else if (val >= 66) return "4'";
else if (val >= 44) return "8'";
else if (val >= 22) return "16'";
else // if (val >= 00)
return "32'";
}
};
hbox.add(comp);
comp = new LabelledDial("VCF", this, "keysvcfcutoff", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Cutoff");
hbox.add(comp);
comp = new LabelledDial("VCF", this, "keysvcfenvelopeintensity", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("EG Int");
hbox.add(comp);
comp = new LabelledDial("LFO", this, "keyslforate", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Rate");
hbox.add(comp);
comp = new LabelledDial("LFO", this, "keyslfopitchintensity", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Pitch Int");
hbox.add(comp);
comp = new LabelledDial("LFO", this, "keyslfocutoffintensity", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Cutoff Int");
hbox.add(comp);
vbox.add(hbox);
hbox = new HBox();
comp = new LabelledDial("Delay", this, "keysdelaytime", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Time");
hbox.add(comp);
comp = new LabelledDial("Delay", this, "keysdelayfeedback", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Feedback");
hbox.add(comp);
comp = new LabelledDial("Envelope", this, "keysenvelopeattack", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial("Envelope", this, "keysenvelopedecayrelease", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay/Release");
hbox.add(comp);
comp = new LabelledDial("Envelope", this, "keysenvelopesustain", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Sustain");
hbox.add(comp);
// ASR
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "keysenvelopeattack", "keysenvelopedecayrelease", null, "keysenvelopedecayrelease"},
new String[] { null, null, "keysenvelopesustain", "keysenvelopesustain", null },
new double[] { 0, 0.25/127, 0.25/127, 0.25, 0.25/127 },
new double[] { 0.0, 1.0, 1.0/127.0, 1.0/127.0, 0 });
hbox.add(comp);
vbox.add(hbox);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public JComponent addVolcaKick(Color color)
{
Category category = new Category(this, "Kick", color);
JComponent comp;
String[] params;
VBox vbox = new VBox();
HBox hbox = new HBox();
comp = new LabelledDial("Pulse", this, "kickpulsecolor", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Color");
hbox.add(comp);
comp = new LabelledDial("Pulse", this, "kickpulselevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Drive", this, "kickdrive", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Tone", this, "kicktone", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Resonator", this, "kickresonatorpitch", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Pitch");
hbox.add(comp);
comp = new LabelledDial("Resonator", this, "kickresonatorbend", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Bend");
hbox.add(comp);
comp = new LabelledDial("Resonator", this, "kickresonatortime", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Time");
hbox.add(comp);
vbox.add(hbox);
hbox = new HBox();
comp = new LabelledDial("Accent", this, "kickaccent", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Amp", this, "kickampattack", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial("Amp", this, "kickampdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "kickampattack", "kickampdecay" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
vbox.add(hbox);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public JComponent addVolcaNuBass(Color color)
{
Category category = new Category(this, "NuBass", color);
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
comp = new LabelledDial("VTO", this, "nubassvtopitch", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
int v = NUBASS_PITCH[value];
if (value <= 56)
{
if (v % 100 == 0)
return "" + (v / 100) + "n";
else return "" + v + "c";
}
else if (value >= 72)
{
if (v % 100 == 0)
return "+" + (v / 100) + "n";
else return "+" + v + "c";
}
else
{
return "Off";
}
}
};
((LabelledDial)comp).addAdditionalLabel("Pitch");
hbox.add(comp);
comp = new LabelledDial("VTO", this, "nubassvtosaturation", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Saturation");
hbox.add(comp);
comp = new LabelledDial("VTO", this, "nubassvtolevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level");
hbox.add(comp);
comp = new LabelledDial("Accent", this, "nubassaccent", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("LFO", this, "nubasslforate", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Rate");
hbox.add(comp);
comp = new LabelledDial("LFO", this, "nubasslfointensity", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Intensity");
hbox.add(comp);
vbox.add(hbox);
hbox = new HBox();
comp = new LabelledDial("VCF", this, "nubassvcfcutoff", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Cutoff");
hbox.add(comp);
comp = new LabelledDial("VCF", this, "nubassvcfpeak", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Peak");
hbox.add(comp);
comp = new LabelledDial("VCF", this, "nubassvcfattack", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial("VCF", this, "nubassvcfdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new LabelledDial("VCF", this, "nubassvcfegintensity", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("EG Int");
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "nubassvcfattack", "nubassvcfdecay" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
vbox.add(hbox);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public JComponent addVolcaSamplePart(int part, Color color)
{
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
Category category = new Category(this, "Part " + part, color);
category.makePasteable("sample1part");
comp = new LabelledDial("Level", this, "sample1part" + part + "level", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Pan", this, "sample1part" + part + "pan", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
if (value == 64) return "
else if (value == 0) return "< 63";
else if (value < 64) return "< " + (64 - value);
else return (value - 64) + " >";
}
};
hbox.add(comp);
comp = new LabelledDial("Hi", this, "sample1part" + part + "hicutoff", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Cutoff");
hbox.add(comp);
comp = new LabelledDial(" Amp Env ", this, "sample1part" + part + "ampegattack", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial(" Amp Env ", this, "sample1part" + part + "ampegdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "sample1part" + part + "ampegattack", "sample1part" + part + "ampegdecay" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
comp = new LabelledDial("Speed", this, "sample1part" + part + "speed", color, 0, 127)
{
public boolean isSymmetric()
{
return true;
}
public String map(int value)
{
if (value == 0) return "-63";
else return "" + (value - 64);
}
};
hbox.add(comp);
comp = new LabelledDial("Reverse", this, "sample1part" + part + "pajenreversepart", color, 0, 127)
{
public String map(int value)
{
if (value == 0) return "Off";
else if (value > 63) return "Toggle";
else return "On";
}
};
((LabelledDial)comp).addAdditionalLabel("Part [P]");
hbox.add(comp);
comp = new LabelledDial("Mute", this, "sample1part" + part + "pajenmutepart", color, 0, 127)
{
public String map(int value)
{
if (value == 0) return "Off";
else if (value > 63) return "Toggle";
else return "On";
}
};
((LabelledDial)comp).addAdditionalLabel("Part [P]");
hbox.add(comp);
comp = new LabelledDial("Solo", this, "sample1part" + part + "pajensolopart", color, 0, 127)
{
public String map(int value)
{
if (value == 0) return "Off";
else if (value > 63) return "Toggle";
else return "On";
}
};
((LabelledDial)comp).addAdditionalLabel("Part [P]");
hbox.add(comp);
vbox.add(hbox);
hbox = new HBox();
comp = new LabelledDial("Sample", this, "sample1part" + part + "startpoint", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Start");
hbox.add(comp);
comp = new LabelledDial("Sample", this, "sample1part" + part + "length", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Length");
hbox.add(comp);
comp = new LabelledDial("Pitch Env", this, "sample1part" + part + "pitchegintensity", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
if (value == 0) return "-63";
else return "" + (value - 64);
}
};
((LabelledDial)comp).addAdditionalLabel("Intensity");
hbox.add(comp);
comp = new LabelledDial("Pitch Env", this, "sample1part" + part + "pitchegattack", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial("Pitch Env", this, "sample1part" + part + "pitchegdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, "sample1part" + part + "pitchegattack", "sample1part" + part + "pitchegdecay" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
comp = new LabelledDial("Sample", this, "sample1part" + part + "pajensampleselect", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Select [P]");
hbox.add(comp);
comp = new LabelledDial("Reverb", this, "sample1part" + part + "pajenreverbonoff", color, 0, 127)
{
public String map(int value)
{
if (value == 0) return "Off";
else if (value > 63) return "Toggle";
else return "On";
}
};
((LabelledDial)comp).addAdditionalLabel("On/Off [P]");
hbox.add(comp);
comp = new LabelledDial("Loop", this, "sample1part" + part + "pajenloop", color, 0, 127)
{
public String map(int value)
{
if (value == 0) return "Off";
else if (value > 63) return "Toggle";
else return "On";
}
};
((LabelledDial)comp).addAdditionalLabel("Part [P]");
hbox.add(comp);
vbox.add(hbox);
category.add(vbox);
return category;
}
public JComponent addVolcaSample(Color color)
{
Category category = new Category(this, "Sample / Sample2 [Multi Channel]", color);
JComponent comp;
VBox vbox;
HBox hbox;
String[] params;
vbox = new VBox();
hbox = new HBox();
comp = new LabelledDial("Part", this, "sample1part" + 1 + "pajenpartselect", color, 0, 127)
{
public String map(int value)
{
if (value <= 12) return "1";
else if (value <= 25) return "2";
else if (value <= 38) return "3";
else if (value <= 51) return "4";
else if (value <= 63) return "5";
else if (value <= 76) return "6";
else if (value <= 89) return "7";
else if (value <= 102) return "8";
else if (value <= 115) return "9";
else return "10";
}
};
((LabelledDial)comp).addAdditionalLabel("Select [P]");
hbox.add(comp);
// make some dummy labelled dials
for(int i = 2; i <= 10; i++)
{
comp = new LabelledDial("Part", this, "sample1part" + i + "pajenpartselect", color, 0, 127);
}
comp = new LabelledDial("Reverb", this, "sample1part" + 1 + "pajenreverbtype", color, 0, 127)
{
public String map(int value)
{
if (value <= 42) return "0";
else if (value <= 85) return "1";
else return "2";
}
};
((LabelledDial)comp).addAdditionalLabel("Type [P]");
hbox.add(comp);
// make some dummy labelled dials
for(int i = 2; i <= 10; i++)
{
comp = new LabelledDial("Reverb", this, "sample1part" + i + "pajenreverbtype", color, 0, 127);
}
comp = new LabelledDial("Reverb", this, "sample1part" + 1 + "pajenreverblevel", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Level [P]");
hbox.add(comp);
// make some dummy labelled dials
for(int i = 2; i <= 10; i++)
{
comp = new LabelledDial("Reverb", this, "sample1part" + i + "pajenreverblevel", color, 0, 127);
}
JLabel label = new JLabel(" Test Notes Play Part ");
label.setFont(Style.SMALL_FONT());
label.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label.setForeground(Style.TEXT_COLOR());
sampleCombo = new JComboBox(SAMPLE_PARTS);
sampleCombo.setMaximumRowCount(SAMPLE_PARTS.length);
sampleCombo.setSelectedIndex(0);
sampleCombo.putClientProperty("JComponent.sizeVariant", "small");
sampleCombo.setEditable(false);
sampleCombo.setFont(Style.SMALL_FONT());
VBox st = new VBox();
HBox stb = new HBox();
stb.add(label);
st.add(stb);
st.add(sampleCombo);
hbox.add(st);
vbox.add(hbox);
vbox.add(Strut.makeVerticalStrut(10));
vbox.add(new Category(this, "", Style.COLOR_A()));
vbox.add(Strut.makeVerticalStrut(10));
final JComponent typical = addVolcaSamplePart(1, color);
final int h = typical.getPreferredSize().height;
final int w = typical.getPreferredSize().width;
VBox vbox2 = new VBox()
{
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
{
if (orientation == SwingConstants.VERTICAL)
return w;
else
return h;
}
public Dimension getPreferredScrollableViewportSize()
{
Dimension size = getPreferredSize();
size.height = h * 2;
return size;
}
};
for(int part = 1; part <= 10; part++)
{
vbox2.add(addVolcaSamplePart(part, (part % 2 == 0 ? Style.COLOR_A() : Style.COLOR_B())));
}
JScrollPane pane = new JScrollPane(vbox2, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.getViewport().setBackground(Style.BACKGROUND_COLOR());
pane.setBorder(null);
vbox.add(pane);
category.add(vbox, BorderLayout.CENTER);
return category;
}
public JComponent addVolcaSample2Part(int part, Color color)
{
String prefix = "sample2";
JComponent comp;
String[] params;
HBox hbox = new HBox();
VBox vbox = new VBox();
Category category = new Category(this, "Part " + part, color);
category.makePasteable("sample2part");
comp = new LabelledDial("Level", this, prefix + "part" + part + "level", color, 0, 127);
hbox.add(comp);
comp = new LabelledDial("Pan", this, prefix + "part" + part + "pan", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
if (value == 64) return "
else if (value == 0) return "< 63";
else if (value < 64) return "< " + (64 - value);
else return (value - 64) + " >";
}
};
hbox.add(comp);
comp = new LabelledDial("Hi", this, prefix + "part" + part + "hicutoff", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Cutoff");
hbox.add(comp);
comp = new LabelledDial(" Amp Env ", this, prefix + "part" + part + "ampegattack", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial(" Amp Env ", this, prefix + "part" + part + "ampegdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, prefix + "part" + part + "ampegattack", prefix + "part" + part + "ampegdecay" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
vbox.add(hbox);
hbox = new HBox();
if (part == 1)
{
hbox = new HBox();
comp = new LabelledDial("Sample", this, prefix + "part" + part + "startpoint", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Start");
hbox.add(comp);
comp = new LabelledDial("Sample", this, prefix + "part" + part + "length", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Length");
hbox.add(comp);
comp = new LabelledDial("Speed", this, prefix + "part" + part + "speed", color, 0, 127)
{
public boolean isSymmetric()
{
return true;
}
public String map(int value)
{
if (value == 0) return "-63";
else return "" + (value - 64);
}
};
hbox.add(comp);
comp = new LabelledDial("Pitch Env", this, prefix + "part" + part + "pitchegintensity", color, 0, 127)
{
public boolean isSymmetric() { return true; }
public String map(int value)
{
if (value == 0) return "-63";
else return "" + (value - 64);
}
};
((LabelledDial)comp).addAdditionalLabel("Intensity");
hbox.add(comp);
comp = new LabelledDial("Pitch Env", this, prefix + "part" + part + "pitchegattack", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Attack");
hbox.add(comp);
comp = new LabelledDial("Pitch Env", this, prefix + "part" + part + "pitchegdecay", color, 0, 127);
((LabelledDial)comp).addAdditionalLabel("Decay");
hbox.add(comp);
comp = new EnvelopeDisplay(this, Style.ENVELOPE_COLOR(),
new String[] { null, prefix + "part" + part + "pitchegattack", prefix + "part" + part + "pitchegdecay" },
new String[] { null, null, null },
new double[] { 0, 0.5/127, 0.5/127 },
new double[] { 0.0, 1.0, 0.0 });
hbox.add(comp);
vbox.add(hbox);
}
category.add(vbox);
return category;
}
public JComponent addVolcaSample2(Color color)
{
Category category = new Category(this, "Sample2 [Single Channel]", color);
JComponent comp;
String[] params;
final JComponent typical = addVolcaSample2Part(1, color);
final int h = typical.getPreferredSize().height;
final int w = typical.getPreferredSize().width;
VBox vbox = new VBox()
{
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
{
if (orientation == SwingConstants.VERTICAL)
return w;
else
return h;
}
public Dimension getPreferredScrollableViewportSize()
{
Dimension size = getPreferredSize();
size.height = h * 2;
return size;
}
};
for(int part = 1; part <= 10; part++)
{
vbox.add(addVolcaSample2Part(part, (part % 2 == 0 ? Style.COLOR_B() : Style.COLOR_A())));
}
JScrollPane pane = new JScrollPane(vbox, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
pane.getViewport().setBackground(Style.BACKGROUND_COLOR());
pane.setBorder(null);
category.add(pane, BorderLayout.CENTER);
return category;
}
final static int[][] CC = new int[][]
{
// BASS
{
5, 11, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49
},
// BEATS
{
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59
},
// DRUM (SINGLE)
{
14, 15, 16, 17, 18, 19, 20, 103, 109, 23, 24, 25, 26, 27, 28, 29, 104, 110, 46, 47, 48, 49, 50, 51, 52, 105, 111, 55, 56, 57, 58, 59, 60, 61, 106, 112, 80, 81, 82, 83, 84, 85, 86, 107, 113, 89, 90, 96, 97, 98, 99, 100, 108, 114, 116, 117, 118, 119
},
// DRUM (SPLIT)
{
// Note that this is PER MIDI CHANNEL 1-6
10, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 46, 47, 48, 49, 50, 51, 52, 103,
// Globals
116, 117, 118, 119
},
{
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
// PAJEN FIRMWARE
85, 86, 87, 88, 89, 90, 91
},
// KEYS
{
5, 11, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53
},
// KICK
{
40, 41, 42, 43, 44, 45, 46, 47, 48, 49
},
// NUBASS
{
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50
},
// SAMPLE
{
// Note that this is PER MIDI CHANNEL 1-10
7, 10, 40, 41, 42, 43, 44, 45, 46, 47, 48,
// Pajen (in the user guide order)
50, 54, 56, 58, 59, 55, 52, 51, 57 // note no 53 // THIS IS NOT GOING TO BE THE FINAL VERSION
},
// SAMPLE PAJEN-7 FIRMWARE CHANNEL 11
{
0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
1, 11, 21, 31, 41, 51, 61, 71, 81, 91, 101,
2, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102,
3, 13, 23, 33, 43, 53, 63, 73, 83, 93, 103,
4, 14, 24, 34, 44, 54, 64, 74, 84, 94, 104,
5, 15, 25, 35, 45, 55, 65, 75, 85, 95, 105,
6, 16, 26, 36, 46, 56, 66, 76, 86, 96, 106,
7, 17, 27, 37, 47, 57, 67, 77, 87, 97, 107,
8, 18, 28, 38, 48, 58, 68, 78, 88, 98, 108,
9, 19, 29, 39, 49, 59, 69, 79, 89, 99, 109,
},
// SAMPLE2
{
// "I don't understand why korg doesn't release the official midi implementation chart
// for sample2. Anyways, here are the mappings for parts other than part1:"
// attrib: [level, pan, ampAttack, ampDelay, hicut]
// CC range: [14 - 19] - Part2 [20 - 25] - Part3 [26 - 31] - Part4 [50 - 55] -
// Part5 [56 - 61] - Part6 [76 - 81] - Part7 [82 - 87] - Part8 [102 - 107] -
// Part9 [108 - 113] - Part10
// -- Sean: I'm guessing Part 1 is the standard CCs for the original Sample
// -- Sean: maybe there's a bug? The CC ranges are 6 long but there are only 5 attributes.
// Did he forget one?
// Note that these aren't in increasing order so as to keep the parts together
7, 10, 40, 41, 42, 43, 44, 45, 46, 47, 48, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 102, 103, 104, 105, 106, 108, 109, 110, 112, 113
},
};
static HashMap allParametersToCC;
final static String[][] allParameters = new String[][]
{
{
"bassslidetime",
"bassexpression",
"bassoctave",
"basslforate",
"basslfointensity",
"bassvco1pitch",
"bassvco2pitch",
"bassvco3pitch",
"bassegattack",
"bassegdecayrelease",
"basscutoffegintensity",
"bassgatetime",
},
{
"beatskicklevel",
"beatssnarelevel",
"beatslotomlevel",
"beatshitomlevel",
"beatsclosedhatlevel",
"beatsopenhatlevel",
"beatsclaplevel",
"beatsclaveslevel",
"beatsagogolevel",
"beatscrashlevel",
"beatsclappcmspeed",
"beatsclavespcmspeed",
"beatsagogopcmspeed",
"beatscrashpcmspeed",
"beatsstuttertime",
"beatsstutterdepth",
"beatstomdecay",
"beatsclosedhatdecay",
"beatsopenhatdecay",
"beatshatgrain",
},
{
"drumsinglepart1select",
"drumsinglepart1level",
"drumsinglepart1modamt",
"drumsinglepart1modrate",
"drumsinglepart1pitch",
"drumsinglepart1attack",
"drumsinglepart1release",
"drumsinglepart1send",
"drumsinglepart1pan",
"drumsinglepart2select",
"drumsinglepart2level",
"drumsinglepart2modamt",
"drumsinglepart2modrate",
"drumsinglepart2pitch",
"drumsinglepart2attack",
"drumsinglepart2release",
"drumsinglepart2send",
"drumsinglepart2pan",
"drumsinglepart3select",
"drumsinglepart3level",
"drumsinglepart3modamt",
"drumsinglepart3modrate",
"drumsinglepart3pitch",
"drumsinglepart3attack",
"drumsinglepart3release",
"drumsinglepart3send",
"drumsinglepart3pan",
"drumsinglepart4select",
"drumsinglepart4level",
"drumsinglepart4modamt",
"drumsinglepart4modrate",
"drumsinglepart4pitch",
"drumsinglepart4attack",
"drumsinglepart4release",
"drumsinglepart4send",
"drumsinglepart4pan",
"drumsinglepart5select",
"drumsinglepart5level",
"drumsinglepart5modamt",
"drumsinglepart5modrate",
"drumsinglepart5pitch",
"drumsinglepart5attack",
"drumsinglepart5release",
"drumsinglepart5send",
"drumsinglepart5pan",
"drumsinglepart6select",
"drumsinglepart6level",
"drumsinglepart6modamt",
"drumsinglepart6modrate",
"drumsinglepart6pitch",
"drumsinglepart6attack",
"drumsinglepart6release",
"drumsinglepart6send",
"drumsinglepart6pan",
"drumsinglewaveguidemodel",
"drumsingledecay",
"drumsinglebody",
"drumsingletune",
},
{
"drumsplitpart1pan",
"drumsplitpart1layer1select",
"drumsplitpart1layer2select",
"drumsplitpart1layer3select",
"drumsplitpart1layer1level",
"drumsplitpart1layer2level",
"drumsplitpart1layer3level",
"drumsplitpart1layer1attack",
"drumsplitpart1layer2attack",
"drumsplitpart1layer3attack",
"drumsplitpart1layer1release",
"drumsplitpart1layer2release",
"drumsplitpart1layer3release",
"drumsplitpart1layer1pitch",
"drumsplitpart1layer2pitch",
"drumsplitpart1layer3pitch",
"drumsplitpart1layer1modamt",
"drumsplitpart1layer2modamt",
"drumsplitpart1layer3modamt",
"drumsplitpart1layer1modrate",
"drumsplitpart1layer2modrate",
"drumsplitpart1layer3modrate",
"drumsplitpart1bitreduction",
"drumsplitpart1fold",
"drumsplitpart1drive",
"drumsplitpart1drygain",
"drumsplitpart1send",
"drumsplitpart2pan",
"drumsplitpart2layer1select",
"drumsplitpart2layer2select",
"drumsplitpart2layer3select",
"drumsplitpart2layer1level",
"drumsplitpart2layer2level",
"drumsplitpart2layer3level",
"drumsplitpart2layer1attack",
"drumsplitpart2layer2attack",
"drumsplitpart2layer3attack",
"drumsplitpart2layer1release",
"drumsplitpart2layer2release",
"drumsplitpart2layer3release",
"drumsplitpart2layer1pitch",
"drumsplitpart2layer2pitch",
"drumsplitpart2layer3pitch",
"drumsplitpart2layer1modamt",
"drumsplitpart2layer2modamt",
"drumsplitpart2layer3modamt",
"drumsplitpart2layer1modrate",
"drumsplitpart2layer2modrate",
"drumsplitpart2layer3modrate",
"drumsplitpart2bitreduction",
"drumsplitpart2fold",
"drumsplitpart2drive",
"drumsplitpart2drygain",
"drumsplitpart2send",
"drumsplitpart3pan",
"drumsplitpart3layer1select",
"drumsplitpart3layer2select",
"drumsplitpart3layer3select",
"drumsplitpart3layer1level",
"drumsplitpart3layer2level",
"drumsplitpart3layer3level",
"drumsplitpart3layer1attack",
"drumsplitpart3layer2attack",
"drumsplitpart3layer3attack",
"drumsplitpart3layer1release",
"drumsplitpart3layer2release",
"drumsplitpart3layer3release",
"drumsplitpart3layer1pitch",
"drumsplitpart3layer2pitch",
"drumsplitpart3layer3pitch",
"drumsplitpart3layer1modamt",
"drumsplitpart3layer2modamt",
"drumsplitpart3layer3modamt",
"drumsplitpart3layer1modrate",
"drumsplitpart3layer2modrate",
"drumsplitpart3layer3modrate",
"drumsplitpart3bitreduction",
"drumsplitpart3fold",
"drumsplitpart3drive",
"drumsplitpart3drygain",
"drumsplitpart3send",
"drumsplitpart4pan",
"drumsplitpart4layer1select",
"drumsplitpart4layer2select",
"drumsplitpart4layer3select",
"drumsplitpart4layer1level",
"drumsplitpart4layer2level",
"drumsplitpart4layer3level",
"drumsplitpart4layer1attack",
"drumsplitpart4layer2attack",
"drumsplitpart4layer3attack",
"drumsplitpart4layer1release",
"drumsplitpart4layer2release",
"drumsplitpart4layer3release",
"drumsplitpart4layer1pitch",
"drumsplitpart4layer2pitch",
"drumsplitpart4layer3pitch",
"drumsplitpart4layer1modamt",
"drumsplitpart4layer2modamt",
"drumsplitpart4layer3modamt",
"drumsplitpart4layer1modrate",
"drumsplitpart4layer2modrate",
"drumsplitpart4layer3modrate",
"drumsplitpart4bitreduction",
"drumsplitpart4fold",
"drumsplitpart4drive",
"drumsplitpart4drygain",
"drumsplitpart4send",
"drumsplitpart5pan",
"drumsplitpart5layer1select",
"drumsplitpart5layer2select",
"drumsplitpart5layer3select",
"drumsplitpart5layer1level",
"drumsplitpart5layer2level",
"drumsplitpart5layer3level",
"drumsplitpart5layer1attack",
"drumsplitpart5layer2attack",
"drumsplitpart5layer3attack",
"drumsplitpart5layer1release",
"drumsplitpart5layer2release",
"drumsplitpart5layer3release",
"drumsplitpart5layer1pitch",
"drumsplitpart5layer2pitch",
"drumsplitpart5layer3pitch",
"drumsplitpart5layer1modamt",
"drumsplitpart5layer2modamt",
"drumsplitpart5layer3modamt",
"drumsplitpart5layer1modrate",
"drumsplitpart5layer2modrate",
"drumsplitpart5layer3modrate",
"drumsplitpart5bitreduction",
"drumsplitpart5fold",
"drumsplitpart5drive",
"drumsplitpart5drygain",
"drumsplitpart5send",
"drumsplitpart6pan",
"drumsplitpart6layer1select",
"drumsplitpart6layer2select",
"drumsplitpart6layer3select",
"drumsplitpart6layer1level",
"drumsplitpart6layer2level",
"drumsplitpart6layer3level",
"drumsplitpart6layer1attack",
"drumsplitpart6layer2attack",
"drumsplitpart6layer3attack",
"drumsplitpart6layer1release",
"drumsplitpart6layer2release",
"drumsplitpart6layer3release",
"drumsplitpart6layer1pitch",
"drumsplitpart6layer2pitch",
"drumsplitpart6layer3pitch",
"drumsplitpart6layer1modamt",
"drumsplitpart6layer2modamt",
"drumsplitpart6layer3modamt",
"drumsplitpart6layer1modrate",
"drumsplitpart6layer2modrate",
"drumsplitpart6layer3modrate",
"drumsplitpart6bitreduction",
"drumsplitpart6fold",
"drumsplitpart6drive",
"drumsplitpart6drygain",
"drumsplitpart6send",
"drumsplitwaveguidemodel",
"drumsplitdecay",
"drumsplitbody",
"drumsplittune",
},
{
"fmtranspose",
"fmevelocity",
"fmmodulatorattack",
"fmmodulatordecay",
"fmcarrierattack",
"fmcarrierdecay",
"fmlforate",
"fmlfopitchdepth",
"fmalgorithm",
"fmarpeggiatortype",
"fmarpeggiatordiv",
"fmpajenchorus",
"fmpajenchorusstereowidth",
"fmpajenchorusspeed",
"fmpajenloadpatch",
"fmpajenloadpattern",
"fmpajentempodivisor",
"fmpajenmodwheelcc",
},
{
"keysportamento",
"keysexpression",
"keysvoice",
"keysoctave",
"keysdetune",
"keysenvelopeintensity",
"keysvcfcutoff",
"keysvcfenvelopeintensity",
"keyslforate",
"keyslfopitchintensity",
"keyslfocutoffintensity",
"keysenvelopeattack",
"keysenvelopedecayrelease",
"keysenvelopesustain",
"keysdelaytime",
"keysdelayfeedback",
},
{
"kickpulsecolor",
"kickpulselevel",
"kickampattack",
"kickampdecay",
"kickdrive",
"kicktone",
"kickresonatorpitch",
"kickresonatorbend",
"kickresonatortime",
"kickaccent",
},
{
"nubassvtopitch",
"nubassvtosaturation",
"nubassvtolevel",
"nubassvcfcutoff",
"nubassvcfpeak",
"nubassvcfattack",
"nubassvcfdecay",
"nubassvcfegintensity",
"nubassaccent",
"nubasslforate",
"nubasslfointensity",
},
{
"sample1part1level",
"sample1part1pan",
"sample1part1startpoint",
"sample1part1length",
"sample1part1hicutoff",
"sample1part1speed",
"sample1part1pitchegintensity",
"sample1part1pitchegattack",
"sample1part1pitchegdecay",
"sample1part1ampegattack",
"sample1part1ampegdecay",
"sample1part1pajensampleselect",
"sample1part1pajenpartselect",
"sample1part1pajenreversepart",
"sample1part1pajenmutepart",
"sample1part1pajensolopart",
"sample1part1pajenloop",
"sample1part1pajenreverbtype",
"sample1part1pajenreverblevel",
"sample1part1pajenreverbonoff",
"sample1part2level",
"sample1part2pan",
"sample1part2startpoint",
"sample1part2length",
"sample1part2hicutoff",
"sample1part2speed",
"sample1part2pitchegintensity",
"sample1part2pitchegattack",
"sample1part2pitchegdecay",
"sample1part2ampegattack",
"sample1part2ampegdecay",
"sample1part2pajensampleselect",
"sample1part2pajenpartselect",
"sample1part2pajenreversepart",
"sample1part2pajenmutepart",
"sample1part2pajensolopart",
"sample1part2pajenloop",
"sample1part2pajenreverbtype",
"sample1part2pajenreverblevel",
"sample1part2pajenreverbonoff",
"sample1part3level",
"sample1part3pan",
"sample1part3startpoint",
"sample1part3length",
"sample1part3hicutoff",
"sample1part3speed",
"sample1part3pitchegintensity",
"sample1part3pitchegattack",
"sample1part3pitchegdecay",
"sample1part3ampegattack",
"sample1part3ampegdecay",
"sample1part3pajensampleselect",
"sample1part3pajenpartselect",
"sample1part3pajenreversepart",
"sample1part3pajenmutepart",
"sample1part3pajensolopart",
"sample1part3pajenloop",
"sample1part3pajenreverbtype",
"sample1part3pajenreverblevel",
"sample1part3pajenreverbonoff",
"sample1part4level",
"sample1part4pan",
"sample1part4startpoint",
"sample1part4length",
"sample1part4hicutoff",
"sample1part4speed",
"sample1part4pitchegintensity",
"sample1part4pitchegattack",
"sample1part4pitchegdecay",
"sample1part4ampegattack",
"sample1part4ampegdecay",
"sample1part4pajensampleselect",
"sample1part4pajenpartselect",
"sample1part4pajenreversepart",
"sample1part4pajenmutepart",
"sample1part4pajensolopart",
"sample1part4pajenloop",
"sample1part4pajenreverbtype",
"sample1part4pajenreverblevel",
"sample1part4pajenreverbonoff",
"sample1part5level",
"sample1part5pan",
"sample1part5startpoint",
"sample1part5length",
"sample1part5hicutoff",
"sample1part5speed",
"sample1part5pitchegintensity",
"sample1part5pitchegattack",
"sample1part5pitchegdecay",
"sample1part5ampegattack",
"sample1part5ampegdecay",
"sample1part5pajensampleselect",
"sample1part5pajenpartselect",
"sample1part5pajenreversepart",
"sample1part5pajenmutepart",
"sample1part5pajensolopart",
"sample1part5pajenloop",
"sample1part5pajenreverbtype",
"sample1part5pajenreverblevel",
"sample1part5pajenreverbonoff",
"sample1part6level",
"sample1part6pan",
"sample1part6startpoint",
"sample1part6length",
"sample1part6hicutoff",
"sample1part6speed",
"sample1part6pitchegintensity",
"sample1part6pitchegattack",
"sample1part6pitchegdecay",
"sample1part6ampegattack",
"sample1part6ampegdecay",
"sample1part6pajensampleselect",
"sample1part6pajenpartselect",
"sample1part6pajenreversepart",
"sample1part6pajenmutepart",
"sample1part6pajensolopart",
"sample1part6pajenloop",
"sample1part6pajenreverbtype",
"sample1part6pajenreverblevel",
"sample1part6pajenreverbonoff",
"sample1part7level",
"sample1part7pan",
"sample1part7startpoint",
"sample1part7length",
"sample1part7hicutoff",
"sample1part7speed",
"sample1part7pitchegintensity",
"sample1part7pitchegattack",
"sample1part7pitchegdecay",
"sample1part7ampegattack",
"sample1part7ampegdecay",
"sample1part7pajensampleselect",
"sample1part7pajenpartselect",
"sample1part7pajenreversepart",
"sample1part7pajenmutepart",
"sample1part7pajensolopart",
"sample1part7pajenloop",
"sample1part7pajenreverbtype",
"sample1part7pajenreverblevel",
"sample1part7pajenreverbonoff",
"sample1part8level",
"sample1part8pan",
"sample1part8startpoint",
"sample1part8length",
"sample1part8hicutoff",
"sample1part8speed",
"sample1part8pitchegintensity",
"sample1part8pitchegattack",
"sample1part8pitchegdecay",
"sample1part8ampegattack",
"sample1part8ampegdecay",
"sample1part8pajensampleselect",
"sample1part8pajenpartselect",
"sample1part8pajenreversepart",
"sample1part8pajenmutepart",
"sample1part8pajensolopart",
"sample1part8pajenloop",
"sample1part8pajenreverbtype",
"sample1part8pajenreverblevel",
"sample1part8pajenreverbonoff",
"sample1part9level",
"sample1part9pan",
"sample1part9startpoint",
"sample1part9length",
"sample1part9hicutoff",
"sample1part9speed",
"sample1part9pitchegintensity",
"sample1part9pitchegattack",
"sample1part9pitchegdecay",
"sample1part9ampegattack",
"sample1part9ampegdecay",
"sample1part9pajensampleselect",
"sample1part9pajenpartselect",
"sample1part9pajenreversepart",
"sample1part9pajenmutepart",
"sample1part9pajensolopart",
"sample1part9pajenloop",
"sample1part9pajenreverbtype",
"sample1part9pajenreverblevel",
"sample1part9pajenreverbonoff",
"sample1part10level",
"sample1part10pan",
"sample1part10startpoint",
"sample1part10length",
"sample1part10hicutoff",
"sample1part10speed",
"sample1part10pitchegintensity",
"sample1part10pitchegattack",
"sample1part10pitchegdecay",
"sample1part10ampegattack",
"sample1part10ampegdecay",
"sample1part10pajensampleselect",
"sample1part10pajenpartselect",
"sample1part10pajenreversepart",
"sample1part10pajenmutepart",
"sample1part10pajensolopart",
"sample1part10pajenloop",
"sample1part10pajenreverbtype",
"sample1part10pajenreverblevel",
"sample1part10pajenreverbonoff",
},
{
"sample2part1level",
"sample2part1pan",
"sample2part1startpoint",
"sample2part1length",
"sample2part1hicutoff",
"sample2part1speed",
"sample2part1pitchegintensity",
"sample2part1pitchegattack",
"sample2part1pitchegdecay",
"sample2part1ampegattack",
"sample2part1ampegdecay",
"sample2part2level",
"sample2part2pan",
"sample2part2ampegattack",
"sample2part2ampegdecay",
"sample2part2hicutoff",
"sample2part3level",
"sample2part3pan",
"sample2part3hicutoff",
"sample2part3ampegattack",
"sample2part3ampegdecay",
"sample2part4level",
"sample2part4pan",
"sample2part4ampegattack",
"sample2part4ampegdecay",
"sample2part4hicutoff",
"sample2part5level",
"sample2part5pan",
"sample2part5ampegattack",
"sample2part5ampegdecay",
"sample2part5hicutoff",
"sample2part6level",
"sample2part6pan",
"sample2part6hicutoff",
"sample2part6ampegattack",
"sample2part6ampegdecay",
"sample2part7level",
"sample2part7pan",
"sample2part7ampegattack",
"sample2part7ampegdecay",
"sample2part7hicutoff",
"sample2part8level",
"sample2part8pan",
"sample2part8ampegattack",
"sample2part8ampegdecay",
"sample2part8hicutoff",
"sample2part9level",
"sample2part9pan",
"sample2part9ampegattack",
"sample2part9ampegdecay",
"sample2part9hicutoff",
"sample2part10level",
"sample2part10pan",
"sample2part10ampegattack",
"sample2part10ampegdecay",
"sample2part10hicutoff",
}
};
public boolean getSendsAllParametersAsDump() { return false; }
public Object[] emitAll(String key)
{
if (key.equals("name")) return new Object[0]; // this is not emittable
// Which panel is being displayed?
String panel = PREFIXES[getSynthType()];
if (key.startsWith(panel))
{
// doit
if (key.startsWith("sample1"))
{
int num = StringUtility.getSecondInt(key);
return buildCC(num - 1, ((Integer)allParametersToCC.get(key)).intValue(), model.get(key, 0));
}
else if (key.startsWith("drumsplit") &&
!key.equals("drumsplitwaveguidemodel") &&
!key.equals("drumsplitdecay") &&
!key.equals("drumsplitbody") &&
!key.equals("drumsplittune"))
{
int num = StringUtility.getFirstInt(key); // part
return buildCC(num - 1, ((Integer)allParametersToCC.get(key)).intValue(), model.get(key, 0));
}
else
{
return buildCC(getChannelOut(), ((Integer)allParametersToCC.get(key)).intValue(), model.get(key, 0));
}
}
else return new Object[0];
}
public int parse(byte[] data, boolean fromFile)
{
// grab name
char[] name = new char[16];
for(int i = 0; i < 16; i++)
{
name[i] = (char)(data[i + 20] & 127);
if (name[i] >= 127 || name[i] < ' ')
name[i] = ' ';
}
model.set("name", String.valueOf(name));
// determine type
int type = data[20 + 16];
int pos = 21 + 16;
if (type == 0) // "All Volcas"
{
for(int j = 0; j < allParameters.length; j++)
{
for(int i = 0; i < allParameters[j].length; i++)
{
model.set(allParameters[j][i], data[pos++] & 127);
}
}
}
else
{
for(int i = 0; i < allParameters[type - 1].length; i++)
{
model.set(allParameters[type - 1][i], data[pos++] & 127);
}
}
if (type > 0)
{
setSynthType(type - 1, true);
}
return PARSE_SUCCEEDED;
}
public static final int INIT_PATCH_DATA_LENGTH = 567;
public byte[] emit(Model tempModel, boolean toWorkingMemory, boolean toFile)
{
if (tempModel == null)
tempModel = getModel();
final boolean initPatch = false;
int type = getSynthType();
byte[] data = new byte[(initPatch ? INIT_PATCH_DATA_LENGTH : allParameters[type].length) + 38];
data[0] = (byte)0xF0;
data[1] = (byte)0x7D;
data[2] = (byte)'E';
data[3] = (byte)'D';
data[4] = (byte)'I';
data[5] = (byte)'S';
data[6] = (byte)'Y';
data[7] = (byte)'N';
data[8] = (byte)' ';
data[9] = (byte)'K';
data[10] = (byte)'O';
data[11] = (byte)'R';
data[12] = (byte)'G';
data[13] = (byte)' ';
data[14] = (byte)'V';
data[15] = (byte)'O';
data[16] = (byte)'L';
data[17] = (byte)'C';
data[18] = (byte)'A';
// Load version
data[19] = (byte) 0;
// Set end
data[data.length - 1] = (byte)0xF7;
// Load name
char[] name = (model.get("name", "") + " ").substring(0, 16).toCharArray();
for(int i = 0; i < name.length; i++)
{
if (name[i] < ' ' || name[i] >= 127)
name[i] = ' ';
data[i + 20] = (byte)(name[i]);
}
if (initPatch)
{
// This code is used to generate the init patch
data[20 + 16] = (byte) 0;
int pos = 21 + 16;
for(int j = 0; j < allParameters.length; j++)
{
for(int i = 0; i < allParameters[j].length; i++)
{
data[pos++] = (byte)(model.get(allParameters[j][i], 0));
}
}
}
else
{
// This is the standard data output load type
data[20 + 16] = (byte) (type + 1);
for(int i = 0; i < allParameters[type].length; i++)
{
data[21 + 16 + i] = (byte)(model.get(allParameters[type][i], 0));
}
}
return data;
}
public static final int MAXIMUM_NAME_LENGTH = 16;
public String revisePatchName(String name)
{
name = super.revisePatchName(name); // trim first time
if (name.length() > MAXIMUM_NAME_LENGTH)
name = name.substring(0, MAXIMUM_NAME_LENGTH);
StringBuffer nameb = new StringBuffer(name);
for(int i = 0 ; i < nameb.length(); i++)
{
char c = nameb.charAt(i);
if (c < 32 || c > 127)
nameb.setCharAt(i, ' ');
}
name = nameb.toString();
return super.revisePatchName(name); // trim again
}
public void revise()
{
// check the easy stuff -- out of range parameters
super.revise();
String nm = model.get("name", "Untitled");
String newnm = revisePatchName(nm);
if (!nm.equals(newnm))
model.set("name", newnm);
}
public String getPatchName(Model model) { return model.get("name", "Untitled"); }
public boolean testVerify(Synth synth2, String key, Object val1, Object val2)
{
if (key.equals("name"))
{
return ((String)val1).trim() != ((String)val2).trim();
}
// we ignore keys that don't start with the prefix we're interested in
else if (!key.startsWith(PREFIXES[getSynthType()]))
return true;
return false;
}
} |
package radlab.rain.workload.scadr;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashSet;
import java.util.Random;
//import java.util.regex.Pattern;
//import java.util.regex.Matcher;
import javax.xml.parsers.DocumentBuilderFactory;
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.StringBody;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import radlab.rain.Generator;
import radlab.rain.LoadProfile;
import radlab.rain.IScoreboard;
import radlab.rain.Operation;
import radlab.rain.ScenarioTrack;
import radlab.rain.util.HttpTransport;
import java.security.MessageDigest;
import java.math.BigInteger;
public abstract class ScadrOperation extends Operation
{
public static String AUTH_TOKEN_PATTERN = "(<input name=\"authenticity_token\" (type=\"hidden\") value=\"(\\S*)\" />)";
public static String ALPHABET = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final int MAX_THOUGHT_LENGTH = 140;
// These references will be set by the Generator.
protected HttpTransport _http;
protected HashSet<String> _cachedURLs = new HashSet<String>();
private Random _random = new Random();
// Keep track of where this operation is supposed to go so that
// we can update the app server traffic stats
private String _appServerTarget = "";
public ScadrOperation(boolean interactive, IScoreboard scoreboard)
{
super(interactive, scoreboard);
}
public ScadrGenerator getGenerator()
{
return (ScadrGenerator) this._generator;
}
@Override
public void cleanup()
{}
@Override
public void preExecute()
{
if( this._appServerTarget == null || this._appServerTarget.trim().length() == 0 )
return;
ScenarioTrack track = this._generator.getTrack();
if( track instanceof ScadrScenarioTrack )
((ScadrScenarioTrack) track).requestIssue( this._appServerTarget );
}
@Override
public void postExecute()
{
if( this._appServerTarget == null || this._appServerTarget.trim().length() == 0 )
return;
ScenarioTrack track = this._generator.getTrack();
if( track instanceof ScadrScenarioTrack )
((ScadrScenarioTrack) track).requestRetire( this._appServerTarget );
}
@Override
public void prepare(Generator generator) {
this._generator = generator;
ScadrGenerator scadrGenerator = (ScadrGenerator) generator;
// Save the appServer target that's currently in the generator
this._appServerTarget = scadrGenerator._appServerUrl;
// Refresh the cache to simulate real-world browsing.
this.refreshCache();
this._http = scadrGenerator.getHttpTransport();
LoadProfile currentLoadProfile = scadrGenerator.getLatestLoadProfile();
if( currentLoadProfile != null )
this.setGeneratedDuringProfile( currentLoadProfile );
}
/**
* Load the static files specified by the URLs if the current request is
* not cached and the file was not previously loaded and cached.
*
* @param urls The set of static file URLs.
* @return The number of static files loaded.
*
* @throws IOException
*/
protected long loadStatics( String[] urls ) throws IOException
{
long staticsLoaded = 0;
for ( String url : urls )
{
if ( this._cachedURLs.add( url ) )
{
this._http.fetchUrl( url );
staticsLoaded++;
}
}
return staticsLoaded;
}
/**
* Refreshes the cache by resetting it 40% of the time.
*
* @return True if the cache was refreshed; false otherwise.
*/
protected boolean refreshCache()
{
boolean resetCache = ( this._random.nextDouble() < 0.6 );
if ( resetCache )
{
this._cachedURLs.clear();
}
return resetCache;
}
/*public String parseAuthTokenRegex( StringBuilder buffer ) throws IOException
{
String token = "";
//System.out.println( buffer.toString() );
Pattern authTokenPattern = Pattern.compile( AUTH_TOKEN_PATTERN, Pattern.CASE_INSENSITIVE );
Matcher match = authTokenPattern.matcher( buffer.toString() );
//System.out.println( "Groups: " + match.groupCount() );
if( match.find() )
{
//System.out.println( buffer.substring( match.start(), match.end()) );
//System.out.println( match.group(3) );
token = match.group( 3 );
}
return token;
}*/
/**
* Parses an HTML document for an authenticity token used by the Ruby on
* Rails framework to authenticate forms.
*
* @param buffer The HTTP response; expected to be an HTML document.
* @return The authenticity token if found; otherwise, null.
*
* @throws IOException
*/
public String parseAuthTokenSAX( StringBuilder buffer ) throws IOException
{
String token = "";
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false );
Document document = factory.newDocumentBuilder().parse( new InputSource( new StringReader( buffer.toString() ) ) );
NodeList inputList = document.getElementsByTagName("input");
for ( int i = 0; i < inputList.getLength(); i++ )
{
Element input = (Element) inputList.item(i);
String name = input.getAttribute("name");
if ( name.equals("authenticity_token") )
{
token = input.getAttribute("value");
break;
}
}
}
catch ( Exception e )
{
//e.printStackTrace();
}
return token;
}
/*
public static void main( String[] args )
{
String input = "<form action=\"/user_session\" class=\"new_user_session\" id=\"user_session_3558\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"authenticity_token\" type=\"hidden\" value=\"XiJqPX2XOX0y3RHpVHLbhrjxcuDDnUTcvkrGVP7yDXk=\" /></div>";
Pattern authTokenPattern = Pattern.compile( "<input name=\"authenticity_token\" (.)* value=\"(.*)\"", Pattern.CASE_INSENSITIVE );
Matcher match = authTokenPattern.matcher( input );
match.find();
System.out.println( "Groups: " + match.groupCount() );
System.out.println( match.group(2) );
}*/
// Add all the methods here for viewing the homepage, logging in etc. so that we could
// reuse them from other operations if necessary
public String doHomePage() throws Exception
{
long start = 0;
long end = 0;
boolean debug = this.getGenerator().getIsDebugMode();
if( debug )
start = System.currentTimeMillis();
//System.out.println( "Starting HomePage" );
String authToken = "";
StringBuilder response = this._http.fetchUrl( this.getGenerator()._homeUrl );
this.trace( this.getGenerator()._homeUrl );
if( response.length() == 0 || this._http.getStatusCode() > 399 )
{
String errorMessage = "Home page GET ERROR - Received an empty/error response. HTTP Status Code: " + this._http.getStatusCode();
throw new IOException( errorMessage );
}
// Get the authenticity token for login and pass it to the generator so that it can
// be used to log in if necessary
authToken = "";//this.parseAuthTokenRegex( response );
this.loadStatics( this.getGenerator().homepageStatics );
this.trace( this.getGenerator().homepageStatics );
//System.out.println( "HomePage worked" );
if( debug )
{
end = System.currentTimeMillis();
System.out.println( "HomePage (s): " + (end - start)/1000.0 );
}
return authToken;
}
public void doCreateUser( String username ) throws Exception
{
long start = 0;
long end = 0;
boolean debug = this.getGenerator().getIsDebugMode();
if( debug )
start = System.currentTimeMillis();
//System.out.println( "Starting CreateUser" );
// Load the create user page to get the auth token
StringBuilder response = this._http.fetchUrl( this.getGenerator()._createUserUrl );
this.trace( this.getGenerator()._createUserUrl );
if( response.length() == 0 || this._http.getStatusCode() > 399 )
{
String errorMessage = "Create user page GET ERROR - Received an empty/error response. HTTP Status Code: " + this._http.getStatusCode();
throw new IOException( errorMessage );
}
// Get the authToken
/*String authToken = this.parseAuthTokenRegex( response );
if( authToken == null || authToken.trim().length() == 0 )
throw new Exception( "Authenticity token not found." );*/
// Load the other statics
this.loadStatics( this.getGenerator().createuserpageStatics );
this.trace( this.getGenerator().createuserpageStatics );
// Pick a random city (hometown)- we could implement a hometown hotspot here if we want
int rndCity = this._random.nextInt( ScadrGenerator.US_CITIES.length );
String hometown = ScadrGenerator.US_CITIES[rndCity];
String commitAction = "Submit";
/*
authenticity_token XiJqPX2XOX0y3RHpVHLbhrjxcuDDnUTcvkrGVP7yDXk=
commit Save changes
user[home_town] somewhere's ville
user[username] testuser
user[password] foo
confirm_password foo
*/
// Post the to create user results url
HttpPost httpPost = new HttpPost( this.getGenerator()._createUserResultUrl );
// Weird things happen if we don't specify HttpMultipartMode.BROWSER_COMPATIBLE.
// Scadr rejects the auth token as invalid without it. Not sure if this is a
// Scadr-specific issue or not. HTTP POSTs by the Olio (Ruby web-app) driver
// worked without it.
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
//entity.addPart( "authenticity_token", new StringBody( authToken ) );
entity.addPart( "commit", new StringBody( commitAction ) );
entity.addPart( "user[home_town]", new StringBody( hometown ) );
entity.addPart( "user[username]", new StringBody( username ) );
entity.addPart( "user[plain_password]", new StringBody( username ) );
entity.addPart( "user[confirm_password]", new StringBody( username ) );
httpPost.setEntity( entity );
// Make the POST request and verify that it succeeds.
response = this._http.fetch( httpPost );
//System.out.println( response );
// Look at the response for the string 'Your account "<username>" has been created!'
StringBuilder successMessage = new StringBuilder();
successMessage.append( "Your account \"" );
successMessage.append( username.toString() );
successMessage.append( "\" has been created!" );
if(! (response.toString().contains( successMessage.toString() ) ) )
throw new Exception( "Creating new user: " + username.toString() + " failed! No success message found. HTTP Status Code: " + this._http.getStatusCode() );
this.trace( this.getGenerator()._createUserResultUrl );
//System.out.println( "CreateUser worked" );
if( debug )
{
end = System.currentTimeMillis();
System.out.println( "CreateUser (s): " + (end - start)/1000.0 );
}
}
public void doCreateUser() throws Exception
{
// If we're already logged in then skip the creation step
if( this.getGenerator().getIsLoggedIn() )
{
//System.out.println( "Skipping user creation since we're already logged in." );
return;
}
//else System.out.println( "Not logged in." );
// Make up a username - just user-<generatedBy>
String username = this.getUsername();
this.doCreateUser( username );
// Save the username in the generator
this.getGenerator()._username = username;
// Creating a user for ourselves automatically logs us in
this.getGenerator().setIsLoggedIn( true );
}
public boolean doLogin() throws Exception
{
if( this.getGenerator().getIsLoggedIn() )
return true; // Don't re-login
long start = 0;
long end = 0;
boolean debug = this.getGenerator().getIsDebugMode();
if( debug )
start = System.currentTimeMillis();
//System.out.println( "Starting Login" );
StringBuilder response = this._http.fetchUrl( this.getGenerator()._loginUrl );
this.trace( this.getGenerator()._loginUrl );
if( response == null || response.length() == 0 || this._http.getStatusCode() > 399 )
{
String errorMessage = "";
if( response != null )
errorMessage = "Login page GET ERROR - Received an empty/error response. URL: " + this.getGenerator()._loginUrl + " HTTP Status Code: " + this._http.getStatusCode() + " Response: " + response.toString();
else errorMessage = "Login page GET ERROR - Received an empty/error response. URL: " + this.getGenerator()._loginUrl + " HTTP Status Code: " + this._http.getStatusCode() + " Response: NULL";
throw new IOException( errorMessage );
}
// Get the authToken
/*String authToken = this.parseAuthTokenRegex( response );
if( authToken == null || authToken.trim().length() == 0 )
throw new Exception( "Authenticity token not found." );*/
// Load the other statics
this.loadStatics( this.getGenerator().loginpageStatics );
this.trace( this.getGenerator().loginpageStatics );
/*
authenticity_token XiJqPX2XOX0y3RHpVHLbhrjxcuDDnUTcvkrGVP7yDXk=
commit Login
user_session[username] user-
user_session[password] user-
*/
// Get the username from the generator - if it's not there then make up one
String username = this.getGenerator()._username;
if( username == null || username.trim().length() == 0 )
username = this.getUsername();
String commitAction = "Login";
HttpPost httpPost = new HttpPost( this.getGenerator()._loginResultUrl );
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
//entity.addPart( "authenticity_token", new StringBody( authToken ) );
entity.addPart( "commit", new StringBody( commitAction ) );
entity.addPart( "user_session[username]", new StringBody( username ) );
entity.addPart( "user_session[password]", new StringBody( username ) );
httpPost.setEntity( entity );
// Make the POST request and verify that it succeeds.
response = this._http.fetch( httpPost );
// See whether we were logged in - if not doCreateUser and try again
StringBuilder successMessage = new StringBuilder();
successMessage.append( "Logged in as " ).append( username.toString() );
// Return true if we're able to log in
if( response.toString().contains( successMessage.toString() ) )
{
//System.out.println( "Login worked" );
if( debug )
{
end = System.currentTimeMillis();
System.out.println( "Login (s): " + (end - start)/1000.0 );
}
return true;
}
else throw new Exception( "Error unable to log in. No success message found. HTTP Status Code: " + this._http.getStatusCode() + " Response: " + response.toString() );
}
public void doPostThought() throws Exception
{
long start = 0;
long end = 0;
boolean debug = this.getGenerator().getIsDebugMode();
if( debug )
start = System.currentTimeMillis();
//System.out.println( "Starting PostThought" );
boolean result = false;
// See whether we're logged in - if not try to log in
if( !this.getGenerator().getIsLoggedIn() )
result = this.doLogin();
else result = true;
if( !result )
throw new Exception( "Error logging in. Can't post thought." );
String username = this.getGenerator()._username;
if( username == null || username.trim().length() == 0 )
username = this.getUsername();
// Fetch the post thoughts page
String postThoughtUrl = String.format( this.getGenerator()._postThoughtUrlTemplate, username );
StringBuilder response = this._http.fetchUrl( postThoughtUrl );
this.trace( postThoughtUrl );
if( response.length() == 0 || this._http.getStatusCode() > 399 )
{
String errorMessage = "PostThought page GET ERROR - Received an empty/error response. HTTP Status Code: " + this._http.getStatusCode();
throw new IOException( errorMessage );
}
// Get the auth token
/*String authToken = this.parseAuthTokenRegex( response );
if( authToken == null || authToken.trim().length() == 0 )
throw new Exception( "Authenticity token not found." );*/
// Load the other statics
this.loadStatics( this.getGenerator().postthoughtpageStatics );
this.trace( this.getGenerator().postthoughtpageStatics );
/*
authenticity_token XiJqPX2XOX0y3RHpVHLbhrjxcuDDnUTcvkrGVP7yDXk=
commit Think
thought[text] thought 1
*/
String commitAction = "Think";
String thought = this.getThought();
String postThoughtResultUrl = String.format( this.getGenerator()._postThoughtResultUrlTemplate, username );
HttpPost httpPost = new HttpPost( postThoughtResultUrl );
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
//entity.addPart( "authenticity_token", new StringBody( authToken ) );
entity.addPart( "commit", new StringBody( commitAction ) );
entity.addPart( "thought[text]", new StringBody( thought ) );
httpPost.setEntity( entity );
// Make the POST request and verify that it succeeds.
response = this._http.fetch( httpPost );
//String postBody = "authenticity_token=" + authToken + "&commit=" + commitAction + "&thought[text]=" + thought;
//response = this._http.fetchUrl( postThoughtResultUrl, postBody );
String successMessage = "New thought created.";
if( !response.toString().contains( successMessage.toString() ) )
{
throw new Exception( "Unable to create new thought." + " Logged in status: " + this.getGenerator().getIsLoggedIn() + " URL: " + postThoughtResultUrl + " HTTP Status Code: " + this._http.getStatusCode() + " Response: " + response.toString() );
}
else
{
//System.out.println( "PostThought worked." );
if( debug )
{
end = System.currentTimeMillis();
System.out.println( "PostThought (s): " + (end - start)/1000.0 );
}
}
}
public void doLogout() throws Exception
{
if( !this.getGenerator().getIsLoggedIn() )
return;
long start = 0;
long end = 0;
boolean debug = this.getGenerator().getIsDebugMode();
if( debug )
start = System.currentTimeMillis();
StringBuilder response = this._http.fetchUrl( this.getGenerator()._logoutUrl );
this.trace( this.getGenerator()._logoutUrl );
if( response.length() == 0 || this._http.getStatusCode() > 399 )
{
String errorMessage = "";
if( response != null )
errorMessage = "Logout page GET ERROR - Received an empty/error response. " + " Logged in status: " + this.getGenerator().getIsLoggedIn() + " URL: " + this.getGenerator()._logoutUrl + " HTTP Status Code: " + this._http.getStatusCode() + " Response length: " + response.length();
else errorMessage = "Logout page GET ERROR - Received an empty/error response. " + " Logged in status: " + this.getGenerator().getIsLoggedIn() +" URL: " + this.getGenerator()._logoutUrl + " HTTP Status Code: " + this._http.getStatusCode() + " Response length: 0/NULL";
throw new IOException( errorMessage );
}
String successMessage = "You are now logged out.";
if( !response.toString().contains( successMessage.toString() ) )
throw new Exception( "Unable to log out. HTTP Status Code: " + this._http.getStatusCode() + " Response: " + response.toString() );
if( debug )
{
end = System.currentTimeMillis();
System.out.println( "Logout (s): " + (end - start)/1000.0 );
}
// Update the generator to indicate that we've logged out
this.getGenerator().setIsLoggedIn( false );
}
public void doSubscribe( boolean createTargetUser ) throws Exception
{
long start = 0;
long end = 0;
boolean debug = this.getGenerator().getIsDebugMode();
if( debug )
start = System.currentTimeMillis();
//System.out.println( "Starting Subscribe" );
boolean result = false;
// If we're not logged in, try to log in
if( !this.getGenerator().getIsLoggedIn() )
result = this.doLogin();
else result = true;
if( !result )
throw new Exception( "Error logging in. Can't subscribe to user." );
String me = this.getGenerator()._username;
if( me == null || me.trim().length() == 0 )
me = this.getUsername();
// Randomly pick a target based on the number of users running in this track.
// We can implement a data hotspot here if we want some users more sought after to follow.
String targetUser = me;
// We can't subscribe to ourselves, so keep trying to pick someone else
while( targetUser.equals( me ) )
targetUser = this.subscribeToUser( this.getGenerator().getTrack().getMaxUsers() );
String targetUserUrl = String.format( this.getGenerator()._postThoughtUrlTemplate, targetUser );
// Do a get for that user - look for a subscribe button
StringBuilder response = this._http.fetchUrl( targetUserUrl );
this.trace( targetUserUrl );
if( response.length() == 0 || this._http.getStatusCode() > 399 || response.toString().contains( "does not exist" ) )
{
// Create user if they don't exist
if( !createTargetUser )
{
String errorMessage = "Subscribe to user page GET ERROR - Received an empty/error response. HTTP Status Code: " + this._http.getStatusCode();
throw new IOException( errorMessage );
}
else
{
//System.out.println( "Creating target user: " + targetUser + " so we can subscribe to their thoughtstream." );
this.doCreateUser( targetUser );
}
}
// Get the auth token
/*
String authToken = this.parseAuthTokenRegex( response );
if( authToken == null || authToken.trim().length() == 0 )
throw new Exception( "Authenticity token not found." );*/
// Load the other statics
this.loadStatics( this.getGenerator().postthoughtpageStatics );
this.trace( this.getGenerator().postthoughtpageStatics );
/*
authenticity_token XiJqPX2XOX0y3RHpVHLbhrjxcuDDnUTcvkrGVP7yDXk=
commit Subscribe
subscription[target] foo
*/
String commitAction = "Subscribe";
String createSubscriptionResultUrl = String.format( this.getGenerator()._createSubscriptionResultUrlTemplate, me );
HttpPost httpPost = new HttpPost( createSubscriptionResultUrl );
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
//entity.addPart( "authenticity_token", new StringBody( authToken ) );
entity.addPart( "commit", new StringBody( commitAction ) );
entity.addPart( "subscription[target]", new StringBody( targetUser ) );
httpPost.setEntity( entity );
// Make the POST request and verify that it succeeds.
response = this._http.fetch( httpPost );
String successMessage1 = "Subscribed to " + targetUser;
String successMessage2 = "You are subscribed to " + targetUser;
if( response.toString().contains( successMessage1.toString() ) ||
response.toString().contains( successMessage2.toString() ) )
{
//System.out.println( "Subscribe worked" );
if( debug )
{
end = System.currentTimeMillis();
System.out.println( "Subscribe (s): " + (end - start)/1000.0 );
}
return;
}
else
{
if( response != null )
throw new Exception( "Unable to subscribe to user: " + targetUser + " Logged in status: " + this.getGenerator().getIsLoggedIn() + " URL: " + createSubscriptionResultUrl + " HTTP Status Code: " + this._http.getStatusCode() + " Response: " + response.toString() );
else throw new Exception( "Unable to subscribe to user: " + targetUser + " Logged in status: " + this.getGenerator().getIsLoggedIn() + " URL: " + createSubscriptionResultUrl + " HTTP Status Code: " + this._http.getStatusCode() + " Response: NULL" );
}
}
private String subscribeToUser( int numberOfUsers )
{
if( numberOfUsers == 1 )
return "fakeUser";
int rndTarget = this._random.nextInt( numberOfUsers );
StringBuilder target = new StringBuilder();
target.append( "user-").append( this.getGenerator().getTrack().getName() ).append( "-Generator-" ).append( rndTarget );
return distributeUserName(target.toString());
}
private String getUsername()
{
// User names can't have any periods in them
return distributeUserName("user-" + this._generatedBy.replace( '.', '-'));
}
//Append a hash to the beginning of usernames so they distribute better
private String distributeUserName(String username)
{
//Stupid checked exceptions
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(username.getBytes(), 0, username.length());
byte[] md5Sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5Sum);
return bigInt.toString(16) + username;
}
catch (Exception e) {
System.out.println("CANT CALCULATE HASH using undistributed username");
return username;
}
}
private String getThought()
{
StringBuilder thought = new StringBuilder();
int maxCount = ScadrOperation.MAX_THOUGHT_LENGTH;
// Pick elements randomly from the alphabet - every 3 characters flip a coin on inserting
// a space
while( maxCount > 0 )
{
char rndChar = ScadrOperation.ALPHABET.charAt( this._random.nextInt( ScadrOperation.ALPHABET.length() ) );
if( maxCount % 3 == 0 )
{
if( this._random.nextDouble() < 0.3 )
thought.append( " " );
else thought.append( rndChar );
}
else thought.append( rndChar );
maxCount
}
return thought.toString();
}
} |
package com.namelessdev.mpdroid.helpers;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import com.namelessdev.mpdroid.MPDApplication;
import com.namelessdev.mpdroid.cover.CachedCover;
import com.namelessdev.mpdroid.cover.ICoverRetriever;
import com.namelessdev.mpdroid.cover.LastFMCover;
import com.namelessdev.mpdroid.cover.LocalCover;
/**
* Download Covers Asynchronous with Messages
*
* @author Stefan Agner
* @version $Id: $
*/
public class CoverAsyncHelper extends Handler {
private static final int EVENT_DOWNLOADCOVER = 0;
private static final int EVENT_COVERDOWNLOADED = 1;
private static final int EVENT_COVERNOTFOUND = 2;
private static final int MAX_SIZE = 0;
public static final String PREFERENCE_CACHE = "enableLocalCoverCache";
public static final String PREFERENCE_LASTFM = "enableLastFM";
public static final String PREFERENCE_LOCALSERVER = "enableLocalCover";
private MPDApplication app = null;
private SharedPreferences settings = null;
private ICoverRetriever[] coverRetrievers = null;
private int coverMaxSize = 0;
public void setCoverRetrievers(List<CoverRetrievers> whichCoverRetrievers) {
if (whichCoverRetrievers == null) {
coverRetrievers = new ICoverRetriever[0];
}
coverRetrievers = new ICoverRetriever[whichCoverRetrievers.size()];
for (int i = 0; i < whichCoverRetrievers.size(); i++) {
switch (whichCoverRetrievers.get(i)) {
case CACHE:
this.coverRetrievers[i] = new CachedCover(app);
break;
case LASTFM:
this.coverRetrievers[i] = new LastFMCover();
break;
case LOCAL:
this.coverRetrievers[i] = new LocalCover(this.app, this.settings);
break;
}
}
}
public interface CoverDownloadListener {
public void onCoverDownloaded(Bitmap cover);
public void onCoverNotFound();
}
private Collection<CoverDownloadListener> coverDownloadListener;
private CoverAsyncWorker oCoverAsyncWorker;
public CoverAsyncHelper(MPDApplication app, SharedPreferences settings) {
this.app = app;
this.settings = settings;
HandlerThread oThread = new HandlerThread("CoverAsyncWorker");
oThread.start();
oCoverAsyncWorker = new CoverAsyncWorker(oThread.getLooper());
coverDownloadListener = new LinkedList<CoverDownloadListener>();
}
public void setCoverRetrieversFromPreferences() {
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(app);
final List<CoverRetrievers> enabledRetrievers = new ArrayList<CoverRetrievers>();
//There is a cover provider order, respect it.
//Cache -> LastFM -> MPD Server
if(settings.getBoolean(PREFERENCE_CACHE, true)) {
enabledRetrievers.add(CoverRetrievers.CACHE);
}
if (settings.getBoolean(PREFERENCE_LASTFM, true)) {
enabledRetrievers.add(CoverRetrievers.LASTFM);
}
if (settings.getBoolean(PREFERENCE_LOCALSERVER, true)) {
enabledRetrievers.add(CoverRetrievers.LOCAL);
}
setCoverRetrievers(enabledRetrievers);
}
public void setCoverMaxSize(int size) {
coverMaxSize = size;
}
public void addCoverDownloadListener(CoverDownloadListener listener) {
coverDownloadListener.add(listener);
}
public void downloadCover(String artist, String album, String path, String filename) {
downloadCover(artist, album, path, filename, MAX_SIZE);
}
public void downloadCover(String artist, String album, String path, String filename, int targetSize) {
CoverInfo info = new CoverInfo();
info.sArtist = artist;
info.sAlbum = album;
info.sPath = path;
info.sFilename = filename;
info.iSize = targetSize;
oCoverAsyncWorker.obtainMessage(EVENT_DOWNLOADCOVER, info).sendToTarget();
}
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_COVERDOWNLOADED:
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverDownloaded((Bitmap) msg.obj);
break;
case EVENT_COVERNOTFOUND:
for (CoverDownloadListener listener : coverDownloadListener)
listener.onCoverNotFound();
break;
default:
break;
}
}
private class CoverAsyncWorker extends Handler {
public CoverAsyncWorker(Looper looper) {
super(looper);
}
public Bitmap getBitmapForRetriever(CoverInfo info, ICoverRetriever retriever) {
String[] urls = null;
try {
// Get URL to the Cover...
urls = retriever.getCoverUrl(info.sArtist, info.sAlbum, info.sPath, info.sFilename);
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
if (urls == null || urls.length == 0) {
return null;
}
Bitmap downloadedCover = null;
for (String url : urls) {
if (url == null)
continue;
Log.i(MPDApplication.TAG, "Downloading cover art at url : " + url);
if (retriever.isCoverLocal()) {
downloadedCover = BitmapFactory.decodeFile(url);
} else {
downloadedCover = download(url);
}
if (downloadedCover != null) {
break;
}
}
return downloadedCover;
}
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_DOWNLOADCOVER:
Bitmap cover = null;
for (ICoverRetriever coverRetriever : coverRetrievers) {
cover = getBitmapForRetriever((CoverInfo) msg.obj, coverRetriever);
if (cover != null) {
Log.i(MPDApplication.TAG, "Found cover art using retriever : " + coverRetriever.getName());
// if cover is not read from cache
if (!(coverRetriever instanceof CachedCover)) {
// Save this cover into cache, if it is enabled.
for (ICoverRetriever coverRetriever1 : coverRetrievers) {
if (coverRetriever1 instanceof CachedCover) {
Log.i(MPDApplication.TAG, "Saving cover art to cache");
((CachedCover) coverRetriever1).save(((CoverInfo) msg.obj).sArtist, ((CoverInfo) msg.obj).sAlbum, cover);
}
}
}
CoverAsyncHelper.this.obtainMessage(EVENT_COVERDOWNLOADED, cover).sendToTarget();
break;
}
}
if (cover == null) {
Log.i(MPDApplication.TAG, "No cover art found");
CoverAsyncHelper.this.obtainMessage(EVENT_COVERNOTFOUND).sendToTarget();
}
break;
default:
}
}
}
private class CoverInfo {
public String sArtist;
public String sAlbum;
public String sPath;
public String sFilename;
public int iSize;
}
public enum CoverRetrievers {
CACHE,
LASTFM,
LOCAL;
}
} |
package forms;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.data.validation.Constraints;
@Entity
public class LeagueForm {
@Id
private long id;
/*the name of the league*/
@Constraints.Required(message = "League name is required")
public String leagueName;
/*A short description of the league*/
@Constraints.Required(message = "Description is required")
public String description;
/*the number of teams in the league*/
@Constraints.Required(message = "Number of teams is required")
public int numTeams;
/*The start date of the league*/
@Constraints.Required(message = "Start date is required")
public int startDate;
/*The end date of the league*/
public int endDate;
/**
* no arguments constructor
*/
public LeagueForm(){
}
/**
* Constructor for initializing all the fields
* @param leagueName the name of the new league
* @param description the short description of the league
* @param numTeams the number of teams in the league
* @param startDate the starting date of the league
* @param endDate the end date of the league
*/
public LeagueForm(String leagueName, String description, int numTeams, int startDate, int endDate)
{
this.leagueName = leagueName;
this.description = description;
this.numTeams = numTeams;
this.startDate = startDate;
this.endDate = endDate;
}
/**
* Constructor for initializing only the required fields
* @param leagueName the name of the new league
* @param description the short description of the league
* @param numTeams the number of teams in the league
* @param startDate the starting date of the league
*/
public LeagueForm(String leagueName, String description, int numTeams, int startDate)
{
this.leagueName = leagueName;
this.description = description;
this.numTeams = numTeams;
this.startDate = startDate;
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the leagueName
*/
public String getLeagueName() {
return leagueName;
}
/**
* @param leagueName the leagueName to set
*/
public void setLeagueName(String leagueName) {
this.leagueName = leagueName;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the numTeams
*/
public int getNumTeams() {
return numTeams;
}
/**
* @param numTeams the numTeams to set
*/
public void setNumTeams(int numTeams) {
this.numTeams = numTeams;
}
/**
* @return the startDate
*/
public int getStartDate() {
return startDate;
}
/**
* @param startDate the startDate to set
*/
public void setStartDate(int startDate) {
this.startDate = startDate;
}
/**
* @return the endDate
*/
public int getEndDate() {
return endDate;
}
/**
* @param endDate the endDate to set
*/
public void setEndDate(int endDate) {
this.endDate = endDate;
}
} |
package tests.eu.qualimaster.monitoring;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import tests.eu.qualimaster.monitoring.profiling.ProfilingTests;
/**
* The test suite for the Data Management Layer. Do not rename this class.<br/>
* Set environment variable
* "STORM_TEST_TIMEOUT_MS" to a value greater than 15.000 (ms).
*
* @author Holger Eichelberger
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({SimpleMonitoringTests.class, ChangeMonitoringTests.class,
//StormTest.class,
HwMonitoringTest.class, SystemStateTest.class, LogTest.class, TopologyTests.class, ReasoningTaskTests.class,
StormClusterMonitoringTest.class, ObservationTests.class,
CloudEnvironmentTests.class,
ProfilingTests.class,
// must be last
MonitoringConfigurationTests.class})
public class AllTests {
} |
package battlecode.world;
import battlecode.common.*;
import gnu.trove.list.array.TIntArrayList;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for RobotController. These are where the gameplay tests are.
*
* Using TestGame and TestMapBuilder as helpers.
*/
public class RobotControllerTest {
public final double EPSILON = 1.0e-5; // Smaller epsilon requred, possibly due to strictfp? Used to be 1.0e-9
/**
* Tests the most basic methods of RobotController. This test has extra
* comments to serve as an example of how to use TestMapBuilder and
* TestGame.
*
* @throws GameActionException shouldn't happen
*/
@Test
public void testBasic() throws GameActionException {
// Prepares a map with the following properties:
// origin = [0,0], width = 10, height = 10, num rounds = 100
// random seed = 1337
// The map doesn't have to meet specs.
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
// Let's spawn a robot for each team. The integers represent IDs.
float oX = game.getOriginX();
float oY = game.getOriginY();
final int archonA = game.spawn(oX + 3, oY + 3, RobotType.ARCHON, Team.A);
final int soldierB = game.spawn(oX + 1, oY + 1, RobotType.SOLDIER, Team
.B);
InternalRobot archonABot = game.getBot(archonA);
assertEquals(new MapLocation(oX + 3, oY + 3), archonABot.getLocation());
// The following specifies the code to be executed in the next round.
// Bytecodes are not counted, and yields are automatic at the end.
game.round((id, rc) -> {
if (id == archonA) {
rc.move(Direction.getEast());
} else if (id == soldierB) {
// do nothing
}
});
// Let's assert that things happened properly.
assertEquals(new MapLocation(
oX + 3 + RobotType.ARCHON.strideRadius,
oY + 3
), archonABot.getLocation());
// Lets wait for 10 rounds go by.
game.waitRounds(10);
// hooray!
}
/**
* Ensure that actions take place immediately.
*/
@Test
public void testImmediateActions() throws GameActionException {
LiveMap map= new TestMapBuilder("test", 0, 0, 100, 100, 1337, 1000).build();
TestGame game = new TestGame(map);
final int a = game.spawn(1, 1, RobotType.SOLDIER, Team.A);
game.round((id, rc) -> {
if (id != a) return;
final MapLocation start = rc.getLocation();
assertEquals(new MapLocation(1, 1), start);
rc.move(Direction.getEast());
final MapLocation newLocation = rc.getLocation();
assertEquals(new MapLocation(1 + RobotType.SOLDIER.strideRadius, 1), newLocation);
});
// Let delays go away
game.waitRounds(10);
}
@Test
public void testSpawns() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
// Let's spawn a robot for each team. The integers represent IDs.
final int archonA = game.spawn(3, 3, RobotType.ARCHON, Team.A);
// The following specifies the code to be executed in the next round.
// Bytecodes are not counted, and yields are automatic at the end.
game.round((id, rc) -> {
assertTrue("Can't build robot", rc.canBuildRobot(RobotType.GARDENER, Direction.getEast()));
rc.buildRobot(RobotType.GARDENER, Direction.getEast());
});
for (InternalRobot robot : game.getWorld().getObjectInfo().robots()) {
if (robot.getID() != archonA) {
assertEquals(RobotType.GARDENER, robot.getType());
}
}
// Lets wait for 10 rounds go by.
game.waitRounds(10);
// hooray!
}
/**
* Checks attacks of bullets in various ways
*
* @throws GameActionException
*/
@Test
public void testBulletAttack() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
// Create some units
final int soldierA = game.spawn(5, 5, RobotType.SOLDIER, Team.A);
final int soldierA2 = game.spawn(9, 5, RobotType.SOLDIER, Team.A);
final int soldierB = game.spawn(1, 5, RobotType.SOLDIER, Team.B);
game.waitRounds(20); // Let soldiers mature
// soldierA fires a shot at soldierA2
game.round((id, rc) -> {
if (id != soldierA) return;
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(-1, Team.A);
assertEquals(nearbyRobots.length,1);
assertTrue(rc.canFireSingleShot());
rc.fireSingleShot(rc.getLocation().directionTo(nearbyRobots[0].location));
assertFalse(rc.canFireSingleShot());
// Ensure bullet exists and spawns at proper location
InternalBullet[] bullets = game.getWorld().getObjectInfo().bulletsArray();
assertEquals(bullets.length,1);
assertEquals(
bullets[0].getLocation().distanceTo(rc.getLocation()),
rc.getType().bodyRadius + GameConstants.BULLET_SPAWN_OFFSET,
EPSILON
);
});
// soldierA fires a shot at soldierB
game.round((id, rc) -> {
if (id != soldierA) return;
// Original bullet should be gone
InternalBullet[] bullets = game.getWorld().getObjectInfo().bulletsArray();
assertEquals(bullets.length,0);
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(-1, Team.B);
assertEquals(nearbyRobots.length,1);
assertTrue(rc.canFireSingleShot());
rc.fireSingleShot(rc.getLocation().directionTo(nearbyRobots[0].location));
assertFalse(rc.canFireSingleShot());
// Ensure new bullet exists
bullets = game.getWorld().getObjectInfo().bulletsArray();
assertEquals(bullets.length,1);
});
// Let bullets propagate to targets
game.waitRounds(1);
// No more bullets in flight
InternalBullet[] bulletIDs = game.getWorld().getObjectInfo().bulletsArray();
assertEquals(bulletIDs.length,0);
// Two targets are damaged
assertEquals(game.getBot(soldierA2).getHealth(),RobotType.SOLDIER.maxHealth - RobotType.SOLDIER.attackPower,EPSILON);
assertEquals(game.getBot(soldierB).getHealth(),RobotType.SOLDIER.maxHealth - RobotType.SOLDIER.attackPower,EPSILON);
}
/**
* Ensures tank body attack (and bullet attack) perform according to spec
*
* @throws GameActionException
*/
@Test
public void testTankAttack() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int tankB = game.spawn(2, 5, RobotType.TANK, Team.B);
final int neutralTree = game.spawnTree(7, 5, 1, Team.NEUTRAL, 0, null);
game.waitRounds(20); // Wait for units to mature
game.round((id, rc) -> {
if (id != tankB) return;
TreeInfo[] nearbyTrees = rc.senseNearbyTrees(-1);
assertEquals(nearbyTrees.length,1);
assertTrue(rc.canFireSingleShot());
rc.fireSingleShot(rc.getLocation().directionTo(nearbyTrees[0].location));
assertFalse(rc.canFireSingleShot());
});
// Let bullets propagate to targets
game.waitRounds(1);
// Tree took bullet damage
assertEquals(game.getTree(neutralTree).getHealth(),GameConstants.NEUTRAL_TREE_HEALTH_RATE*1 - RobotType.TANK.attackPower,EPSILON);
// Move tank toward tree
game.round((id, rc) -> {
if (id != tankB) return;
TreeInfo[] nearbyTrees = rc.senseNearbyTrees(-1);
assertEquals(nearbyTrees.length,1);
MapLocation originalLoc = rc.getLocation();
assertFalse(rc.hasMoved());
assertTrue(rc.canMove(rc.getLocation().directionTo(nearbyTrees[0].location)));
rc.move(rc.getLocation().directionTo(nearbyTrees[0].location));
assertTrue(rc.hasMoved());
assertFalse(rc.getLocation().equals(originalLoc)); // Tank should have moved
});
// Mpve tank into tree
game.round((id, rc) -> {
if (id != tankB) return;
TreeInfo[] nearbyTrees = rc.senseNearbyTrees(-1);
assertEquals(nearbyTrees.length,1);
MapLocation originalLoc = rc.getLocation();
assertFalse(rc.hasMoved());
rc.move(rc.getLocation().directionTo(nearbyTrees[0].location));
assertTrue(rc.hasMoved());
assertTrue(rc.getLocation().equals(originalLoc)); // Tank doesn't move due to tree in the way
});
// Body Damage
assertEquals(game.getTree(neutralTree).getHealth(),GameConstants.NEUTRAL_TREE_HEALTH_RATE*1 - RobotType.TANK.attackPower - GameConstants.TANK_BODY_DAMAGE,EPSILON);
// Hit exactly enough times to kill tree
for(int i=0; i<(GameConstants.NEUTRAL_TREE_HEALTH_RATE*1-RobotType.TANK.attackPower)/GameConstants.TANK_BODY_DAMAGE - 1; i++) {
game.round((id, rc) -> {
if (id != tankB) return;
TreeInfo[] nearbyTrees = rc.senseNearbyTrees(-1);
assertEquals(nearbyTrees.length,1);
rc.move(rc.getLocation().directionTo(nearbyTrees[0].location));
});
}
// Should be able to move now
game.round((id, rc) -> {
if (id != tankB) return;
TreeInfo[] nearbyTrees = rc.senseNearbyTrees(-1);
assertEquals(nearbyTrees.length,0);
MapLocation originalLoc = rc.getLocation();
rc.move(Direction.getEast());
assertFalse(rc.getLocation().equals(originalLoc));
});
}
/**
* Ensures lumberjacks can cut down trees and perform basher-like attacks
*
* @throws GameActionException
*/
@Test
public void testLumberjacks() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int lumberjackA = game.spawn(2, 5, RobotType.LUMBERJACK, Team.A);
final int soldierA = game.spawn(3, (float)7.1, RobotType.SOLDIER, Team.A);
final int soldierB = game.spawn(3, (float)2.9, RobotType.SOLDIER, Team.B);
final int neutralTree = game.spawnTree(6, 5, 1, Team.NEUTRAL, 0, null);
float expectedTreeHealth = GameConstants.NEUTRAL_TREE_HEALTH_RATE*1;
game.waitRounds(20); // Let bots mature to full health
// Trying to chop a tree
game.round((id, rc) -> {
if (id != lumberjackA) return;
TreeInfo[] nearbyTrees = rc.senseNearbyTrees(-1);
assertEquals(nearbyTrees.length,1);
boolean exception = false;
try {
rc.chop(nearbyTrees[0].ID); // Try to chop neutralTree
} catch (GameActionException e) {
exception = true;
}
assertTrue(exception); // fails, tree is out of range
assertFalse(rc.hasAttacked()); // attack attempt is not counted
// Move toward neutralTree
rc.move(rc.getLocation().directionTo(nearbyTrees[0].location));
exception = false;
try {
rc.chop(nearbyTrees[0].ID); // Try to chop again
} catch (GameActionException e) {
exception = true;
}
assertFalse(exception); // succeeds, tree now in range
assertTrue(rc.hasAttacked());
});
expectedTreeHealth -= GameConstants.LUMBERJACK_CHOP_DAMAGE;
assertEquals(game.getTree(neutralTree).getHealth(),expectedTreeHealth,EPSILON);
// Striking surrounding units
game.round((id, rc) -> {
if (id != lumberjackA) return;
rc.strike();
assertTrue(rc.hasAttacked());
});
expectedTreeHealth -= RobotType.LUMBERJACK.attackPower;
assertEquals(game.getTree(neutralTree).getHealth(),expectedTreeHealth,EPSILON);
assertEquals(game.getBot(soldierA).getHealth(),RobotType.SOLDIER.maxHealth-RobotType.LUMBERJACK.attackPower,EPSILON);
assertEquals(game.getBot(soldierB).getHealth(),RobotType.SOLDIER.maxHealth-RobotType.LUMBERJACK.attackPower,EPSILON);
}
/**
* Planting, withering, watering, bullet income, gardener's can't water neutral, etc
*
* @throws GameActionException
*/
@Test
public void treesBulletsTest() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int gardenerA = game.spawn(5, 5, RobotType.GARDENER, Team.A);
final int neutralTree = game.spawnTree(2, 5, 1, Team.NEUTRAL, 0, null);
// Check initial bullet amounts
assertEquals(game.getWorld().getTeamInfo().getBulletSupply(Team.A),GameConstants.BULLETS_INITIAL_AMOUNT,EPSILON);
assertEquals(game.getWorld().getTeamInfo().getBulletSupply(Team.B),GameConstants.BULLETS_INITIAL_AMOUNT,EPSILON);
game.getWorld().getTeamInfo().adjustBulletSupply(Team.B, -GameConstants.BULLETS_INITIAL_AMOUNT);
// Keep track of expected bullet amounts throughout match
float teamBexpected = 0;
float teamAexpected = GameConstants.BULLETS_INITIAL_AMOUNT;
game.waitRounds(20); // Let bots mature to full health
game.round((id, rc) -> {
if (id != gardenerA) return;
assertFalse(rc.canPlantTree(Direction.getWest())); // tree in way
assertTrue(rc.canPlantTree(Direction.getNorth())); // unobstructed
assertTrue(rc.canPlantTree(Direction.getEast())); // unobstructed
rc.plantTree(Direction.getEast());
assertFalse(rc.canMove(Direction.getEast())); // tree now in the way
assertFalse(rc.canPlantTree(Direction.getNorth())); // has already planted this turn
TreeInfo[] trees = rc.senseNearbyTrees();
assertEquals(trees.length,2);
TreeInfo[] bulletTrees = rc.senseNearbyTrees(-1, rc.getTeam());
assertEquals(bulletTrees.length,1);
assertEquals(bulletTrees[0].health,GameConstants.BULLET_TREE_MAX_HEALTH*GameConstants.PLANTED_UNIT_STARTING_HEALTH_FRACTION,EPSILON);
});
game.waitRounds(80);
teamAexpected -= GameConstants.BULLET_TREE_COST;
assertEquals(game.getWorld().getTeamInfo().getBulletSupply(Team.A),teamAexpected,EPSILON);
game.round((id, rc) -> { // Reaches flull health
if (id != gardenerA) return;
TreeInfo[] trees = rc.senseNearbyTrees();
assertEquals(trees.length,2);
TreeInfo[] bulletTrees = rc.senseNearbyTrees(-1, rc.getTeam());
assertEquals(bulletTrees.length,1);
assertEquals(bulletTrees[0].health,GameConstants.BULLET_TREE_MAX_HEALTH,EPSILON);
});
game.waitRounds(10);
// Check income from trees
for(int i=0; i<11; i++){
teamAexpected += (GameConstants.BULLET_TREE_MAX_HEALTH-i*GameConstants.BULLET_TREE_DECAY_RATE)*GameConstants.BULLET_TREE_BULLET_PRODUCTION_RATE;
}
assertEquals(game.getWorld().getTeamInfo().getBulletSupply(Team.A),teamAexpected,EPSILON);
game.round((id, rc) -> { // Decays for eleven (wait ten plus this one) turns
if (id != gardenerA) return;
TreeInfo[] bulletTrees = rc.senseNearbyTrees(-1, rc.getTeam());
assertEquals(bulletTrees.length,1);
assertEquals(bulletTrees[0].health,GameConstants.BULLET_TREE_MAX_HEALTH-GameConstants.BULLET_TREE_DECAY_RATE*11,EPSILON);
assertTrue(rc.canWater());
rc.water(bulletTrees[0].ID);
// Health has not increased from watering yet, wait until following turn
assertEquals(bulletTrees[0].health,GameConstants.BULLET_TREE_MAX_HEALTH-GameConstants.BULLET_TREE_DECAY_RATE*11,EPSILON);
assertFalse(rc.canWater());
});
game.round((id, rc) -> { // Decays for eleven (wait ten plus this one) turns
if (id != gardenerA) return;
TreeInfo[] bulletTrees = rc.senseNearbyTrees(-1, rc.getTeam());
assertEquals(bulletTrees.length,1);
// Tree was watered last turn, so will now increase in health by 10.
assertEquals(bulletTrees[0].health,GameConstants.BULLET_TREE_MAX_HEALTH-GameConstants.BULLET_TREE_DECAY_RATE*12+GameConstants.WATER_HEALTH_REGEN_RATE,EPSILON);
assertTrue(rc.canWater());
rc.water(bulletTrees[0].ID);
});
game.round((id, rc) -> { // Decays for eleven (wait ten plus this one) turns
if (id != gardenerA) return;
TreeInfo[] bulletTrees = rc.senseNearbyTrees(-1, rc.getTeam());
assertEquals(bulletTrees.length,1);
// Tree was watered last turn, so will now increase in health by 10.
assertEquals(bulletTrees[0].health,GameConstants.BULLET_TREE_MAX_HEALTH-GameConstants.BULLET_TREE_DECAY_RATE,EPSILON);
});
//assertEquals(game.getWorld().getTeamInfo().getBulletSupply(Team.A),0.0,EPSILON);
int numRounds = game.getWorld().getCurrentRound();
// Team B's supply was reset to zero at beginning, this will make sure income works as expected.
for(int i=0; i<numRounds; i++) {
teamBexpected += GameConstants.ARCHON_BULLET_INCOME-teamBexpected*GameConstants.BULLET_INCOME_UNIT_PENALTY;
}
assertEquals(game.getWorld().getTeamInfo().getBulletSupply(Team.B),teamBexpected,EPSILON);
// Wait for tree to decay completely
game.waitRounds(100);
// Tree should be dead
game.round((id, rc) -> { // Decays for eleven (wait ten plus this one) turns
if (id != gardenerA) return;
TreeInfo[] bulletTrees = rc.senseNearbyTrees(-1, rc.getTeam());
assertEquals(bulletTrees.length,0); // no more tree
TreeInfo[] neutralTrees = rc.senseNearbyTrees(-1, Team.NEUTRAL);
assertEquals(neutralTrees.length,1);
// Atempt to water a neutral tree
boolean exception = false;
try{
rc.water(neutralTrees[0].ID);
} catch (GameActionException e) {
exception = true;
}
assertTrue(exception);
});
}
@Test // Normal robots blocked by trees and other robots, drones fly over but blocked by other drones
public void obstructionTest() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int archonA = game.spawn(3, 5, RobotType.ARCHON, Team.A);
final int scoutA = game.spawn(7.5f, 5, RobotType.SCOUT, Team.A);
final int scoutB = game.spawn(7.5f, 2, RobotType.SCOUT, Team.A);
final int neutralTree = game.spawnTree(9f,5, 1, Team.NEUTRAL, 0, null);
game.waitRounds(20);
MapLocation originalArchonALoc = game.getWorld().getObjectInfo().getRobotByID(archonA).getLocation();
MapLocation scoutBLoc = game.getWorld().getObjectInfo().getRobotByID(scoutB).getLocation();
MapLocation neutralTreeLoc = game.getWorld().getObjectInfo().getTreeByID(neutralTree).getLocation();
// Scout can move over trees, but not other robots
game.round((id, rc) -> {
if (id != scoutA) return;
assertFalse(rc.canMove(originalArchonALoc));
assertFalse(rc.canMove(scoutBLoc));
assertTrue(rc.canMove(neutralTreeLoc)); // Scouts can go over trees
rc.move(neutralTreeLoc);
});
// Scout can't go off the map
game.round((id, rc) -> {
if (id != scoutA) return;
assertFalse(rc.canMove(Direction.getEast(),0.01f)); // Off the map
assertTrue(rc.canMove(Direction.getNorth()));
rc.move(Direction.getNorth()); // Move away from tree
});
// Move Archon closer to tree
int numMoves = 0;
MapLocation currentArchonALoc = null;
do {
game.round((id, rc) -> {
if (id != archonA) return;
assertTrue(rc.canMove(neutralTreeLoc));
rc.move(neutralTreeLoc); // Move towards the tree
});
numMoves++;
currentArchonALoc = game.getWorld().getObjectInfo().getRobotByID(archonA).getLocation();
assertEquals(currentArchonALoc.distanceTo(neutralTreeLoc), originalArchonALoc.distanceTo(neutralTreeLoc) - RobotType.ARCHON.strideRadius*numMoves, EPSILON);
} while (currentArchonALoc.distanceTo(neutralTreeLoc) > RobotType.ARCHON.bodyRadius+1+RobotType.ARCHON.strideRadius);
// Move Archon to be just out of tree
game.round((id, rc) -> {
if (id != archonA) return;
assertTrue(rc.canMove(rc.getLocation().directionTo(neutralTreeLoc),rc.getLocation().distanceTo(neutralTreeLoc)-(RobotType.ARCHON.bodyRadius+1+0.0001f)));
rc.move(rc.getLocation().directionTo(neutralTreeLoc),rc.getLocation().distanceTo(neutralTreeLoc)-(RobotType.ARCHON.bodyRadius+1+0.0001f)); // Move towards the tree
assertEquals(rc.getLocation().distanceTo(neutralTreeLoc),RobotType.ARCHON.bodyRadius+1+0.0001f,EPSILON);
});
// Archon can't go over tree
game.round((id, rc) -> {
if (id != archonA) return;
assertFalse(rc.canMove(rc.getLocation().directionTo(neutralTreeLoc),0.001f));
});
}
@Test // Bullet collision works continuously and not at discrete intervals
public void continuousBulletCollisionTest() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 12, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
// Create some units
final int soldierA = game.spawn(3, 5, RobotType.SOLDIER, Team.A);
final int soldierB = game.spawn(9, 5, RobotType.SOLDIER, Team.B);
final int soldierB2 = game.spawn(10f,6.8f,RobotType.SOLDIER, Team.B);
game.waitRounds(20); // Wait for bots to mature to full health
MapLocation soldierBLocation = game.getBot(soldierB).getLocation();
// topOfSoldierB is a location just near the top edge of soldierB.
// if discrete bullet position checking is used, the bullet will clip though some of the tests.
MapLocation topOfSoldierB = soldierBLocation.add(Direction.getNorth(),RobotType.SOLDIER.bodyRadius - 0.01f);
final float testInterval = 0.01f;
for(float i=0; i<1; i+=testInterval){
// soldierA fires a shot at soldierB, and moves a small amount closer.
// Move before firing so it doesn't step into it's own bullet
game.round((id, rc) -> {
if (id != soldierA) return;
rc.move(rc.getLocation().directionTo(soldierBLocation),testInterval);
rc.fireSingleShot(rc.getLocation().directionTo(topOfSoldierB));
});
game.waitRounds(5); // Bullet propagation
// SoldierB should get hit every time (bullet never clips through)
assertEquals(game.getBot(soldierB).getHealth(), RobotType.SOLDIER.maxHealth - RobotType.SOLDIER.attackPower, EPSILON);
game.getBot(soldierB).repairRobot(10); // Repair back to full health so it doesn't die
// SoldierB2 should never get hit
assertEquals(game.getBot(soldierB).getHealth(), RobotType.SOLDIER.maxHealth, EPSILON);
}
// Now check cases where it shouldn't hit soldierB
game.round((id, rc) -> {
if (id != soldierA) return;
rc.move(Direction.getNorth(),RobotType.SOLDIER.bodyRadius+0.01f);
rc.fireSingleShot(Direction.getEast()); // Shoot a bullet parallel, slightly above soldierB
});
game.waitRounds(5); // Bullet propagation
// Bullet goes over soldierB
assertEquals(game.getBot(soldierB).getHealth(), RobotType.SOLDIER.maxHealth, EPSILON);
// ...and hits soldier B2
assertEquals(game.getBot(soldierB2).getHealth(), RobotType.SOLDIER.maxHealth - RobotType.SOLDIER.attackPower, EPSILON);
// Test shooting off the map
game.round((id, rc) -> {
if (id == soldierA)
rc.fireSingleShot(Direction.getEast()); // Shoot a bullet parallel, slightly above soldierB
else if (id == soldierB2)
rc.move(Direction.getNorth()); // Move out of way so soldierA can shoot off the map
});
float bulletDistanceToWall = 12-game.getWorld().getObjectInfo().bulletsArray()[0].getLocation().x;
int turnsToApproachWall = (int)Math.floor(bulletDistanceToWall/RobotType.SOLDIER.bulletSpeed);
game.waitRounds(turnsToApproachWall); // Bullet close to wall
assertEquals(game.getBot(soldierB).getHealth(), RobotType.SOLDIER.maxHealth, EPSILON);
// Bullet should still be in game
assertEquals(game.getWorld().getObjectInfo().bullets().size(),1);
game.waitRounds(1);
// Bullet should hit wall and die
assertEquals(game.getWorld().getObjectInfo().bullets().size(),0);
}
@Test // Buying victory points
public void victoryPointTest() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int archonA = game.spawn(8, 5, RobotType.GARDENER, Team.A);
final int archonB = game.spawn(2, 5, RobotType.GARDENER, Team.B);
game.round((id, rc) -> {
if (id != archonA) return;
rc.donate(100);
assertEquals(rc.getTeamBullets(),GameConstants.BULLETS_INITIAL_AMOUNT-100,EPSILON);
assertEquals(rc.getTeamVictoryPoints(),100/10);
rc.donate(9);
rc.donate(9);
assertEquals(rc.getTeamBullets(),GameConstants.BULLETS_INITIAL_AMOUNT-118,EPSILON);
assertEquals(rc.getTeamVictoryPoints(),100/10);
// Try to donate negative bullets, should fail.
boolean exception = false;
try {
rc.donate(-1);
} catch (GameActionException e) {
exception = true;
}
assertTrue(exception);
// Try to donate more than you have, should fail.
exception = false;
try {
rc.donate(rc.getTeamBullets()+0.1f);
} catch (GameActionException e) {
exception = true;
}
assertTrue(exception);
});
// No winner yet
assertEquals(game.getWorld().getWinner(),null);
// Give TeamA lots of bullets
game.getWorld().getTeamInfo().adjustBulletSupply(Team.A,GameConstants.VICTORY_POINTS_TO_WIN*GameConstants.BULLET_EXCHANGE_RATE);
game.round((id, rc) -> {
if(id != archonA) return;
rc.donate(rc.getTeamBullets());
});
// Team A should win
assertEquals(game.getWorld().getWinner(),Team.A);
// ...by victory point threshold
assertEquals(game.getWorld().getGameStats().getDominationFactor(), DominationFactor.PHILANTROPIED);
}
@Test // Test goodies inside trees
public void testTreeGoodies() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int lumberjackA = game.spawn(5,5,RobotType.LUMBERJACK,Team.A);
final int neutralTree1 = game.spawnTree(8,5,1,Team.NEUTRAL,123,null);
final int neutralTree2 = game.spawnTree(2,5,1,Team.NEUTRAL, 0, RobotType.SOLDIER);
final int neutralTree3 = game.spawnTree(5,8,1,Team.NEUTRAL,123,RobotType.SOLDIER);
game.waitRounds(20); // Allow robots to mature
game.round((id, rc) -> {
TreeInfo[] nearbyTrees = rc.senseNearbyTrees(-1,Team.NEUTRAL);
assertEquals(nearbyTrees.length,3);
int treesWithBullets=0;
int treesWithBots=0;
for(TreeInfo tree : nearbyTrees) {
if(tree.containedBullets > 0)
treesWithBullets++;
if(tree.containedRobot != null)
treesWithBots++;
}
assertEquals(treesWithBots,2);
assertEquals(treesWithBullets,2);
rc.chop(neutralTree1);
});
// While tree is not dead, continue hitting it
while(game.getTree(neutralTree1).getHealth() > GameConstants.LUMBERJACK_CHOP_DAMAGE) {
game.round((id, rc) -> {
rc.chop(neutralTree1);
});
}
// Bullets before final blow
assertEquals(game.getWorld().getTeamInfo().getBulletSupply(Team.A),GameConstants.BULLETS_INITIAL_AMOUNT,EPSILON);
// Kill the tree
game.round((id, rc) -> {
rc.chop(neutralTree1);
});
// Bullets rewarded after it dies
assertEquals(game.getWorld().getTeamInfo().getBulletSupply(Team.A),GameConstants.BULLETS_INITIAL_AMOUNT+123,EPSILON);
// While tree2 is not dead, continue hitting it
while(game.getTree(neutralTree2).getHealth() > GameConstants.LUMBERJACK_CHOP_DAMAGE) {
game.round((id, rc) -> {
rc.chop(neutralTree2);
});
}
// Only one active robot before killing the robot-containing tree
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.A),1);
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.B),0);
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.NEUTRAL),0);
// Kill the tree
game.round((id, rc) -> {
if(id != lumberjackA) return;
rc.chop(neutralTree2);
// New robot should exist immediately
RobotInfo[] nearbyRobots = rc.senseNearbyRobots();
assertEquals(nearbyRobots.length,1);
// Can't move into its location
assertFalse(rc.canMove(nearbyRobots[0].getLocation()));
});
// Two robots should exist after it dies
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.A),2);
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.B),0);
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.NEUTRAL),0);
// Make sure the new robot runs player code
game.round((id, rc) -> {
if(id != lumberjackA) {
assertTrue(rc.getType().equals(RobotType.SOLDIER));
TreeInfo trees[] = rc.senseNearbyTrees(-1,Team.NEUTRAL);
assertEquals(trees.length,1);
rc.fireSingleShot(rc.getLocation().directionTo(trees[0].getLocation()));
}
});
// Last tree should get hit and lose health
game.waitRounds(2);
// Soldier should have damaged last tree
assertEquals(game.getTree(neutralTree3).getHealth(),GameConstants.NEUTRAL_TREE_HEALTH_RATE-RobotType.SOLDIER.attackPower,EPSILON);
// While tree3 is not dead, continue shooting it
while(game.getTree(neutralTree3).getHealth() > RobotType.SOLDIER.attackPower) {
game.round((id, rc) -> {
if(id != lumberjackA) {
TreeInfo trees[] = rc.senseNearbyTrees(-1,Team.NEUTRAL);
assertEquals(trees.length,1);
rc.fireSingleShot(rc.getLocation().directionTo(trees[0].getLocation()));
}
});
}
// Tree alive before bullets propagate
assertEquals(game.getWorld().getObjectInfo().getTreeCount(Team.NEUTRAL),1);
float initialBullets = game.getWorld().getTeamInfo().getBulletSupply(Team.A);
game.waitRounds(3); // Bullets propagate
// Tree should be gone
assertEquals(game.getWorld().getObjectInfo().getTreeCount(Team.NEUTRAL),0);
// No additional robots added
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.A),2);
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.B),0);
assertEquals(game.getWorld().getObjectInfo().getRobotCount(Team.NEUTRAL),0);
// No additional bullets
assertEquals(initialBullets,game.getWorld().getTeamInfo().getBulletSupply(Team.A),EPSILON);
}
@Test
public void testNullSense() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int soldierA = game.spawn(3, 5, RobotType.SOLDIER, Team.A);
final int soldierB = game.spawn(7, 5, RobotType.SOLDIER, Team.B);
game.round((id, rc) -> {
if(id != soldierA) return;
RobotInfo actualBot = rc.senseRobotAtLocation(new MapLocation(3,5));
RobotInfo nullBot = rc.senseRobotAtLocation(new MapLocation(5,7));
assertNotEquals(actualBot,null);
assertEquals(nullBot,null);
});
}
@Test
public void testDirections() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int soldierA = game.spawn(3, 5, RobotType.SCOUT, Team.A);
final int neutralTree = game.spawnTree(5,5,1,Team.NEUTRAL,0,null);
game.round((id, rc) -> {
if (id != soldierA) return;
// Silly Direction sanity checks
for (int i = 0; i < 3; i++) {
assertEquals(new Direction(0.1f).radians, new Direction(0.1f).rotateLeftRads((float) (2 * Math.PI * i)).radians, EPSILON);
assertEquals(new Direction(-0.1f).radians, new Direction(-0.1f).rotateLeftRads((float) (2 * Math.PI * i)).radians, EPSILON);
assertEquals(new Direction(0.1f).radians, new Direction(0.1f).rotateRightRads((float) (2 * Math.PI * i)).radians, EPSILON);
assertEquals(new Direction(-0.1f).radians, new Direction(-0.1f).rotateRightRads((float) (2 * Math.PI * i)).radians, EPSILON);
}
// Ensure range (-Math.PI,Math.PI]
Direction testDir = Direction.getNorth();
float testRads = testDir.radians;
Direction fromRads = new Direction(testRads);
for (int i = 0; i < 200; i++) {
testDir = testDir.rotateLeftDegrees(i);
// Stays within range
assertTrue(Math.abs(testDir.radians) <= Math.PI);
// Direction.reduce() functionality works
testRads += Math.toRadians(i);
fromRads = new Direction(testRads);
assertEquals(testDir.radians, fromRads.radians, 0.0001); // silly rounding errors can accumulate, so larger epsilon
}
});
// Test from ndefilippis
Direction d = new Direction((float) Math.PI);
assertEquals(d.radians, Math.PI, 1E-7);
}
@Test
public void overlappingScoutTest() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int scoutA = game.spawn(3, 5, RobotType.SCOUT, Team.A);
final int neutralTree = game.spawnTree(5,5,1,Team.NEUTRAL,0,null);
game.round((id, rc) -> {
if (id != scoutA) return;
TreeInfo[] nearbyTrees = rc.senseNearbyTrees();
rc.move(nearbyTrees[0].getLocation());
boolean exception = false;
try {
nearbyTrees = rc.senseNearbyTrees();
} catch (Exception e) {
System.out.println("Scout threw an error when trying to sense tree at its location, this shouldn't happen");
exception = true;
}
assertFalse(exception);
MapLocation loc1 = new MapLocation(5, 5);
MapLocation loc2 = loc1.add(null, 5);
assertEquals(loc1, loc2);
});
}
@Test
public void testShakeInsideTree() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int scoutA = game.spawn(1, 5, RobotType.SCOUT, Team.A);
final int neutralTree = game.spawnTree(5,5,5,Team.NEUTRAL,0,null);
for(int i=0; i<8; i++) {
game.round((id, rc) -> {
if (id != scoutA) return;
// I can shake the tree I am on
assertTrue(rc.canShake(neutralTree));
// I can see the tree I am on
TreeInfo[] sensedTrees = rc.senseNearbyTrees(0.1f);
assertEquals(sensedTrees.length, 1);
// I can shake the tree I am on based on location
assertTrue(rc.canShake(rc.getLocation()));
// I can shake this tree in the same ways from another location
assertTrue(rc.canMove(Direction.getEast(), 1));
rc.move(Direction.getEast(), 1);
});
}
}
@Test
public void testNullIsCircleOccupied() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int gardener = game.spawnTree(5,5,5,Team.A,0,null);
game.round((id, rc) -> {
if(id != gardener) return;
boolean exception = false;
try {
assertFalse(rc.isCircleOccupiedExceptByThisRobot(rc.getLocation(), 3));
} catch(Exception e) {
exception = true;
}
assertFalse(exception);
});
}
@Test
public void hitScoutsBeforeTrees() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 10, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
// In case scouts are on top of trees with radius 1, hit scout first
final int soldierA = game.spawn(5,5,RobotType.SOLDIER,Team.A);
final int scoutB = game.spawn(8,5,RobotType.SCOUT,Team.B);
final int neutralTree1 = game.spawnTree(8,5,1,Team.NEUTRAL,123,null);
game.waitRounds(20); // Let them mature
// Fire shot at tree/soldier combo
game.round((id, rc) -> {
if (id != soldierA) return;
rc.fireSingleShot(rc.getLocation().directionTo(new MapLocation(8,5)));
});
game.waitRounds(1);
// Scout gets hit, tree does not
assertEquals(game.getBot(scoutB).getHealth(),RobotType.SCOUT.maxHealth-RobotType.SOLDIER.attackPower, EPSILON);
assertEquals(game.getTree(neutralTree1).getHealth(),GameConstants.NEUTRAL_TREE_HEALTH_RATE, EPSILON);
}
// Check to ensure execution order is equal to spawn order
@Test
public void executionOrderTest() throws GameActionException {
LiveMap map = new TestMapBuilder("test", new MapLocation(0,0), 50, 10, 1337, 100)
.build();
// This creates the actual game.
TestGame game = new TestGame(map);
final int TEST_UNITS = 10;
int[] testIDs = new int[TEST_UNITS];
for(int i=0; i<TEST_UNITS; i++) {
testIDs[i] = game.spawn(2+i*3,5,RobotType.SOLDIER,Team.A);
}
final int archonA = game.spawn(40,5,RobotType.ARCHON,Team.A);
final int gardenerA = game.spawn(46,5,RobotType.GARDENER,Team.A);
TIntArrayList executionOrder = new TIntArrayList();
game.round((id, rc) -> {
if(rc.getType() == RobotType.SOLDIER) {
executionOrder.add(id);
} else if (id == archonA) {
assertTrue(rc.canHireGardener(Direction.getEast()));
rc.hireGardener(Direction.getEast());
} else if (id == gardenerA) {
assertTrue(rc.canBuildRobot(RobotType.LUMBERJACK,Direction.getEast()));
} else {
// If either the spawned gardener or the lumberjack run code in the first round, this will fail.
assertTrue(false);
}
});
// Assert IDs aren't in order (random change, but very unlikely unless something is wrong)
boolean sorted = true;
for(int i=0; i<TEST_UNITS-1; i++) {
if (testIDs[i] < testIDs[i+1])
sorted = false;
}
assertFalse(sorted);
// Assert execution IS in order
for(int i=0; i<TEST_UNITS; i++) {
assertEquals(testIDs[i],executionOrder.get(i));
}
}
} |
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import org.junit.After;
import org.junit.Before;
import com.google.sps.data.Session;
import com.google.sps.data.SessionInterface;
import java.util.Optional;
import java.util.ArrayList;
import java.util.List;
/** Class that tests the methods in the Session class. */
@RunWith(JUnit4.class)
public class SessionTest {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
@Before
public void setUp() {
helper.setUp();
}
@After
public void tearDown() {
helper.tearDown();
}
@Test
public void testGetter() {
// Creates test data.
Optional<String> controller = Optional.of("Taniece");
Optional<String> ipOfVm = Optional.of("123.123.12.1");
List<String> attendees = new ArrayList<>();
attendees.add("Taniece");
SessionInterface session = new Session("12345", controller, ipOfVm, attendees);
Assert.assertEquals(session.getSessionId(), "12345");
Assert.assertEquals(session.getScreenNameOfController(), controller);
Assert.assertEquals(session.getIpOfVM(), ipOfVm);
Assert.assertEquals(session.getListOfAttendees(), attendees);
}
// Test if Optional variables are converted properly.
@Test
public void testOptionalValues() {
// Creates test data.
Optional<String> controller = Optional.of("Taniece");
Optional<String> ipOfVm = Optional.of("123.123.12.1");
List<String> attendees = new ArrayList<>();
attendees.add("Taniece");
SessionInterface session = new Session("12345", controller, ipOfVm, attendees);
Assert.assertEquals(session.getScreenNameOfController().get(), "Taniece");
Assert.assertEquals(session.getIpOfVM().get(), "123.123.12.1");
}
@Test
public void testConversionBetweenEntityAndSession() {
// Creates test data.
Optional<String> controller = Optional.of("Taniece");
Optional<String> ipOfVm = Optional.of("123.123.12.1");
List<String> attendees = new ArrayList<>();
attendees.add("Taniece");
SessionInterface session = new Session("12345", controller, ipOfVm, attendees);
Entity sessionEntity = session.toEntity();
SessionInterface newSession = Session.fromEntity(sessionEntity);
Assert.assertTrue(session.equals(newSession));
}
@Test
public void testEqualsMethod() {
// Creates test data.
Optional<String> controller1 = Optional.of("Jasmine");
Optional<String> ipOfVm1 = Optional.of("123.321.12.1");
List<String> attendees1 = new ArrayList<>();
attendees1.add("Jasmine");
SessionInterface session1 =
new Session("12345", controller1, ipOfVm1, attendees1);
Optional<String> controller2 = Optional.of("Chris");
Optional<String> ipOfVm2 = Optional.of("123.321.12.1");
List<String> attendees2 = new ArrayList<>();
attendees2.add("Chris");
SessionInterface session2 =
new Session("54321", controller2, ipOfVm2, attendees2);
Assert.assertFalse(session1.equals(session2));
}
} |
package com.jcabi.github;
import com.jcabi.github.mock.MkGithub;
import com.jcabi.http.Request;
import com.jcabi.http.mock.MkAnswer;
import com.jcabi.http.mock.MkContainer;
import com.jcabi.http.mock.MkGrizzlyContainer;
import com.jcabi.http.request.ApacheRequest;
import java.net.HttpURLConnection;
import javax.json.Json;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Testcase for RtCommits.
*
* @author Marcin Cylke (marcin.cylke+github@gmail.com)
* @version $Id$
* @checkstyle MultipleStringLiterals (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public class RtStatusesTest {
/**
* Tests creating a Commit.
*
* @throws Exception when an Error occurs
*/
@Test
public final void createsStatus() throws Exception {
final MkContainer container = new MkGrizzlyContainer().next(
new MkAnswer.Simple(
HttpURLConnection.HTTP_CREATED,
Json.createObjectBuilder().add("state", "failure")
.add("target_url", "https://ci.example.com/1000/output")
.add("description", "Build has completed successfully")
.add("context", "continuous-integration/jenkins")
.build().toString()
)
).start();
final Request req = new ApacheRequest(container.home());
final Statuses statuses = new RtStatuses(
req,
new RtCommit(
req,
new MkGithub().randomRepo(),
"0abcd89jcabitest"
)
);
try {
statuses.create(
new RtStatus(
Status.State.Failure, "http://example.com",
"description", "ctx"
)
);
MatcherAssert.assertThat(
container.take().method(),
Matchers.equalTo(Request.POST)
);
Matchers.equalToIgnoringCase(Status.State.Failure.name());
} finally {
container.stop();
}
}
} |
package com.jcabi.log;
import java.util.Formattable;
import java.util.FormattableFlags;
import java.util.Formatter;
import java.util.Locale;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Abstract test case for all decors in the package.
* @author Marina Kosenko (marina.kosenko@gmail.com)
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
public abstract class AbstractDecorTest {
/**
* Object/system under test.
*/
private final transient Object sut;
/**
* The text to expect as an output.
*/
private final transient String text;
/**
* Formatting flas.
*/
private final transient int flags;
/**
* Formatting width.
*/
private final transient int width;
/**
* Formatting precision.
*/
private final transient int precision;
/**
* Public ctor.
* @param obj The object
* @param txt Expected text
* @param flgs Flags
* @param wdt Width
* @param prcs Precission
* @checkstyle ParameterNumber (3 lines)
*/
public AbstractDecorTest(final Object obj, final String txt,
final int flgs, final int wdt, final int prcs) {
this.sut = obj;
this.text = txt;
this.flags = flgs;
this.width = wdt;
this.precision = prcs;
Locale.setDefault(Locale.US);
}
/**
* AbstractDecor can convert object to text.
* @throws Exception If some problem inside
*/
@Test
public final void convertsDifferentFormats() throws Exception {
final Formattable decor = this.decor();
final Appendable dest = Mockito.mock(Appendable.class);
final Formatter fmt = new Formatter(dest);
decor.formatTo(fmt, this.flags, this.width, this.precision);
Mockito.verify(dest).append(this.text);
}
/**
* AbstractDecor can convert object to text, via Logger.
* @throws Exception If some problem inside
*/
@Test
public final void convertsDifferentFormatsViaLogger() throws Exception {
final StringBuilder format = new StringBuilder();
format.append('%');
if ((this.flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags
.LEFT_JUSTIFY) {
format.append('-');
}
if (this.width > 0) {
format.append(Integer.toString(this.width));
}
if (this.precision > 0) {
format.append('.').append(Integer.toString(this.precision));
}
if ((this.flags & FormattableFlags.UPPERCASE) == FormattableFlags
.UPPERCASE) {
format.append('S');
} else {
format.append('s');
}
MatcherAssert.assertThat(
Logger.format(format.toString(), this.decor()),
Matchers.equalTo(this.text)
);
}
/**
* Get decor with the object.
* @return The decor to test
* @throws Exception If some problem
*/
protected abstract Formattable decor() throws Exception;
/**
* Get object under test.
* @return The object
*/
protected final Object object() {
return this.sut;
}
} |
package com.noths.ratel;
import org.hamcrest.CustomTypeSafeMatcher;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
public class HoneybadgerTest {
private Honeybadger subject;
private Executor executor;
private String systemEnvironment;
private String name;
private URL url;
private String key;
private HttpRequest httpRequest;
private String language;
@Before
public void setup() throws MalformedURLException {
executor = mock(Executor.class);
final DummyConfiguration configuration = new DummyConfiguration();
systemEnvironment = "expected environment";
name = "expected name";
url = new URL("http", "localhost", 80, "index.html");
key = "expected key";
language = "language";
configuration.setEnvironment(systemEnvironment);
configuration.setName(name);
configuration.setUrl(url);
configuration.setKey(key);
configuration.setExclude(Collections.singletonList(UnsupportedOperationException.class.getName()));
httpRequest = mock(HttpRequest.class);
subject = new Honeybadger(configuration, executor, httpRequest, language);
}
@Test
public void shouldDoNothingIfExceptionExcluded() {
subject.notify("", new UnsupportedOperationException());
verifyZeroInteractions(executor, httpRequest);
}
@Test
public void shouldSendRequestToHoneyBadgerIfExceptionHasOccurred() throws Exception {
final String message = "exception message";
final String controller = "name of the controller";
final String action = "name of the action";
final String userAgent = "user agent";
final String remoteAddress = "address of the browser";
final String method = "method of HTTP request";
final String requestUri = "URL that was requested";
final Map<String, String> parameters = Collections.singletonMap("parameter", "value");
doAnswer(new Answer<Void>() {
@Override
public Void answer(final InvocationOnMock invocation) throws Throwable {
((Runnable) invocation.getArguments()[0]).run();
return null;
}
}).when(executor).execute(any(Runnable.class));
subject.notify(requestUri,
controller,
action,
method,
userAgent,
remoteAddress,
toArray(parameters),
new IllegalArgumentException(message));
final String description = String.format("HttpEntity with headers (contentType=application/json, X-API-Key=%s)" +
" and body (controller=%s, action=%s, userAgent=%s, remoteAddress=%s, requestUri=%s," +
" parameters=%s, message=%s, method=%s, environment=%s, name=%s)",
key, controller, action, userAgent, remoteAddress, requestUri, parameters, message, method, systemEnvironment, name);
CustomTypeSafeMatcher<HttpURLConnection> matchesHttpUrlConnection =
new CustomTypeSafeMatcher<HttpURLConnection>("HttpURLConnection with a URL of " + url) {
@Override
protected boolean matchesSafely(final HttpURLConnection item) {
return item.getURL() == url;
}
};
CustomTypeSafeMatcher<Object> matchesBodyMap = new CustomTypeSafeMatcher<Object>(description) {
@Override
protected boolean matchesSafely(final Object item) {
if (!(item instanceof Map)) {
return false;
}
final Map<?, ?> body = (Map<?, ?>) item;
return bodyMatches(body, requestUri, parameters, method, controller, action, userAgent, remoteAddress);
}
};
verify(httpRequest).call(argThat(matchesHttpUrlConnection), eq("POST"), eq(expectedHeaders(key)), argThat(matchesBodyMap));
}
private Map<String, String[]> toArray(final Map<String, String> map) {
final Map<String, String[]> ret = new HashMap<String, String[]>();
for (final Map.Entry<String, String> e : map.entrySet()) {
ret.put(e.getKey(), new String[]{e.getValue()});
}
return ret;
}
private boolean bodyMatches(final Object body, final String requestUri, final Map<String, String> parameters, final String method, final String controller,
final String action, final String userAgent, final String remoteAddress) {
if (!(body instanceof Map)) {
return false;
}
final Map notice = (Map) body;
final Server server = (Server) notice.get("server");
final Notifier notifier = (Notifier) notice.get("notifier");
final Error error = (Error) notice.get("error");
final Request request = (Request) notice.get("request");
if (server == null || notifier == null || error == null || request == null) {
return false;
}
if (anyNull(server.getHostname(), server.getProjectRoot().getPath()) || !equals(server.getEnvironmentName(), systemEnvironment)) {
return false;
}
if (anyNull(notifier.getName(), notifier.getVersion()) || !equals(notifier.getName(), name) || !equals(notifier.getLanguage(), language)) {
return false;
}
if (!request.getUrl().endsWith(requestUri) || !parameters.equals(request.getParams())) {
return false;
}
if (anyNull(error.getMessage(), error.getClazz()) || error.getBacktrace().isEmpty()) {
return false;
}
if (!request.getCgiData().get("REQUEST_METHOD").equals(method) || !request.getCgiData().get("HTTP_USER_AGENT").equals(userAgent)
|| !request.getCgiData().get("REMOTE_ADDR").equals(remoteAddress)) {
return false;
}
if (!request.getAction().equals(action) || !request.getComponent().equals(controller)) {
return false;
}
return true;
}
private Map<String, String> expectedHeaders(final String key) {
final HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-API-Key", key);
headers.put("Content-Type", "application/json");
return headers;
}
private boolean anyNull(final String... os) {
for (final String o : os) {
if (o == null || o.trim().equals("")) {
return true;
}
}
return false;
}
private boolean equals(final Object one, final Object two) {
if (one == two) {
return true;
}
if (one == null || two == null) {
return false;
}
return one.equals(two);
}
private static final class DummyConfiguration implements HoneybadgerConfiguration {
private String key;
private URL url;
private String name;
private String environment;
private List<String> exclude;
@Override
public String getKey() {
return key;
}
public void setKey(final String key) {
this.key = key;
}
@Override
public URL getUrl() {
return url;
}
public void setUrl(final URL url) {
this.url = url;
}
@Override
public String getName() {
return name;
}
@Override
public String getVersion() {
return null;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String getEnvironment() {
return environment;
}
public void setEnvironment(final String environment) {
this.environment = environment;
}
@Override
public Collection<String> getExcludeExceptions() {
return exclude;
}
public void setExclude(final List<String> exclude) {
this.exclude = exclude;
}
}
} |
package com.wizzardo.tools.xml;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class NodeTest {
@Test
public void parse() {
String s;
Node xml;
s = "I say: '${hello}'";
Assert.assertEquals("I say: '${hello}'", new XmlParser().parse(s).textOwn());
s = "<xml><xml>";
Assert.assertEquals("xml", new XmlParser().parse(s).name());
s = "<xml/>";
Assert.assertEquals("xml", new XmlParser().parse(s).name());
s = "<xml attr><xml>";
Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr"));
s = "<xml attr ><xml>";
Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr"));
s = "<xml attr />";
Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr"));
s = "<xml attr/>";
Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr"));
s = "<xml attr attr2/>";
Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr"));
s = "<xml attr=\"qwerty\"/>";
Assert.assertEquals("qwerty", new XmlParser().parse(s).attr("attr"));
s = "<xml attr=\"qwerty\" attr2/>";
Assert.assertEquals("qwerty", new XmlParser().parse(s).attr("attr"));
s = "<xml attr2 attr=\"qwerty\"/>";
Assert.assertEquals("qwerty", new XmlParser().parse(s).attr("attr"));
s = "<xml><child></child></xml>";
Assert.assertEquals(1, new XmlParser().parse(s).size());
s = "<xml><child/></xml>";
Assert.assertEquals(1, new XmlParser().parse(s).size());
s = "<xml><child attr=\"qwerty\"/></xml>";
Assert.assertEquals(1, new XmlParser().parse(s).size());
Assert.assertEquals("qwerty", new XmlParser().parse(s).first().attr("attr"));
s = "<xml><child/><child/><child/>ololo</xml>";
Assert.assertEquals(4, new XmlParser().parse(s).size());
Assert.assertEquals("ololo", new XmlParser().parse(s).text());
Assert.assertEquals("ololo", new XmlParser().parse(s).textOwn());
s = "<xml><child/><child/><child>ololo</child></xml>";
Assert.assertEquals(3, new XmlParser().parse(s).size());
Assert.assertEquals("ololo", new XmlParser().parse(s).text());
Assert.assertEquals("", new XmlParser().parse(s).textOwn());
s = "<xml><child/><child/><child>ololo</child>lo</xml>";
Assert.assertEquals(4, new XmlParser().parse(s).size());
Assert.assertEquals("ololo lo", new XmlParser().parse(s).text());
Assert.assertEquals("lo", new XmlParser().parse(s).textOwn());
s = "<xml>\n\t\tololo\n\t\t</xml>";
Assert.assertEquals("ololo", new XmlParser().parse(s).text());
}
@Test
public void xml_1() throws IOException {
String s = "<div><!-- <comment> --></div>";
Node div = new XmlParser().parse(s);
Assert.assertEquals(0, div.attributes().size());
Assert.assertEquals(1, div.children().size());
Assert.assertEquals("<!-- <comment> -->", div.children().get(0).ownText());
}
@Test
public void html_1() throws IOException {
String s = "";
for (File f : new File("src/test/resources/xml").listFiles()) {
System.out.println("parsing: " + f);
new HtmlParser().parse(f);
}
}
@Test
public void html_2() throws IOException {
String s = "<div width=100px></div>";
Node root = new HtmlParser().parse(s);
Node div = root.children().get(0);
Assert.assertEquals(1, div.attributes().size());
Assert.assertEquals(0, div.children().size());
Assert.assertEquals("100px", div.attr("width"));
s = "<div width=100px height=50px></div>";
root = new HtmlParser().parse(s);
div = root.children().get(0);
Assert.assertEquals(2, div.attributes().size());
Assert.assertEquals(0, div.children().size());
Assert.assertEquals("100px", div.attr("width"));
Assert.assertEquals("50px", div.attr("height"));
}
@Test
public void gsp_1() throws IOException {
String s = "<div><g:textField name=\"${it.key}\" placeholder=\"${[].collect({it})}\"/></div>";
Node root = new GspParser().parse(s);
Node div = root.children().get(0);
Assert.assertEquals("div", div.name());
Assert.assertEquals(1, div.children().size());
Node textField = div.children().get(0);
Assert.assertEquals("g:textField", textField.name());
Assert.assertEquals(0, textField.children().size());
Assert.assertEquals(2, textField.attributes().size());
Assert.assertEquals("${it.key}", textField.attr("name"));
Assert.assertEquals("${[].collect({it})}", textField.attr("placeholder"));
}
@Test
public void gsp_2() throws IOException {
String s = "<div><g:textField name=\"${it.key}\" placeholder=\"${String.valueOf(it.getValue()).replace(\"\\\"\", \"\")}\"/></div>";
Node root = new GspParser().parse(s);
Node div = root.children().get(0);
Assert.assertEquals("div", div.name());
Assert.assertEquals(1, div.children().size());
Node textField = div.children().get(0);
Assert.assertEquals("g:textField", textField.name());
Assert.assertEquals(0, textField.children().size());
Assert.assertEquals(2, textField.attributes().size());
Assert.assertEquals("${it.key}", textField.attr("name"));
Assert.assertEquals("${String.valueOf(it.getValue()).replace(\"\\\"\", \"\")}", textField.attr("placeholder"));
}
@Test
public void gsp_3() throws IOException {
String s = "<div id=\"${id}\"><span>foo:</span>${foo}</div>";
Node root = new GspParser().parse(s);
Node div = root.children().get(0);
Assert.assertEquals("div", div.name());
Assert.assertEquals(2, div.children().size());
Assert.assertEquals(1, div.attributes().size());
Assert.assertEquals("${id}", div.attr("id"));
Node span = div.children().get(0);
Assert.assertEquals("span", span.name());
Assert.assertEquals(1, span.children().size());
Assert.assertEquals("foo:", span.text());
Node foo = div.children().get(1);
Assert.assertEquals("${foo}", foo.text());
}
} |
package de.bmoth.app;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.junit.Test;
import static javafx.scene.input.KeyCode.ENTER;
import static org.junit.Assert.assertEquals;
public class ReplControllerTest extends HeadlessUITest {
private int z3WaitTime = 7500;
private TextArea repl;
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("repl.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root, 500, 300);
stage.setScene(scene);
stage.show();
repl = lookup("#replText").query();
}
@Test
public void replTypeSimplePredicateTest() {
clickOn(repl).write("x = 5").push(ENTER).sleep(z3WaitTime);
assertEquals("x = 5\n{x=5}\n", repl.getText());
}
@Test
public void replTypeUnsatisfiablePredicateTest() {
clickOn(repl).write("x = 5 & x = 6").push(ENTER).sleep(z3WaitTime);
assertEquals("x = 5 & x = 6\nUNSATISFIABLE\n", repl.getText());
}
@Test
public void replTypeSetPredicateTest() {
clickOn(repl).write("x = {1}").push(ENTER).sleep(z3WaitTime);
assertEquals("x = {1}\n{x=[1 -> true, else -> false]}\n", repl.getText());
}
} |
package de.meggsimum.w3w;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for {@linkplain What3Words}
*
* @author Christian Mayer, meggsimum
*/
public class What3WordsTest extends TestCase {
/**
* Ensure to set your API-Key here before running the test suite
*/
private static final String API_KEY = "YOUR-API-KEY-HERE";
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public What3WordsTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(What3WordsTest.class);
}
/**
* Tests the words -> position API wrapper
*/
public void testWordsToPosition() {
What3Words w3w = new What3Words(API_KEY);
String[] words = {"goldfish", "fuzzy", "aggregates"};
double[] coords;
try {
coords = w3w.wordsToPosition(words);
assertEquals(2, coords.length);
assertEquals(49.422636, coords[0]);
assertEquals(8.320833, coords[1]);
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Tests the position -> words API wrapper
*/
public void testPositionToWords() {
What3Words w3w = new What3Words(API_KEY);
double[] coords = {49.422636, 8.320833};
String[] words;
try {
words = w3w.positionToWords(coords);
assertEquals(3, words.length);
assertEquals("goldfish", words[0]);
assertEquals("fuzzy", words[1]);
assertEquals("aggregates", words[2]);
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Tests the position -> words API wrapper after changing the language
*/
public void testChangeLang() {
What3Words w3w = new What3Words(API_KEY);
w3w.setLanguage("de");
double[] coords = {49.422636, 8.320833};
String[] words;
try {
words = w3w.positionToWords(coords);
assertEquals(3, words.length);
assertEquals("kleid", words[0]);
assertEquals("ober", words[1]);
assertEquals("endlos", words[2]);
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Test for exception in case of an invalid API-key
*/
public void testWhat3WordsException() {
What3Words w3w = new What3Words("non-existing-api-key");
double[] coords = { 49.422636, 8.320833 };
boolean thrown = false;
try {
w3w.positionToWords(coords);
} catch (Exception e) {
thrown = true;
assertEquals("Error returned from w3w API: Missing or invalid key",
e.getCause().getMessage());
}
assertTrue(thrown);
}
} |
package de.meggsimum.w3w;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for {@linkplain What3Words}
*
* @author Christian Mayer, meggsimum
*/
public class What3WordsTest extends TestCase {
/**
* Ensure to set your API-Key here before running the test suite
*/
private static final String API_KEY = "YOUR-API-KEY-HERE";
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public What3WordsTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(What3WordsTest.class);
}
/**
* Tests the words -> position API wrapper
*/
public void testWordsToPosition() {
What3Words w3w = new What3Words(API_KEY);
String[] words = {"goldfish", "fuzzy", "aggregates"};
double[] coords;
try {
coords = w3w.wordsToPosition(words);
assertEquals(2, coords.length);
assertEquals(49.422636, coords[0]);
assertEquals(8.320833, coords[1]);
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Tests the position -> words API wrapper
*/
public void testPositionToWords() {
What3Words w3w = new What3Words(API_KEY);
double[] coords = {49.422636, 8.320833};
String[] words;
try {
words = w3w.positionToWords(coords);
assertEquals(3, words.length);
assertEquals("goldfish", words[0]);
assertEquals("fuzzy", words[1]);
assertEquals("aggregates", words[2]);
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Tests the position -> words API wrapper after changing the language
*/
public void testChangeLang() {
What3Words w3w = new What3Words(API_KEY);
w3w.setLanguage("de");
double[] coords = {49.422636, 8.320833};
String[] words;
try {
words = w3w.positionToWords(coords);
assertEquals(3, words.length);
assertEquals("kleid", words[0]);
assertEquals("ober", words[1]);
assertEquals("endlos", words[2]);
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Test for exception in case of an invalid API-key
*/
public void testWhat3WordsException() {
What3Words w3w = new What3Words(API_KEY);
double[] coords = { 49.422636, 8.320833 };
boolean thrown = false;
try {
w3w.positionToWords(coords);
} catch (Exception e) {
thrown = true;
assertEquals("Error returned from w3w API: Missing or invalid key",
e.getCause().getMessage());
}
assertTrue(thrown);
}
} |
package hu.bme.mit.spaceship;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Before;
import org.junit.Test;
public class GT4500Test {
private GT4500 ship;
private TorpedoStore mock1, mock2;
@Before
public void init(){
mock1 = mock(TorpedoStore.class);
mock2 = mock(TorpedoStore.class);
this.ship = new GT4500(mock1, mock2);
}
@Test
public void fireTorpedos_Single_Success(){
// Arrange
// Act
boolean result = ship.fireTorpedos(FiringMode.SINGLE);
verify(mock1, times(1)).fireTorpedos("1");
// Assert
assertEquals(true, result);
}
@Test
public void fireTorpedos_All_Success(){
// Arrange
// Act
boolean result = ship.fireTorpedos(FiringMode.ALL);
// Assert
assertEquals(true, result);
}
} |
package loci.common.utests;
import static org.testng.AssertJUnit.assertEquals;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import loci.common.Location;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Unit tests for the loci.common.Location class.
*
* @see loci.common.Location
*/
public class LocationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows");
// -- Fields --
private enum LocalRemoteType {
LOCAL,
HTTP,
S3,
};
private Location[] files;
private Location[] rootFiles;
private boolean[] exists;
private boolean[] isDirectory;
private boolean[] isHidden;
private String[] mode;
private LocalRemoteType[] isRemote;
private boolean isOnline;
private boolean canAccessS3;
// -- Setup methods --
@BeforeClass
public void setup() throws IOException {
File tmpDirectory = new File(System.getProperty("java.io.tmpdir"),
System.currentTimeMillis() + "-location-test");
boolean success = tmpDirectory.mkdirs();
tmpDirectory.deleteOnExit();
File hiddenFile = File.createTempFile(".hiddenTest", null, tmpDirectory);
hiddenFile.deleteOnExit();
File invalidFile = File.createTempFile("invalidTest", null, tmpDirectory);
String invalidPath = invalidFile.getAbsolutePath();
invalidFile.delete();
File validFile = File.createTempFile("validTest", null, tmpDirectory);
validFile.deleteOnExit();
files = new Location[] {
new Location(validFile.getAbsolutePath()),
new Location(invalidPath),
new Location(tmpDirectory),
new Location("http:
new Location("https:
new Location("https:
new Location("https:
new Location(hiddenFile),
new Location("s3+http://localhost:31836/bucket-dne"),
new Location("s3+http://localhost:31836/bioformats.test.public"),
new Location("s3+http://localhost:31836/bioformats.test.public/single-channel.ome.tiff"),
new Location("s3+http://localhost:31836/bioformats.test.private/single-channel.ome.tiff"),
new Location("s3+http://accesskey:secretkey@localhost:31836/bioformats.test.private/single-channel.ome.tiff")
};
rootFiles = new Location[] {
new Location("/"),
new Location("https:
new Location("s3://s3.example.org"),
};
exists = new boolean[] {
true,
false,
true,
true,
true,
false,
false,
true,
false,
true,
true,
false,
true,
};
isDirectory = new boolean[] {
false,
false,
true,
false,
false,
false,
false,
false,
false,
true,
false,
false,
false,
};
isHidden = new boolean[] {
false,
false,
false,
false,
false,
false,
false,
true,
false,
false,
false,
false,
false,
};
mode = new String[] {
"rw",
"",
"rw",
"r",
"r",
"",
"",
"rw",
"",
"r",
"r",
"",
"r",
};
isRemote = new LocalRemoteType[] {
LocalRemoteType.LOCAL,
LocalRemoteType.LOCAL,
LocalRemoteType.LOCAL,
LocalRemoteType.HTTP,
LocalRemoteType.HTTP,
LocalRemoteType.HTTP,
LocalRemoteType.HTTP,
LocalRemoteType.LOCAL,
LocalRemoteType.S3,
LocalRemoteType.S3,
LocalRemoteType.S3,
LocalRemoteType.S3,
LocalRemoteType.S3,
};
}
@BeforeClass
public void checkIfOnline() throws IOException {
try {
new Socket("www.openmicroscopy.org", 80).close();
isOnline = true;
} catch (IOException e) {
isOnline = false;
}
try {
new Socket("localhost", 31836).close();
canAccessS3 = true;
} catch (IOException e) {
canAccessS3 = false;
}
if (!isOnline) {
System.err.println("WARNING: online tests are disabled!");
}
if (!canAccessS3) {
System.err.println("WARNING: S3 tests are disabled!");
}
}
private void skipIfOffline(int i) throws SkipException {
if (isRemote[i] == LocalRemoteType.HTTP && !isOnline) {
throw new SkipException("must be online to test " + files[i].getName());
}
}
private void skipIfS3Offline(int i) throws SkipException {
if (isRemote[i] == LocalRemoteType.S3 && !canAccessS3) {
throw new SkipException("must have access to s3 to test " + files[i].getName());
}
}
// -- Tests --
@Test
public void testReadWriteMode() {
for (int i=0; i<files.length; i++) {
skipIfOffline(i);
skipIfS3Offline(i);
String msg = files[i].getName();
assertEquals(msg, files[i].canRead(), mode[i].contains("r"));
assertEquals(msg, files[i].canWrite(), mode[i].contains("w"));
}
}
@Test
public void testAbsolute() {
for (Location file : files) {
assertEquals(file.getName(), file.getAbsolutePath(),
file.getAbsoluteFile().getAbsolutePath());
}
}
@Test
public void testExists() {
for (int i=0; i<files.length; i++) {
skipIfOffline(i);
skipIfS3Offline(i);
assertEquals(files[i].getName(), files[i].exists(), exists[i]);
}
}
@Test
public void testCanonical() throws IOException {
for (Location file : files) {
assertEquals(file.getName(), file.getCanonicalPath(),
file.getCanonicalFile().getAbsolutePath());
}
}
@Test
public void testParent() {
for (Location file : files) {
assertEquals(file.getName(), file.getParent(),
file.getParentFile().getAbsolutePath());
}
}
@Test
public void testParentRoot() {
for (Location file : rootFiles) {
assertEquals(file.getName(), file.getParent(), null);
}
}
@Test
public void testIsDirectory() {
for (int i=0; i<files.length; i++) {
skipIfS3Offline(i);
assertEquals(files[i].getName(), files[i].isDirectory(), isDirectory[i]);
}
}
@Test
public void testIsFile() {
for (int i=0; i<files.length; i++) {
skipIfOffline(i);
skipIfS3Offline(i);
assertEquals(files[i].getName(), files[i].isFile(),
!isDirectory[i] && exists[i]);
}
}
@Test
public void testIsHidden() {
for (int i=0; i<files.length; i++) {
assertEquals(files[i].getName(), files[i].isHidden() || IS_WINDOWS, isHidden[i] || IS_WINDOWS);
}
}
@Test
public void testListFiles() {
for (int i=0; i<files.length; i++) {
String[] completeList = files[i].list();
String[] unhiddenList = files[i].list(true);
Location[] fileList = files[i].listFiles();
if (!files[i].isDirectory()) {
assertEquals(files[i].getName(), completeList, null);
assertEquals(files[i].getName(), unhiddenList, null);
assertEquals(files[i].getName(), fileList, null);
continue;
}
assertEquals(files[i].getName(), completeList.length, fileList.length);
List<String> complete = Arrays.asList(completeList);
for (String child : unhiddenList) {
assertEquals(files[i].getName(), complete.contains(child), true);
assertEquals(files[i].getName(),
new Location(files[i], child).isHidden(), false);
}
for (int f=0; f<fileList.length; f++) {
assertEquals(files[i].getName(),
fileList[f].getName(), completeList[f]);
}
}
}
@Test
public void testToURL() throws IOException {
for (Location file : files) {
String path = file.getAbsolutePath();
if (!path.contains(":
if (IS_WINDOWS) {
path = "file:/" + path;
}
else {
path = "file://" + path;
}
}
if (file.isDirectory() && !path.endsWith(File.separator)) {
path += File.separator;
}
try {
assertEquals(file.getName(), file.toURL(), new URL(path));
} catch (MalformedURLException e) {
assertEquals(path, true, path.contains("s3+http:
}
}
}
@Test
public void testToString() {
for (Location file : files) {
assertEquals(file.getName(), file.toString(), file.getAbsolutePath());
}
}
} |
package retromock.parser;
import com.google.gson.Gson;
import org.junit.Test;
import retrofit.client.Header;
import retrofit.client.Response;
import retrofit.mime.TypedByteArray;
import retromock.test.FileLocator;
import retromock.test.Http200ResponseBean;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
public class HttpParserTest {
static final List<Path> HTTP_FILES = FileLocator.findAllInClasspath("http-*-response.txt");
static final String LOCALHOST = "http://localhost";
static final Gson GSON = new Gson();
@Test
public void testParse200ResponseFromFile() throws Exception {
Response response = HttpParser.parse(LOCALHOST, getFile("http-200-response.txt"));
assertNotNull(response);
assertEquals(LOCALHOST, response.getUrl());
assertEquals(200, response.getStatus());
assertEquals("OK", response.getReason());
Map<String, String> headers = headerMap(response.getHeaders());
assertEquals("Flat-File", headers.get("X-Powered-By"));
assertTrue(response.getBody() instanceof TypedByteArray);
TypedByteArray body = (TypedByteArray) response.getBody();
assertEquals(headers.get("Content-Type"), body.mimeType());
assertEquals(headers.get("Content-Length"), String.valueOf(body.length()));
Http200ResponseBean bodyAsBean = GSON.fromJson(new String(body.getBytes()), Http200ResponseBean.class);
assertEquals("test", bodyAsBean.getTitle());
assertEquals("qwerty", bodyAsBean.getFoot());
}
@Test
public void testParse404ResponseFromFile() throws Exception {
Response response = HttpParser.parse(LOCALHOST, getFile("http-404-response.txt"));
assertNotNull(response);
assertEquals(LOCALHOST, response.getUrl());
assertEquals(404, response.getStatus());
assertEquals("Not Found", response.getReason());
Map<String, String> headers = headerMap(response.getHeaders());
assertEquals("Flat-File", headers.get("X-Powered-By"));
assertEquals(headers.get("Content-Length"), "0");
}
private Map<String, String> headerMap(List<Header> headers) {
Map<String, String> headerMap = new HashMap<>();
for (Header header : headers) {
headerMap.put(header.getName(), header.getValue());
}
return headerMap;
}
private static Path getFile(String name) {
Path fileName = Paths.get(name);
for (Path path : HTTP_FILES) {
if (path.endsWith(fileName)) {
return path;
}
}
return null;
}
} |
package seedu.address.testutil;
import seedu.task.model.tag.UniqueTagList;
import seedu.task.model.task.*;
/**
* A mutable person object. For testing only.
*/
public class TestTask implements ReadOnlyTask {
private TaskName taskName;
private Importance importance;
private DueTime dueTime;
private DueDate dueDate;
private UniqueTagList tags;
public TestTask() {
tags = new UniqueTagList();
}
public void setName(TaskName taskName) {
this.taskName = taskName;
}
public void setImportance(Importance importance) {
this.importance = importance;
}
public void setDueTime(DueTime dueTime) {
this.dueTime = dueTime;
}
public void setDueDate(DueDate dueDate) {
this.dueDate = dueDate;
}
@Override
public TaskName getName() {
return taskName;
}
@Override
public DueDate getDueDate() {
return dueDate;
}
@Override
public DueTime getDueTime() {
return dueTime;
}
@Override
public Importance getImportance() {
return importance;
}
@Override
public UniqueTagList getTags() {
return tags;
}
@Override
public String toString() {
return getAsText();
}
public String getAddCommand() {
StringBuilder sb = new StringBuilder();
sb.append("add " + this.getName().fullName + " ");
sb.append("d/" + this.getDueDate().value + " ");
sb.append("e/" + this.getDueTime().value + " ");
sb.append("i/" + this.getImportance().value + " ");
this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " "));
return sb.toString();
}
} |
package json;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonToTreeParser {
private Node root;
private static final String LABEL_IDENTATION = "
private static final String IDENTATION = " ";
public Node parse(String json) {
root = new Node("root");
JSONObject jsonObject = new JSONObject(json);
parse(jsonObject, null);
return root;
}
public boolean validateJSON(String json) {
JSONObject jsonObject = new JSONObject(json);
try {
JSONObject.testValidity(jsonObject);
return true;
}
catch (JSONException e) {
e.printStackTrace();
return false;
}
}
private void parse(JSONObject jsonObject, Node node) {
final Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
final String next = keys.next();
System.out.println("next: "+next);
final Object object = jsonObject.get(next);
checkType(object, next, node);
}
}
private void parse(JSONArray jsonArray, Node node) {
for(int i = 0; i < jsonArray.length(); i++) {
checkType(jsonArray.get(i), null, node);
}
}
private void checkType(Object o, String next, Node parent) {
if(o instanceof JSONObject) {
final Node node = createNewNode(next, parent);
parse((JSONObject) o, node);
}
else if(o instanceof JSONArray) {
final Node node = createNewNode(next, parent);
parse((JSONArray) o, node);
}
else if(o instanceof String) {
String value = (String) o;
System.out.println("Data-Entry: "+next+" "+value);
Data data = new Data(next, value);
addToDataList(parent, data);
}
else if(o instanceof Integer) {
final Integer value = (Integer) o;
System.out.println("Data-Entry: "+next+" "+value);
Data data = new Data(next, value.toString());
addToDataList(parent, data);
}
else if(o instanceof Double) {
final Double value = (Double) o;
System.out.println("Data-Entry: "+next+" "+value);
Data data = new Data(next, value.toString());
addToDataList(parent, data);
}
else {
System.out.println("Whatever");
// TODO: To be continued...
}
}
private Node createNewNode(String next, Node parent) {
final Node node = new Node(next);
if(parent == null) {
root.children.add(node);
}
else {
parent.children.add(node);
}
return node;
}
private void addToDataList(Node parent, Data data) {
if(parent == null) {
Node node = new Node("Unknown");
node.dataList.add(data);
root.children.add(node);
}
else {
parent.dataList.add(data);
}
}
public String traverseNodes(Node tree) {
return traverseNodes(tree, 0);
}
private String traverseNodes(Node node, int identationCount) {
String labelIdent = createIdentation(identationCount, LABEL_IDENTATION);
String ident = createIdentation(identationCount, IDENTATION);
String treeStructure = "";
final String label = "+"+labelIdent+"Label: "+node.label;
System.out.println(label);
treeStructure += label;
// System.out.println(ident+"Data:");
for(Data d : node.dataList) {
final String key = "|"+ident+"- Key: "+d.key;
System.out.println(key);
treeStructure += key;
final String value = "|"+ident+" Value: "+d.value;
System.out.println(value);
treeStructure += value;
}
for(Node child : node.children) {
treeStructure += traverseNodes(child, identationCount+1);
}
return treeStructure;
}
private String createIdentation(int identationCount, String identationKind) {
String identation = "";
for(int i = 0; i < identationCount; i++) {
identation += identationKind;
}
return identation;
}
private class Data {
private String key, value;
public Data(String next, String value) {
this.key = next;
this.value = value;
}
}
// public modifier for usage in JUnit-Tests
public class Node {
private String label;
private List<Data> dataList = new ArrayList<Data>();
private List<Node> children = new ArrayList<Node>();
public Node(String next) {
this.label = next;
}
}
} |
package org.jetbrains.idea.devkit.dom;
import com.intellij.ide.presentation.Presentation;
import com.intellij.util.xml.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
@DefinesXml
@Presentation(icon = "AllIcons.Nodes.Plugin", typeName = "Plugin")
@Stubbed
public interface IdeaPlugin extends DomElement {
String TAG_NAME = "idea-plugin";
@Nullable
String getPluginId();
@SubTag("product-descriptor")
@Nullable
ProductDescriptor getProductDescriptor();
@NotNull
@NameValue
@Stubbed
GenericDomValue<String> getId();
/**
* @deprecated Unused.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@NotNull
@Attribute("version")
@Deprecated
GenericAttributeValue<Integer> getIdeaPluginVersion();
@NotNull
GenericAttributeValue<String> getUrl();
/**
* @deprecated Unused.
*/
@SuppressWarnings("DeprecatedIsStillUsed")
@NotNull
@Deprecated
GenericAttributeValue<Boolean> getUseIdeaClassloader();
@NotNull
GenericAttributeValue<Boolean> getAllowBundledUpdate();
@NotNull
GenericAttributeValue<Boolean> getImplementationDetail();
@NotNull
@Stubbed
@Required(false)
GenericDomValue<String> getName();
@NotNull
GenericDomValue<String> getDescription();
@NotNull
@Required(false)
GenericDomValue<String> getVersion();
@NotNull
Vendor getVendor();
@NotNull
GenericDomValue<String> getChangeNotes();
@NotNull
@Stubbed
IdeaVersion getIdeaVersion();
@NotNull
GenericDomValue<String> getCategory();
@NotNull
GenericDomValue<String> getResourceBundle();
@NotNull
@Stubbed
@SubTagList("depends")
List<Dependency> getDependencies();
@SubTagList("depends")
Dependency addDependency();
@NotNull
@Stubbed
@SubTagList("module")
List<PluginModule> getModules();
@NotNull
@SubTagList("extensions")
@Stubbed
List<Extensions> getExtensions();
Extensions addExtensions();
@NotNull
@Stubbed
@SubTagList("extensionPoints")
List<ExtensionPoints> getExtensionPoints();
ExtensionPoints addExtensionPoints();
@NotNull
@SubTagList("application-components")
List<ApplicationComponents> getApplicationComponents();
ApplicationComponents addApplicationComponents();
@NotNull
@SubTagList("project-components")
List<ProjectComponents> getProjectComponents();
ProjectComponents addProjectComponents();
@NotNull
@SubTagList("module-components")
List<ModuleComponents> getModuleComponents();
ModuleComponents addModuleComponents();
@NotNull
@SubTagList("actions")
@Stubbed
List<Actions> getActions();
Actions addActions();
/**
* Available since 192.
*/
@NotNull
@SubTagList("applicationListeners")
List<Listeners> getApplicationListeners();
/**
* Available since 192.
*/
@NotNull
@SubTagList("projectListeners")
List<Listeners> getProjectListeners();
/**
* @deprecated not used anymore
*/
@Deprecated
@NotNull
List<Helpset> getHelpsets();
/**
* @deprecated not used anymore
*/
@Deprecated
Helpset addHelpset();
} |
package com.cyq7on.practice.sort;
public class QuickSort3Ways extends Sort {
public static void sort(int[] arr) {
quickSort(arr, 0, arr.length - 1);
}
public static void quickSort(int[] arr, int left, int right) {
if (left >= right) {
return;
}
swap(arr, left, (int) ((right - left) * Math.random() + left));
int pivot = arr[left];
int lt = left; // arr[l+1,lt] < v
int gt = right + 1; // arr[gt,r] > v
int i = left + 1; // arr[lt+1,i) == v
while (i < gt) {
if (arr[i] > pivot) {
swap(arr, i, gt - 1);
gt
} else if (arr[i] < pivot) {
swap(arr, i, lt + 1);
lt++;
i++;
} else {
i++;
}
}
swap(arr, left, lt);
//ltleftv-1
quickSort(arr, left, lt - 1);
quickSort(arr, gt, right);
}
public static void main(String[] args) {
test(InsertionSort.class.getName(), 50000, 1, 10);
test(SelectionSort.class.getName(), 50000, 1, 10);
test(QuickSort3Ways.class.getName(), 50000, 1, 10);
test(QuickSort2Ways.class.getName(), 50000, 1, 10);
test(QuickSort.class.getName(), 50000, 1, 10);
}
} |
package us.kbase.common.service;
import us.kbase.auth.AuthException;
import us.kbase.auth.AuthService;
import us.kbase.auth.AuthToken;
import us.kbase.auth.AuthUser;
import us.kbase.common.utils.UTCDateFormat;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.ini4j.Ini;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* Helper class used as ancestor of generated server side servlets for JSON RPC calling.
* @author rsutormin
*/
public class JsonServerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String APP_JSON = "application/json";
private static final String DONT_TRUST_X_IP_HEADERS =
"dont_trust_x_ip_headers";
private static final String STRING_TRUE = "true";
private static final String X_FORWARDED_FOR = "X-Forwarded-For";
private static final String X_REAL_IP = "X-Real-IP";
private ObjectMapper mapper;
private Map<String, Method> rpcCache;
public static final int LOG_LEVEL_ERR = JsonServerSyslog.LOG_LEVEL_ERR;
public static final int LOG_LEVEL_INFO = JsonServerSyslog.LOG_LEVEL_INFO;
public static final int LOG_LEVEL_DEBUG = JsonServerSyslog.LOG_LEVEL_DEBUG;
public static final int LOG_LEVEL_DEBUG2 = JsonServerSyslog.LOG_LEVEL_DEBUG + 1;
public static final int LOG_LEVEL_DEBUG3 = JsonServerSyslog.LOG_LEVEL_DEBUG + 2;
private JsonServerSyslog sysLogger;
private JsonServerSyslog userLogger;
final private static String KB_DEP = "KB_DEPLOYMENT_CONFIG";
final private static String KB_SERVNAME = "KB_SERVICE_NAME";
private static final String KB_JOB_SERVICE_URL = "KB_JOB_SERVICE_URL";
private static final String CONFIG_JOB_SERVICE_URL_PARAM = "job-service-url";
protected Map<String, String> config = new HashMap<String, String>();
private Server jettyServer = null;
private Integer jettyPort = null;
private boolean startupFailed = false;
private Long maxRPCPackageSize = null;
private int maxRpcMemoryCacheSize = 16 * 1024 * 1024;
private File rpcDiskCacheTempDir = null;
private final String specServiceName;
private final UTCDateFormat utcDatetimeFormat = new UTCDateFormat();
private String serviceVersion = null;
/**
* Starts a test jetty server on an OS-determined port. Blocks until the
* server is terminated.
* @throws Exception if the server couldn't be started.
*/
public void startupServer() throws Exception {
startupServer(0);
}
/**
* Starts a test jetty server. Blocks until the
* server is terminated.
* @param port the port to which the server will connect.
* @throws Exception if the server couldn't be started.
*/
public void startupServer(int port) throws Exception {
jettyServer = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
jettyServer.setHandler(context);
/**
* Get the jetty test server port. Returns null if the server is not running or starting up.
* @return the port
*/
public Integer getServerPort() {
return jettyPort;
}
/**
* Stops the test jetty server.
* @throws Exception if there was an error stopping the server.
*/
public void stopServer() throws Exception {
jettyServer.stop();
jettyServer = null;
jettyPort = null;
}
public void startupFailed() {
this.startupFailed = true;
}
public JsonServerServlet(String specServiceName) {
this.specServiceName = specServiceName;
this.mapper = new ObjectMapper().registerModule(new JacksonTupleModule());
this.rpcCache = new HashMap<String, Method>();
for (Method m : getClass().getMethods()) {
if (m.isAnnotationPresent(JsonServerMethod.class)) {
JsonServerMethod ann = m.getAnnotation(JsonServerMethod.class);
rpcCache.put(ann.rpc(), m);
if (ann.async()) {
rpcCache.put(ann.rpc() + "_async", m);
rpcCache.put(ann.rpc() + "_check", m);
}
}
}
String serviceName = System.getProperty(KB_SERVNAME) == null ?
System.getenv(KB_SERVNAME) : System.getProperty(KB_SERVNAME);
if (serviceName == null) {
serviceName = specServiceName;
if (serviceName.contains(":"))
serviceName = serviceName.substring(0, serviceName.indexOf(':')).trim();
}
String file = System.getProperty(KB_DEP) == null ?
System.getenv(KB_DEP) : System.getProperty(KB_DEP);
sysLogger = new JsonServerSyslog(serviceName, KB_DEP, LOG_LEVEL_INFO);
userLogger = new JsonServerSyslog(sysLogger);
//read the config file
if (file == null) {
return;
}
File deploy = new File(file);
Ini ini = null;
try {
ini = new Ini(deploy);
} catch (IOException ioe) {
sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), "There was an IO Error reading the deploy file "
+ deploy + ". Traceback:\n" + ioe);
return;
}
config = ini.get(serviceName);
if (config == null) {
config = new HashMap<String, String>();
sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), "The configuration file " + deploy +
" has no section " + serviceName);
}
}
/**
* WARNING! Please use this method for testing purposes only.
* @param output
*/
public void changeSyslogOutput(JsonServerSyslog.SyslogOutput output) {
sysLogger.changeOutput(output);
userLogger.changeOutput(output);
}
public void logErr(String message) {
userLogger.logErr(message);
}
public void logErr(Throwable err) {
userLogger.logErr(err);
}
public void logInfo(String message) {
userLogger.logInfo(message);
}
public void logDebug(String message) {
userLogger.logDebug(message);
}
public void logDebug(String message, int debugLevelFrom1to3) {
userLogger.logDebug(message, debugLevelFrom1to3);
}
public int getLogLevel() {
return userLogger.getLogLevel();
}
public void setLogLevel(int level) {
userLogger.setLogLevel(level);
}
public void clearLogLevel() {
userLogger.clearLogLevel();
}
public boolean isLogDebugEnabled() {
return userLogger.getLogLevel() >= LOG_LEVEL_DEBUG;
}
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
setupResponseHeaders(request, response);
response.setContentLength(0);
response.getOutputStream().print("");
response.getOutputStream().flush();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JsonServerSyslog.RpcInfo info = JsonServerSyslog.getCurrentRpcInfo().reset();
info.setIp(request.getRemoteAddr());
response.setContentType(APP_JSON);
OutputStream output = response.getOutputStream();
JsonServerSyslog.getCurrentRpcInfo().reset();
if (startupFailed) {
writeError(wrap(response), -32603, "The server did not start up properly. Please check the log files for the cause.", output);
return;
}
writeError(wrap(response), -32300, "HTTP GET not allowed.", output);
}
private void setupResponseHeaders(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
String allowedHeaders = request.getHeader("HTTP_ACCESS_CONTROL_REQUEST_HEADERS");
response.setHeader("Access-Control-Allow-Headers", allowedHeaders == null ? "authorization" : allowedHeaders);
response.setContentType(APP_JSON);
}
@Override
protected void doPost(HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
checkMemoryForRpc();
String remoteIp = getIpAddress(request);
setupResponseHeaders(request, response);
OutputStream output = response.getOutputStream();
ResponseStatusSetter respStatus = new ResponseStatusSetter() {
@Override
public void setStatus(int status) {
response.setStatus(status);
}
};
JsonServerSyslog.RpcInfo info = JsonServerSyslog.getCurrentRpcInfo().reset();
info.setIp(remoteIp);
JsonTokenStream jts = null;
File tempFile = null;
try {
InputStream input = request.getInputStream();
byte[] buffer = new byte[100000];
ByteArrayOutputStream bufferOs = new ByteArrayOutputStream();
long rpcSize = 0;
while (rpcSize < maxRpcMemoryCacheSize) {
int count = input.read(buffer, 0, Math.min(buffer.length, maxRpcMemoryCacheSize - (int)rpcSize));
if (count < 0)
break;
bufferOs.write(buffer, 0, count);
rpcSize += count;
}
if (rpcSize >= maxRpcMemoryCacheSize) {
OutputStream os;
if (rpcDiskCacheTempDir == null) {
os = bufferOs;
} else {
tempFile = generateTempFile();
os = new BufferedOutputStream(new FileOutputStream(tempFile));
bufferOs.close();
os.write(bufferOs.toByteArray());
bufferOs = null;
}
while (true) {
int count = input.read(buffer, 0, buffer.length);
if (count < 0)
break;
os.write(buffer, 0, count);
rpcSize += count;
if (maxRPCPackageSize != null && rpcSize > maxRPCPackageSize) {
writeError(respStatus, -32700, "Object is too big, length is more than " + maxRPCPackageSize + " bytes", output);
os.close();
return;
}
}
os.close();
if (tempFile == null) {
jts = new JsonTokenStream(((ByteArrayOutputStream)os).toByteArray());
bufferOs = null;
} else {
jts = new JsonTokenStream(tempFile);
}
} else {
bufferOs.close();
jts = new JsonTokenStream(bufferOs.toByteArray());
}
bufferOs = null;
String token = request.getHeader("Authorization");
String requestHeaderXFF = request.getHeader(X_FORWARDED_FOR);
RpcCallData rpcCallData;
try {
rpcCallData = mapper.readValue(jts, RpcCallData.class);
} catch (Exception ex) {
writeError(respStatus, -32700, "Parse error (" + ex.getMessage() + ")", ex, output);
return;
} finally {
jts.close();
}
Object idNode = rpcCallData.getId();
try {
info.setId(idNode == null ? null : "" + idNode);
} catch (Exception ex) {}
String rpcName = rpcCallData.getMethod();
if (rpcName == null) {
writeError(respStatus, -32601, "JSON RPC method property is not defined", output);
return;
}
rpcName = correctRpcMethod(rpcName);
List<UObject> paramsList = rpcCallData.getParams();
if (paramsList == null) {
writeError(respStatus, -32601, "JSON RPC params property is not defined", output);
return;
}
Context context = rpcCallData.getContext();
if (context == null)
context = new Context();
if (context.getCallStack() == null)
context.setCallStack(new ArrayList<MethodCall>());
MethodCall currentCall = new MethodCall().withMethodParams(paramsList)
.withTime(utcDatetimeFormat.formatDate(new Date()));
context.getCallStack().add(currentCall);
if (rpcName.contains(".")) {
int pos = rpcName.indexOf('.');
currentCall.setService(rpcName.substring(0, pos));
currentCall.setMethod(rpcName.substring(pos + 1));
} else {
currentCall.setService(specServiceName);
currentCall.setMethod(rpcName);
}
processRpcCall(context, token, info, requestHeaderXFF, respStatus, output);
} catch (Exception ex) {
writeError(respStatus, -32400, "Unexpected internal error (" + ex.getMessage() + ")", ex, output);
} finally {
if (jts != null) {
try {
jts.close();
} catch (Exception ignore) {}
if (tempFile != null) {
try {
tempFile.delete();
} catch (Exception ignore) {}
}
}
}
}
protected int processRpcCall(File input, File output, String token) {
JsonServerSyslog.RpcInfo info = JsonServerSyslog.getCurrentRpcInfo().reset();
final int[] responseCode = {0};
ResponseStatusSetter response = new ResponseStatusSetter() {
@Override
public void setStatus(int status) {
responseCode[0] = status;
}
};
OutputStream os = null;
try {
os = new FileOutputStream(output);
Context context = mapper.readValue(input, Context.class);
processRpcCall(context, token, info, null, response, os);
} catch (Throwable ex) {
writeError(response, -32400, "Unexpected internal error (" + ex.getMessage() + ")", ex, os);
} finally {
if (os != null)
try {
os.close();
} catch (Exception ignore) {}
}
return responseCode[0];
}
protected void processRpcCall(Context context, String token, JsonServerSyslog.RpcInfo info,
String requestHeaderXForwardedFor, ResponseStatusSetter response, OutputStream output) {
MethodCall currentCall = context.getCallStack().get(context.getCallStack().size() - 1);
info.setModule(currentCall.getService());
info.setMethod(currentCall.getMethod());
String rpcName = currentCall.getService() + "." + currentCall.getMethod();
List<UObject> paramsList = currentCall.getMethodParams();
AuthToken userProfile = null;
try {
Method rpcMethod = rpcCache.get(rpcName);
if (rpcMethod == null) {
writeError(response, -32601, "Can not find method [" + rpcName + "] in server class " + getClass().getName(), output);
return;
}
String origRpcName = rpcMethod.getAnnotation(JsonServerMethod.class).rpc();
if (origRpcName.equals(rpcName)) {
int rpcArgCount = rpcMethod.getGenericParameterTypes().length;
Object[] methodValues = new Object[rpcArgCount];
if (rpcArgCount > 0 && rpcMethod.getParameterTypes()[rpcArgCount - 1].isArray() &&
rpcMethod.getParameterTypes()[rpcArgCount - 1].getComponentType().equals(Context.class)) {
rpcArgCount
methodValues[rpcArgCount] = new Context[] {context};
}
if (rpcArgCount > 0 && rpcMethod.getParameterTypes()[rpcArgCount - 1].equals(AuthToken.class)) {
if (token != null || !rpcMethod.getAnnotation(JsonServerMethod.class).authOptional()) {
try {
userProfile = validateToken(token);
if (userProfile != null)
info.setUser(userProfile.getClientId());
} catch (Throwable ex) {
writeError(response, -32400, "Token validation failed: " + ex.getMessage(), ex, output);
return;
}
}
rpcArgCount
methodValues[rpcArgCount] = userProfile;
}
if (startupFailed) {
writeError(response, -32603, "The server did not start up properly. Please check the log files for the cause.", output);
return;
}
if (paramsList.size() != rpcArgCount) {
writeError(response, -32602, "Wrong parameter count for method " + rpcName, output);
return;
}
for (int typePos = 0; typePos < paramsList.size(); typePos++) {
UObject jsonData = paramsList.get(typePos);
Type paramType = rpcMethod.getGenericParameterTypes()[typePos];
PlainTypeRef paramJavaType = new PlainTypeRef(paramType);
try {
Object obj;
if (jsonData == null) {
obj = null;
} else if (paramType instanceof Class && paramType.equals(UObject.class)) {
obj = jsonData;
} else {
try {
obj = mapper.readValue(jsonData.getPlacedStream(), paramJavaType);
} finally {
if (jsonData.isTokenStream())
((JsonTokenStream)jsonData.getUserObject()).close();
}
}
methodValues[typePos] = obj;
} catch (Exception ex) {
writeError(response, -32602, "Wrong type of parameter " + typePos + " for method " + rpcName + " (" + ex.getMessage() + ")", ex, output);
return;
}
}
Object result;
try {
logHeaders(requestHeaderXForwardedFor);
sysLogger.log(LOG_LEVEL_INFO, getClass().getName(), "start method");
result = rpcMethod.invoke(this, methodValues);
sysLogger.log(LOG_LEVEL_INFO, getClass().getName(), "end method");
} catch (Throwable ex) {
if (ex instanceof InvocationTargetException && ex.getCause() != null) {
ex = ex.getCause();
}
writeError(response, -32500, ex, output);
onRpcMethodDone();
return;
}
try {
boolean notVoid = !rpcMethod.getReturnType().equals(Void.TYPE);
boolean isTuple = rpcMethod.getAnnotation(JsonServerMethod.class).tuple();
if (notVoid && !isTuple) {
result = Arrays.asList(result);
}
Map<String, Object> ret = new LinkedHashMap<String, Object>();
ret.put("version", "1.1");
ret.put("result", result);
mapper.writeValue(new UnclosableOutputStream(output), ret);
output.flush();
} finally {
try {
onRpcMethodDone();
} catch (Exception ignore) {}
}
} else {
if (token == null) {
writeError(response, -32400, "Authentication is required for using job service", output);
return;
}
try {
userProfile = validateToken(token);
if (userProfile != null)
info.setUser(userProfile.getClientId());
} catch (Throwable ex) {
writeError(response, -32400, "Token validation failed: " + ex.getMessage(), ex, output);
return;
}
JsonClientCaller jobService = getJobServiceClient(userProfile);
List<Object> result = null;
if (rpcName.equals(origRpcName + "_async")) {
List<Object> runJobParams = new ArrayList<Object>();
Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
runJobParams.add(paramMap);
int pos = origRpcName.indexOf('.');
paramMap.put("service", origRpcName.substring(0, pos));
paramMap.put("service_ver", getServiceVersion());
paramMap.put("method", origRpcName.substring(pos + 1));
paramMap.put("method_params", paramsList);
paramMap.put("context", context);
TypeReference<List<Object>> retType = new TypeReference<List<Object>>() {};
result = jobService.jsonrpcCall("KBaseJobService.run_job", runJobParams, retType, true, true);
} else if (rpcName.equals(origRpcName + "_check")) {
TypeReference<List<Map<String, UObject>>> retType = new TypeReference<List<Map<String, UObject>>>() {};
List<Map<String, UObject>> jobStateList = jobService.jsonrpcCall("KBaseJobService.check_job", paramsList, retType, true, true);
Map<String, UObject> jobState = jobStateList.get(0);
Long finished = jobState.get("finished").asClassInstance(Long.class);
if (finished != 0L) {
UObject error = jobState.get("error");
if (error != null && !error.isNull()) {
Map<String, Object> ret = new LinkedHashMap<String, Object>();
ret.put("version", "1.1");
ret.put("error", error);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
mapper.writeValue(new UnclosableOutputStream(output), ret);
output.flush();
return;
}
}
result = new ArrayList<Object>();
result.add(finished);
result.add(jobState.get("result"));
} else {
writeError(response, -32601, "Can not find method [" + rpcName + "] in server class " + getClass().getName(), output);
return;
}
Map<String, Object> ret = new LinkedHashMap<String, Object>();
ret.put("version", "1.1");
ret.put("result", result);
mapper.writeValue(new UnclosableOutputStream(output), ret);
output.flush();
}
} catch (Exception ex) {
writeError(response, -32400, "Unexpected internal error (" + ex.getMessage() + ")", ex, output);
}
}
private void logHeaders(final String xFF) {
if (xFF != null && !xFF.isEmpty()) {
sysLogger.log(LOG_LEVEL_INFO, getClass().getName(),
X_FORWARDED_FOR + ": " + xFF);
}
}
private String getIpAddress(HttpServletRequest request) {
final String xFF = request.getHeader(X_FORWARDED_FOR);
final String realIP = request.getHeader(X_REAL_IP);
final boolean trustXHeaders = !STRING_TRUE.equals(
config.get(DONT_TRUST_X_IP_HEADERS));
if (trustXHeaders) {
if (xFF != null && !xFF.isEmpty()) {
return xFF.split(",")[0].trim();
}
if (realIP != null && !realIP.isEmpty()) {
return realIP.trim();
}
}
return request.getRemoteAddr();
}
protected String correctRpcMethod(String methodWithModule) {
// Do nothing. Inherited classes can use for method/module name correction.
return methodWithModule;
}
protected void checkMemoryForRpc() {
// Do nothing. Inherited classes could define proper implementation.
}
protected void onRpcMethodDone() {
// Do nothing. Inherited classes could define proper implementation.
}
protected File generateTempFile() {
File tempFile = null;
long suffix = System.currentTimeMillis();
while (true) {
tempFile = new File(rpcDiskCacheTempDir, "rpc" + suffix + ".json");
if (!tempFile.exists())
break;
suffix++;
}
return tempFile;
}
protected Long getMaxRPCPackageSize() {
return this.maxRPCPackageSize;
}
protected void setMaxRPCPackageSize(Long maxRPCPackageSize) {
this.maxRPCPackageSize = maxRPCPackageSize;
}
private static AuthToken validateToken(String token)
throws AuthException, IOException {
if (token == null)
throw new AuthException(
"Authorization is required for this method but no credentials were provided");
final AuthToken ret = new AuthToken(token);
final boolean validToken;
try {
validToken = AuthService.validateToken(ret);
} catch (UnknownHostException uhe) {
//message from UHE is only the host name
throw new AuthException(
"Could not contact Authorization Service host to validate user token: "
+ uhe.getMessage(), uhe);
}
if (!validToken) {
throw new AuthException("User token was invalid");
}
return ret;
}
public static AuthUser getUserProfile(AuthToken token)
throws IOException, AuthException {
return AuthService.getUserFromToken(token);
}
private void writeError(ResponseStatusSetter response, int code, String message, OutputStream output) {
writeError(response, code, message, null, output);
}
private void writeError(ResponseStatusSetter response, int code, Throwable ex, OutputStream output) {
writeError(response, code, ex.getMessage(), ex, output);
}
private void writeError(ResponseStatusSetter response, int code, String message, Throwable ex, OutputStream output) {
//new Exception(message, ex).printStackTrace();
String data = null;
if (ex != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.close();
data = sw.toString();
sysLogger.logErr(ex, getClass().getName());
} else {
sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), message);
}
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
ObjectNode ret = mapper.createObjectNode();
ObjectNode error = mapper.createObjectNode();
error.put("name", "JSONRPCError");
error.put("code", code);
error.put("message", message);
error.put("error", data);
ret.put("version", "1.1");
ret.put("error", error);
String id = JsonServerSyslog.getCurrentRpcInfo().getId();
if (id != null)
ret.put("id", id);
try {
ByteArrayOutputStream bais = new ByteArrayOutputStream();
mapper.writeValue(bais, ret);
bais.close();
//String logMessage = new String(bytes);
//sysLogger.log(LOG_LEVEL_ERR, getClass().getName(), logMessage);
output.write(bais.toByteArray());
output.flush();
} catch (Exception e) {
System.err.println(
"Unable to write error to output - current exception:");
e.printStackTrace();
System.err.println("original exception:");
ex.printStackTrace();
}
}
public int getMaxRpcMemoryCacheSize() {
return maxRpcMemoryCacheSize;
}
public void setMaxRpcMemoryCacheSize(int maxRpcMemoryCacheSize) {
this.maxRpcMemoryCacheSize = maxRpcMemoryCacheSize;
}
public File getRpcDiskCacheTempDir() {
return rpcDiskCacheTempDir;
}
public void setRpcDiskCacheTempDir(File rpcDiskCacheTempDir) {
this.rpcDiskCacheTempDir = rpcDiskCacheTempDir;
}
private ResponseStatusSetter wrap(final HttpServletResponse response) {
return new ResponseStatusSetter() {
@Override
public void setStatus(int status) {
response.setStatus(status);
}
};
}
private JsonClientCaller getJobServiceClient(AuthToken token) throws Exception {
String url = System.getProperty(KB_JOB_SERVICE_URL);
if (url == null)
url = System.getenv(KB_JOB_SERVICE_URL);
if (url == null)
url = config.get(CONFIG_JOB_SERVICE_URL_PARAM);
if (url == null)
throw new IllegalStateException("Neither '" + CONFIG_JOB_SERVICE_URL_PARAM + "' " +
"parameter is defined in configuration nor '" + KB_JOB_SERVICE_URL + "' " +
"variable is defined in system");
JsonClientCaller ret = new JsonClientCaller(new URL(url), token);
ret.setInsecureHttpConnectionAllowed(true);
return ret;
}
public String getServiceVersion() {
return serviceVersion;
}
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
public static class RpcCallData {
private Object id;
private String method;
private List<UObject> params;
private Object version;
private Context context;
public Object getId() {
return id;
}
public void setId(Object id) {
this.id = id;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public List<UObject> getParams() {
return params;
}
public void setParams(List<UObject> params) {
this.params = params;
}
public Object getVersion() {
return version;
}
public void setVersion(Object version) {
this.version = version;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
private static class PlainTypeRef extends TypeReference<Object> {
Type type;
PlainTypeRef(Type type) {
this.type = type;
}
@Override
public Type getType() {
return type;
}
}
private static class UnclosableOutputStream extends OutputStream {
OutputStream inner;
boolean isClosed = false;
public UnclosableOutputStream(OutputStream inner) {
this.inner = inner;
}
@Override
public void write(int b) throws IOException {
if (isClosed)
return;
inner.write(b);
}
@Override
public void close() throws IOException {
isClosed = true;
}
@Override
public void flush() throws IOException {
inner.flush();
}
@Override
public void write(byte[] b) throws IOException {
if (isClosed)
return;
inner.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (isClosed)
return;
inner.write(b, off, len);
}
}
public static interface ResponseStatusSetter {
public void setStatus(int status);
}
} |
package com.battlelancer.seriesguide.util;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.SeriesGuideData;
import com.battlelancer.seriesguide.SeriesGuidePreferences;
import com.battlelancer.seriesguide.provider.SeriesContract.Shows;
import com.battlelancer.seriesguide.ui.ShowsActivity;
import com.battlelancer.thetvdbapi.TheTVDB;
import org.xml.sax.SAXException;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.ViewStub;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.atomic.AtomicInteger;
public class UpdateTask extends AsyncTask<Void, Integer, Integer> {
private static final int UPDATE_SUCCESS = 100;
private static final int UPDATE_SAXERROR = 102;
private static final int UPDATE_OFFLINE = 103;
private static final int UPDATE_INCOMPLETE = 104;
public String[] mShows = null;
public String mFailedShows = "";
private final ShowsActivity mShowsActivity;
public final AtomicInteger mUpdateCount = new AtomicInteger();
private boolean mIsFullUpdate = false;
private View mProgressOverlay;
private ProgressBar mUpdateProgress;
private String mCurrentShowName;
private TextView mUpdateStatus;
public UpdateTask(boolean isFullUpdate, ShowsActivity context) {
mShowsActivity = context;
mIsFullUpdate = isFullUpdate;
}
public UpdateTask(String[] shows, int index, String failedShows, ShowsActivity context) {
mShowsActivity = context;
mShows = shows;
mUpdateCount.set(index);
mFailedShows = failedShows;
}
@Override
protected void onPreExecute() {
// see if we already inflated the progress overlay
mProgressOverlay = mShowsActivity.findViewById(R.id.overlay_update);
if (mProgressOverlay == null) {
mProgressOverlay = ((ViewStub) mShowsActivity.findViewById(R.id.stub_update)).inflate();
}
mShowsActivity.showOverlay(mProgressOverlay);
// setup the progress overlay
mUpdateProgress = (ProgressBar) mProgressOverlay.findViewById(R.id.ProgressBarShowListDet);
mUpdateProgress.setIndeterminate(true);
mUpdateStatus = (TextView) mProgressOverlay.findViewById(R.id.textViewUpdateStatus);
mUpdateStatus.setText("");
final View cancelButton = mProgressOverlay.findViewById(R.id.overlayCancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mShowsActivity.onCancelTasks();
}
});
}
@Override
protected Integer doInBackground(Void... params) {
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(mShowsActivity.getApplicationContext());
final ContentResolver resolver = mShowsActivity.getContentResolver();
final AtomicInteger updateCount = mUpdateCount;
long currentServerTime = 0;
if (mShows == null) {
try {
currentServerTime = TheTVDB.getServerTime(mShowsActivity);
} catch (SAXException e1) {
return UPDATE_SAXERROR;
}
final long previousUpdateTime = Long.valueOf(prefs.getString(
SeriesGuidePreferences.KEY_LASTUPDATETIME, "0"));
// new update task
if (mIsFullUpdate || isFullUpdateNeeded(currentServerTime, previousUpdateTime)) {
final Cursor shows = resolver.query(Shows.CONTENT_URI, new String[] {
Shows._ID
}, null, null, null);
mShows = new String[shows.getCount()];
int i = 0;
while (shows.moveToNext()) {
mShows[i] = shows.getString(0);
i++;
}
shows.close();
} else {
try {
mShows = TheTVDB.deltaUpdateShows(previousUpdateTime, mShowsActivity);
} catch (SAXException e) {
return UPDATE_SAXERROR;
}
}
}
int resultCode = UPDATE_SUCCESS;
String id;
mUpdateProgress.setIndeterminate(false);
for (int i = updateCount.get(); i < mShows.length; i++) {
// fail early if cancelled or network connection is lost
if (isCancelled()) {
resultCode = UPDATE_INCOMPLETE;
break;
}
if (!SeriesGuideData.isNetworkAvailable(mShowsActivity)) {
resultCode = UPDATE_OFFLINE;
break;
}
id = mShows[i];
Cursor show = resolver.query(Shows.buildShowUri(id), new String[] {
Shows.TITLE
}, null, null, null);
if (show.moveToFirst()) {
mCurrentShowName = show.getString(0);
}
show.close();
publishProgress(i, mShows.length + 1);
for (int itry = 0; itry < 2; itry++) {
try {
TheTVDB.updateShow(id, mShowsActivity);
break;
} catch (SAXException saxe) {
// failed twice
if (itry == 1) {
resultCode = UPDATE_SAXERROR;
addFailedShow(mCurrentShowName);
}
}
}
updateCount.incrementAndGet();
}
publishProgress(mShows.length, mShows.length + 1);
// renew FTS3 table (only if we updated shows)
if (mShows.length != 0) {
TheTVDB.onRenewFTSTable(mShowsActivity);
}
publishProgress(mShows.length + 1, mShows.length + 1);
// store time of update if it was successful
if (currentServerTime != 0 && resultCode == UPDATE_SUCCESS) {
prefs.edit()
.putString(SeriesGuidePreferences.KEY_LASTUPDATETIME,
String.valueOf(currentServerTime)).commit();
}
return resultCode;
}
private boolean isFullUpdateNeeded(long currentServerTime, long previousUpdateTime) {
// check if more than 28 days have passed
// we compare with local time to avoid an additional network call
if (currentServerTime - previousUpdateTime > 3600 * 24 * 28) {
return true;
} else {
return false;
}
}
@Override
protected void onPostExecute(Integer result) {
mShowsActivity.setFailedShowsString(mFailedShows);
switch (result) {
case UPDATE_SUCCESS:
AnalyticsUtils.getInstance(mShowsActivity).trackEvent("Shows", "Update Task",
"Success", 0);
Toast.makeText(mShowsActivity, mShowsActivity.getString(R.string.update_success),
Toast.LENGTH_SHORT).show();
break;
case UPDATE_SAXERROR:
AnalyticsUtils.getInstance(mShowsActivity).trackEvent("Shows", "Update Task",
"SAX error", 0);
mShowsActivity.showDialog(ShowsActivity.UPDATE_SAXERROR_DIALOG);
break;
case UPDATE_OFFLINE:
AnalyticsUtils.getInstance(mShowsActivity).trackEvent("Shows", "Update Task",
"Offline", 0);
mShowsActivity.showDialog(ShowsActivity.UPDATE_OFFLINE_DIALOG);
break;
}
mShowsActivity.updateLatestEpisode();
mShowsActivity.hideOverlay(mProgressOverlay);
}
@Override
protected void onCancelled() {
mShowsActivity.hideOverlay(mProgressOverlay);
}
@Override
protected void onProgressUpdate(Integer... values) {
mUpdateProgress.setMax(values[1]);
mUpdateProgress.setProgress(values[0]);
if (values[0] == values[1]) {
// clear the text field if we are finishing up
mUpdateStatus.setText("");
} else if (values[0] + 1 == values[1]) {
// if we're one before completion, we're rebuilding the search index
mUpdateStatus.setText(mShowsActivity.getString(R.string.update_rebuildsearch) + "...");
} else {
mUpdateStatus.setText(mCurrentShowName + "...");
}
}
private void addFailedShow(String seriesName) {
if (mFailedShows.length() != 0) {
mFailedShows += ", ";
}
mFailedShows += seriesName;
}
} |
package com.virtualapplications.play;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.AlertDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.StrictMode;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutionException;
import com.virtualapplications.play.SqliteHelper.Games;
public class GameInfo {
private Context mContext;
public GameInfo (Context mContext) {
this.mContext = mContext;
}
public void saveImage(String key, Bitmap image) {
String path = mContext.getExternalFilesDir(null) + "/covers/";
OutputStream fOut = null;
File file = new File(path, key + ".jpg"); // the File to save to
if (!file.getParentFile().exists()) {
file.getParentFile().mkdir();
}
try {
fOut = new FileOutputStream(file, false);
image.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush();
fOut.close(); // do not forget to close the stream
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Bitmap getImage(String key, View childview, String boxart) {
String path = mContext.getExternalFilesDir(null) + "/covers/";
File file = new File(path, key + ".jpg");
if(file.exists())
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
if (childview != null) {
ImageView preview = (ImageView) childview.findViewById(R.id.game_icon);
preview.setImageBitmap(bitmap);
preview.setScaleType(ScaleType.CENTER_INSIDE);
((TextView) childview.findViewById(R.id.game_text)).setVisibility(View.GONE);
}
return bitmap;
} else {
new GameImage(childview, boxart).execute(key);
return null;
}
}
public class GameImage extends AsyncTask<String, Integer, Bitmap> {
private View childview;
private String key;
private ImageView preview;
private String boxart;
public GameImage(View childview, String boxart) {
this.childview = childview;
this.boxart = boxart;
}
protected void onPreExecute() {
if (childview != null) {
preview = (ImageView) childview.findViewById(R.id.game_icon);
}
}
private int calculateInSampleSize(BitmapFactory.Options options) {
final int height = options.outHeight;
final int width = options.outWidth;
int reqHeight = 420;
int reqWidth = 360;
if (preview != null) {
reqHeight = preview.getMeasuredHeight();
reqWidth = preview.getMeasuredWidth();
}
// TODO: Find a calculated width and height without ImageView
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
@Override
protected Bitmap doInBackground(String... params) {
key = params[0];
if (GamesDbAPI.isNetworkAvailable(mContext)) {
String api = null;
if (boxart != null) {
api = "http://thegamesdb.net/banners/" + boxart;
} else {
api = "http://thegamesdb.net/banners/boxart/thumb/original/front/" + key + "-1.jpg";
}
try {
URL imageURL = new URL(api);
URLConnection conn1 = imageURL.openConnection();
InputStream im = conn1.getInputStream();
BufferedInputStream bis = new BufferedInputStream(im, 512);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, options);
options.inSampleSize = calculateInSampleSize(options);
options.inJustDecodeBounds = false;
bis.close();
im.close();
conn1 = imageURL.openConnection();
im = conn1.getInputStream();
bis = new BufferedInputStream(im, 512);
bitmap = BitmapFactory.decodeStream(bis, null, options);
bis.close();
im.close();
bis = null;
im = null;
return bitmap;
} catch (IOException e) {
}
}
return null;
}
@Override
protected void onPostExecute(Bitmap image) {
if (image != null) {
saveImage(key, image);
if (preview != null) {
preview.setImageBitmap(image);
preview.setScaleType(ScaleType.CENTER_INSIDE);
((TextView) childview.findViewById(R.id.game_text)).setVisibility(View.GONE);
}
}
}
}
public void getDatabase(boolean overwrite) {
String DB_PATH = mContext.getFilesDir().getAbsolutePath() + "/../databases/";
String DB_NAME = "games.db";
if (overwrite || !new File (DB_PATH + DB_NAME).exists()) {
byte[] buffer = new byte[1024];
OutputStream myOutput = null;
int length;
InputStream myInput = null;
try
{
myInput = mContext.getAssets().open(DB_NAME);
myOutput = new FileOutputStream(DB_PATH + DB_NAME);
while((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
myOutput.close();
myOutput.flush();
myInput.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
public OnLongClickListener configureLongClick(final String title, final String overview, final File gameFile) {
return new OnLongClickListener() {
public boolean onLongClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(overview);
builder.setNegativeButton("Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
return;
}
});
builder.setPositiveButton("Launch",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
MainActivity.launchGame(gameFile);
return;
}
});
builder.create().show();
return true;
}
};
}
public String[] getGameInfo(File game, View childview) {
String serial = getSerial(game);
String gameID = null, title = null, overview = null, boxart = null;
ContentResolver cr = mContext.getContentResolver();
String selection = Games.KEY_SERIAL + "=?";
String[] selectionArgs = { serial };
Cursor c = cr.query(Games.GAMES_URI, null, selection, selectionArgs, null);
if (c != null) {
if (c.moveToFirst()) {
do {
gameID = c.getString(c.getColumnIndex(Games.KEY_GAMEID));
title = c.getString(c.getColumnIndex(Games.KEY_TITLE));
overview = c.getString(c.getColumnIndex(Games.KEY_OVERVIEW));
boxart = c.getString(c.getColumnIndex(Games.KEY_BOXART));
if (gameID != null && !gameID.equals("")) {
break;
}
} while (c.moveToNext());
}
c.close();
}
if (overview != null && boxart != null &&
!overview.equals("") && !boxart.equals("")) {
return new String[] { gameID, title, overview, boxart };
} else {
GamesDbAPI gameDatabase = new GamesDbAPI(mContext, gameID);
gameDatabase.setView(childview);
gameDatabase.execute(game);
return null;
}
}
public String getSerial(File game) {
String serial = NativeInterop.getDiskId(game.getPath());
Log.d("Play!", game.getName() + " [" + serial + "]");
return serial;
}
} |
package SimpleWriteAndRead;
import com.continuuity.api.data.*;
import com.continuuity.api.flow.flowlet.*;
import com.continuuity.api.flow.flowlet.builders.*;
public class ReaderFlowlet extends AbstractComputeFlowlet {
@Override
public void configure(StreamsConfigurator configurator) {
TupleSchema in = new TupleSchemaBuilder().
add("key", byte[].class).
create();
configurator.getDefaultTupleInputStream().setSchema(in);
}
@Override
public void process(Tuple tuple, TupleContext tupleContext, OutputCollector outputCollector) {
if (Common.debug)
System.out.println(this.getClass().getSimpleName() + ": Received tuple " + tuple);
// perform inline read of key
byte [] key = tuple.get("key");
ReadKey read = new ReadKey(key);
ReadOperationExecutor executor =
getFlowletLaunchContext().getReadExecutor();
byte [] value = executor.execute(read);
if (Common.debug)
System.out.println(this.getClass().getSimpleName() + ": Read value (" +
new String(value) + ") for key (" + new String(key) + ")");
}
} |
package com.mygdx.states;
import com.mygdx.handlers.AssetManager;
import com.mygdx.handlers.GameStateManager;
import com.mygdx.UI.MyStage;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.mygdx.handlers.NetworkManager;
public class LevelSelect extends GameState {
private MyStage stage;
private TextButton easy;
private TextButton medium;
private TextButton hard;
private TextButton insane;
public LevelSelect(GameStateManager gameStateManager, NetworkManager networkManager){
super(gameStateManager,networkManager);
stage = new MyStage();
Gdx.input.setInputProcessor(stage);
Skin skin = new Skin(Gdx.files.internal("UiData/uiskin.json"));
easy = new TextButton("Easy",skin);
easy.setSize(200, 60);
easy.setPosition(game.V_WIDTH/2-easy.getWidth()/2, game.V_HEIGHT*3/4);
easy.addListener(new ClickListener());
stage.addActor(easy);
medium = new TextButton("Medium",skin);
medium.setSize(200,60);
medium.setPosition(game.V_WIDTH / 2 - easy.getWidth() / 2, easy.getY() - 60);
medium.addListener(new ClickListener());
stage.addActor(medium);
hard = new TextButton("Hard",skin);
hard.setSize(200, 60);
hard.setPosition(game.V_WIDTH/2-hard.getWidth()/2, medium.getY() - 60);
hard.addListener(new ClickListener());
stage.addActor(hard);
insane = new TextButton("Insane",skin);
insane.setSize(200, 60);
insane.setPosition(game.V_WIDTH/2-insane.getWidth()/2, hard.getY() - 60);
insane.addListener(new ClickListener());
stage.addActor(insane);
}
@Override
public void update(float delta) {
if(easy.isChecked()){
gameStateManager.setState(GameStateManager.PLAY, 1);
}
if(medium.isChecked()) {
gameStateManager.setState(GameStateManager.PLAY, 2);
}
if(hard.isChecked()) {
gameStateManager.setState(GameStateManager.PLAY, 3);
}
if(insane.isChecked()) {
gameStateManager.setState(GameStateManager.PLAY, 4);
}
}
@Override
public void show() {
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 2);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
update(delta);
stage.act(delta);
stage.draw();
//((OrthographicCamera)stage.getCamera()).zoom += .01;
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
}
} |
package org.batfish.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.batfish.collections.EdgeSet;
import org.batfish.collections.FibMap;
import org.batfish.collections.FibRow;
import org.batfish.collections.FibSet;
import org.batfish.collections.FlowSinkInterface;
import org.batfish.collections.FlowSinkSet;
import org.batfish.collections.FunctionSet;
import org.batfish.collections.MultiSet;
import org.batfish.collections.NodeInterfacePair;
import org.batfish.collections.NodeRoleMap;
import org.batfish.collections.NodeSet;
import org.batfish.collections.PolicyRouteFibIpMap;
import org.batfish.collections.PolicyRouteFibNodeMap;
import org.batfish.collections.PredicateSemantics;
import org.batfish.collections.PredicateValueTypeMap;
import org.batfish.collections.QualifiedNameMap;
import org.batfish.collections.RoleNodeMap;
import org.batfish.collections.RoleSet;
import org.batfish.collections.TreeMultiSet;
import org.batfish.common.BfConsts;
import org.batfish.grammar.BatfishCombinedParser;
import org.batfish.grammar.ParseTreePrettyPrinter;
import org.batfish.grammar.juniper.JuniperCombinedParser;
import org.batfish.grammar.juniper.JuniperFlattener;
import org.batfish.grammar.logicblox.LogQLPredicateInfoExtractor;
import org.batfish.grammar.logicblox.LogiQLCombinedParser;
import org.batfish.grammar.logicblox.LogiQLPredicateInfoResolver;
import org.batfish.grammar.question.QuestionCombinedParser;
import org.batfish.grammar.question.QuestionExtractor;
import org.batfish.grammar.topology.BatfishTopologyCombinedParser;
import org.batfish.grammar.topology.BatfishTopologyExtractor;
import org.batfish.grammar.topology.GNS3TopologyCombinedParser;
import org.batfish.grammar.topology.GNS3TopologyExtractor;
import org.batfish.grammar.topology.RoleCombinedParser;
import org.batfish.grammar.topology.RoleExtractor;
import org.batfish.grammar.topology.TopologyExtractor;
import org.batfish.grammar.z3.ConcretizerQueryResultCombinedParser;
import org.batfish.grammar.z3.ConcretizerQueryResultExtractor;
import org.batfish.grammar.z3.DatalogQueryResultCombinedParser;
import org.batfish.grammar.z3.DatalogQueryResultExtractor;
import org.batfish.job.FlattenVendorConfigurationJob;
import org.batfish.job.FlattenVendorConfigurationResult;
import org.batfish.job.ParseVendorConfigurationJob;
import org.batfish.job.ParseVendorConfigurationResult;
import org.batfish.logic.LogicResourceLocator;
import org.batfish.logicblox.ConfigurationFactExtractor;
import org.batfish.logicblox.Facts;
import org.batfish.logicblox.LBInitializationException;
import org.batfish.logicblox.LBValueType;
import org.batfish.logicblox.LogicBloxFrontend;
import org.batfish.logicblox.PredicateInfo;
import org.batfish.logicblox.ProjectFile;
import org.batfish.logicblox.QueryException;
import org.batfish.logicblox.TopologyFactExtractor;
import org.batfish.question.Question;
import org.batfish.representation.BgpNeighbor;
import org.batfish.representation.BgpProcess;
import org.batfish.representation.Configuration;
import org.batfish.representation.Edge;
import org.batfish.representation.Interface;
import org.batfish.representation.Ip;
import org.batfish.representation.IpProtocol;
import org.batfish.representation.LineAction;
import org.batfish.representation.OspfArea;
import org.batfish.representation.OspfProcess;
import org.batfish.representation.PolicyMap;
import org.batfish.representation.PolicyMapAction;
import org.batfish.representation.PolicyMapClause;
import org.batfish.representation.PolicyMapMatchRouteFilterListLine;
import org.batfish.representation.Prefix;
import org.batfish.representation.RouteFilterLine;
import org.batfish.representation.RouteFilterList;
import org.batfish.representation.Topology;
import org.batfish.representation.VendorConfiguration;
import org.batfish.representation.cisco.CiscoVendorConfiguration;
import org.batfish.util.StringFilter;
import org.batfish.util.SubRange;
import org.batfish.util.UrlZipExplorer;
import org.batfish.util.Util;
import org.batfish.z3.ConcretizerQuery;
import org.batfish.z3.FailureInconsistencyBlackHoleQuerySynthesizer;
import org.batfish.z3.MultipathInconsistencyQuerySynthesizer;
import org.batfish.z3.NodJob;
import org.batfish.z3.NodJobResult;
import org.batfish.z3.QuerySynthesizer;
import org.batfish.z3.ReachableQuerySynthesizer;
import org.batfish.z3.RoleReachabilityQuerySynthesizer;
import org.batfish.z3.RoleTransitQuerySynthesizer;
import org.batfish.z3.Synthesizer;
import com.logicblox.bloxweb.client.ServiceClientException;
import com.logicblox.connect.Workspace.Relation;
import com.microsoft.z3.Context;
import com.microsoft.z3.Z3Exception;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* This class encapsulates the main control logic for Batfish.
*/
public class Batfish implements AutoCloseable {
/**
* Name of the LogiQL executable block containing basic facts that are true
* for any network
*/
private static final String BASIC_FACTS_BLOCKNAME = "BaseFacts";
/**
* Name of the file in which the topology of a network is serialized
*/
private static final String EDGES_FILENAME = "edges";
/**
* Name of the LogiQL data-plane predicate containing next hop information
* for policy-routing
*/
private static final String FIB_POLICY_ROUTE_NEXT_HOP_PREDICATE_NAME = "FibForwardPolicyRouteNextHopIp";
/**
* Name of the LogiQL data-plane predicate containing next hop information
* for destination-based routing
*/
private static final String FIB_PREDICATE_NAME = "FibNetwork";
/**
* Name of the file in which the destination-routing FIBs are serialized
*/
private static final String FIBS_FILENAME = "fibs";
/**
* Name of the file in which the policy-routing FIBs are serialized
*/
private static final String FIBS_POLICY_ROUTE_NEXT_HOP_FILENAME = "fibs-policy-route";
/**
* Name of the LogiQL predicate containing flow-sink interface tags
*/
private static final String FLOW_SINK_PREDICATE_NAME = "FlowSinkInterface";
/**
* Name of the file in which derived flow-sink interface tags are serialized
*/
private static final String FLOW_SINKS_FILENAME = "flow-sinks";
private static final String GEN_OSPF_STARTING_IP = "10.0.0.0";
/**
* A byte-array containing the first 4 bytes comprising the header for a file
* that is the output of java serialization
*/
private static final byte[] JAVA_SERIALIZED_OBJECT_HEADER = { (byte) 0xac,
(byte) 0xed, (byte) 0x00, (byte) 0x05 };
private static final long JOB_POLLING_PERIOD_MS = 1000l;
/**
* The name of the LogiQL library for org.batfish
*/
private static final String LB_BATFISH_LIBRARY_NAME = "libbatfish";
/**
* The name of the file in which LogiQL predicate type-information and
* documentation is serialized
*/
private static final String PREDICATE_INFO_FILENAME = "predicateInfo.object";
/**
* A string containing the system-specific path separator character
*/
private static final String SEPARATOR = System.getProperty("file.separator");
/**
* Role name for generated stubs
*/
private static final String STUB_ROLE = "generated_stubs";
private static final String TESTRIG_CONFIGURATION_DIRECTORY = "configs";
/**
* The name of the [optional] topology file within a test-rig
*/
private static final String TOPOLOGY_FILENAME = "topology.net";
/**
* The name of the LogiQL predicate containing pairs of interfaces in the
* same LAN segment
*/
private static final String TOPOLOGY_PREDICATE_NAME = "LanAdjacent";
public static String flatten(String input, BatfishLogger logger,
Settings settings) {
JuniperCombinedParser jparser = new JuniperCombinedParser(input,
settings.getThrowOnParserError(), settings.getThrowOnLexerError());
ParserRuleContext jtree = parse(jparser, logger, settings);
JuniperFlattener flattener = new JuniperFlattener();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(flattener, jtree);
return flattener.getFlattenedConfigurationText();
}
private static void initControlPlaneFactBins(
Map<String, StringBuilder> factBins) {
initFactBins(Facts.CONTROL_PLANE_FACT_COLUMN_HEADERS, factBins);
}
private static void initFactBins(Map<String, String> columnHeaderMap,
Map<String, StringBuilder> factBins) {
for (String factPredicate : columnHeaderMap.keySet()) {
String columnHeaders = columnHeaderMap.get(factPredicate);
String initialText = columnHeaders + "\n";
factBins.put(factPredicate, new StringBuilder(initialText));
}
}
private static void initTrafficFactBins(Map<String, StringBuilder> factBins) {
initFactBins(Facts.TRAFFIC_FACT_COLUMN_HEADERS, factBins);
}
public static ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
BatfishLogger logger, Settings settings) {
ParserRuleContext tree;
try {
tree = parser.parse();
}
catch (BatfishException e) {
throw new ParserBatfishException("Parser error", e);
}
List<String> errors = parser.getErrors();
int numErrors = errors.size();
if (numErrors > 0) {
logger.error(numErrors + " ERROR(S)\n");
for (int i = 0; i < numErrors; i++) {
String prefix = "ERROR " + (i + 1) + ": ";
String msg = errors.get(i);
String prefixedMsg = Util.applyPrefix(prefix, msg);
logger.error(prefixedMsg + "\n");
}
throw new ParserBatfishException("Parser error(s)");
}
else if (!settings.printParseTree()) {
logger.info("OK\n");
}
else {
logger.info("OK, PRINTING PARSE TREE:\n");
logger.info(ParseTreePrettyPrinter.print(tree, parser) + "\n\n");
}
return tree;
}
public static ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
String filename, BatfishLogger logger, Settings settings) {
logger.info("Parsing: \"" + filename + "\"...");
return parse(parser, logger, settings);
}
private List<LogicBloxFrontend> _lbFrontends;
private BatfishLogger _logger;
private PredicateInfo _predicateInfo;
private Settings _settings;
private long _timerCount;
private File _tmpLogicDir;
public Batfish(Settings settings) {
_settings = settings;
_logger = _settings.getLogger();
_lbFrontends = new ArrayList<LogicBloxFrontend>();
_tmpLogicDir = null;
}
private void addProject(LogicBloxFrontend lbFrontend) {
_logger.info("\n*** ADDING PROJECT ***\n");
resetTimer();
String settingsLogicDir = _settings.getLogicDir();
File logicDir;
if (settingsLogicDir != null) {
logicDir = new ProjectFile(settingsLogicDir);
}
else {
logicDir = retrieveLogicDir().getAbsoluteFile();
}
String result = lbFrontend.addProject(logicDir, "");
cleanupLogicDir();
if (result != null) {
throw new BatfishException(result + "\n");
}
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void addStaticFacts(LogicBloxFrontend lbFrontend, String blockName) {
_logger.info("\n*** ADDING STATIC FACTS ***\n");
resetTimer();
_logger.info("Adding " + blockName + "....");
String output = lbFrontend.execNamedBlock(LB_BATFISH_LIBRARY_NAME + ":"
+ blockName);
if (output == null) {
_logger.info("OK\n");
}
else {
throw new BatfishException(output + "\n");
}
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void anonymizeConfigurations() {
// TODO Auto-generated method stub
}
private void answer(String questionPath) {
Question question = parseQuestion(questionPath);
switch (question.getType()) {
case MULTIPATH:
answerMultipath(question);
break;
default:
throw new BatfishException("Unknown question type");
}
}
private void answerMultipath(Question question) {
String environmentName = question.getMasterEnvironment();
Path envPath = Paths.get(_settings.getAutoBaseDir(),
BfConsts.RELPATH_ENVIRONMENTS_DIR, environmentName);
Path queryDir = Paths.get(_settings.getAutoBaseDir(),
BfConsts.RELPATH_QUESTIONS_DIR, _settings.getQuestionName(),
BfConsts.RELPATH_QUERIES_DIR);
_settings.setMultipathInconsistencyQueryPath(queryDir.resolve(
BfConsts.RELPATH_MULTIPATH_QUERY_PREFIX).toString());
_settings.setNodeSetPath(envPath.resolve(BfConsts.RELPATH_ENV_NODE_SET)
.toString());
_settings.setDataPlaneDir(envPath
.resolve(BfConsts.RELPATH_DATA_PLANE_DIR).toString());
_settings.setDumpFactsDir(_settings.getTrafficFactDumpDir());
genMultipathQueries();
List<QuerySynthesizer> queries = new ArrayList<QuerySynthesizer>();
Map<String, Configuration> configurations = deserializeConfigurations(_settings
.getSerializeIndependentPath());
Set<String> flowLines = null;
try {
Context ctx = new Context();
Synthesizer dataPlane = synthesizeDataPlane(configurations, ctx);
Map<QuerySynthesizer, NodeSet> queryNodes = new HashMap<QuerySynthesizer, NodeSet>();
for (String node : configurations.keySet()) {
MultipathInconsistencyQuerySynthesizer query = new MultipathInconsistencyQuerySynthesizer(
node);
queries.add(query);
NodeSet nodes = new NodeSet();
nodes.add(node);
queryNodes.put(query, nodes);
}
flowLines = computeNodOutput(dataPlane, queries, queryNodes);
}
catch (Z3Exception e) {
throw new BatfishException("Error creating nod programs", e);
}
Map<String, StringBuilder> trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
StringBuilder wSetFlowOriginate = trafficFactBins.get("SetFlowOriginate");
for (String flowLine : flowLines) {
wSetFlowOriginate.append(flowLine);
}
dumpFacts(trafficFactBins);
}
/**
* This function extracts predicate type information from the logic files. It
* is meant only to be called during the build process, and should never be
* executed from a jar
*/
private void buildPredicateInfo() {
Path logicBinDirPath = null;
URL logicSourceURL = LogicResourceLocator.class.getProtectionDomain()
.getCodeSource().getLocation();
String logicSourceString = logicSourceURL.toString();
if (logicSourceString.startsWith("onejar:")) {
throw new BatfishException(
"buildPredicateInfo() should never be called from within a jar");
}
String logicPackageResourceName = LogicResourceLocator.class.getPackage()
.getName().replace('.', SEPARATOR.charAt(0));
try {
logicBinDirPath = Paths.get(LogicResourceLocator.class
.getClassLoader().getResource(logicPackageResourceName).toURI());
}
catch (URISyntaxException e) {
throw new BatfishException("Failed to resolve logic output directory",
e);
}
Path logicSrcDirPath = Paths.get(_settings.getLogicSrcDir());
final Set<Path> logicFiles = new TreeSet<Path>();
try {
Files.walkFileTree(logicSrcDirPath,
new java.nio.file.SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
String name = file.getFileName().toString();
if (!name.equals("BaseFacts.logic")
&& !name.endsWith("_rules.logic")
&& !name.startsWith("service_")
&& name.endsWith(".logic")) {
logicFiles.add(file);
}
return super.visitFile(file, attrs);
}
});
}
catch (IOException e) {
throw new BatfishException("Could not make list of logic files", e);
}
PredicateValueTypeMap predicateValueTypes = new PredicateValueTypeMap();
QualifiedNameMap qualifiedNameMap = new QualifiedNameMap();
FunctionSet functions = new FunctionSet();
PredicateSemantics predicateSemantics = new PredicateSemantics();
List<ParserRuleContext> trees = new ArrayList<ParserRuleContext>();
for (Path logicFilePath : logicFiles) {
String input = readFile(logicFilePath.toFile());
LogiQLCombinedParser parser = new LogiQLCombinedParser(input,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, logicFilePath.toString());
trees.add(tree);
}
ParseTreeWalker walker = new ParseTreeWalker();
for (ParserRuleContext tree : trees) {
LogQLPredicateInfoExtractor extractor = new LogQLPredicateInfoExtractor(
predicateValueTypes);
walker.walk(extractor, tree);
}
for (ParserRuleContext tree : trees) {
LogiQLPredicateInfoResolver resolver = new LogiQLPredicateInfoResolver(
predicateValueTypes, qualifiedNameMap, functions,
predicateSemantics);
walker.walk(resolver, tree);
}
PredicateInfo predicateInfo = new PredicateInfo(predicateSemantics,
predicateValueTypes, functions, qualifiedNameMap);
File predicateInfoFile = logicBinDirPath.resolve(PREDICATE_INFO_FILENAME)
.toFile();
serializeObject(predicateInfo, predicateInfoFile);
}
private void cleanupLogicDir() {
if (_tmpLogicDir != null) {
try {
FileUtils.deleteDirectory(_tmpLogicDir);
}
catch (IOException e) {
throw new BatfishException(
"Error cleaning up temporary logic directory", e);
}
_tmpLogicDir = null;
}
}
@Override
public void close() throws Exception {
for (LogicBloxFrontend lbFrontend : _lbFrontends) {
// Close backend threads
if (lbFrontend != null && lbFrontend.connected()) {
lbFrontend.close();
}
}
}
private void computeDataPlane(LogicBloxFrontend lbFrontend) {
_logger.info("\n*** COMPUTING DATA PLANE STRUCTURES ***\n");
resetTimer();
lbFrontend.initEntityTable();
_logger.info("Retrieving flow sink information from LogicBlox...");
FlowSinkSet flowSinks = getFlowSinkSet(lbFrontend);
_logger.info("OK\n");
_logger.info("Retrieving topology information from LogicBlox...");
EdgeSet topologyEdges = getTopologyEdges(lbFrontend);
_logger.info("OK\n");
String fibQualifiedName = _predicateInfo.getPredicateNames().get(
FIB_PREDICATE_NAME);
_logger
.info("Retrieving destination-routing FIB information from LogicBlox...");
Relation fibNetwork = lbFrontend.queryPredicate(fibQualifiedName);
_logger.info("OK\n");
String fibPolicyRouteNextHopQualifiedName = _predicateInfo
.getPredicateNames().get(FIB_POLICY_ROUTE_NEXT_HOP_PREDICATE_NAME);
_logger
.info("Retrieving policy-routing FIB information from LogicBlox...");
Relation fibPolicyRouteNextHops = lbFrontend
.queryPredicate(fibPolicyRouteNextHopQualifiedName);
_logger.info("OK\n");
_logger.info("Caclulating forwarding rules...");
FibMap fibs = getRouteForwardingRules(fibNetwork, lbFrontend);
PolicyRouteFibNodeMap policyRouteFibNodeMap = getPolicyRouteFibNodeMap(
fibPolicyRouteNextHops, lbFrontend);
_logger.info("OK\n");
Path flowSinksPath = Paths.get(_settings.getDataPlaneDir(),
FLOW_SINKS_FILENAME);
new File(_settings.getDataPlaneDir()).mkdirs();
Path fibsPath = Paths.get(_settings.getDataPlaneDir(), FIBS_FILENAME);
Path fibsPolicyRoutePath = Paths.get(_settings.getDataPlaneDir(),
FIBS_POLICY_ROUTE_NEXT_HOP_FILENAME);
Path edgesPath = Paths.get(_settings.getDataPlaneDir(), EDGES_FILENAME);
_logger.info("Serializing flow sink set...");
serializeObject(flowSinks, flowSinksPath.toFile());
_logger.info("OK\n");
_logger.info("Serializing fibs...");
serializeObject(fibs, fibsPath.toFile());
_logger.info("OK\n");
_logger.info("Serializing policy route next hop interface map...");
serializeObject(policyRouteFibNodeMap, fibsPolicyRoutePath.toFile());
_logger.info("OK\n");
_logger.info("Serializing toplogy edges...");
serializeObject(topologyEdges, edgesPath.toFile());
_logger.info("OK\n");
printElapsedTime();
}
private Set<String> computeNodOutput(Synthesizer dataPlane,
List<QuerySynthesizer> queries,
Map<QuerySynthesizer, NodeSet> queryNodes) {
Set<String> facts = new TreeSet<String>();
int numConcurrentThreads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(numConcurrentThreads);
// ExecutorService pool = Executors.newSingleThreadExecutor();
Set<NodJob> jobs = new HashSet<NodJob>();
for (final QuerySynthesizer query : queries) {
NodeSet nodes = queryNodes.get(query);
NodJob job = new NodJob(dataPlane, query, nodes);
jobs.add(job);
}
List<Future<NodJobResult>> results;
try {
results = pool.invokeAll(jobs);
}
catch (InterruptedException e) {
throw new BatfishException("Nod executor service interrupted", e);
}
for (Future<NodJobResult> future : results) {
try {
NodJobResult result = future.get();
if (result.terminatedSuccessfully()) {
facts.addAll(result.getFlowLines());
}
else {
Throwable failureCause = result.getFailureCause();
if (failureCause != null) {
throw new BatfishException("Failure running nod job",
failureCause);
}
else {
throw new BatfishException("Unknown failure running nod job");
}
}
}
catch (InterruptedException e) {
throw new BatfishException("Nod job interrupted", e);
}
catch (ExecutionException e) {
throw new BatfishException("Could not execute nod job", e);
}
}
pool.shutdown();
return facts;
}
private void concretize() {
_logger.info("\n*** GENERATING Z3 CONCRETIZER QUERIES ***\n");
resetTimer();
String[] concInPaths = _settings.getConcretizerInputFilePaths();
String[] negConcInPaths = _settings.getNegatedConcretizerInputFilePaths();
List<ConcretizerQuery> concretizerQueries = new ArrayList<ConcretizerQuery>();
String blacklistDstIpPath = _settings.getBlacklistDstIpPath();
if (blacklistDstIpPath != null) {
String blacklistDstIpFileText = readFile(new File(blacklistDstIpPath));
String[] blacklistDstpIpStrs = blacklistDstIpFileText.split("\n");
Set<Ip> blacklistDstIps = new TreeSet<Ip>();
for (String blacklistDstIpStr : blacklistDstpIpStrs) {
Ip blacklistDstIp = new Ip(blacklistDstIpStr);
blacklistDstIps.add(blacklistDstIp);
}
if (blacklistDstIps.size() == 0) {
_logger.warn("Warning: empty set of blacklisted destination ips\n");
}
ConcretizerQuery blacklistIpQuery = ConcretizerQuery
.blacklistDstIpQuery(blacklistDstIps);
concretizerQueries.add(blacklistIpQuery);
}
for (String concInPath : concInPaths) {
_logger.info("Reading z3 datalog query output file: \"" + concInPath
+ "\"...");
File queryOutputFile = new File(concInPath);
String queryOutputStr = readFile(queryOutputFile);
_logger.info("OK\n");
DatalogQueryResultCombinedParser parser = new DatalogQueryResultCombinedParser(
queryOutputStr, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, concInPath);
_logger.info("Computing concretizer queries...");
ParseTreeWalker walker = new ParseTreeWalker();
DatalogQueryResultExtractor extractor = new DatalogQueryResultExtractor(
_settings.concretizeUnique(), false);
walker.walk(extractor, tree);
_logger.info("OK\n");
List<ConcretizerQuery> currentQueries = extractor
.getConcretizerQueries();
if (concretizerQueries.size() == 0) {
concretizerQueries.addAll(currentQueries);
}
else {
concretizerQueries = ConcretizerQuery.crossProduct(
concretizerQueries, currentQueries);
}
}
if (negConcInPaths != null) {
for (String negConcInPath : negConcInPaths) {
_logger
.info("Reading z3 datalog query output file (to be negated): \""
+ negConcInPath + "\"...");
File queryOutputFile = new File(negConcInPath);
String queryOutputStr = readFile(queryOutputFile);
_logger.info("OK\n");
DatalogQueryResultCombinedParser parser = new DatalogQueryResultCombinedParser(
queryOutputStr, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, negConcInPath);
_logger.info("Computing concretizer queries...");
ParseTreeWalker walker = new ParseTreeWalker();
DatalogQueryResultExtractor extractor = new DatalogQueryResultExtractor(
_settings.concretizeUnique(), true);
walker.walk(extractor, tree);
_logger.info("OK\n");
List<ConcretizerQuery> currentQueries = extractor
.getConcretizerQueries();
if (concretizerQueries.size() == 0) {
concretizerQueries.addAll(currentQueries);
}
else {
concretizerQueries = ConcretizerQuery.crossProduct(
concretizerQueries, currentQueries);
}
}
}
for (int i = 0; i < concretizerQueries.size(); i++) {
ConcretizerQuery cq = concretizerQueries.get(i);
String concQueryPath = _settings.getConcretizerOutputFilePath() + "-"
+ i + ".smt2";
_logger.info("Writing concretizer query file: \"" + concQueryPath
+ "\"...");
writeFile(concQueryPath, cq.getText());
_logger.info("OK\n");
}
printElapsedTime();
}
private LogicBloxFrontend connect() {
boolean assumedToExist = !_settings.createWorkspace();
String workspaceMaster = _settings.getWorkspaceName();
if (assumedToExist) {
String jobLogicBloxHostnamePath = _settings
.getJobLogicBloxHostnamePath();
if (jobLogicBloxHostnamePath != null) {
String lbHostname = readFile(new File(jobLogicBloxHostnamePath));
_settings.setConnectBloxHost(lbHostname);
}
}
else {
String serviceLogicBloxHostname = _settings
.getServiceLogicBloxHostname();
if (serviceLogicBloxHostname != null) {
_settings.setConnectBloxHost(serviceLogicBloxHostname);
}
}
LogicBloxFrontend lbFrontend = null;
try {
lbFrontend = initFrontend(assumedToExist, workspaceMaster);
}
catch (LBInitializationException e) {
throw new BatfishException("Failed to connect to LogicBlox", e);
}
return lbFrontend;
}
private Map<String, Configuration> convertConfigurations(
Map<String, VendorConfiguration> vendorConfigurations) {
boolean processingError = false;
Map<String, Configuration> configurations = new TreeMap<String, Configuration>();
_logger
.info("\n*** CONVERTING VENDOR CONFIGURATIONS TO INDEPENDENT FORMAT ***\n");
resetTimer();
boolean pedanticAsError = _settings.getPedanticAsError();
boolean pedanticRecord = _settings.getPedanticRecord();
boolean redFlagAsError = _settings.getRedFlagAsError();
boolean redFlagRecord = _settings.getRedFlagRecord();
boolean unimplementedAsError = _settings.getUnimplementedAsError();
boolean unimplementedRecord = _settings.getUnimplementedRecord();
for (String name : vendorConfigurations.keySet()) {
_logger.debug("Processing: \"" + name + "\"");
VendorConfiguration vc = vendorConfigurations.get(name);
Warnings warnings = new Warnings(pedanticAsError, pedanticRecord,
redFlagAsError, redFlagRecord, unimplementedAsError,
unimplementedRecord, false);
try {
Configuration config = vc
.toVendorIndependentConfiguration(warnings);
configurations.put(name, config);
_logger.debug(" ...OK\n");
}
catch (BatfishException e) {
_logger.fatal("...CONVERSION ERROR\n");
_logger.fatal(ExceptionUtils.getStackTrace(e));
processingError = true;
if (_settings.exitOnParseError()) {
break;
}
else {
continue;
}
}
finally {
for (String warning : warnings.getRedFlagWarnings()) {
_logger.redflag(warning);
}
for (String warning : warnings.getUnimplementedWarnings()) {
_logger.unimplemented(warning);
}
for (String warning : warnings.getPedanticWarnings()) {
_logger.pedantic(warning);
}
}
}
if (processingError) {
throw new BatfishException("Vendor conversion error(s)");
}
else {
printElapsedTime();
return configurations;
}
}
public Map<String, Configuration> deserializeConfigurations(
String serializedConfigPath) {
_logger
.info("\n*** DESERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n");
resetTimer();
Map<String, Configuration> configurations = new TreeMap<String, Configuration>();
File dir = new File(serializedConfigPath);
File[] serializedConfigs = dir.listFiles();
if (serializedConfigs == null) {
throw new BatfishException(
"Error reading vendor-independent configs directory");
}
for (File serializedConfig : serializedConfigs) {
String name = serializedConfig.getName();
_logger.debug("Reading config: \"" + serializedConfig + "\"");
Object object = deserializeObject(serializedConfig);
Configuration c = (Configuration) object;
configurations.put(name, c);
_logger.debug(" ...OK\n");
}
disableBlacklistedInterface(configurations);
disableBlacklistedNode(configurations);
printElapsedTime();
return configurations;
}
private Object deserializeObject(File inputFile) {
FileInputStream fis;
Object o = null;
ObjectInputStream ois;
try {
fis = new FileInputStream(inputFile);
if (!isJavaSerializationData(inputFile)) {
XStream xstream = new XStream(new DomDriver("UTF-8"));
ois = xstream.createObjectInputStream(fis);
}
else {
ois = new ObjectInputStream(fis);
}
o = ois.readObject();
ois.close();
}
catch (IOException | ClassNotFoundException e) {
throw new BatfishException("Failed to deserialize object from file: "
+ inputFile.toString(), e);
}
return o;
}
public Map<String, VendorConfiguration> deserializeVendorConfigurations(
String serializedVendorConfigPath) {
_logger.info("\n*** DESERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
Map<String, VendorConfiguration> vendorConfigurations = new TreeMap<String, VendorConfiguration>();
File dir = new File(serializedVendorConfigPath);
File[] serializedConfigs = dir.listFiles();
if (serializedConfigs == null) {
throw new BatfishException("Error reading vendor configs directory");
}
for (File serializedConfig : serializedConfigs) {
String name = serializedConfig.getName();
_logger.debug("Reading vendor config: \"" + serializedConfig + "\"");
Object object = deserializeObject(serializedConfig);
VendorConfiguration vc = (VendorConfiguration) object;
vendorConfigurations.put(name, vc);
_logger.debug("...OK\n");
}
printElapsedTime();
return vendorConfigurations;
}
private void disableBlacklistedInterface(
Map<String, Configuration> configurations) {
String blacklistInterfaceString = _settings.getBlacklistInterfaceString();
if (blacklistInterfaceString != null) {
String[] blacklistInterfaceStringParts = blacklistInterfaceString
.split(",");
String blacklistInterfaceNode = blacklistInterfaceStringParts[0];
String blacklistInterfaceName = blacklistInterfaceStringParts[1];
Configuration c = configurations.get(blacklistInterfaceNode);
Interface i = c.getInterfaces().get(blacklistInterfaceName);
i.setActive(false);
}
}
private void disableBlacklistedNode(Map<String, Configuration> configurations) {
String blacklistNode = _settings.getBlacklistNode();
if (blacklistNode != null) {
if (!configurations.containsKey(blacklistNode)) {
throw new BatfishException("Cannot blacklist non-existent node: "
+ blacklistNode);
}
Configuration configuration = configurations.get(blacklistNode);
for (Interface iface : configuration.getInterfaces().values()) {
iface.setActive(false);
}
}
}
private void dumpFacts(Map<String, StringBuilder> factBins) {
_logger.info("\n*** DUMPING FACTS ***\n");
resetTimer();
Path factsDir = Paths.get(_settings.getDumpFactsDir());
try {
Files.createDirectories(factsDir);
for (String factsFilename : factBins.keySet()) {
String facts = factBins.get(factsFilename).toString();
Path factsFilePath = factsDir.resolve(factsFilename);
_logger.info("Writing: \""
+ factsFilePath.toAbsolutePath().toString() + "\"\n");
FileUtils.write(factsFilePath.toFile(), facts);
}
}
catch (IOException e) {
throw new BatfishException("Failed to write fact dump file", e);
}
printElapsedTime();
}
private void dumpInterfaceDescriptions(String testRigPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> configs = parseVendorConfigurations(configurationData);
Map<String, VendorConfiguration> sortedConfigs = new TreeMap<String, VendorConfiguration>();
sortedConfigs.putAll(configs);
StringBuilder sb = new StringBuilder();
for (VendorConfiguration vconfig : sortedConfigs.values()) {
String node = vconfig.getHostname();
CiscoVendorConfiguration config = null;
try {
config = (CiscoVendorConfiguration) vconfig;
}
catch (ClassCastException e) {
continue;
}
Map<String, org.batfish.representation.cisco.Interface> sortedInterfaces = new TreeMap<String, org.batfish.representation.cisco.Interface>();
sortedInterfaces.putAll(config.getInterfaces());
for (org.batfish.representation.cisco.Interface iface : sortedInterfaces
.values()) {
String iname = iface.getName();
String description = iface.getDescription();
sb.append(node + " " + iname);
if (description != null) {
sb.append(" \"" + description + "\"");
}
sb.append("\n");
}
}
String output = sb.toString();
writeFile(outputPath, output);
}
private void flatten(String inputPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(inputPath);
Map<File, String> outputConfigurationData = new TreeMap<File, String>();
File inputFolder = new File(inputPath);
File[] configs = inputFolder.listFiles();
if (configs == null) {
throw new BatfishException("Error reading configs from input test rig");
}
try {
Files.createDirectories(Paths.get(outputPath));
}
catch (IOException e) {
throw new BatfishException(
"Could not create output testrig directory", e);
}
_logger.info("\n*** FLATTENING TEST RIG ***\n");
resetTimer();
ExecutorService pool;
boolean shuffle;
if (_settings.getParseParallel()) {
int numConcurrentThreads = Runtime.getRuntime().availableProcessors();
pool = Executors.newFixedThreadPool(numConcurrentThreads);
shuffle = true;
}
else {
pool = Executors.newSingleThreadExecutor();
shuffle = false;
}
List<FlattenVendorConfigurationJob> jobs = new ArrayList<FlattenVendorConfigurationJob>();
boolean processingError = false;
for (File inputFile : configurationData.keySet()) {
Warnings warnings = new Warnings(_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(), _settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = configurationData.get(inputFile);
String name = inputFile.getName();
File outputFile = Paths.get(outputPath,
TESTRIG_CONFIGURATION_DIRECTORY, name).toFile();
FlattenVendorConfigurationJob job = new FlattenVendorConfigurationJob(
_settings, fileText, inputFile, outputFile, warnings);
jobs.add(job);
}
if (shuffle) {
Collections.shuffle(jobs);
}
List<Future<FlattenVendorConfigurationResult>> futures = new ArrayList<Future<FlattenVendorConfigurationResult>>();
for (FlattenVendorConfigurationJob job : jobs) {
Future<FlattenVendorConfigurationResult> future = pool.submit(job);
futures.add(future);
}
while (!futures.isEmpty()) {
List<Future<FlattenVendorConfigurationResult>> currentFutures = new ArrayList<Future<FlattenVendorConfigurationResult>>();
currentFutures.addAll(futures);
for (Future<FlattenVendorConfigurationResult> future : currentFutures) {
if (future.isDone()) {
futures.remove(future);
FlattenVendorConfigurationResult result = null;
try {
result = future.get();
}
catch (InterruptedException | ExecutionException e) {
throw new BatfishException("Error executing parse job", e);
}
_logger.append(result.getHistory());
Throwable failureCause = result.getFailureCause();
if (failureCause != null) {
if (_settings.exitOnParseError()) {
throw new BatfishException("Failed parse job",
failureCause);
}
else {
processingError = true;
_logger.error(ExceptionUtils.getStackTrace(failureCause));
}
}
else {
File outputFile = result.getOutputFile();
String flattenedText = result.getFlattenedText();
outputConfigurationData.put(outputFile, flattenedText);
}
}
else {
continue;
}
}
if (!futures.isEmpty()) {
try {
Thread.sleep(JOB_POLLING_PERIOD_MS);
}
catch (InterruptedException e) {
throw new BatfishException("interrupted while sleeping", e);
}
}
}
pool.shutdown();
if (processingError) {
throw new BatfishException("Error flattening vendor configurations");
}
else {
printElapsedTime();
}
for (Entry<File, String> e : outputConfigurationData.entrySet()) {
File outputFile = e.getKey();
String flatConfigText = e.getValue();
String outputFileAsString = outputFile.toString();
_logger.debug("Writing config to \"" + outputFileAsString + "\"...");
writeFile(outputFileAsString, flatConfigText);
_logger.debug("OK\n");
}
Path inputTopologyPath = Paths.get(inputPath, TOPOLOGY_FILENAME);
Path outputTopologyPath = Paths.get(outputPath, TOPOLOGY_FILENAME);
if (Files.isRegularFile(inputTopologyPath)) {
String topologyFileText = readFile(inputTopologyPath.toFile());
writeFile(outputTopologyPath.toString(), topologyFileText);
}
}
private void genBlackHoleQueries() {
_logger.info("\n*** GENERATING BLACK-HOLE QUERIES ***\n");
resetTimer();
String fiQueryBasePath = _settings.getBlackHoleQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
QuerySynthesizer synth = new FailureInconsistencyBlackHoleQuerySynthesizer(
hostname);
String queryText = synth.getQueryText();
String fiQueryPath;
fiQueryPath = fiQueryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + fiQueryPath + "\"...");
writeFile(fiQueryPath, queryText);
_logger.info("OK\n");
}
printElapsedTime();
}
private void generateOspfConfigs(String topologyPath, String outputPath) {
File topologyFilePath = new File(topologyPath);
Topology topology = parseTopology(topologyFilePath);
Map<String, Configuration> configs = new TreeMap<String, Configuration>();
NodeSet allNodes = new NodeSet();
Map<NodeInterfacePair, Set<NodeInterfacePair>> interfaceMap = new HashMap<NodeInterfacePair, Set<NodeInterfacePair>>();
// first we collect set of all mentioned nodes, and build mapping from
// each interface to the set of interfaces that connect to each other
for (Edge edge : topology.getEdges()) {
allNodes.add(edge.getNode1());
allNodes.add(edge.getNode2());
NodeInterfacePair interface1 = new NodeInterfacePair(edge.getNode1(),
edge.getInt1());
NodeInterfacePair interface2 = new NodeInterfacePair(edge.getNode2(),
edge.getInt2());
Set<NodeInterfacePair> interfaceSet = interfaceMap.get(interface1);
if (interfaceSet == null) {
interfaceSet = new HashSet<NodeInterfacePair>();
}
interfaceMap.put(interface1, interfaceSet);
interfaceMap.put(interface2, interfaceSet);
interfaceSet.add(interface1);
interfaceSet.add(interface2);
}
// then we create configs for every mentioned node
for (String hostname : allNodes) {
Configuration config = new Configuration(hostname);
configs.put(hostname, config);
}
// Now we create interfaces for each edge and record the number of
// neighbors so we know how large to make the subnet
long currentStartingIpAsLong = new Ip(GEN_OSPF_STARTING_IP).asLong();
Set<Set<NodeInterfacePair>> interfaceSets = new HashSet<Set<NodeInterfacePair>>();
interfaceSets.addAll(interfaceMap.values());
for (Set<NodeInterfacePair> interfaceSet : interfaceSets) {
int numInterfaces = interfaceSet.size();
if (numInterfaces < 2) {
throw new BatfishException(
"The following interface set contains less than two interfaces: "
+ interfaceSet.toString());
}
int numHostBits = 0;
for (int shiftedValue = numInterfaces - 1; shiftedValue != 0; shiftedValue >>= 1, numHostBits++) {
}
int subnetBits = 32 - numHostBits;
int offset = 0;
for (NodeInterfacePair currentPair : interfaceSet) {
Ip ip = new Ip(currentStartingIpAsLong + offset);
Prefix prefix = new Prefix(ip, subnetBits);
String ifaceName = currentPair.getInterface();
Interface iface = new Interface(ifaceName);
iface.setPrefix(prefix);
// dirty hack for setting bandwidth for now
double ciscoBandwidth = org.batfish.representation.cisco.Interface
.getDefaultBandwidth(ifaceName);
double juniperBandwidth = org.batfish.representation.juniper.Interface
.getDefaultBandwidthByName(ifaceName);
double bandwidth = Math.min(ciscoBandwidth, juniperBandwidth);
iface.setBandwidth(bandwidth);
String hostname = currentPair.getHostname();
Configuration config = configs.get(hostname);
config.getInterfaces().put(ifaceName, iface);
offset++;
}
currentStartingIpAsLong += (1 << numHostBits);
}
for (Configuration config : configs.values()) {
// use cisco arbitrarily
config.setVendor(ConfigurationFormat.CISCO);
OspfProcess proc = new OspfProcess();
config.setOspfProcess(proc);
proc.setReferenceBandwidth(org.batfish.representation.cisco.OspfProcess.DEFAULT_REFERENCE_BANDWIDTH);
long backboneArea = 0;
OspfArea area = new OspfArea(backboneArea);
proc.getAreas().put(backboneArea, area);
area.getInterfaces().addAll(config.getInterfaces().values());
}
serializeIndependentConfigs(configs, outputPath);
}
private void generateStubs(String inputRole, int stubAs,
String interfaceDescriptionRegex, String configPath) {
Map<String, Configuration> configs = deserializeConfigurations(configPath);
Pattern pattern = Pattern.compile(interfaceDescriptionRegex);
Map<String, Configuration> stubConfigurations = new TreeMap<String, Configuration>();
_logger.info("\n*** GENERATING STUBS ***\n");
resetTimer();
// load old node-roles to be updated at end
RoleSet stubRoles = new RoleSet();
stubRoles.add(STUB_ROLE);
File nodeRolesPath = new File(_settings.getNodeRolesPath());
_logger.info("Deserializing old node-roles mappings: \"" + nodeRolesPath
+ "\" ...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(nodeRolesPath);
_logger.info("OK\n");
// create origination policy common to all stubs
String stubOriginationPolicyName = "~STUB_ORIGINATION_POLICY~";
PolicyMap stubOriginationPolicy = new PolicyMap(stubOriginationPolicyName);
PolicyMapClause clause = new PolicyMapClause();
stubOriginationPolicy.getClauses().add(clause);
String stubOriginationRouteFilterListName = "~STUB_ORIGINATION_ROUTE_FILTER~";
RouteFilterList rf = new RouteFilterList(
stubOriginationRouteFilterListName);
RouteFilterLine rfl = new RouteFilterLine(LineAction.ACCEPT, Prefix.ZERO,
new SubRange(0, 0));
rf.addLine(rfl);
PolicyMapMatchRouteFilterListLine matchLine = new PolicyMapMatchRouteFilterListLine(
Collections.singleton(rf));
clause.getMatchLines().add(matchLine);
clause.setAction(PolicyMapAction.PERMIT);
// create flow sink interface common to all stubs
String flowSinkName = "TenGibabitEthernet100/100";
Interface flowSink = new Interface(flowSinkName);
flowSink.setPrefix(Prefix.ZERO);
flowSink.setActive(true);
flowSink.setBandwidth(10E9d);
Set<String> skipWarningNodes = new HashSet<String>();
for (Configuration config : configs.values()) {
if (!config.getRoles().contains(inputRole)) {
continue;
}
for (BgpNeighbor neighbor : config.getBgpProcess().getNeighbors()
.values()) {
if (!neighbor.getRemoteAs().equals(stubAs)) {
continue;
}
Prefix neighborPrefix = neighbor.getPrefix();
if (neighborPrefix.getPrefixLength() != 32) {
throw new BatfishException(
"do not currently handle generating stubs based on dynamic bgp sessions");
}
Ip neighborAddress = neighborPrefix.getAddress();
int edgeAs = neighbor.getLocalAs();
/*
* Now that we have the ip address of the stub, we want to find the
* interface that connects to it. We will extract the hostname for
* the stub from the description of this interface using the
* supplied regex.
*/
boolean found = false;
for (Interface iface : config.getInterfaces().values()) {
Prefix prefix = iface.getPrefix();
if (prefix == null || !prefix.contains(neighborAddress)) {
continue;
}
// the neighbor address falls within the network assigned to this
// interface, so now we check the description
String description = iface.getDescription();
Matcher matcher = pattern.matcher(description);
if (matcher.find()) {
String hostname = matcher.group(1);
if (configs.containsKey(hostname)) {
Configuration duplicateConfig = configs.get(hostname);
if (!duplicateConfig.getRoles().contains(STUB_ROLE)
|| duplicateConfig.getRoles().size() != 1) {
throw new BatfishException(
"A non-generated node with hostname: \""
+ hostname
+ "\" already exists in network under analysis");
}
else {
if (!skipWarningNodes.contains(hostname)) {
_logger
.warn("WARNING: Overwriting previously generated node: \""
+ hostname + "\"\n");
skipWarningNodes.add(hostname);
}
}
}
found = true;
Configuration stub = stubConfigurations.get(hostname);
// create stub if it doesn't exist yet
if (stub == null) {
stub = new Configuration(hostname);
stubConfigurations.put(hostname, stub);
stub.getInterfaces().put(flowSinkName, flowSink);
stub.setBgpProcess(new BgpProcess());
stub.getPolicyMaps().put(stubOriginationPolicyName,
stubOriginationPolicy);
stub.getRouteFilterLists().put(
stubOriginationRouteFilterListName, rf);
stub.setVendor(ConfigurationFormat.CISCO);
stub.setRoles(stubRoles);
nodeRoles.put(hostname, stubRoles);
}
// create interface that will on which peering will occur
Map<String, Interface> stubInterfaces = stub.getInterfaces();
String stubInterfaceName = "TenGigabitEthernet0/"
+ (stubInterfaces.size() - 1);
Interface stubInterface = new Interface(stubInterfaceName);
stubInterfaces.put(stubInterfaceName, stubInterface);
stubInterface.setPrefix(new Prefix(neighborAddress, prefix
.getPrefixLength()));
stubInterface.setActive(true);
stubInterface.setBandwidth(10E9d);
// create neighbor within bgp process
BgpNeighbor edgeNeighbor = new BgpNeighbor(prefix);
edgeNeighbor.getOriginationPolicies().add(
stubOriginationPolicy);
edgeNeighbor.setRemoteAs(edgeAs);
edgeNeighbor.setLocalAs(stubAs);
edgeNeighbor.setSendCommunity(true);
edgeNeighbor.setDefaultMetric(0);
stub.getBgpProcess().getNeighbors()
.put(edgeNeighbor.getPrefix(), edgeNeighbor);
break;
}
else {
throw new BatfishException(
"Unable to derive stub hostname from interface description: \""
+ description + "\" using regex: \""
+ interfaceDescriptionRegex + "\"");
}
}
if (!found) {
throw new BatfishException(
"Could not determine stub hostname corresponding to ip: \""
+ neighborAddress.toString()
+ "\" listed as neighbor on router: \""
+ config.getHostname() + "\"");
}
}
}
// write updated node-roles mappings to disk
_logger.info("Serializing updated node-roles mappings: \""
+ nodeRolesPath + "\" ...");
serializeObject(nodeRoles, nodeRolesPath);
_logger.info("OK\n");
printElapsedTime();
// write stubs to disk
serializeIndependentConfigs(stubConfigurations, configPath);
}
private void genMultipathQueries() {
_logger.info("\n*** GENERATING MULTIPATH-INCONSISTENCY QUERIES ***\n");
resetTimer();
String mpiQueryBasePath = _settings.getMultipathInconsistencyQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
QuerySynthesizer synth = new MultipathInconsistencyQuerySynthesizer(
hostname);
String queryText = synth.getQueryText();
String mpiQueryPath = mpiQueryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + mpiQueryPath + "\"...");
writeFile(mpiQueryPath, queryText);
_logger.info("OK\n");
}
_logger.info("Writing node lines for next stage...");
StringBuilder sb = new StringBuilder();
for (String node : nodes) {
sb.append(node + "\n");
}
writeFile(nodeSetTextPath, sb.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genReachableQueries() {
_logger.info("\n*** GENERATING REACHABLE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getReachableQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String acceptNode = _settings.getAcceptNode();
String blacklistedNode = _settings.getBlacklistNode();
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
if (hostname.equals(acceptNode) || hostname.equals(blacklistedNode)) {
continue;
}
QuerySynthesizer synth = new ReachableQuerySynthesizer(hostname,
acceptNode);
String queryText = synth.getQueryText();
String queryPath;
queryPath = queryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
printElapsedTime();
}
private void genRoleReachabilityQueries() {
_logger.info("\n*** GENERATING NODE-TO-ROLE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getRoleReachabilityQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
String roleSetTextPath = _settings.getRoleSetPath();
String nodeRolesPath = _settings.getNodeRolesPath();
String iterationsPath = nodeRolesPath + ".iterations";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
_logger.info("Reading node roles from: \"" + nodeRolesPath + "\"...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
_logger.info("OK\n");
RoleNodeMap roleNodes = nodeRoles.toRoleNodeMap();
for (String hostname : nodes) {
for (String role : roleNodes.keySet()) {
QuerySynthesizer synth = new RoleReachabilityQuerySynthesizer(
hostname, role);
String queryText = synth.getQueryText();
String queryPath = queryBasePath + "-" + hostname + "-" + role
+ ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
}
_logger.info("Writing node lines for next stage...");
StringBuilder sbNodes = new StringBuilder();
for (String node : nodes) {
sbNodes.append(node + "\n");
}
writeFile(nodeSetTextPath, sbNodes.toString());
_logger.info("OK\n");
StringBuilder sbRoles = new StringBuilder();
_logger.info("Writing role lines for next stage...");
sbRoles = new StringBuilder();
for (String role : roleNodes.keySet()) {
sbRoles.append(role + "\n");
}
writeFile(roleSetTextPath, sbRoles.toString());
_logger.info("OK\n");
_logger
.info("Writing role-node-role iteration ordering lines for concretizer stage...");
StringBuilder sbIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transmittingRole = roleNodeEntry.getKey();
NodeSet transmittingNodes = roleNodeEntry.getValue();
if (transmittingNodes.size() < 2) {
continue;
}
String[] tNodeArray = transmittingNodes.toArray(new String[] {});
String masterNode = tNodeArray[0];
for (int i = 1; i < tNodeArray.length; i++) {
String slaveNode = tNodeArray[i];
for (String receivingRole : roleNodes.keySet()) {
String iterationLine = transmittingRole + ":" + masterNode + ":"
+ slaveNode + ":" + receivingRole + "\n";
sbIterations.append(iterationLine);
}
}
}
writeFile(iterationsPath, sbIterations.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genRoleTransitQueries() {
_logger.info("\n*** GENERATING ROLE-TO-NODE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getRoleTransitQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
String roleSetTextPath = _settings.getRoleSetPath();
String nodeRolesPath = _settings.getNodeRolesPath();
String roleNodesPath = _settings.getRoleNodesPath();
String iterationsPath = nodeRolesPath + ".rtiterations";
String constraintsIterationsPath = nodeRolesPath
+ ".rtconstraintsiterations";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
_logger.info("Reading node roles from: \"" + nodeRolesPath + "\"...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
_logger.info("OK\n");
RoleNodeMap roleNodes = nodeRoles.toRoleNodeMap();
for (Entry<String, NodeSet> sourceEntry : roleNodes.entrySet()) {
String sourceRole = sourceEntry.getKey();
for (Entry<String, NodeSet> transitEntry : roleNodes.entrySet()) {
String transitRole = transitEntry.getKey();
if (transitRole.equals(sourceRole)) {
continue;
}
NodeSet transitNodes = transitEntry.getValue();
for (String transitNode : transitNodes) {
QuerySynthesizer synth = new RoleTransitQuerySynthesizer(
sourceRole, transitNode);
String queryText = synth.getQueryText();
String queryPath = queryBasePath + "-" + transitNode + "-"
+ sourceRole + ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
}
}
_logger.info("Writing node lines for next stage...");
StringBuilder sbNodes = new StringBuilder();
for (String node : nodes) {
sbNodes.append(node + "\n");
}
writeFile(nodeSetTextPath, sbNodes.toString());
_logger.info("OK\n");
StringBuilder sbRoles = new StringBuilder();
_logger.info("Writing role lines for next stage...");
sbRoles = new StringBuilder();
for (String role : roleNodes.keySet()) {
sbRoles.append(role + "\n");
}
writeFile(roleSetTextPath, sbRoles.toString());
_logger.info("OK\n");
// not actually sure if this is necessary
StringBuilder sbRoleNodes = new StringBuilder();
_logger.info("Writing role-node mappings for concretizer stage...");
sbRoleNodes = new StringBuilder();
for (Entry<String, NodeSet> e : roleNodes.entrySet()) {
String role = e.getKey();
NodeSet currentNodes = e.getValue();
sbRoleNodes.append(role + ":");
for (String node : currentNodes) {
sbRoleNodes.append(node + ",");
}
sbRoleNodes.append(role + "\n");
}
writeFile(roleNodesPath, sbRoleNodes.toString());
_logger
.info("Writing transitrole-transitnode-sourcerole iteration ordering lines for constraints stage...");
StringBuilder sbConstraintsIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transitRole = roleNodeEntry.getKey();
NodeSet transitNodes = roleNodeEntry.getValue();
if (transitNodes.size() < 2) {
continue;
}
for (String sourceRole : roleNodes.keySet()) {
if (sourceRole.equals(transitRole)) {
continue;
}
for (String transitNode : transitNodes) {
String iterationLine = transitRole + ":" + transitNode + ":"
+ sourceRole + "\n";
sbConstraintsIterations.append(iterationLine);
}
}
}
writeFile(constraintsIterationsPath, sbConstraintsIterations.toString());
_logger.info("OK\n");
_logger
.info("Writing transitrole-master-slave-sourcerole iteration ordering lines for concretizer stage...");
StringBuilder sbIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transitRole = roleNodeEntry.getKey();
NodeSet transitNodes = roleNodeEntry.getValue();
if (transitNodes.size() < 2) {
continue;
}
String[] tNodeArray = transitNodes.toArray(new String[] {});
String masterNode = tNodeArray[0];
for (int i = 1; i < tNodeArray.length; i++) {
String slaveNode = tNodeArray[i];
for (String sourceRole : roleNodes.keySet()) {
if (sourceRole.equals(transitRole)) {
continue;
}
String iterationLine = transitRole + ":" + masterNode + ":"
+ slaveNode + ":" + sourceRole + "\n";
sbIterations.append(iterationLine);
}
}
}
writeFile(iterationsPath, sbIterations.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genZ3(Map<String, Configuration> configurations) {
_logger.info("\n*** GENERATING Z3 LOGIC ***\n");
resetTimer();
String outputPath = _settings.getZ3File();
if (outputPath == null) {
throw new BatfishException("Need to specify output path for z3 logic");
}
String nodeSetPath = _settings.getNodeSetPath();
if (nodeSetPath == null) {
throw new BatfishException(
"Need to specify output path for serialized set of nodes in environment");
}
Path flowSinkSetPath = Paths.get(_settings.getDataPlaneDir(),
FLOW_SINKS_FILENAME);
Path fibsPath = Paths.get(_settings.getDataPlaneDir(), FIBS_FILENAME);
Path prFibsPath = Paths.get(_settings.getDataPlaneDir(),
FIBS_POLICY_ROUTE_NEXT_HOP_FILENAME);
Path edgesPath = Paths.get(_settings.getDataPlaneDir(), EDGES_FILENAME);
_logger.info("Deserializing flow sink interface set: \""
+ flowSinkSetPath.toString() + "\"...");
FlowSinkSet flowSinks = (FlowSinkSet) deserializeObject(flowSinkSetPath
.toFile());
_logger.info("OK\n");
_logger.info("Deserializing destination route fibs: \""
+ fibsPath.toString() + "\"...");
FibMap fibs = (FibMap) deserializeObject(fibsPath.toFile());
_logger.info("OK\n");
_logger.info("Deserializing policy route fibs: \""
+ prFibsPath.toString() + "\"...");
PolicyRouteFibNodeMap prFibs = (PolicyRouteFibNodeMap) deserializeObject(prFibsPath
.toFile());
_logger.info("OK\n");
_logger.info("Deserializing toplogy edges: \"" + edgesPath.toString()
+ "\"...");
EdgeSet topologyEdges = (EdgeSet) deserializeObject(edgesPath.toFile());
_logger.info("OK\n");
_logger.info("Synthesizing Z3 logic...");
Synthesizer s = new Synthesizer(configurations, fibs, prFibs,
topologyEdges, _settings.getSimplify(), flowSinks);
String result = s.synthesize();
List<String> warnings = s.getWarnings();
int numWarnings = warnings.size();
if (numWarnings == 0) {
_logger.info("OK\n");
}
else {
for (String warning : warnings) {
_logger.warn(warning);
}
}
_logger.info("Writing Z3 logic: \"" + outputPath + "\"...");
File z3Out = new File(outputPath);
z3Out.delete();
writeFile(outputPath, result);
_logger.info("OK\n");
_logger.info("Serializing node set: \"" + nodeSetPath + "\"...");
NodeSet nodeSet = s.getNodeSet();
serializeObject(nodeSet, new File(nodeSetPath));
_logger.info("OK\n");
printElapsedTime();
}
public Map<String, Configuration> getConfigurations(
String serializedVendorConfigPath) {
Map<String, VendorConfiguration> vendorConfigurations = deserializeVendorConfigurations(serializedVendorConfigPath);
Map<String, Configuration> configurations = convertConfigurations(vendorConfigurations);
return configurations;
}
private double getElapsedTime(long beforeTime) {
long difference = System.currentTimeMillis() - beforeTime;
double seconds = difference / 1000d;
return seconds;
}
// private Set<Path> getMultipathQueryPaths(Path directory) {
// Set<Path> queryPaths = new TreeSet<Path>();
// try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(
// directory, new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path path) throws IOException {
// String filename = path.getFileName().toString();
// return filename
// .startsWith(BfConsts.RELPATH_MULTIPATH_QUERY_PREFIX)
// && filename.endsWith(".smt2");
// for (Path path : directoryStream) {
// queryPaths.add(path);
// catch (IOException ex) {
// throw new BatfishException(
// "Could not list files in queries directory", ex);
// return queryPaths;
private FlowSinkSet getFlowSinkSet(LogicBloxFrontend lbFrontend) {
FlowSinkSet flowSinks = new FlowSinkSet();
String qualifiedName = _predicateInfo.getPredicateNames().get(
FLOW_SINK_PREDICATE_NAME);
Relation flowSinkRelation = lbFrontend.queryPredicate(qualifiedName);
List<String> nodes = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nodes,
flowSinkRelation.getColumns().get(0));
List<String> interfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, interfaces,
flowSinkRelation.getColumns().get(1));
for (int i = 0; i < nodes.size(); i++) {
String node = nodes.get(i);
String iface = interfaces.get(i);
FlowSinkInterface f = new FlowSinkInterface(node, iface);
flowSinks.add(f);
}
return flowSinks;
}
private List<String> getHelpPredicates(Map<String, String> predicateSemantics) {
Set<String> helpPredicateSet = new LinkedHashSet<String>();
_settings.getHelpPredicates();
if (_settings.getHelpPredicates() == null) {
helpPredicateSet.addAll(predicateSemantics.keySet());
}
else {
helpPredicateSet.addAll(_settings.getHelpPredicates());
}
List<String> helpPredicates = new ArrayList<String>();
helpPredicates.addAll(helpPredicateSet);
Collections.sort(helpPredicates);
return helpPredicates;
}
private PolicyRouteFibNodeMap getPolicyRouteFibNodeMap(
Relation fibPolicyRouteNextHops, LogicBloxFrontend lbFrontend) {
PolicyRouteFibNodeMap nodeMap = new PolicyRouteFibNodeMap();
List<String> nodeList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nodeList,
fibPolicyRouteNextHops.getColumns().get(0));
List<String> ipList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_IP, ipList,
fibPolicyRouteNextHops.getColumns().get(1));
List<String> outInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, outInterfaces,
fibPolicyRouteNextHops.getColumns().get(2));
List<String> inNodes = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, inNodes,
fibPolicyRouteNextHops.getColumns().get(3));
List<String> inInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, inInterfaces,
fibPolicyRouteNextHops.getColumns().get(4));
int size = nodeList.size();
for (int i = 0; i < size; i++) {
String nodeOut = nodeList.get(i);
String nodeIn = inNodes.get(i);
Ip ip = new Ip(ipList.get(i));
String ifaceOut = outInterfaces.get(i);
String ifaceIn = inInterfaces.get(i);
PolicyRouteFibIpMap ipMap = nodeMap.get(nodeOut);
if (ipMap == null) {
ipMap = new PolicyRouteFibIpMap();
nodeMap.put(nodeOut, ipMap);
}
EdgeSet edges = ipMap.get(ip);
if (edges == null) {
edges = new EdgeSet();
ipMap.put(ip, edges);
}
Edge newEdge = new Edge(nodeOut, ifaceOut, nodeIn, ifaceIn);
edges.add(newEdge);
}
return nodeMap;
}
public PredicateInfo getPredicateInfo(Map<String, String> logicFiles) {
// Get predicate semantics from rules file
_logger.info("\n*** PARSING PREDICATE INFO ***\n");
resetTimer();
String predicateInfoPath = getPredicateInfoPath();
PredicateInfo predicateInfo = (PredicateInfo) deserializeObject(new File(
predicateInfoPath));
printElapsedTime();
return predicateInfo;
}
private String getPredicateInfoPath() {
File logicDir = retrieveLogicDir();
return Paths.get(logicDir.toString(), PREDICATE_INFO_FILENAME).toString();
}
private FibMap getRouteForwardingRules(Relation fibNetworkForward,
LogicBloxFrontend lbFrontend) {
FibMap fibs = new FibMap();
List<String> nameList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nameList,
fibNetworkForward.getColumns().get(0));
List<String> networkList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_INDEX_NETWORK, networkList,
fibNetworkForward.getColumns().get(1));
List<String> interfaceList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, interfaceList,
fibNetworkForward.getColumns().get(2));
List<String> nextHopList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nextHopList,
fibNetworkForward.getColumns().get(3));
List<String> nextHopIntList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nextHopIntList,
fibNetworkForward.getColumns().get(4));
String currentHostname = "";
Map<String, Integer> startIndices = new HashMap<String, Integer>();
Map<String, Integer> endIndices = new HashMap<String, Integer>();
for (int i = 0; i < nameList.size(); i++) {
String currentRowHostname = nameList.get(i);
if (!currentHostname.equals(currentRowHostname)) {
if (i > 0) {
endIndices.put(currentHostname, i - 1);
}
currentHostname = currentRowHostname;
startIndices.put(currentHostname, i);
}
}
endIndices.put(currentHostname, nameList.size() - 1);
for (String hostname : startIndices.keySet()) {
FibSet fibRows = new FibSet();
fibs.put(hostname, fibRows);
int startIndex = startIndices.get(hostname);
int endIndex = endIndices.get(hostname);
for (int i = startIndex; i <= endIndex; i++) {
String networkStr = networkList.get(i);
Prefix prefix = new Prefix(networkStr);
String iface = interfaceList.get(i);
String nextHop = nextHopList.get(i);
String nextHopInt = nextHopIntList.get(i);
fibRows.add(new FibRow(prefix, iface, nextHop, nextHopInt));
}
}
return fibs;
}
private Map<String, String> getSemanticsFiles() {
final Map<String, String> semanticsFiles = new HashMap<String, String>();
File logicDirFile = retrieveLogicDir();
FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String pathString = file.toString();
if (pathString.endsWith(".semantics")) {
String contents = FileUtils.readFileToString(file.toFile());
semanticsFiles.put(pathString, contents);
}
return super.visitFile(file, attrs);
}
};
try {
Files.walkFileTree(Paths.get(logicDirFile.getAbsolutePath()), visitor);
}
catch (IOException e) {
e.printStackTrace();
}
cleanupLogicDir();
return semanticsFiles;
}
public EdgeSet getTopologyEdges(LogicBloxFrontend lbFrontend) {
EdgeSet edges = new EdgeSet();
String qualifiedName = _predicateInfo.getPredicateNames().get(
TOPOLOGY_PREDICATE_NAME);
Relation topologyRelation = lbFrontend.queryPredicate(qualifiedName);
List<String> fromRouters = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, fromRouters,
topologyRelation.getColumns().get(0));
List<String> fromInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, fromInterfaces,
topologyRelation.getColumns().get(1));
List<String> toRouters = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, toRouters,
topologyRelation.getColumns().get(2));
List<String> toInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, toInterfaces,
topologyRelation.getColumns().get(3));
for (int i = 0; i < fromRouters.size(); i++) {
if (Util.isLoopback(fromInterfaces.get(i))
|| Util.isLoopback(toInterfaces.get(i))) {
continue;
}
Edge newEdge = new Edge(fromRouters.get(i), fromInterfaces.get(i),
toRouters.get(i), toInterfaces.get(i));
edges.add(newEdge);
}
return edges;
}
private void histogram(String testRigPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(configurationData);
_logger.info("Building feature histogram...");
MultiSet<String> histogram = new TreeMultiSet<String>();
for (VendorConfiguration vc : vendorConfigurations.values()) {
Set<String> unimplementedFeatures = vc.getUnimplementedFeatures();
histogram.add(unimplementedFeatures);
}
_logger.info("OK\n");
for (String feature : histogram.elements()) {
int count = histogram.count(feature);
_logger.output(feature + ": " + count + "\n");
}
}
public LogicBloxFrontend initFrontend(boolean assumedToExist,
String workspace) throws LBInitializationException {
_logger.info("\n*** STARTING CONNECTBLOX SESSION ***\n");
resetTimer();
LogicBloxFrontend lbFrontend = new LogicBloxFrontend(
_settings.getConnectBloxHost(), _settings.getConnectBloxPort(),
_settings.getLbWebPort(), _settings.getLbWebAdminPort(), workspace,
assumedToExist, _logger);
lbFrontend.initialize();
if (!lbFrontend.connected()) {
throw new BatfishException(
"Error connecting to ConnectBlox service. Please make sure service is running and try again.");
}
_logger.info("SUCCESS\n");
printElapsedTime();
_lbFrontends.add(lbFrontend);
return lbFrontend;
}
private boolean isJavaSerializationData(File inputFile) {
try (FileInputStream i = new FileInputStream(inputFile)) {
int headerLength = JAVA_SERIALIZED_OBJECT_HEADER.length;
byte[] headerBytes = new byte[headerLength];
int result = i.read(headerBytes, 0, headerLength);
if (result != headerLength) {
throw new BatfishException("Read wrong number of bytes");
}
return Arrays.equals(headerBytes, JAVA_SERIALIZED_OBJECT_HEADER);
}
catch (IOException e) {
throw new BatfishException("Could not read header from file: "
+ inputFile.toString(), e);
}
}
private ParserRuleContext parse(BatfishCombinedParser<?, ?> parser) {
return parse(parser, _logger, _settings);
}
private ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
String filename) {
_logger.info("Parsing: \"" + filename + "\"...");
return parse(parser);
}
private void parseFlowsFromConstraints(StringBuilder sb,
RoleNodeMap roleNodes) {
Path flowConstraintsDir = Paths.get(_settings.getFlowPath());
File[] constraintsFiles = flowConstraintsDir.toFile().listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.matches(".*-concrete-.*.smt2.out");
}
});
if (constraintsFiles == null) {
throw new BatfishException("Error reading flow constraints directory");
}
for (File constraintsFile : constraintsFiles) {
String flowConstraintsText = readFile(constraintsFile);
ConcretizerQueryResultCombinedParser parser = new ConcretizerQueryResultCombinedParser(
flowConstraintsText, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, constraintsFile.toString());
ParseTreeWalker walker = new ParseTreeWalker();
ConcretizerQueryResultExtractor extractor = new ConcretizerQueryResultExtractor();
walker.walk(extractor, tree);
String id = extractor.getId();
if (id == null) {
continue;
}
Map<String, Long> constraints = extractor.getConstraints();
long src_ip = 0;
long dst_ip = 0;
long src_port = 0;
long dst_port = 0;
long protocol = IpProtocol.IP.number();
for (String varName : constraints.keySet()) {
Long value = constraints.get(varName);
switch (varName) {
case Synthesizer.SRC_IP_VAR:
src_ip = value;
break;
case Synthesizer.DST_IP_VAR:
dst_ip = value;
break;
case Synthesizer.SRC_PORT_VAR:
src_port = value;
break;
case Synthesizer.DST_PORT_VAR:
dst_port = value;
break;
case Synthesizer.IP_PROTOCOL_VAR:
protocol = value;
break;
default:
throw new Error("invalid variable name");
}
}
// TODO: cleanup dirty hack
if (roleNodes != null) {
// id is role
NodeSet nodes = roleNodes.get(id);
for (String node : nodes) {
String line = node + "|" + src_ip + "|" + dst_ip + "|"
+ src_port + "|" + dst_port + "|" + protocol + "\n";
sb.append(line);
}
}
else {
String node = id;
String line = node + "|" + src_ip + "|" + dst_ip + "|" + src_port
+ "|" + dst_port + "|" + protocol + "\n";
sb.append(line);
}
}
}
private NodeRoleMap parseNodeRoles(String testRigPath) {
Path rolePath = Paths.get(testRigPath, "node_roles");
String roleFileText = readFile(rolePath.toFile());
_logger.info("Parsing: \"" + rolePath.toAbsolutePath().toString() + "\"");
BatfishCombinedParser<?, ?> parser = new RoleCombinedParser(roleFileText,
_settings.getThrowOnParserError(), _settings.getThrowOnLexerError());
RoleExtractor extractor = new RoleExtractor();
ParserRuleContext tree = parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(extractor, tree);
NodeRoleMap nodeRoles = extractor.getRoleMap();
return nodeRoles;
}
private Question parseQuestion(String questionPath) {
File questionFile = new File(questionPath);
_logger.info("Reading question file: \"" + questionPath + "\"...");
String questionText = readFile(questionFile);
_logger.info("OK\n");
QuestionCombinedParser parser = new QuestionCombinedParser(questionText,
_settings.getThrowOnParserError(), _settings.getThrowOnLexerError());
QuestionExtractor extractor = new QuestionExtractor();
try {
ParserRuleContext tree = parse(parser, questionPath);
_logger.info("\tPost-processing...");
extractor.processParseTree(tree);
_logger.info("OK\n");
}
catch (ParserBatfishException e) {
String error = "Error parsing question: \"" + questionPath + "\"";
throw new BatfishException(error, e);
}
catch (Exception e) {
String error = "Error post-processing parse tree of question file: \""
+ questionPath + "\"";
throw new BatfishException(error, e);
}
return extractor.getQuestion();
}
private Topology parseTopology(File topologyFilePath) {
_logger.info("*** PARSING TOPOLOGY ***\n");
resetTimer();
String topologyFileText = readFile(topologyFilePath);
BatfishCombinedParser<?, ?> parser = null;
TopologyExtractor extractor = null;
_logger.info("Parsing: \""
+ topologyFilePath.getAbsolutePath().toString() + "\"");
if (topologyFileText.startsWith("autostart")) {
parser = new GNS3TopologyCombinedParser(topologyFileText,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
extractor = new GNS3TopologyExtractor();
}
else if (topologyFileText.startsWith("CONFIGPARSER_TOPOLOGY")) {
parser = new BatfishTopologyCombinedParser(topologyFileText,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
extractor = new BatfishTopologyExtractor();
}
else if (topologyFileText.equals("")) {
throw new BatfishException("...ERROR: empty topology\n");
}
else {
_logger.fatal("...ERROR\n");
throw new BatfishException("Topology format error");
}
ParserRuleContext tree = parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(extractor, tree);
Topology topology = extractor.getTopology();
printElapsedTime();
return topology;
}
private Map<String, VendorConfiguration> parseVendorConfigurations(
Map<File, String> configurationData) {
_logger.info("\n*** PARSING VENDOR CONFIGURATION FILES ***\n");
resetTimer();
ExecutorService pool;
boolean shuffle;
if (_settings.getParseParallel()) {
int numConcurrentThreads = Runtime.getRuntime().availableProcessors();
pool = Executors.newFixedThreadPool(numConcurrentThreads);
shuffle = true;
}
else {
pool = Executors.newSingleThreadExecutor();
shuffle = false;
}
Map<String, VendorConfiguration> vendorConfigurations = new TreeMap<String, VendorConfiguration>();
List<ParseVendorConfigurationJob> jobs = new ArrayList<ParseVendorConfigurationJob>();
boolean processingError = false;
for (File currentFile : configurationData.keySet()) {
Warnings warnings = new Warnings(_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(), _settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = configurationData.get(currentFile);
ParseVendorConfigurationJob job = new ParseVendorConfigurationJob(
_settings, fileText, currentFile, warnings);
jobs.add(job);
}
if (shuffle) {
Collections.shuffle(jobs);
}
List<Future<ParseVendorConfigurationResult>> futures = new ArrayList<Future<ParseVendorConfigurationResult>>();
for (ParseVendorConfigurationJob job : jobs) {
Future<ParseVendorConfigurationResult> future = pool.submit(job);
futures.add(future);
}
// try {
// futures = pool.invokeAll(jobs);
// catch (InterruptedException e) {
// throw new BatfishException("Error invoking parse jobs", e);
while (!futures.isEmpty()) {
List<Future<ParseVendorConfigurationResult>> currentFutures = new ArrayList<Future<ParseVendorConfigurationResult>>();
currentFutures.addAll(futures);
for (Future<ParseVendorConfigurationResult> future : currentFutures) {
if (future.isDone()) {
futures.remove(future);
ParseVendorConfigurationResult result = null;
try {
result = future.get();
}
catch (InterruptedException | ExecutionException e) {
throw new BatfishException("Error executing parse job", e);
}
_logger.append(result.getHistory());
Throwable failureCause = result.getFailureCause();
if (failureCause != null) {
if (_settings.exitOnParseError()) {
throw new BatfishException("Failed parse job",
failureCause);
}
else {
processingError = true;
_logger.error(ExceptionUtils.getStackTrace(failureCause));
}
}
else {
VendorConfiguration vc = result.getVendorConfiguration();
if (vc != null) {
String hostname = vc.getHostname();
if (vendorConfigurations.containsKey(hostname)) {
throw new BatfishException("Duplicate hostname: "
+ hostname);
}
else {
vendorConfigurations.put(hostname, vc);
}
}
}
}
else {
continue;
}
}
if (!futures.isEmpty()) {
try {
Thread.sleep(JOB_POLLING_PERIOD_MS);
}
catch (InterruptedException e) {
throw new BatfishException("interrupted while sleeping", e);
}
}
}
pool.shutdown();
if (processingError) {
return null;
}
else {
printElapsedTime();
return vendorConfigurations;
}
}
private void populateConfigurationFactBins(
Collection<Configuration> configurations,
Map<String, StringBuilder> factBins) {
_logger
.info("\n*** EXTRACTING LOGICBLOX FACTS FROM CONFIGURATIONS ***\n");
resetTimer();
Set<Long> communities = new LinkedHashSet<Long>();
for (Configuration c : configurations) {
communities.addAll(c.getCommunities());
}
boolean pedanticAsError = _settings.getPedanticAsError();
boolean pedanticRecord = _settings.getPedanticRecord();
boolean redFlagAsError = _settings.getRedFlagAsError();
boolean redFlagRecord = _settings.getRedFlagRecord();
boolean unimplementedAsError = _settings.getUnimplementedAsError();
boolean unimplementedRecord = _settings.getUnimplementedRecord();
boolean processingError = false;
for (Configuration c : configurations) {
String hostname = c.getHostname();
_logger.debug("Extracting facts from: \"" + hostname + "\"");
Warnings warnings = new Warnings(pedanticAsError, pedanticRecord,
redFlagAsError, redFlagRecord, unimplementedAsError,
unimplementedRecord, false);
try {
ConfigurationFactExtractor cfe = new ConfigurationFactExtractor(c,
communities, factBins, warnings);
cfe.writeFacts();
_logger.debug("...OK\n");
}
catch (BatfishException e) {
_logger.fatal("...EXTRACTION ERROR\n");
_logger.fatal(ExceptionUtils.getStackTrace(e));
processingError = true;
if (_settings.exitOnParseError()) {
break;
}
else {
continue;
}
}
finally {
for (String warning : warnings.getRedFlagWarnings()) {
_logger.redflag(warning);
}
for (String warning : warnings.getUnimplementedWarnings()) {
_logger.unimplemented(warning);
}
for (String warning : warnings.getPedanticWarnings()) {
_logger.pedantic(warning);
}
}
}
if (processingError) {
throw new BatfishException(
"Failed to extract facts from vendor-indpendent configuration structures");
}
printElapsedTime();
}
private void postFacts(LogicBloxFrontend lbFrontend,
Map<String, StringBuilder> factBins) {
Map<String, StringBuilder> enabledFacts = new HashMap<String, StringBuilder>();
enabledFacts.putAll(factBins);
enabledFacts.keySet().removeAll(_settings.getDisabledFacts());
_logger.info("\n*** POSTING FACTS TO BLOXWEB SERVICES ***\n");
resetTimer();
_logger.info("Starting bloxweb services...");
lbFrontend.startLbWebServices();
_logger.info("OK\n");
_logger.info("Posting facts...");
try {
lbFrontend.postFacts(enabledFacts);
}
catch (ServiceClientException e) {
throw new BatfishException("Failed to post facts to bloxweb services",
e);
}
_logger.info("OK\n");
_logger.info("Stopping bloxweb services...");
lbFrontend.stopLbWebServices();
_logger.info("OK\n");
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void printAllPredicateSemantics(
Map<String, String> predicateSemantics) {
// Get predicate semantics from rules file
_logger.info("\n*** PRINTING PREDICATE SEMANTICS ***\n");
List<String> helpPredicates = getHelpPredicates(predicateSemantics);
for (String predicate : helpPredicates) {
printPredicateSemantics(predicate);
_logger.info("\n");
}
}
private void printElapsedTime() {
double seconds = getElapsedTime(_timerCount);
_logger.info("Time taken for this task: " + seconds + " seconds\n");
}
private void printPredicate(LogicBloxFrontend lbFrontend,
String predicateName) {
List<String> output;
printPredicateSemantics(predicateName);
String qualifiedName = _predicateInfo.getPredicateNames().get(
predicateName);
if (qualifiedName == null) { // predicate not found
_logger.error("ERROR: No information for predicate: " + predicateName
+ "\n");
return;
}
Relation relation = lbFrontend.queryPredicate(qualifiedName);
try {
output = lbFrontend.getPredicate(_predicateInfo, relation,
predicateName);
for (String match : output) {
_logger.output(match + "\n");
}
}
catch (QueryException q) {
_logger.fatal(q.getMessage() + "\n");
}
}
private void printPredicateCount(LogicBloxFrontend lbFrontend,
String predicateName) {
int numRows = lbFrontend.queryPredicate(predicateName).getColumns()
.get(0).size();
String output = "|" + predicateName + "| = " + numRows + "\n";
_logger.info(output);
}
public void printPredicateCounts(LogicBloxFrontend lbFrontend,
Set<String> predicateNames) {
// Print predicate(s) here
_logger.info("\n*** SUBMITTING QUERY(IES) ***\n");
resetTimer();
for (String predicateName : predicateNames) {
printPredicateCount(lbFrontend, predicateName);
// _logger.info("\n");
}
printElapsedTime();
}
public void printPredicates(LogicBloxFrontend lbFrontend,
Set<String> predicateNames) {
// Print predicate(s) here
_logger.info("\n*** SUBMITTING QUERY(IES) ***\n");
resetTimer();
String queryDumpDirStr = _settings.getQueryDumpDir();
if (queryDumpDirStr == null) {
for (String predicateName : predicateNames) {
printPredicate(lbFrontend, predicateName);
}
}
else {
Path queryDumpDir = Paths.get(queryDumpDirStr);
queryDumpDir.toFile().mkdirs();
for (String predicateName : predicateNames) {
String outputPath = queryDumpDir.resolve(predicateName).toString();
printPredicateToFile(lbFrontend, predicateName, outputPath);
}
}
printElapsedTime();
}
private void printPredicateSemantics(String predicateName) {
String semantics = _predicateInfo.getPredicateSemantics(predicateName);
if (semantics == null) {
semantics = "<missing>";
}
_logger.info("\n");
_logger.info("Predicate: " + predicateName + "\n");
_logger.info("Semantics: " + semantics + "\n");
}
private void printPredicateToFile(LogicBloxFrontend lbFrontend,
String predicateName, String outputPath) {
List<String> output;
printPredicateSemantics(predicateName);
StringBuilder sb = new StringBuilder();
String qualifiedName = _predicateInfo.getPredicateNames().get(
predicateName);
if (qualifiedName == null) { // predicate not found
_logger.error("ERROR: No information for predicate: " + predicateName
+ "\n");
return;
}
Relation relation = lbFrontend.queryPredicate(qualifiedName);
try {
output = lbFrontend.getPredicate(_predicateInfo, relation,
predicateName);
for (String match : output) {
sb.append(match + "\n");
}
}
catch (QueryException q) {
_logger.fatal(q.getMessage() + "\n");
}
String outputString = sb.toString();
writeFile(outputPath, outputString);
}
private void processTopology(File topologyFilePath,
Map<String, StringBuilder> factBins) {
Topology topology = null;
topology = parseTopology(topologyFilePath);
TopologyFactExtractor tfe = new TopologyFactExtractor(topology);
tfe.writeFacts(factBins);
}
private Map<File, String> readConfigurationFiles(String testRigPath) {
_logger.info("\n*** READING CONFIGURATION FILES ***\n");
resetTimer();
Map<File, String> configurationData = new TreeMap<File, String>();
File configsPath = Paths
.get(testRigPath, TESTRIG_CONFIGURATION_DIRECTORY).toFile();
File[] configFilePaths = configsPath.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
});
if (configFilePaths == null) {
throw new BatfishException("Error reading test rig configs directory");
}
for (File file : configFilePaths) {
_logger.debug("Reading: \"" + file.toString() + "\"\n");
String fileText = readFile(file.getAbsoluteFile()) + "\n";
configurationData.put(file, fileText);
}
printElapsedTime();
return configurationData;
}
public String readFile(File file) {
String text = null;
try {
text = FileUtils.readFileToString(file);
}
catch (IOException e) {
throw new BatfishException("Failed to read file: " + file.toString(),
e);
}
return text;
}
private void resetTimer() {
_timerCount = System.currentTimeMillis();
}
private File retrieveLogicDir() {
File logicDirFile = null;
final String locatorFilename = LogicResourceLocator.class.getSimpleName()
+ ".class";
URL logicSourceURL = LogicResourceLocator.class.getProtectionDomain()
.getCodeSource().getLocation();
String logicSourceString = logicSourceURL.toString();
UrlZipExplorer zip = null;
StringFilter lbFilter = new StringFilter() {
@Override
public boolean accept(String filename) {
return filename.endsWith(".lbb") || filename.endsWith(".lbp")
|| filename.endsWith(".semantics")
|| filename.endsWith(locatorFilename)
|| filename.endsWith(PREDICATE_INFO_FILENAME);
}
};
if (logicSourceString.startsWith("onejar:")) {
FileVisitor<Path> visitor = null;
try {
zip = new UrlZipExplorer(logicSourceURL);
Path destinationDir = Files.createTempDirectory("lbtmpproject");
File destinationDirAsFile = destinationDir.toFile();
zip.extractFiles(lbFilter, destinationDirAsFile);
visitor = new SimpleFileVisitor<Path>() {
private String _projectDirectory;
@Override
public String toString() {
return _projectDirectory;
}
@Override
public FileVisitResult visitFile(Path aFile,
BasicFileAttributes aAttrs) throws IOException {
if (aFile.endsWith(locatorFilename)) {
_projectDirectory = aFile.getParent().toString();
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(destinationDir, visitor);
_tmpLogicDir = destinationDirAsFile;
}
catch (IOException e) {
throw new BatfishException(
"Failed to retrieve logic dir from onejar archive", e);
}
String fileString = visitor.toString();
return new File(fileString);
}
else {
String logicPackageResourceName = LogicResourceLocator.class
.getPackage().getName().replace('.', SEPARATOR.charAt(0));
try {
logicDirFile = new File(LogicResourceLocator.class.getClassLoader()
.getResource(logicPackageResourceName).toURI());
}
catch (URISyntaxException e) {
throw new BatfishException("Failed to resolve logic directory", e);
}
return logicDirFile;
}
}
private void revert(LogicBloxFrontend lbFrontend) {
_logger.info("\n*** REVERTING WORKSPACE ***\n");
String workspaceName = new File(_settings.getTestRigPath()).getName();
String branchName = _settings.getBranchName();
_logger.debug("Reverting workspace: \"" + workspaceName
+ "\" to branch: \"" + branchName + "\n");
String errorResult = lbFrontend.revertDatabase(branchName);
if (errorResult != null) {
throw new BatfishException("Failed to revert database: " + errorResult);
}
}
public void run() {
if (_settings.getAnswer()) {
String questionPath = _settings.getQuestionPath();
answer(questionPath);
return;
}
if (_settings.getBuildPredicateInfo()) {
buildPredicateInfo();
return;
}
if (_settings.getHistogram()) {
histogram(_settings.getTestRigPath());
return;
}
if (_settings.getGenerateOspfTopologyPath() != null) {
generateOspfConfigs(_settings.getGenerateOspfTopologyPath(),
_settings.getSerializeIndependentPath());
return;
}
if (_settings.getFlatten()) {
String flattenSource = _settings.getTestRigPath();
String flattenDestination = _settings.getFlattenDestination();
flatten(flattenSource, flattenDestination);
return;
}
if (_settings.getGenerateStubs()) {
String configPath = _settings.getSerializeIndependentPath();
String inputRole = _settings.getGenerateStubsInputRole();
String interfaceDescriptionRegex = _settings
.getGenerateStubsInterfaceDescriptionRegex();
int stubAs = _settings.getGenerateStubsRemoteAs();
generateStubs(inputRole, stubAs, interfaceDescriptionRegex, configPath);
return;
}
if (_settings.getZ3()) {
Map<String, Configuration> configurations = deserializeConfigurations(_settings
.getSerializeIndependentPath());
genZ3(configurations);
return;
}
if (_settings.getAnonymize()) {
anonymizeConfigurations();
return;
}
if (_settings.getInterfaceFailureInconsistencyReachableQuery()) {
genReachableQueries();
return;
}
if (_settings.getRoleReachabilityQuery()) {
genRoleReachabilityQueries();
return;
}
if (_settings.getRoleTransitQuery()) {
genRoleTransitQueries();
return;
}
if (_settings.getInterfaceFailureInconsistencyBlackHoleQuery()) {
genBlackHoleQueries();
return;
}
if (_settings.getGenerateMultipathInconsistencyQuery()) {
genMultipathQueries();
return;
}
if (_settings.getSerializeVendor()) {
String testRigPath = _settings.getTestRigPath();
String outputPath = _settings.getSerializeVendorPath();
serializeVendorConfigs(testRigPath, outputPath);
return;
}
if (_settings.dumpInterfaceDescriptions()) {
String testRigPath = _settings.getTestRigPath();
String outputPath = _settings.getDumpInterfaceDescriptionsPath();
dumpInterfaceDescriptions(testRigPath, outputPath);
return;
}
if (_settings.getSerializeIndependent()) {
String inputPath = _settings.getSerializeVendorPath();
String outputPath = _settings.getSerializeIndependentPath();
serializeIndependentConfigs(inputPath, outputPath);
return;
}
if (_settings.getConcretize()) {
concretize();
return;
}
if (_settings.getQuery() || _settings.getPrintSemantics()
|| _settings.getDataPlane()) {
Map<String, String> logicFiles = getSemanticsFiles();
_predicateInfo = getPredicateInfo(logicFiles);
// Print predicate semantics and quit if requested
if (_settings.getPrintSemantics()) {
printAllPredicateSemantics(_predicateInfo.getPredicateSemantics());
return;
}
}
Map<String, StringBuilder> cpFactBins = null;
if (_settings.getFacts() || _settings.getDumpControlPlaneFacts()) {
cpFactBins = new LinkedHashMap<String, StringBuilder>();
initControlPlaneFactBins(cpFactBins);
Map<String, Configuration> configurations = deserializeConfigurations(_settings
.getSerializeIndependentPath());
writeTopologyFacts(_settings.getTestRigPath(), configurations,
cpFactBins);
writeConfigurationFacts(configurations, cpFactBins);
String flowSinkPath = _settings.getFlowSinkPath();
if (flowSinkPath != null) {
FlowSinkSet flowSinks = (FlowSinkSet) deserializeObject(new File(
flowSinkPath));
writeFlowSinkFacts(flowSinks, cpFactBins);
}
if (_settings.getDumpControlPlaneFacts()) {
dumpFacts(cpFactBins);
}
if (!(_settings.getFacts() || _settings.createWorkspace())) {
return;
}
}
// Start frontend
LogicBloxFrontend lbFrontend = null;
if (_settings.createWorkspace() || _settings.getFacts()
|| _settings.getQuery() || _settings.getDataPlane()
|| _settings.revert()) {
lbFrontend = connect();
}
if (_settings.revert()) {
revert(lbFrontend);
return;
}
// Create new workspace (will overwrite existing) if requested
if (_settings.createWorkspace()) {
addProject(lbFrontend);
String lbHostnamePath = _settings.getJobLogicBloxHostnamePath();
String lbHostname = _settings.getServiceLogicBloxHostname();
if (lbHostnamePath != null && lbHostname != null) {
writeFile(lbHostnamePath, lbHostname);
}
if (!_settings.getFacts()) {
return;
}
}
// Post facts if requested
if (_settings.getFacts()) {
addStaticFacts(lbFrontend, BASIC_FACTS_BLOCKNAME);
postFacts(lbFrontend, cpFactBins);
return;
}
if (_settings.getQuery()) {
lbFrontend.initEntityTable();
Map<String, String> allPredicateNames = _predicateInfo
.getPredicateNames();
Set<String> predicateNames = new TreeSet<String>();
if (_settings.getQueryAll()) {
predicateNames.addAll(allPredicateNames.keySet());
}
else {
predicateNames.addAll(_settings.getPredicates());
}
if (_settings.getCountsOnly()) {
printPredicateCounts(lbFrontend, predicateNames);
}
else {
printPredicates(lbFrontend, predicateNames);
}
return;
}
if (_settings.getDataPlane()) {
computeDataPlane(lbFrontend);
return;
}
Map<String, StringBuilder> trafficFactBins = null;
if (_settings.getPostFlows()) {
trafficFactBins = new LinkedHashMap<String, StringBuilder>();
Path dumpDir = Paths.get(_settings.getTrafficFactDumpDir());
for (String predicate : Facts.TRAFFIC_FACT_COLUMN_HEADERS.keySet()) {
File factFile = dumpDir.resolve(predicate).toFile();
String contents = readFile(factFile);
StringBuilder sb = new StringBuilder();
trafficFactBins.put(predicate, sb);
sb.append(contents);
}
lbFrontend = connect();
postFacts(lbFrontend, trafficFactBins);
return;
}
if (_settings.getFlows() || _settings.getDumpTrafficFacts()) {
trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
writeTrafficFacts(trafficFactBins);
if (_settings.getDumpTrafficFacts()) {
dumpFacts(trafficFactBins);
}
if (_settings.getFlows()) {
lbFrontend = connect();
postFacts(lbFrontend, trafficFactBins);
return;
}
}
throw new BatfishException(
"No task performed! Run with -help flag to see usage");
}
private void serializeIndependentConfigs(
Map<String, Configuration> configurations, String outputPath) {
_logger
.info("\n*** SERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n");
resetTimer();
new File(outputPath).mkdirs();
for (String name : configurations.keySet()) {
Configuration c = configurations.get(name);
Path currentOutputPath = Paths.get(outputPath, name);
_logger.info("Serializing: \"" + name + "\" ==> \""
+ currentOutputPath.toString() + "\"");
serializeObject(c, currentOutputPath.toFile());
_logger.debug(" ...OK\n");
}
printElapsedTime();
}
private void serializeIndependentConfigs(String vendorConfigPath,
String outputPath) {
Map<String, Configuration> configurations = getConfigurations(vendorConfigPath);
serializeIndependentConfigs(configurations, outputPath);
}
private void serializeObject(Object object, File outputFile) {
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = new FileOutputStream(outputFile);
if (_settings.getSerializeToText()) {
XStream xstream = new XStream(new DomDriver("UTF-8"));
oos = xstream.createObjectOutputStream(fos);
}
else {
oos = new ObjectOutputStream(fos);
}
oos.writeObject(object);
oos.close();
}
catch (IOException e) {
throw new BatfishException(
"Failed to serialize object to output file: "
+ outputFile.toString(), e);
}
}
private void serializeVendorConfigs(String testRigPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(configurationData);
if (vendorConfigurations == null) {
throw new BatfishException("Exiting due to parser errors\n");
}
String nodeRolesPath = _settings.getNodeRolesPath();
if (nodeRolesPath != null) {
NodeRoleMap nodeRoles = parseNodeRoles(testRigPath);
for (Entry<String, RoleSet> nodeRolesEntry : nodeRoles.entrySet()) {
String hostname = nodeRolesEntry.getKey();
VendorConfiguration config = vendorConfigurations.get(hostname);
if (config == null) {
throw new BatfishException(
"role set assigned to non-existent node: \"" + hostname
+ "\"");
}
RoleSet roles = nodeRolesEntry.getValue();
config.setRoles(roles);
}
_logger.info("Serializing node-roles mappings: \"" + nodeRolesPath
+ "\"...");
serializeObject(nodeRoles, new File(nodeRolesPath));
_logger.info("OK\n");
}
_logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
new File(outputPath).mkdirs();
for (String name : vendorConfigurations.keySet()) {
VendorConfiguration vc = vendorConfigurations.get(name);
Path currentOutputPath = Paths.get(outputPath, name);
_logger.debug("Serializing: \"" + name + "\" ==> \""
+ currentOutputPath.toString() + "\"...");
serializeObject(vc, currentOutputPath.toFile());
_logger.debug("OK\n");
}
printElapsedTime();
}
private Synthesizer synthesizeDataPlane(
Map<String, Configuration> configurations, Context ctx)
throws Z3Exception {
_logger.info("\n*** GENERATING Z3 LOGIC ***\n");
resetTimer();
String dataPlaneDir = _settings.getDataPlaneDir();
if (dataPlaneDir == null) {
throw new BatfishException("Data plane dir not set");
}
Path flowSinkSetPath = Paths.get(dataPlaneDir, FLOW_SINKS_FILENAME);
Path fibsPath = Paths.get(dataPlaneDir, FIBS_FILENAME);
Path prFibsPath = Paths.get(dataPlaneDir,
FIBS_POLICY_ROUTE_NEXT_HOP_FILENAME);
Path edgesPath = Paths.get(dataPlaneDir, EDGES_FILENAME);
_logger.info("Deserializing flow sink interface set: \""
+ flowSinkSetPath.toString() + "\"...");
FlowSinkSet flowSinks = (FlowSinkSet) deserializeObject(flowSinkSetPath
.toFile());
_logger.info("OK\n");
_logger.info("Deserializing destination route fibs: \""
+ fibsPath.toString() + "\"...");
FibMap fibs = (FibMap) deserializeObject(fibsPath.toFile());
_logger.info("OK\n");
_logger.info("Deserializing policy route fibs: \""
+ prFibsPath.toString() + "\"...");
PolicyRouteFibNodeMap prFibs = (PolicyRouteFibNodeMap) deserializeObject(prFibsPath
.toFile());
_logger.info("OK\n");
_logger.info("Deserializing toplogy edges: \"" + edgesPath.toString()
+ "\"...");
EdgeSet topologyEdges = (EdgeSet) deserializeObject(edgesPath.toFile());
_logger.info("OK\n");
_logger.info("Synthesizing Z3 logic...");
Synthesizer s = new Synthesizer(configurations, fibs, prFibs,
topologyEdges, _settings.getSimplify(), flowSinks);
List<String> warnings = s.getWarnings();
int numWarnings = warnings.size();
if (numWarnings == 0) {
_logger.info("OK\n");
}
else {
for (String warning : warnings) {
_logger.warn(warning);
}
}
printElapsedTime();
return s;
}
public void writeConfigurationFacts(
Map<String, Configuration> configurations,
Map<String, StringBuilder> factBins) {
populateConfigurationFactBins(configurations.values(), factBins);
}
private void writeFile(String outputPath, String output) {
File outputFile = new File(outputPath);
try {
FileUtils.write(outputFile, output);
}
catch (IOException e) {
throw new BatfishException("Failed to write file: " + outputPath, e);
}
}
private void writeFlowSinkFacts(FlowSinkSet flowSinks,
Map<String, StringBuilder> cpFactBins) {
StringBuilder sb = cpFactBins.get("SetFlowSinkInterface");
for (FlowSinkInterface f : flowSinks) {
String node = f.getNode();
String iface = f.getInterface();
sb.append(node + "|" + iface + "\n");
}
}
public void writeTopologyFacts(String testRigPath,
Map<String, Configuration> configurations,
Map<String, StringBuilder> factBins) {
Path topologyFilePath = Paths.get(testRigPath, TOPOLOGY_FILENAME);
// Get generated facts from topology file
if (Files.exists(topologyFilePath)) {
processTopology(topologyFilePath.toFile(), factBins);
}
else {
// tell logicblox to guess adjacencies based on interface
// subnetworks
_logger
.info("*** (GUESSING TOPOLOGY IN ABSENCE OF EXPLICIT FILE) ***\n");
StringBuilder wGuessTopology = factBins.get("GuessTopology");
wGuessTopology.append("1\n");
}
}
private void writeTrafficFacts(Map<String, StringBuilder> factBins) {
StringBuilder wSetFlowOriginate = factBins.get("SetFlowOriginate");
RoleNodeMap roleNodes = null;
if (_settings.getRoleHeaders()) {
String nodeRolesPath = _settings.getNodeRolesPath();
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
roleNodes = nodeRoles.toRoleNodeMap();
}
parseFlowsFromConstraints(wSetFlowOriginate, roleNodes);
if (_settings.duplicateRoleFlows()) {
StringBuilder wDuplicateRoleFlows = factBins.get("DuplicateRoleFlows");
wDuplicateRoleFlows.append("1\n");
}
}
} |
package net.hive.controller;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
class FileWorker {
String readUsingFiles(String fileName) throws IOException {
Path path = Paths.get(fileName);
Scanner scanner = new Scanner(path);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.equals("jdbc:firebirdsql:192.168.99.239/3050:")){
System.out.println(line);
}
return line;
}
return fileName;
}
} |
package nu.validator.client;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.mortbay.util.ajax.JSON;
import org.relaxng.datatype.DatatypeException;
import com.thaiopensource.relaxng.exceptions.BadAttributeValueException;
import org.whattf.datatype.Html5DatatypeException;
import nu.validator.validation.SimpleDocumentValidator;
public class TestRunner implements ErrorHandler {
private boolean inError = false;
private boolean emitMessages = false;
private boolean exceptionIsWarning = false;
private boolean expectingError = false;
private Exception exception = null;
private SimpleDocumentValidator validator;
private PrintWriter err;
private PrintWriter out;
private String schema = "http://s.validator.nu/html5-all.rnc";
private boolean failed = false;
private static File messagesFile;
private static String[] ignoreList = null;
private static boolean writeMessages;
private static boolean verbose;
private String baseDir = null;
private Map<String, String> expectedMessages;
private Map<String, String> reportedMessages;
public TestRunner() throws IOException {
reportedMessages = new LinkedHashMap<String, String>();
validator = new SimpleDocumentValidator();
try {
this.err = new PrintWriter(new OutputStreamWriter(System.err,
"UTF-8"));
this.out = new PrintWriter(new OutputStreamWriter(System.out,
"UTF-8"));
} catch (Exception e) {
// If this happens, the JDK is too broken anyway
throw new RuntimeException(e);
}
}
private void checkHtmlFile(File file) throws IOException, SAXException {
if (!file.exists()) {
if (verbose) {
out.println(String.format("\"%s\": warning: File not found.",
file.toURI().toURL().toString()));
out.flush();
}
return;
}
if (verbose) {
out.println(file);
out.flush();
}
if (isHtml(file)) {
validator.checkHtmlFile(file, true);
} else if (isXhtml(file)) {
validator.checkXmlFile(file);
} else {
if (verbose) {
out.println(String.format(
"\"%s\": warning: File was not checked."
+ " Files must have a .html, .xhtml, .htm,"
+ " or .xht extension.",
file.toURI().toURL().toString()));
out.flush();
}
}
}
private boolean isXhtml(File file) {
String name = file.getName();
return name.endsWith(".xhtml") || name.endsWith(".xht");
}
private boolean isHtml(File file) {
String name = file.getName();
return name.endsWith(".html") || name.endsWith(".htm");
}
private boolean isCheckableFile(File file) {
return file.isFile() && (isHtml(file) || isXhtml(file));
}
private void recurseDirectory(File directory) throws SAXException,
IOException {
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
recurseDirectory(file);
} else {
checkHtmlFile(file);
}
}
}
private void checkFiles(List<File> files) {
for (File file : files) {
reset();
emitMessages = true;
try {
if (file.isDirectory()) {
recurseDirectory(file);
} else {
checkHtmlFile(file);
}
} catch (IOException e) {
} catch (SAXException e) {
}
if (inError) {
failed = true;
}
}
}
private boolean messageMatches(String testFilename) {
// p{C} = Other = Control+Format+Private_Use+Surrogate+Unassigned
// http://www.regular-expressions.info/unicode.html#category
// http://www.unicode.org/reports/tr18/#General_Category_Property
String messageReported = exception.getMessage().replaceAll("\\p{C}",
"?");
String messageExpected = expectedMessages.get(testFilename).replaceAll(
"\\p{C}", "?");
return messageReported.equals(messageExpected);
}
private void checkInvalidFiles(List<File> files) throws IOException,
SAXException {
String testFilename;
expectingError = true;
for (File file : files) {
reset();
try {
if (file.isDirectory()) {
recurseDirectory(file);
} else {
checkHtmlFile(file);
}
} catch (IOException e) {
} catch (SAXException e) {
}
if (exception != null) {
testFilename = file.getAbsolutePath().substring(
baseDir.length() + 1);
if (ignoreList != null) {
for (String substring : ignoreList) {
if (testFilename.contains(substring)) {
if (verbose) {
out.println(String.format(
"\"%s\": warning: File ignored.",
file.toURI().toURL().toString()));
out.flush();
}
return;
}
}
}
if (writeMessages) {
reportedMessages.put(testFilename, exception.getMessage());
} else if (expectedMessages != null
&& expectedMessages.get(testFilename) == null) {
try {
err.println(String.format(
"\"%s\": warning: No expected message in"
+ " messages file.",
file.toURI().toURL().toString()));
err.flush();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} else if (expectedMessages != null
&& !messageMatches(testFilename)) {
try {
err.println(String.format(
"\"%s\": error: Expected \"%s\""
+ " but instead encountered \"%s\".",
file.toURI().toURL().toString(),
expectedMessages.get(testFilename),
exception.getMessage()));
err.flush();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
if (!inError) {
failed = true;
try {
err.println(String.format(
"\"%s\": error: Expected an error but did not"
+ " encounter any.",
file.toURI().toURL().toString()));
err.flush();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
}
private void checkHasWarningFiles(List<File> files) {
String testFilename;
expectingError = false;
for (File file : files) {
reset();
try {
if (file.isDirectory()) {
recurseDirectory(file);
} else {
checkHtmlFile(file);
}
} catch (IOException e) {
} catch (SAXException e) {
}
if (exception != null) {
testFilename = file.getAbsolutePath().substring(
baseDir.length() + 1);
if (writeMessages) {
reportedMessages.put(testFilename, exception.getMessage());
} else if (expectedMessages != null
&& expectedMessages.get(testFilename) == null) {
try {
err.println(String.format(
"\"%s\": warning: No expected message in"
+ " messages file.",
file.toURI().toURL().toString()));
err.flush();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} else if (expectedMessages != null
&& !messageMatches(testFilename)) {
try {
err.println(String.format(
"\"%s\": error: Expected \"%s\""
+ " but instead encountered \"%s\".",
file.toURI().toURL().toString(),
expectedMessages.get(testFilename),
exception.getMessage()));
err.flush();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
if (inError) {
failed = true;
try {
err.println(String.format(
"\"%s\": error: Expected a warning but encountered"
+ " an error first.",
file.toURI().toURL().toString()));
err.flush();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} else if (!exceptionIsWarning) {
try {
err.println(String.format(
"\"%s\": error: Expected a warning but did not"
+ " encounter any.",
file.toURI().toURL().toString()));
err.flush();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
if (inError) {
failed = true;
try {
err.println(String.format(
"\"%s\": error: Expected a warning only but"
+ " encountered at least one error.",
file.toURI().toURL().toString()));
err.flush();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
}
private enum State {
EXPECTING_INVALID_FILES, EXPECTING_VALID_FILES, EXPECTING_ANYTHING
}
private void checkTestDirectoryAgainstSchema(File directory,
String schemaUrl) throws SAXException, Exception {
validator.setUpMainSchema(schemaUrl, this);
checkTestFiles(directory, State.EXPECTING_ANYTHING);
}
private void checkTestFiles(File directory, State state)
throws SAXException, IOException {
File[] files = directory.listFiles();
List<File> validFiles = new ArrayList<File>();
List<File> invalidFiles = new ArrayList<File>();
List<File> hasWarningFiles = new ArrayList<File>();
if (files == null) {
if (verbose) {
try {
out.println(String.format(
"\"%s\": warning: No files found in directory.",
directory.toURI().toURL().toString()));
out.flush();
} catch (MalformedURLException mue) {
throw new RuntimeException(mue);
}
}
return;
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
if (state != State.EXPECTING_ANYTHING) {
checkTestFiles(file, state);
} else if ("invalid".equals(file.getName())) {
checkTestFiles(file, State.EXPECTING_INVALID_FILES);
} else if ("valid".equals(file.getName())) {
checkTestFiles(file, State.EXPECTING_VALID_FILES);
} else {
checkTestFiles(file, State.EXPECTING_ANYTHING);
}
} else if (isCheckableFile(file)) {
if (state == State.EXPECTING_INVALID_FILES) {
invalidFiles.add(file);
} else if (state == State.EXPECTING_VALID_FILES) {
validFiles.add(file);
} else if (file.getPath().indexOf("novalid") > 0) {
invalidFiles.add(file);
} else if (file.getPath().indexOf("haswarn") > 0) {
hasWarningFiles.add(file);
} else {
validFiles.add(file);
}
}
}
if (validFiles.size() > 0) {
validator.setUpValidatorAndParsers(this, false, false);
checkFiles(validFiles);
}
if (invalidFiles.size() > 0) {
validator.setUpValidatorAndParsers(this, false, false);
checkInvalidFiles(invalidFiles);
}
if (hasWarningFiles.size() > 0) {
validator.setUpValidatorAndParsers(this, false, false);
checkHasWarningFiles(hasWarningFiles);
}
if (writeMessages) {
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(messagesFile), "utf-8");
BufferedWriter bw = new BufferedWriter(out);
bw.write(JSON.toString(reportedMessages));
bw.close();
}
}
public boolean runTestSuite() throws SAXException, Exception {
if (messagesFile != null) {
baseDir = messagesFile.getAbsoluteFile().getParent();
FileInputStream fis = new FileInputStream(messagesFile);
InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
expectedMessages = (HashMap<String, String>) JSON.parse(reader);
} else {
baseDir = System.getProperty("user.dir");
}
for (File directory : new File(baseDir).listFiles()) {
if (directory.isDirectory()) {
if (directory.getName().contains("rdfalite")) {
checkTestDirectoryAgainstSchema(directory,
"http://s.validator.nu/html5-rdfalite.rnc");
} else if (directory.getName().contains("xhtml")) {
checkTestDirectoryAgainstSchema(directory,
"http://s.validator.nu/xhtml5-all.rnc");
} else {
checkTestDirectoryAgainstSchema(directory, schema);
}
}
}
if (verbose) {
if (failed) {
out.println("Failure!");
out.flush();
} else {
out.println("Success!");
out.flush();
}
}
return !failed;
}
private void emitMessage(SAXParseException e, String messageType) {
String systemId = e.getSystemId();
err.write((systemId == null) ? "" : '\"' + systemId + '\"');
err.write(":");
err.write(Integer.toString(e.getLineNumber()));
err.write(":");
err.write(Integer.toString(e.getColumnNumber()));
err.write(": ");
err.write(messageType);
err.write(": ");
err.write(e.getMessage());
err.write("\n");
err.flush();
System.exit(1);
}
public void warning(SAXParseException e) throws SAXException {
if (emitMessages) {
emitMessage(e, "warning");
} else if (exception == null && !expectingError) {
exception = e;
exceptionIsWarning = true;
}
}
public void error(SAXParseException e) throws SAXException {
if (emitMessages) {
emitMessage(e, "error");
} else if (exception == null) {
exception = e;
if (e instanceof BadAttributeValueException) {
BadAttributeValueException ex = (BadAttributeValueException) e;
Map<String, DatatypeException> datatypeErrors = ex.getExceptions();
for (Map.Entry<String, DatatypeException> entry : datatypeErrors.entrySet()) {
DatatypeException dex = entry.getValue();
if (dex instanceof Html5DatatypeException) {
Html5DatatypeException ex5 = (Html5DatatypeException) dex;
if (ex5.isWarning()) {
exceptionIsWarning = true;
return;
}
}
}
}
}
inError = true;
}
public void fatalError(SAXParseException e) throws SAXException {
inError = true;
if (emitMessages) {
emitMessage(e, "fatal error");
return;
} else if (exception == null) {
exception = e;
}
}
public void reset() {
exception = null;
inError = false;
emitMessages = false;
exceptionIsWarning = false;
}
public static void main(String[] args) throws SAXException, Exception {
if (args.length < 1) {
usage();
System.exit(0);
}
verbose = false;
String messagesFilename = null;
System.setProperty("org.whattf.datatype.warn", "true");
for (int i = 0; i < args.length; i++) {
if ("--verbose".equals(args[i])) {
verbose = true;
} else if ("--errors-only".equals(args[i])) {
System.setProperty("org.whattf.datatype.warn", "false");
} else if ("--write-messages".equals(args[i])) {
writeMessages = true;
} else if (args[i].startsWith("--ignore=")) {
ignoreList = args[i].substring(9, args[i].length()).split(",");
} else if (args[i].startsWith("
System.out.println(String.format(
"\nError: There is no option \"%s\".", args[i]));
usage();
System.exit(1);
} else {
if (args[i].endsWith(".json")) {
messagesFilename = args[i];
} else {
System.out.println("\nError: Expected the name of a messages"
+ " file with a .json extension.");
usage();
System.exit(1);
}
}
}
if (messagesFilename != null) {
messagesFile = new File(messagesFilename);
if (!messagesFile.exists()) {
System.out.println("\nError: \"" + messagesFilename
+ "\" file not found.");
System.exit(1);
} else if (!messagesFile.isFile()) {
System.out.println("\nError: \"" + messagesFilename
+ "\" is not a file.");
System.exit(1);
}
} else if (writeMessages) {
System.out.println("\nError: Expected the name of a messages"
+ " file with a .json extension.");
usage();
System.exit(1);
}
TestRunner tr = new TestRunner();
if (tr.runTestSuite()) {
System.exit(0);
} else {
System.exit(1);
}
}
private static void usage() {
System.out.println("\nUsage:");
System.out.println("\n java nu.validator.client.TestRunner [--errors-only] [--write-messages]");
System.out.println(" [--verbose] [MESSAGES.json]");
System.out.println("\n...where the MESSAGES.json file contains name/value pairs in which the name is");
System.out.println("a pathname of a document to check and the value is the first error message or");
System.out.println("warning message the validator is expected to report when checking that document.");
System.out.println("Use the --write-messages option to create the file.");
}
} |
package com.axelor.db;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import org.hibernate.MultiTenancyStrategy;
import org.hibernate.cache.infinispan.InfinispanRegionFactory;
import org.hibernate.cache.jcache.JCacheRegionFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.hikaricp.internal.HikariCPConnectionProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axelor.app.AppSettings;
import com.axelor.auth.AuditInterceptor;
import com.axelor.common.ResourceUtils;
import com.axelor.common.StringUtils;
import com.axelor.db.hibernate.naming.ImplicitNamingStrategyImpl;
import com.axelor.db.hibernate.naming.PhysicalNamingStrategyImpl;
import com.axelor.db.internal.DBHelper;
import com.axelor.db.search.SearchMappingFactory;
import com.axelor.db.search.SearchModule;
import com.axelor.db.tenants.TenantConnectionProvider;
import com.axelor.db.tenants.TenantModule;
import com.axelor.db.tenants.TenantResolver;
import com.google.inject.AbstractModule;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.jpa.JpaPersistModule;
/**
* A Guice module to configure JPA.
*
* This module takes care of initializing JPA and registers an Hibernate custom
* scanner that automatically scans all the classpath entries for Entity
* classes.
*
*/
public class JpaModule extends AbstractModule {
private static final String INFINISPAN_CONFIG = "infinispan.xml";
private static final String INFINISPAN_CONFIG_FALLBACK = "infinispan-fallback.xml";
private static Logger log = LoggerFactory.getLogger(JpaModule.class);
private String jpaUnit;
private boolean autoscan;
private boolean autostart;
private Properties properties;
static {
JpaScanner.exclude("com.axelor.test.db");
JpaScanner.exclude("com.axelor.web.db");
}
/**
* Create new instance of the {@link JpaModule} with the given persistence
* unit name.
*
* If <i>autoscan</i> is true then a custom Hibernate scanner will be used
* to scan all the classpath entries for Entity classes.
*
* If <i>autostart</i> is true then the {@link PersistService} will be
* started automatically.
*
* @param jpaUnit
* the persistence unit name
* @param autoscan
* whether to enable autoscan
* @param autostart
* whether to automatically start persistence service
*/
public JpaModule(String jpaUnit, boolean autoscan, boolean autostart) {
this.jpaUnit = jpaUnit;
this.autoscan = autoscan;
this.autostart = autostart;
}
/**
* Create a new instance of the {@link JpaModule} with the given persistence
* unit name with <i>autoscan</i> and <i>autostart</i> enabled.
*
* @param jpaUnit
* the persistence unit name
*/
public JpaModule(String jpaUnit) {
this(jpaUnit, true, true);
}
public JpaModule scan(String pkg) {
JpaScanner.include(pkg);
return this;
}
/**
* Configures the JPA persistence provider with a set of properties.
*
* @param properties
* A set of name value pairs that configure a JPA persistence
* provider as per the specification.
* @return this instance itself
*/
public JpaModule properties(final Properties properties) {
this.properties = properties;
return this;
}
@Override
protected void configure() {
log.debug("Configuring database...");
final AppSettings settings = AppSettings.get();
final Properties properties = new Properties();
if (this.properties != null) {
properties.putAll(this.properties);
}
if (this.autoscan) {
properties.put(Environment.SCANNER, JpaScanner.class.getName());
}
properties.put(Environment.INTERCEPTOR, AuditInterceptor.class.getName());
properties.put(Environment.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
properties.put(Environment.IMPLICIT_NAMING_STRATEGY, ImplicitNamingStrategyImpl.class.getName());
properties.put(Environment.PHYSICAL_NAMING_STRATEGY, PhysicalNamingStrategyImpl.class.getName());
properties.put(Environment.AUTOCOMMIT, "false");
properties.put(Environment.CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT, "true");
properties.put(Environment.MAX_FETCH_DEPTH, "3");
// Use HikariCP as default pool provider
properties.put(Environment.CONNECTION_PROVIDER, HikariCPConnectionProvider.class.getName());
properties.put("hibernate.hikari.minimumIdle", "10");
properties.put("hibernate.hikari.maximumPoolSize", "200");
properties.put("hibernate.hikari.idleTimeout", "30000");
// update properties with all hibernate.* settings from app configuration
settings.getProperties().stringPropertyNames().stream()
.filter(n -> n.startsWith("hibernate."))
.forEach(n -> properties.put(n, settings.get(n)));
configureCache(settings, properties);
configureMultiTenancy(settings, properties);
configureSearch(settings, properties);
try {
configureConnection(settings, properties);
} catch (Exception e) {
}
install(new SearchModule());
install(new TenantModule());
install(new JpaPersistModule(jpaUnit).properties(properties));
if (this.autostart) {
bind(Initializer.class).asEagerSingleton();
}
bind(JPA.class).asEagerSingleton();
}
private void configureConnection(final AppSettings settings, final Properties properties) {
if (DBHelper.isDataSourceUsed()) {
properties.put(Environment.DATASOURCE, DBHelper.getDataSourceName());
return;
}
final Map<String, String> keys = new HashMap<>();
final String unit = jpaUnit.replaceAll("(PU|Unit)$", "").replaceAll("^persistence$", "default");
keys.put("db.%s.ddl", Environment.HBM2DDL_AUTO);
keys.put("db.%s.driver", Environment.JPA_JDBC_DRIVER);
keys.put("db.%s.url", Environment.JPA_JDBC_URL);
keys.put("db.%s.user", Environment.JPA_JDBC_USER);
keys.put("db.%s.password", Environment.JPA_JDBC_PASSWORD);
for (String key : keys.keySet()) {
String name = keys.get(key);
String value = settings.get(String.format(key, unit));
if (!StringUtils.isBlank(value)) {
properties.put(name, value.trim());
}
}
}
private void configureCache(final AppSettings settings, final Properties properties) {
if (!DBHelper.isCacheEnabled()) {
return;
}
properties.put(Environment.USE_SECOND_LEVEL_CACHE, "true");
properties.put(Environment.USE_QUERY_CACHE, "true");
final String jcacheProvider = settings.get(JCacheRegionFactory.PROVIDER);
final String jcacheConfig = settings.get(JCacheRegionFactory.CONFIG_URI);
if (jcacheProvider != null) {
// use jcache
properties.put(Environment.CACHE_REGION_FACTORY, JCacheRegionFactory.class.getName());
properties.put(JCacheRegionFactory.PROVIDER, jcacheProvider);
properties.put(JCacheRegionFactory.CONFIG_URI, jcacheConfig);
} else {
// use infinispan
properties.put(Environment.CACHE_REGION_FACTORY, InfinispanRegionFactory.class.getName());
String infinispanConfig = settings.get(InfinispanRegionFactory.INFINISPAN_CONFIG_RESOURCE_PROP);
if (infinispanConfig == null) {
infinispanConfig = ResourceUtils.getResource(INFINISPAN_CONFIG) != null
? INFINISPAN_CONFIG
: INFINISPAN_CONFIG_FALLBACK;
}
if (INFINISPAN_CONFIG_FALLBACK.equals(infinispanConfig)) {
properties.put(Environment.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "read-write");
}
properties.put(InfinispanRegionFactory.INFINISPAN_CONFIG_RESOURCE_PROP, infinispanConfig);
}
}
private void configureMultiTenancy(final AppSettings settings, final Properties properties) {
// multi-tenancy support
if (settings.getBoolean(TenantModule.CONFIG_MULTI_TENANCY, false)) {
properties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE.name());
properties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, TenantConnectionProvider.class.getName());
properties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, TenantResolver.class.getName());
}
}
private void configureSearch(final AppSettings settings, final Properties properties) {
// hibernate-search support
if ("none".equalsIgnoreCase(settings.get(SearchModule.CONFIG_DIRECTORY_PROVIDER))) {
properties.put(org.hibernate.search.cfg.Environment.AUTOREGISTER_LISTENERS, "false");
properties.remove(SearchModule.CONFIG_DIRECTORY_PROVIDER);
} else {
if (properties.getProperty(SearchModule.CONFIG_DIRECTORY_PROVIDER) == null) {
properties.setProperty(SearchModule.CONFIG_DIRECTORY_PROVIDER, SearchModule.DEFAULT_DIRECTORY_PROVIDER);
}
if (properties.getProperty(SearchModule.CONFIG_INDEX_BASE) == null) {
properties.setProperty(SearchModule.CONFIG_INDEX_BASE,
settings.getPath(SearchModule.CONFIG_INDEX_BASE, SearchModule.DEFAULT_INDEX_BASE));
}
properties.put(org.hibernate.search.cfg.Environment.MODEL_MAPPING, SearchMappingFactory.class.getName());
}
}
public static class Initializer {
@Inject
Initializer(PersistService service) {
log.debug("Starting database service...");
service.start();
}
}
} |
package joliex.gwt.client;
import com.google.gwt.user.client.rpc.IsSerializable;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Value implements Serializable, IsSerializable
{
public enum Type implements IsSerializable {
UNDEFINED, STRING, INT, DOUBLE, LONG ,BOOLEAN, BYTEARRAY
}
private Map< String, ValueVector > children = new HashMap< String, ValueVector >();
private String valueObject = null;
private Type type = Type.UNDEFINED;
public Value()
{}
public Value( String value )
{
setValue( value );
}
public Value( Integer value )
{
setValue( value );
}
public Value( Double value )
{
setValue( value );
}
// Added by Balint Maschio
public Value( Long value )
{
setValue( value );
}
public Value( Boolean value )
{
setValue( value );
}
public boolean isString()
{
return type == Type.STRING;
}
public boolean isInt()
{
return type == Type.INT;
}
public boolean isDouble()
{
return type == Type.DOUBLE;
}
// Added by Balint Maschio
public boolean isLong()
{
return type == Type.LONG;
}
// Added by Balint Maschio
public boolean isBool()
{
return type == Type.BOOLEAN;
}
public boolean isDefined()
{
return type != Type.UNDEFINED;
}
public ValueVector getChildren( String id )
{
ValueVector v = children.get( id );
if ( v == null ) {
v = new ValueVector();
children.put( id, v );
}
return v;
}
public boolean hasChildren()
{
return !children.isEmpty();
}
public boolean hasChildren( String id )
{
return children.get( id ) != null;
}
public void deepCopy( Value otherValue )
{
valueObject = otherValue.valueObject;
type = otherValue.type;
ValueVector myVector;
Value myValue;
for( Entry< String, ValueVector > entry : otherValue.children.entrySet() ) {
myVector = new ValueVector();
for( Value v : entry.getValue() ) {
myValue = new Value();
myValue.deepCopy( v );
myVector.add( v );
}
children.put( entry.getKey(), myVector );
}
}
public String strValue()
{
if ( valueObject == null )
return new String();
return valueObject.toString();
}
public int intValue()
{
if ( valueObject == null )
return 0;
return Integer.valueOf( valueObject );
}
public double doubleValue()
{
if ( valueObject == null )
return 0.0;
return Double.valueOf( valueObject );
}
// Added by Balint Maschio
public long longValue()
{
if ( valueObject == null )
return 0L;
return Long.valueOf( valueObject );
}
public boolean boolValue()
{
if ( valueObject == null )
return false;
return Boolean.valueOf( valueObject );
}
public ByteArray byteArrayValue() {
ByteArray r = null;
if ( valueObject == null ) {
byte[] resp = new byte[0];
return new ByteArray( resp );
} else {
char[] chars = valueObject.toCharArray();
byte[] byteArrayToReturn= new byte[chars.length * 2 ]; //bytes per char = 2
for (int i = 0; i < chars.length; i++)
{
for (int j = 0; j < 2; j++)
byteArrayToReturn[i * 2 + j] = (byte) (chars[i] >>> (8 * (1 - j)));
}
return new ByteArray( byteArrayToReturn );
}
}
public Value getNewChild( String childId )
{
ValueVector vec = getChildren( childId );
Value retVal = new Value();
vec.add( retVal );
return retVal;
}
public Map< String, ValueVector > children()
{
return children;
}
public Value getFirstChild( String id )
{
return getChildren( id ).first();
}
public void setValue( String obj )
{
valueObject = obj;
type = Type.STRING;
}
public void setValue( Integer obj )
{
valueObject = obj.toString();
type = Type.INT;
}
public void setValue( Double obj )
{
valueObject = obj.toString();
type = Type.DOUBLE;
}
// Added by Balint Maschio
public void setValue( Long obj )
{
valueObject = obj.toString();
type = Type.LONG;
}
public void setValue( Boolean obj )
{
valueObject = obj.toString();
type = Type.BOOLEAN;
}
public void setValue( ByteArray obj ) {
valueObject = obj.toString();
type = Type.BYTEARRAY;
}
} |
package controller;
import datatree.DataTree;
import genome.Genome;
import genome.Strand;
import ribbonnodes.RibbonEdge;
import ribbonnodes.RibbonNode;
import java.awt.Color;
import java.util.ArrayList;
/**
* Class that calculates and returns the Ribbons and Edges to be drawn on the screen,
* based on the data stored in genomeGraph and dataTree.
*/
public final class RibbonController {
private GenomeGraph genomeGraph; //The graph that contains the geographic information of the stands.
private DataTree dataTree; //The tree that contains the phylogenetic information of the strands.
/**
* Create ribbonController object.
*
* @param genomeGraph the graph that contains the geographic information of the stands.
* @param dataTree datatree that contains the phylogenetic information of the strands
*/
public RibbonController(GenomeGraph genomeGraph, DataTree dataTree) {
this.genomeGraph = genomeGraph;
this.dataTree = dataTree;
}
/**
* Get the ribbon nodes with edges for a certain view in the GUI.
*
* @param minX the minx of the view.
* @param maxX the maxx of the view.
* @param zoomLevel the zoomlevel of the view.
* @return The list of ribbonNodes.
*/
@SuppressWarnings("checkstyle:methodlength")
public ArrayList<RibbonNode> getRibbonNodes(int minX, int maxX, int zoomLevel) {
System.out.println(minX + ", " + maxX);
ArrayList<String> actGen = genomeGraph.getActiveGenomes();
//HARD CODED ACTIVE GENOMES.
if (actGen.size() < 2) {
actGen.add("TKK_02_0010.fasta");
actGen.add("TKK_02_0006.fasta");
actGen.add("TKK_02_0025.fasta");
actGen.add("TKK_02_0005.fasta");
actGen.add("TKK_02_0008.fasta");
actGen.add("TKK_02_0004.fasta");
}
ArrayList<RibbonNode> result = new ArrayList<>();
ArrayList<Strand> filteredNodes = dataTree.getStrands(minX, maxX, actGen, zoomLevel + 1);
int id = 0;
for (Strand strand : filteredNodes) {
RibbonNode ribbon = new RibbonNode(id, strand.getGenomes());
ribbon.setX(strand.getX());
ribbon.addStrand(strand);
id++;
result.add(ribbon);
}
result.sort((RibbonNode o1, RibbonNode o2) -> new Integer(o1.getX()).compareTo(o2.getX()));
addEdges(result);
calcYcoordinates(result);
return result;
}
/**
* Collapses the ribbon Nodes and edges in nodes.
*
* @param nodes The ribbonNode Graph to collapse.
* @return A collapsed graph.
*/
private void collapseRibbons(ArrayList<RibbonNode> nodes) {
for (int i = 0; i < nodes.size(); i++) {
RibbonNode node = nodes.get(i);
if (node != null) {
if (node.getOutEdges().size() == 1) {
RibbonNode other = getNodeWithId(node.getOutEdges().get(0).getEnd(), nodes);
if (other.getInEdges().size() == 1) {
node.addStrands(other.getStrands());
for (RibbonEdge edge : other.getOutEdges()) {
edge.setStartId(node.getId());
}
node.setOutEdges(other.getOutEdges());
nodes.remove(other);
}
}
}
}
}
/**
* Return a node with a certain id contained in a Ribbon Graph.
*
* @param id The id to return for.
* @param nodes The RibbonGraph.
* @return null if that id is not found.
*/
public RibbonNode getNodeWithId(int id, ArrayList<RibbonNode> nodes) {
for (RibbonNode node : nodes) {
if (node.getId() == id) {
return node;
}
}
return null;
}
/**
* Calculate the Y coordinates for the nodes in a ribbonGraph.
*
* @param nodes The ribbonGraph to calculate y cooridnates for.
* @return The ribbonGraph with added y coordinates.
*/
private void calcYcoordinates(ArrayList<RibbonNode> nodes) {
ArrayList<String> ag = genomeGraph.getActiveGenomes();
for (Genome genome : genomeGraph.getGenomes().values()) {
}
}
/**
* Calculate and add edges to a ribbonGraph.
*
* @param nodes the RibbinGraph to calculate edges for.
* @return The ribbonGraph with added edges.
*/
private void addEdges(ArrayList<RibbonNode> nodes) {
for (String genomeID : genomeGraph.getActiveGenomes()) {
RibbonNode currentNode = findNextNodeWithGenome(nodes, genomeID, -1);
while (currentNode != null) {
currentNode = addEdgeReturnEnd(nodes, currentNode, genomeID);
}
}
}
/**
* Finds the next node that contains a certain genome, creates an edge between the two nodes and returns the end Node of the edge.
*
* @param nodes The RibbonGraph.
* @param currentNode The start node of the edge.
* @param genomeID The genome id to find an edge for.
* @return The end node of the edge.
*/
public RibbonNode addEdgeReturnEnd(ArrayList<RibbonNode> nodes, RibbonNode currentNode, String genomeID) {
RibbonNode next = findNextNodeWithGenome(nodes, genomeID, nodes.indexOf(currentNode));
if (next != null) {
if (currentNode.getOutEdge(currentNode.getId(), next.getId()) == null) {
RibbonEdge edge = new RibbonEdge(currentNode.getId(), next.getId());
edge.setColor(getColorForGenomeID(genomeID));
currentNode.addEdge(edge);
next.addEdge(edge);
} else {
currentNode.getOutEdge(currentNode.getId(), next.getId()).addGenomeToEdge(getColorForGenomeID(genomeID));
}
}
return next;
}
/**
* Finds the next node in a ribbongraph that contains a certain genome.
*
* @param nodes The ribbonGraph to search through.
* @param genome The genome to find the next edge for.
* @param currentIndex The current node index to start searching.
* @return The next node that contains genome.
*/
public RibbonNode findNextNodeWithGenome(ArrayList<RibbonNode> nodes, String genome, int currentIndex) {
for (int i = currentIndex + 1; i < nodes.size(); i++) {
if (nodes.get(i).getGenomes().contains(genome)) {
return nodes.get(i);
}
}
return null;
}
/**
* Return the color associated with a genome.
*
* @param GenomeID The genome to return the color for.
* @return The color that is associated with this genomeid.
*/
public Color getColorForGenomeID(String GenomeID) {
Color[] colors = {new Color(0, 0, 255),
new Color(0, 255, 0),
new Color(255, 0, 0),
new Color(0, 255, 255),
new Color(255, 0, 255),
new Color(255, 255, 0),
new Color(0, 0, 128),
new Color(0, 128, 0),
new Color(128, 0, 0)};
return colors[genomeGraph.getActiveGenomes().indexOf(GenomeID)];
}
} |
package team353;
import battlecode.common.*;
import java.util.*;
public class RobotPlayer {
public static class smuConstants {
public static int roundToLaunchAttack = 1600;
public static int roundToDefendTowers = 500;
public static int roundToFormSupplyConvoy = 1200; // roundToBuildSOLDIERS;
public static int RADIUS_FOR_SUPPLY_CONVOY = 2;
public static int numTowersRemainingToAttackHQ = 2;
public static double weightExponentMagic = 0.3;
public static double weightScaleMagic = 0.8;
public static int currentOreGoal = 100;
public static double percentBeaversToGoToSecondBase = 0.4;
// Defence
public static int NUM_TOWER_PROTECTORS = 4;
public static int NUM_HOLE_PROTECTORS = 3;
public static int PROTECT_OTHERS_RANGE = 15;
public static int DISTANCE_TO_START_PROTECTING_SQUARED = 200;
// Idle States
public static MapLocation defenseRallyPoint;
public static int PROTECT_HOLE = 1;
public static int PROTECT_TOWER = 2;
// Supply
public static int NUM_ROUNDS_TO_KEEP_SUPPLIED = 20;
// Contain
public static int CLOCKWISE = 0;
public static int COUNTERCLOCKWISE = 1;
public static int CURRENTLY_BEING_CONTAINED = 1;
public static int NOT_CURRENTLY_BEING_CONTAINED = 2;
// Strategies
/*
* NOTE: If changing these values, alter smuTeamMemoryIndices accordingly
*/
public static int STRATEGY_DRONE_CONTAIN = 1;
public static int STRATEGY_TANKS_AND_SOLDIERS = 2;
public static int STRATEGY_DRONE_SWARM = 3;
public static int STRATEGY_TANKS_AND_LAUNCHERS = 4;
public static int STRATEGY_LAUNCHERS = 5;
public static int STRATEGY_TANK_SWARM =6;
}
public static class smuIndices {
public static int RALLY_POINT_X = 0;
public static int RALLY_POINT_Y = 1;
//Economy
public static int freqQueue = 11;
public static int STRATEGY = 19;
public static int HQ_BEING_CONTAINED = 20;
public static int HQ_BEING_CONTAINED_BY = 21;
//Strategy broadcasts use frequencies 1000 through 3200!
//TODO
public static final int channelAEROSPACELAB = 1100;
public static final int channelBARRACKS = 1200;
public static final int channelBASHER = 1300;
public static final int channelBEAVER = 1400;
public static final int channelCOMMANDER = 1500;
public static final int channelCOMPUTER = 1600;
public static final int channelDRONE = 1700;
public static final int channelHANDWASHSTATION = 1800;
public static final int channelHELIPAD = 1900;
public static final int channelHQ = 2000;
public static final int channelLAUNCHER = 2100;
public static final int channelMINER = 2200;
public static final int channelMINERFACTORY = 2300;
public static final int channelMISSILE = 2400;
public static final int channelSOLDIER = 2500;
public static final int channelSUPPLYDEPOT = 2600;
public static final int channelTANK = 2700;
public static final int channelTANKFACTORY = 2800;
public static final int channelTECHNOLOGYINSTITUTE = 2900;
public static final int channelTOWER = 3000;
public static final int channelTRAININGFIELD = 3100;
public static final int[] channel = new int[] {0, channelAEROSPACELAB, channelBARRACKS, channelBASHER, channelBEAVER, channelCOMMANDER,
channelCOMPUTER, channelDRONE, channelHANDWASHSTATION, channelHELIPAD, channelHQ, channelLAUNCHER, channelMINER,
channelMINERFACTORY, channelMISSILE, channelSOLDIER, channelSUPPLYDEPOT, channelTANK, channelTANKFACTORY,
channelTECHNOLOGYINSTITUTE, channelTOWER, channelTRAININGFIELD};
public static int TOWER_HOLES_BEGIN = 4000;
}
public static class smuTeamMemoryIndices {
public static int PREV_MAP_TOWER_THREAT = 0;
public static int PREV_MAP_VOID_TYPE_PERCENT = 1;
public static int NUM_ROUNDS_USING_STRATEGY_BASE = 1;
// Strategies from smuConstants take values 2-7
public static int ROUND_OUR_HQ_ATTACKED = 8;
// Round their HQ attacked?
public static int ROUND_OUR_TOWER_DESTROYED_BASE = 10;
// Base will expand to values 10-16
public static int ROUND_THEIR_TOWER_DESTROYED_BASE = 17;
// Base will expand to values 17-23
// public static int ROUND_STARTED_USING_STRATEGY_BASE = 23;
// // Base will expand to values 23-29
}
public static void run(RobotController rc) throws GameActionException {
BaseBot myself;
if (rc.getType() == RobotType.HQ) {
myself = new HQ(rc);
} else if (rc.getType() == RobotType.MINER) {
myself = new Miner(rc);
} else if (rc.getType() == RobotType.MINERFACTORY) {
myself = new Minerfactory(rc);
} else if (rc.getType() == RobotType.BEAVER) {
myself = new Beaver(rc);
} else if (rc.getType() == RobotType.BARRACKS) {
myself = new Barracks(rc);
} else if (rc.getType() == RobotType.SOLDIER) {
myself = new Soldier(rc);
} else if (rc.getType() == RobotType.BASHER) {
myself = new Basher(rc);
} else if (rc.getType() == RobotType.HELIPAD) {
myself = new Helipad(rc);
} else if (rc.getType() == RobotType.DRONE) {
myself = new Drone(rc);
} else if (rc.getType() == RobotType.TOWER) {
myself = new Tower(rc);
} else if (rc.getType() == RobotType.SUPPLYDEPOT) {
myself = new Supplydepot(rc);
} else if (rc.getType() == RobotType.HANDWASHSTATION) {
myself = new Handwashstation(rc);
} else if (rc.getType() == RobotType.TANKFACTORY) {
myself = new Tankfactory(rc);
} else if (rc.getType() == RobotType.TANK) {
myself = new Tank(rc);
} else if (rc.getType() == RobotType.AEROSPACELAB) {
myself = new Aerospacelab(rc);
} else if (rc.getType() == RobotType.LAUNCHER) {
myself = new Launcher(rc);
} else if (rc.getType() == RobotType.MISSILE) {
myself = new Missile(rc);
} else {
myself = new BaseBot(rc);
}
while (true) {
try {
myself.go();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static class BaseBot {
protected RobotController rc;
protected MapLocation myHQ, theirHQ;
protected Team myTeam, theirTeam;
protected int myRange;
protected RobotType myType;
static Random rand;
public BaseBot(RobotController rc) {
this.rc = rc;
this.myHQ = rc.senseHQLocation();
this.theirHQ = rc.senseEnemyHQLocation();
this.myTeam = rc.getTeam();
this.theirTeam = this.myTeam.opponent();
this.myType = rc.getType();
this.myRange = myType.attackRadiusSquared;
rand = new Random(rc.getID());
}
public int getDistanceSquared(MapLocation A, MapLocation B){
return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
}
public int getDistanceSquared(MapLocation A){
MapLocation B = rc.getLocation();
return (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y);
}
public Direction[] getDirectionsToward(MapLocation dest) {
Direction toDest = rc.getLocation().directionTo(dest);
Direction[] dirs = new Direction[5];
dirs[0] = toDest;
if (rand.nextDouble() < 0.5){
dirs[1] = toDest.rotateLeft();
dirs[2] = toDest.rotateRight();
} else {
dirs[2] = toDest.rotateLeft();
dirs[1] = toDest.rotateRight();
}
if (rand.nextDouble() < 0.5){
dirs[3] = toDest.rotateLeft().rotateLeft();
dirs[4] = toDest.rotateRight().rotateRight();
} else {
dirs[4] = toDest.rotateLeft().rotateLeft();
dirs[3] = toDest.rotateRight().rotateRight();
}
return dirs;
}
public Direction[] getDirectionsAway(MapLocation dest) {
Direction toDest = rc.getLocation().directionTo(dest).opposite();
Direction[] dirs = new Direction[5];
dirs[0] = toDest;
if (rand.nextDouble() < 0.5){
dirs[1] = toDest.rotateLeft();
dirs[2] = toDest.rotateRight();
} else {
dirs[2] = toDest.rotateLeft();
dirs[1] = toDest.rotateRight();
}
if (rand.nextDouble() < 0.5){
dirs[3] = toDest.rotateLeft().rotateLeft();
dirs[4] = toDest.rotateRight().rotateRight();
} else {
dirs[4] = toDest.rotateLeft().rotateLeft();
dirs[3] = toDest.rotateRight().rotateRight();
}
return dirs;
}
public Direction getMoveDir(MapLocation dest) {
Direction[] dirs = getDirectionsToward(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
public Direction getMoveDirAway(MapLocation dest) {
Direction[] dirs = getDirectionsAway(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
public Direction getMoveDirRand(MapLocation dest) {
//TODO return a random direction
Direction[] dirs = getDirectionsToward(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
public Direction getMoveDirAwayRand(MapLocation dest) {
//TODO return a random direction
Direction[] dirs = getDirectionsAway(dest);
for (Direction d : dirs) {
if (rc.canMove(d)) {
return d;
}
}
return null;
}
//Will return a single direction for spawning. (Uses getDirectionsToward())
public Direction getSpawnDir(RobotType type) {
Direction[] arrayOfDirections = new Direction[]{Direction.EAST, Direction.NORTH, Direction.NORTH_EAST, Direction.NORTH_WEST,
Direction.SOUTH, Direction.SOUTH_EAST, Direction.SOUTH_WEST, Direction.WEST};
// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(arrayOfDirections));
for (Direction d : arrayOfDirections) {
if (rc.canSpawn(d, type)) {
return d;
}
}
return null;
}
//Will return a single direction for building. (Uses getDirectionsToward())
public Direction getBuildDir(RobotType type) {
Direction[] dirs = getDirectionsToward(this.theirHQ);
for (Direction d : dirs) {
if (rc.canBuild(d, type)) {
return d;
}
}
dirs = getDirectionsToward(this.myHQ);
for (Direction d : dirs) {
if (rc.canBuild(d, type)) {
return d;
} else {
// //System.out.println("Could not find valid build location!");
}
}
return null;
}
public RobotInfo[] getAllies() {
RobotInfo[] allies = rc.senseNearbyRobots(Integer.MAX_VALUE, myTeam);
return allies;
}
public RobotInfo[] getEnemiesInAttackingRange() {
RobotInfo[] enemies = rc.senseNearbyRobots(myRange, theirTeam);
return enemies;
}
public Direction getDirOfLauncherTarget() {
int startingByteCode = Clock.getBytecodeNum();
MapLocation myLocation = rc.getLocation();
Direction[] targetDirections = getDirectionsToward(theirHQ);
MapLocation[] targets = new MapLocation[5];
for (int i=0; i<targetDirections.length; i++){
targets[i] = myLocation.add(targetDirections[i], 3);
}
for (int j = 0; j < targets.length; j++) {
if (Clock.getBytecodesLeft() > 500) {
int teammates = 0;
MapLocation targetCenter = targets[j];
RobotInfo[] allRobotsInTargetArea = rc.senseNearbyRobots(
targetCenter, 15, null);
for (RobotInfo robot : allRobotsInTargetArea) {
if (robot.team == myTeam)
teammates++;
}
if (allRobotsInTargetArea.length >= 2 * teammates) {
// //System.out.println("getPositionOfLauncherTarget [bytecode]:" + (Clock.getBytecodeNum()-startingByteCode));
return myLocation.directionTo(targetCenter);
}
}
}
// System.out.println("FAILED getPositionOfLauncherTarget [bytecode]:" + (Clock.getBytecodeNum()-startingByteCode));
return null;
}
public void attackLeastHealthEnemy(RobotInfo[] enemies) throws GameActionException {
if (enemies.length == 0) {
return;
}
double minEnergon = Double.MAX_VALUE;
MapLocation toAttack = null;
for (RobotInfo info : enemies) {
if (info.health < minEnergon) {
toAttack = info.location;
minEnergon = info.health;
}
}
if (toAttack != null) {
rc.attackLocation(toAttack);
}
}
public void attackLeastHealthEnemyInRange() throws GameActionException {
RobotInfo[] enemies = getEnemiesInAttackingRange();
if (enemies.length > 0) {
if (rc.isWeaponReady()) {
attackLeastHealthEnemy(enemies);
}
}
}
public void moveToRallyPoint() throws GameActionException {
if (rc.isCoreReady()) {
int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X);
int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y);
MapLocation rallyPoint = new MapLocation(rallyX, rallyY);
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack &&
rc.getLocation().distanceSquaredTo(rallyPoint) > 8 + Clock.getRoundNum() / 100) {
moveOptimally(getDirectionsToward(rallyPoint));
} else {
Direction newDir = getMoveDir(rallyPoint);
if (newDir != null && rc.canMove(newDir)) {
rc.move(newDir);
}
}
}
}
//Returns the current rally point MapLocation
public MapLocation getRallyPoint() throws GameActionException {
int rallyX = rc.readBroadcast(smuIndices.RALLY_POINT_X);
int rallyY = rc.readBroadcast(smuIndices.RALLY_POINT_Y);
MapLocation rallyPoint = new MapLocation(rallyX, rallyY);
return rallyPoint;
}
//Moves a random safe direction from input array
public void moveOptimally(Direction[] optimalDirections) throws GameActionException {
//TODO check safety
if (optimalDirections != null) {
boolean lookingForDirection = true;
int attemptForDirection = 0;
while(lookingForDirection){
MapLocation[] enemyTowers = rc.senseEnemyTowerLocations();
Direction currentDirection = optimalDirections[attemptForDirection];
//Direction currentDirection = optimalDirections[(int) (rand.nextDouble()*optimalDirections.length)];
MapLocation tileInFront = rc.getLocation().add(currentDirection);
//check that the direction in front is not a tile that can be attacked by the enemy towers
boolean tileInFrontSafe = true;
for(MapLocation m: enemyTowers){
if(m.distanceSquaredTo(tileInFront)<=RobotType.TOWER.attackRadiusSquared+1){
tileInFrontSafe = false;
break;
}
}
//check that we are not facing off the edge of the map
TerrainTile terrainTileInFront = rc.senseTerrainTile(tileInFront);
if(!tileInFrontSafe ||
!rc.isPathable(myType, tileInFront) ||
terrainTileInFront == TerrainTile.OFF_MAP ||
(myType != RobotType.DRONE && terrainTileInFront!=TerrainTile.NORMAL)){
//currentDirection = currentDirection.rotateLeft();
attemptForDirection++;
if (attemptForDirection == optimalDirections.length) {
//System.out.println("No suitable direction found!");
return;
}
}else{
//try to move in the currentDirection direction
if(currentDirection != null && rc.isCoreReady() && rc.canMove(currentDirection)){
rc.move(currentDirection);
lookingForDirection = false;
return;
}
}
}
}
}
//Gets optimal directions and then calls moveOptimally() with those directions.
public void moveOptimally() throws GameActionException {
Direction[] optimalDirections = getOptimalDirections();
if (optimalDirections != null) {
moveOptimally(optimalDirections);
}
}
//TODO Finish
public Direction[] getOptimalDirections() throws GameActionException {
// The switch statement should result in an array of directions that make sense
//for the RobotType. Safety is considered in moveOptimally()
RobotType currentRobotType = rc.getType();
Direction[] optimalDirections = Direction.values();
Collections.shuffle(Arrays.asList(optimalDirections));
switch(currentRobotType){
case BASHER:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case BEAVER:
if (getDistanceSquared(this.myHQ) < 50){
optimalDirections = getDirectionsAway(this.myHQ);
}
break;
case COMMANDER:
break;
case COMPUTER:
break;
case DRONE:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case LAUNCHER:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case MINER:
if (getDistanceSquared(this.myHQ) < 50){
optimalDirections = getDirectionsAway(this.myHQ);
}
break;
case MISSILE:
break;
case SOLDIER:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
case TANK:
optimalDirections = getDirectionsToward(this.theirHQ);
break;
default:
} //Done RobotType specific actions.
return optimalDirections;
}
//Spawns or Queues the unit if it is needed
public boolean tryToSpawn(RobotType spawnType) throws GameActionException{
int round = Clock.getRoundNum();
double ore = rc.getTeamOre();
int spawnTypeInt = RobotTypeToInt(spawnType);
int spawnQueue = rc.readBroadcast(smuIndices.freqQueue);
int currentAmount = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+0);
int desiredAmount = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+1);
int roundToBeginSpawning = rc.readBroadcast(smuIndices.channel[spawnTypeInt]+2);
//Check if we actually need anymore spawnType units
if (round > roundToBeginSpawning && currentAmount < desiredAmount){
if(ore > myType.oreCost){
if (spawnUnit(spawnType)) return true;
} else {
//Add spawnType to queue
if (spawnQueue == 0){
rc.broadcast(smuIndices.freqQueue, spawnTypeInt);
}
return false;
}
}
return false;
}
//Spawns unit based on calling type. Performs all checks.
public boolean spawnOptimally() throws GameActionException {
if (rc.isCoreReady()){
int spawnQueue = rc.readBroadcast(smuIndices.freqQueue);
switch(myType){
case BARRACKS:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.SOLDIER)){
if (tryToSpawn(RobotType.SOLDIER)) return true;
}
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BASHER)){
if (tryToSpawn(RobotType.BASHER)) return true;
}
break;
case HQ:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.BEAVER)){
if (tryToSpawn(RobotType.BEAVER)) return true;
}
break;
case HELIPAD:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.DRONE)){
if (tryToSpawn(RobotType.DRONE)) return true;
}
break;
case AEROSPACELAB:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.LAUNCHER)){
if (tryToSpawn(RobotType.LAUNCHER)) return true;
}
break;
case MINERFACTORY:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.MINER)){
if (tryToSpawn(RobotType.MINER)) return true;
}
break;
case TANKFACTORY:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.TANK)){
if (tryToSpawn(RobotType.TANK)) return true;
}
break;
case TECHNOLOGYINSTITUTE:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMPUTER)){
if (tryToSpawn(RobotType.COMPUTER)) return true;
}
break;
case TRAININGFIELD:
if (spawnQueue == 0 || spawnQueue == RobotTypeToInt(RobotType.COMMANDER)){
if (tryToSpawn(RobotType.COMMANDER)) return true;
}
break;
default:
// System.out.println("ERROR: No building type match found in spawnOptimally()!");
return false;
}
}//isCoreReady
return false;
}
//Gets direction, checks delays, and spawns unit
public boolean spawnUnit(RobotType spawnType) {
//Get a direction and then actually spawn the unit.
Direction randomDir = getSpawnDir(spawnType);
if(rc.isCoreReady() && randomDir != null){
try {
if (rc.canSpawn(randomDir, spawnType)) {
rc.spawn(randomDir, spawnType);
if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == spawnType) {
rc.broadcast(smuIndices.freqQueue, 0);
}
incrementCount(spawnType);
return true;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
return false;
}
//Spawns unit based on calling type. Performs all checks.
public void buildOptimally() throws GameActionException {
int round = Clock.getRoundNum();
double ore = rc.getTeamOre();
boolean buildingsOutrankUnits = true;
int queue = rc.readBroadcast(smuIndices.freqQueue);
RobotType[] arrayOfStructures = new RobotType[] {RobotType.AEROSPACELAB,
RobotType.BARRACKS, RobotType.HANDWASHSTATION, RobotType.HELIPAD, RobotType.HQ,
RobotType.MINERFACTORY, RobotType.SUPPLYDEPOT, RobotType.TANKFACTORY,
RobotType.TECHNOLOGYINSTITUTE, RobotType.TOWER, RobotType.TRAININGFIELD};
//If there is something in the queue and we can not replace it, then return
if (queue != 0 && !buildingsOutrankUnits){
System.out.println("Queue full, can't outrank");
return;
}
//Check if there is a building in queue
if (Arrays.asList(arrayOfStructures).contains(IntToRobotType(queue))) {
//Build it if we can afford it
if (ore > IntToRobotType(queue).oreCost) {
System.out.println("INFO: Satisfying queue. ("+IntToRobotType(queue).name()+")");
buildUnit(IntToRobotType(queue));
}
//Return either way, we can't replace buildings in the queue
return;
}
//Loop over structures and build or queue any needed ones
for (RobotType structure : arrayOfStructures) {
int intStructure = RobotTypeToInt(structure);
double weightOfStructure = getWeightOfRobotType(IntToRobotType(intStructure));
if (weightOfStructure == 1.0){
if (ore > IntToRobotType(intStructure).oreCost){
buildUnit(IntToRobotType(intStructure));
System.out.println("Tried to build "+ IntToRobotType(intStructure));
} else {
rc.broadcast(smuIndices.freqQueue, intStructure);
System.out.println("Scheduled a " + IntToRobotType(intStructure).name() +
". Need " + (IntToRobotType(intStructure).oreCost-ore) + " more ore.");
}
return;
}
}//end loop of structures
}
//Gets direction, checks delays, and builds unit
public boolean buildUnit(RobotType buildType) {
//Get a direction and then actually build the unit.
Direction randomDir = getBuildDir(buildType);
if(rc.isCoreReady() && randomDir != null){
try {
if (rc.canBuild(randomDir, buildType)) {
rc.build(randomDir, buildType);
if (IntToRobotType(rc.readBroadcast(smuIndices.freqQueue)) == buildType) {
rc.broadcast(smuIndices.freqQueue, 0);
}
incrementCount(buildType);
return true;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
return false;
}
//Increment the currentAmount of a RobotType
public void incrementCount(RobotType type) throws GameActionException {
int intType = RobotTypeToInt(type);
int currentAmount = rc.readBroadcast(smuIndices.channel[intType]+0);
rc.broadcast(smuIndices.channel[intType+0], currentAmount+1);
}
public void transferSupplies() throws GameActionException {
double lowestSupply = rc.getSupplyLevel();
if (lowestSupply == 0) {
return;
}
int roundStart = Clock.getRoundNum();
final MapLocation myLocation = rc.getLocation();
RobotInfo[] nearbyAllies = rc.senseNearbyRobots(myLocation,GameConstants.SUPPLY_TRANSFER_RADIUS_SQUARED,rc.getTeam());
double transferAmount = 0;
MapLocation suppliesToThisLocation = null;
for(RobotInfo ri:nearbyAllies){
if (!ri.type.isBuilding && ri.supplyLevel < lowestSupply) {
lowestSupply = ri.supplyLevel;
transferAmount = (rc.getSupplyLevel()-ri.supplyLevel)/2;
suppliesToThisLocation = ri.location;
}
}
if(suppliesToThisLocation!=null){
if (roundStart == Clock.getRoundNum() && transferAmount > 0 && Clock.getBytecodesLeft() > 550) {
try {
rc.transferSupplies((int)transferAmount, suppliesToThisLocation);
} catch(GameActionException gax) {
gax.printStackTrace();
}
}
}
}
// true, I'm in the convoy or going to be
// false, no place in the convoy for me
public boolean formSupplyConvoy() {
try {
if (rc.readBroadcast(smuIndices.STRATEGY) == smuConstants.STRATEGY_DRONE_CONTAIN) {
return false;
}
} catch (GameActionException e1) {
e1.printStackTrace();
}
Direction directionForChain = getSupplyConvoyDirection(myHQ);
RobotInfo minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, myHQ, directionForChain);
if (minerAtEdge == null){
goToLocation(myHQ.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY));
return true;
} else if (minerAtEdge.ID == rc.getID()) {
return true;
}
RobotInfo previousMiner = null;
try {
while ((minerAtEdge != null || !minerAtEdge.type.isBuilding) && minerAtEdge.location.distanceSquaredTo(getRallyPoint()) > 4) {
directionForChain = getSupplyConvoyDirection(minerAtEdge.location);
previousMiner = minerAtEdge;
minerAtEdge = getUnitAtEdgeOfSupplyRangeOf(RobotType.MINER, minerAtEdge.location, directionForChain);
if (minerAtEdge == null) {
goToLocation(previousMiner.location.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY));
return true;
} else if (minerAtEdge.ID == rc.getID()) {
return true;
}
}
} catch (GameActionException e) {
e.printStackTrace();
}
return false;
}
public Direction getSupplyConvoyDirection(MapLocation startLocation) {
Direction directionForChain = myHQ.directionTo(theirHQ);
MapLocation locationToGo = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL && rc.canSenseLocation(locationToGo)) {
RobotInfo robotInDirection;
try {
robotInDirection = rc.senseRobotAtLocation(locationToGo);
if (robotInDirection == null || !robotInDirection.type.isBuilding) {
return directionForChain;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
Direction[] directions = {Direction.NORTH, Direction.NORTH_EAST, Direction.EAST, Direction.SOUTH_EAST, Direction.SOUTH, Direction.SOUTH_WEST, Direction.WEST, Direction.NORTH_WEST};
for (int i = 0; i < directions.length; i++) {
locationToGo = startLocation.add(directions[i], smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (directions[i] != directionForChain && directions[i] != Direction.OMNI && directions[i] != Direction.NONE
&& rc.senseTerrainTile(locationToGo) == TerrainTile.NORMAL) {
RobotInfo robotInDirection;
try {
robotInDirection = rc.senseRobotAtLocation(locationToGo);
if (robotInDirection == null || !robotInDirection.type.isBuilding) {
return directions[i];
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
}
return Direction.NONE;
}
public RobotInfo getUnitAtEdgeOfSupplyRangeOf(RobotType unitType, MapLocation startLocation, Direction directionForChain) {
MapLocation locationInChain = startLocation.add(directionForChain, smuConstants.RADIUS_FOR_SUPPLY_CONVOY);
if (rc.canSenseLocation(locationInChain)) {
try {
return rc.senseRobotAtLocation(locationInChain);
} catch (GameActionException e) {
e.printStackTrace();
}
}
return null;
}
public MapLocation getSecondBaseLocation() {
Direction directionToTheirHQ = myHQ.directionTo(theirHQ);
MapLocation secondBase = null;
if (directionToTheirHQ == Direction.EAST || directionToTheirHQ == Direction.WEST) {
secondBase = getSecondBaseLocationInDirections(Direction.NORTH, Direction.SOUTH);
} else if (directionToTheirHQ == Direction.NORTH || directionToTheirHQ == Direction.SOUTH) {
secondBase = getSecondBaseLocationInDirections(Direction.EAST, Direction.WEST);
} else {
Direction[] directions = breakdownDirection(directionToTheirHQ);
secondBase = getSecondBaseLocationInDirections(directions[0], directions[1]);
}
if (secondBase != null) {
secondBase = secondBase.add(myHQ.directionTo(secondBase), 4);
}
return secondBase;
}
public MapLocation getSecondBaseLocationInDirections(Direction dir1, Direction dir2) {
MapLocation towers[] = rc.senseTowerLocations();
int maxDistance = Integer.MIN_VALUE;
int maxDistanceIndex = -1;
Direction dirToEnemy = myHQ.directionTo(theirHQ);
Direction dir1left = dir1.rotateLeft();
Direction dir1right = dir1.rotateRight();
Direction dir2left = dir2.rotateLeft();
Direction dir2right = dir2.rotateRight();
for (int i = 0; i<towers.length; i++) {
Direction dirToTower = myHQ.directionTo(towers[i]);
if (dirToTower == dir1 || dirToTower == dir2
|| (dir1left != dirToEnemy && dirToTower == dir1left)
|| (dir1right != dirToEnemy && dirToTower == dir1right)
|| (dir2left != dirToEnemy && dirToTower == dir2left)
|| (dir2right != dirToEnemy && dirToTower == dir2right)) {
int distanceToTower = myHQ.distanceSquaredTo(towers[i]);
if (distanceToTower > maxDistance) {
maxDistance = distanceToTower;
maxDistanceIndex = i;
}
}
}
if (maxDistanceIndex != -1) {
return towers[maxDistanceIndex];
}
return null;
}
public void beginningOfTurn() {
if (rc.senseEnemyHQLocation() != null) {
this.theirHQ = rc.senseEnemyHQLocation();
}
}
public void endOfTurn() {
}
public void go() throws GameActionException {
beginningOfTurn();
execute();
endOfTurn();
}
public void execute() throws GameActionException {
rc.yield();
}
public void supplyAndYield() throws GameActionException {
transferSupplies();
rc.yield();
}
public int myContainDirection = smuConstants.CLOCKWISE;
public MapLocation myContainPreviousLocation;
public void contain() {
MapLocation enemyHQ = rc.senseEnemyHQLocation();
MapLocation[] enemyTowers = rc.senseEnemyTowerLocations();
MapLocation myLocation = rc.getLocation();
int radiusFromHQ = 24;
if (enemyTowers.length >= 2) {
radiusFromHQ = 35;
}
if (myLocation.distanceSquaredTo(enemyHQ) > radiusFromHQ + 3) {
// move towards the HQ
try {
RobotInfo[] nearbyTeammates = rc.senseNearbyRobots(4, myTeam);
int numAttackers = 0;
for (RobotInfo teammate : nearbyTeammates) {
if (!teammate.type.isBuilding && teammate.type != RobotType.MINER && teammate.type != RobotType.BEAVER) numAttackers++;
}
if (numAttackers >= getNumAttackersToContain()) {
moveOptimally();
}
} catch (GameActionException e) {
e.printStackTrace();
}
} else {
MapLocation locationToGo = null;
Direction directionToGo = null;
if (myContainDirection == smuConstants.CLOCKWISE) {
directionToGo = getClockwiseDirection(myLocation, enemyHQ);
} else {
directionToGo = getCounterClockwiseDirection(myLocation, enemyHQ);
}
locationToGo = myLocation.add(directionToGo);
if (rc.isPathable(myType, locationToGo)) {
if (isLocationSafe(locationToGo)) {
goToLocation(locationToGo);
} else {
Direction[] directions = breakdownDirection(directionToGo);
for (int i = 0; i < directions.length; i++) {
locationToGo = myLocation.add(directions[i]);
if (isLocationSafe(locationToGo)) {
goToLocation(locationToGo);
myContainPreviousLocation = myLocation;
return;
}
}
}
} else if (myContainPreviousLocation.equals(myLocation)){
if (myContainDirection == smuConstants.CLOCKWISE) {
myContainDirection = smuConstants.COUNTERCLOCKWISE;
} else {
myContainDirection = smuConstants.CLOCKWISE;
}
}
}
myContainPreviousLocation = myLocation;
}
public int getNumAttackersToContain() {
if (myType == RobotType.SOLDIER) {
return 2;
} else if (myType == RobotType.TANK) {
return 1;
} else {
return 2;
}
}
public boolean isLocationSafe(MapLocation location) {
int hqAttackRadius = RobotType.HQ.attackRadiusSquared;
if (rc.senseEnemyTowerLocations().length >= 2) hqAttackRadius = 35;
if (location.distanceSquaredTo(theirHQ) > hqAttackRadius) {
for (MapLocation tower : rc.senseEnemyTowerLocations()) {
if (location.distanceSquaredTo(tower) <= RobotType.TOWER.attackRadiusSquared) {
return false;
}
}
return true;
}
return false;
}
//TODO
public void mineOptimally() throws GameActionException {
MapLocation myLocation = rc.getLocation();
if (rc.senseOre(myLocation) > 0){
if (rc.isCoreReady()){
rc.mine();
}
return;
}
//MapLocation[] possibleSites = myLocation.getAllMapLocationsWithinRadiusSq(rc.getLocation(), 2);
Direction[] arrayOfDirections = new Direction[]{Direction.EAST, Direction.NORTH, Direction.NORTH_EAST, Direction.NORTH_WEST,
Direction.SOUTH, Direction.SOUTH_EAST, Direction.SOUTH_WEST, Direction.WEST};
List<MapLocation> likelyMineSites = new ArrayList<MapLocation>();
int numOfPossibleSites = 0;
for (Direction dir : arrayOfDirections){
MapLocation site = myLocation.add(dir);
TerrainTile siteTerrainTile = rc.senseTerrainTile(site);
if(rc.isPathable(myType, site) &&
siteTerrainTile != TerrainTile.OFF_MAP &&
siteTerrainTile == TerrainTile.NORMAL &&
rc.senseOre(site) > 0.0){
likelyMineSites.add(site);
numOfPossibleSites++;
}
}
if (numOfPossibleSites > 0) {
MapLocation[] possibleMineSites = likelyMineSites.toArray(new MapLocation[likelyMineSites.size()]);
//Sort possibleMineSites based on ore
Arrays.sort(possibleMineSites, new Comparator<MapLocation>() {
public int compare(MapLocation location1, MapLocation location2) {
double ore1 = 0;
double ore2 = 0;
if (location1 != null) ore1 = rc.senseOre(location1);
if (location2 != null) ore2 = rc.senseOre(location2);
return Double.compare(ore2, ore1); //descending ORE-der... heh heh heh
}
});
System.out.println("#"+possibleMineSites.length+" 0th: "+rc.senseOre(possibleMineSites[0])+" @ "+possibleMineSites[0].toString());
int numAdjacentMiners = 0;
double siteOre;
double siteWeight;
Direction siteDir;
//Get robots in the 5x5 square we are observing
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(8, myTeam);
System.out.println("##"+possibleMineSites.length+" nearbyRobots: "+nearbyRobots.length);
//Check possibleMineSites for adjacencies to other miners
for (int i =0; i < possibleMineSites.length; i++) {
MapLocation site = possibleMineSites[i];
//int nextIndex = i;
//if (i != possibleMineSites.length -1) nextIndex = i+1;
numAdjacentMiners = 0;
//System.out.println("###"+possibleMineSites.length+" ith "+possibleMineSites[i].toString()+" nearbyRobots: "+nearbyRobots.length);
for (int j = 0; j < nearbyRobots.length; j++) {
//System.out.println("
if (nearbyRobots[j].type == RobotType.MINER
&& site.distanceSquaredTo(nearbyRobots[j].location) <= 2) {
//Another miner is too close
numAdjacentMiners++;
if (numAdjacentMiners >= 2) {
System.out.println("
site = null;
break;
}
}
}//end nearbyRobots
if (site != null){
siteOre = rc.senseOre(site) / 60.0;
siteWeight = siteOre - 0.25*numAdjacentMiners;
siteDir = myLocation.directionTo(site);
double roll = rand.nextDouble();
//System.out.println("MINER: rolled "+roll+" against "+siteWeight+" for Dir-"+siteDir.toString());
if (roll < siteWeight && rc.isCoreReady() && rc.canMove(siteDir)){
rc.move(siteDir);
return;
}
}
}//end possibleMineSites
if (rand.nextDouble() < 0.5) {
moveToRallyPoint();
} else {
moveOptimally(getDirectionsAway(this.myHQ));
}
} else {
//System.out.println("MINER: No ore nearby. Bytecode Remaining: "+Clock.getBytecodesLeft());
if (rand.nextDouble() < 0.5) {
moveToRallyPoint();
} else {
moveOptimally(getDirectionsAway(this.myHQ));
}
}
}
public Direction[] breakdownDirection(Direction direction) {
Direction[] breakdown = new Direction[2];
switch(direction) {
case NORTH_EAST:
breakdown[0] = Direction.NORTH;
breakdown[1] = Direction.EAST;
break;
case SOUTH_EAST:
breakdown[0] = Direction.SOUTH;
breakdown[1] = Direction.EAST;
break;
case NORTH_WEST:
breakdown[0] = Direction.NORTH;
breakdown[1] = Direction.WEST;
break;
case SOUTH_WEST:
breakdown[0] = Direction.SOUTH;
breakdown[1] = Direction.WEST;
break;
default:
break;
}
return breakdown;
}
public Direction getClockwiseDirection(MapLocation myLocation, MapLocation anchor) {
Direction directionToAnchor = myLocation.directionTo(anchor);
if (directionToAnchor.equals(Direction.EAST) || directionToAnchor.equals(Direction.SOUTH_EAST)) {
return Direction.NORTH_EAST;
} else if (directionToAnchor.equals(Direction.SOUTH) || directionToAnchor.equals(Direction.SOUTH_WEST)) {
return Direction.SOUTH_EAST;
} else if (directionToAnchor.equals(Direction.WEST) || directionToAnchor.equals(Direction.NORTH_WEST)) {
return Direction.SOUTH_WEST;
} else if (directionToAnchor.equals(Direction.NORTH) || directionToAnchor.equals(Direction.NORTH_EAST)) {
return Direction.NORTH_WEST;
}
return Direction.NONE;
}
public Direction getCounterClockwiseDirection(MapLocation myLocation, MapLocation anchor) {
Direction oppositeDirection = getClockwiseDirection(myLocation, anchor);
if (oppositeDirection.equals(Direction.NORTH_EAST)) {
return Direction.SOUTH_WEST;
} else if (oppositeDirection.equals(Direction.SOUTH_EAST)) {
return Direction.NORTH_WEST;
} else if (oppositeDirection.equals(Direction.SOUTH_WEST)) {
return Direction.NORTH_EAST;
} else if (oppositeDirection.equals(Direction.NORTH_WEST)) {
return Direction.SOUTH_WEST;
}
return Direction.NONE;
}
// Defend
public boolean defendSelf() {
RobotInfo[] nearbyEnemies = getEnemiesInAttackRange();
if(nearbyEnemies != null && nearbyEnemies.length > 0) {
try {
if (rc.isWeaponReady()) {
attackLeastHealthEnemyInRange();
}
} catch (GameActionException e) {
e.printStackTrace();
}
return true;
}
return false;
}
public boolean defendTeammates() {
RobotInfo[] engagedRobots = getRobotsEngagedInAttack();
if(engagedRobots != null && engagedRobots.length>0) { // Check broadcasts for enemies that are being attacked
// TODO: Calculate which enemy is attacking/within range/closest to teammate
// For now, just picking the first enemy
// Once our unit is in range of the other unit, A1 will takeover
for (RobotInfo robot : engagedRobots) {
if (robot.team == theirTeam) {
goToLocation(robot.location);
}
}
return true;
}
return false;
}
public boolean defend() {
// A1, Protect Self
boolean isProtectingSelf = defendSelf();
if (isProtectingSelf) {
return true;
}
// A2, Protect Nearby
boolean isProtectingTeammates = defendTeammates();
if (isProtectingTeammates) {
return true;
}
return false;
}
public int RobotTypeToInt(RobotType type){
switch(type) {
case AEROSPACELAB:
return 1;
case BARRACKS:
return 2;
case BASHER:
return 3;
case BEAVER:
return 4;
case COMMANDER:
return 5;
case COMPUTER:
return 6;
case DRONE:
return 7;
case HANDWASHSTATION:
return 8;
case HELIPAD:
return 9;
case HQ:
return 10;
case LAUNCHER:
return 11;
case MINER:
return 12;
case MINERFACTORY:
return 13;
case MISSILE:
return 14;
case SOLDIER:
return 15;
case SUPPLYDEPOT:
return 16;
case TANK:
return 17;
case TANKFACTORY:
return 18;
case TECHNOLOGYINSTITUTE:
return 19;
case TOWER:
return 20;
case TRAININGFIELD:
return 21;
default:
return -1;
}
}
public RobotType IntToRobotType(int type){
switch(type) {
case 1:
return RobotType.AEROSPACELAB;
case 2:
return RobotType.BARRACKS;
case 3:
return RobotType.BASHER;
case 4:
return RobotType.BEAVER;
case 5:
return RobotType.COMMANDER;
case 6:
return RobotType.COMPUTER;
case 7:
return RobotType.DRONE;
case 8:
return RobotType.HANDWASHSTATION;
case 9:
return RobotType.HELIPAD;
case 10:
return RobotType.HQ;
case 11:
return RobotType.LAUNCHER;
case 12:
return RobotType.MINER;
case 13:
return RobotType.MINERFACTORY;
case 14:
return RobotType.MISSILE;
case 15:
return RobotType.SOLDIER;
case 16:
return RobotType.SUPPLYDEPOT;
case 17:
return RobotType.TANK;
case 18:
return RobotType.TANKFACTORY;
case 19:
return RobotType.TECHNOLOGYINSTITUTE;
case 20:
return RobotType.TOWER;
case 21:
return RobotType.TRAININGFIELD;
default:
return null;
}
}
// //Returns a weight representing the 'need' for the RobotType
// public double getWeightOfRobotType(RobotType type) throws GameActionException {
// int typeInt = RobotTypeToInt(type);
// if (rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) == 0) return 0;
// double weight = rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt) +
// (rc.readBroadcast(smuIndices.freqRoundToFinish + typeInt) - rc.readBroadcast(smuIndices.freqRoundToBuild + typeInt)) /
// rc.readBroadcast(smuIndices.freqDesiredNumOf + typeInt) * rc.readBroadcast(smuIndices.freqNum[typeInt]);
// return weight;
//Returns a weight representing the 'need' for the RobotType
public double getWeightOfRobotType(RobotType type) throws GameActionException {
int typeInt = RobotTypeToInt(type);
int round = Clock.getRoundNum();
double weight = 0;
if (!type.isBuilding) {
int currentAmount = rc.readBroadcast(smuIndices.channel[typeInt]+0);
int desiredAmount = rc.readBroadcast(smuIndices.channel[typeInt]+1);
int roundToBeginSpawning = rc.readBroadcast(smuIndices.channel[typeInt]+2);
int roundToFinishSpawning = rc.readBroadcast(smuIndices.channel[typeInt]+3);
//Return zero if unit is not desired. (Divide by zero protection)
if (desiredAmount == 0) {
//System.out.println("Error: No desired "+IntToRobotType(typeInt));
return 0;
}
if (roundToBeginSpawning >= roundToFinishSpawning) {
//System.out.println("Error: build > finish for: "+IntToRobotType(typeInt));
return 0;
}
if (round < roundToBeginSpawning) {
//System.out.println("Error: Too early for "+IntToRobotType(typeInt));
return 0;
}
//The weight is equal to a point on the surface drawn by z = x^(m*y) where
double x = (double) (round - roundToBeginSpawning)
/ (double) (roundToFinishSpawning - roundToBeginSpawning);
double y = (double) currentAmount / (double) desiredAmount;
weight = smuConstants.weightScaleMagic
* Math.pow(x, (smuConstants.weightExponentMagic + y));
//System.out.println("type: "+IntToRobotType(typeInt)+" x: " + x + " y: " + y + " weight: " + weight);
return weight;
} //end units
if (type.isBuilding){
int currentAmount = rc.readBroadcast(smuIndices.channel[typeInt]+0);
int desiredAmount = rc.readBroadcast(smuIndices.channel[typeInt]+1);
int nextRoundToBuild = rc.readBroadcast(smuIndices.channel[typeInt]+2+currentAmount);
int intQueuedType = rc.readBroadcast(smuIndices.freqQueue);
if (currentAmount < desiredAmount && nextRoundToBuild != 0) {
if (round > nextRoundToBuild && typeInt != intQueuedType) {
//TODO We need to check if we are currently building it...
System.out.println("Warning: round > nextRoundToBuild && not queued >> " + type.name());
return 1.0;
}
if (round == nextRoundToBuild) {
return 1.0;
}
if (round < nextRoundToBuild) {
return 0.0;
}
System.out.println("ERROR: Unexpected return path in getWeightOfRobotType " + type.name());
return weight;
} else {
return 0;
}
} //end structures
System.out.println("ERROR: Unexpected return path in getWeightOfRobotType");
return weight;
}
public RobotInfo[] getEnemiesInAttackRange() {
return rc.senseNearbyRobots(myRange, theirTeam);
}
//TODO Use optimally instead?
public void goToLocation(MapLocation location) {
try {
if (rc.canSenseLocation(location) && rc.senseRobotAtLocation(location) != null
&& rc.getLocation().distanceSquaredTo(location)<3) { // 3 squares
return;
}
Direction direction = getMoveDir(location);
if (direction == null) return;
RobotInfo[] nearbyEnemies = rc.senseNearbyRobots(rc.getLocation().add(direction), RobotType.TOWER.attackRadiusSquared, theirTeam);
boolean towersNearby = false;
for (RobotInfo enemy : nearbyEnemies) {
if (enemy.type == RobotType.TOWER || enemy.type == RobotType.HQ) {
towersNearby = true;
break;
}
}
if (!towersNearby || Clock.getRoundNum() > smuConstants.roundToLaunchAttack) {
if (direction != null && rc.isCoreReady() && rc.canMove(direction) && Clock.getBytecodesLeft() > 55) {
rc.move(direction);
}
}
} catch (GameActionException e1) {
e1.printStackTrace();
}
}
public RobotInfo[] getRobotsEngagedInAttack() {
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(smuConstants.PROTECT_OTHERS_RANGE);
boolean hasEnemy = false;
boolean hasFriendly = false;
for (RobotInfo robot : nearbyRobots) {
if(robot.team == theirTeam && robot.type != RobotType.TOWER) {
hasEnemy = true;
if (hasFriendly) {
return nearbyRobots;
}
} else {
hasFriendly = true;
if (hasEnemy) {
return nearbyRobots;
}
}
}
return null;
}
public RobotInfo[] getTeammatesInAttackRange() {
return rc.senseNearbyRobots(myRange, myTeam);
}
public RobotInfo[] getTeammatesNearTower(MapLocation towerLocation) {
return rc.senseNearbyRobots(towerLocation, RobotType.TOWER.attackRadiusSquared, myTeam);
}
// Find out if there are any holes between a teams tower and their HQ
public MapLocation[] computeHoles() {
MapLocation[] towerLocations = rc.senseTowerLocations();
MapLocation[][] towerRadii = new MapLocation[towerLocations.length][];
for(int i = 0; i < towerLocations.length; i++) {
// Get all map locations that a tower can attack
MapLocation[] locations = MapLocation.getAllMapLocationsWithinRadiusSq(towerLocations[i], RobotType.TOWER.attackRadiusSquared);
Arrays.sort(locations);
towerRadii[i] = locations;
}
if(towerRadii.length == 0 || towerRadii[0] == null) {
return null;
}
// Naively say, if overlapping by two towers, there is no path
int[] overlapped = new int[towerRadii.length];
int holesBroadcastIndex = smuIndices.TOWER_HOLES_BEGIN;
for(int i = 0; i<towerRadii.length; i++) {
MapLocation[] locations = towerRadii[i];
boolean coveredLeft = false;
boolean coveredRight = false;
boolean coveredTop = false;
boolean coveredBottom = false;
for (int j = 0; j < towerRadii.length; j++) {
if (j != i) {
MapLocation[] otherLocations = towerRadii[j];
if (locations[0].x <= otherLocations[otherLocations.length-1].x &&
otherLocations[0].x <= locations[locations.length-1].x &&
locations[0].y <= otherLocations[otherLocations.length-1].y &&
otherLocations[0].y <= locations[locations.length-1].y) {
overlapped[i]++;
Direction otherTowerDir = towerLocations[i].directionTo(towerLocations[j]);
if (otherTowerDir.equals(Direction.EAST) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.SOUTH_EAST)) {
coveredLeft = true;
}
if (otherTowerDir.equals(Direction.WEST) || otherTowerDir.equals(Direction.NORTH_WEST) || otherTowerDir.equals(Direction.SOUTH_WEST)) {
coveredRight = true;
}
if (otherTowerDir.equals(Direction.NORTH) || otherTowerDir.equals(Direction.NORTH_EAST) || otherTowerDir.equals(Direction.NORTH_WEST)) {
coveredTop = true;
}
if (otherTowerDir.equals(Direction.SOUTH) || otherTowerDir.equals(Direction.SOUTH_EAST) || otherTowerDir.equals(Direction.SOUTH_WEST)) {
coveredBottom = true;
}
}
}
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x - 1, locations[0].y))) {
overlapped[i]++;
coveredLeft = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[locations.length-1].x + 1, locations[0].y))) {
overlapped[i]++;
coveredRight = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[0].y - 1))) {
overlapped[i]++;
coveredTop = true;
}
if(overlapped[i]<2 && !rc.isPathable(RobotType.BEAVER, new MapLocation(locations[0].x, locations[locations.length-1].y + 1))) {
overlapped[i]++;
coveredBottom = true;
}
// //System.out.println("Tower " + i + " overlapped " + overlapped[i] + " " + towerLocations[i]);
if (overlapped[i] < 2) {
try {
int towerAttackRadius = (int) Math.sqrt(RobotType.TOWER.attackRadiusSquared) + 1;
if (!coveredLeft) {
// //System.out.println("Tower " + towerLocations[i] + " Not covered left");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x - towerAttackRadius);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y);
holesBroadcastIndex+=2;
}
if (!coveredRight) {
// //System.out.println("Tower " + towerLocations[i] + " Not covered right");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x + towerAttackRadius);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y);
holesBroadcastIndex+=2;
}
if (!coveredTop) {
// //System.out.println("Tower " + towerLocations[i] + " Not covered top");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y - towerAttackRadius);
holesBroadcastIndex+=2;
}
if (!coveredBottom) {
// //System.out.println("Tower " + towerLocations[i] + " Not covered bottom");
rc.broadcast(holesBroadcastIndex, towerLocations[i].x);
rc.broadcast(holesBroadcastIndex + 1, towerLocations[i].y + towerAttackRadius);
holesBroadcastIndex+=2;
}
} catch (GameActionException e) {
e.printStackTrace();
}
}
}
// Signify end of holes
try {
rc.broadcast(holesBroadcastIndex, -1);
} catch (GameActionException e) {
e.printStackTrace();
}
// //System.out.println("BYTEEND on " + Clock.getRoundNum() + ": " + Clock.getBytecodeNum());
return null;
}
}
public static class HQ extends BaseBot {
public int xMin, xMax, yMin, yMax;
public int xpos, ypos;
public int totalNormal, totalVoid, totalProcessed;
public int towerThreat;
public static double ratio;
public boolean isFinishedAnalyzing = false;
public boolean analyzedTowers = false;
public int defaultStrategy = smuConstants.STRATEGY_TANKS_AND_SOLDIERS;
public boolean hasChosenStrategyPrior = false;
public int strategy = defaultStrategy;
public int prevStrategy = 0;
public int numTowers;
public int numEnemyTowers;
public boolean dronesFailed = false;
public boolean analyzedPrevMatch = false;
public HQ(RobotController rc) {
super(rc);
numTowers = rc.senseTowerLocations().length;
numEnemyTowers = rc.senseEnemyTowerLocations().length;
xMin = Math.min(this.myHQ.x, this.theirHQ.x);
xMax = Math.max(this.myHQ.x, this.theirHQ.x);
yMin = Math.min(this.myHQ.y, this.theirHQ.y);
yMax = Math.max(this.myHQ.y, this.theirHQ.y);
xpos = xMin;
ypos = yMin;
totalNormal = totalVoid = totalProcessed = 0;
towerThreat = 0;
isFinishedAnalyzing = false;
try {
computeStrategy();
} catch (GameActionException e) {
e.printStackTrace();
}
computeHoles();
}
public void analyzePreviousMatch() {
long[] prevGameTeamMemory = rc.getTeamMemory();
boolean hasData = false;
for (long memory : prevGameTeamMemory) {
if (memory != 0) {
hasData = true;
break;
}
}
if (hasData) {
double prevRatio = ((double) prevGameTeamMemory[smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT])/100.0;
int mostUsed = 0;
int mostUsedIndex = -1;
int secondMostUsed = 0;
int secondMostUsedIndex = -1;
for(int i = 0; i < 6; i++) { // 6 is number of different strategies
int numRoundsUsed = (int) prevGameTeamMemory[smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + i];
if (numRoundsUsed > mostUsed) {
secondMostUsed = mostUsed;
secondMostUsedIndex = mostUsedIndex;
mostUsed = numRoundsUsed;
mostUsedIndex = i;
} else if (numRoundsUsed > secondMostUsed) {
secondMostUsed = numRoundsUsed;
secondMostUsedIndex = i;
}
}
if (mostUsed == smuConstants.STRATEGY_DRONE_CONTAIN || mostUsed == smuConstants.STRATEGY_DRONE_SWARM) {
dronesFailed = true;
// System.out.println(Clock.getRoundNum() + " Drones failed.");
} else {
if (ratio > 0.85 && prevRatio > 0.85) {
// Both Traversables
int i = 0;
while (prevGameTeamMemory[smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + i] != 0) {
i++;
}
int ourTowersDestroyed = i;
int j = 0;
while (prevGameTeamMemory[smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + j] != 0) {
j++;
}
int theirTowersDestroyed = j;
if (ourTowersDestroyed < theirTowersDestroyed) {
defaultStrategy = mostUsedIndex + 1;
} else {
if (secondMostUsedIndex != -1) {
defaultStrategy = secondMostUsedIndex + 1;
}
}
}
}
for (int i = 0; i < GameConstants.TEAM_MEMORY_LENGTH; i++) {
rc.setTeamMemory(i, 0);
}
}
analyzedPrevMatch = true;
}
public void analyzeMap() {
while (ypos < yMax + 1) {
TerrainTile t = rc.senseTerrainTile(new MapLocation(xpos, ypos));
if (t == TerrainTile.NORMAL) {
totalNormal++;
totalProcessed++;
}
else if (t == TerrainTile.VOID) {
totalVoid++;
totalProcessed++;
}
xpos++;
if (xpos == xMax + 1) {
xpos = xMin;
ypos++;
}
if (Clock.getBytecodesLeft() < 50) {
return;
}
}
ratio = (double) totalNormal / totalProcessed;
isFinishedAnalyzing = true;
}
public void analyzeTowers() {
MapLocation[] towers = rc.senseEnemyTowerLocations();
towerThreat = 0;
for (int i=0; i<towers.length; ++i) {
MapLocation towerLoc = towers[i];
if ((xMin <= towerLoc.x && towerLoc.x <= xMax && yMin <= towerLoc.y && towerLoc.y <= yMax) || towerLoc.distanceSquaredTo(this.theirHQ) <= 50) {
for (int j=0; j<towers.length; ++j) {
if (towers[j].distanceSquaredTo(towerLoc) <= 50) {
towerThreat++;
}
}
}
}
analyzedTowers = true;
}
public void chooseStrategy() throws GameActionException {
if (hasChosenStrategyPrior && Clock.getRoundNum() % 250 != 0) {
return;
}
if (rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) == smuConstants.NOT_CURRENTLY_BEING_CONTAINED) {
// Test for Swarms
MapLocation[] ourTowers = rc.senseTowerLocations();
RobotType swarmingType = null;
if (ourTowers != null && ourTowers.length > 0) {
int closestTower = -1;
int closestDistanceToEnemyHQ = Integer.MAX_VALUE;
for (int i = 0; i < ourTowers.length; i++) {
int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ);
if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) {
closestDistanceToEnemyHQ = currDistanceToEnemyHQ;
closestTower = i;
}
}
RobotInfo[] enemiesSwarming = rc.senseNearbyRobots(ourTowers[closestTower], 100, theirTeam);
if (enemiesSwarming != null && enemiesSwarming.length > 0) {
swarmingType = IntToRobotType(getMajorityRobotType(enemiesSwarming));
}
}
if (ratio <= 0.85) {
// Void heavy map
if (towerThreat >= 10) {
// Defensive Map
strategy = smuConstants.STRATEGY_DRONE_SWARM;
} else {
// Offensive Map
strategy = smuConstants.STRATEGY_DRONE_CONTAIN;
}
} else {
// Traversable Map
if (swarmingType == RobotType.SOLDIER) {
strategy = smuConstants.STRATEGY_TANKS_AND_LAUNCHERS;
} else if (swarmingType == RobotType.DRONE) {
strategy = smuConstants.STRATEGY_LAUNCHERS;
} else if (swarmingType == RobotType.TANK) {
strategy = smuConstants.STRATEGY_TANK_SWARM;
} else {
strategy = defaultStrategy;
}
}
} else {
RobotType containingType = IntToRobotType(rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED_BY));
if (containingType == RobotType.DRONE) {
strategy = smuConstants.STRATEGY_LAUNCHERS;
} else if (containingType == RobotType.TANK) {
strategy = smuConstants.STRATEGY_LAUNCHERS;
}
}
//STRATEGY_DRONE_CONTAIN = 1;
//STRATEGY_TANKS_AND_SOLDIERS = 2;
//STRATEGY_DRONE_SWARM = 3;
//STRATEGY_TANKS_AND_LAUNCHERS = 4;
//STRATEGY_LAUNCHERS = 5;
//STRATEGY_TANK_SWARM = 6;
//strategy = 1;
rc.broadcast(smuIndices.STRATEGY, strategy);
hasChosenStrategyPrior = true;
}
public void computeStrategy() throws GameActionException{
if (prevStrategy == strategy) {
return;
}
// [desiredNumOf, roundToBuild, roundToFinish]
int[] strategyAEROSPACELAB = new int[3];
int[] strategyBARRACKS = new int[3];
int[] strategyBASHER = new int[3];
int[] strategyBEAVER = new int[3];
int[] strategyCOMMANDER = new int[3];
int[] strategyCOMPUTER = new int[3];
int[] strategyDRONE = new int[3];
int[] strategyHANDWASHSTATION = new int[3];
int[] strategyHELIPAD = new int[3];
int[] strategyHQ = new int[3];
int[] strategyLAUNCHER = new int[3];
int[] strategyMINER = new int[3];
int[] strategyMINERFACTORY = new int[3];
int[] strategyMISSILE = new int[3];
int[] strategySOLDIER = new int[3];
int[] strategySUPPLYDEPOT = new int[3];
int[] strategyTANK = new int[3];
int[] strategyTANKFACTORY = new int[3];
int[] strategyTECHNOLOGYINSTITUTE = new int[3];
int[] strategyTOWER = new int[3];
int[] strategyTRAININGFIELD = new int[3];
if (strategy == smuConstants.STRATEGY_TANKS_AND_SOLDIERS) {
System.out.println("COMPUTE STRATEGY: Tanks and Soldiers");
strategyAEROSPACELAB = new int[] {0};
strategyBARRACKS = new int[] {100, 300, 650, 800};
strategyBASHER = new int[] {50, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 0};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {0, 0, 0};
strategyHANDWASHSTATION = new int[] {1850, 1860, 1870};
strategyHELIPAD = new int[] {0};
strategyHQ = new int[] {0};
strategyLAUNCHER = new int[] {0, 0, 0};
strategyMINER = new int[] {50, 1, 500};
strategyMINERFACTORY = new int[] {1, 200};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {120, 200, 1200};
// strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
strategySUPPLYDEPOT = new int[] {1000, 1400, 1500};
strategyTANK = new int[] {20, 1100, 1800};
strategyTANKFACTORY = new int[] {1000, 1200};
strategyTECHNOLOGYINSTITUTE = new int[] {0};
strategyTOWER = new int[] {0};
strategyTRAININGFIELD = new int[] {0};
} else if(strategy == smuConstants.STRATEGY_LAUNCHERS){
System.out.println("COMPUTE STRATEGY: Launchers");
strategyAEROSPACELAB = new int[] {800, 1000};
strategyBARRACKS = new int[] {4, 500, 1500};
strategyBASHER = new int[] {0, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 0};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {0, 0, 0};
strategyHANDWASHSTATION = new int[] {1850, 1860, 1870};
strategyHELIPAD = new int[] {1};
strategyHQ = new int[] {0};
strategyLAUNCHER = new int[] {20, 1100, 1700};
strategyMINER = new int[] {30, 1, 500};
strategyMINERFACTORY = new int[] {2, 1, 250};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {120, 200, 1200};
strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
strategyTANK = new int[] {0, 1100, 1800};
strategyTANKFACTORY = new int[] {0};
strategyTECHNOLOGYINSTITUTE = new int[] {0};
strategyTOWER = new int[] {0};
strategyTRAININGFIELD = new int[] {0};
} else if(strategy == smuConstants.STRATEGY_DRONE_CONTAIN) {
System.out.println("COMPUTE STRATEGY: Drone Contain");
strategyAEROSPACELAB = new int[] {0};
strategyBARRACKS = new int[] {0};
strategyBASHER = new int[] {0, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 100};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {50, 100, 1800};
strategyHANDWASHSTATION = new int[] {1850, 1860, 1870};
strategyHELIPAD = new int[] {1, 300};
strategyHQ = new int[] {0};
strategyLAUNCHER = new int[] {0, 1100, 1700};
strategyMINER = new int[] {20, 100, 500};
strategyMINERFACTORY = new int[] {100, 500};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {0, 200, 1200};
strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
strategyTANK = new int[] {0, 1100, 1800};
strategyTANKFACTORY = new int[] {0};
strategyTECHNOLOGYINSTITUTE = new int[] {0};
strategyTOWER = new int[] {0};
strategyTRAININGFIELD = new int[] {0};
} else if(strategy == smuConstants.STRATEGY_DRONE_SWARM) {
System.out.println("COMPUTE STRATEGY: Drone Swarm");
strategyAEROSPACELAB = new int[] {0};
strategyBARRACKS = new int[] {2, 500, 1500};
strategyBASHER = new int[] {0, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 0};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {120, 100, 1800};
strategyHANDWASHSTATION = new int[] {1850, 1860, 1870};
strategyHELIPAD = new int[] {1, 400};
strategyHQ = new int[] {0};
strategyLAUNCHER = new int[] {0, 1100, 1700};
strategyMINER = new int[] {30, 1, 500};
strategyMINERFACTORY = new int[] {2, 1, 250};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {25, 200, 1200};
strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
strategyTANK = new int[] {0, 0, 0};
strategyTANKFACTORY = new int[] {0};
strategyTECHNOLOGYINSTITUTE = new int[] {0};
strategyTOWER = new int[] {0};
strategyTRAININGFIELD = new int[] {0};
} else if(strategy == smuConstants.STRATEGY_TANK_SWARM) {
System.out.println("COMPUTE STRATEGY: Tank Swarm");
strategyAEROSPACELAB = new int[] {0};
strategyBARRACKS = new int[] {2, 100, 1500};
strategyBASHER = new int[] {0, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 0};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {0, 100, 1800};
strategyHANDWASHSTATION = new int[] {1850, 1860, 1870};
strategyHELIPAD = new int[] {0};
strategyHQ = new int[] {0};
strategyLAUNCHER = new int[] {0, 0, 0};
strategyMINER = new int[] {30, 1, 500};
strategyMINERFACTORY = new int[] {2, 1, 250};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {60, 200, 1200};
strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
strategyTANK = new int[] {100, 300, 1800};
strategyTANKFACTORY = new int[] {200, 400, 600, 800, 1000};
strategyTECHNOLOGYINSTITUTE = new int[] {0};
strategyTOWER = new int[] {0};
strategyTRAININGFIELD = new int[] {0};
} else if(strategy == smuConstants.STRATEGY_TANKS_AND_LAUNCHERS) {
System.out.println("COMPUTE STRATEGY: Tanks and Launchers");
strategyAEROSPACELAB = new int[] {1000, 1200};
strategyBARRACKS = new int[] {0, 100, 1500};
strategyBASHER = new int[] {0, 1200, 1700};
strategyBEAVER = new int[] {10, 0, 0};
strategyCOMMANDER = new int[] {0, 0, 0};
strategyCOMPUTER = new int[] {0, 0, 0};
strategyDRONE = new int[] {0, 100, 1800};
strategyHANDWASHSTATION = new int[] {1850, 1860, 1870};
strategyHELIPAD = new int[] {500};
strategyHQ = new int[] {0};
strategyLAUNCHER = new int[] {30, 1100, 1700};
strategyMINER = new int[] {30, 1, 500};
strategyMINERFACTORY = new int[] {2, 1, 250};
strategyMISSILE = new int[] {0, 0, 0};
strategySOLDIER = new int[] {0, 200, 1200};
strategySUPPLYDEPOT = new int[] {700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500};
strategyTANK = new int[] {100, 800, 1800};
strategyTANKFACTORY = new int[] {5, 500, 1400};
strategyTECHNOLOGYINSTITUTE = new int[] {0};
strategyTOWER = new int[] {0};
strategyTRAININGFIELD = new int[] {0};
}
//BE CAREFUL!!!
//TODO
int[][] strategyUnitArray = new int[][] {strategyBASHER, strategyBEAVER, strategyCOMMANDER, strategyCOMPUTER, strategyDRONE, strategyLAUNCHER, strategyMINER, strategyMISSILE, strategySOLDIER, strategyTANK};
int[] channelUnitArray = new int[] {smuIndices.channelBASHER, smuIndices.channelBEAVER, smuIndices.channelCOMMANDER, smuIndices.channelCOMPUTER, smuIndices.channelDRONE, smuIndices.channelLAUNCHER, smuIndices.channelMINER, smuIndices.channelMISSILE, smuIndices.channelSOLDIER, smuIndices.channelTANK};
int[][] strategyStructureArray = new int[][] {strategyAEROSPACELAB, strategyBARRACKS, strategyHANDWASHSTATION, strategyHELIPAD, strategyHQ, strategyMINERFACTORY, strategySUPPLYDEPOT, strategyTANKFACTORY, strategyTECHNOLOGYINSTITUTE, strategyTOWER, strategyTRAININGFIELD};
int[] channelStructureArray = new int[] {smuIndices.channelAEROSPACELAB, smuIndices.channelBARRACKS, smuIndices.channelHANDWASHSTATION, smuIndices.channelHELIPAD, smuIndices.channelHQ, smuIndices.channelMINERFACTORY, smuIndices.channelSUPPLYDEPOT, smuIndices.channelTANKFACTORY, smuIndices.channelTECHNOLOGYINSTITUTE, smuIndices.channelTOWER, smuIndices.channelTRAININGFIELD};
//Broadcast unit strategies
for (int i = 1; i < strategyUnitArray.length; i++) {
rc.broadcast(channelUnitArray[i] + 0, 0);
rc.broadcast(channelUnitArray[i] + 1, strategyUnitArray[i][0]);
rc.broadcast(channelUnitArray[i] + 2, strategyUnitArray[i][1]);
rc.broadcast(channelUnitArray[i] + 3, strategyUnitArray[i][2]);
}
//Broadcast structure strategies
for (int i = 1; i < strategyStructureArray.length; i++) {
rc.broadcast(channelStructureArray[i] + 0, 0);
if (strategyStructureArray[i].length > 1) {
rc.broadcast(channelStructureArray[i] + 1, strategyStructureArray[i].length);
for (int j = 0; j < strategyStructureArray[i].length; j++) {
rc.broadcast(channelStructureArray[i] + j + 2, strategyStructureArray[i][j]);
}
} else {
rc.broadcast(channelStructureArray[i] + 1, 0);
rc.broadcast(channelStructureArray[i] + 2, 0);
}
}
prevStrategy = strategy;
}
public void saveTeamMemory() {
long[] teamMemory = rc.getTeamMemory();;
int currRound = Clock.getRoundNum();
if (analyzedTowers && teamMemory[smuTeamMemoryIndices.PREV_MAP_TOWER_THREAT] == 0) {
rc.setTeamMemory(smuTeamMemoryIndices.PREV_MAP_TOWER_THREAT, towerThreat);;
}
if (isFinishedAnalyzing && teamMemory[smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT] == 0) {
rc.setTeamMemory(smuTeamMemoryIndices.PREV_MAP_VOID_TYPE_PERCENT, (long) (ratio * 100));
}
rc.setTeamMemory(smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + strategy, teamMemory[smuTeamMemoryIndices.NUM_ROUNDS_USING_STRATEGY_BASE + strategy] + 1);
if (teamMemory[smuTeamMemoryIndices.ROUND_OUR_HQ_ATTACKED] == 0) {
if (rc.getHealth() < RobotType.HQ.maxHealth) {
rc.setTeamMemory(smuTeamMemoryIndices.ROUND_OUR_HQ_ATTACKED, currRound);
}
}
int currNumTowers = rc.senseTowerLocations().length;
if (currNumTowers < numTowers) {
int towersIndex = 0;
while (teamMemory[smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + towersIndex] != 0) {
towersIndex++;
}
for (int i = 0; i < numTowers - currNumTowers; i++) {
rc.setTeamMemory(smuTeamMemoryIndices.ROUND_OUR_TOWER_DESTROYED_BASE + towersIndex + i, currRound);
}
numTowers = currNumTowers;
}
int currNumEnemyTowers = rc.senseEnemyTowerLocations().length;
if (currNumEnemyTowers < numEnemyTowers) {
int towersIndex = 0;
while (teamMemory[smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + towersIndex] != 0) {
towersIndex++;
}
for (int i = 0; i < numEnemyTowers - currNumEnemyTowers; i++) {
rc.setTeamMemory(smuTeamMemoryIndices.ROUND_THEIR_TOWER_DESTROYED_BASE + towersIndex + i, currRound);
}
numEnemyTowers = currNumEnemyTowers;
}
}
public RobotType checkContainment() throws GameActionException {
RobotInfo[] enemyRobotsContaining = rc.senseNearbyRobots(50, theirTeam);
if (enemyRobotsContaining.length > 4) {
rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.CURRENTLY_BEING_CONTAINED);
int robotTypeContaining = getMajorityRobotType(enemyRobotsContaining);
rc.broadcast(smuIndices.HQ_BEING_CONTAINED_BY, robotTypeContaining);
return IntToRobotType(robotTypeContaining);
} else {
rc.broadcast(smuIndices.HQ_BEING_CONTAINED, smuConstants.NOT_CURRENTLY_BEING_CONTAINED);
return null;
}
}
public int getMajorityRobotType(RobotInfo[] enemyRobots) {
int[] enemyRobotTypes = new int[22]; //Max RobotType -> int value + 1
int highestValue = 0;
int highestValueIndex = -1;
for (int i = 0; i < enemyRobots.length; i++) {
int robotType = RobotTypeToInt(enemyRobots[i].type);
enemyRobotTypes[robotType] = enemyRobotTypes[robotType] + 1;
if (enemyRobotTypes[robotType] > highestValue) {
highestValue = enemyRobotTypes[robotType];
highestValueIndex = i;
}
}
return highestValueIndex;
}
public void setRallyPoint() throws GameActionException {
MapLocation rallyPoint = null;
RobotType beingContained = checkContainment();
if (beingContained == null) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
MapLocation[] ourTowers = rc.senseTowerLocations();
if (ourTowers != null && ourTowers.length > 0) {
int closestTower = -1;
int closestDistanceToEnemyHQ = Integer.MAX_VALUE;
for (int i = 0; i < ourTowers.length; i++) {
int currDistanceToEnemyHQ = ourTowers[i].distanceSquaredTo(theirHQ);
if (currDistanceToEnemyHQ < closestDistanceToEnemyHQ) {
closestDistanceToEnemyHQ = currDistanceToEnemyHQ;
closestTower = i;
}
}
rallyPoint = ourTowers[closestTower].add(ourTowers[closestTower].directionTo(theirHQ), 2);
}
} else {
MapLocation[] enemyTowers = rc.senseEnemyTowerLocations();
if (enemyTowers == null || enemyTowers.length <= smuConstants.numTowersRemainingToAttackHQ) {
rallyPoint = rc.senseEnemyHQLocation();
} else {
rallyPoint = enemyTowers[0];
}
}
} else {
rallyPoint = getSecondBaseLocation();
if (rallyPoint != null) {
rallyPoint = rallyPoint.add(rallyPoint.directionTo(theirHQ), 8);
}
}
if (rallyPoint != null) {
rc.broadcast(smuIndices.RALLY_POINT_X, rallyPoint.x);
rc.broadcast(smuIndices.RALLY_POINT_Y, rallyPoint.y);
}
}
public void execute() throws GameActionException {
spawnOptimally();
setRallyPoint();
attackLeastHealthEnemyInRange();
transferSupplies();
if (!isFinishedAnalyzing) {
analyzeMap();
if (!analyzedTowers) {
analyzeTowers();
}
} else {
if (!analyzedPrevMatch) analyzePreviousMatch();
chooseStrategy();
try {
computeStrategy();
} catch (GameActionException e) {
e.printStackTrace();
}
}
if (analyzedPrevMatch) saveTeamMemory();
rc.yield();
}
}
//BEAVER
public static class Beaver extends BaseBot {
public MapLocation secondBase;
public Beaver(RobotController rc) {
super(rc);
Random rand = new Random(rc.getID());
if (rand.nextDouble() < smuConstants.percentBeaversToGoToSecondBase) {
secondBase = getSecondBaseLocation();
}
}
public void execute() throws GameActionException {
if (secondBase != null && rc.getLocation().distanceSquaredTo(secondBase) > 6) {
goToLocation(secondBase);
}
buildOptimally();
transferSupplies();
if (Clock.getRoundNum() > 400) defend();
if (rc.isCoreReady()) {
//mine
if (rc.senseOre(rc.getLocation()) > 0) {
rc.mine();
}
else {
moveOptimally();
}
}
rc.yield();
}
}
//MINERFACTORY
public static class Minerfactory extends BaseBot {
public Minerfactory(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//MINER
public static class Miner extends BaseBot {
public Miner(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
boolean inConvoy = false;
if (Clock.getRoundNum()>smuConstants.roundToFormSupplyConvoy
&& rc.readBroadcast(smuIndices.HQ_BEING_CONTAINED) != smuConstants.CURRENTLY_BEING_CONTAINED) {
inConvoy = formSupplyConvoy();
}
if (!inConvoy) {
if (!defend()) {
//System.out.println("Mining optimally");
mineOptimally();
}
} else if(!defendSelf()) {
if (rc.isCoreReady() && rc.senseOre(rc.getLocation()) > 0) {
rc.mine();
}
}
transferSupplies();
rc.yield();
}
}
//BARRACKS
public static class Barracks extends BaseBot {
public Barracks(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//SOLDIER
public static class Soldier extends BaseBot {
public Soldier(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (!defend()) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
contain();
} else {
moveToRallyPoint();
}
}
transferSupplies();
rc.yield();
}
}
//BASHER
public static class Basher extends BaseBot {
public Basher(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
contain();
} else {
moveToRallyPoint();
}
transferSupplies();
rc.yield();
}
}
//TANK
public static class Tank extends BaseBot {
public Tank(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (!defend()) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
contain();
} else {
moveToRallyPoint();
}
}
transferSupplies();
rc.yield();
}
}
//DRONE
public static class Drone extends BaseBot {
public Drone(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (!defendSelf()) {
if (Clock.getRoundNum() < smuConstants.roundToLaunchAttack) {
contain();
} else {
moveToRallyPoint();
}
}
transferSupplies();
rc.yield();
}
}
//TOWER
public static class Tower extends BaseBot {
public Tower(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
attackLeastHealthEnemyInRange();
rc.yield();
}
}
//SUPPLYDEPOT
public static class Supplydepot extends BaseBot {
public Supplydepot(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
rc.yield();
}
}
//HANDWASHSTATION
public static class Handwashstation extends BaseBot {
public Handwashstation(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
rc.yield();
}
}
//TANKFACTORY
public static class Tankfactory extends BaseBot {
public Tankfactory(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//HELIPAD
public static class Helipad extends BaseBot {
public Helipad(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//AEROSPACELAB
public static class Aerospacelab extends BaseBot {
public Aerospacelab(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
transferSupplies();
spawnOptimally();
rc.yield();
}
}
//LAUNCHER
public static class Launcher extends BaseBot {
public Launcher(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
boolean launched = false;
if (rc.getMissileCount() > 0) {
Direction targetDir = getDirOfLauncherTarget();
if (targetDir != null && rc.isWeaponReady()){
if (rc.canLaunch(targetDir)){
rc.launchMissile(targetDir);
launched = true;
}
}
}
if (!launched) {
contain();
}
rc.yield();
}
}
//MISSILE
public static class Missile extends BaseBot {
public Direction dirToTarget = null;
public Missile(RobotController rc) {
super(rc);
}
public void execute() throws GameActionException {
if (dirToTarget == null) {
RobotInfo[] nearbyRobots = rc.senseNearbyRobots(2, myTeam);
for (RobotInfo robot : nearbyRobots) {
if (robot.type == RobotType.LAUNCHER) {
dirToTarget = rc.getLocation().directionTo(robot.location).opposite();
}
}
// //System.out.println("dirToTarget: "+dirToTarget.name());
}
if (rc.isCoreReady() && rc.canMove(dirToTarget)){
rc.move(dirToTarget);
}
// if (getTeammatesInAttackRange().length <= 1 && getTeammatesInAttackRange().length > 4){
// rc.explode();
rc.yield();
}
}
} |
package org.commcare.resources.model;
import org.javarosa.core.services.storage.IMetaData;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapList;
import org.javarosa.core.util.externalizable.ExtWrapTagged;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
/**
* <p>
* Resources are records which resolve the location of data
* definitions (Suites, Xforms, Images, etc), and keep track
* of their status in the local environment. A Resource model
* knows where certain resources definitions can be found, what
* abstract resource those definitions are, a unique status about
* whether that resource is installed or locally available,
* and what installer it uses.</p>
*
* <p>
* Resources are immutable and should be treated as such. The
* abstract definition of a resource model is actually inside
* of the Resource Table, and changes should be committed to
* the table in order to change the resource.</p>
*
* <p>
* As resources are installed into the local environment, their
* status is updated to reflect that progress. The possible status
* enumerations are:
*
* <ul>
* <li>RESOURCE_STATUS_UNINITIALIZED - The resource has not yet been
* evaluated by the the resource table.</li>
* <li>RESOURCE_STATUS_LOCAL - The resource definition is locally present
* and ready to be read and installed</li>
* <li>RESOURCE_STATUS_INSTALLED - This resource is present locally and has
* been installed. It is ready to be used.</li>
* <li>RESOURCE_STATUS_UPGRADE - This resource definition has been read, and
* the resource is present locally and ready to install, but a previous
* version of it must be uninstalled first so its place can be taken.</li>
* <li>RESOURCE_STATUS_DELETE - This resource is no longer needed and should
* be uninstalled and its record removed.</li>
* </ul>
* </p>
*
* @author ctsims
*/
public class Resource implements Persistable, IMetaData {
public static final String META_INDEX_RESOURCE_ID = "ID";
public static final String META_INDEX_RESOURCE_GUID = "RGUID";
public static final String META_INDEX_PARENT_GUID = "PGUID";
public static final String META_INDEX_VERSION = "VERSION";
public static final int RESOURCE_AUTHORITY_LOCAL = 0;
public static final int RESOURCE_AUTHORITY_REMOTE = 1;
public static final int RESOURCE_AUTHORITY_CACHE = 2;
public static final int RESOURCE_AUTHORITY_RELATIVE = 4;
public static final int RESOURCE_AUTHORITY_TEMPORARY = 8;
// Completely Unprocessed
public static final int RESOURCE_STATUS_UNINITIALIZED = 0;
// Resource is in the local environment and ready to install
public static final int RESOURCE_STATUS_LOCAL = 1;
// Installed and ready to use
public static final int RESOURCE_STATUS_INSTALLED = 4;
// Resource is ready to replace an existing installed resource.
public static final int RESOURCE_STATUS_UPGRADE = 8;
// Resource is no longer needed in the local environment and can be
// completely removed
public static final int RESOURCE_STATUS_DELETE = 16;
// Resource has been "unstaged" (won't necessarily work as an app
// resource), but can be reverted to installed atomically.
public static final int RESOURCE_STATUS_UNSTAGED = 17;
// Resource is transitioning from installed to unstaged, and can be in any
// interstitial state.
public static final int RESOURCE_STATUS_INSTALL_TO_UNSTAGE = 18;
// Resource is transitioning from unstaged to being installed
public static final int RESOURCE_STATUS_UNSTAGE_TO_INSTALL = 19;
// Resource is transitioning from being upgraded to being installed
public static final int RESOURCE_STATUS_UPGRADE_TO_INSTALL = 20;
// Resource is transitioning from being installed to being upgraded
public static final int RESOURCE_STATUS_INSTALL_TO_UPGRADE = 21;
public static final int RESOURCE_VERSION_UNKNOWN = -2;
protected int recordId = -1;
protected int version;
protected int status;
protected String id;
protected Vector<ResourceLocation> locations;
protected ResourceInstaller initializer;
protected String guid;
// Not sure if we want this persisted just yet...
protected String parent;
protected String descriptor;
/**
* For serialization only
*/
public Resource() {
}
/**
* Creates a resource record identifying where a specific version of a resource
* can be located.
*
* @param version The version of the resource being defined.
* @param id A unique string identifying the abstract resource
* @param locations A set of locations from which this resource's definition
* can be retrieved. Note that this vector is copied and should not be changed
* after being passed in here.
*/
public Resource(int version, String id, Vector<ResourceLocation> locations, String descriptor) {
this.version = version;
this.id = id;
this.locations = locations;
this.guid = PropertyUtils.genGUID(25);
this.status = RESOURCE_STATUS_UNINITIALIZED;
this.descriptor = descriptor;
}
/**
* @return The locations where this resource's definition can be obtained.
*/
public Vector<ResourceLocation> getLocations() {
return locations;
}
/**
* @return An enumerated ID identifying the status of this resource on
* the local device.
*/
public int getStatus() {
return status;
}
/**
* @return The unique identifier for what resource this record offers the definition of.
*/
public String getResourceId() {
return id;
}
/**
* @return A GUID that the resource table uses to identify this definition.
*/
public String getRecordGuid() {
return guid;
}
/**
* @param parent The GUID of the resource record which has made this resource relevant
* for installation. This method should only be called by a resource table committing
* this resource record definition.
*/
protected void setParentId(String parent) {
this.parent = parent;
}
/**
* @return True if this resource's relevance is derived from another resource. False
* otherwise.
*/
public boolean hasParent() {
if (parent == null || "".equals(parent)) {
return false;
} else {
return true;
}
}
/**
* @return The GUID of the resource record which has made this resource relevant
* for installation. This method should only be called by a resource table committing
* this resource record definition.
*/
public String getParentId() {
return parent;
}
/**
* @return The version of the resource that this record defines.
*/
public int getVersion() {
return version;
}
/**
* @param version The version of the resource that this record defines. Can only be used
* to set the version if the current version is RESOURCE_VERSION_UNKOWN.
*/
protected void setVersion(int version) {
if (this.version == Resource.RESOURCE_VERSION_UNKNOWN) {
this.version = version;
}
}
/**
* @param initializer Associates a ResourceInstaller with this resource record. This method
* should only be called by a resource table committing this resource record definition.
*/
protected void setInstaller(ResourceInstaller initializer) {
this.initializer = initializer;
}
/**
* @return The installer which should be used to install the resource for this record.
*/
public ResourceInstaller getInstaller() {
return initializer;
}
/**
* @param status The current status of this resource. Should only be called by the resource
* table.
*/
protected void setStatus(int status) {
this.status = status;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.services.storage.Persistable#getID()
*/
public int getID() {
return recordId;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.services.storage.Persistable#setID(int)
*/
public void setID(int ID) {
recordId = ID;
}
/**
* @param peer A resource record which defines the same resource as this record.
* @return True if this record defines a newer version of the same resource as
* peer, or if this resource generally is suspected to obsolete peer (if, for
* instance this resource's version is yet unknown it will be assumed that it
* is newer until it is.)
*/
public boolean isNewer(Resource peer) {
if (version == RESOURCE_VERSION_UNKNOWN) {
return true;
} else if (!peer.id.equals(this.id)) {
return false;
} else {
return this.version > peer.getVersion();
}
}
/**
* Take on all identifiers from the incoming
* resouce, so as to replace it in a different table.
*/
public void mimick(Resource source) {
this.guid = source.guid;
this.id = source.id;
this.recordId = source.recordId;
this.descriptor = source.descriptor;
}
public String getDescriptor() {
if (descriptor == null) {
return id;
} else {
return descriptor;
}
}
/*
* (non-Javadoc)
* @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory)
*/
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
this.recordId = ExtUtil.readInt(in);
this.version = ExtUtil.readInt(in);
this.id = ExtUtil.readString(in);
this.guid = ExtUtil.readString(in);
this.status = ExtUtil.readInt(in);
this.parent = ExtUtil.nullIfEmpty(ExtUtil.readString(in));
locations = (Vector<ResourceLocation>)ExtUtil.read(in, new ExtWrapList(ResourceLocation.class), pf);
this.initializer = (ResourceInstaller)ExtUtil.read(in, new ExtWrapTagged(), pf);
this.descriptor = ExtUtil.nullIfEmpty(ExtUtil.readString(in));
}
/*
* (non-Javadoc)
* @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream)
*/
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.writeNumeric(out, recordId);
ExtUtil.writeNumeric(out, version);
ExtUtil.writeString(out, id);
ExtUtil.writeString(out, guid);
ExtUtil.writeNumeric(out, status);
ExtUtil.writeString(out, ExtUtil.emptyIfNull(parent));
ExtUtil.write(out, new ExtWrapList(locations));
ExtUtil.write(out, new ExtWrapTagged(initializer));
ExtUtil.writeString(out, ExtUtil.emptyIfNull(descriptor));
}
/*
* (non-Javadoc)
* @see org.javarosa.core.services.storage.IMetaData#getMetaData()
*/
public Hashtable getMetaData() {
Hashtable md = new Hashtable();
String[] fields = getMetaDataFields();
for (int i = 0; i < fields.length; ++i) {
md.put(fields[i], getMetaData(fields[i]));
}
return md;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.services.storage.IMetaData#getMetaData(java.lang.String)
*/
public Object getMetaData(String fieldName) {
if (fieldName.equals(META_INDEX_RESOURCE_ID)) {
return id;
} else if (fieldName.equals(META_INDEX_RESOURCE_GUID)) {
return guid;
} else if (fieldName.equals(META_INDEX_PARENT_GUID)) {
return parent == null ? "" : parent;
} else if (fieldName.equals(META_INDEX_VERSION)) {
return new Integer(version);
}
throw new IllegalArgumentException("No Field w/name " + fieldName + " is relevant for resources");
}
/*
* (non-Javadoc)
* @see org.javarosa.core.services.storage.IMetaData#getMetaDataFields()
*/
public String[] getMetaDataFields() {
return new String[]{META_INDEX_RESOURCE_ID, META_INDEX_RESOURCE_GUID, META_INDEX_PARENT_GUID, META_INDEX_VERSION};
}
public boolean isDirty() {
return (getStatus() == Resource.RESOURCE_STATUS_INSTALL_TO_UNSTAGE ||
getStatus() == Resource.RESOURCE_STATUS_INSTALL_TO_UPGRADE ||
getStatus() == Resource.RESOURCE_STATUS_UNSTAGE_TO_INSTALL ||
getStatus() == Resource.RESOURCE_STATUS_UPGRADE_TO_INSTALL);
}
public static int getCleanFlag(int dirtyFlag) {
// We actually will just push it forward by default, since this method
// is used by things that can only be in the right state
if (dirtyFlag == Resource.RESOURCE_STATUS_INSTALL_TO_UNSTAGE) {
return RESOURCE_STATUS_UNSTAGED;
} else if (dirtyFlag == Resource.RESOURCE_STATUS_INSTALL_TO_UPGRADE) {
return RESOURCE_STATUS_UPGRADE;
} else if (dirtyFlag == Resource.RESOURCE_STATUS_UNSTAGE_TO_INSTALL) {
return RESOURCE_STATUS_INSTALLED;
} else if (dirtyFlag == Resource.RESOURCE_STATUS_UPGRADE_TO_INSTALL) {
return RESOURCE_STATUS_INSTALLED;
}
return -1;
}
} |
package io.scif.io;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.service.AbstractService;
import org.scijava.service.Service;
/**
* Default service for working with the {@link java.nio} package, particularly
* NIO {@link ByteBuffer} objects.
*
* @author Chris Allan
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public class DefaultNIOService extends AbstractService implements NIOService {
// -- Fields --
@Parameter
private LogService log;
/** Whether or not we are to use memory mapped I/O. */
private final boolean useMappedByteBuffer = Boolean.parseBoolean(System
.getProperty("mappedBuffers"));
// -- NIOService API methods --
@Override
public ByteBuffer allocate(final FileChannel channel, final MapMode mapMode,
final long bufferStartPosition, final int newSize) throws IOException
{
log.debug("NIO: allocate: mapped=" + useMappedByteBuffer + ", start=" +
bufferStartPosition + ", size=" + newSize);
if (useMappedByteBuffer) {
return allocateMappedByteBuffer(channel, mapMode, bufferStartPosition,
newSize);
}
return allocateDirect(channel, bufferStartPosition, newSize);
}
// -- Helper methods --
/**
* Allocates memory and copies the desired file data into it.
*
* @param channel File channel to allocate or map byte buffers from.
* @param bufferStartPosition The absolute position of the start of the
* buffer.
* @param newSize The buffer size.
* @return A newly allocated NIO byte buffer.
* @throws IOException If there is an issue aligning or allocating the buffer.
*/
private ByteBuffer allocateDirect(final FileChannel channel,
final long bufferStartPosition, final int newSize) throws IOException
{
final ByteBuffer buffer = ByteBuffer.allocate(newSize);
channel.read(buffer, bufferStartPosition);
return buffer;
}
/**
* Memory maps the desired file data into memory.
*
* @param channel File channel to allocate or map byte buffers from.
* @param mapMode The map mode. Required but only used if memory mapped I/O is
* to occur.
* @param bufferStartPosition The absolute position of the start of the
* buffer.
* @param newSize The buffer size.
* @return A newly mapped NIO byte buffer.
* @throws IOException If there is an issue mapping, aligning or allocating
* the buffer.
*/
private ByteBuffer allocateMappedByteBuffer(final FileChannel channel,
final MapMode mapMode, final long bufferStartPosition, final int newSize)
throws IOException
{
return channel.map(mapMode, bufferStartPosition, newSize);
}
} |
package org.commcare.session;
import org.commcare.suite.model.EntityDatum;
import org.commcare.suite.model.SessionDatum;
import org.commcare.suite.model.Text;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.xpath.XPathException;
import java.util.Vector;
/**
* Performs all logic involved in polling the current CommCareSession to determine what information
* or action is needed by the session, and then sends a signal to the registered
* SessionNavigationResponder to indicate what should be done to get it (or if an error occurred)
*
* @author amstone
*/
public class SessionNavigator {
// Result codes to be interpreted by the SessionNavigationResponder
public static final int ASSERTION_FAILURE = 0;
public static final int NO_CURRENT_FORM = 1;
public static final int START_FORM_ENTRY = 2;
public static final int GET_COMMAND = 3;
public static final int START_ENTITY_SELECTION = 4;
public static final int LAUNCH_CONFIRM_DETAIL = 5;
public static final int XPATH_EXCEPTION_THROWN = 6;
public static final int START_SYNC_REQUEST = 7;
public static final int PROCESS_QUERY_REQUEST = 8;
public static final int REPORT_CASE_AUTOSELECT = 9;
private final SessionNavigationResponder responder;
private CommCareSession currentSession;
private EvaluationContext ec;
private TreeReference currentAutoSelectedCase;
private XPathException thrownException;
public SessionNavigator(SessionNavigationResponder r) {
this.responder = r;
}
private void sendResponse(int resultCode) {
responder.processSessionResponse(resultCode);
}
public TreeReference getCurrentAutoSelection() {
return this.currentAutoSelectedCase;
}
public XPathException getCurrentException() {
return this.thrownException;
}
/**
* Polls the CommCareSession to determine what information is needed in order to proceed with
* the next entry step in the session, and then executes the action to get that info, OR
* proceeds with trying to enter the form if no more info is needed
*/
public void startNextSessionStep() {
currentSession = responder.getSessionForNavigator();
ec = responder.getEvalContextForNavigator();
String needed = currentSession.getNeededData(ec);
if (needed == null) {
readyToProceed();
} else if (needed.equals(SessionFrame.STATE_COMMAND_ID)) {
sendResponse(GET_COMMAND);
} else if (needed.equals(SessionFrame.STATE_SYNC_REQUEST)) {
sendResponse(START_SYNC_REQUEST);
} else if (needed.equals(SessionFrame.STATE_QUERY_REQUEST)) {
sendResponse(PROCESS_QUERY_REQUEST);
} else if (needed.equals(SessionFrame.STATE_DATUM_VAL)) {
handleGetDatum();
} else if (needed.equals(SessionFrame.STATE_DATUM_COMPUTED)) {
handleCompute();
}
}
private void readyToProceed() {
Text text = currentSession.getCurrentEntry().getAssertions().getAssertionFailure(ec);
if (text != null) {
// We failed one of our assertions
sendResponse(ASSERTION_FAILURE);
}
else if (currentSession.getForm() == null) {
sendResponse(NO_CURRENT_FORM);
} else {
sendResponse(START_FORM_ENTRY);
}
}
private void handleGetDatum() {
TreeReference autoSelection = getAutoSelectedCase();
if (autoSelection == null) {
sendResponse(START_ENTITY_SELECTION);
} else {
sendResponse(REPORT_CASE_AUTOSELECT);
this.currentAutoSelectedCase = autoSelection;
handleAutoSelect();
}
}
private void handleAutoSelect() {
SessionDatum selectDatum = currentSession.getNeededDatum();
if (selectDatum instanceof EntityDatum) {
EntityDatum entityDatum = (EntityDatum)selectDatum;
if (entityDatum.getLongDetail() == null) {
// No confirm detail defined for this entity select, so just set the case id right away
// and proceed
String autoSelectedCaseId = EntityDatum.getCaseIdFromReference(
currentAutoSelectedCase, entityDatum, ec);
currentSession.setDatum(entityDatum.getDataId(), autoSelectedCaseId);
startNextSessionStep();
} else {
sendResponse(LAUNCH_CONFIRM_DETAIL);
}
}
}
/**
* Returns the auto-selected case for the next needed datum, if there should be one.
* Returns null if auto selection is not enabled, or if there are multiple available cases
* for the datum (and therefore auto-selection should not be used).
*/
private TreeReference getAutoSelectedCase() {
SessionDatum selectDatum = currentSession.getNeededDatum();
if (selectDatum instanceof EntityDatum) {
EntityDatum entityDatum = (EntityDatum)selectDatum;
if (entityDatum.isAutoSelectEnabled()) {
Vector<TreeReference> entityListElements = ec.expandReference(entityDatum.getNodeset());
if (entityListElements.size() == 1) {
return entityListElements.elementAt(0);
}
}
}
return null;
}
private void handleCompute() {
try {
currentSession.setComputedDatum(ec);
} catch (XPathException e) {
this.thrownException = e;
sendResponse(XPATH_EXCEPTION_THROWN);
return;
}
startNextSessionStep();
}
public void stepBack() {
currentSession.stepBack(ec);
}
} |
package thredds.servlet;
import java.io.*;
import java.util.*;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.FactoryConfigurationError;
import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;
import ucar.unidata.util.StringUtil;
import ucar.unidata.io.FileCache;
import thredds.catalog.XMLEntityResolver;
public class ServletUtil {
static private org.slf4j.Logger log;
static private boolean isDebugInit = false;
static private boolean isLogInit = false;
public static final String CONTENT_TEXT = "text/plain; charset=iso-8859-1";
/**
* Initialize THREDDS servlet debugging.
*
* @see thredds.servlet.Debug
*
* @param servlet the servlet on which to initialze debugging.
*/
public static void initDebugging(HttpServlet servlet) {
if (isDebugInit) return;
isDebugInit = true;
ServletContext webapp = servlet.getServletContext();
String debugOn = webapp.getInitParameter("DebugOn");
if (debugOn != null) {
StringTokenizer toker = new StringTokenizer(debugOn);
while (toker.hasMoreTokens())
Debug.set(toker.nextToken(), true);
}
}
/**
* Initialize logging for the web application context in which the given
* servlet is running. Two types of logging are supported:
* <p/>
* 1) Regular logging using the SLF4J API.
* 2) Access logging which can write Apache common logging format logs,
* use the ServletUtil.logServerSetup(String) method.
* <p/>
* The log directory is determined by the servlet containers content
* directory. The configuration of logging is controlled by the log4j.xml
* file. The log4j.xml file needs to setup at least two loggers: "thredds";
* and "threddsAccessLogger"
*
* @param servlet - the servlet.
*/
public static void initLogging(HttpServlet servlet) {
// Initialize logging if not already done.
if (isLogInit)
return;
System.out.println("+++ServletUtil.initLogging");
ServletContext servletContext = servlet.getServletContext();
// set up the log path
String logPath = getContentPath(servlet) + "logs";
File logPathFile = new File(logPath);
if (!logPathFile.exists()) {
if (!logPathFile.mkdirs()) {
throw new RuntimeException("Creation of logfile directory failed." + logPath);
}
}
// read in Log4J config file
System.setProperty("logdir", logPath); // variable substitution
try {
String log4Jconfig = servletContext.getInitParameter("log4j-init-file");
if (log4Jconfig == null)
log4Jconfig = getRootPath(servlet) + "WEB-INF/log4j.xml";
DOMConfigurator.configure(log4Jconfig);
System.out.println("+++Log4j configured from file " + log4Jconfig);
} catch (FactoryConfigurationError t) {
t.printStackTrace();
}
/* read in user defined Log4J file
String log4Jconfig = ServletUtil.getContentPath(servlet) + "log4j.xml";
File test = new File(log4Jconfig);
if (test.exists())
try {
DOMConfigurator.configure(log4Jconfig);
System.out.println("+++Log4j configured from file "+log4Jconfig);
} catch (FactoryConfigurationError t) {
t.printStackTrace();
} */
log = org.slf4j.LoggerFactory.getLogger(ServletUtil.class);
isLogInit = true;
}
/**
* Gather information from the given HttpServletRequest for inclusion in both
* regular logging messages and THREDDS access log messages. Call this method
* at start of each doXXX() method (e.g., doGet(), doPut()) in any servlet
* you implement.
* <p/>
* Use the SLF4J API to log a regular logging messages. Use the
* logServerAccess() method to log a THREDDS access log message.
* <p/>
* This method gathers the following information:
* 1) "ID" - an identifier for the current thread;
* 2) "host" - the remote host (IP address or host name);
* 3) "userid" - the id of the remote user;
* 4) "startTime" - the system time in millis when this request is started (i.e., when this method is called); and
* 5) "request" - The HTTP request, e.g., "GET /index.html HTTP/1.1".
* <p/>
* The appearance of the regular log messages and the THREDDS access log
* messages are controlled in the log4j.xml configuration file. For the log
* messages to look like an Apache server "common" log message, use the
* following log4j pattern:
* <p/>
* "%X{host} %X{ident} %X{userid} [%d{dd/MMM/yyyy:HH:mm:ss}] %X{request} %m%n"
*
* @param req the current HttpServletRequest.
*/
public static void logServerAccessSetup(HttpServletRequest req) {
HttpSession session = req.getSession(false);
// Setup context.
synchronized (ServletUtil.class) {
MDC.put("ID", Long.toString(++logServerAccessId));
}
MDC.put("host", req.getRemoteHost());
MDC.put("ident", (session == null) ? "-" : session.getId());
MDC.put("userid", req.getRemoteUser() != null ? req.getRemoteUser() : "-");
MDC.put("startTime", System.currentTimeMillis());
String query = req.getQueryString();
query = (query != null) ? "?" + query : "";
StringBuffer request = new StringBuffer();
request.append("\"").append(req.getMethod()).append(" ")
.append(req.getRequestURI()).append(query)
.append(" ").append(req.getProtocol()).append("\"");
MDC.put("request", request.toString());
log.info("Remote host: " + req.getRemoteHost() + " - Request: " + request);
}
/**
* Gather current thread information for inclusion in regular logging
* messages. Call this method only for non-request servlet activities, e.g.,
* during the init() or destroy().
* <p/>
* Use the SLF4J API to log a regular logging messages.
* <p/>
* This method gathers the following information:
* 1) "ID" - an identifier for the current thread; and
* 2) "startTime" - the system time in millis when this method is called.
* <p/>
* The appearance of the regular log messages are controlled in the
* log4j.xml configuration file.
*
* @param msg - the information log message logged when this method finishes.
*/
public static void logServerSetup(String msg) {
// Setup context.
synchronized (ServletUtil.class) {
MDC.put("ID", Long.toString(++logServerAccessId));
}
MDC.put("startTime", System.currentTimeMillis());
log.info(msg);
}
private static volatile long logServerAccessId = 0;
/**
* Write log entry to THREDDS access log.
*
* @param resCode - the result code for this request.
* @param resSizeInBytes - the number of bytes returned in this result, -1 if unknown.
*/
public static void logServerAccess(int resCode, long resSizeInBytes) {
long endTime = System.currentTimeMillis();
long startTime = (Long) MDC.get("startTime");
long duration = endTime - startTime;
log.info("Request Completed - " + resCode + " - " + resSizeInBytes + " - " + duration);
}
/**
* Return the real path on the servers file system that corresponds to the root document ("/") on the given servlet.
*
* @param servlet the HttpServlet whose root path is to be mapped.
* @return the real path on the servers file system that corresponds to the root document ("/") on the given servlet.
*/
public static String getRootPath(HttpServlet servlet) {
ServletContext sc = servlet.getServletContext();
String rootPath = sc.getRealPath("/");
rootPath = rootPath.replace('\\', '/');
return rootPath;
}
/**
* Return the real path on the servers file system that corresponds to the given path on the given servlet.
*
* @param servlet the HttpServlet whose path is to be mapped.
* @param path the virtual/URL path to map to the servers file system.
* @return the real path on the servers file system that corresponds to the given path on the given servlet.
*/
public static String getPath(HttpServlet servlet, String path) {
ServletContext sc = servlet.getServletContext();
String spath = sc.getRealPath(path);
spath = spath.replace('\\', '/');
return spath;
}
/* public static String getRootPathUrl(HttpServlet servlet) {
String rootPath = getRootPath( servlet);
rootPath = StringUtil.replace(rootPath, ' ', "%20");
return rootPath;
} */
private static String contextPath = null;
/**
* Return the context path for the given servlet.
* Note - ToDo: Why not just use ServletContext.getServletContextName()?
*
* @param servlet the HttpServlet whose context path is returned.
* @return the context path for the given servlet.
*/
public static String getContextPath(HttpServlet servlet) {
if (contextPath == null) {
ServletContext servletContext = servlet.getServletContext();
String tmpContextPath = servletContext.getInitParameter("ContextPath"); // cannot be overridden in the ThreddsConfig file
if (tmpContextPath == null) tmpContextPath = "thredds";
contextPath = "/" + tmpContextPath;
}
return contextPath;
}
private static String contentPath = null;
/**
* Return the content path for the given servlet.
*
* @param servlet the HttpServlet whose content path is returned.
* @return the content path for the given servlet.
*/
public static String getContentPath(HttpServlet servlet) {
if (contentPath == null) {
String tmpContentPath = "../../content" + getContextPath(servlet) + "/";
File cf = new File(getRootPath(servlet) + tmpContentPath);
try {
contentPath = cf.getCanonicalPath() + "/";
contentPath = contentPath.replace('\\', '/');
} catch (IOException e) {
e.printStackTrace();
}
}
return contentPath;
}
/**
* Return the default/initial content path for the given servlet. The
* content of which is copied to the content path when the web app
* is first installed.
*
* @param servlet the HttpServlet whose initial content path is returned.
* @return the default/initial content path for the given servlet.
*/
public static String getInitialContentPath(HttpServlet servlet) {
return getRootPath(servlet) + "WEB-INF/initialContent/";
}
/**
* Return the file path dealing with leading and trailing path
* seperators (which must be a slash ("/")) for the given directory
* and file paths.
*
* Note: Dealing with path strings is fragile.
* ToDo: Switch from using path strings to java.io.Files.
*
* @param dirPath the directory path.
* @param filePath the file path.
* @return a full file path with the given directory and file paths.
*/
public static String formFilename(String dirPath, String filePath) {
if ((dirPath == null) || (filePath == null))
return null;
if (filePath.startsWith("/"))
filePath = filePath.substring(1);
return dirPath.endsWith("/") ? dirPath + filePath : dirPath + "/" + filePath;
}
/**
* Handle a request for a raw/static file (i.e., not a catalog or dataset request).
* <p/>
* Look in the content (user) directory then the root (distribution) directory
* for a file that matches the given path and, if found, return it as the
* content of the HttpServletResponse. If the file is forbidden (i.e., the
* path contains a "..", "WEB-INF", or "META-INF" directory), send a
* HttpServletResponse.SC_FORBIDDEN response. If no file matches the request
* (including an "index.html" file if the path ends in "/"), send an
* HttpServletResponse.SC_NOT_FOUND..
* <p/>
* <ol>
* <li>Make sure the path does not contain ".." directories. </li>
* <li>Make sure the path does not contain "WEB-INF" or "META-INF". </li>
* <li>Check for requested file in the content directory
* (if the path is a directory, make sure the path ends with "/" and
* check for an "index.html" file). </li>
* <li>Check for requested file in the root directory
* (if the path is a directory, make sure the path ends with "/" and
* check for an "index.html" file).</li>
* </ol
*
* @param path the requested path
* @param servlet the servlet handling the request
* @param req the HttpServletRequest
* @param res the HttpServletResponse
* @throws IOException if can't complete request due to IO problems.
*/
public static void handleRequestForRawFile(String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res)
throws IOException {
// Don't allow ".." directories in path.
if (path.indexOf("/../") != -1
|| path.equals("..")
|| path.startsWith("../")
|| path.endsWith("/..")) {
res.sendError(HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"..\" directory.");
ServletUtil.logServerAccess(HttpServletResponse.SC_FORBIDDEN, -1);
return;
}
// Don't allow access to WEB-INF or META-INF directories.
String upper = path.toUpperCase();
if (upper.indexOf("WEB-INF") != -1
|| upper.indexOf("META-INF") != -1) {
res.sendError(HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"WEB-INF\" or \"META-INF\".");
ServletUtil.logServerAccess(HttpServletResponse.SC_FORBIDDEN, -1);
return;
}
// Find a regular file
File regFile = null;
// Look in content directory for regular file.
File cFile = new File(ServletUtil.formFilename(getContentPath(servlet), path));
if (cFile.exists()) {
if (cFile.isDirectory()) {
if (!path.endsWith("/")) {
String newPath = req.getRequestURL().append("/").toString();
ServletUtil.sendPermanentRedirect(newPath, req, res);
}
// If request path is a directory, check for index.html file.
cFile = new File(cFile, "index.html");
if (cFile.exists() && !cFile.isDirectory())
regFile = cFile;
}
// If not a directory, use this file.
else
regFile = cFile;
}
if (regFile == null) {
// Look in root directory.
File rFile = new File(ServletUtil.formFilename(getRootPath(servlet), path));
if (rFile.exists()) {
if (rFile.isDirectory()) {
if (!path.endsWith("/")) {
String newPath = req.getRequestURL().append("/").toString();
ServletUtil.sendPermanentRedirect(newPath, req, res);
}
rFile = new File(rFile, "index.html");
if (rFile.exists() && !rFile.isDirectory())
regFile = rFile;
} else
regFile = rFile;
}
}
if (regFile == null) {
res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404
ServletUtil.logServerAccess(HttpServletResponse.SC_NOT_FOUND, -1);
return;
}
ServletUtil.returnFile(servlet, req, res, regFile, null);
}
/**
* Handle an explicit request for a content directory file (path must start
* with "/content/".
* <p/>
* Note: As these requests will show the configuration files for the server,
* these requests should be covered by security constraints.
* <p/>
* <ol>
* <li>Make sure the path does not contain ".." directories. </li>
* <li>Check for the requested file in the content directory. </li>
* </ol
*
* @param path the requested path (must start with "/content/")
* @param servlet the servlet handling the request
* @param req the HttpServletRequest
* @param res the HttpServletResponse
* @throws IOException if can't complete request due to IO problems.
*/
public static void handleRequestForContentFile(String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res)
throws IOException {
handleRequestForContentOrRootFile("/content/", path, servlet, req, res);
}
/**
* Handle an explicit request for a root directory file (path must start
* with "/root/".
* <p/>
* Note: As these requests will show the configuration files for the server,
* these requests should be covered by security constraints.
* <p/>
* <ol>
* <li>Make sure the path does not contain ".." directories. </li>
* <li>Check for the requested file in the root directory. </li>
* </ol
*
* @param path the requested path (must start with "/root/")
* @param servlet the servlet handling the request
* @param req the HttpServletRequest
* @param res the HttpServletResponse
* @throws IOException if can't complete request due to IO problems.
*/
public static void handleRequestForRootFile(String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res)
throws IOException {
handleRequestForContentOrRootFile("/root/", path, servlet, req, res);
}
/**
* Convenience routine used by handleRequestForContentFile()
* and handleRequestForRootFile().
*
* @param pathPrefix
* @param path
* @param servlet
* @param req
* @param res
* @throws IOException
*/
private static void handleRequestForContentOrRootFile(String pathPrefix, String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res)
throws IOException {
if (!pathPrefix.equals("/content/")
&& !pathPrefix.equals("/root/")) {
log.error("handleRequestForContentFile(): The path prefix <" + pathPrefix + "> must be \"/content/\" or \"/root/\".");
throw new IllegalArgumentException("Path prefix must be \"/content/\" or \"/root/\".");
}
if (!path.startsWith(pathPrefix)) {
log.error("handleRequestForContentFile(): path <" + path + "> must start with \"" + pathPrefix + "\".");
throw new IllegalArgumentException("Path must start with \"" + pathPrefix + "\".");
}
// Don't allow ".." directories in path.
if (path.indexOf("/../") != -1
|| path.equals("..")
|| path.startsWith("../")
|| path.endsWith("/..")) {
res.sendError(HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"..\" directory.");
ServletUtil.logServerAccess(HttpServletResponse.SC_FORBIDDEN, -1);
return;
}
// Find the requested file.
File file = new File(ServletUtil.formFilename(getContentPath(servlet), path.substring(pathPrefix.length() - 1)));
if (file.exists()) {
// Do not allow request for a directory.
if (file.isDirectory()) {
if (!path.endsWith("/")) {
String redirectPath = req.getRequestURL().append("/").toString();
ServletUtil.sendPermanentRedirect(redirectPath, req, res);
return;
}
HtmlWriter.getInstance().writeDirectory(res, file, path);
return;
}
// Return the requested file.
ServletUtil.returnFile(servlet, req, res, file, null);
} else {
// Requested file not found.
ServletUtil.logServerAccess(HttpServletResponse.SC_NOT_FOUND, -1);
res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404
}
}
/**
* Send a permanent redirect (HTTP status 301 "Moved Permanently") response
* with the given target path.
* <p/>
* The given target path may be relative or absolute. If it is relative, it
* will be resolved against the request URL.
*
* @param targetPath the path to which the client is redirected.
* @param req the HttpServletRequest
* @param res the HttpServletResponse
* @throws IOException if can't write the response.
*/
public static void sendPermanentRedirect(String targetPath, HttpServletRequest req, HttpServletResponse res)
throws IOException {
// Absolute URL needed so resolve the target path against the request URL.
URI uri;
try {
uri = new URI(req.getRequestURL().toString());
}
catch (URISyntaxException e) {
log.error("sendPermanentRedirect(): Bad syntax on request URL <" + req.getRequestURL() + ">.", e);
ServletUtil.logServerAccess(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0);
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
String absolutePath = uri.resolve(targetPath).toString();
absolutePath = res.encodeRedirectURL(absolutePath);
res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
res.addHeader("Location", absolutePath);
String title = "Permanently Moved - 301";
String body = new StringBuffer()
.append("<p>")
.append("The requested URL <").append(req.getRequestURL())
.append("> has been permanently moved (HTTP status code 301).")
.append(" Instead, please use the following URL: <a href=\"").append(absolutePath).append("\">").append(absolutePath).append("</a>.")
.append("</p>")
.toString();
String htmlResp = new StringBuffer()
.append(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag())
.append("<head><title>")
.append(title)
.append("</title></head><body>")
.append("<h1>").append(title).append("</h1>")
.append(body)
.append("</body></html>")
.toString();
ServletUtil.logServerAccess(HttpServletResponse.SC_MOVED_PERMANENTLY, htmlResp.length());
// Write the catalog out.
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.print(htmlResp);
out.flush();
}
/**
* Write a file to the response stream.
*
* @param servlet called from here
* @param contentPath file root path
* @param path file path reletive to the root
* @param req the request
* @param res the response
* @param contentType content type, or null
* @throws IOException on write error
*/
public static void returnFile(HttpServlet servlet, String contentPath, String path,
HttpServletRequest req, HttpServletResponse res, String contentType) throws IOException {
String filename = ServletUtil.formFilename(contentPath, path);
log.debug("returnFile(): returning file <" + filename + ">.");
// No file, nothing to view
if (filename == null) {
ServletUtil.logServerAccess(HttpServletResponse.SC_NOT_FOUND, 0);
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// dontallow ..
if (filename.indexOf("..") != -1) {
ServletUtil.logServerAccess(HttpServletResponse.SC_FORBIDDEN, 0);
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// dont allow access to WEB-INF or META-INF
String upper = filename.toUpperCase();
if (upper.indexOf("WEB-INF") != -1 || upper.indexOf("META-INF") != -1) {
ServletUtil.logServerAccess(HttpServletResponse.SC_FORBIDDEN, 0);
res.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
returnFile(servlet, req, res, new File(filename), contentType);
}
/**
* Write a file to the response stream.
*
* @param servlet called from here
* @param req the request
* @param res the response
* @param file to serve
* @param contentType content type, or null
* @throws IOException on write error
*/
public static void returnFile(HttpServlet servlet, HttpServletRequest req, HttpServletResponse res, File file, String contentType)
throws IOException {
// No file, nothing to view
if (file == null) {
ServletUtil.logServerAccess(HttpServletResponse.SC_BAD_REQUEST, 0);
res.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// check that it exists
if (!file.exists()) {
ServletUtil.logServerAccess(HttpServletResponse.SC_NOT_FOUND, 0);
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// not a directory
if (!file.isFile()) {
ServletUtil.logServerAccess(HttpServletResponse.SC_BAD_REQUEST, 0);
res.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// Set the type of the file
String filename = file.getPath();
if (null == contentType) {
if (filename.endsWith(".html"))
contentType = "text/html; charset=iso-8859-1";
else if (filename.endsWith(".xml"))
contentType = "text/xml; charset=iso-8859-1";
else if (filename.endsWith(".txt") || (filename.endsWith(".log")))
contentType = CONTENT_TEXT;
else if (filename.indexOf(".log.") > 0)
contentType = CONTENT_TEXT;
else if (filename.endsWith(".nc"))
contentType = "application/x-netcdf";
else
contentType = servlet.getServletContext().getMimeType(filename);
if (contentType == null) contentType = "application/octet-stream";
}
res.setContentType(contentType);
// see if its a Range Request
boolean isRangeRequest = false;
long startPos = 0, endPos = Long.MAX_VALUE;
String rangeRequest = req.getHeader("Range");
if (rangeRequest != null) { // bytes=12-34 or bytes=12-
int pos = rangeRequest.indexOf("=");
if (pos > 0) {
int pos2 = rangeRequest.indexOf("-");
if (pos2 > 0) {
String startString = rangeRequest.substring(pos + 1, pos2);
String endString = rangeRequest.substring(pos2 + 1);
startPos = Long.parseLong(startString);
if (endString.length() > 0)
endPos = Long.parseLong(endString) + 1;
isRangeRequest = true;
}
}
}
// set content length
long fileSize = file.length();
int contentLength = (int) fileSize;
if (isRangeRequest) {
endPos = Math.min(endPos, fileSize);
contentLength = (int) (endPos - startPos);
}
res.setContentLength(contentLength);
boolean debugRequest = Debug.isSet("returnFile");
if (debugRequest) log.debug("returnFile(): filename = " + filename + " contentType = " + contentType +
" contentLength = " + file.length());
// indicate we allow Range Requests
res.addHeader("Accept-Ranges", "bytes");
if (req.getMethod().equals("HEAD")) {
ServletUtil.logServerAccess(HttpServletResponse.SC_OK, 0);
return;
}
try {
if (isRangeRequest) {
// set before content is sent
res.addHeader("Content-Range", "bytes " + startPos + "-" + (endPos - 1) + "/" + fileSize);
res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
ucar.unidata.io.RandomAccessFile raf = null;
try {
raf = FileCache.acquire(filename);
thredds.util.IO.copyRafB(raf, startPos, contentLength, res.getOutputStream(), new byte[60000]);
ServletUtil.logServerAccess(HttpServletResponse.SC_PARTIAL_CONTENT, contentLength);
return;
} finally {
if (raf != null) FileCache.release(raf);
}
}
// Return the file
ServletOutputStream out = res.getOutputStream();
thredds.util.IO.copyFileB(file, out, 60000);
res.flushBuffer();
out.close();
if (debugRequest) log.debug("returnFile(): returnFile ok = " + filename);
ServletUtil.logServerAccess(HttpServletResponse.SC_OK, contentLength);
}
// @todo Split up this exception handling: those from file access vs those from dealing with response
// File access: catch and res.sendError()
// response: don't catch (let bubble up out of doGet() etc)
catch (FileNotFoundException e) {
log.error("returnFile(): FileNotFoundException= " + filename);
ServletUtil.logServerAccess(HttpServletResponse.SC_NOT_FOUND, 0);
res.sendError(HttpServletResponse.SC_NOT_FOUND);
}
catch (java.net.SocketException e) {
log.info("returnFile(): SocketException sending file: " + filename + " " + e.getMessage());
ServletUtil.logServerAccess(1000, 0); // dunno what error code to log
}
catch (IOException e) {
String eName = e.getClass().getName(); // dont want compile time dependency on ClientAbortException
if (eName.equals("org.apache.catalina.connector.ClientAbortException")) {
log.info("returnFile(): ClientAbortException while sending file: " + filename + " " + e.getMessage());
ServletUtil.logServerAccess(1000, 0); // dunno what error code to log
return;
}
log.error("returnFile(): IOException (" + e.getClass().getName() + ") sending file ", e);
ServletUtil.logServerAccess(HttpServletResponse.SC_NOT_FOUND, 0);
res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending file: " + e.getMessage());
}
}
/**
* Send given content string as the HTTP response.
*
* @param contents the string to return as the HTTP response.
* @param res the HttpServletResponse
* @throws IOException if an I/O error occurs while writing the response.
*/
public static void returnString(String contents, HttpServletResponse res)
throws IOException
{
try {
ServletOutputStream out = res.getOutputStream();
thredds.util.IO.copy(new ByteArrayInputStream(contents.getBytes()), out);
ServletUtil.logServerAccess(HttpServletResponse.SC_OK, contents.length());
}
catch (IOException e) {
log.error(" IOException sending string: ", e);
ServletUtil.logServerAccess(HttpServletResponse.SC_NOT_FOUND, 0);
res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending string: " + e.getMessage());
}
}
/**
* Return the request URL relative to the server (i.e., starting with the context path).
*
* @param req
* @return
*/
public static String getReletiveURL(HttpServletRequest req) {
return req.getContextPath() + req.getServletPath() + req.getPathInfo();
}
/**
* Forward this request to the CatalogServices servlet ("/catalog.html").
*
* @param req
* @param res
* @throws IOException
* @throws ServletException
*/
public static void forwardToCatalogServices(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
String reqs = "catalog=" + getReletiveURL(req);
String query = req.getQueryString();
if (query != null)
reqs = reqs + "&" + query;
log.info("forwardToCatalogServices(): request string = \"/catalog.html?" + reqs + "\"");
// dispatch to CatalogHtml servlet
// "The pathname specified may be relative, although it cannot extend outside the current servlet context.
// "If the path begins with a "/" it is interpreted as relative to the current context root."
RequestDispatcher dispatch = req.getRequestDispatcher("/catalog.html?" + reqs);
if (dispatch != null)
dispatch.forward(req, res);
else
res.sendError(HttpServletResponse.SC_NOT_FOUND);
ServletUtil.logServerAccess(HttpServletResponse.SC_NOT_FOUND, 0);
}
public static boolean saveFile(HttpServlet servlet, String contentPath, String path, HttpServletRequest req,
HttpServletResponse res) {
// @todo Need to use logServerAccess() below here.
boolean debugRequest = Debug.isSet("SaveFile");
if (debugRequest) log.debug(" saveFile(): path= " + path);
String filename = contentPath + path; // absolute path
File want = new File(filename);
// backup current version if it exists
int version = getBackupVersion(want.getParent(), want.getName());
String fileSave = filename + "~" + version;
File file = new File(filename);
if (file.exists()) {
try {
thredds.util.IO.copyFile(filename, fileSave);
} catch (IOException e) {
log.error("saveFile(): Unable to save copy of file " + filename + " to " + fileSave + "\n" + e.getMessage());
return false;
}
}
// save new file
try {
OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
thredds.util.IO.copy(req.getInputStream(), out);
out.close();
if (debugRequest) log.debug("saveFile(): ok= " + filename);
res.setStatus(HttpServletResponse.SC_CREATED);
ServletUtil.logServerAccess(HttpServletResponse.SC_CREATED, -1);
return true;
} catch (IOException e) {
log.error("saveFile(): Unable to PUT file " + filename + " to " + fileSave + "\n" + e.getMessage());
return false;
}
}
private static int getBackupVersion(String dirName, String fileName) {
int maxN = 0;
File dir = new File(dirName);
if (!dir.exists())
return -1;
String[] files = dir.list();
if (null == files)
return -1;
for (String name : files) {
if (name.indexOf(fileName) < 0) continue;
int pos = name.indexOf('~');
if (pos < 0) continue;
String ver = name.substring(pos + 1);
int n = 0;
try {
n = Integer.parseInt(ver);
} catch (NumberFormatException e) {
log.error("Format Integer error on backup filename= " + ver);
}
maxN = Math.max(n, maxN);
}
return maxN + 1;
}
static public boolean copyDir(String fromDir, String toDir) throws IOException {
File contentFile = new File(toDir + ".INIT");
if (!contentFile.exists()) {
thredds.util.IO.copyDirTree(fromDir, toDir);
contentFile.createNewFile();
return true;
}
return false;
}
static public void handleException(Throwable t, HttpServletResponse res) {
try {
String message = t.getMessage();
if (message == null) message = "NULL message " + t.getClass().getName();
if (Debug.isSet("trustedMode")) { // security issue: only show stack if trusted
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
t.printStackTrace(ps);
message = new String(bs.toByteArray());
}
ServletUtil.logServerAccess(HttpServletResponse.SC_BAD_REQUEST, message.length());
log.error("handleException", t);
t.printStackTrace(); // debugging - log.error not showing stack trace !!
res.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
} catch (IOException e) {
log.error("handleException(): IOException", e);
t.printStackTrace();
}
}
static public void showServerInfo(HttpServlet servlet, PrintStream out) {
out.println("Server Info");
out.println(" getDocumentBuilderFactoryVersion(): " + XMLEntityResolver.getDocumentBuilderFactoryVersion());
out.println();
Properties sysp = System.getProperties();
Enumeration e = sysp.propertyNames();
List<String> list = Collections.list(e);
Collections.sort(list);
out.println("System Properties:");
for (String name : list) {
String value = System.getProperty(name);
out.println(" " + name + " = " + value);
}
out.println();
}
static public void showServletInfo(HttpServlet servlet, PrintStream out) {
out.println("Servlet Info");
out.println(" getServletName(): " + servlet.getServletName());
out.println(" getRootPath(): " + getRootPath(servlet));
out.println(" Init Parameters:");
Enumeration params = servlet.getInitParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
out.println(" " + name + ": " + servlet.getInitParameter(name));
}
out.println();
ServletContext context = servlet.getServletContext();
out.println("Context Info");
try {
out.println(" context.getResource('/'): " + context.getResource("/"));
} catch (java.net.MalformedURLException e) {
} // cant happen
out.println(" context.getServerInfo(): " + context.getServerInfo());
out.println(" name: " + getServerInfoName(context.getServerInfo()));
out.println(" version: " + getServerInfoVersion(context.getServerInfo()));
out.println(" context.getInitParameterNames():");
params = context.getInitParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
out.println(" " + name + ": " + context.getInitParameter(name));
}
out.println(" context.getAttributeNames():");
params = context.getAttributeNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
out.println(" context.getAttribute(\"" + name + "\"): " +
context.getAttribute(name));
}
out.println();
}
/**
* Show the pieces of the request, for debugging
*
* @param req the HttpServletRequest
* @return parsed request
*/
public static String getRequestParsed(HttpServletRequest req) {
return req.getRequestURI() + " = " + req.getContextPath() + "(context), " +
req.getServletPath() + "(servletPath), " +
req.getPathInfo() + "(pathInfo), " + req.getQueryString() + "(query)";
}
/**
* This is everything except the query string
*
* @param req the HttpServletRequest
* @return parsed request base
*/
public static String getRequestBase(HttpServletRequest req) {
return req.getRequestURL().toString();
}
/**
* The request base as a URI
* @param req the HttpServletRequest
* @return parsed request as a URI
*/
public static URI getRequestURI(HttpServletRequest req) {
try {
return new URI(getRequestBase(req));
} catch (URISyntaxException e) {
e.printStackTrace();
return null;
}
}
/**
* servletPath + pathInfo
* @param req the HttpServletRequest
* @return parsed request servletPath + pathInfo
*/
public static String getRequestPath(HttpServletRequest req) {
StringBuffer buff = new StringBuffer();
if (req.getServletPath() != null)
buff.append(req.getServletPath());
if (req.getPathInfo() != null)
buff.append(req.getPathInfo());
return buff.toString();
}
/**
* The entire request including query string
* @param req the HttpServletRequest
* @return entire parsed request
*/
public static String getRequest(HttpServletRequest req) {
String query = req.getQueryString();
return getRequestBase(req) + (query == null ? "" : "?" + req.getQueryString());
}
/**
* Return the value of the given parameter for the given request. Should
* only be used if the parameter is known to only have one value. If used
* on a multi-valued parameter, the first value is returned.
*
* @param req the HttpServletRequest
* @param paramName the name of the parameter to find.
* @return the value of the given parameter for the given request.
*/
public static String getParameterIgnoreCase(HttpServletRequest req, String paramName) {
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
if (s.equalsIgnoreCase(paramName))
return req.getParameter(s);
}
return null;
}
/**
* Return the values of the given parameter (ignoring case) for the given request.
*
* @param req the HttpServletRequest
* @param paramName the name of the parameter to find.
* @return the values of the given parameter for the given request.
*/
public static String[] getParameterValuesIgnoreCase(HttpServletRequest req, String paramName) {
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
if (s.equalsIgnoreCase(paramName))
return req.getParameterValues(s);
}
return null;
}
public static String getFileURL(String filename) {
filename = filename.replace('\\', '/');
filename = StringUtil.replace(filename, ' ', "+");
return "file:" + filename;
}
public static String getFileURL2(String filename) {
File f = new File(filename);
try {
return f.toURL().toString();
} catch (java.net.MalformedURLException e) {
e.printStackTrace();
}
return null;
}
/**
* Show deatails about the request
*
* @param servlet used to get teh servlet context, may be null
* @param req the request
* @return string showing the details of the request.
*/
static public String showRequestDetail(HttpServlet servlet, HttpServletRequest req) {
StringBuffer sbuff = new StringBuffer();
sbuff.append("Request Info\n");
sbuff.append(" req.getServerName(): ").append(req.getServerName()).append("\n");
sbuff.append(" req.getServerPort(): ").append(req.getServerPort()).append("\n");
sbuff.append(" req.getContextPath:").append(req.getContextPath()).append("\n");
sbuff.append(" req.getServletPath:").append(req.getServletPath()).append("\n");
sbuff.append(" req.getPathInfo:").append(req.getPathInfo()).append("\n");
sbuff.append(" req.getQueryString:").append(req.getQueryString()).append("\n");
sbuff.append(" req.getRequestURI:").append(req.getRequestURI()).append("\n");
sbuff.append(" getRequestBase:").append(getRequestBase(req)).append("\n");
sbuff.append(" getRequest:").append(getRequest(req)).append("\n");
sbuff.append("\n");
sbuff.append(" req.getPathTranslated:").append(req.getPathTranslated()).append("\n");
String path = req.getPathTranslated();
if ((path != null) && (servlet != null)) {
ServletContext context = servlet.getServletContext();
sbuff.append(" getMimeType:").append(context.getMimeType(path)).append("\n");
}
sbuff.append("\n");
sbuff.append(" req.getScheme:").append(req.getScheme()).append("\n");
sbuff.append(" req.getProtocol:").append(req.getProtocol()).append("\n");
sbuff.append(" req.getMethod:").append(req.getMethod()).append("\n");
sbuff.append("\n");
sbuff.append(" req.getContentType:").append(req.getContentType()).append("\n");
sbuff.append(" req.getContentLength:").append(req.getContentLength()).append("\n");
sbuff.append(" req.getRemoteAddr():").append(req.getRemoteAddr());
try {
sbuff.append(" getRemoteHost():").append(java.net.InetAddress.getByName(req.getRemoteHost()).getHostName()).append("\n");
} catch (java.net.UnknownHostException e) {
sbuff.append(" getRemoteHost():").append(e.getMessage()).append("\n");
}
sbuff.append(" getRemoteUser():").append(req.getRemoteUser()).append("\n");
sbuff.append("\n");
sbuff.append("Request Parameters:\n");
Enumeration params = req.getParameterNames();
while (params.hasMoreElements()) {
String name = (String) params.nextElement();
String values[] = req.getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
sbuff.append(" ").append(name).append(" (").append(i).append("): ").append(values[i]).append("\n");
}
}
}
sbuff.append("\n");
sbuff.append("Request Headers:\n");
Enumeration names = req.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Enumeration values = req.getHeaders(name); // support multiple values
if (values != null) {
while (values.hasMoreElements()) {
String value = (String) values.nextElement();
sbuff.append(" ").append(name).append(": ").append(value).append("\n");
}
}
}
sbuff.append("
return sbuff.toString();
}
static public String showRequestHeaders(HttpServletRequest req) {
StringBuffer sbuff = new StringBuffer();
sbuff.append("Request Headers:\n");
Enumeration names = req.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Enumeration values = req.getHeaders(name); // support multiple values
if (values != null) {
while (values.hasMoreElements()) {
String value = (String) values.nextElement();
sbuff.append(" ").append(name).append(": ").append(value).append("\n");
}
}
}
return sbuff.toString();
}
static public void showSession(HttpServletRequest req, HttpServletResponse res,
PrintStream out) {
// res.setContentType("text/html");
// Get the current session object, create one if necessary
HttpSession session = req.getSession();
// Increment the hit count for this page. The value is saved
// in this client's session under the name "snoop.count".
Integer count = (Integer) session.getAttribute("snoop.count");
if (count == null) {
count = 1;
} else
count = count + 1;
session.setAttribute("snoop.count", count);
out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag());
out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
out.println("<BODY><H1>Session Snoop</H1>");
// Display the hit count for this page
out.println("You've visited this page " + count +
((!(count.intValue() != 1)) ? " time." : " times."));
out.println("<P>");
out.println("<H3>Here is your saved session data:</H3>");
Enumeration atts = session.getAttributeNames();
while (atts.hasMoreElements()) {
String name = (String) atts.nextElement();
out.println(name + ": " + session.getAttribute(name) + "<BR>");
}
out.println("<H3>Here are some vital stats on your session:</H3>");
out.println("Session id: " + session.getId() +
" <I>(keep it secret)</I><BR>");
out.println("New session: " + session.isNew() + "<BR>");
out.println("Timeout: " + session.getMaxInactiveInterval());
out.println("<I>(" + session.getMaxInactiveInterval() / 60 +
" minutes)</I><BR>");
out.println("Creation time: " + session.getCreationTime());
out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
out.println("Last access time: " + session.getLastAccessedTime());
out.println("<I>(" + new Date(session.getLastAccessedTime()) +
")</I><BR>");
out.println("Requested session ID from cookie: " +
req.isRequestedSessionIdFromCookie() + "<BR>");
out.println("Requested session ID from URL: " +
req.isRequestedSessionIdFromURL() + "<BR>");
out.println("Requested session ID valid: " +
req.isRequestedSessionIdValid() + "<BR>");
out.println("<H3>Test URL Rewriting</H3>");
out.println("Click <A HREF=\"" +
res.encodeURL(req.getRequestURI()) + "\">here</A>");
out.println("to test that session tracking works via URL");
out.println("rewriting even when cookies aren't supported.");
out.println("</BODY></HTML>");
}
static public void showSession(HttpServletRequest req, PrintStream out) {
// res.setContentType("text/html");
// Get the current session object, create one if necessary
HttpSession session = req.getSession();
out.println("Session id: " + session.getId());
out.println(" session.isNew(): " + session.isNew());
out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
out.println(" session.getCreationTime(): " + session.getCreationTime() + " (" + new Date(session.getCreationTime()) + ")");
out.println(" session.getLastAccessedTime(): " + session.getLastAccessedTime() + " (" + new Date(session.getLastAccessedTime()) + ")");
out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());
out.println("Saved session Attributes:");
Enumeration atts = session.getAttributeNames();
while (atts.hasMoreElements()) {
String name = (String) atts.nextElement();
out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
}
}
static public String showSecurity(HttpServletRequest req, String role) {
StringBuffer sbuff = new StringBuffer();
sbuff.append("Security Info\n");
sbuff.append(" req.getRemoteUser(): ").append(req.getRemoteUser()).append("\n");
sbuff.append(" req.getUserPrincipal(): ").append(req.getUserPrincipal()).append("\n");
sbuff.append(" req.isUserInRole(").append(role).append("):").append(req.isUserInRole(role)).append("\n");
sbuff.append("
return sbuff.toString();
}
static private String getServerInfoName(String serverInfo) {
int slash = serverInfo.indexOf('/');
if (slash == -1) return serverInfo;
else return serverInfo.substring(0, slash);
}
static private String getServerInfoVersion(String serverInfo) {
// Version info is everything between the slash and the space
int slash = serverInfo.indexOf('/');
if (slash == -1) return null;
int space = serverInfo.indexOf(' ', slash);
if (space == -1) space = serverInfo.length();
return serverInfo.substring(slash + 1, space);
}
static public void showThreads(PrintStream pw) {
Thread current = Thread.currentThread();
ThreadGroup group = current.getThreadGroup();
while (true) {
if (group.getParent() == null) break;
group = group.getParent();
}
showThreads(pw, group, current);
}
static private void showThreads(PrintStream pw, ThreadGroup g, Thread current) {
int nthreads = g.activeCount();
pw.println("\nThread Group = " + g.getName() + " activeCount= " + nthreads);
Thread[] tarray = new Thread[nthreads];
int n = g.enumerate(tarray, false);
for (int i = 0; i < n; i++) {
Thread thread = tarray[i];
ClassLoader loader = thread.getContextClassLoader();
String loaderName = (loader == null) ? "Default" : loader.getClass().getName();
Thread.State state = thread.getState(); // LOOK JDK 1.5
long id = thread.getId(); // LOOK JDK 1.5
pw.print(" " + id + " " + thread.getName() + " " + state + " " + loaderName);
if (thread == current)
pw.println(" **** CURRENT ***");
else
pw.println();
}
int ngroups = g.activeGroupCount();
ThreadGroup[] garray = new ThreadGroup[ngroups];
int ng = g.enumerate(garray, false);
for (int i = 0; i < ng; i++) {
ThreadGroup nested = garray[i];
showThreads(pw, nested, current);
}
}
public static void main(String[] args) {
String s = "C:/Program Files/you";
System.out.println("FileURL = " + getFileURL(s));
System.out.println("FileURL2 = " + getFileURL2(s));
}
} |
package org.apache.xerces.impl;
/**
* This class defines the version number of the parser.
*
* @version $Id$
*/
public class Version {
// Data
/** Version string.
* @deprecated getVersion() should be used instead. */
public static String fVersion = "@@VERSION@@";
private static final String fImmutableVersion = "@@VERSION@@";
// public methods
/* Print out the version information.
* @return the version of the parser.
*/
public static String getVersion() {
return fImmutableVersion;
} // getVersion(): String
// MAIN
/**
* Prints out the version number to System.out. This is needed
* for the build system.
*/
public static void main(String argv[]) {
System.out.println(fVersion);
}
} // class Version |
package org.basex.gui.view.map;
import static org.basex.Text.*;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.SwingUtilities;
import org.basex.core.Context;
import org.basex.data.Data;
import org.basex.data.Nodes;
import org.basex.gui.GUI;
import org.basex.gui.GUIConstants;
import org.basex.gui.GUIProp;
import org.basex.gui.layout.BaseXLayout;
import org.basex.gui.layout.BaseXPopup;
import org.basex.gui.view.View;
import org.basex.gui.view.ViewData;
import org.basex.util.IntList;
import org.basex.util.Performance;
import org.basex.util.Token;
public final class MapView extends View implements Runnable {
/** Dynamic zooming steps. */
private static final int[] ZS = {
0, 31, 113, 205, 356, 553, 844, 1226, 1745, 2148, 2580, 3037,
3515, 4008, 4511, 5019, 5527, 6030, 6522, 6998, 7453, 7883,
8283, 8749, 9158, 9456, 9650, 9797, 9885, 9973, 10000
};
/** Number of zooming steps. */
private static final int ZOOMSIZE = ZS.length - 1;
/** Maximum zooming step. */
private static final int MAXZS = ZS[ZOOMSIZE];
/** Layout rectangle. */
protected MapRect layout;
/** Array of current rectangles. */
private transient MapRects mainRects;
/** Data specific map layout. */
private transient MapPainter painter;
/** Rectangle history. */
private final MapRect[] rectHist = new MapRect[MAXHIST];
/** Current zooming Step (set to 0 when no zooming takes place). */
private int zoomStep;
/** Main rectangle. */
private MapRect mainRect;
/** Dragged rectangle. */
private MapRect dragRect;
/** Flag for zooming in/out. */
private boolean zoomIn;
/** Zooming speed. */
private int zoomSpeed;
/** Horizontal mouse position. */
private int mouseX = -1;
/** Vertical mouse position. */
private int mouseY = -1;
/** Drag tolerance. */
private int dragTol;
/** Currently focused rectangle. */
private transient MapRect focusedRect;
/** TreeMap. */
private BufferedImage mainMap;
/** Zoomed TreeMap. */
private BufferedImage zoomMap;
/**
* Default Constructor.
* @param help help text
*/
public MapView(final byte[] help) {
super(help);
setMode(GUIConstants.FILL.NONE);
mainMap = createImage();
zoomMap = createImage();
popup = new BaseXPopup(this, GUIConstants.POPUP);
}
/**
* Creates a buffered image.
* @return buffered image
*/
private BufferedImage createImage() {
final Dimension screen = getToolkit().getScreenSize();
final int w = Math.max(1, screen.width);
final int h = Math.max(1, screen.height);
final BufferedImage img = new BufferedImage(w, h,
BufferedImage.TYPE_INT_BGR);
final Graphics g = img.getGraphics();
g.setColor(GUIConstants.COLORS[0]);
g.fillRect(0, 0, w, h);
return img;
}
@Override
public void refreshInit() {
focusedRect = null;
mainRects = null;
zoomStep = 0;
slide = false;
if(painter != null) painter.close();
final Data data = GUI.context.data();
if(data != null && getWidth() != 0) {
if(!GUIProp.showmap) return;
painter = data.deepfs ? new MapFS(this) : new MapDefault(this);
calc();
repaint();
}
}
@Override
public void refreshFocus() {
if(mainRects == null || working) return;
if(focused == -1 && focusedRect != null) focusedRect = null;
final MapRect m = focusedRect;
int mi = 0;
for(final int ms = mainRects.size; mi < ms; mi++) {
final MapRect rect = mainRects.get(mi);
if(focused == rect.p || mi + 1 < ms &&
focused < mainRects.get(mi + 1).p) {
focusedRect = rect;
break;
}
}
if(focusedRect != m) repaint();
}
@Override
public void refreshMark() {
if(getWidth() == 0) return;
drawMap();
repaint();
}
@Override
public void refreshContext(final boolean more, final boolean quick) {
if(!GUIProp.showmap) {
mainRects = null;
return;
}
// use simple zooming animation for result node filtering
final Nodes context = GUI.context.current();
final boolean page = !more && rectHist[hist + 1] != null &&
rectHist[hist + 1].p == 0 || more && (context.size != 1 ||
focusedRect == null || context.pre[0] != focusedRect.p);
if(page) focusedRect = new MapRect(0, 0, getWidth(), 1);
zoom(more, quick);
}
@Override
public void refreshLayout() {
calc();
repaint();
}
@Override
public void refreshUpdate() {
refreshContext(false, true);
}
/**
* Zooms the focused rectangle.
* @param more show more
* @param quick context switch (no animation)
*/
private void zoom(final boolean more, final boolean quick) {
working = !quick;
zoomIn = more;
// choose zooming rectangle
if(more) {
rectHist[hist] = focusedRect.clone();
mainRect = rectHist[hist];
} else {
mainRect = rectHist[hist + 1];
}
if(mainRect == null) mainRect = new MapRect(0, 0, getWidth(), getHeight());
// reset data & start zooming
final BufferedImage tmpMap = zoomMap;
zoomMap = mainMap;
mainMap = tmpMap;
focusedRect = null;
// create new context nodes
calc();
// calculate zooming speed (slower for large zooming scales)
zoomSpeed = (int) (Math.log(128 * getWidth() / mainRect.w) +
Math.log(128 * getHeight() / mainRect.h));
if(quick) {
working = false;
focus();
repaint();
} else {
zoomStep = ZOOMSIZE;
new Thread(this).start();
}
}
/**
* Starts the zooming thread.
*/
public void run() {
focusedRect = null;
// run zooming
while(zoomStep > 1) {
Performance.sleep(zoomSpeed);
zoomStep
repaint();
}
// wait until current painting is finished
while(painting) Performance.sleep(zoomSpeed);
// remove old rectangle and repaint map
zoomStep = 0;
working = false;
focus();
repaint();
}
/**
* Finds rectangle at cursor position.
* @return focused rectangle
*/
private boolean focus() {
if(working || mainRects == null) return false;
/* Loop through all rectangles. As the rectangles are sorted by pre
* order and small rectangles are descendants of bigger ones, the
* focused rectangle can be found by simply parsing the array backward. */
int r = mainRects.size;
while(--r >= 0) {
final MapRect rect = mainRects.get(r);
if(rect.contains(mouseX, mouseY)) break;
}
// don't focus top rectangles
final MapRect fr = r >= 0 ? mainRects.get(r) : null;
// find focused rectangle
final boolean newFocus = focusedRect != fr || fr != null && fr.thumb;
focusedRect = fr;
if(fr != null) GUI.get().cursor(painter.highlight(focusedRect, mouseX,
mouseY, false) ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW);
if(newFocus) notifyFocus(focusedRect != null ? focusedRect.p : -1, this);
return newFocus;
}
/**
* Initializes the calculation of the main TreeMap.
* @return performance string
*/
private String calc() {
// calculate initial rectangle
final int w = getWidth(), h = getHeight();
// Screenshots: int w = mainMap.getWidth(), h = mainMap.getHeight();
final MapRect rect = new MapRect(0, 0, w, h, 0, 0);
// calculate new main rectangles
if(painter == null) return null;
mainRects = new MapRects();
painter.reset();
layout = null;
final int o = GUIProp.fontsize + 4;
switch(GUIProp.maplayout) {
case 0: layout = new MapRect(0, 0, 0, 0); break;
case 1: layout = new MapRect(1, 1, 2, 2); break;
case 2: layout = new MapRect(0, o, 0, o); break;
case 3: layout = new MapRect(2, o - 1, 4, o + 1); break;
case 4: layout = new MapRect(o >> 2, o, o >> 1, o + (o >> 2)); break;
case 5: layout = new MapRect(o >> 1, o, o, o + (o >> 1)); break;
default:
}
// call recursive TreeMap algorithm
final Performance perf = new Performance();
final Nodes nodes = GUI.context.current();
calcMap(rect, new IntList(nodes.pre), 0, nodes.size, true);
// output timing information
final StringBuilder sb = new StringBuilder();
sb.append(STATUSMAP1);
sb.append(perf.getTimer());
painter.init(mainRects);
drawMap();
sb.append(STATUSMAP2);
sb.append(perf.getTimer());
focus();
/* Screenshots:
try {
File file = new File("screenshot.png");
ImageIO.write(mainMap, "png", file);
} catch(IOException e) {
e.printStackTrace();
}*/
return sb.toString();
}
/**
* Recursively splits rectangles on one level.
* @param r parent rectangle
* @param l children array
* @param ns start array position
* @param ne end array position
* @param first first traversal
*/
private void calcMap(final MapRect r, final IntList l,
final int ns, final int ne, final boolean first) {
// one rectangle left.. continue with children
if(ne - ns == 1) {
// calculate rectangle sizes
final MapRect t = new MapRect(r.x, r.y, r.w, r.h, l.get(ns), r.l);
mainRects.add(t);
final int x = t.x + layout.x;
final int y = t.y + layout.y;
final int w = t.w - layout.w;
final int h = t.h - layout.h;
// get children
final int o = GUIProp.fontsize + 4;
// skip too small rectangles and leaf nodes (= meta data in deepfs)
if((w >= o || h >= o) && w > 0 && h > 0 &&
!ViewData.isLeaf(GUI.context.data(), t.p)) {
final IntList ch = children(t.p);
if(ch.size != 0) calcMap(new MapRect(x, y, w, h,
l.get(ns), r.l + 1), ch, 0, ch.size - 1, false);
}
} else {
// recursively split current nodes
int nn = ne - ns;
int ln = nn >> 1;
int ni = ns + ln;
// consider number of descendants to calculate split point
if(!GUIProp.mapsimple && !first) {
nn = l.get(ne) - l.get(ns);
ni = ns + 1;
for(; ni < ne - 1; ni++) if(l.get(ni) - l.get(ns) >= (nn >> 1)) break;
ln = l.get(ni) - l.get(ns);
}
// determine rectangle orientation (horizontal/vertical)
final int p = GUIProp.mapprop;
final boolean v = p > 4 ? r.w > r.h * (p + 4) / 8 :
r.w * (13 - p) / 8 > r.h;
int xx = r.x;
int yy = r.y;
int ww = !v ? r.w : (int) ((long) r.w * ln / nn);
int hh = v ? r.h : (int) ((long) r.h * ln / nn);
// paint both rectangles if enough space is left
if(ww > 0 && hh > 0) calcMap(new MapRect(xx, yy, ww, hh, 0, r.l),
l, ns, ni, first);
if(v) {
xx += ww;
ww = r.w - ww;
} else {
yy += hh;
hh = r.h - hh;
}
if(ww > 0 && hh > 0) calcMap(new MapRect(xx, yy, ww, hh, 0, r.l),
l, ni, ne, first);
}
}
/**
* Returns all children of the specified node.
* @param par parent node
* @return children
*/
private IntList children(final int par) {
final IntList list = new IntList();
final Data data = GUI.context.data();
final int kind = data.kind(par);
final int last = par + data.size(par, kind);
int p = par + (GUIProp.mapatts ? 1 : data.attSize(par, kind));
while(p != last) {
list.add(p);
p += data.size(p, data.kind(p));
}
// paint all children
if(list.size != 0) list.add(p);
return list;
}
@Override
public void paintComponent(final Graphics g) {
final Data data = GUI.context.data();
if(data == null) return;
if(mainRects == null) {
refreshInit();
return;
}
// calculate map
painting = true;
// paint map
final boolean in = zoomStep > 0 && zoomIn;
final Image img1 = in ? zoomMap : mainMap;
final Image img2 = in ? mainMap : zoomMap;
if(zoomStep > 0) {
drawImage(g, img1, -zoomStep);
drawImage(g, img2, zoomStep);
} else {
drawImage(g, mainMap, zoomStep);
}
// skip node path view
if(focusedRect == null || mainRects.size == 1 &&
focusedRect == mainRects.get(0)) {
painting = false;
return;
}
if(GUIProp.maplayout == 0) {
g.setColor(GUIConstants.COLORS[32]);
int pre = mainRects.size;
int par = ViewData.parent(data, focusedRect.p);
while(--pre >= 0) {
final MapRect rect = mainRects.get(pre);
if(rect.p == par) {
final int x = rect.x;
final int y = rect.y;
final int w = rect.w;
final int h = rect.h;
g.drawRect(x, y, w, h);
g.drawRect(x - 1, y - 1, w + 2, h + 2);
par = ViewData.parent(data, par);
}
}
}
if(dragRect != null) {
g.setColor(GUIConstants.colormark3);
g.drawRect(dragRect.x, dragRect.y, dragRect.w, dragRect.h);
g.drawRect(dragRect.x - 1, dragRect.y - 1, dragRect.w + 2,
dragRect.h + 2);
} else {
// paint focused rectangle
final int x = focusedRect.x;
final int y = focusedRect.y;
final int w = focusedRect.w;
final int h = focusedRect.h;
g.setColor(GUIConstants.color6);
g.drawRect(x, y, w, h);
g.drawRect(x - 1, y - 1, w + 2, h + 2);
// draw tag label
if(data.kind(focusedRect.p) == Data.ELEM) {
g.setFont(GUIConstants.font);
final byte[] tag = ViewData.tag(data, focusedRect.p);
final int tw = BaseXLayout.width(g, tag);
final int th = g.getFontMetrics().getHeight();
final int xx = Math.min(getWidth() - tw - 8, x);
g.setColor(GUIConstants.COLORS[focusedRect.l + 5]);
g.fillRect(xx - 1, y - th, tw + 4, th);
g.setColor(GUIConstants.color1);
g.drawString(Token.string(tag), xx, y - 4);
}
// add interactions for current thumbnail rectangle...
//if(focusedRect.thumb) ...
}
painting = false;
}
/**
* Draws image with correct scaling.
* @param g graphics reference
* @param img image to be drawn
* @param zi zooming factor
*/
private void drawImage(final Graphics g, final Image img, final int zi) {
if(img == null) return;
final MapRect r = new MapRect(0, 0, getWidth(), getHeight());
zoom(r, zi);
g.drawImage(img, r.x, r.y, r.x + r.w, r.y + r.h, 0, 0,
getWidth(), getHeight(), this);
}
/**
* Zooms the coordinates of the specified rectangle.
* @param r rectangle to be zoomed
* @param zs zooming step
*/
private void zoom(final MapRect r, final int zs) {
int xs = r.x;
int ys = r.y;
int xe = xs + r.w;
int ye = ys + r.h;
// calculate zooming rectangle
// get window size
if(zs != 0) {
final MapRect zr = mainRect;
final int tw = getWidth();
final int th = getHeight();
if(zs > 0) {
final long s = zoomIn ? ZS[zs] : ZS[ZOOMSIZE - zs];
xs = (int) ((zr.x + xs * zr.w / tw - xs) * s / MAXZS);
ys = (int) ((zr.y + ys * zr.h / th - ys) * s / MAXZS);
xe += (int) ((zr.x + xe * zr.w / tw - xe) * s / MAXZS);
ye += (int) ((zr.y + ye * zr.h / th - ye) * s / MAXZS);
} else {
final long s = 10000 - (zoomIn ? ZS[-zs] : ZS[ZOOMSIZE + zs]);
xs = (int) (-xe * zr.x / zr.w * s / MAXZS);
xe = (int) (xs + xe + xe * (xe - zr.w) / zr.w * s / MAXZS);
ys = (int) (-ye * zr.y / zr.h * s / MAXZS);
ye = (int) (ys + ye + ye * (ye - zr.h) / zr.h * s / MAXZS);
}
}
r.x = xs;
r.y = ys;
r.w = xe - xs;
r.h = ye - ys;
}
/**
* Creates a buffered image for the treemap.
*/
void drawMap() {
final Graphics g = mainMap.getGraphics();
g.setColor(GUIConstants.COLORS[2]);
BaseXLayout.antiAlias(g);
if(mainRects != null) painter.drawRectangles(g, mainRects);
}
@Override
public void mouseMoved(final MouseEvent e) {
if(working) return;
super.mouseMoved(e);
// refresh mouse focus
mouseX = e.getX();
mouseY = e.getY();
if(focus()) repaint();
}
@Override
public void mouseClicked(final MouseEvent e) {
if(working) return;
final boolean left = SwingUtilities.isLeftMouseButton(e);
if(!left || focusedRect == null) return;
// single/double click?
if(painter.highlight(focusedRect, mouseX, mouseY, true)) return;
}
@Override
public void mousePressed(final MouseEvent e) {
if(working) return;
super.mousePressed(e);
mouseX = e.getX();
mouseY = e.getY();
dragTol = 0;
if(!focus() && focused == -1) return;
// left/right mouse click?
final boolean left = SwingUtilities.isLeftMouseButton(e);
final int pre = focused;
// add or remove marked node
final Nodes marked = GUI.context.marked();
if(!left) {
// right mouse button
if(marked.find(pre) < 0) notifyMark(0);
} else if(e.getClickCount() == 2) {
if(mainRects.size != 1) notifyContext(marked, false);
} else if(e.isShiftDown()) {
notifyMark(1);
} else if(e.isControlDown()) {
notifyMark(2);
} else {
if(marked.find(pre) < 0) notifyMark(0);
}
}
@Override
public void mouseDragged(final MouseEvent e) {
if(working || ++dragTol < 8) return;
super.mouseDragged(e);
// refresh mouse focus
int mx = mouseX;
int my = mouseY;
int mw = e.getX() - mx;
int mh = e.getY() - my;
if(mw < 0) mx -= mw = -mw;
if(mh < 0) my -= mh = -mh;
dragRect = new MapRect(mx, my, mw, mh);
final Context context = GUI.context;
final Data data = context.data();
final IntList list = new IntList();
int np = 0;
int r = -1;
while(++r < mainRects.size) {
final MapRect rect = mainRects.get(r);
if(mainRects.get(r).p < np) continue;
if(dragRect.contains(rect)) {
list.add(rect.p);
np = rect.p + data.size(rect.p, data.kind(rect.p));
}
}
final Nodes marked = new Nodes(list.get(), data);
marked.size = list.size;
View.notifyMark(marked);
}
@Override
public void mouseReleased(final MouseEvent e) {
if(working) return;
if(dragRect != null) {
dragRect = null;
repaint();
}
}
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
if(working || focused == -1) return;
if(e.getWheelRotation() > 0) notifyContext(
new Nodes(focused, GUI.context.data()), false);
else notifyHist(false);
}
@Override
public void keyPressed(final KeyEvent e) {
if(working) return;
super.keyPressed(e);
if(mainRects == null || e.isControlDown() || e.isAltDown()) return;
final int key = e.getKeyCode();
final boolean shift = e.isShiftDown();
final Context context = GUI.context;
final Data data = context.data();
final int size = data.size;
final Nodes current = context.current();
if(key == KeyEvent.VK_R) {
final Random rnd = new Random();
int pre = 0;
do {
pre = rnd.nextInt(size);
} while(data.kind(pre) != Data.ELEM || !ViewData.isLeaf(data, pre));
focused = pre;
notifySwitch(new Nodes(focused, data));
} else if(key == KeyEvent.VK_N || key == KeyEvent.VK_B) {
// jump to next node
int pre = (current.pre[0] + 1) % size;
while(data.kind(pre) != Data.ELEM || !ViewData.isLeaf(data, pre))
pre = (pre + 1) % size;
notifySwitch(new Nodes(pre, data));
} else if(key == KeyEvent.VK_P || key == KeyEvent.VK_Z) {
// jump to previous node
int pre = (current.pre[0] == 0 ? size : current.pre[0]) - 1;
while(data.kind(pre) != Data.ELEM || !ViewData.isLeaf(data, pre))
pre = (pre == 0 ? size : pre) - 1;
notifySwitch(new Nodes(pre, data));
} else if(key == KeyEvent.VK_S && !slide) {
// slide show
slide = true;
new Thread() {
@Override
public void run() {
while(slide) {
int pre = context.current().pre[0];
if(slideForward) {
pre = (pre + 1) % size;
while(!ViewData.isLeaf(data, pre)) pre = (pre + 1) % size;
} else {
pre = (pre == 0 ? size : pre) - 1;
while(!ViewData.isLeaf(data, pre))
pre = (pre == 0 ? size : pre) - 1;
}
notifySwitch(new Nodes(pre, data));
Performance.sleep(slideSpeed);
}
}
}.start();
}
final boolean cursor = key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN ||
key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT;
if(!cursor) return;
if(focusedRect == null) focusedRect = mainRects.get(0).clone();
int o = GUIProp.fontsize + 4;
if(key == KeyEvent.VK_UP) {
mouseY = focusedRect.y + (shift ? focusedRect.h -
GUIProp.fontsize : 0) - 1;
if(shift) mouseX = focusedRect.x + (focusedRect.w >> 1);
} else if(key == KeyEvent.VK_DOWN) {
mouseY = focusedRect.y + (shift ? o : focusedRect.h + 1);
if(shift) mouseX = focusedRect.x + (focusedRect.w >> 1);
} else if(key == KeyEvent.VK_LEFT) {
mouseX = focusedRect.x + (shift ? focusedRect.w -
GUIProp.fontsize : 0) - 1;
if(shift) mouseY = focusedRect.y + (focusedRect.h >> 1);
} else if(key == KeyEvent.VK_RIGHT) {
mouseX = focusedRect.x + (shift ? o : focusedRect.w + 1);
if(shift) mouseY = focusedRect.y + (focusedRect.h >> 1);
}
o = mainRects.get(0).w == getWidth() ? (o >> 1) + 1 : 0;
mouseX = Math.max(o, Math.min(getWidth() - o - 1, mouseX));
mouseY = Math.max(o << 1, Math.min(getHeight() - o - 1, mouseY));
if(focus()) repaint();
}
/** Slide show flag. */
boolean slide;
/** Slide show flag. */
int slideSpeed = 2000;
/** Slide show flag. */
boolean slideForward = true;
@Override
public void keyTyped(final KeyEvent e) {
if(working) return;
super.keyTyped(e);
final char ch = e.getKeyChar();
if(ch == '|') {
GUIProp.maplayout = (GUIProp.maplayout + 1) % MAPLAYOUTCHOICE.length;
View.notifyLayout();
}
}
@Override
public void componentResized(final ComponentEvent e) {
if(working) return;
focusedRect = null;
GUI.get().status.setPerformance(calc());
repaint();
}
} |
package org.camsrobotics.frc2016;
import org.camsrobotics.frc2016.auto.AutoExecutor;
import org.camsrobotics.frc2016.subsystems.Drive;
import org.camsrobotics.frc2016.subsystems.Intake;
import org.camsrobotics.frc2016.subsystems.Shooter;
import org.camsrobotics.frc2016.subsystems.Drive.DriveSignal;
import org.camsrobotics.lib.MultiLooper;
import edu.wpi.first.wpilibj.IterativeRobot;
/**
* This is where the magic happens!
*
* @author Wesley
*
*/
public class Robot extends IterativeRobot {
MultiLooper controllers = new MultiLooper("Controllers", 1/200.0);
MultiLooper slowControllers = new MultiLooper("SlowControllers", 1/100.0);
AutoExecutor auto = new AutoExecutor(AutoExecutor.Mode.LOW_BAR);
Drive drive = HardwareAdapter.kDrive;
Shooter shooter = HardwareAdapter.kShooter;
Intake intake = HardwareAdapter.kIntake;
DriverInput driverInput = HardwareAdapter.kDriverInput;
public void robotInit() {
System.out.println("NerdyBot Apotheosis Initialization");
controllers.addLoopable(shooter);
controllers.addLoopable(intake);
slowControllers.addLoopable(drive);
}
public void autonomousInit() {
System.out.println("NerdyBot Apotheosis Autonomous Start");
drive.resetEncoders();
auto.start();
controllers.start();
slowControllers.start();
}
public void autonomousPeriodic() {
}
public void teleopInit() {
System.out.println("NerdyBot Apotheosis Teleoperated Start");
drive.resetEncoders();
controllers.start();
slowControllers.start();
}
public void teleopPeriodic() {
}
public void disabledInit() {
System.out.println("NerdyBot Apotheosis Disabled...enable me!");
auto.stop();
controllers.stop();
slowControllers.stop();
drive.driveOpenLoop(DriveSignal.kStop);
drive.stop();
shooter.setDesiredRPM(0);
shooter.stop();
System.gc();
}
public void disabledPeriodic() {
}
public void allPeriodic() {
// TODO: add the logging
}
} |
package org.opencms.db;
import org.opencms.main.OpenCms;
import com.opencms.core.CmsException;
import com.opencms.file.CmsObject;
import com.opencms.file.CmsResource;
import com.opencms.file.CmsResourceTypeFolder;
import com.opencms.flex.CmsEvent;
import com.opencms.flex.I_CmsEventListener;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Allows to import resources from the filesystem or a ZIP file into the OpenCms VFS.<p>
*
* @author Alexander Kandzior (a.kandzior@alkacon.com)
*
* @version $Revision: 1.3 $
*/
public class CmsImportFolder {
private CmsObject m_cms;
/** The name of the import folder to load resources from */
private String m_importFolderName;
/** The import path in the OpenCms VFS */
private String m_importPath;
/** The resource (folder or ZIP file) to import from in the real file system */
private File m_importResource;
/** Will be true if the import resource a valid ZIP file */
private boolean m_validZipFile = false;
/** The import resource ZIP stream to load resources from */
private ZipInputStream m_zipStreamIn = null;
public CmsImportFolder(
byte[] content,
String importPath,
CmsObject cms,
boolean noSubFolder
) throws CmsException {
m_importPath = importPath;
m_cms = cms;
try {
// open the import resource
m_zipStreamIn = new ZipInputStream(new ByteArrayInputStream(content));
m_cms.readFolder(importPath);
// import the resources
importZipResource(m_zipStreamIn, m_importPath, noSubFolder);
} catch (Exception exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
public CmsImportFolder(String importFolderName, String importPath, CmsObject cms) throws CmsException {
try {
m_importFolderName = importFolderName;
m_importPath = importPath;
m_cms = cms;
// open the import resource
getImportResource();
// frist lock the path to import into.
m_cms.lockResource(m_importPath);
// import the resources
if (m_zipStreamIn == null) {
importResources(m_importResource, m_importPath);
} else {
importZipResource(m_zipStreamIn, m_importPath, false);
}
// all is done, unlock the resources
m_cms.unlockResource(m_importPath, false);
} catch (Exception exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Returns a byte array containing the content of a file from the real file system.<p>
*
* @param file the file to read
* @return the content of the read file
* @throws Exception if something goes wrong during file IO
*/
private byte[] getFileBytes(File file) throws Exception {
FileInputStream fileStream = new FileInputStream(file);
int charsRead = 0;
int size = new Long(file.length()).intValue();
byte[] buffer = new byte[size];
while (charsRead < size) {
charsRead += fileStream.read(buffer, charsRead, size - charsRead);
}
fileStream.close();
return buffer;
}
/**
* Returns the OpenCms file type, based on the extension of the given filename.<p>
*
* @param filename the file name to check
* @return the OpenCms file type, based on the extension of the given filename
* @throws CmsException if something goes wrong
*/
private String getFileType(String filename) throws CmsException {
String result = null;
int pos = filename.lastIndexOf('.');
if (pos >= 0) {
String suffix = filename.substring(pos + 1);
if ((suffix != null) && !("".equals(suffix)))
suffix = suffix.toLowerCase();
// read the known file extensions from the database
Hashtable extensions = m_cms.readFileExtensions();
if (extensions != null) {
result = (String)extensions.get(suffix);
}
}
if (result == null) {
result = "plain";
}
return result;
}
/**
* Stores the import resource in an Object member variable.<p>
* @throws CmsException if something goes wrong
*/
private void getImportResource() throws CmsException {
try {
// get the import resource
m_importResource = new File(m_importFolderName);
// check if this is a folder or a ZIP file
if (m_importResource.isFile()) {
try {
m_zipStreamIn = new ZipInputStream(new FileInputStream(m_importResource));
} catch (IOException e) {
// if file but no ZIP file throw an exception
throw new CmsException(e.toString());
}
}
} catch (Exception exc) {
throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc);
}
}
/**
* Imports the resources from the folder in the real file system to the OpenCms VFS.<p>
*
* @param folder the folder to import from
* @param importPath the OpenCms VFS import path to import to
* @throws Exception if something goes wrong during file IO
*/
private void importResources(File folder, String importPath) throws Exception {
String[] diskFiles = folder.list();
File currentFile;
for (int i = 0; i < diskFiles.length; i++) {
currentFile = new File(folder, diskFiles[i]);
if (currentFile.isDirectory()) {
// create directory in cms
m_cms.createResource(importPath, currentFile.getName(), CmsResourceTypeFolder.C_RESOURCE_TYPE_ID);
importResources(currentFile, importPath + currentFile.getName() + "/");
} else {
// import file into cms
int type = m_cms.getResourceTypeId(getFileType(currentFile.getName()));
byte[] content = getFileBytes(currentFile);
// create the file
m_cms.createResource(importPath, currentFile.getName(), type, null, content);
}
}
}
/**
* Imports the resources from a ZIP file in the real file system to the OpenCms VFS.<p>
*
* @param zipStreamIn the input Stream
* @param importPath the path in the vfs
* @param noSubFolder create subFolders or not
* @throws Exception if something goes wrong during file IO
*/
private void importZipResource(ZipInputStream zipStreamIn, String importPath, boolean noSubFolder) throws Exception {
boolean isFolder = false;
boolean exit = false;
int j, r, stop, charsRead, size;
int entries = 0;
int totalBytes = 0;
int offset = 0;
byte[] buffer = null;
boolean resourceExists;
while (true) {
// handle the single entries ...
j = 0;
stop = 0;
charsRead = 0;
totalBytes = 0;
// open the entry ...
ZipEntry entry = zipStreamIn.getNextEntry();
if (entry == null) {
break;
}
entries++; // count number of entries in zip
String actImportPath = importPath;
String filename = m_cms.getRequestContext().getFileTranslator().translateResource(entry.getName());
// separete path in direcotries an file name ...
StringTokenizer st = new StringTokenizer(filename, "/\\");
int count = st.countTokens();
String[] path = new String[count];
if (filename.endsWith("\\") || filename.endsWith("/")) {
isFolder = true; // last entry is a folder
} else {
isFolder = false; // last entry is a file
}
while (st.hasMoreTokens()) {
// store the files and folder names in array ...
path[j] = st.nextToken();
j++;
}
stop = isFolder?path.length:(path.length - 1);
if (noSubFolder) {
stop = 0;
}
// now write the folders ...
for (r = 0; r < stop; r++) {
try {
m_cms.createResource(actImportPath, path[r], CmsResourceTypeFolder.C_RESOURCE_TYPE_ID);
} catch (CmsException e) {
// of course some folders did already exist!
}
actImportPath += path[r];
actImportPath += "/";
}
if (! isFolder) {
// import file into cms
int type = m_cms.getResourceTypeId(getFileType(path[path.length - 1]));
size = new Long(entry.getSize()).intValue();
if (size == -1) {
Vector v = new Vector();
while (true) {
buffer = new byte[512];
offset = 0;
while (offset < buffer.length) {
charsRead = zipStreamIn.read(buffer, offset, buffer.length - offset);
if (charsRead == -1) {
exit = true;
break; // end of stream
}
offset += charsRead;
totalBytes += charsRead;
}
if (offset > 0) {
v.addElement(buffer);
}
if (exit) {
exit = false;
break;
}
}
buffer = new byte[totalBytes];
offset = 0;
byte[] act = null;
for (int z = 0; z < v.size() - 1; z++) {
act = (byte[])v.elementAt(z);
System.arraycopy(act, 0, buffer, offset, act.length);
offset += act.length;
}
act = (byte[])v.lastElement();
if ((totalBytes > act.length) && (totalBytes % act.length != 0)) {
totalBytes = totalBytes % act.length;
} else if ((totalBytes > act.length) && (totalBytes % act.length == 0)) {
totalBytes = act.length;
}
System.arraycopy(act, 0, buffer, offset, totalBytes);
// handle empty files ...
if (totalBytes == 0) {
buffer = " ".getBytes();
}
} else {
// size was read clearly ...
buffer = new byte[size];
while (charsRead < size) {
charsRead += zipStreamIn.read(buffer, charsRead, size - charsRead);
}
// handle empty files ...
if (size == 0) {
buffer = " ".getBytes();
}
}
filename = actImportPath + path[path.length - 1];
try {
m_cms.lockResource(filename, true);
m_cms.readFileHeader(filename);
resourceExists = true;
} catch (CmsException e) {
resourceExists = false;
}
if (resourceExists) {
CmsResource res = m_cms.readFileHeader(filename, true);
m_cms.deleteAllProperties(filename);
m_cms.replaceResource(filename, type, Collections.EMPTY_MAP, buffer);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROPERTY_MAP_MODIFIED, Collections.singletonMap("resource", res)));
} else {
m_cms.createResource(actImportPath, path[path.length - 1], type, Collections.EMPTY_MAP, buffer);
}
}
// close the entry ...
zipStreamIn.closeEntry();
}
zipStreamIn.close();
if (entries > 0) {
// at least one entry, got a valid zip file ...
m_validZipFile = true;
}
}
/**
* Returns true if a valid ZIP file was imported.<p>
*
* @return true if a valid ZIP file was imported
*/
public boolean isValidZipFile() {
return m_validZipFile;
}
} |
package org.pentaho.di.trans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs.FileName;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.pentaho.di.cluster.ClusterSchema;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.LastUsedFile;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.SQLStatement;
import org.pentaho.di.core.changed.ChangedFlag;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleRowException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.gui.GUIPositionInterface;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.gui.SpoonFactory;
import org.pentaho.di.core.gui.UndoInterface;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.reflection.StringSearchResult;
import org.pentaho.di.core.reflection.StringSearcher;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.undo.TransAction;
import org.pentaho.di.core.util.StringUtil;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.core.xml.XMLInterface;
import org.pentaho.di.partition.PartitionSchema;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.resource.ResourceDefinition;
import org.pentaho.di.resource.ResourceExportInterface;
import org.pentaho.di.resource.ResourceNamingInterface;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.di.shared.SharedObjectInterface;
import org.pentaho.di.shared.SharedObjects;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepErrorMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.step.StepPartitioningMeta;
import org.pentaho.di.trans.steps.mapping.MappingMeta;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* This class defines a transformation and offers methods to save and load it
* from XML or a PDI database repository.
*
* @since 20-jun-2003
* @author Matt
*/
public class TransMeta extends ChangedFlag implements XMLInterface, Comparator<TransMeta>, Comparable<TransMeta>,
Cloneable, UndoInterface,
HasDatabasesInterface, VariableSpace, EngineMetaInterface,
ResourceExportInterface, HasSlaveServersInterface
{
public static final String XML_TAG = "transformation";
private static LogWriter log = LogWriter.getInstance();
// private List inputFiles;
private List<DatabaseMeta> databases;
private List<StepMeta> steps;
private List<TransHopMeta> hops;
private List<NotePadMeta> notes;
private List<TransDependency> dependencies;
private List<SlaveServer> slaveServers;
private List<ClusterSchema> clusterSchemas;
private List<PartitionSchema> partitionSchemas;
private RepositoryDirectory directory;
private RepositoryDirectory directoryTree;
private String name;
private String description;
private String extended_description;
private String trans_version;
private int trans_status;
private String filename;
private StepMeta readStep;
private StepMeta writeStep;
private StepMeta inputStep;
private StepMeta outputStep;
private StepMeta updateStep;
private StepMeta rejectedStep;
private String logTable;
private DatabaseMeta logConnection;
private int sizeRowset;
private DatabaseMeta maxDateConnection;
private String maxDateTable;
private String maxDateField;
private double maxDateOffset;
private double maxDateDifference;
private String arguments[];
private Hashtable<String,Counter> counters;
private boolean changed_steps, changed_databases, changed_hops, changed_notes;
private List<TransAction> undo;
private int max_undo;
private int undo_position;
private DBCache dbCache;
private long id;
private boolean useBatchId;
private boolean logfieldUsed;
private String createdUser, modifiedUser;
private Date createdDate, modifiedDate;
private int sleepTimeEmpty;
private int sleepTimeFull;
private Result previousResult;
private List<RowMetaAndData> resultRows;
private List<ResultFile> resultFiles;
private boolean usingUniqueConnections;
private boolean feedbackShown;
private int feedbackSize;
/** flag to indicate thread management usage. Set to default to false from version 2.5.0 on. Before that it was enabled by default. */
private boolean usingThreadPriorityManagment;
/** If this is null, we load from the default shared objects file : $KETTLE_HOME/.kettle/shared.xml */
private String sharedObjectsFile;
private VariableSpace variables = new Variables();
/** The slave-step-copy/partition distribution. Only used for slave transformations in a clustering environment. */
private SlaveStepCopyPartitionDistribution slaveStepCopyPartitionDistribution;
/** Just a flag indicating that this is a slave transformation - internal use only, no GUI option */
private boolean slaveTransformation;
/** The repository to reference in the one-off case that it is needed */
private Repository repository;
public static final int TYPE_UNDO_CHANGE = 1;
public static final int TYPE_UNDO_NEW = 2;
public static final int TYPE_UNDO_DELETE = 3;
public static final int TYPE_UNDO_POSITION = 4;
public static final String desc_type_undo[] = { "", Messages.getString("TransMeta.UndoTypeDesc.UndoChange"), Messages.getString("TransMeta.UndoTypeDesc.UndoNew"), Messages.getString("TransMeta.UndoTypeDesc.UndoDelete"), Messages.getString("TransMeta.UndoTypeDesc.UndoPosition") }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
private static final String XML_TAG_INFO = "info";
private static final String XML_TAG_ORDER = "order";
private static final String XML_TAG_NOTEPADS = "notepads";
private static final String XML_TAG_DEPENDENCIES = "dependencies";
private static final String XML_TAG_PARTITIONSCHEMAS = "partitionschemas";
private static final String XML_TAG_SLAVESERVERS = "slaveservers";
private static final String XML_TAG_CLUSTERSCHEMAS = "clusterschemas";
private static final String XML_TAG_STEP_ERROR_HANDLING = "step_error_handling";
/**
* Builds a new empty transformation.
*/
public TransMeta()
{
clear();
initializeVariablesFrom(null);
}
/**
* Builds a new empty transformation with a set of variables to inherit from.
* @param parent the variable space to inherit from
*/
public TransMeta(VariableSpace parent)
{
clear();
initializeVariablesFrom(parent);
}
/**
* Constructs a new transformation specifying the filename, name and arguments.
*
* @param filename The filename of the transformation
* @param name The name of the transformation
* @param arguments The arguments as Strings
*/
public TransMeta(String filename, String name, String arguments[])
{
clear();
this.filename = filename;
this.name = name;
this.arguments = arguments;
initializeVariablesFrom(null);
}
/**
* Compares two transformation on name, filename
*/
public int compare(TransMeta t1, TransMeta t2)
{
if (Const.isEmpty(t1.getName()) && !Const.isEmpty(t2.getName())) return -1;
if (!Const.isEmpty(t1.getName()) && Const.isEmpty(t2.getName())) return 1;
if (Const.isEmpty(t1.getName()) && Const.isEmpty(t2.getName()))
{
if (Const.isEmpty(t1.getFilename()) && !Const.isEmpty(t2.getFilename())) return -1;
if (!Const.isEmpty(t1.getFilename()) && Const.isEmpty(t2.getFilename())) return 1;
if (Const.isEmpty(t1.getFilename()) && Const.isEmpty(t2.getFilename()))
{
return 0;
}
return t1.getFilename().compareTo(t2.getFilename());
}
return t1.getName().compareTo(t2.getName());
}
public int compareTo(TransMeta o)
{
return compare(this, o);
}
public boolean equals(Object obj)
{
if (!(obj instanceof TransMeta))
return false;
return compare(this, (TransMeta)obj)==0;
}
@Override
public Object clone() {
return realClone(true);
}
public Object realClone(boolean doClear) {
try {
TransMeta transMeta = (TransMeta) super.clone();
if (doClear) {
transMeta.clear();
} else {
// Clear out the things we're replacing below
transMeta.databases = new ArrayList<DatabaseMeta>();
transMeta.steps = new ArrayList<StepMeta>();
transMeta.hops = new ArrayList<TransHopMeta>();
transMeta.notes = new ArrayList<NotePadMeta>();
transMeta.dependencies = new ArrayList<TransDependency>();
transMeta.partitionSchemas = new ArrayList<PartitionSchema>();
transMeta.slaveServers = new ArrayList<SlaveServer>();
transMeta.clusterSchemas = new ArrayList<ClusterSchema>();
}
for (DatabaseMeta db : databases) transMeta.addDatabase((DatabaseMeta)db.clone());
for (StepMeta step : steps) transMeta.addStep((StepMeta) step.clone());
for (TransHopMeta hop : hops) transMeta.addTransHop((TransHopMeta) hop.clone());
for (NotePadMeta note : notes) transMeta.addNote((NotePadMeta)note.clone());
for (TransDependency dep : dependencies) transMeta.addDependency((TransDependency)dep.clone());
for (SlaveServer slave : slaveServers) transMeta.getSlaveServers().add((SlaveServer)slave.clone());
for (ClusterSchema schema : clusterSchemas) transMeta.getClusterSchemas().add((ClusterSchema)schema.clone());
for (PartitionSchema schema : partitionSchemas) transMeta.getPartitionSchemas().add((PartitionSchema)schema.clone());
return transMeta;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
/**
* Get the database ID in the repository for this object.
*
* @return the database ID in the repository for this object.
*/
public long getID()
{
return id;
}
/**
* Set the database ID for this object in the repository.
*
* @param id the database ID for this object in the repository.
*/
public void setID(long id)
{
this.id = id;
}
/**
* Clears the transformation.
*/
public void clear()
{
setID(-1L);
databases = new ArrayList<DatabaseMeta>();
steps = new ArrayList<StepMeta>();
hops = new ArrayList<TransHopMeta>();
notes = new ArrayList<NotePadMeta>();
dependencies = new ArrayList<TransDependency>();
partitionSchemas = new ArrayList<PartitionSchema>();
slaveServers = new ArrayList<SlaveServer>();
clusterSchemas = new ArrayList<ClusterSchema>();
slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution();
name = null;
description=null;
trans_status=-1;
trans_version=null;
extended_description=null;
filename = null;
readStep = null;
writeStep = null;
inputStep = null;
outputStep = null;
updateStep = null;
logTable = null;
logConnection = null;
sizeRowset = Const.ROWS_IN_ROWSET;
sleepTimeEmpty = Const.TIMEOUT_GET_MILLIS;
sleepTimeFull = Const.TIMEOUT_PUT_MILLIS;
maxDateConnection = null;
maxDateTable = null;
maxDateField = null;
maxDateOffset = 0.0;
maxDateDifference = 0.0;
undo = new ArrayList<TransAction>();
max_undo = Const.MAX_UNDO;
undo_position = -1;
counters = new Hashtable<String,Counter>();
resultRows = null;
clearUndo();
clearChanged();
useBatchId = true; // Make this one the default from now on...
logfieldUsed = false; // Don't use the log-field by default...
createdUser = "-"; //$NON-NLS-1$
createdDate = new Date(); //$NON-NLS-1$
modifiedUser = "-"; //$NON-NLS-1$
modifiedDate = new Date(); //$NON-NLS-1$
// LOAD THE DATABASE CACHE!
dbCache = DBCache.getInstance();
directoryTree = new RepositoryDirectory();
// Default directory: root
directory = directoryTree;
resultRows = new ArrayList<RowMetaAndData>();
resultFiles = new ArrayList<ResultFile>();
feedbackShown = true;
feedbackSize = Const.ROWS_UPDATE;
usingThreadPriorityManagment = false; // set to false in version 2.5.0
}
public void clearUndo()
{
undo = new ArrayList<TransAction>();
undo_position = -1;
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#getDatabases()
*/
public List<DatabaseMeta> getDatabases()
{
return databases;
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#setDatabases(java.util.ArrayList)
*/
public void setDatabases(List<DatabaseMeta> databases)
{
this.databases = databases;
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#addDatabase(org.pentaho.di.core.database.DatabaseMeta)
*/
public void addDatabase(DatabaseMeta databaseMeta)
{
databases.add(databaseMeta);
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#addOrReplaceDatabase(org.pentaho.di.core.database.DatabaseMeta)
*/
public void addOrReplaceDatabase(DatabaseMeta databaseMeta)
{
int index = databases.indexOf(databaseMeta);
if (index<0)
{
databases.add(databaseMeta);
}
else
{
DatabaseMeta previous = getDatabase(index);
previous.replaceMeta(databaseMeta);
}
changed_databases = true;
}
/**
* Add a new step to the transformation
*
* @param stepMeta The step to be added.
*/
public void addStep(StepMeta stepMeta)
{
steps.add(stepMeta);
changed_steps = true;
}
/**
* Add a new step to the transformation if that step didn't exist yet.
* Otherwise, replace the step.
*
* @param stepMeta The step to be added.
*/
public void addOrReplaceStep(StepMeta stepMeta)
{
int index = steps.indexOf(stepMeta);
if (index<0)
{
steps.add(stepMeta);
}
else
{
StepMeta previous = getStep(index);
previous.replaceMeta(stepMeta);
}
changed_steps = true;
}
/**
* Add a new hop to the transformation.
*
* @param hi The hop to be added.
*/
public void addTransHop(TransHopMeta hi)
{
hops.add(hi);
changed_hops = true;
}
/**
* Add a new note to the transformation.
*
* @param ni The note to be added.
*/
public void addNote(NotePadMeta ni)
{
notes.add(ni);
changed_notes = true;
}
/**
* Add a new dependency to the transformation.
*
* @param td The transformation dependency to be added.
*/
public void addDependency(TransDependency td)
{
dependencies.add(td);
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#addDatabase(int, org.pentaho.di.core.database.DatabaseMeta)
*/
public void addDatabase(int p, DatabaseMeta ci)
{
databases.add(p, ci);
}
/**
* Add a new step to the transformation
*
* @param p The location
* @param stepMeta The step to be added.
*/
public void addStep(int p, StepMeta stepMeta)
{
steps.add(p, stepMeta);
changed_steps = true;
}
/**
* Add a new hop to the transformation on a certain location.
*
* @param p the location
* @param hi The hop to be added.
*/
public void addTransHop(int p, TransHopMeta hi)
{
hops.add(p, hi);
changed_hops = true;
}
/**
* Add a new note to the transformation on a certain location.
*
* @param p The location
* @param ni The note to be added.
*/
public void addNote(int p, NotePadMeta ni)
{
notes.add(p, ni);
changed_notes = true;
}
/**
* Add a new dependency to the transformation on a certain location
*
* @param p The location.
* @param td The transformation dependency to be added.
*/
public void addDependency(int p, TransDependency td)
{
dependencies.add(p, td);
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#getDatabase(int)
*/
public DatabaseMeta getDatabase(int i)
{
return databases.get(i);
}
/**
* Get an ArrayList of defined steps.
*
* @return an ArrayList of defined steps.
*/
public List<StepMeta> getSteps()
{
return steps;
}
/**
* Retrieves a step on a certain location.
*
* @param i The location.
* @return The step information.
*/
public StepMeta getStep(int i)
{
return steps.get(i);
}
/**
* Retrieves a hop on a certain location.
*
* @param i The location.
* @return The hop information.
*/
public TransHopMeta getTransHop(int i)
{
return hops.get(i);
}
/**
* Retrieves notepad information on a certain location.
*
* @param i The location
* @return The notepad information.
*/
public NotePadMeta getNote(int i)
{
return notes.get(i);
}
/**
* Retrieves a dependency on a certain location.
*
* @param i The location.
* @return The dependency.
*/
public TransDependency getDependency(int i)
{
return dependencies.get(i);
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#removeDatabase(int)
*/
public void removeDatabase(int i)
{
if (i < 0 || i >= databases.size()) return;
databases.remove(i);
changed_databases = true;
}
/**
* Removes a step from the transformation on a certain location.
*
* @param i The location
*/
public void removeStep(int i)
{
if (i < 0 || i >= steps.size()) return;
steps.remove(i);
changed_steps = true;
}
/**
* Removes a hop from the transformation on a certain location.
*
* @param i The location
*/
public void removeTransHop(int i)
{
if (i < 0 || i >= hops.size()) return;
hops.remove(i);
changed_hops = true;
}
/**
* Removes a note from the transformation on a certain location.
*
* @param i The location
*/
public void removeNote(int i)
{
if (i < 0 || i >= notes.size()) return;
notes.remove(i);
changed_notes = true;
}
public void raiseNote(int p)
{
// if valid index and not last index
if ((p >=0) && (p < notes.size()-1))
{
NotePadMeta note = notes.remove(p);
notes.add(note);
changed_notes = true;
}
}
public void lowerNote(int p)
{
// if valid index and not first index
if ((p >0) && (p < notes.size()))
{
NotePadMeta note = notes.remove(p);
notes.add(0, note);
changed_notes = true;
}
}
/**
* Removes a dependency from the transformation on a certain location.
*
* @param i The location
*/
public void removeDependency(int i)
{
if (i < 0 || i >= dependencies.size()) return;
dependencies.remove(i);
}
/**
* Clears all the dependencies from the transformation.
*/
public void removeAllDependencies()
{
dependencies.clear();
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#nrDatabases()
*/
public int nrDatabases()
{
return databases.size();
}
/**
* Count the nr of steps in the transformation.
*
* @return The nr of steps
*/
public int nrSteps()
{
return steps.size();
}
/**
* Count the nr of hops in the transformation.
*
* @return The nr of hops
*/
public int nrTransHops()
{
return hops.size();
}
/**
* Count the nr of notes in the transformation.
*
* @return The nr of notes
*/
public int nrNotes()
{
return notes.size();
}
/**
* Count the nr of dependencies in the transformation.
*
* @return The nr of dependencies
*/
public int nrDependencies()
{
return dependencies.size();
}
/**
* Changes the content of a step on a certain position
*
* @param i The position
* @param stepMeta The Step
*/
public void setStep(int i, StepMeta stepMeta)
{
steps.set(i, stepMeta);
}
/**
* Changes the content of a hop on a certain position
*
* @param i The position
* @param hi The hop
*/
public void setTransHop(int i, TransHopMeta hi)
{
hops.set(i, hi);
}
/**
* Counts the number of steps that are actually used in the transformation.
*
* @return the number of used steps.
*/
public int nrUsedSteps()
{
int nr = 0;
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (isStepUsedInTransHops(stepMeta)) nr++;
}
return nr;
}
/**
* Gets a used step on a certain location
*
* @param lu The location
* @return The used step.
*/
public StepMeta getUsedStep(int lu)
{
int nr = 0;
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (isStepUsedInTransHops(stepMeta))
{
if (lu == nr) return stepMeta;
nr++;
}
}
return null;
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#findDatabase(java.lang.String)
*/
public DatabaseMeta findDatabase(String name)
{
int i;
for (i = 0; i < nrDatabases(); i++)
{
DatabaseMeta ci = getDatabase(i);
if (ci.getName().equalsIgnoreCase(name)) { return ci; }
}
return null;
}
/**
* Searches the list of steps for a step with a certain name
*
* @param name The name of the step to look for
* @return The step information or null if no nothing was found.
*/
public StepMeta findStep(String name)
{
return findStep(name, null);
}
/**
* Searches the list of steps for a step with a certain name while excluding one step.
*
* @param name The name of the step to look for
* @param exclude The step information to exclude.
* @return The step information or null if nothing was found.
*/
public StepMeta findStep(String name, StepMeta exclude)
{
if (name==null) return null;
int excl = -1;
if (exclude != null) excl = indexOfStep(exclude);
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (i != excl && stepMeta.getName().equalsIgnoreCase(name)) { return stepMeta; }
}
return null;
}
/**
* Searches the list of hops for a hop with a certain name
*
* @param name The name of the hop to look for
* @return The hop information or null if nothing was found.
*/
public TransHopMeta findTransHop(String name)
{
int i;
for (i = 0; i < nrTransHops(); i++)
{
TransHopMeta hi = getTransHop(i);
if (hi.toString().equalsIgnoreCase(name)) { return hi; }
}
return null;
}
/**
* Search all hops for a hop where a certain step is at the start.
*
* @param fromstep The step at the start of the hop.
* @return The hop or null if no hop was found.
*/
public TransHopMeta findTransHopFrom(StepMeta fromstep)
{
int i;
for (i = 0; i < nrTransHops(); i++)
{
TransHopMeta hi = getTransHop(i);
if (hi.getFromStep() != null && hi.getFromStep().equals(fromstep)) // return the first
{ return hi; }
}
return null;
}
/**
* Find a certain hop in the transformation..
*
* @param hi The hop information to look for.
* @return The hop or null if no hop was found.
*/
public TransHopMeta findTransHop(TransHopMeta hi)
{
return findTransHop(hi.getFromStep(), hi.getToStep());
}
/**
* Search all hops for a hop where a certain step is at the start and another is at the end.
*
* @param from The step at the start of the hop.
* @param to The step at the end of the hop.
* @return The hop or null if no hop was found.
*/
public TransHopMeta findTransHop(StepMeta from, StepMeta to)
{
return findTransHop(from, to, false);
}
/**
* Search all hops for a hop where a certain step is at the start and another is at the end.
*
* @param from The step at the start of the hop.
* @param to The step at the end of the hop.
* @return The hop or null if no hop was found.
*/
public TransHopMeta findTransHop(StepMeta from, StepMeta to, boolean disabledToo)
{
int i;
for (i = 0; i < nrTransHops(); i++)
{
TransHopMeta hi = getTransHop(i);
if (hi.isEnabled() || disabledToo)
{
if (hi.getFromStep() != null && hi.getToStep() != null && hi.getFromStep().equals(from) && hi.getToStep().equals(to)) { return hi; }
}
}
return null;
}
/**
* Search all hops for a hop where a certain step is at the end.
*
* @param tostep The step at the end of the hop.
* @return The hop or null if no hop was found.
*/
public TransHopMeta findTransHopTo(StepMeta tostep)
{
int i;
for (i = 0; i < nrTransHops(); i++)
{
TransHopMeta hi = getTransHop(i);
if (hi.getToStep() != null && hi.getToStep().equals(tostep)) // Return the first!
{ return hi; }
}
return null;
}
/**
* Determines whether or not a certain step is informative. This means that the previous step is sending information
* to this step, but only informative. This means that this step is using the information to process the actual
* stream of data. We use this in StreamLookup, TableInput and other types of steps.
*
* @param this_step The step that is receiving information.
* @param prev_step The step that is sending information
* @return true if prev_step if informative for this_step.
*/
public boolean isStepInformative(StepMeta this_step, StepMeta prev_step)
{
String[] infoSteps = this_step.getStepMetaInterface().getInfoSteps();
if (infoSteps == null) return false;
for (int i = 0; i < infoSteps.length; i++)
{
if (prev_step.getName().equalsIgnoreCase(infoSteps[i])) return true;
}
return false;
}
/**
* Counts the number of previous steps for a step name.
*
* @param stepname The name of the step to start from
* @return The number of preceding steps.
*/
public int findNrPrevSteps(String stepname)
{
return findNrPrevSteps(findStep(stepname), false);
}
/**
* Counts the number of previous steps for a step name taking into account whether or not they are informational.
*
* @param stepname The name of the step to start from
* @return The number of preceding steps.
*/
public int findNrPrevSteps(String stepname, boolean info)
{
return findNrPrevSteps(findStep(stepname), info);
}
/**
* Find the number of steps that precede the indicated step.
*
* @param stepMeta The source step
*
* @return The number of preceding steps found.
*/
public int findNrPrevSteps(StepMeta stepMeta)
{
return findNrPrevSteps(stepMeta, false);
}
/**
* Find the previous step on a certain location.
*
* @param stepname The source step name
* @param nr the location
*
* @return The preceding step found.
*/
public StepMeta findPrevStep(String stepname, int nr)
{
return findPrevStep(findStep(stepname), nr);
}
/**
* Find the previous step on a certain location taking into account the steps being informational or not.
*
* @param stepname The name of the step
* @param nr The location
* @param info true if we only want the informational steps.
* @return The step information
*/
public StepMeta findPrevStep(String stepname, int nr, boolean info)
{
return findPrevStep(findStep(stepname), nr, info);
}
/**
* Find the previous step on a certain location.
*
* @param stepMeta The source step information
* @param nr the location
*
* @return The preceding step found.
*/
public StepMeta findPrevStep(StepMeta stepMeta, int nr)
{
return findPrevStep(stepMeta, nr, false);
}
/**
* Count the number of previous steps on a certain location taking into account the steps being informational or
* not.
*
* @param stepMeta The name of the step
* @param info true if we only want the informational steps.
* @return The number of preceding steps
*/
public int findNrPrevSteps(StepMeta stepMeta, boolean info)
{
int count = 0;
int i;
for (i = 0; i < nrTransHops(); i++) // Look at all the hops;
{
TransHopMeta hi = getTransHop(i);
if (hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta))
{
// Check if this previous step isn't informative (StreamValueLookup)
// We don't want fields from this stream to show up!
if (info || !isStepInformative(stepMeta, hi.getFromStep()))
{
count++;
}
}
}
return count;
}
/**
* Find the previous step on a certain location taking into account the steps being informational or not.
*
* @param stepMeta The step
* @param nr The location
* @param info true if we only want the informational steps.
* @return The preceding step information
*/
public StepMeta findPrevStep(StepMeta stepMeta, int nr, boolean info)
{
int count = 0;
int i;
for (i = 0; i < nrTransHops(); i++) // Look at all the hops;
{
TransHopMeta hi = getTransHop(i);
if (hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta))
{
if (info || !isStepInformative(stepMeta, hi.getFromStep()))
{
if (count == nr) { return hi.getFromStep(); }
count++;
}
}
}
return null;
}
/**
* Get the informational steps for a certain step. An informational step is a step that provides information for
* lookups etc.
*
* @param stepMeta The name of the step
* @return The informational steps found
*/
public StepMeta[] getInfoStep(StepMeta stepMeta)
{
String[] infoStepName = stepMeta.getStepMetaInterface().getInfoSteps();
if (infoStepName == null) return null;
StepMeta[] infoStep = new StepMeta[infoStepName.length];
for (int i = 0; i < infoStep.length; i++)
{
infoStep[i] = findStep(infoStepName[i]);
}
return infoStep;
}
/**
* Find the the number of informational steps for a certains step.
*
* @param stepMeta The step
* @return The number of informational steps found.
*/
public int findNrInfoSteps(StepMeta stepMeta)
{
if (stepMeta == null) return 0;
int count = 0;
for (int i = 0; i < nrTransHops(); i++) // Look at all the hops;
{
TransHopMeta hi = getTransHop(i);
if (hi == null || hi.getToStep() == null)
{
log.logError(toString(), Messages.getString("TransMeta.Log.DestinationOfHopCannotBeNull")); //$NON-NLS-1$
}
if (hi != null && hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta))
{
// Check if this previous step isn't informative (StreamValueLookup)
// We don't want fields from this stream to show up!
if (isStepInformative(stepMeta, hi.getFromStep()))
{
count++;
}
}
}
return count;
}
/**
* Find the informational fields coming from an informational step into the step specified.
*
* @param stepname The name of the step
* @return A row containing fields with origin.
*/
public RowMetaInterface getPrevInfoFields(String stepname) throws KettleStepException
{
return getPrevInfoFields(findStep(stepname));
}
/**
* Find the informational fields coming from an informational step into the step specified.
*
* @param stepMeta The receiving step
* @return A row containing fields with origin.
*/
public RowMetaInterface getPrevInfoFields(StepMeta stepMeta) throws KettleStepException
{
RowMetaInterface row = new RowMeta();
for (int i = 0; i < nrTransHops(); i++) // Look at all the hops;
{
TransHopMeta hi = getTransHop(i);
if (hi.isEnabled() && hi.getToStep().equals(stepMeta))
{
if (isStepInformative(stepMeta, hi.getFromStep()))
{
getThisStepFields(stepMeta, null, row);
return row;
}
}
}
return row;
}
/**
* Find the number of succeeding steps for a certain originating step.
*
* @param stepMeta The originating step
* @return The number of succeeding steps.
*/
public int findNrNextSteps(StepMeta stepMeta)
{
int count = 0;
int i;
for (i = 0; i < nrTransHops(); i++) // Look at all the hops;
{
TransHopMeta hi = getTransHop(i);
if (hi.isEnabled() && hi.getFromStep().equals(stepMeta)) count++;
}
return count;
}
/**
* Find the succeeding step at a location for an originating step.
*
* @param stepMeta The originating step
* @param nr The location
* @return The step found.
*/
public StepMeta findNextStep(StepMeta stepMeta, int nr)
{
int count = 0;
int i;
for (i = 0; i < nrTransHops(); i++) // Look at all the hops;
{
TransHopMeta hi = getTransHop(i);
if (hi.isEnabled() && hi.getFromStep().equals(stepMeta))
{
if (count == nr) { return hi.getToStep(); }
count++;
}
}
return null;
}
/**
* Retrieve an array of preceding steps for a certain destination step.
*
* @param stepMeta The destination step
* @return An array containing the preceding steps.
*/
public StepMeta[] getPrevSteps(StepMeta stepMeta)
{
int nr = findNrPrevSteps(stepMeta, true);
StepMeta retval[] = new StepMeta[nr];
for (int i = 0; i < nr; i++)
{
retval[i] = findPrevStep(stepMeta, i, true);
}
return retval;
}
/**
* Retrieve an array of succeeding step names for a certain originating step name.
*
* @param stepname The originating step name
* @return An array of succeeding step names
*/
public String[] getPrevStepNames(String stepname)
{
return getPrevStepNames(findStep(stepname));
}
/**
* Retrieve an array of preceding steps for a certain destination step.
*
* @param stepMeta The destination step
* @return an array of preceding step names.
*/
public String[] getPrevStepNames(StepMeta stepMeta)
{
StepMeta prevStepMetas[] = getPrevSteps(stepMeta);
String retval[] = new String[prevStepMetas.length];
for (int x = 0; x < prevStepMetas.length; x++)
retval[x] = prevStepMetas[x].getName();
return retval;
}
/**
* Retrieve an array of succeeding steps for a certain originating step.
*
* @param stepMeta The originating step
* @return an array of succeeding steps.
*/
public StepMeta[] getNextSteps(StepMeta stepMeta)
{
int nr = findNrNextSteps(stepMeta);
StepMeta retval[] = new StepMeta[nr];
for (int i = 0; i < nr; i++)
{
retval[i] = findNextStep(stepMeta, i);
}
return retval;
}
/**
* Retrieve an array of succeeding step names for a certain originating step.
*
* @param stepMeta The originating step
* @return an array of succeeding step names.
*/
public String[] getNextStepNames(StepMeta stepMeta)
{
StepMeta nextStepMeta[] = getNextSteps(stepMeta);
String retval[] = new String[nextStepMeta.length];
for (int x = 0; x < nextStepMeta.length; x++)
retval[x] = nextStepMeta[x].getName();
return retval;
}
/**
* Find the step that is located on a certain point on the canvas, taking into account the icon size.
*
* @param x the x-coordinate of the point queried
* @param y the y-coordinate of the point queried
* @return The step information if a step is located at the point. Otherwise, if no step was found: null.
*/
public StepMeta getStep(int x, int y, int iconsize)
{
int i, s;
s = steps.size();
for (i = s - 1; i >= 0; i--) // Back to front because drawing goes from start to end
{
StepMeta stepMeta = steps.get(i);
if (partOfTransHop(stepMeta) || stepMeta.isDrawn()) // Only consider steps from active or inactive hops!
{
Point p = stepMeta.getLocation();
if (p != null)
{
if (x >= p.x && x <= p.x + iconsize && y >= p.y && y <= p.y + iconsize + 20) { return stepMeta; }
}
}
}
return null;
}
/**
* Find the note that is located on a certain point on the canvas.
*
* @param x the x-coordinate of the point queried
* @param y the y-coordinate of the point queried
* @return The note information if a note is located at the point. Otherwise, if nothing was found: null.
*/
public NotePadMeta getNote(int x, int y)
{
int i, s;
s = notes.size();
for (i = s - 1; i >= 0; i--) // Back to front because drawing goes from start to end
{
NotePadMeta ni = notes.get(i);
Point loc = ni.getLocation();
Point p = new Point(loc.x, loc.y);
if (x >= p.x && x <= p.x + ni.width + 2 * Const.NOTE_MARGIN && y >= p.y && y <= p.y + ni.height + 2 * Const.NOTE_MARGIN) { return ni; }
}
return null;
}
/**
* Determines whether or not a certain step is part of a hop.
*
* @param stepMeta The step queried
* @return true if the step is part of a hop.
*/
public boolean partOfTransHop(StepMeta stepMeta)
{
int i;
for (i = 0; i < nrTransHops(); i++)
{
TransHopMeta hi = getTransHop(i);
if (hi.getFromStep() == null || hi.getToStep() == null) return false;
if (hi.getFromStep().equals(stepMeta) || hi.getToStep().equals(stepMeta)) return true;
}
return false;
}
/**
* Returns the fields that are emitted by a certain step name
*
* @param stepname The stepname of the step to be queried.
* @return A row containing the fields emitted.
*/
public RowMetaInterface getStepFields(String stepname) throws KettleStepException
{
StepMeta stepMeta = findStep(stepname);
if (stepMeta != null)
return getStepFields(stepMeta);
else
return null;
}
/**
* Returns the fields that are emitted by a certain step
*
* @param stepMeta The step to be queried.
* @return A row containing the fields emitted.
*/
public RowMetaInterface getStepFields(StepMeta stepMeta) throws KettleStepException
{
return getStepFields(stepMeta, null);
}
public RowMetaInterface getStepFields(StepMeta[] stepMeta) throws KettleStepException
{
RowMetaInterface fields = new RowMeta();
for (int i = 0; i < stepMeta.length; i++)
{
RowMetaInterface flds = getStepFields(stepMeta[i]);
if (flds != null) fields.mergeRowMeta(flds);
}
return fields;
}
/**
* Returns the fields that are emitted by a certain step
*
* @param stepMeta The step to be queried.
* @param monitor The progress monitor for progress dialog. (null if not used!)
* @return A row containing the fields emitted.
*/
public RowMetaInterface getStepFields(StepMeta stepMeta, IProgressMonitor monitor) throws KettleStepException
{
return getStepFields(stepMeta, null, monitor);
}
/**
* Returns the fields that are emitted by a certain step
*
* @param stepMeta The step to be queried.
* @param targetStep the target step
* @param monitor The progress monitor for progress dialog. (null if not used!)
* @return A row containing the fields emitted.
*/
public RowMetaInterface getStepFields(StepMeta stepMeta, StepMeta targetStep, IProgressMonitor monitor) throws KettleStepException
{
RowMetaInterface row = new RowMeta();
if (stepMeta == null) return row;
// See if the step is sending ERROR rows to the specified target step.
if (targetStep!=null && stepMeta.isSendingErrorRowsToStep(targetStep))
{
// The error rows are the same as the input rows for
// the step but with the selected error fields added
row = getPrevStepFields(stepMeta);
// Add to this the error fields...
StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta();
row.addRowMeta(stepErrorMeta.getErrorFields());
return row;
}
// Resume the regular program...
log.logDebug(toString(), Messages.getString("TransMeta.Log.FromStepALookingAtPreviousStep", stepMeta.getName(), String.valueOf(findNrPrevSteps(stepMeta)) )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
for (int i = 0; i < findNrPrevSteps(stepMeta); i++)
{
StepMeta prevStepMeta = findPrevStep(stepMeta, i);
if (monitor != null)
{
monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingStepTask.Title", prevStepMeta.getName() )); //$NON-NLS-1$ //$NON-NLS-2$
}
RowMetaInterface add = getStepFields(prevStepMeta, stepMeta, monitor);
if (add == null) add = new RowMeta();
log.logDebug(toString(), Messages.getString("TransMeta.Log.FoundFieldsToAdd") + add.toString()); //$NON-NLS-1$
if (i == 0)
{
row.addRowMeta(add);
}
else
{
// See if the add fields are not already in the row
for (int x = 0; x < add.size(); x++)
{
ValueMetaInterface v = add.getValueMeta(x);
ValueMetaInterface s = row.searchValueMeta(v.getName());
if (s == null)
{
row.addValueMeta(v);
}
}
}
}
// Finally, see if we need to add/modify/delete fields with this step "name"
return getThisStepFields(stepMeta, targetStep, row, monitor);
}
/**
* Find the fields that are entering a step with a certain name.
*
* @param stepname The name of the step queried
* @return A row containing the fields (w/ origin) entering the step
*/
public RowMetaInterface getPrevStepFields(String stepname) throws KettleStepException
{
return getPrevStepFields(findStep(stepname));
}
/**
* Find the fields that are entering a certain step.
*
* @param stepMeta The step queried
* @return A row containing the fields (w/ origin) entering the step
*/
public RowMetaInterface getPrevStepFields(StepMeta stepMeta) throws KettleStepException
{
return getPrevStepFields(stepMeta, null);
}
/**
* Find the fields that are entering a certain step.
*
* @param stepMeta The step queried
* @param monitor The progress monitor for progress dialog. (null if not used!)
* @return A row containing the fields (w/ origin) entering the step
*/
public RowMetaInterface getPrevStepFields(StepMeta stepMeta, IProgressMonitor monitor) throws KettleStepException
{
RowMetaInterface row = new RowMeta();
if (stepMeta == null) { return null; }
log.logDebug(toString(), Messages.getString("TransMeta.Log.FromStepALookingAtPreviousStep", stepMeta.getName(), String.valueOf(findNrPrevSteps(stepMeta)) )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
for (int i = 0; i < findNrPrevSteps(stepMeta); i++)
{
StepMeta prevStepMeta = findPrevStep(stepMeta, i);
if (monitor != null)
{
monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingStepTask.Title", prevStepMeta.getName() )); //$NON-NLS-1$ //$NON-NLS-2$
}
RowMetaInterface add = getStepFields(prevStepMeta, stepMeta, monitor);
log.logDebug(toString(), Messages.getString("TransMeta.Log.FoundFieldsToAdd2") + add.toString()); //$NON-NLS-1$
if (i == 0) // we expect all input streams to be of the same layout!
{
row.addRowMeta(add); // recursive!
}
else
{
// See if the add fields are not already in the row
for (int x = 0; x < add.size(); x++)
{
ValueMetaInterface v = add.getValueMeta(x);
ValueMetaInterface s = row.searchValueMeta(v.getName());
if (s == null)
{
row.addValueMeta(v);
}
}
}
}
return row;
}
/**
* Return the fields that are emitted by a step with a certain name
*
* @param stepname The name of the step that's being queried.
* @param row A row containing the input fields or an empty row if no input is required.
* @return A Row containing the output fields.
*/
public RowMetaInterface getThisStepFields(String stepname, RowMetaInterface row) throws KettleStepException
{
return getThisStepFields(findStep(stepname), null, row);
}
/**
* Returns the fields that are emitted by a step
*
* @param stepMeta : The StepMeta object that's being queried
* @param nextStep : if non-null this is the next step that's call back to ask what's being sent
* @param row : A row containing the input fields or an empty row if no input is required.
*
* @return A Row containing the output fields.
*/
public RowMetaInterface getThisStepFields(StepMeta stepMeta, StepMeta nextStep, RowMetaInterface row) throws KettleStepException
{
return getThisStepFields(stepMeta, nextStep, row, null);
}
/**
* Returns the fields that are emitted by a step
*
* @param stepMeta : The StepMeta object that's being queried
* @param nextStep : if non-null this is the next step that's call back to ask what's being sent
* @param row : A row containing the input fields or an empty row if no input is required.
*
* @return A Row containing the output fields.
*/
public RowMetaInterface getThisStepFields(StepMeta stepMeta, StepMeta nextStep, RowMetaInterface row, IProgressMonitor monitor) throws KettleStepException
{
// Then this one.
log.logDebug(toString(), Messages.getString("TransMeta.Log.GettingFieldsFromStep",stepMeta.getName(), stepMeta.getStepID())); //$NON-NLS-1$ //$NON-NLS-2$
String name = stepMeta.getName();
if (monitor != null)
{
monitor.subTask(Messages.getString("TransMeta.Monitor.GettingFieldsFromStepTask.Title", name )); //$NON-NLS-1$ //$NON-NLS-2$
}
StepMetaInterface stepint = stepMeta.getStepMetaInterface();
RowMetaInterface inform[] = null;
StepMeta[] lu = getInfoStep(stepMeta);
if (Const.isEmpty(lu))
{
inform = new RowMetaInterface[] { stepint.getTableFields(), };
}
else
{
inform = new RowMetaInterface[lu.length];
for (int i=0;i<lu.length;i++) inform[i] = getStepFields(lu[i]);
}
// Set the Repository object on the Mapping step
// That way the mapping step can determine the output fields for repository hosted mappings...
// This is the exception to the rule so we don't pass this through the getFields() method.
for (StepMeta step : steps)
{
if (step.getStepMetaInterface() instanceof MappingMeta)
{
((MappingMeta)step.getStepMetaInterface()).setRepository(repository);
}
}
// Go get the fields...
stepint.getFields(row, name, inform, nextStep, this);
return row;
}
/**
* Determine if we should put a replace warning or not for the transformation in a certain repository.
*
* @param rep The repository.
* @return True if we should show a replace warning, false if not.
*/
public boolean showReplaceWarning(Repository rep)
{
if (getID() < 0)
{
try
{
if (rep.getTransformationID(getName(), directory.getID()) > 0) return true;
}
catch (KettleException dbe)
{
log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseError") + dbe.getMessage()); //$NON-NLS-1$
return true;
}
}
return false;
}
public void saveRep(Repository rep) throws KettleException
{
saveRep(rep, null);
}
/**
* Saves the transformation to a repository.
*
* @param rep The repository.
* @throws KettleException if an error occurrs.
*/
public void saveRep(Repository rep, IProgressMonitor monitor) throws KettleException
{
try
{
if (monitor!=null) monitor.subTask(Messages.getString("TransMeta.Monitor.LockingRepository")); //$NON-NLS-1$
rep.lockRepository(); // make sure we're they only one using the repository at the moment
rep.insertLogEntry("save transformation '"+getName()+"'");
// Clear attribute id cache
rep.clearNextIDCounters(); // force repository lookup.
// Do we have a valid directory?
if (directory.getID() < 0) { throw new KettleException(Messages.getString("TransMeta.Exception.PlsSelectAValidDirectoryBeforeSavingTheTransformation")); } //$NON-NLS-1$
int nrWorks = 2 + nrDatabases() + nrNotes() + nrSteps() + nrTransHops();
if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.SavingTransformationTask.Title") + getPathAndName(), nrWorks); //$NON-NLS-1$
log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingOfTransformationStarted")); //$NON-NLS-1$
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException();
// Before we start, make sure we have a valid transformation ID!
// Two possibilities:
// 1) We have a ID: keep it
// 2) We don't have an ID: look it up.
// If we find a transformation with the same name: ask!
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.HandlingOldVersionTransformationTask.Title")); //$NON-NLS-1$
setID(rep.getTransformationID(getName(), directory.getID()));
// If no valid id is available in the database, assign one...
if (getID() <= 0)
{
setID(rep.getNextTransformationID());
}
else
{
// If we have a valid ID, we need to make sure everything is cleared out
// of the database for this id_transformation, before we put it back in...
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.DeletingOldVersionTransformationTask.Title")); //$NON-NLS-1$
log.logDebug(toString(), Messages.getString("TransMeta.Log.DeletingOldVersionTransformation")); //$NON-NLS-1$
rep.delAllFromTrans(getID());
log.logDebug(toString(), Messages.getString("TransMeta.Log.OldVersionOfTransformationRemoved")); //$NON-NLS-1$
}
if (monitor != null) monitor.worked(1);
log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingNotes")); //$NON-NLS-1$
for (int i = 0; i < nrNotes(); i++)
{
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave"));
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingNoteTask.Title") + (i + 1) + "/" + nrNotes()); //$NON-NLS-1$ //$NON-NLS-2$
NotePadMeta ni = getNote(i);
ni.saveRep(rep, getID());
if (ni.getID() > 0) rep.insertTransNote(getID(), ni.getID());
if (monitor != null) monitor.worked(1);
}
log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingDatabaseConnections")); //$NON-NLS-1$
for (int i = 0; i < nrDatabases(); i++)
{
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave"));
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingDatabaseTask.Title") + (i + 1) + "/" + nrDatabases()); //$NON-NLS-1$ //$NON-NLS-2$
DatabaseMeta databaseMeta = getDatabase(i);
// ONLY save the database connection if it has changed and nothing was saved in the repository
if(databaseMeta.hasChanged() || databaseMeta.getID()<=0)
{
databaseMeta.saveRep(rep);
}
if (monitor != null) monitor.worked(1);
}
// Before saving the steps, make sure we have all the step-types.
// It is possible that we received another step through a plugin.
log.logDebug(toString(), Messages.getString("TransMeta.Log.CheckingStepTypes")); //$NON-NLS-1$
rep.updateStepTypes();
log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingSteps")); //$NON-NLS-1$
for (int i = 0; i < nrSteps(); i++)
{
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave"));
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingStepTask.Title") + (i + 1) + "/" + nrSteps()); //$NON-NLS-1$ //$NON-NLS-2$
StepMeta stepMeta = getStep(i);
stepMeta.saveRep(rep, getID());
if (monitor != null) monitor.worked(1);
}
rep.closeStepAttributeInsertPreparedStatement();
log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingHops")); //$NON-NLS-1$
for (int i = 0; i < nrTransHops(); i++)
{
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave"));
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingHopTask.Title") + (i + 1) + "/" + nrTransHops()); //$NON-NLS-1$ //$NON-NLS-2$
TransHopMeta hi = getTransHop(i);
hi.saveRep(rep, getID());
if (monitor != null) monitor.worked(1);
}
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.FinishingTask.Title")); //$NON-NLS-1$
log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingTransformationInfo")); //$NON-NLS-1$
rep.insertTransformation(this); // save the top level information for the transformation
rep.closeTransAttributeInsertPreparedStatement();
// Save the partition schemas
for (int i=0;i<partitionSchemas.size();i++)
{
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave"));
PartitionSchema partitionSchema = partitionSchemas.get(i);
// See if this transformation really is a consumer of this object
// It might be simply loaded as a shared object from the repository
boolean isUsedByTransformation = isUsingPartitionSchema(partitionSchema);
partitionSchema.saveRep(rep, getID(), isUsedByTransformation);
}
// Save the slaves
for (int i=0;i<slaveServers.size();i++)
{
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave"));
SlaveServer slaveServer = slaveServers.get(i);
boolean isUsedByTransformation = isUsingSlaveServer(slaveServer);
slaveServer.saveRep(rep, getID(), isUsedByTransformation);
}
// Save the clustering schemas
for (int i=0;i<clusterSchemas.size();i++)
{
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave"));
ClusterSchema clusterSchema = clusterSchemas.get(i);
boolean isUsedByTransformation = isUsingClusterSchema(clusterSchema);
clusterSchema.saveRep(rep, getID(), isUsedByTransformation);
}
log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingDependencies")); //$NON-NLS-1$
for (int i = 0; i < nrDependencies(); i++)
{
if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave"));
TransDependency td = getDependency(i);
td.saveRep(rep, getID());
}
// Save the step error handling information as well!
for (int i=0;i<nrSteps();i++)
{
StepMeta stepMeta = getStep(i);
StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta();
if (stepErrorMeta!=null)
{
stepErrorMeta.saveRep(rep, getId(), stepMeta.getID());
}
}
rep.closeStepAttributeInsertPreparedStatement();
log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingFinished")); //$NON-NLS-1$
if (monitor!=null) monitor.subTask(Messages.getString("TransMeta.Monitor.UnlockingRepository")); //$NON-NLS-1$
rep.unlockRepository();
// Perform a commit!
rep.commit();
clearChanged();
if (monitor != null) monitor.worked(1);
if (monitor != null) monitor.done();
}
catch (KettleDatabaseException dbe)
{
// Oops, roll back!
rep.rollback();
log.logError(toString(), Messages.getString("TransMeta.Log.ErrorSavingTransformationToRepository") + Const.CR + dbe.getMessage()); //$NON-NLS-1$
throw new KettleException(Messages.getString("TransMeta.Log.ErrorSavingTransformationToRepository"), dbe); //$NON-NLS-1$
}
finally
{
// don't forget to unlock the repository.
// Normally this is done by the commit / rollback statement, but hey there are some freaky database out
// there...
rep.unlockRepository();
}
}
public boolean isUsingPartitionSchema(PartitionSchema partitionSchema)
{
// Loop over all steps and see if the partition schema is used.
for (int i=0;i<nrSteps();i++)
{
StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta();
if (stepPartitioningMeta!=null)
{
PartitionSchema check = stepPartitioningMeta.getPartitionSchema();
if (check!=null && check.equals(partitionSchema))
{
return true;
}
}
}
return false;
}
public boolean isUsingClusterSchema(ClusterSchema clusterSchema)
{
// Loop over all steps and see if the partition schema is used.
for (int i=0;i<nrSteps();i++)
{
ClusterSchema check = getStep(i).getClusterSchema();
if (check!=null && check.equals(clusterSchema))
{
return true;
}
}
return false;
}
public boolean isUsingSlaveServer(SlaveServer slaveServer)
{
// Loop over all steps and see if the slave server is used.
for (int i=0;i<nrSteps();i++)
{
ClusterSchema clusterSchema = getStep(i).getClusterSchema();
if (clusterSchema!=null)
{
for (SlaveServer check : clusterSchema.getSlaveServers())
{
if (check.equals(slaveServer))
{
return true;
}
}
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#readDatabases(org.pentaho.di.repository.Repository, boolean)
*/
public void readDatabases(Repository rep, boolean overWriteShared) throws KettleException
{
try
{
long dbids[] = rep.getDatabaseIDs();
for (int i = 0; i < dbids.length; i++)
{
DatabaseMeta databaseMeta = new DatabaseMeta(rep, dbids[i]);
DatabaseMeta check = findDatabase(databaseMeta.getName()); // Check if there already is one in the transformation
if (check==null || overWriteShared) // We only add, never overwrite database connections.
{
if (databaseMeta.getName() != null)
{
addOrReplaceDatabase(databaseMeta);
if (!overWriteShared) databaseMeta.setChanged(false);
}
}
}
changed_databases = false;
}
catch (KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadDatabaseIDSFromRepository"), dbe); //$NON-NLS-1$
}
catch (KettleException ke)
{
throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadDatabasesFromRepository"), ke); //$NON-NLS-1$
}
}
/**
* Read the partitions in the repository and add them to this transformation if they are not yet present.
* @param rep The repository to load from.
* @param overWriteShared if an object with the same name exists, overwrite
* @throws KettleException
*/
public void readPartitionSchemas(Repository rep, boolean overWriteShared) throws KettleException
{
try
{
long dbids[] = rep.getPartitionSchemaIDs();
for (int i = 0; i < dbids.length; i++)
{
PartitionSchema partitionSchema = new PartitionSchema(rep, dbids[i]);
PartitionSchema check = findPartitionSchema(partitionSchema.getName()); // Check if there already is one in the transformation
if (check==null || overWriteShared)
{
if (!Const.isEmpty(partitionSchema.getName()))
{
addOrReplacePartitionSchema(partitionSchema);
if (!overWriteShared) partitionSchema.setChanged(false);
}
}
}
}
catch (KettleException dbe)
{
throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadPartitionSchemaFromRepository"), dbe); //$NON-NLS-1$
}
}
/**
* Read the slave servers in the repository and add them to this transformation if they are not yet present.
* @param rep The repository to load from.
* @param overWriteShared if an object with the same name exists, overwrite
* @throws KettleException
*/
public void readSlaves(Repository rep, boolean overWriteShared) throws KettleException
{
try
{
long dbids[] = rep.getSlaveIDs();
for (int i = 0; i < dbids.length; i++)
{
SlaveServer slaveServer = new SlaveServer(rep, dbids[i]);
SlaveServer check = findSlaveServer(slaveServer.getName()); // Check if there already is one in the transformation
if (check==null || overWriteShared)
{
if (!Const.isEmpty(slaveServer.getName()))
{
addOrReplaceSlaveServer(slaveServer);
if (!overWriteShared) slaveServer.setChanged(false);
}
}
}
}
catch (KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadSlaveServersFromRepository"), dbe); //$NON-NLS-1$
}
}
/**
* Read the clusters in the repository and add them to this transformation if they are not yet present.
* @param rep The repository to load from.
* @param overWriteShared if an object with the same name exists, overwrite
* @throws KettleException
*/
public void readClusters(Repository rep, boolean overWriteShared) throws KettleException
{
try
{
long dbids[] = rep.getClusterIDs();
for (int i = 0; i < dbids.length; i++)
{
ClusterSchema cluster = new ClusterSchema(rep, dbids[i], slaveServers);
ClusterSchema check = findClusterSchema(cluster.getName()); // Check if there already is one in the transformation
if (check==null || overWriteShared)
{
if (!Const.isEmpty(cluster.getName()))
{
addOrReplaceClusterSchema(cluster);
if (!overWriteShared) cluster.setChanged(false);
}
}
}
}
catch (KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadClustersFromRepository"), dbe); //$NON-NLS-1$
}
}
/**
* Load the transformation name & other details from a repository.
*
* @param rep The repository to load the details from.
*/
public void loadRepTrans(Repository rep) throws KettleException
{
try
{
RowMetaAndData r = rep.getTransformation(getID());
if (r != null)
{
name = r.getString("NAME", null); //$NON-NLS-1$
// Trans description
description = r.getString("DESCRIPTION", null);
extended_description = r.getString("EXTENDED_DESCRIPTION", null);
trans_version = r.getString("TRANS_VERSION", null);
trans_status=(int) r.getInteger("TRANS_STATUS", -1L);
readStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_READ", -1L)); //$NON-NLS-1$
writeStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_WRITE", -1L)); //$NON-NLS-1$
inputStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_INPUT", -1L)); //$NON-NLS-1$
outputStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_OUTPUT", -1L)); //$NON-NLS-1$
updateStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_UPDATE", -1L)); //$NON-NLS-1$
long id_rejected = rep.getTransAttributeInteger(getID(), 0, "ID_STEP_REJECTED"); // $NON-NLS-1$
if (id_rejected>0)
{
rejectedStep = StepMeta.findStep(steps, id_rejected); //$NON-NLS-1$
}
logConnection = DatabaseMeta.findDatabase(databases, r.getInteger("ID_DATABASE_LOG", -1L)); //$NON-NLS-1$
logTable = r.getString("TABLE_NAME_LOG", null); //$NON-NLS-1$
useBatchId = r.getBoolean("USE_BATCHID", false); //$NON-NLS-1$
logfieldUsed = r.getBoolean("USE_LOGFIELD", false); //$NON-NLS-1$
maxDateConnection = DatabaseMeta.findDatabase(databases, r.getInteger("ID_DATABASE_MAXDATE", -1L)); //$NON-NLS-1$
maxDateTable = r.getString("TABLE_NAME_MAXDATE", null); //$NON-NLS-1$
maxDateField = r.getString("FIELD_NAME_MAXDATE", null); //$NON-NLS-1$
maxDateOffset = r.getNumber("OFFSET_MAXDATE", 0.0); //$NON-NLS-1$
maxDateDifference = r.getNumber("DIFF_MAXDATE", 0.0); //$NON-NLS-1$
createdUser = r.getString("CREATED_USER", null); //$NON-NLS-1$
createdDate = r.getDate("CREATED_DATE", null); //$NON-NLS-1$
modifiedUser = r.getString("MODIFIED_USER", null); //$NON-NLS-1$
modifiedDate = r.getDate("MODIFIED_DATE", null); //$NON-NLS-1$
// Optional:
sizeRowset = Const.ROWS_IN_ROWSET;
Long val_size_rowset = r.getInteger("SIZE_ROWSET"); //$NON-NLS-1$
if (val_size_rowset != null )
{
sizeRowset = val_size_rowset.intValue();
}
long id_directory = r.getInteger("ID_DIRECTORY", -1L); //$NON-NLS-1$
if (id_directory >= 0)
{
log.logDetailed(toString(), "ID_DIRECTORY=" + id_directory); //$NON-NLS-1$
// Set right directory...
directory = directoryTree.findDirectory(id_directory);
}
usingUniqueConnections = rep.getTransAttributeBoolean(getID(), 0, "UNIQUE_CONNECTIONS");
feedbackShown = !"N".equalsIgnoreCase( rep.getTransAttributeString(getID(), 0, "FEEDBACK_SHOWN") );
feedbackSize = (int) rep.getTransAttributeInteger(getID(), 0, "FEEDBACK_SIZE");
usingThreadPriorityManagment = !"N".equalsIgnoreCase( rep.getTransAttributeString(getID(), 0, "USING_THREAD_PRIORITIES") );
}
}
catch (KettleDatabaseException dbe)
{
throw new KettleException(Messages.getString("TransMeta.Exception.UnableToLoadTransformationInfoFromRepository"), dbe); //$NON-NLS-1$
}
finally
{
initializeVariablesFrom(null);
setInternalKettleVariables();
}
}
public boolean isRepReference() {
return isRepReference(getFilename(), this.getName());
}
public boolean isFileReference() {
return !isRepReference(getFilename(), this.getName());
}
public static boolean isRepReference(String exactFilename, String exactTransname) {
return Const.isEmpty(exactFilename) && !Const.isEmpty(exactTransname);
}
public static boolean isFileReference(String exactFilename, String exactTransname) {
return !isRepReference(exactFilename, exactTransname);
}
/** Read a transformation with a certain name from a repository
*
* @param rep The repository to read from.
* @param transname The name of the transformation.
* @param repdir the path to the repository directory
*/
public TransMeta(Repository rep, String transname, RepositoryDirectory repdir) throws KettleException
{
this(rep, transname, repdir, null, true);
}
/**
* Read a transformation with a certain name from a repository
*
* @param rep The repository to read from.
* @param transname The name of the transformation.
* @param repdir the path to the repository directory
* @param setInternalVariables true if you want to set the internal variables based on this transformation information
*/
public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, boolean setInternalVariables) throws KettleException
{
this(rep, transname, repdir, null, setInternalVariables);
}
/** Read a transformation with a certain name from a repository
*
* @param rep The repository to read from.
* @param transname The name of the transformation.
* @param repdir the path to the repository directory
* @param monitor The progress monitor to display the progress of the file-open operation in a dialog
*/
public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, IProgressMonitor monitor) throws KettleException
{
this(rep, transname, repdir, monitor, true);
}
/** Read a transformation with a certain name from a repository
*
* @param rep The repository to read from.
* @param transname The name of the transformation.
* @param repdir the path to the repository directory
* @param monitor The progress monitor to display the progress of the file-open operation in a dialog
* @param setInternalVariables true if you want to set the internal variables based on this transformation information
*/
public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, IProgressMonitor monitor, boolean setInternalVariables) throws KettleException
{
this();
try
{
String pathAndName = repdir.isRoot() ? repdir + transname : repdir + RepositoryDirectory.DIRECTORY_SEPARATOR + transname;
setName(transname);
directory = repdir;
directoryTree = directory.findRoot();
// Get the transformation id
log.logDetailed(toString(), Messages.getString("TransMeta.Log.LookingForTransformation", transname ,directory.getPath() )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTransformationInfoTask.Title")); //$NON-NLS-1$
setID(rep.getTransformationID(transname, directory.getID()));
if (monitor != null) monitor.worked(1);
// If no valid id is available in the database, then give error...
if (getID() > 0)
{
long noteids[] = rep.getTransNoteIDs(getID());
long stepids[] = rep.getStepIDs(getID());
long hopids[] = rep.getTransHopIDs(getID());
int nrWork = 3 + noteids.length + stepids.length + hopids.length;
if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.LoadingTransformationTask.Title") + pathAndName, nrWork); //$NON-NLS-1$
log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadingTransformation", getName() )); //$NON-NLS-1$ //$NON-NLS-2$
// Load the common database connections
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTheAvailableSharedObjectsTask.Title")); //$NON-NLS-1$
try
{
readSharedObjects(rep);
}
catch(Exception e)
{
LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.ErrorReadingSharedObjects.Message", e.toString()));
LogWriter.getInstance().logError(toString(), Const.getStackTracker(e));
}
if (monitor != null) monitor.worked(1);
// Load the notes...
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingNoteTask.Title")); //$NON-NLS-1$
for (int i = 0; i < noteids.length; i++)
{
NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]);
if (indexOfNote(ni) < 0) addNote(ni);
if (monitor != null) monitor.worked(1);
}
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingStepsTask.Title")); //$NON-NLS-1$
rep.fillStepAttributesBuffer(getID()); // read all the attributes on one go!
for (int i = 0; i < stepids.length; i++)
{
log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadingStepWithID") + stepids[i]); //$NON-NLS-1$
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingStepTask.Title") + (i + 1) + "/" + (stepids.length)); //$NON-NLS-1$ //$NON-NLS-2$
StepMeta stepMeta = new StepMeta(rep, stepids[i], databases, counters, partitionSchemas);
// In this case, we just add or replace the shared steps.
// The repository is considered "more central"
addOrReplaceStep(stepMeta);
if (monitor != null) monitor.worked(1);
}
if (monitor != null) monitor.worked(1);
rep.setStepAttributesBuffer(null); // clear the buffer (should be empty anyway)
// Have all StreamValueLookups, etc. reference the correct source steps...
for (int i = 0; i < nrSteps(); i++)
{
StepMetaInterface sii = getStep(i).getStepMetaInterface();
sii.searchInfoAndTargetSteps(steps);
}
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.LoadingTransformationDetailsTask.Title")); //$NON-NLS-1$
loadRepTrans(rep);
if (monitor != null) monitor.worked(1);
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingHopTask.Title")); //$NON-NLS-1$
for (int i = 0; i < hopids.length; i++)
{
TransHopMeta hi = new TransHopMeta(rep, hopids[i], steps);
addTransHop(hi);
if (monitor != null) monitor.worked(1);
}
// Have all step partitioning meta-data reference the correct schemas that we just loaded
for (int i = 0; i < nrSteps(); i++)
{
StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta();
if (stepPartitioningMeta!=null)
{
stepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas);
}
}
// Have all step clustering schema meta-data reference the correct cluster schemas that we just loaded
for (int i = 0; i < nrSteps(); i++)
{
getStep(i).setClusterSchemaAfterLoading(clusterSchemas);
}
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTheDependenciesTask.Title")); //$NON-NLS-1$
long depids[] = rep.getTransDependencyIDs(getID());
for (int i = 0; i < depids.length; i++)
{
TransDependency td = new TransDependency(rep, depids[i], databases);
addDependency(td);
}
if (monitor != null) monitor.worked(1);
// Also load the step error handling metadata
for (int i=0;i<nrSteps();i++)
{
StepMeta stepMeta = getStep(i);
String sourceStep = rep.getStepAttributeString(stepMeta.getID(), "step_error_handling_source_step");
if (sourceStep!=null)
{
StepErrorMeta stepErrorMeta = new StepErrorMeta(this, rep, stepMeta, steps);
stepErrorMeta.getSourceStep().setStepErrorMeta(stepErrorMeta); // a bit of a trick, I know.
}
}
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SortingStepsTask.Title")); //$NON-NLS-1$
sortSteps();
if (monitor != null) monitor.worked(1);
if (monitor != null) monitor.done();
}
else
{
throw new KettleException(Messages.getString("TransMeta.Exception.TransformationDoesNotExist") + name); //$NON-NLS-1$
}
log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadedTransformation2", transname , String.valueOf(directory == null))); //$NON-NLS-1$ //$NON-NLS-2$
log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadedTransformation", transname , directory.getPath() )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
catch (KettleDatabaseException e)
{
log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseErrorOccuredReadingTransformation") + Const.CR + e); //$NON-NLS-1$
throw new KettleException(Messages.getString("TransMeta.Exception.DatabaseErrorOccuredReadingTransformation"), e); //$NON-NLS-1$
}
catch (Exception e)
{
log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseErrorOccuredReadingTransformation") + Const.CR + e); //$NON-NLS-1$
throw new KettleException(Messages.getString("TransMeta.Exception.DatabaseErrorOccuredReadingTransformation2"), e); //$NON-NLS-1$
}
finally
{
initializeVariablesFrom(null);
if (setInternalVariables) setInternalKettleVariables();
}
}
/**
* Find the location of hop
*
* @param hi The hop queried
* @return The location of the hop, -1 if nothing was found.
*/
public int indexOfTransHop(TransHopMeta hi)
{
return hops.indexOf(hi);
}
/**
* Find the location of step
*
* @param stepMeta The step queried
* @return The location of the step, -1 if nothing was found.
*/
public int indexOfStep(StepMeta stepMeta)
{
return steps.indexOf(stepMeta);
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#indexOfDatabase(org.pentaho.di.core.database.DatabaseMeta)
*/
public int indexOfDatabase(DatabaseMeta ci)
{
return databases.indexOf(ci);
}
/**
* Find the location of a note
*
* @param ni The note queried
* @return The location of the note, -1 if nothing was found.
*/
public int indexOfNote(NotePadMeta ni)
{
return notes.indexOf(ni);
}
public String getFileType() {
return LastUsedFile.FILE_TYPE_TRANSFORMATION;
}
public String[] getFilterNames() {
return Const.getTransformationFilterNames();
}
public String[] getFilterExtensions() {
return Const.STRING_TRANS_FILTER_EXT;
}
public String getDefaultExtension() {
return Const.STRING_TRANS_DEFAULT_EXT;
}
public String getXML()
{
Props props = null;
if (Props.isInitialized()) props=Props.getInstance();
StringBuffer retval = new StringBuffer(800);
retval.append(XMLHandler.openTag(XML_TAG)).append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.openTag(XML_TAG_INFO)).append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("name", name)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("description", description)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("extended_description", extended_description));
retval.append(" ").append(XMLHandler.addTagValue("trans_version", trans_version));
// Let's add the last known file location if we have any...
if (!Const.isEmpty(filename)) {
retval.append(" ").append(XMLHandler.addTagValue("filename", filename)); //$NON-NLS-1$ //$NON-NLS-2$
}
if ( trans_status >= 0 )
{
retval.append(" ").append(XMLHandler.addTagValue("trans_status", trans_status));
}
retval.append(" ").append(XMLHandler.addTagValue("directory", directory != null ? directory.getPath() : RepositoryDirectory.DIRECTORY_SEPARATOR)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" <log>").append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("read", readStep == null ? "" : readStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("write", writeStep == null ? "" : writeStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("input", inputStep == null ? "" : inputStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("output", outputStep == null ? "" : outputStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("update", updateStep == null ? "" : updateStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("rejected", rejectedStep == null ? "" : rejectedStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("connection", logConnection == null ? "" : logConnection.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("table", logTable)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("use_batchid", useBatchId)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("use_logfield", logfieldUsed)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" </log>").append(Const.CR); //$NON-NLS-1$
retval.append(" <maxdate>").append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("connection", maxDateConnection == null ? "" : maxDateConnection.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" ").append(XMLHandler.addTagValue("table", maxDateTable)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("field", maxDateField)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("offset", maxDateOffset)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("maxdiff", maxDateDifference)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" </maxdate>").append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("size_rowset", sizeRowset)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("sleep_time_empty", sleepTimeEmpty)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("sleep_time_full", sleepTimeFull)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("unique_connections", usingUniqueConnections)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("feedback_shown", feedbackShown)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("feedback_size", feedbackSize)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("using_thread_priorities", usingThreadPriorityManagment)); // $NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("shared_objects_file", sharedObjectsFile)); // $NON-NLS-1$
retval.append(" ").append(XMLHandler.openTag(XML_TAG_DEPENDENCIES)).append(Const.CR); //$NON-NLS-1$
for (int i = 0; i < nrDependencies(); i++)
{
TransDependency td = getDependency(i);
retval.append(td.getXML());
}
retval.append(" ").append(XMLHandler.closeTag(XML_TAG_DEPENDENCIES)).append(Const.CR); //$NON-NLS-1$
// The partitioning schemas...
retval.append(" ").append(XMLHandler.openTag(XML_TAG_PARTITIONSCHEMAS)).append(Const.CR); //$NON-NLS-1$
for (int i = 0; i < partitionSchemas.size(); i++)
{
PartitionSchema partitionSchema = partitionSchemas.get(i);
retval.append(partitionSchema.getXML());
}
retval.append(" ").append(XMLHandler.closeTag(XML_TAG_PARTITIONSCHEMAS)).append(Const.CR); //$NON-NLS-1$
// The slave servers...
retval.append(" ").append(XMLHandler.openTag(XML_TAG_SLAVESERVERS)).append(Const.CR); //$NON-NLS-1$
for (int i = 0; i < slaveServers.size(); i++)
{
SlaveServer slaveServer = slaveServers.get(i);
retval.append(" ").append(slaveServer.getXML()).append(Const.CR);
}
retval.append(" ").append(XMLHandler.closeTag(XML_TAG_SLAVESERVERS)).append(Const.CR); //$NON-NLS-1$
// The cluster schemas...
retval.append(" ").append(XMLHandler.openTag(XML_TAG_CLUSTERSCHEMAS)).append(Const.CR); //$NON-NLS-1$
for (int i = 0; i < clusterSchemas.size(); i++)
{
ClusterSchema clusterSchema = clusterSchemas.get(i);
retval.append(clusterSchema.getXML());
}
retval.append(" ").append(XMLHandler.closeTag(XML_TAG_CLUSTERSCHEMAS)).append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("modified_user", modifiedUser));
retval.append(" ").append(XMLHandler.addTagValue("modified_date", modifiedDate));
retval.append(" ").append(XMLHandler.closeTag(XML_TAG_INFO)).append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.openTag(XML_TAG_NOTEPADS)).append(Const.CR); //$NON-NLS-1$
if (notes != null) for (int i = 0; i < nrNotes(); i++)
{
NotePadMeta ni = getNote(i);
retval.append(ni.getXML());
}
retval.append(" ").append(XMLHandler.closeTag(XML_TAG_NOTEPADS)).append(Const.CR); //$NON-NLS-1$
// The database connections...
for (int i = 0; i < nrDatabases(); i++)
{
DatabaseMeta dbMeta = getDatabase(i);
if (props!=null && props.areOnlyUsedConnectionsSavedToXML())
{
if (isDatabaseConnectionUsed(dbMeta)) retval.append(dbMeta.getXML());
}
else
{
retval.append(dbMeta.getXML());
}
}
retval.append(" ").append(XMLHandler.openTag(XML_TAG_ORDER)).append(Const.CR); //$NON-NLS-1$
for (int i = 0; i < nrTransHops(); i++)
{
TransHopMeta transHopMeta = getTransHop(i);
retval.append(transHopMeta.getXML());
}
retval.append(" ").append(XMLHandler.closeTag(XML_TAG_ORDER)).append(Const.CR); //$NON-NLS-1$
/* The steps... */
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
retval.append(stepMeta.getXML());
}
/* The error handling metadata on the steps */
retval.append(" ").append(XMLHandler.openTag(XML_TAG_STEP_ERROR_HANDLING)).append(Const.CR);
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (stepMeta.getStepErrorMeta()!=null)
{
retval.append(stepMeta.getStepErrorMeta().getXML());
}
}
retval.append(" ").append(XMLHandler.closeTag(XML_TAG_STEP_ERROR_HANDLING)).append(Const.CR);
// The slave-step-copy/partition distribution. Only used for slave transformations in a clustering environment.
retval.append(" ").append(slaveStepCopyPartitionDistribution.getXML());
// Is this a slave transformation or not?
retval.append(" ").append(XMLHandler.addTagValue("slave_transformation", slaveTransformation));
retval.append("</").append(XML_TAG+">").append(Const.CR); //$NON-NLS-1$
return retval.toString();
}
/**
* Parse a file containing the XML that describes the transformation.
* No default connections are loaded since no repository is available at this time.
* Since the filename is set, internal variables are being set that relate to this.
*
* @param fname The filename
*/
public TransMeta(String fname) throws KettleXMLException
{
this(fname, true);
}
/**
* Parse a file containing the XML that describes the transformation.
* No default connections are loaded since no repository is available at this time.
*
* @param fname The filename
* @param setInternalVariables true if you want to set the internal variables based on this transformation information
*/
public TransMeta(String fname, boolean setInternalVariables) throws KettleXMLException
{
this(fname, null, setInternalVariables);
}
/**
* Parse a file containing the XML that describes the transformation.
*
* @param fname The filename
* @param rep The repository to load the default set of connections from, null if no repository is avaailable
*/
public TransMeta(String fname, Repository rep) throws KettleXMLException
{
this(fname, rep, true);
}
/**
* Parse a file containing the XML that describes the transformation.
*
* @param fname The filename
* @param rep The repository to load the default set of connections from, null if no repository is avaailable
* @param setInternalVariables true if you want to set the internal variables based on this transformation information
*/
public TransMeta(String fname, Repository rep, boolean setInternalVariables ) throws KettleXMLException
{
// OK, try to load using the VFS stuff...
Document doc=null;
try
{
doc = XMLHandler.loadXMLFile(KettleVFS.getFileObject(fname));
}
catch (IOException e)
{
throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", fname)+" : "+e.toString(), e);
}
if (doc != null)
{
// Clear the transformation
clearUndo();
clear();
// Root node:
Node transnode = XMLHandler.getSubNode(doc, XML_TAG); //$NON-NLS-1$
// Load from this node...
loadXML(transnode, rep, setInternalVariables);
setFilename(fname);
}
else
{
throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", fname)); //$NON-NLS-1$
}
}
/*
* Load the transformation from an XML node
*
* @param transnode The XML node to parse
* @throws KettleXMLException
*
public TransMeta(Node transnode) throws KettleXMLException
{
loadXML(transnode);
}
*/
/*
* Parse a file containing the XML that describes the transformation.
* (no repository is available to load default list of database connections from)
*
* @param transnode The XML node to load from
* @throws KettleXMLException
*
private void loadXML(Node transnode) throws KettleXMLException
{
loadXML(transnode, null, false);
}
*/
/**
* Parse a file containing the XML that describes the transformation.
* Specify a repository to load default list of database connections from and to reference in mappings etc.
*
* @param transnode The XML node to load from
* @param rep the repository to reference.
* @throws KettleXMLException
*/
public TransMeta(Node transnode, Repository rep) throws KettleXMLException
{
loadXML(transnode, rep, false);
}
/**
* Parse a file containing the XML that describes the transformation.
*
* @param transnode The XML node to load from
* @param rep The repository to load the default list of database connections from (null if no repository is available)
* @param setInternalVariables true if you want to set the internal variables based on this transformation information
* @throws KettleXMLException
*/
public void loadXML(Node transnode, Repository rep, boolean setInternalVariables ) throws KettleXMLException
{
Props props = null;
if (Props.isInitialized())
{
props=Props.getInstance();
}
try
{
// Clear the transformation
clearUndo();
clear();
// Read all the database connections from the repository to make sure that we don't overwrite any there by loading from XML.
try
{
sharedObjectsFile = XMLHandler.getTagValue(transnode, "info", "shared_objects_file"); //$NON-NLS-1$ //$NON-NLS-2$
readSharedObjects(rep);
}
catch(Exception e)
{
LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.ErrorReadingSharedObjects.Message", e.toString()));
LogWriter.getInstance().logError(toString(), Const.getStackTracker(e));
}
// Handle connections
int n = XMLHandler.countNodes(transnode, DatabaseMeta.XML_TAG); //$NON-NLS-1$
log.logDebug(toString(), Messages.getString("TransMeta.Log.WeHaveConnections", String.valueOf(n) )); //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i < n; i++)
{
log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtConnection") + i); //$NON-NLS-1$
Node nodecon = XMLHandler.getSubNodeByNr(transnode, DatabaseMeta.XML_TAG, i); //$NON-NLS-1$
DatabaseMeta dbcon = new DatabaseMeta(nodecon);
DatabaseMeta exist = findDatabase(dbcon.getName());
if (exist == null)
{
addDatabase(dbcon);
}
else
{
if (!exist.isShared()) // otherwise, we just keep the shared connection.
{
boolean askOverwrite = Props.isInitialized() ? props.askAboutReplacingDatabaseConnections() : false;
boolean overwrite = Props.isInitialized() ? props.replaceExistingDatabaseConnections() : true;
if (askOverwrite)
{
if( SpoonFactory.getInstance() != null ) {
Object res[] = SpoonFactory.getInstance().messageDialogWithToggle("Warning",
null,
"Connection ["+dbcon.getName()+"] already exists, do you want to overwrite this database connection?",
Const.WARNING,
new String[] { Messages.getString("System.Button.Yes"), //$NON-NLS-1$
Messages.getString("System.Button.No") },//$NON-NLS-1$
1,
"Please, don't show this warning anymore.",
!props.askAboutReplacingDatabaseConnections() );
int idx = ((Integer)res[0]).intValue();
boolean toggleState = ((Boolean)res[1]).booleanValue();
props.setAskAboutReplacingDatabaseConnections(!toggleState);
overwrite = ((idx&0xFF)==0); // Yes means: overwrite
}
}
if (overwrite)
{
int idx = indexOfDatabase(exist);
removeDatabase(idx);
addDatabase(idx, dbcon);
}
}
}
}
// Read the notes...
Node notepadsnode = XMLHandler.getSubNode(transnode, XML_TAG_NOTEPADS); //$NON-NLS-1$
int nrnotes = XMLHandler.countNodes(notepadsnode, NotePadMeta.XML_TAG); //$NON-NLS-1$
for (int i = 0; i < nrnotes; i++)
{
Node notepadnode = XMLHandler.getSubNodeByNr(notepadsnode, NotePadMeta.XML_TAG, i); //$NON-NLS-1$
NotePadMeta ni = new NotePadMeta(notepadnode);
notes.add(ni);
}
// Handle Steps
int s = XMLHandler.countNodes(transnode, StepMeta.XML_TAG); //$NON-NLS-1$
log.logDebug(toString(), Messages.getString("TransMeta.Log.ReadingSteps") + s + " steps..."); //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i < s; i++)
{
Node stepnode = XMLHandler.getSubNodeByNr(transnode, StepMeta.XML_TAG, i); //$NON-NLS-1$
log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtStep") + i); //$NON-NLS-1$
StepMeta stepMeta = new StepMeta(stepnode, databases, counters);
// Check if the step exists and if it's a shared step.
// If so, then we will keep the shared version, not this one.
// The stored XML is only for backup purposes.
StepMeta check = findStep(stepMeta.getName());
if (check!=null)
{
if (!check.isShared()) // Don't overwrite shared objects
{
addOrReplaceStep(stepMeta);
}
else
{
check.setDraw(stepMeta.isDrawn()); // Just keep the drawn flag and location
check.setLocation(stepMeta.getLocation());
}
}
else
{
addStep(stepMeta); // simply add it.
}
}
// Read the error handling code of the steps...
Node errorHandlingNode = XMLHandler.getSubNode(transnode, XML_TAG_STEP_ERROR_HANDLING);
int nrErrorHandlers = XMLHandler.countNodes(errorHandlingNode, StepErrorMeta.XML_TAG);
for (int i=0;i<nrErrorHandlers;i++)
{
Node stepErrorMetaNode = XMLHandler.getSubNodeByNr(errorHandlingNode, StepErrorMeta.XML_TAG, i);
StepErrorMeta stepErrorMeta = new StepErrorMeta(this, stepErrorMetaNode, steps);
stepErrorMeta.getSourceStep().setStepErrorMeta(stepErrorMeta); // a bit of a trick, I know.
}
// Have all StreamValueLookups, etc. reference the correct source steps...
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
StepMetaInterface sii = stepMeta.getStepMetaInterface();
if (sii != null) sii.searchInfoAndTargetSteps(steps);
}
// Handle Hops
Node ordernode = XMLHandler.getSubNode(transnode, XML_TAG_ORDER); //$NON-NLS-1$
n = XMLHandler.countNodes(ordernode, TransHopMeta.XML_TAG); //$NON-NLS-1$
log.logDebug(toString(), Messages.getString("TransMeta.Log.WeHaveHops") + n + " hops..."); //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i < n; i++)
{
log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtHop") + i); //$NON-NLS-1$
Node hopnode = XMLHandler.getSubNodeByNr(ordernode, TransHopMeta.XML_TAG, i); //$NON-NLS-1$
TransHopMeta hopinf = new TransHopMeta(hopnode, steps);
addTransHop(hopinf);
}
// get transformation info:
Node infonode = XMLHandler.getSubNode(transnode, XML_TAG_INFO); //$NON-NLS-1$
// Name
name = XMLHandler.getTagValue(infonode, "name"); //$NON-NLS-1$
// description
description = XMLHandler.getTagValue(infonode, "description");
// extended description
extended_description = XMLHandler.getTagValue(infonode, "extended_description");
// trans version
trans_version = XMLHandler.getTagValue(infonode, "trans_version");
// trans status
trans_status = Const.toInt(XMLHandler.getTagValue(infonode, "trans_status"),-1);
// Also load and set the filename
filename = XMLHandler.getTagValue(infonode, "filename"); //$NON-NLS-1$
/*
* Directory String directoryPath = XMLHandler.getTagValue(infonode, "directory");
*/
// Logging method...
readStep = findStep(XMLHandler.getTagValue(infonode, "log", "read")); //$NON-NLS-1$ //$NON-NLS-2$
writeStep = findStep(XMLHandler.getTagValue(infonode, "log", "write")); //$NON-NLS-1$ //$NON-NLS-2$
inputStep = findStep(XMLHandler.getTagValue(infonode, "log", "input")); //$NON-NLS-1$ //$NON-NLS-2$
outputStep = findStep(XMLHandler.getTagValue(infonode, "log", "output")); //$NON-NLS-1$ //$NON-NLS-2$
updateStep = findStep(XMLHandler.getTagValue(infonode, "log", "update")); //$NON-NLS-1$ //$NON-NLS-2$
rejectedStep = findStep(XMLHandler.getTagValue(infonode, "log", "rejected")); //$NON-NLS-1$ //$NON-NLS-2$
String logcon = XMLHandler.getTagValue(infonode, "log", "connection"); //$NON-NLS-1$ //$NON-NLS-2$
logConnection = findDatabase(logcon);
logTable = XMLHandler.getTagValue(infonode, "log", "table"); //$NON-NLS-1$ //$NON-NLS-2$
useBatchId = "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "log", "use_batchid")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
logfieldUsed= "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "log", "USE_LOGFIELD")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// Maxdate range options...
String maxdatcon = XMLHandler.getTagValue(infonode, "maxdate", "connection"); //$NON-NLS-1$ //$NON-NLS-2$
maxDateConnection = findDatabase(maxdatcon);
maxDateTable = XMLHandler.getTagValue(infonode, "maxdate", "table"); //$NON-NLS-1$ //$NON-NLS-2$
maxDateField = XMLHandler.getTagValue(infonode, "maxdate", "field"); //$NON-NLS-1$ //$NON-NLS-2$
String offset = XMLHandler.getTagValue(infonode, "maxdate", "offset"); //$NON-NLS-1$ //$NON-NLS-2$
maxDateOffset = Const.toDouble(offset, 0.0);
String mdiff = XMLHandler.getTagValue(infonode, "maxdate", "maxdiff"); //$NON-NLS-1$ //$NON-NLS-2$
maxDateDifference = Const.toDouble(mdiff, 0.0);
// Check the dependencies as far as dates are concerned...
// We calculate BEFORE we run the MAX of these dates
// If the date is larger then enddate, startdate is set to MIN_DATE
Node depsNode = XMLHandler.getSubNode(infonode, XML_TAG_DEPENDENCIES); //$NON-NLS-1$
int nrDeps = XMLHandler.countNodes(depsNode, TransDependency.XML_TAG); //$NON-NLS-1$
for (int i = 0; i < nrDeps; i++)
{
Node depNode = XMLHandler.getSubNodeByNr(depsNode, TransDependency.XML_TAG, i); //$NON-NLS-1$
TransDependency transDependency = new TransDependency(depNode, databases);
if (transDependency.getDatabase() != null && transDependency.getFieldname() != null)
{
addDependency(transDependency);
}
}
// Read the partitioning schemas
Node partSchemasNode = XMLHandler.getSubNode(infonode, XML_TAG_PARTITIONSCHEMAS); //$NON-NLS-1$
int nrPartSchemas = XMLHandler.countNodes(partSchemasNode, PartitionSchema.XML_TAG); //$NON-NLS-1$
for (int i = 0 ; i < nrPartSchemas ; i++)
{
Node partSchemaNode = XMLHandler.getSubNodeByNr(partSchemasNode, PartitionSchema.XML_TAG, i);
PartitionSchema partitionSchema = new PartitionSchema(partSchemaNode);
// Check if the step exists and if it's a shared step.
// If so, then we will keep the shared version, not this one.
// The stored XML is only for backup purposes.
PartitionSchema check = findPartitionSchema(partitionSchema.getName());
if (check!=null)
{
if (!check.isShared()) // we don't overwrite shared objects.
{
addOrReplacePartitionSchema(partitionSchema);
}
}
else
{
partitionSchemas.add(partitionSchema);
}
}
// Have all step partitioning meta-data reference the correct schemas that we just loaded
for (int i = 0; i < nrSteps(); i++)
{
StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta();
if (stepPartitioningMeta!=null)
{
stepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas);
}
StepPartitioningMeta targetStepPartitioningMeta = getStep(i).getTargetStepPartitioningMeta();
if (targetStepPartitioningMeta!=null)
{
targetStepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas);
}
}
// Read the slave servers...
Node slaveServersNode = XMLHandler.getSubNode(infonode, XML_TAG_SLAVESERVERS); //$NON-NLS-1$
int nrSlaveServers = XMLHandler.countNodes(slaveServersNode, SlaveServer.XML_TAG); //$NON-NLS-1$
for (int i = 0 ; i < nrSlaveServers ; i++)
{
Node slaveServerNode = XMLHandler.getSubNodeByNr(slaveServersNode, SlaveServer.XML_TAG, i);
SlaveServer slaveServer = new SlaveServer(slaveServerNode);
// Check if the object exists and if it's a shared object.
// If so, then we will keep the shared version, not this one.
// The stored XML is only for backup purposes.
SlaveServer check = findSlaveServer(slaveServer.getName());
if (check!=null)
{
if (!check.isShared()) // we don't overwrite shared objects.
{
addOrReplaceSlaveServer(slaveServer);
}
}
else
{
slaveServers.add(slaveServer);
}
}
// Read the cluster schemas
Node clusterSchemasNode = XMLHandler.getSubNode(infonode, XML_TAG_CLUSTERSCHEMAS); //$NON-NLS-1$
int nrClusterSchemas = XMLHandler.countNodes(clusterSchemasNode, ClusterSchema.XML_TAG); //$NON-NLS-1$
for (int i = 0 ; i < nrClusterSchemas ; i++)
{
Node clusterSchemaNode = XMLHandler.getSubNodeByNr(clusterSchemasNode, ClusterSchema.XML_TAG, i);
ClusterSchema clusterSchema = new ClusterSchema(clusterSchemaNode, slaveServers);
// Check if the object exists and if it's a shared object.
// If so, then we will keep the shared version, not this one.
// The stored XML is only for backup purposes.
ClusterSchema check = findClusterSchema(clusterSchema.getName());
if (check!=null)
{
if (!check.isShared()) // we don't overwrite shared objects.
{
addOrReplaceClusterSchema(clusterSchema);
}
}
else
{
clusterSchemas.add(clusterSchema);
}
}
// Have all step clustering schema meta-data reference the correct cluster schemas that we just loaded
for (int i = 0; i < nrSteps(); i++)
{
getStep(i).setClusterSchemaAfterLoading(clusterSchemas);
}
String srowset = XMLHandler.getTagValue(infonode, "size_rowset"); //$NON-NLS-1$
sizeRowset = Const.toInt(srowset, Const.ROWS_IN_ROWSET);
sleepTimeEmpty = Const.toInt(XMLHandler.getTagValue(infonode, "sleep_time_empty"), Const.TIMEOUT_GET_MILLIS); //$NON-NLS-1$
sleepTimeFull = Const.toInt(XMLHandler.getTagValue(infonode, "sleep_time_full"), Const.TIMEOUT_PUT_MILLIS); //$NON-NLS-1$
usingUniqueConnections = "Y".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "unique_connections") ); //$NON-NLS-1$
feedbackShown = !"N".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "feedback_shown") ); //$NON-NLS-1$
feedbackSize = Const.toInt(XMLHandler.getTagValue(infonode, "feedback_size"), Const.ROWS_UPDATE); //$NON-NLS-1$
usingThreadPriorityManagment = !"N".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "using_thread_priorities") ); //$NON-NLS-1$
// Created user/date
createdUser = XMLHandler.getTagValue(infonode, "created_user");
String createDate = XMLHandler.getTagValue(infonode, "created_date");
if (createDate!=null)
{
createdDate = XMLHandler.stringToDate(createDate);
}
// Changed user/date
modifiedUser = XMLHandler.getTagValue(infonode, "modified_user");
String modDate = XMLHandler.getTagValue(infonode, "modified_date");
if (modDate!=null)
{
modifiedDate = XMLHandler.stringToDate(modDate);
}
Node partitionDistNode = XMLHandler.getSubNode(transnode, SlaveStepCopyPartitionDistribution.XML_TAG);
if (partitionDistNode!=null) {
slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution(partitionDistNode);
}
else {
slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution(); // leave empty
}
// Is this a slave transformation?
slaveTransformation = "Y".equalsIgnoreCase(XMLHandler.getTagValue(transnode, "slave_transformation"));
log.logDebug(toString(), Messages.getString("TransMeta.Log.NumberOfStepsReaded") + nrSteps()); //$NON-NLS-1$
log.logDebug(toString(), Messages.getString("TransMeta.Log.NumberOfHopsReaded") + nrTransHops()); //$NON-NLS-1$
sortSteps();
}
catch (KettleXMLException xe)
{
throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorReadingTransformation"), xe); //$NON-NLS-1$
} catch (KettleException e) {
throw new KettleXMLException(e);
}
finally
{
initializeVariablesFrom(null);
if (setInternalVariables) setInternalKettleVariables();
}
}
public void readSharedObjects(Repository rep) throws KettleException
{
if ( rep != null )
{
sharedObjectsFile = rep.getTransAttributeString(getId(), 0, "SHARED_FILE");
}
// Extract the shared steps, connections, etc. using the SharedObjects class
String soFile = environmentSubstitute(sharedObjectsFile);
SharedObjects sharedObjects = new SharedObjects(soFile);
// First read the databases...
// We read databases & slaves first because there might be dependencies that need to be resolved.
for (SharedObjectInterface object : sharedObjects.getObjectsMap().values())
{
if (object instanceof DatabaseMeta)
{
DatabaseMeta databaseMeta = (DatabaseMeta) object;
addOrReplaceDatabase(databaseMeta);
}
else if (object instanceof SlaveServer)
{
SlaveServer slaveServer = (SlaveServer) object;
addOrReplaceSlaveServer(slaveServer);
}
else if (object instanceof StepMeta)
{
StepMeta stepMeta = (StepMeta) object;
addOrReplaceStep(stepMeta);
}
else if (object instanceof PartitionSchema)
{
PartitionSchema partitionSchema = (PartitionSchema) object;
addOrReplacePartitionSchema(partitionSchema);
}
else if (object instanceof ClusterSchema)
{
ClusterSchema clusterSchema = (ClusterSchema) object;
addOrReplaceClusterSchema(clusterSchema);
}
}
if (rep!=null)
{
readDatabases(rep, true);
readPartitionSchemas(rep, true);
readSlaves(rep, true);
readClusters(rep, true);
}
}
/**
* Gives you an List of all the steps that are at least used in one active hop. These steps will be used to
* execute the transformation. The others will not be executed.
* Update 3.0 : we also add those steps that are not linked to another hop, but have at least one remote input or output step defined.
*
* @param all Set to true if you want to get ALL the steps from the transformation.
* @return A ArrayList of steps
*/
public List<StepMeta> getTransHopSteps(boolean all)
{
List<StepMeta> st = new ArrayList<StepMeta>();
int idx;
for (int x = 0; x < nrTransHops(); x++)
{
TransHopMeta hi = getTransHop(x);
if (hi.isEnabled() || all)
{
idx = st.indexOf(hi.getFromStep()); // FROM
if (idx < 0) st.add(hi.getFromStep());
idx = st.indexOf(hi.getToStep());
if (idx < 0) st.add(hi.getToStep());
}
}
// Also, add the steps that need to be painted, but are not part of a hop
for (int x = 0; x < nrSteps(); x++)
{
StepMeta stepMeta = getStep(x);
if (stepMeta.isDrawn() && !isStepUsedInTransHops(stepMeta))
{
st.add(stepMeta);
}
if (!stepMeta.getRemoteInputSteps().isEmpty() || !stepMeta.getRemoteOutputSteps().isEmpty())
{
if (!st.contains(stepMeta)) st.add(stepMeta);
}
}
return st;
}
/**
* Get the name of the transformation
*
* @return The name of the transformation
*/
public String getName()
{
return name;
}
/**
* Set the name of the transformation.
*
* @param n The new name of the transformation
*/
public void setName(String n)
{
name = n;
setInternalKettleVariables();
}
/**
* Builds a name - if no name is set, yet - from the filename
*/
public void nameFromFilename()
{
if (!Const.isEmpty(filename))
{
name = Const.createName(filename);
}
}
/**
* Get the filename (if any) of the transformation
*
* @return The filename of the transformation.
*/
public String getFilename()
{
return filename;
}
/**
* Set the filename of the transformation
*
* @param fname The new filename of the transformation.
*/
public void setFilename(String fname)
{
filename = fname;
setInternalKettleVariables();
}
/**
* Determines if a step has been used in a hop or not.
*
* @param stepMeta The step queried.
* @return True if a step is used in a hop (active or not), false if this is not the case.
*/
public boolean isStepUsedInTransHops(StepMeta stepMeta)
{
TransHopMeta fr = findTransHopFrom(stepMeta);
TransHopMeta to = findTransHopTo(stepMeta);
if (fr != null || to != null) return true;
return false;
}
/**
* Sets the changed parameter of the transformation.
*
* @param ch True if you want to mark the transformation as changed, false if not.
*/
public void setChanged(boolean ch)
{
if (ch)
setChanged();
else
clearChanged();
}
/**
* Clears the different changed flags of the transformation.
*
*/
public void clearChanged()
{
changed_steps = false;
changed_databases = false;
changed_hops = false;
changed_notes = false;
for (int i = 0; i < nrSteps(); i++)
{
getStep(i).setChanged(false);
if (getStep(i).getStepPartitioningMeta() != null)
{
getStep(i).getStepPartitioningMeta().hasChanged(false);
}
}
for (int i = 0; i < nrDatabases(); i++)
{
getDatabase(i).setChanged(false);
}
for (int i = 0; i < nrTransHops(); i++)
{
getTransHop(i).setChanged(false);
}
for (int i = 0; i < nrNotes(); i++)
{
getNote(i).setChanged(false);
}
for (int i = 0; i < partitionSchemas.size(); i++)
{
partitionSchemas.get(i).setChanged(false);
}
for (int i = 0; i < clusterSchemas.size(); i++)
{
clusterSchemas.get(i).setChanged(false);
}
super.clearChanged();
}
/* (non-Javadoc)
* @see org.pentaho.di.trans.HasDatabaseInterface#haveConnectionsChanged()
*/
public boolean haveConnectionsChanged()
{
if (changed_databases) return true;
for (int i = 0; i < nrDatabases(); i++)
{
DatabaseMeta ci = getDatabase(i);
if (ci.hasChanged()) return true;
}
return false;
}
/**
* Checks whether or not the steps have changed.
*
* @return True if the connections have been changed.
*/
public boolean haveStepsChanged()
{
if (changed_steps) return true;
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (stepMeta.hasChanged()) return true;
if (stepMeta.getStepPartitioningMeta() != null && stepMeta.getStepPartitioningMeta().hasChanged() ) return true;
}
return false;
}
/**
* Checks whether or not any of the hops have been changed.
*
* @return True if a hop has been changed.
*/
public boolean haveHopsChanged()
{
if (changed_hops) return true;
for (int i = 0; i < nrTransHops(); i++)
{
TransHopMeta hi = getTransHop(i);
if (hi.hasChanged()) return true;
}
return false;
}
/**
* Checks whether or not any of the notes have been changed.
*
* @return True if the notes have been changed.
*/
public boolean haveNotesChanged()
{
if (changed_notes) return true;
for (int i = 0; i < nrNotes(); i++)
{
NotePadMeta ni = getNote(i);
if (ni.hasChanged()) return true;
}
return false;
}
/**
* Checks whether or not any of the partitioning schemas have been changed.
*
* @return True if the partitioning schemas have been changed.
*/
public boolean havePartitionSchemasChanged()
{
for (int i = 0; i < partitionSchemas.size(); i++)
{
PartitionSchema ps = partitionSchemas.get(i);
if (ps.hasChanged()) return true;
}
return false;
}
/**
* Checks whether or not any of the clustering schemas have been changed.
*
* @return True if the clustering schemas have been changed.
*/
public boolean haveClusterSchemasChanged()
{
for (int i = 0; i < clusterSchemas.size(); i++)
{
ClusterSchema cs = clusterSchemas.get(i);
if (cs.hasChanged()) return true;
}
return false;
}
/**
* Checks whether or not the transformation has changed.
*
* @return True if the transformation has changed.
*/
public boolean hasChanged()
{
if (super.hasChanged()) return true;
if (haveConnectionsChanged()) return true;
if (haveStepsChanged()) return true;
if (haveHopsChanged()) return true;
if (haveNotesChanged()) return true;
if (havePartitionSchemasChanged()) return true;
if (haveClusterSchemasChanged()) return true;
return false;
}
/**
* See if there are any loops in the transformation, starting at the indicated step. This works by looking at all
* the previous steps. If you keep going backward and find the step, there is a loop. Both the informational and the
* normal steps need to be checked for loops!
*
* @param stepMeta The step position to start looking
*
* @return True if a loop has been found, false if no loop is found.
*/
public boolean hasLoop(StepMeta stepMeta)
{
return hasLoop(stepMeta, null, true) || hasLoop(stepMeta, null, false);
}
/**
* See if there are any loops in the transformation, starting at the indicated step. This works by looking at all
* the previous steps. If you keep going backward and find the orginal step again, there is a loop.
*
* @param stepMeta The step position to start looking
* @param lookup The original step when wandering around the transformation.
* @param info Check the informational steps or not.
*
* @return True if a loop has been found, false if no loop is found.
*/
public boolean hasLoop(StepMeta stepMeta, StepMeta lookup, boolean info)
{
int nr = findNrPrevSteps(stepMeta, info);
for (int i = 0; i < nr; i++)
{
StepMeta prevStepMeta = findPrevStep(stepMeta, i, info);
if (prevStepMeta != null)
{
if (prevStepMeta.equals(stepMeta)) return true;
if (prevStepMeta.equals(lookup)) return true;
if (hasLoop(prevStepMeta, lookup == null ? stepMeta : lookup, info)) return true;
}
}
return false;
}
/**
* Mark all steps in the transformation as selected.
*
*/
public void selectAll()
{
int i;
for (i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
stepMeta.setSelected(true);
}
for (i = 0; i < nrNotes(); i++)
{
NotePadMeta ni = getNote(i);
ni.setSelected(true);
}
setChanged();
notifyObservers("refreshGraph");
}
/**
* Clear the selection of all steps.
*
*/
public void unselectAll()
{
int i;
for (i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
stepMeta.setSelected(false);
}
for (i = 0; i < nrNotes(); i++)
{
NotePadMeta ni = getNote(i);
ni.setSelected(false);
}
}
/**
* Count the number of selected steps in this transformation
*
* @return The number of selected steps.
*/
public int nrSelectedSteps()
{
int i, count;
count = 0;
for (i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn()) count++;
}
return count;
}
/**
* Get the selected step at a certain location
*
* @param nr The location
* @return The selected step
*/
public StepMeta getSelectedStep(int nr)
{
int i, count;
count = 0;
for (i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (stepMeta.isSelected() && stepMeta.isDrawn())
{
if (nr == count) return stepMeta;
count++;
}
}
return null;
}
/**
* Count the number of selected notes in this transformation
*
* @return The number of selected notes.
*/
public int nrSelectedNotes()
{
int i, count;
count = 0;
for (i = 0; i < nrNotes(); i++)
{
NotePadMeta ni = getNote(i);
if (ni.isSelected()) count++;
}
return count;
}
/**
* Get the selected note at a certain index
*
* @param nr The index
* @return The selected note
*/
public NotePadMeta getSelectedNote(int nr)
{
int i, count;
count = 0;
for (i = 0; i < nrNotes(); i++)
{
NotePadMeta ni = getNote(i);
if (ni.isSelected())
{
if (nr == count) return ni;
count++;
}
}
return null;
}
/**
* Get an array of all the selected step and note locations
*
* @return The selected step and notes locations.
*/
public Point[] getSelectedStepLocations()
{
List<Point> points = new ArrayList<Point>();
for (int i = 0; i < nrSelectedSteps(); i++)
{
StepMeta stepMeta = getSelectedStep(i);
Point p = stepMeta.getLocation();
points.add(new Point(p.x, p.y)); // explicit copy of location
}
return points.toArray(new Point[points.size()]);
}
/**
* Get an array of all the selected step and note locations
*
* @return The selected step and notes locations.
*/
public Point[] getSelectedNoteLocations()
{
List<Point> points = new ArrayList<Point>();
for (int i = 0; i < nrSelectedNotes(); i++)
{
NotePadMeta ni = getSelectedNote(i);
Point p = ni.getLocation();
points.add(new Point(p.x, p.y)); // explicit copy of location
}
return points.toArray(new Point[points.size()]);
}
/**
* Get an array of all the selected steps
*
* @return An array of all the selected steps.
*/
public StepMeta[] getSelectedSteps()
{
int sels = nrSelectedSteps();
if (sels == 0) return null;
StepMeta retval[] = new StepMeta[sels];
for (int i = 0; i < sels; i++)
{
StepMeta stepMeta = getSelectedStep(i);
retval[i] = stepMeta;
}
return retval;
}
/**
* Get an array of all the selected steps
*
* @return A list containing all the selected & drawn steps.
*/
public List<GUIPositionInterface> getSelectedDrawnStepsList()
{
List<GUIPositionInterface> list = new ArrayList<GUIPositionInterface>();
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (stepMeta.isDrawn() && stepMeta.isSelected()) list.add(stepMeta);
}
return list;
}
/**
* Get an array of all the selected notes
*
* @return An array of all the selected notes.
*/
public NotePadMeta[] getSelectedNotes()
{
int sels = nrSelectedNotes();
if (sels == 0) return null;
NotePadMeta retval[] = new NotePadMeta[sels];
for (int i = 0; i < sels; i++)
{
NotePadMeta si = getSelectedNote(i);
retval[i] = si;
}
return retval;
}
/**
* Get an array of all the selected step names
*
* @return An array of all the selected step names.
*/
public String[] getSelectedStepNames()
{
int sels = nrSelectedSteps();
if (sels == 0) return null;
String retval[] = new String[sels];
for (int i = 0; i < sels; i++)
{
StepMeta stepMeta = getSelectedStep(i);
retval[i] = stepMeta.getName();
}
return retval;
}
/**
* Get an array of the locations of an array of steps
*
* @param steps An array of steps
* @return an array of the locations of an array of steps
*/
public int[] getStepIndexes(StepMeta steps[])
{
int retval[] = new int[steps.length];
for (int i = 0; i < steps.length; i++)
{
retval[i] = indexOfStep(steps[i]);
}
return retval;
}
/**
* Get an array of the locations of an array of notes
*
* @param notes An array of notes
* @return an array of the locations of an array of notes
*/
public int[] getNoteIndexes(NotePadMeta notes[])
{
int retval[] = new int[notes.length];
for (int i = 0; i < notes.length; i++)
retval[i] = indexOfNote(notes[i]);
return retval;
}
/**
* Get the maximum number of undo operations possible
*
* @return The maximum number of undo operations that are allowed.
*/
public int getMaxUndo()
{
return max_undo;
}
/**
* Sets the maximum number of undo operations that are allowed.
*
* @param mu The maximum number of undo operations that are allowed.
*/
public void setMaxUndo(int mu)
{
max_undo = mu;
while (undo.size() > mu && undo.size() > 0)
undo.remove(0);
}
/**
* Add an undo operation to the undo list
*
* @param from array of objects representing the old state
* @param to array of objectes representing the new state
* @param pos An array of object locations
* @param prev An array of points representing the old positions
* @param curr An array of points representing the new positions
* @param type_of_change The type of change that's being done to the transformation.
* @param nextAlso indicates that the next undo operation needs to follow this one.
*/
public void addUndo(Object from[], Object to[], int pos[], Point prev[], Point curr[], int type_of_change, boolean nextAlso)
{
// First clean up after the current position.
// Example: position at 3, size=5
// 012345
// remove 34
// Add 4
// 01234
while (undo.size() > undo_position + 1 && undo.size() > 0)
{
int last = undo.size() - 1;
undo.remove(last);
}
TransAction ta = new TransAction();
switch (type_of_change)
{
case TYPE_UNDO_CHANGE:
ta.setChanged(from, to, pos);
break;
case TYPE_UNDO_DELETE:
ta.setDelete(from, pos);
break;
case TYPE_UNDO_NEW:
ta.setNew(from, pos);
break;
case TYPE_UNDO_POSITION:
ta.setPosition(from, pos, prev, curr);
break;
}
ta.setNextAlso(nextAlso);
undo.add(ta);
undo_position++;
if (undo.size() > max_undo)
{
undo.remove(0);
undo_position
}
}
/**
* Get the previous undo operation and change the undo pointer
*
* @return The undo transaction to be performed.
*/
public TransAction previousUndo()
{
if (undo.isEmpty() || undo_position < 0) return null; // No undo left!
TransAction retval = undo.get(undo_position);
undo_position
return retval;
}
/**
* View current undo, don't change undo position
*
* @return The current undo transaction
*/
public TransAction viewThisUndo()
{
if (undo.isEmpty() || undo_position < 0) return null; // No undo left!
TransAction retval = undo.get(undo_position);
return retval;
}
/**
* View previous undo, don't change undo position
*
* @return The previous undo transaction
*/
public TransAction viewPreviousUndo()
{
if (undo.isEmpty() || undo_position - 1 < 0) return null; // No undo left!
TransAction retval = undo.get(undo_position - 1);
return retval;
}
/**
* Get the next undo transaction on the list. Change the undo pointer.
*
* @return The next undo transaction (for redo)
*/
public TransAction nextUndo()
{
int size = undo.size();
if (size == 0 || undo_position >= size - 1) return null; // no redo left...
undo_position++;
TransAction retval = undo.get(undo_position);
return retval;
}
/**
* Get the next undo transaction on the list.
*
* @return The next undo transaction (for redo)
*/
public TransAction viewNextUndo()
{
int size = undo.size();
if (size == 0 || undo_position >= size - 1) return null; // no redo left...
TransAction retval = undo.get(undo_position + 1);
return retval;
}
/**
* Get the maximum size of the canvas by calculating the maximum location of a step
*
* @return Maximum coordinate of a step in the transformation + (100,100) for safety.
*/
public Point getMaximum()
{
int maxx = 0, maxy = 0;
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
Point loc = stepMeta.getLocation();
if (loc.x > maxx) maxx = loc.x;
if (loc.y > maxy) maxy = loc.y;
}
for (int i = 0; i < nrNotes(); i++)
{
NotePadMeta notePadMeta = getNote(i);
Point loc = notePadMeta.getLocation();
if (loc.x + notePadMeta.width > maxx) maxx = loc.x + notePadMeta.width;
if (loc.y + notePadMeta.height > maxy) maxy = loc.y + notePadMeta.height;
}
return new Point(maxx + 100, maxy + 100);
}
/**
* Get the names of all the steps.
*
* @return An array of step names.
*/
public String[] getStepNames()
{
String retval[] = new String[nrSteps()];
for (int i = 0; i < nrSteps(); i++)
retval[i] = getStep(i).getName();
return retval;
}
/**
* Get all the steps in an array.
*
* @return An array of all the steps in the transformation.
*/
public StepMeta[] getStepsArray()
{
StepMeta retval[] = new StepMeta[nrSteps()];
for (int i = 0; i < nrSteps(); i++)
retval[i] = getStep(i);
return retval;
}
/**
* Look in the transformation and see if we can find a step in a previous location starting somewhere.
*
* @param startStep The starting step
* @param stepToFind The step to look for backward in the transformation
* @return true if we can find the step in an earlier location in the transformation.
*/
public boolean findPrevious(StepMeta startStep, StepMeta stepToFind)
{
// Normal steps
int nrPrevious = findNrPrevSteps(startStep, false);
for (int i = 0; i < nrPrevious; i++)
{
StepMeta stepMeta = findPrevStep(startStep, i, false);
if (stepMeta.equals(stepToFind)) return true;
boolean found = findPrevious(stepMeta, stepToFind); // Look further back in the tree.
if (found) return true;
}
// Info steps
nrPrevious = findNrPrevSteps(startStep, true);
for (int i = 0; i < nrPrevious; i++)
{
StepMeta stepMeta = findPrevStep(startStep, i, true);
if (stepMeta.equals(stepToFind)) return true;
boolean found = findPrevious(stepMeta, stepToFind); // Look further back in the tree.
if (found) return true;
}
return false;
}
/**
* Put the steps in alfabetical order.
*/
public void sortSteps()
{
try
{
Collections.sort(steps);
}
catch (Exception e)
{
LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.Exception.ErrorOfSortingSteps") + e); //$NON-NLS-1$
LogWriter.getInstance().logError(toString(), Const.getStackTracker(e));
}
}
public void sortHops()
{
Collections.sort(hops);
}
/**
* Put the steps in a more natural order: from start to finish. For the moment, we ignore splits and joins. Splits
* and joins can't be listed sequentially in any case!
*
*/
public void sortStepsNatural()
{
// Loop over the steps...
for (int j = 0; j < nrSteps(); j++)
{
// Buble sort: we need to do this several times...
for (int i = 0; i < nrSteps() - 1; i++)
{
StepMeta one = getStep(i);
StepMeta two = getStep(i + 1);
if (!findPrevious(two, one))
{
setStep(i + 1, one);
setStep(i, two);
}
}
}
}
/**
* Sort the hops in a natural way: from beginning to end
*/
public void sortHopsNatural()
{
// Loop over the hops...
for (int j = 0; j < nrTransHops(); j++)
{
// Buble sort: we need to do this several times...
for (int i = 0; i < nrTransHops() - 1; i++)
{
TransHopMeta one = getTransHop(i);
TransHopMeta two = getTransHop(i + 1);
StepMeta a = two.getFromStep();
StepMeta b = one.getToStep();
if (!findPrevious(a, b) && !a.equals(b))
{
setTransHop(i + 1, one);
setTransHop(i, two);
}
}
}
}
/**
* This procedure determines the impact of the different steps in a transformation on databases, tables and field.
*
* @param impact An ArrayList of DatabaseImpact objects.
*
*/
public void analyseImpact(List<DatabaseImpact> impact, IProgressMonitor monitor) throws KettleStepException
{
if (monitor != null)
{
monitor.beginTask(Messages.getString("TransMeta.Monitor.DeterminingImpactTask.Title"), nrSteps()); //$NON-NLS-1$
}
boolean stop = false;
for (int i = 0; i < nrSteps() && !stop; i++)
{
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.LookingAtStepTask.Title") + (i + 1) + "/" + nrSteps()); //$NON-NLS-1$ //$NON-NLS-2$
StepMeta stepMeta = getStep(i);
RowMetaInterface prev = getPrevStepFields(stepMeta);
StepMetaInterface stepint = stepMeta.getStepMetaInterface();
RowMetaInterface inform = null;
StepMeta[] lu = getInfoStep(stepMeta);
if (lu != null)
{
inform = getStepFields(lu);
}
else
{
inform = stepint.getTableFields();
}
stepint.analyseImpact(impact, this, stepMeta, prev, null, null, inform);
if (monitor != null)
{
monitor.worked(1);
stop = monitor.isCanceled();
}
}
if (monitor != null) monitor.done();
}
/**
* Proposes an alternative stepname when the original already exists...
*
* @param stepname The stepname to find an alternative for..
* @return The alternative stepname.
*/
public String getAlternativeStepname(String stepname)
{
String newname = stepname;
StepMeta stepMeta = findStep(newname);
int nr = 1;
while (stepMeta != null)
{
nr++;
newname = stepname + " " + nr; //$NON-NLS-1$
stepMeta = findStep(newname);
}
return newname;
}
/**
* Builds a list of all the SQL statements that this transformation needs in order to work properly.
*
* @return An ArrayList of SQLStatement objects.
*/
public List<SQLStatement> getSQLStatements() throws KettleStepException
{
return getSQLStatements(null);
}
/**
* Builds a list of all the SQL statements that this transformation needs in order to work properly.
*
* @return An ArrayList of SQLStatement objects.
*/
public List<SQLStatement> getSQLStatements(IProgressMonitor monitor) throws KettleStepException
{
if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForTransformationTask.Title"), nrSteps() + 1); //$NON-NLS-1$
List<SQLStatement> stats = new ArrayList<SQLStatement>();
for (int i = 0; i < nrSteps(); i++)
{
StepMeta stepMeta = getStep(i);
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForStepTask.Title",""+stepMeta )); //$NON-NLS-1$ //$NON-NLS-2$
RowMetaInterface prev = getPrevStepFields(stepMeta);
SQLStatement sql = stepMeta.getStepMetaInterface().getSQLStatements(this, stepMeta, prev);
if (sql.getSQL() != null || sql.hasError())
{
stats.add(sql);
}
if (monitor != null) monitor.worked(1);
}
// Also check the sql for the logtable...
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForTransformationTask.Title2")); //$NON-NLS-1$
if (logConnection != null && logTable != null && logTable.length() > 0)
{
Database db = new Database(logConnection);
db.shareVariablesWith(this);
try
{
db.connect();
RowMetaInterface fields = Database.getTransLogrecordFields(false, useBatchId, logfieldUsed);
String sql = db.getDDL(logTable, fields);
if (sql != null && sql.length() > 0)
{
SQLStatement stat = new SQLStatement("<this transformation>", logConnection, sql); //$NON-NLS-1$
stats.add(stat);
}
}
catch (KettleDatabaseException dbe)
{
SQLStatement stat = new SQLStatement("<this transformation>", logConnection, null); //$NON-NLS-1$
stat.setError(Messages.getString("TransMeta.SQLStatement.ErrorDesc.ErrorObtainingTransformationLogTableInfo") + dbe.getMessage()); //$NON-NLS-1$
stats.add(stat);
}
finally
{
db.disconnect();
}
}
if (monitor != null) monitor.worked(1);
if (monitor != null) monitor.done();
return stats;
}
/**
* Get the SQL statements, needed to run this transformation, as one String.
*
* @return the SQL statements needed to run this transformation.
*/
public String getSQLStatementsString() throws KettleStepException
{
String sql = ""; //$NON-NLS-1$
List<SQLStatement> stats = getSQLStatements();
for (int i = 0; i < stats.size(); i++)
{
SQLStatement stat = stats.get(i);
if (!stat.hasError() && stat.hasSQL())
{
sql += stat.getSQL();
}
}
return sql;
}
/**
* Checks all the steps and fills a List of (CheckResult) remarks.
*
* @param remarks The remarks list to add to.
* @param only_selected Check only the selected steps.
* @param monitor The progress monitor to use, null if not used
*/
public void checkSteps(List<CheckResultInterface> remarks, boolean only_selected, IProgressMonitor monitor)
{
try
{
remarks.clear(); // Start with a clean slate...
Map<ValueMetaInterface,String> values = new Hashtable<ValueMetaInterface,String>();
String stepnames[];
StepMeta steps[];
if (!only_selected || nrSelectedSteps() == 0)
{
stepnames = getStepNames();
steps = getStepsArray();
}
else
{
stepnames = getSelectedStepNames();
steps = getSelectedSteps();
}
boolean stop_checking = false;
if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.VerifyingThisTransformationTask.Title"), steps.length + 2); //$NON-NLS-1$
for (int i = 0; i < steps.length && !stop_checking; i++)
{
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.VerifyingStepTask.Title",stepnames[i])); //$NON-NLS-1$ //$NON-NLS-2$
StepMeta stepMeta = steps[i];
int nrinfo = findNrInfoSteps(stepMeta);
StepMeta[] infostep = null;
if (nrinfo > 0)
{
infostep = getInfoStep(stepMeta);
}
RowMetaInterface info = null;
if (infostep != null)
{
try
{
info = getStepFields(infostep);
}
catch (KettleStepException kse)
{
info = null;
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingStepInfoFields.Description",""+stepMeta , Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$
remarks.add(cr);
}
}
// The previous fields from non-informative steps:
RowMetaInterface prev = null;
try
{
prev = getPrevStepFields(stepMeta);
}
catch (KettleStepException kse)
{
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingInputFields.Description", ""+stepMeta
, Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$
remarks.add(cr);
// This is a severe error: stop checking...
// Otherwise we wind up checking time & time again because nothing gets put in the database
// cache, the timeout of certain databases is very long... (Oracle)
stop_checking = true;
}
if (isStepUsedInTransHops(stepMeta))
{
// Get the input & output steps!
// Copy to arrays:
String input[] = getPrevStepNames(stepMeta);
String output[] = getNextStepNames(stepMeta);
// Check step specific info...
stepMeta.check(remarks, this, prev, input, output, info);
if (prev != null)
{
for (int x = 0; x < prev.size(); x++)
{
ValueMetaInterface v = prev.getValueMeta(x);
String name = v.getName();
if (name == null)
values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameIsEmpty.Description")); //$NON-NLS-1$
else
if (name.indexOf(' ') >= 0)
values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameContainsSpaces.Description")); //$NON-NLS-1$
else
{
char list[] = new char[] { '.', ',', '-', '/', '+', '*', '\'', '\t', '"', '|', '@', '(', ')', '{', '}', '!', '^' };
for (int c = 0; c < list.length; c++)
{
if (name.indexOf(list[c]) >= 0)
values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameContainsUnfriendlyCodes.Description",String.valueOf(list[c]) )); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
// Check if 2 steps with the same name are entering the step...
if (prev.size() > 1)
{
String fieldNames[] = prev.getFieldNames();
String sortedNames[] = Const.sortStrings(fieldNames);
String prevName = sortedNames[0];
for (int x = 1; x < sortedNames.length; x++)
{
// Checking for doubles
if (prevName.equalsIgnoreCase(sortedNames[x]))
{
// Give a warning!!
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR,
Messages.getString("TransMeta.CheckResult.TypeResultWarning.HaveTheSameNameField.Description", prevName ), stepMeta); //$NON-NLS-1$ //$NON-NLS-2$
remarks.add(cr);
}
else
{
prevName = sortedNames[x];
}
}
}
}
else
{
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.CannotFindPreviousFields.Description") + stepMeta.getName(), //$NON-NLS-1$
stepMeta);
remarks.add(cr);
}
}
else
{
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.StepIsNotUsed.Description"), stepMeta); //$NON-NLS-1$
remarks.add(cr);
}
// Also check for mixing rows...
try
{
checkRowMixingStatically(stepMeta, null);
}
catch(KettleRowException e)
{
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, e.getMessage(), stepMeta);
remarks.add(cr);
}
if (monitor != null)
{
monitor.worked(1); // progress bar...
if (monitor.isCanceled()) stop_checking = true;
}
}
// Also, check the logging table of the transformation...
if (monitor == null || !monitor.isCanceled())
{
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingTheLoggingTableTask.Title")); //$NON-NLS-1$
if (getLogConnection() != null)
{
Database logdb = new Database(getLogConnection());
logdb.shareVariablesWith(this);
try
{
logdb.connect();
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.ConnectingWorks.Description"), //$NON-NLS-1$
null);
remarks.add(cr);
if (getLogTable() != null)
{
if (logdb.checkTableExists(getLogTable()))
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.LoggingTableExists.Description", getLogTable() ), null); //$NON-NLS-1$ //$NON-NLS-2$
remarks.add(cr);
RowMetaInterface fields = Database.getTransLogrecordFields(false, isBatchIdUsed(), isLogfieldUsed());
String sql = logdb.getDDL(getLogTable(), fields);
if (sql == null || sql.length() == 0)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.CorrectLayout.Description"), null); //$NON-NLS-1$
remarks.add(cr);
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LoggingTableNeedsAdjustments.Description") + Const.CR + sql, //$NON-NLS-1$
null);
remarks.add(cr);
}
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LoggingTableDoesNotExist.Description"), null); //$NON-NLS-1$
remarks.add(cr);
}
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LogTableNotSpecified.Description"), null); //$NON-NLS-1$
remarks.add(cr);
}
}
catch (KettleDatabaseException dbe)
{
}
finally
{
logdb.disconnect();
}
}
if (monitor != null) monitor.worked(1);
}
if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingForDatabaseUnfriendlyCharactersInFieldNamesTask.Title")); //$NON-NLS-1$
if (values.size() > 0)
{
for(ValueMetaInterface v:values.keySet())
{
String message = values.get(v);
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.Description",v.getName() , message ,v.getOrigin() ), findStep(v.getOrigin())); //$NON-NLS-1$
remarks.add(cr);
}
}
else
{
CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK,
Messages.getString("TransMeta.CheckResult.TypeResultOK.Description"), null); //$NON-NLS-1$
remarks.add(cr);
}
if (monitor != null) monitor.worked(1);
}
catch (Exception e)
{
LogWriter.getInstance().logError(toString(), Const.getStackTracker(e));
throw new RuntimeException(e);
}
}
/**
* @return Returns the resultRows.
*/
public List<RowMetaAndData> getResultRows()
{
return resultRows;
}
/**
* @param resultRows The resultRows to set.
*/
public void setResultRows(List<RowMetaAndData> resultRows)
{
this.resultRows = resultRows;
}
/**
* @return Returns the directory.
*/
public RepositoryDirectory getDirectory()
{
return directory;
}
/**
* @param directory The directory to set.
*/
public void setDirectory(RepositoryDirectory directory)
{
this.directory = directory;
setInternalKettleVariables();
}
/**
* @return Returns the directoryTree.
* @deprecated
*/
public RepositoryDirectory getDirectoryTree()
{
return directoryTree;
}
/**
* @param directoryTree The directoryTree to set.
* @deprecated
*/
public void setDirectoryTree(RepositoryDirectory directoryTree)
{
this.directoryTree = directoryTree;
}
/**
* @return The directory path plus the name of the transformation
*/
public String getPathAndName()
{
if (getDirectory().isRoot())
return getDirectory().getPath() + getName();
else
return getDirectory().getPath() + RepositoryDirectory.DIRECTORY_SEPARATOR + getName();
}
/**
* @return Returns the arguments.
*/
public String[] getArguments()
{
return arguments;
}
/**
* @param arguments The arguments to set.
*/
public void setArguments(String[] arguments)
{
this.arguments = arguments;
}
/**
* @return Returns the counters.
*/
public Hashtable<String,Counter> getCounters()
{
return counters;
}
/**
* @param counters The counters to set.
*/
public void setCounters(Hashtable<String,Counter> counters)
{
this.counters = counters;
}
/**
* @return Returns the dependencies.
*/
public List<TransDependency> getDependencies()
{
return dependencies;
}
/**
* @param dependencies The dependencies to set.
*/
public void setDependencies(List<TransDependency> dependencies)
{
this.dependencies = dependencies;
}
/**
* @return Returns the id.
*/
public long getId()
{
return id;
}
/**
* @param id The id to set.
*/
public void setId(long id)
{
this.id = id;
}
/**
* @return Returns the inputStep.
*/
public StepMeta getInputStep()
{
return inputStep;
}
/**
* @param inputStep The inputStep to set.
*/
public void setInputStep(StepMeta inputStep)
{
this.inputStep = inputStep;
}
/**
* @return Returns the logConnection.
*/
public DatabaseMeta getLogConnection()
{
return logConnection;
}
/**
* @param logConnection The logConnection to set.
*/
public void setLogConnection(DatabaseMeta logConnection)
{
this.logConnection = logConnection;
}
/**
* @return Returns the logTable.
*/
public String getLogTable()
{
return logTable;
}
/**
* @param logTable The logTable to set.
*/
public void setLogTable(String logTable)
{
this.logTable = logTable;
}
/**
* @return Returns the maxDateConnection.
*/
public DatabaseMeta getMaxDateConnection()
{
return maxDateConnection;
}
/**
* @param maxDateConnection The maxDateConnection to set.
*/
public void setMaxDateConnection(DatabaseMeta maxDateConnection)
{
this.maxDateConnection = maxDateConnection;
}
/**
* @return Returns the maxDateDifference.
*/
public double getMaxDateDifference()
{
return maxDateDifference;
}
/**
* @param maxDateDifference The maxDateDifference to set.
*/
public void setMaxDateDifference(double maxDateDifference)
{
this.maxDateDifference = maxDateDifference;
}
/**
* @return Returns the maxDateField.
*/
public String getMaxDateField()
{
return maxDateField;
}
/**
* @param maxDateField The maxDateField to set.
*/
public void setMaxDateField(String maxDateField)
{
this.maxDateField = maxDateField;
}
/**
* @return Returns the maxDateOffset.
*/
public double getMaxDateOffset()
{
return maxDateOffset;
}
/**
* @param maxDateOffset The maxDateOffset to set.
*/
public void setMaxDateOffset(double maxDateOffset)
{
this.maxDateOffset = maxDateOffset;
}
/**
* @return Returns the maxDateTable.
*/
public String getMaxDateTable()
{
return maxDateTable;
}
/**
* @param maxDateTable The maxDateTable to set.
*/
public void setMaxDateTable(String maxDateTable)
{
this.maxDateTable = maxDateTable;
}
/**
* @return Returns the outputStep.
*/
public StepMeta getOutputStep()
{
return outputStep;
}
/**
* @param outputStep The outputStep to set.
*/
public void setOutputStep(StepMeta outputStep)
{
this.outputStep = outputStep;
}
/**
* @return Returns the readStep.
*/
public StepMeta getReadStep()
{
return readStep;
}
/**
* @param readStep The readStep to set.
*/
public void setReadStep(StepMeta readStep)
{
this.readStep = readStep;
}
/**
* @return Returns the updateStep.
*/
public StepMeta getUpdateStep()
{
return updateStep;
}
/**
* @param updateStep The updateStep to set.
*/
public void setUpdateStep(StepMeta updateStep)
{
this.updateStep = updateStep;
}
/**
* @return Returns the writeStep.
*/
public StepMeta getWriteStep()
{
return writeStep;
}
/**
* @param writeStep The writeStep to set.
*/
public void setWriteStep(StepMeta writeStep)
{
this.writeStep = writeStep;
}
/**
* @return Returns the sizeRowset.
*/
public int getSizeRowset()
{
return sizeRowset;
}
/**
* @param sizeRowset The sizeRowset to set.
*/
public void setSizeRowset(int sizeRowset)
{
this.sizeRowset = sizeRowset;
}
/**
* @return Returns the dbCache.
*/
public DBCache getDbCache()
{
return dbCache;
}
/**
* @param dbCache The dbCache to set.
*/
public void setDbCache(DBCache dbCache)
{
this.dbCache = dbCache;
}
/**
* @return Returns the useBatchId.
*/
public boolean isBatchIdUsed()
{
return useBatchId;
}
/**
* @param useBatchId The useBatchId to set.
*/
public void setBatchIdUsed(boolean useBatchId)
{
this.useBatchId = useBatchId;
}
/**
* @return Returns the logfieldUsed.
*/
public boolean isLogfieldUsed()
{
return logfieldUsed;
}
/**
* @param logfieldUsed The logfieldUsed to set.
*/
public void setLogfieldUsed(boolean logfieldUsed)
{
this.logfieldUsed = logfieldUsed;
}
/**
* @return Returns the createdDate.
*/
public Date getCreatedDate()
{
return createdDate;
}
/**
* @param createdDate The createdDate to set.
*/
public void setCreatedDate(Date createdDate)
{
this.createdDate = createdDate;
}
/**
* @param createdUser The createdUser to set.
*/
public void setCreatedUser(String createdUser)
{
this.createdUser = createdUser;
}
/**
* @return Returns the createdUser.
*/
public String getCreatedUser()
{
return createdUser;
}
/**
* @param modifiedDate The modifiedDate to set.
*/
public void setModifiedDate(Date modifiedDate)
{
this.modifiedDate = modifiedDate;
}
/**
* @return Returns the modifiedDate.
*/
public Date getModifiedDate()
{
return modifiedDate;
}
/**
* @param modifiedUser The modifiedUser to set.
*/
public void setModifiedUser(String modifiedUser)
{
this.modifiedUser = modifiedUser;
}
/**
* @return Returns the modifiedUser.
*/
public String getModifiedUser()
{
return modifiedUser;
}
/**
* Get the description of the transformation
*
* @return The description of the transformation
*/
public String getDescription()
{
return description;
}
/**
* Set the description of the transformation.
*
* @param n The new description of the transformation
*/
public void setDescription(String n)
{
description = n;
}
/**
* Set the extended description of the transformation.
*
* @param n The new extended description of the transformation
*/
public void setExtendedDescription(String n)
{
extended_description = n;
}
/**
* Get the extended description of the transformation
*
* @return The extended description of the transformation
*/
public String getExtendedDescription()
{
return extended_description;
}
/**
* Get the version of the transformation
*
* @return The version of the transformation
*/
public String getTransversion()
{
return trans_version;
}
/**
* Set the version of the transformation.
*
* @param n The new version description of the transformation
*/
public void setTransversion(String n)
{
trans_version = n;
}
/**
* Set the status of the transformation.
*
* @param n The new status description of the transformation
*/
public void setTransstatus(int n)
{
trans_status = n;
}
/**
* Get the status of the transformation
*
* @return The status of the transformation
*/
public int getTransstatus()
{
return trans_status;
}
/**
* @return the textual representation of the transformation: it's name. If the name has not been set, the classname
* is returned.
*/
public String toString()
{
if (name != null) return name;
if (filename != null) return filename;
return TransMeta.class.getName();
}
/**
* Cancel queries opened for checking & fieldprediction
*/
public void cancelQueries() throws KettleDatabaseException
{
for (int i = 0; i < nrSteps(); i++)
{
getStep(i).getStepMetaInterface().cancelQueries();
}
}
/**
* Get the arguments used by this transformation.
*
* @param arguments
* @return A row with the used arguments in it.
*/
public Map<String, String> getUsedArguments(String[] arguments)
{
Map<String, String> transArgs = new HashMap<String, String>();
for (int i = 0; i < nrSteps(); i++)
{
StepMetaInterface smi = getStep(i).getStepMetaInterface();
Map<String, String> stepArgs = smi.getUsedArguments(); // Get the command line arguments that this step uses.
if (stepArgs != null)
{
transArgs.putAll(stepArgs);
}
}
// OK, so perhaps, we can use the arguments from a previous execution?
String[] saved = Props.isInitialized() ? Props.getInstance().getLastArguments() : null;
// Set the default values on it...
// Also change the name to "Argument 1" .. "Argument 10"
for (String argument : transArgs.keySet())
{
String value = "";
int argNr = Const.toInt(argument, -1);
if (arguments!=null && argNr > 0 && argNr <= arguments.length)
{
value = Const.NVL(arguments[argNr-1], "");
}
if (value.length()==0) // try the saved option...
{
if (argNr > 0 && argNr < saved.length && saved[argNr] != null)
{
value = saved[argNr-1];
}
}
transArgs.put(argument, value);
}
return transArgs;
}
/**
* @return Sleep time waiting when buffer is empty, in nano-seconds
*/
public int getSleepTimeEmpty()
{
return Const.TIMEOUT_GET_MILLIS;
}
/**
* @return Sleep time waiting when buffer is full, in nano-seconds
*/
public int getSleepTimeFull()
{
return Const.TIMEOUT_PUT_MILLIS;
}
/**
* @param sleepTimeEmpty The sleepTimeEmpty to set.
*/
public void setSleepTimeEmpty(int sleepTimeEmpty)
{
this.sleepTimeEmpty = sleepTimeEmpty;
}
/**
* @param sleepTimeFull The sleepTimeFull to set.
*/
public void setSleepTimeFull(int sleepTimeFull)
{
this.sleepTimeFull = sleepTimeFull;
}
/**
* This method asks all steps in the transformation whether or not the specified database connection is used.
* The connection is used in the transformation if any of the steps uses it or if it is being used to log to.
* @param databaseMeta The connection to check
* @return true if the connection is used in this transformation.
*/
public boolean isDatabaseConnectionUsed(DatabaseMeta databaseMeta)
{
for (int i=0;i<nrSteps();i++)
{
StepMeta stepMeta = getStep(i);
DatabaseMeta dbs[] = stepMeta.getStepMetaInterface().getUsedDatabaseConnections();
for (int d=0;d<dbs.length;d++)
{
if (dbs[d].equals(databaseMeta)) return true;
}
}
if (logConnection!=null && logConnection.equals(databaseMeta)) return true;
return false;
}
/*
public List getInputFiles() {
return inputFiles;
}
public void setInputFiles(List inputFiles) {
this.inputFiles = inputFiles;
}
*/
/**
* Get a list of all the strings used in this transformation.
*
* @return A list of StringSearchResult with strings used in the
*/
public List<StringSearchResult> getStringList(boolean searchSteps, boolean searchDatabases, boolean searchNotes, boolean includePasswords)
{
List<StringSearchResult> stringList = new ArrayList<StringSearchResult>();
if (searchSteps)
{
// Loop over all steps in the transformation and see what the used vars are...
for (int i=0;i<nrSteps();i++)
{
StepMeta stepMeta = getStep(i);
stringList.add(new StringSearchResult(stepMeta.getName(), stepMeta, this, "Step name"));
if (stepMeta.getDescription()!=null) stringList.add(new StringSearchResult(stepMeta.getDescription(), stepMeta, this, "Step description"));
StepMetaInterface metaInterface = stepMeta.getStepMetaInterface();
StringSearcher.findMetaData(metaInterface, 1, stringList, stepMeta, this);
}
}
// Loop over all steps in the transformation and see what the used vars are...
if (searchDatabases)
{
for (int i=0;i<nrDatabases();i++)
{
DatabaseMeta meta = getDatabase(i);
stringList.add(new StringSearchResult(meta.getName(), meta, this, "Database connection name"));
if (meta.getHostname()!=null) stringList.add(new StringSearchResult(meta.getHostname(), meta, this, "Database hostname"));
if (meta.getDatabaseName()!=null) stringList.add(new StringSearchResult(meta.getDatabaseName(), meta, this, "Database name"));
if (meta.getUsername()!=null) stringList.add(new StringSearchResult(meta.getUsername(), meta, this, "Database Username"));
if (meta.getDatabaseTypeDesc()!=null) stringList.add(new StringSearchResult(meta.getDatabaseTypeDesc(), meta, this, "Database type description"));
if (meta.getDatabasePortNumberString()!=null) stringList.add(new StringSearchResult(meta.getDatabasePortNumberString(), meta, this, "Database port"));
if (meta.getServername()!=null) stringList.add(new StringSearchResult(meta.getServername(), meta, this, "Database server"));
if ( includePasswords )
{
if (meta.getPassword()!=null) stringList.add(new StringSearchResult(meta.getPassword(), meta, this, "Database password"));
}
}
}
// Loop over all steps in the transformation and see what the used vars are...
if (searchNotes)
{
for (int i=0;i<nrNotes();i++)
{
NotePadMeta meta = getNote(i);
if (meta.getNote()!=null) stringList.add(new StringSearchResult(meta.getNote(), meta, this, "Notepad text"));
}
}
return stringList;
}
public List<StringSearchResult> getStringList(boolean searchSteps, boolean searchDatabases, boolean searchNotes)
{
return getStringList(searchSteps, searchDatabases, searchNotes, false);
}
public List<String> getUsedVariables()
{
// Get the list of Strings.
List<StringSearchResult> stringList = getStringList(true, true, false, true);
List<String> varList = new ArrayList<String>();
// Look around in the strings, see what we find...
for (int i=0;i<stringList.size();i++)
{
StringSearchResult result = stringList.get(i);
StringUtil.getUsedVariables(result.getString(), varList, false);
}
return varList;
}
/**
* @return Returns the previousResult.
*/
public Result getPreviousResult()
{
return previousResult;
}
/**
* @param previousResult The previousResult to set.
*/
public void setPreviousResult(Result previousResult)
{
this.previousResult = previousResult;
}
/**
* @return Returns the resultFiles.
*/
public List<ResultFile> getResultFiles()
{
return resultFiles;
}
/**
* @param resultFiles The resultFiles to set.
*/
public void setResultFiles(List<ResultFile> resultFiles)
{
this.resultFiles = resultFiles;
}
/**
* @return the partitionSchemas
*/
public List<PartitionSchema> getPartitionSchemas()
{
return partitionSchemas;
}
/**
* @param partitionSchemas the partitionSchemas to set
*/
public void setPartitionSchemas(List<PartitionSchema> partitionSchemas)
{
this.partitionSchemas = partitionSchemas;
}
/**
* Get the available partition schema names.
* @return
*/
public String[] getPartitionSchemasNames()
{
String names[] = new String[partitionSchemas.size()];
for (int i=0;i<names.length;i++)
{
names[i] = partitionSchemas.get(i).getName();
}
return names;
}
/**
* @return the feedbackShown
*/
public boolean isFeedbackShown()
{
return feedbackShown;
}
/**
* @param feedbackShown the feedbackShown to set
*/
public void setFeedbackShown(boolean feedbackShown)
{
this.feedbackShown = feedbackShown;
}
/**
* @return the feedbackSize
*/
public int getFeedbackSize()
{
return feedbackSize;
}
/**
* @param feedbackSize the feedbackSize to set
*/
public void setFeedbackSize(int feedbackSize)
{
this.feedbackSize = feedbackSize;
}
/**
* @return the usingUniqueConnections
*/
public boolean isUsingUniqueConnections()
{
return usingUniqueConnections;
}
/**
* @param usingUniqueConnections the usingUniqueConnections to set
*/
public void setUsingUniqueConnections(boolean usingUniqueConnections)
{
this.usingUniqueConnections = usingUniqueConnections;
}
public List<ClusterSchema> getClusterSchemas()
{
return clusterSchemas;
}
public void setClusterSchemas(List<ClusterSchema> clusterSchemas)
{
this.clusterSchemas = clusterSchemas;
}
/**
* @return The slave server strings from this cluster schema
*/
public String[] getClusterSchemaNames()
{
String[] names = new String[clusterSchemas.size()];
for (int i=0;i<names.length;i++)
{
names[i] = clusterSchemas.get(i).getName();
}
return names;
}
/**
* Find a partition schema using its name.
* @param name The name of the partition schema to look for.
* @return the partition with the specified name of null if nothing was found
*/
public PartitionSchema findPartitionSchema(String name)
{
for (int i=0;i<partitionSchemas.size();i++)
{
PartitionSchema schema = partitionSchemas.get(i);
if (schema.getName().equalsIgnoreCase(name)) return schema;
}
return null;
}
/**
* Find a clustering schema using its name
* @param name The name of the clustering schema to look for.
* @return the cluster schema with the specified name of null if nothing was found
*/
public ClusterSchema findClusterSchema(String name)
{
for (int i=0;i<clusterSchemas.size();i++)
{
ClusterSchema schema = clusterSchemas.get(i);
if (schema.getName().equalsIgnoreCase(name)) return schema;
}
return null;
}
/**
* Add a new partition schema to the transformation if that didn't exist yet.
* Otherwise, replace it.
*
* @param partitionSchema The partition schema to be added.
*/
public void addOrReplacePartitionSchema(PartitionSchema partitionSchema)
{
int index = partitionSchemas.indexOf(partitionSchema);
if (index<0)
{
partitionSchemas.add(partitionSchema);
}
else
{
PartitionSchema previous = partitionSchemas.get(index);
previous.replaceMeta(partitionSchema);
}
setChanged();
}
/**
* Add a new slave server to the transformation if that didn't exist yet.
* Otherwise, replace it.
*
* @param slaveServer The slave server to be added.
*/
public void addOrReplaceSlaveServer(SlaveServer slaveServer)
{
int index = slaveServers.indexOf(slaveServer);
if (index<0)
{
slaveServers.add(slaveServer);
}
else
{
SlaveServer previous = slaveServers.get(index);
previous.replaceMeta(slaveServer);
}
setChanged();
}
/**
* Add a new cluster schema to the transformation if that didn't exist yet.
* Otherwise, replace it.
*
* @param clusterSchema The cluster schema to be added.
*/
public void addOrReplaceClusterSchema(ClusterSchema clusterSchema)
{
int index = clusterSchemas.indexOf(clusterSchema);
if (index<0)
{
clusterSchemas.add(clusterSchema);
}
else
{
ClusterSchema previous = clusterSchemas.get(index);
previous.replaceMeta(clusterSchema);
}
setChanged();
}
public String getSharedObjectsFile()
{
return sharedObjectsFile;
}
public void setSharedObjectsFile(String sharedObjectsFile)
{
this.sharedObjectsFile = sharedObjectsFile;
}
public boolean saveSharedObjects()
{
try
{
// First load all the shared objects...
String soFile = environmentSubstitute(sharedObjectsFile);
SharedObjects sharedObjects = new SharedObjects(soFile);
// Now overwrite the objects in there
List<SharedObjectInterface> shared = new ArrayList<SharedObjectInterface>();
shared.addAll(databases);
shared.addAll(steps);
shared.addAll(partitionSchemas);
shared.addAll(slaveServers);
shared.addAll(clusterSchemas);
// The databases connections...
for (SharedObjectInterface sharedObject : shared )
{
if (sharedObject.isShared())
{
sharedObjects.storeObject(sharedObject);
}
}
// Save the objects
sharedObjects.saveToFile();
return true;
}
catch(Exception e)
{
log.logError(toString(), "Unable to save shared ojects: "+e.toString());
return false;
}
}
/**
* @return the usingThreadPriorityManagment
*/
public boolean isUsingThreadPriorityManagment()
{
return usingThreadPriorityManagment;
}
/**
* @param usingThreadPriorityManagment the usingThreadPriorityManagment to set
*/
public void setUsingThreadPriorityManagment(boolean usingThreadPriorityManagment)
{
this.usingThreadPriorityManagment = usingThreadPriorityManagment;
}
public SlaveServer findSlaveServer(String serverString)
{
return SlaveServer.findSlaveServer(slaveServers, serverString);
}
public String[] getSlaveServerNames()
{
return SlaveServer.getSlaveServerNames(slaveServers);
}
/**
* @return the slaveServers
*/
public List<SlaveServer> getSlaveServers()
{
return slaveServers;
}
/**
* @param slaveServers the slaveServers to set
*/
public void setSlaveServers(List<SlaveServer> slaveServers)
{
this.slaveServers = slaveServers;
}
/**
* @return the rejectedStep
*/
public StepMeta getRejectedStep()
{
return rejectedStep;
}
/**
* @param rejectedStep the rejectedStep to set
*/
public void setRejectedStep(StepMeta rejectedStep)
{
this.rejectedStep = rejectedStep;
}
/**
* Check a step to see if there are no multiple steps to read from.
* If so, check to see if the receiving rows are all the same in layout.
* We only want to ONLY use the DBCache for this to prevent GUI stalls.
*
* @param stepMeta the step to check
* @throws KettleRowException in case we detect a row mixing violation
*
*/
public void checkRowMixingStatically(StepMeta stepMeta, IProgressMonitor monitor) throws KettleRowException
{
int nrPrevious = findNrPrevSteps(stepMeta);
if (nrPrevious>1)
{
RowMetaInterface referenceRow = null;
// See if all previous steps send out the same rows...
for (int i=0;i<nrPrevious;i++)
{
StepMeta previousStep = findPrevStep(stepMeta, i);
try
{
RowMetaInterface row = getStepFields(previousStep, monitor); // Throws KettleStepException
if (referenceRow==null)
{
referenceRow = row;
}
else
{
if ( ! stepMeta.getStepMetaInterface().excludeFromRowLayoutVerification())
{
BaseStep.safeModeChecking(referenceRow, row);
}
}
}
catch(KettleStepException e)
{
// We ignore this one because we are in the process of designing the transformation, anything intermediate can go wrong.
}
}
}
}
public void setInternalKettleVariables()
{
setInternalKettleVariables(variables);
}
public void setInternalKettleVariables(VariableSpace var)
{
if (!Const.isEmpty(filename)) // we have a finename that's defined.
{
try
{
FileObject fileObject = KettleVFS.getFileObject(filename);
FileName fileName = fileObject.getName();
// The filename of the transformation
var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, fileName.getBaseName());
// The directory of the transformation
FileName fileDir = fileName.getParent();
var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, fileDir.getURI());
}
catch(IOException e)
{
var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, "");
var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, "");
}
}
else
{
var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, "");
var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, "");
}
// The name of the transformation
var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_NAME, Const.NVL(name, ""));
// The name of the directory in the repository
var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY, directory!=null?directory.getPath():"");
// Here we don't remove the job specific parameters, as they may come in handy.
if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY)==null)
{
var.setVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY, "Parent Job File Directory"); //$NON-NLS-1$
}
if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME)==null)
{
var.setVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME, "Parent Job Filename"); //$NON-NLS-1$
}
if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_NAME)==null)
{
var.setVariable(Const.INTERNAL_VARIABLE_JOB_NAME, "Parent Job Name"); //$NON-NLS-1$
}
if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY)==null)
{
var.setVariable(Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY, "Parent Job Repository Directory"); //$NON-NLS-1$
}
}
public void copyVariablesFrom(VariableSpace space) {
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
public StepMeta findMappingInputStep(String stepname) throws KettleStepException {
if (!Const.isEmpty(stepname)) {
StepMeta stepMeta = findStep(stepname); // TODO verify that it's a mapping input!!
if (stepMeta==null) {
throw new KettleStepException(Messages.getString("TransMeta.Exception.StepNameNotFound", stepname));
}
return stepMeta;
}
else {
// Find the first mapping input step that fits the bill.
StepMeta stepMeta = null;
for (StepMeta mappingStep : steps) {
if (mappingStep.getStepID().equals("MappingInput")) {
if (stepMeta==null) {
stepMeta = mappingStep;
}
else if (stepMeta!=null) {
throw new KettleStepException(Messages.getString("TransMeta.Exception.OnlyOneMappingInputStepAllowed", "2"));
}
}
}
if (stepMeta==null) {
throw new KettleStepException(Messages.getString("TransMeta.Exception.OneMappingInputStepRequired"));
}
return stepMeta;
}
}
public StepMeta findMappingOutputStep(String stepname) throws KettleStepException {
if (!Const.isEmpty(stepname)) {
StepMeta stepMeta = findStep(stepname); // TODO verify that it's a mapping output step.
if (stepMeta==null) {
throw new KettleStepException(Messages.getString("TransMeta.Exception.StepNameNotFound", stepname));
}
return stepMeta;
}
else {
// Find the first mapping output step that fits the bill.
StepMeta stepMeta = null;
for (StepMeta mappingStep : steps) {
if (mappingStep.getStepID().equals("MappingOutput")) {
if (stepMeta==null) {
stepMeta = mappingStep;
}
else if (stepMeta!=null) {
throw new KettleStepException(Messages.getString("TransMeta.Exception.OnlyOneMappingOutputStepAllowed", "2"));
}
}
}
if (stepMeta==null) {
throw new KettleStepException(Messages.getString("TransMeta.Exception.OneMappingOutputStepRequired"));
}
return stepMeta;
}
}
public List<ResourceReference> getResourceDependencies() {
List<ResourceReference> resourceReferences = new ArrayList<ResourceReference>();
for (StepMeta stepMeta : steps) {
resourceReferences.addAll( stepMeta.getResourceDependencies(this) );
}
return resourceReferences;
}
public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface resourceNamingInterface) throws KettleException {
try {
FileObject fileObject = KettleVFS.getFileObject(getFilename());
String exportFileName = resourceNamingInterface.nameResource(fileObject.getName().getBaseName(), fileObject.getParent().getName().getPath(), "ktr"); //$NON-NLS-1$
ResourceDefinition definition = definitions.get(exportFileName);
if (definition==null) {
// If we do this once, it will be plenty :-)
TransMeta transMeta = (TransMeta) this.realClone(false);
// transMeta.copyVariablesFrom(space);
// Add used resources, modify transMeta accordingly
// Go through the list of steps, etc.
// These critters change the steps in the cloned TransMeta
// At the end we make a new XML version of it in "exported" format...
// loop over steps, databases will be exported to XML anyway.
for (StepMeta stepMeta : transMeta.getSteps()) {
stepMeta.exportResources(space, definitions, resourceNamingInterface);
}
// Change the filename, calling this sets internal variables inside of the transformation.
transMeta.setFilename(exportFileName);
// At the end, add ourselves to the map...
String transMetaContent = transMeta.getXML();
definition = new ResourceDefinition(exportFileName, transMetaContent);
definitions.put(fileObject.getName().getPath(), definition);
}
return exportFileName;
} catch (FileSystemException e) {
throw new KettleException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", getFilename()), e); //$NON-NLS-1$
} catch (IOException e) {
throw new KettleException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", getFilename()), e); //$NON-NLS-1$
}
}
/**
* @return the slaveStepCopyPartitionDistribution
*/
public SlaveStepCopyPartitionDistribution getSlaveStepCopyPartitionDistribution() {
return slaveStepCopyPartitionDistribution;
}
/**
* @param slaveStepCopyPartitionDistribution the slaveStepCopyPartitionDistribution to set
*/
public void setSlaveStepCopyPartitionDistribution(SlaveStepCopyPartitionDistribution slaveStepCopyPartitionDistribution) {
this.slaveStepCopyPartitionDistribution = slaveStepCopyPartitionDistribution;
}
public boolean isUsingAtLeastOneClusterSchema() {
for (StepMeta stepMeta : steps) {
if (stepMeta.getClusterSchema()!=null) return true;
}
return false;
}
public boolean isSlaveTransformation() {
return slaveTransformation;
}
public void setSlaveTransformation(boolean slaveTransformation) {
this.slaveTransformation = slaveTransformation;
}
/**
* @return the repository
*/
public Repository getRepository() {
return repository;
}
/**
* @param repository the repository to set
*/
public void setRepository(Repository repository) {
this.repository = repository;
}
} |
package org.team2168.commands;
import edu.wpi.first.wpilibj.command.Command;
public class HoodDown extends CommandBase {
public void HoodDown(){
requires(shooter);
}
protected void initialize() {
}
protected void execute() {
shooter.hoodDown();
}
protected boolean isFinished() {
return true;
}
protected void end() {
}
protected void interrupted() {
}
} |
package net.hyperic.sigar.win32;
import java.util.Arrays;
import java.util.List;
public class Service extends Win32 {
// Service State
public static final int SERVICE_STOPPED = 0x00000001;
public static final int SERVICE_START_PENDING = 0x00000002;
public static final int SERVICE_STOP_PENDING = 0x00000003;
public static final int SERVICE_RUNNING = 0x00000004;
public static final int SERVICE_CONTINUE_PENDING = 0x00000005;
public static final int SERVICE_PAUSE_PENDING = 0x00000006;
public static final int SERVICE_PAUSED = 0x00000007;
private static final String[] STATUS = {
"Unknown",
"Stopped",
"Start Pending",
"Stop Pending",
"Running",
"Continue Pending",
"Pause Pending",
"Paused"
};
// Service Controls
private static final int SERVICE_CONTROL_STOP = 0x00000001;
private static final int SERVICE_CONTROL_PAUSE = 0x00000002;
private static final int SERVICE_CONTROL_CONTINUE = 0x00000003;
private static final int SERVICE_CONTROL_INTERROGATE = 0x00000004;
private static final int SERVICE_CONTROL_SHUTDOWN = 0x00000005;
private static final int SERVICE_CONTROL_PARAMCHANGE = 0x00000006;
private static final int SERVICE_CONTROL_NETBINDADD = 0x00000007;
private static final int SERVICE_CONTROL_NETBINDREMOVE = 0x00000008;
private static final int SERVICE_CONTROL_NETBINDENABLE = 0x00000009;
private static final int SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A;
private static final int SERVICE_CONTROL_DEVICEEVENT = 0x0000000B;
private static final int SERVICE_CONTROL_HARDWAREPROFILECHANGE
= 0x0000000C;
private static final int SERVICE_CONTROL_POWEREVENT = 0x0000000D;
private static final int SERVICE_CONTROL_SESSIONCHANGE = 0x0000000E;
// Service Control Manager object specific access types
private static final int STANDARD_RIGHTS_REQUIRED = (int)0x000F0000L;
private static final int SC_MANAGER_CONNECT = 0x0001;
private static final int SC_MANAGER_CREATE_SERVICE = 0x0002;
private static final int SC_MANAGER_ENUMERATE_SERVICE = 0x0004;
private static final int SC_MANAGER_LOCK = 0x0008;
private static final int SC_MANAGER_QUERY_LOCK_STATUS = 0x0010;
private static final int SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020;
private static final int SC_MANAGER_ALL_ACCESS =
(STANDARD_RIGHTS_REQUIRED |
SC_MANAGER_CONNECT |
SC_MANAGER_CREATE_SERVICE |
SC_MANAGER_ENUMERATE_SERVICE |
SC_MANAGER_LOCK |
SC_MANAGER_QUERY_LOCK_STATUS |
SC_MANAGER_MODIFY_BOOT_CONFIG);
// Service object specific access type
private static final int SERVICE_QUERY_CONFIG = 0x0001;
private static final int SERVICE_CHANGE_CONFIG = 0x0002;
private static final int SERVICE_QUERY_STATUS = 0x0004;
private static final int SERVICE_ENUMERATE_DEPENDENTS = 0x0008;
private static final int SERVICE_START = 0x0010;
private static final int SERVICE_STOP = 0x0020;
private static final int SERVICE_PAUSE_CONTINUE = 0x0040;
private static final int SERVICE_INTERROGATE = 0x0080;
private static final int SERVICE_USER_DEFINED_CONTROL = 0x0100;
private static final int SERVICE_ALL_ACCESS =
(STANDARD_RIGHTS_REQUIRED |
SERVICE_QUERY_CONFIG |
SERVICE_CHANGE_CONFIG |
SERVICE_QUERY_STATUS |
SERVICE_ENUMERATE_DEPENDENTS |
SERVICE_START |
SERVICE_STOP |
SERVICE_PAUSE_CONTINUE |
SERVICE_INTERROGATE |
SERVICE_USER_DEFINED_CONTROL);
private long manager;
private long service;
private String name;
private Service() throws Win32Exception
{
this.manager = OpenSCManager("", SC_MANAGER_ALL_ACCESS);
if (this.manager == 0) {
throw getLastErrorException();
}
}
public static native List getServiceNames() throws Win32Exception;
public Service(String serviceName) throws Win32Exception
{
this();
this.service = OpenService(this.manager, serviceName,
SERVICE_ALL_ACCESS);
if (this.service == 0) {
throw getLastErrorException();
}
this.name = serviceName;
}
protected void finalize()
{
close();
}
public synchronized void close()
{
if (this.service != 0) {
CloseServiceHandle(this.service);
this.service = 0;
}
if (this.manager != 0) {
CloseServiceHandle(this.manager);
this.manager = 0;
}
}
public static Service create(ServiceConfig config)
throws Win32Exception
{
if (config.getName() == null) {
throw new IllegalArgumentException("name=null");
}
if (config.getPath() == null) {
throw new IllegalArgumentException("path=null");
}
Service service = new Service();
service.service =
CreateService(service.manager,
config.getName(),
config.getDisplayName(),
config.getType(),
config.getStartType(),
config.getErrorControl(),
config.getPath(),
config.getDependencies(),
config.getServiceStartName(),
config.getPassword());
if (service.service == 0) {
throw getLastErrorException();
}
if (config.getDescription() != null) {
service.setDescription(config.getDescription());
}
return service;
}
public void delete() throws Win32Exception
{
DeleteService(this.service);
}
public void control(int control)
throws Win32Exception
{
if (!ControlService(this.service, control)) {
throw getLastErrorException();
}
}
public void setDescription(String description)
{
ChangeServiceDescription(this.service, description);
}
/**
* @deprecated
* @see #getStatus()
*/
public int status()
{
return getStatus();
}
public int getStatus()
{
return QueryServiceStatus(this.service);
}
public String getStatusString()
{
return STATUS[getStatus()];
}
public void stop() throws Win32Exception
{
if (StopService(this.service) == false) {
throw getLastErrorException();
}
}
private static class Waiter {
long start = System.currentTimeMillis();
Service service;
long timeout;
int wantedState;
int pendingState;
Waiter(Service service,
long timeout,
int wantedState,
int pendingState)
{
this.service = service;
this.timeout = timeout;
this.wantedState = wantedState;
this.pendingState = pendingState;
}
boolean sleep() {
int status;
while ((status = service.getStatus()) != this.wantedState) {
if (status != this.pendingState) {
return false;
}
if ((timeout <= 0) ||
((System.currentTimeMillis() - this.start) < this.timeout))
{
try {
Thread.sleep(100);
} catch(InterruptedException e) {}
}
else {
break;
}
}
return status == this.wantedState;
}
}
public void stop(long timeout) throws Win32Exception
{
long status;
stop();
Waiter waiter =
new Waiter(this, timeout, SERVICE_STOPPED, SERVICE_STOP_PENDING);
if (!waiter.sleep()) {
throw new Win32Exception("Failed to stop service");
}
}
public void start() throws Win32Exception
{
if (StartService(this.service) == false) {
throw getLastErrorException();
}
}
public void start(long timeout) throws Win32Exception
{
long status;
start();
Waiter waiter =
new Waiter(this, timeout, SERVICE_RUNNING, SERVICE_START_PENDING);
if (!waiter.sleep()) {
throw new Win32Exception("Failed to start service");
}
}
public ServiceConfig getConfig() throws Win32Exception {
ServiceConfig config = new ServiceConfig();
if (!QueryServiceConfig(this.service, config)) {
throw getLastErrorException();
}
config.setName(this.name);
return config;
}
private static Win32Exception getLastErrorException()
{
int err = GetLastError();
return new Win32Exception(err, "Win32 Error Code: " +
err + ": " + GetErrorMessage(err));
}
private static native boolean ChangeServiceDescription(long handle,
String description);
private static native boolean CloseServiceHandle(long handle);
private static native long CreateService(long handle,
String serviceName,
String displayName,
int serviceType,
int startType,
int errorControl,
String path,
String[] dependencies,
String startName,
String password);
private static native boolean ControlService(long handle,
int control);
private static native boolean DeleteService(long handle);
private static native long OpenSCManager(String machine,
int access);
private static native long OpenService(long handle,
String service,
int access);
private static native int QueryServiceStatus(long handle);
private static native boolean StartService(long handle);
private static native boolean StopService(long handle);
private static native boolean QueryServiceConfig(long handle,
ServiceConfig config);
public static void main(String[] args) throws Exception {
List services;
if (args.length == 0) {
services = getServiceNames();
}
else if ((args.length == 2) && (args[0].equals("-toggle"))) {
long timeout = 5 * 1000; //5 seconds
Service service = new Service(args[1]);
if (service.getStatus() == SERVICE_RUNNING) {
System.out.println("Stopping service...");
service.stop(timeout);
}
else {
System.out.println("Starting service...");
service.start(timeout);
}
System.out.println(service.getStatusString());
return;
}
else {
services = Arrays.asList(args);
}
for (int i=0; i<services.size(); i++) {
String name = (String)services.get(i);
Service service = new Service(name);
service.getConfig().list(System.out);
System.out.println("status........[" +
service.getStatusString() + "]");
System.out.println("");
}
}
} |
package com.civica.grads.boardgames.model;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import org.junit.Ignore;
import org.junit.Test;
import com.civica.grads.boardgames.interfaces.Move;
import com.civica.grads.boardgames.model.Board;
import com.civica.grads.boardgames.model.BoardTile;
import com.civica.grads.boardgames.model.Counter;
public class BoardTest {
//FIXME: This test fails
@Test
public void toStringOutputExpectedText() {
Board board = new Board(8);
String expected = "Board [size=8, tiles=[[Lcom.civica.grads.exercise3.model.draughts.BoardTile;@6e5e91e4,"
+ " [Lcom.civica.grads.exercise3.model.draughts.BoardTile;@2cdf8d8a, "
+ "[Lcom.civica.grads.exercise3.model.draughts.BoardTile;@30946e09, "
+ "[Lcom.civica.grads.exercise3.model.draughts.BoardTile;@5cb0d902, "
+ "[Lcom.civica.grads.exercise3.model.draughts.BoardTile;@46fbb2c1,"
+ " [Lcom.civica.grads.exercise3.model.draughts.BoardTile;@1698c449,"
+ " [Lcom.civica.grads.exercise3.model.draughts.BoardTile;@5ef04b5,"
+ " [Lcom.civica.grads.exercise3.model.draughts.BoardTile;@5f4da5c3],"
+ " whiteCounters=[], blackCounters=[]]";
String actual = board.toString();
assertEquals(expected, actual);
}
@Test
public void getSizeExpectedValue() {
Board board = new Board(8);
int expected = 8;
int actual = board.getSize();
assertEquals(expected, actual);
}
@Test
@Ignore
public void getTilesExpectedValue() {
// Board board = new Board(8);
// BoardTile[][] expected = new BoardTile[8][8];
// BoardTile[][] actual = board.getTiles();
// assertArrayEquals(expected, actual);
}
@Test
public void getWhiteCountersExpectedValue() {
Board board = new Board(8);
ArrayList<Counter> expected = new ArrayList<>();
ArrayList<Counter> actual = board.getWhiteCounters();
assertEquals(expected, actual);
}
@Test
public void getBlackCountersExpectedValue() {
Board board = new Board(8);
ArrayList<Counter> expected = new ArrayList<>();
ArrayList<Counter> actual = board.getBlackCounters();
assertEquals(expected, actual);
}
@Test (expected = MoveException.class) //TODO: import moveexception when it's been implemented
public void invalidHorizontalMoveDenied() {
Position p1 = mock(Position.class);
when(p1.getX()).thenReturn(0);
when(p1.getY()).thenReturn(0);
Position p2 = mock(Position.class);
when(p2.getX()).thenReturn(0);
when(p2.getY()).thenReturn(0);
Move move = mock(Move.class);
when(move.getPositionStart()).thenReturn(p1);
when(move.getPositionFinish()).thenReturn(p2);
Board board = new Board(8);//TODO: replace with test data
board.applyMove(move);
}
} |
package com.valkryst.VTerminal.component;
import com.valkryst.VTerminal.AsciiCharacter;
import com.valkryst.VTerminal.AsciiString;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Optional;
public class ScreenTest {
private Screen screen;
private final AsciiCharacter character = new AsciiCharacter('?');
private final AsciiString string = new AsciiString("?????");
@Before
public void initalizeScreen() {
screen = new Screen(0, 0, 5, 5);
}
@Test
public void testConstructor_withValidParams() {
final Screen screen = new Screen(4, 6, 9, 10);
Assert.assertEquals(4, screen.getColumnIndex());
Assert.assertEquals(6, screen.getRowIndex());
Assert.assertEquals(9, screen.getWidth());
Assert.assertEquals(10, screen.getHeight());
}
@Test(expected=IllegalArgumentException.class)
public void testConstructor_withNegativeColumnIndex() {
new Screen(-1, 6, 9, 10);
}
@Test(expected=IllegalArgumentException.class)
public void testConstructor_withNegativeRowIndex() {
new Screen(4, -1, 9, 10);
}
@Test(expected=IllegalArgumentException.class)
public void testConstructor_withNegativeWidth() {
new Screen(4, 6, -1, 10);
}
@Test(expected=IllegalArgumentException.class)
public void testConstructor_withNegativeHeight() {
new Screen(4, 6, 9, -1);
}
@Test(expected=UnsupportedOperationException.class)
public void testDraw_screen() {
screen.draw(screen);
}
@Test
public void testClear_oneParam() {
screen.clear('?');
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertEquals('?', character.getCharacter());
}
}
}
@Test
public void testClear_multipleParams_withValidParams() {
screen.clear('?', 2, 2, 2, 2);
for (int y = 0 ; y < screen.getStrings().length ; y++) {
for (int x = 0 ; x < screen.getStrings()[y].getCharacters().length ; x++) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(x, y);
Assert.assertTrue(optChar.isPresent());
if (x == 2 || x == 3) {
if (y == 2 || y == 3) {
Assert.assertEquals('?', optChar.get().getCharacter());
continue;
}
}
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
}
}
@Test
public void testClear_multipleParams_withNegativeColumnIndex() {
screen.clear('?', -1, 2, 2, 2);
for (int y = 0 ; y < screen.getStrings().length ; y++) {
for (int x = 0 ; x < screen.getStrings()[y].getCharacters().length ; x++) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(x, y);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
}
}
@Test
public void testClear_multipleParams_withNegativeRowIndex() {
screen.clear('?', 2, -1, 2, 2);
for (int y = 0 ; y < screen.getStrings().length ; y++) {
for (int x = 0 ; x < screen.getStrings()[y].getCharacters().length ; x++) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(x, y);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
}
}
@Test
public void testClear_multipleParams_withNegativeWidth() {
screen.clear('?', 2, 2, -1, 2);
for (int y = 0 ; y < screen.getStrings().length ; y++) {
for (int x = 0 ; x < screen.getStrings()[y].getCharacters().length ; x++) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(x, y);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
}
}
@Test
public void testClear_multipleParams_withNegativeHeight() {
screen.clear('?', 2, 2, 2, -1);
for (int y = 0 ; y < screen.getStrings().length ; y++) {
for (int x = 0 ; x < screen.getStrings()[y].getCharacters().length ; x++) {
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(x, y);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
}
}
@Test
public void testWrite_charObj_withValidParams() {
screen.write(character, 3, 3);
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(3, 3);
Assert.assertTrue(optChar.isPresent());
Assert.assertEquals('?', optChar.get().getCharacter());
}
@Test
public void testWrite_charObj_allCharPositions() {
for (int y = 0 ; y < screen.getHeight() ; y++) {
for (int x = 0 ; x < screen.getWidth() ; x++) {
screen.write(character, x, y);
}
}
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter chr : string.getCharacters()) {
Assert.assertEquals('?', chr.getCharacter());
}
}
}
@Test
public void testWrite_charObj_withNullCharacter() {
screen.write((AsciiCharacter) null, 3, 3);
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(3, 3);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
@Test
public void testWrite_charObj_withNegativeColumnIndex() {
screen.write(character, -3, 3);
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(3, 3);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
@Test
public void testWrite_charObj_withNegativeRowIndex() {
screen.write(character, 3, -3);
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(3, 3);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
@Test
public void testWrite_charPrim_withValidParams() {
screen.write('?', 3, 3);
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(3, 3);
Assert.assertTrue(optChar.isPresent());
Assert.assertEquals('?', optChar.get().getCharacter());
}
@Test
public void testWrite_charPrim_allCharPositions() {
for (int y = 0 ; y < screen.getHeight() ; y++) {
for (int x = 0 ; x < screen.getWidth() ; x++) {
screen.write('?', x, y);
}
}
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertEquals('?', character.getCharacter());
}
}
}
@Test
public void testWrite_charPrim_withNegativeColumnIndex() {
screen.write('?', -3, 3);
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(3, 3);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
@Test
public void testWrite_charPrim_withNegativeRowIndex() {
screen.write('?', 3, -3);
final Optional<AsciiCharacter> optChar = screen.getCharacterAt(3, 3);
Assert.assertTrue(optChar.isPresent());
Assert.assertNotEquals('?', optChar.get().getCharacter());
}
@Test
public void testWrite_stringObj_withValidParams() {
screen.write(string, 0, 0);
Assert.assertEquals(string, screen.getStrings()[0]);
}
@Test
public void testWrite_stringObj_allCharPositions() {
for (int y = 0 ; y < screen.getHeight() ; y++) {
screen.write(string, 0, y);
Assert.assertEquals(string, screen.getStrings()[y]);
}
}
@Test
public void testWrite_stringObj_withNullString() {
screen.write((AsciiString) null, 0, 0);
Assert.assertNotEquals(string, screen.getStrings()[0]);
}
@Test
public void testWrite_stringObj_withNegativeColumnIndex() {
screen.write(string, -3, 3);
Assert.assertNotEquals(string, screen.getStrings()[0]);
}
@Test
public void testWrite_stringObj_withNegativeRowIndex() {
screen.write(string, 3, -3);
Assert.assertNotEquals(string, screen.getStrings()[0]);
}
@Test
public void testSetBackgroundColor_withValidColor() {
screen.setBackgroundColor(Color.PINK);
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertEquals(Color.PINK, character.getBackgroundColor());
}
}
}
@Test
public void testSetBackgroundColor_withNullColor() {
screen.setBackgroundColor(null);
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertNotEquals(Color.PINK, character.getBackgroundColor());
}
}
}
@Test
public void testSetForegroundColor_withValidColor() {
screen.setForegroundColor(Color.PINK);
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertEquals(Color.PINK, character.getForegroundColor());
}
}
}
@Test
public void testSetForegroundColor_withNullColor() {
screen.setForegroundColor(null);
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertNotEquals(Color.PINK, character.getForegroundColor());
}
}
}
@Test
public void testSetBackgroundAndForegroundColor_withValidColors() {
screen.setBackgroundAndForegroundColor(Color.PINK, Color.GREEN);
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertEquals(Color.PINK, character.getBackgroundColor());
Assert.assertEquals(Color.GREEN, character.getForegroundColor());
}
}
}
@Test
public void testSetBackgroundAndForegroundColor_withNullBackgroundColor() {
screen.setBackgroundAndForegroundColor(null, Color.GREEN);
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertNotEquals(Color.PINK, character.getBackgroundColor());
Assert.assertNotEquals(Color.GREEN, character.getForegroundColor());
}
}
}
@Test
public void testSetBackgroundAndForegroundColor_withNullForegroundColor() {
screen.setBackgroundAndForegroundColor(Color.PINK, null);
for (final AsciiString string : screen.getStrings()) {
for (final AsciiCharacter character : string.getCharacters()) {
Assert.assertNotEquals(Color.PINK, character.getBackgroundColor());
Assert.assertNotEquals(Color.GREEN, character.getForegroundColor());
}
}
}
@Test
public void testAddComponent_withValidComponent() {
final Layer otherComponent = new Layer(0, 0, 2, 2);
screen.addComponent(otherComponent);
Assert.assertTrue(screen.containsComponent(otherComponent));
}
@Test
public void testAddComponent_withNullComponent() {
screen.addComponent(null);
Assert.assertEquals(0, screen.totalComponents());
}
@Test
public void testAddComponent_withSelf() {
screen.addComponent(screen);
Assert.assertEquals(0, screen.totalComponents());
}
@Test
public void testAddComponent_addSameComponentTwice() {
final Layer otherComponent = new Layer(0, 0, 2, 2);
screen.addComponent(otherComponent);
screen.addComponent(otherComponent);
Assert.assertTrue(screen.containsComponent(otherComponent));
Assert.assertEquals(1, screen.totalComponents());
}
@Test
public void testRemoveComponent_withValidComponent() {
final Layer otherComponent = new Layer(0, 0, 2, 2);
screen.addComponent(otherComponent);
Assert.assertTrue(screen.containsComponent(otherComponent));
Assert.assertEquals(1, screen.totalComponents());
screen.removeComponent(otherComponent);
Assert.assertFalse(screen.containsComponent(otherComponent));
Assert.assertEquals(0, screen.totalComponents());
}
@Test
public void testRemoveComponent_withNullComponent() {
final Layer otherComponent = new Layer(0, 0, 2, 2);
screen.addComponent(otherComponent);
Assert.assertTrue(screen.containsComponent(otherComponent));
Assert.assertEquals(1, screen.totalComponents());
screen.removeComponent(null);
Assert.assertTrue(screen.containsComponent(otherComponent));
Assert.assertEquals(1, screen.totalComponents());
}
@Test
public void testRemoveComponent_withSelf() {
final Layer otherComponent = new Layer(0, 0, 2, 2);
screen.addComponent(otherComponent);
Assert.assertTrue(screen.containsComponent(otherComponent));
Assert.assertEquals(1, screen.totalComponents());
screen.removeComponent(screen);
Assert.assertTrue(screen.containsComponent(otherComponent));
Assert.assertEquals(1, screen.totalComponents());
}
} |
package com.baidu.cafe.local;
import java.util.ArrayList;
import android.os.Build;
/**
* @author luxiaoyu01@baidu.com
* @date 2012-11-21
* @version
* @todo
*/
public class NetworkUtils {
private final static String MODE_RCV = "tcp_rcv";
private final static String MODE_SND = "tcp_snd";
private final static String[] NETWORK_CARD_TYPES = new String[] { "eth0:", "wlan0:", "tiwlan0:", "svnet0:",
"rmnet0:", "mlan0:" };
public NetworkUtils() {
}
private static void print(String message) {
if (Log.IS_DEBUG && message != null) {
Log.i("NetworkUtils", message);
}
}
public static int getUidByPid(int pid) {
int uid = -1;
try {
ArrayList<String> uidString = new ShellExecute().execute(String.format("cat /proc/%s/status", pid), "/").console
.grep("Uid").strings;
uid = Integer.valueOf(uidString.get(0).split("\t")[1]);
} catch (Exception e) {
print("Get uid failed!");
e.printStackTrace();
}
return uid;
}
public static ArrayList<Integer> getPidsByPackageName(String packageName) {
ArrayList<Integer> pids = new ArrayList<Integer>();
ArrayList<String> pidStrings = new ShellExecute().execute("ps", "/").console.grep(packageName).getRow(
"\\s{1,}", 2).strings;
for (String pid : pidStrings) {
pids.add(Integer.valueOf(pid));
}
return pids;
}
/**
* invoked 100 times costs 4800ms on Nexus One
*
* @param packageName
* @param mode
* @return
*/
private static int getPackageTraffic(String packageName, String mode) {
if ((!MODE_RCV.equals(mode)) && (!MODE_SND.equals(mode))) {
print("mode invaild:" + mode);
return -1;
}
int traffic = 0;
ArrayList<Integer> pids = getPidsByPackageName(packageName);
if (pids.size() < 1) {
print("pids.size() < 1");
return -1;
}
int pid = pids.get(0);
if (Build.VERSION.SDK_INT >= 14) {// API Level: 14. Android 4.0
int uid = getUidByPid(pid);
if (-1 == uid) {
print("-1 == uid");
return -1;
}
String ret = new ShellExecute().execute(String.format("cat /proc/uid_stat/%s/%s", uid, mode), "/").console.strings
.get(0);
traffic = Integer.valueOf(ret);
} else {
Strings netString = new ShellExecute().execute(String.format("cat /proc/%s/net/dev", pid), "/").console;
int rcv = 0;
int snd = 0;
for (String networkCard : NETWORK_CARD_TYPES) {
Strings netLine = netString.grep(networkCard);
if (netLine.strings.size() != 1) {
continue;
}
rcv += Integer.valueOf(netLine.getRow("\\s{1,}", 2).strings.get(0));
snd += Integer.valueOf(netLine.getRow("\\s{1,}", 10).strings.get(0));
}
if (MODE_RCV.equals(mode)) {
traffic = rcv;
} else if (MODE_SND.equals(mode)) {
traffic = snd;
}
}
return traffic;
}
public static int getPackageRcv(String packageName) {
return getPackageTraffic(packageName, MODE_RCV);
}
public static int getPackageSnd(String packageName) {
return getPackageTraffic(packageName, MODE_SND);
}
} |
package com.ecyrd.jspwiki.plugin;
import com.ecyrd.jspwiki.*;
import junit.framework.*;
import java.io.*;
import java.util.*;
public class PluginManagerTest extends TestCase
{
public static final String NAME1 = "Test1";
Properties props = new Properties();
WikiEngine engine;
WikiContext context;
PluginManager manager;
public PluginManagerTest( String s )
{
super( s );
}
public void setUp()
throws Exception
{
props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") );
engine = new TestEngine2(props);
context = new WikiContext( engine, "testpage" );
manager = new PluginManager( props );
}
public void tearDown()
{
}
public void testSimpleInsert()
throws Exception
{
String res = manager.execute( context,
"{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text=foobar}");
assertEquals( "foobar",
res );
}
public void testSimpleInsertNoPackage()
throws Exception
{
String res = manager.execute( context,
"{INSERT SamplePlugin WHERE text=foobar}");
assertEquals( "foobar",
res );
}
public void testSimpleInsertNoPackage2()
throws Exception
{
props.setProperty( PluginManager.PROP_SEARCHPATH, "com.foo" );
PluginManager m = new PluginManager( props );
String res = m.execute( context,
"{INSERT SamplePlugin2 WHERE text=foobar}");
assertEquals( "foobar",
res );
}
public void testSimpleInsertNoPackage3()
throws Exception
{
props.setProperty( PluginManager.PROP_SEARCHPATH, "com.foo" );
PluginManager m = new PluginManager( props );
String res = m.execute( context,
"{INSERT SamplePlugin3 WHERE text=foobar}");
assertEquals( "foobar",
res );
}
/** Check that in all cases com.ecyrd.jspwiki.plugin is searched. */
public void testSimpleInsertNoPackage4()
throws Exception
{
props.setProperty( PluginManager.PROP_SEARCHPATH, "com.foo,blat.blaa" );
PluginManager m = new PluginManager( props );
String res = m.execute( context,
"{INSERT SamplePlugin WHERE text=foobar}");
assertEquals( "foobar",
res );
}
public void testSimpleInsert2()
throws Exception
{
String res = manager.execute( context,
"{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text = foobar2, moo=blat}");
assertEquals( "foobar2",
res );
}
/** Missing closing brace */
public void testSimpleInsert3()
throws Exception
{
String res = manager.execute( context,
"{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text = foobar2, moo=blat");
assertEquals( "foobar2",
res );
}
public void testQuotedArgs()
throws Exception
{
String res = manager.execute( context,
"{INSERT SamplePlugin WHERE text='this is a space'}");
assertEquals( "this is a space",
res );
}
public void testNumberArgs()
throws Exception
{
String res = manager.execute( context,
"{INSERT SamplePlugin WHERE text=15}");
assertEquals( "15",
res );
}
public static Test suite()
{
return new TestSuite( PluginManagerTest.class );
}
} |
package networking;
import exceptions.NotInitializedVariablesException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
/**
*
*@author Ntanasis Periklis and Chatzipetros Mike
*/
public class MulticastReceiver extends Multicast{
/*
* constructor
*/
MulticastReceiver()
{
super();
}
/*
* constructor
*/
MulticastReceiver(int port)
{
super(port);
}
/*
*constructor
*/
MulticastReceiver(String group)
{
super(group);
}
/*
*constructor
*/
MulticastReceiver(int port,String group)
{
super(port,group);
}
/*
*binds port to socket and joins the mullticast group
*/
@Override
public void openconnection() throws NotInitializedVariablesException, IOException
{
if(group.equalsIgnoreCase("") || port==-1)
{
throw (new NotInitializedVariablesException(this.getClass()+": " +
"NotInitializedVariablesException:\n port or group address " +
"are not initialized"));
}
socket = new MulticastSocket(port);
socket.joinGroup(InetAddress.getByName(group));
}
/*
*closes the open connnections
*/
@Override
public void closeconnection() throws IOException, NotInitializedVariablesException
{
if(socket == null)
{
throw (new NotInitializedVariablesException(this.getClass()+" : " +
"NotInitializedVariablesException:\n socket is not initialized"));
}
socket.leaveGroup(InetAddress.getByName(group));
socket.close();
}
/*
* receiver that returns the received datagram packet
*/
public DatagramPacket receive(byte buffer[]) throws IOException
{
//packet.setLength(buffer.length);
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
this.socket.receive(packet);
return packet;
}
} |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import models.Course;
import models.LectureDB;
import play.Application;
import play.GlobalSettings;
import play.libs.F.Promise;
import play.mvc.Http.RequestHeader;
import play.mvc.SimpleResult;
import views.formdata.LectureForm;
import views.html.InvalidUrl;
import static play.mvc.Results.notFound;
import static play.mvc.Results.badRequest;
public class Global extends GlobalSettings {
File courses = new File("public/files/Courses.txt");
BufferedReader br = null;
public void onStart(Application app) {
if (Course.find().all().size() == 0) {
loadCourses(courses);
}
LectureDB.addLecture(new LectureForm("ICS", "311", "Topic 03 A: Asymtotic Notations", "y86z2OrIYQQ",
"Introduces asymptotic concepts and big-O notation."));
LectureDB.addLecture(new LectureForm("ICS", "311", "Topic 06 C: Hash Functions", "jW4wCfz3DwE",
"Examples of Hash Functions and Universal Hashing"));
LectureDB.addLecture(new LectureForm("KOR", "101", "How to Introduce Yourself in Korean", "x9_BmcUk_Xs",
"In Korea, manners are important, and this step-by-step video teaches you some of the basics you need to"
+ " be polite while speaking Korean. A native Korean teacher will explain the simple phrases necessary."));
}
public Promise<SimpleResult> onHandlerNotFound(RequestHeader request) {
return Promise.<SimpleResult> pure(notFound(InvalidUrl.render("Error 404")));
}
public Promise<SimpleResult> onBadRequest(RequestHeader request, String error) {
return Promise.<SimpleResult> pure(badRequest("Don't try to hack the URL!"));
}
private void loadCourses(File file) {
String line = "";
try {
br = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = br.readLine()) != null) {
String[] split = line.split("[()]");
Course course = new Course(split[1].trim(), split[0].trim());
course.save();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
package edu.wustl.catissuecore.annotations.xmi;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.jmi.model.ModelPackage;
import javax.jmi.model.MofPackage;
import javax.jmi.xmi.XmiReader;
import org.netbeans.api.mdr.MDRManager;
import org.netbeans.api.mdr.MDRepository;
import org.omg.uml.UmlPackage;
import org.openide.util.Lookup;
import edu.common.dynamicextensions.bizlogic.BizLogicFactory;
import edu.common.dynamicextensions.domain.AbstractMetadata;
import edu.common.dynamicextensions.domain.integration.EntityMap;
import edu.common.dynamicextensions.domain.integration.EntityMapCondition;
import edu.common.dynamicextensions.domain.integration.FormContext;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.domaininterface.userinterface.ContainerInterface;
import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.common.dynamicextensions.xmi.XMIUtilities;
import edu.common.dynamicextensions.xmi.importer.XMIImportProcessor;
import edu.wustl.catissuecore.action.annotations.AnnotationConstants;
import edu.wustl.catissuecore.bizlogic.AnnotationBizLogic;
import edu.wustl.catissuecore.bizlogic.AnnotationUtil;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.bizlogic.DefaultBizLogic;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
/**
* @author ashish_gupta
*
*/
public class ImportXmi
{
// name of a UML extent (instance of UML metamodel) that the UML models will be loaded into
private static final String UML_INSTANCE = "UMLInstance";
// name of a MOF extent that will contain definition of UML metamodel
private static final String UML_MM = "UML";
// repository
private static MDRepository rep;
// UML extent
private static UmlPackage uml;
// XMI reader
private static XmiReader reader;
/**
* @param args
*/
public static void main(String[] args)
{
FileInputStream in = null;
try
{
if(args.length == 0)
{
throw new Exception("Please Specify the file name to be imported");
}
if(args.length < 2)
{
throw new Exception("Please Specify the hook entity name");
}
if(args.length < 3)
{
throw new Exception("Please Specify the main container csv file name");
}
if(args.length < 4)
{
throw new Exception("Please Specify the name of the Package to be imported");
}
//Ist parameter is fileName
// Fully qualified Name of the xmi file to be imported
String fileName = args[0];
String hookEntity = args[1];
//"C://Documents and Settings//ashish_gupta//Desktop//XMLs//caTissueCore_1.4_Edited.xmi";
fileName = fileName.replaceAll("\\\\", "
System.out.println("Filename = " +fileName);
System.out.println("Hook Entity = " +hookEntity);
String packageName = "";
String conditionRecordObjectCsvFileName = "";
String pathCsvFileName = "";
int beginIndex = fileName.lastIndexOf("
int endIndex = fileName.lastIndexOf(".");
String domainModelName = "";
//System.out.println("beginIndex = " + beginIndex);
if(beginIndex == -1)
{
domainModelName = fileName.substring(beginIndex+1, endIndex);
}
else
{
domainModelName = fileName.substring(beginIndex+2, endIndex);
}
System.out.println("Name of the file = " +domainModelName);
// get the default repository
rep = MDRManager.getDefault().getDefaultRepository();
// create an XMIReader
reader = (XmiReader) Lookup.getDefault().lookup(XmiReader.class);
init();
in = new FileInputStream(fileName);
// start a read-only transaction
rep.beginTrans(true);
// read the document
reader.read(in, null, uml);
if(args.length > 2)
{
pathCsvFileName = args[2];
}
if(args.length > 3)
{
packageName = args[3];
}
if(args.length > 4)
{
conditionRecordObjectCsvFileName = args[4];
}
if(packageName.equals(""))
{
throw new Exception("Package name is mandatory parameter. If no package is present please specify 'Default'.");
}
List<Long> conditionObjectIds = new ArrayList<Long>();
if(!conditionRecordObjectCsvFileName.equals(""))
{
List<String> conditionObjectNames = readFile(conditionRecordObjectCsvFileName);
for(String conditionObjName :conditionObjectNames)
{
System.out.println("conditionObjName = " + conditionObjName);
Long cpId =(Long) getObjectIdentifier(conditionObjName,CollectionProtocol.class.getName(),Constants.TITLE);
if(cpId == null)
{
throw new DynamicExtensionsSystemException("Specified Collection Protocol does not exist.");
}
conditionObjectIds.add(cpId);
}
}
DefaultBizLogic defaultBizLogic = BizLogicFactory.getDefaultBizLogic();
List staticEntityList = defaultBizLogic.retrieve(AbstractMetadata.class.getName(), Constants.NAME, hookEntity);
if(staticEntityList == null || staticEntityList.size() == 0)
{
throw new DynamicExtensionsSystemException("Please enter correct Hook Entity name.");
}
EntityInterface staticEntity = (EntityInterface) staticEntityList.get(0);
List<String> containerNames = readFile(pathCsvFileName);
XMIImportProcessor xmiImportProcessor = new XMIImportProcessor();
List<ContainerInterface> mainContainerList = xmiImportProcessor.processXmi(uml, domainModelName,packageName, containerNames);
boolean isEditedXmi = xmiImportProcessor.isEditedXmi;
System.out.println("Package name = " +packageName);
System.out.println("isEditedXmi = "+isEditedXmi);
System.out.println("Forms have been created !!!!");
System.out.println("Associating with hook entity.");
//List<ContainerInterface> mainContainerList = getMainContainerList(pathCsvFileName,entityNameVsContainers);
//Integrating with hook entity
associateHookEntity(mainContainerList,conditionObjectIds,staticEntity,isEditedXmi);
System.out.println("
}
catch (Exception e)
{
System.out.println("Fatal error reading XMI.");
System.out.println("
System.out.println(e.getMessage());
System.out.println("\n
}
finally
{
// release the transaction
rep.endTrans();
MDRManager.getDefault().shutdownAll();
try
{
in.close();
}
catch(IOException io)
{
System.out.println("Error. Specified file does not exist.");
}
XMIUtilities.cleanUpRepository();
}
}
/**
* @param path
* @param entityNameVsContainers
* @return
* @throws IOException
*/
// private static List<ContainerInterface> getMainContainerList(String path,Map<String, List<ContainerInterface>> entityNameVsContainers) throws IOException
// List<ContainerInterface> mainContainerList = getContainerObjectList(containerNames,entityNameVsContainers);
// return mainContainerList;
/**
* @param path
* @return
* @throws IOException
*/
private static List<String> readFile(String path) throws IOException
{
List<String> containerNames = new ArrayList<String>();
File file = new File(path);
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String line = null;
//read each line of text file
while((line = bufRdr.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line,",");
while (st.hasMoreTokens())
{
//get next token and store it in the array
containerNames.add(st.nextToken());
}
}
return containerNames;
}
private static void init() throws Exception
{
uml = (UmlPackage) rep.getExtent(UML_INSTANCE);
if (uml == null)
{
// UML extent does not exist -> create it (note that in case one want's to instantiate
// a metamodel other than MOF, they need to provide the second parameter of the createExtent
// method which indicates the metamodel package that should be instantiated)
uml = (UmlPackage) rep.createExtent(UML_INSTANCE, getUmlPackage());
}
}
/** Finds "UML" package -> this is the topmost package of UML metamodel - that's the
* package that needs to be instantiated in order to create a UML extent
*/
private static MofPackage getUmlPackage() throws Exception
{
// get the MOF extent containing definition of UML metamodel
ModelPackage umlMM = (ModelPackage) rep.getExtent(UML_MM);
if (umlMM == null)
{
// it is not present -> create it
umlMM = (ModelPackage) rep.createExtent(UML_MM);
}
// find package named "UML" in this extent
MofPackage result = getUmlPackage(umlMM);
if (result == null)
{
// it cannot be found -> UML metamodel is not loaded -> load it from XMI
reader.read(UmlPackage.class.getResource("resources/01-02-15_Diff.xml").toString(),
umlMM);
// try to find the "UML" package again
result = getUmlPackage(umlMM);
}
return result;
}
/** Finds "UML" package in a given extent
* @param umlMM MOF extent that should be searched for "UML" package.
*/
private static MofPackage getUmlPackage(ModelPackage umlMM)
{
// iterate through all instances of package
System.out.println("Here");
for (Iterator it = umlMM.getMofPackage().refAllOfClass().iterator(); it.hasNext();)
{
MofPackage pkg = (MofPackage) it.next();
System.out.println("\n\nName = " + pkg.getName());
// is the package topmost and is it named "UML"?
if (pkg.getContainer() == null && "UML".equals(pkg.getName()))
{
// yes -> return it
return pkg;
}
}
// a topmost package named "UML" could not be found
return null;
}
/**
* @throws DAOException
* @throws DynamicExtensionsSystemException
* @throws UserNotAuthorizedException
* @throws BizLogicException
* @throws DynamicExtensionsApplicationException
*
*/
private static void associateHookEntity(List<ContainerInterface> mainContainerList,List<Long> conditionObjectIds,EntityInterface staticEntity,boolean isEditedXmi) throws DAOException, DynamicExtensionsSystemException, BizLogicException, UserNotAuthorizedException, DynamicExtensionsApplicationException
{
Object typeId = getObjectIdentifier("edu.wustl.catissuecore.domain.CollectionProtocol",AbstractMetadata.class.getName(),Constants.NAME);
DefaultBizLogic defaultBizLogic = BizLogicFactory.getDefaultBizLogic();
//Set<String> keySet = entityNameVsContainers.keySet();
// for(String key : keySet)
for(ContainerInterface container: mainContainerList)
{
// List<ContainerInterface> containerList = entityNameVsContainers.get(key);
// ContainerInterface container = containerList.get(0);
if(isEditedXmi)
{//Retrieve entity map
List<EntityMap> entityMapList = defaultBizLogic.retrieve(EntityMap.class.getName(), "containerId", container.getId());
if(entityMapList != null && entityMapList.size() > 0)
{
EntityMap entityMap = entityMapList.get(0);
if(conditionObjectIds != null)
{
editConditions(entityMap,conditionObjectIds,typeId);
}
AnnotationBizLogic annotation = new AnnotationBizLogic();
annotation.updateEntityMap(entityMap);
}
else
{//Create new Entity Map
createIntegrationObjects(container,staticEntity,conditionObjectIds,typeId);
}
}
else
{//Create new Entity Map
createIntegrationObjects(container,staticEntity,conditionObjectIds,typeId);
}
}
}
/**
* @param entityMap
* @param clinicalStudyId
* @param typeId
* @throws DynamicExtensionsSystemException
* @throws DAOException
*/
private static void editConditions(EntityMap entityMap,List<Long> conditionObjectIds,Object typeId) throws DynamicExtensionsSystemException, DAOException
{
Collection<FormContext> formContextColl = entityMap.getFormContextCollection();
for(FormContext formContext : formContextColl)
{
Collection<EntityMapCondition> entityMapCondColl = formContext.getEntityMapConditionCollection();
for(Long collectionProtocolId : conditionObjectIds)
{
int temp = 0;
for(EntityMapCondition condition : entityMapCondColl)
{
if(condition.getStaticRecordId().compareTo(collectionProtocolId) == 0)
{
temp++;
break;
}
}
if(temp == 0)
{
EntityMapCondition entityMapCondition = getEntityMapCondition(formContext,collectionProtocolId,typeId);
entityMapCondColl.add(entityMapCondition);
}
}
formContext.setEntityMapConditionCollection(entityMapCondColl);
}
}
/**
* @param container
* @param staticEntity
* @param clinicalStudyId
* @param typeId
* @throws DynamicExtensionsSystemException
* @throws DAOException
* @throws BizLogicException
* @throws UserNotAuthorizedException
* @throws DynamicExtensionsApplicationException
*/
private static void createIntegrationObjects(ContainerInterface container,EntityInterface staticEntity,List<Long> conditionObjectIds,Object typeId) throws DynamicExtensionsSystemException, DAOException, BizLogicException, UserNotAuthorizedException, DynamicExtensionsApplicationException
{
EntityMap entityMap = getEntityMap(container,staticEntity.getId());
Collection<FormContext> formContextColl = getFormContext(entityMap,conditionObjectIds,typeId);
entityMap.setFormContextCollection(formContextColl);
AnnotationBizLogic annotation = new AnnotationBizLogic();
annotation.insert(entityMap, Constants.HIBERNATE_DAO);
AnnotationUtil.addAssociation(staticEntity.getId(), container.getId(), true);
}
/**
* @param entityMap
* @param collectionProtocolName
* @param typeId
* @return
* @throws DynamicExtensionsSystemException
* @throws DAOException
*/
private static Collection<FormContext> getFormContext(EntityMap entityMap,List<Long> conditionObjectIds,Object typeId) throws DynamicExtensionsSystemException, DAOException
{
Collection<FormContext> formContextColl = new HashSet<FormContext>();
FormContext formContext = new FormContext();
formContext.setEntityMap(entityMap);
Collection<EntityMapCondition> entityMapConditionColl = new HashSet<EntityMapCondition>();
if(conditionObjectIds != null)
{
for(Long cpId: conditionObjectIds)
{
entityMapConditionColl.add(getEntityMapCondition(formContext,cpId,typeId));
}
}
formContext.setEntityMapConditionCollection(entityMapConditionColl);
formContextColl.add(formContext);
return formContextColl;
}
/**
* @param formContext
* @param collectionProtocolName
* @param typeId
* @return
* @throws DynamicExtensionsSystemException
* @throws DAOException
*/
private static EntityMapCondition getEntityMapCondition(FormContext formContext,Long conditionObjectId,Object typeId) throws DynamicExtensionsSystemException, DAOException
{
// Collection<EntityMapCondition> entityMapCondColl = new HashSet<EntityMapCondition>();
// for(Long cpId : conditionObjectIds)
EntityMapCondition entityMapCondition = new EntityMapCondition();
entityMapCondition.setStaticRecordId((conditionObjectId));
entityMapCondition.setTypeId(((Long)typeId));
entityMapCondition.setFormContext(formContext);
// entityMapCondColl.add(entityMapCondition);
return entityMapCondition;
}
/**
* @param container
* @param hookEntityName
* @return
* @throws DAOException
* @throws DynamicExtensionsSystemException
*/
private static EntityMap getEntityMap(ContainerInterface container,Object staticEntityId) throws DAOException, DynamicExtensionsSystemException
{
EntityMap entityMap = new EntityMap();
entityMap.setContainerId(container.getId());
entityMap.setCreatedBy("");
entityMap.setCreatedDate(new Date());
entityMap.setLinkStatus(AnnotationConstants.STATUS_ATTACHED);
entityMap.setStaticEntityId(((Long)staticEntityId));
return entityMap;
}
/**
* @param hookEntityName
* @return
* @throws DAOException
*/
private static Object getObjectIdentifier(String whereColumnValue,String selectObjName,String whereColumnName) throws DAOException
{
DefaultBizLogic defaultBizLogic = BizLogicFactory.getDefaultBizLogic();
String[] selectColName = {Constants.SYSTEM_IDENTIFIER};
String[] whereColName = {whereColumnName};
Object[] whereColValue = {whereColumnValue};
String[] whereColCondition = {Constants.EQUALS};
String joinCondition = Constants.AND_JOIN_CONDITION;
List id = defaultBizLogic.retrieve(selectObjName, selectColName, whereColName, whereColCondition, whereColValue, joinCondition);
if(id != null && id.size() > 0)
{
return id.get(0);
}
return null;
}
} |
package org.voovan.http.websocket;
import org.voovan.http.HttpSessionParam;
import org.voovan.http.server.HttpRequest;
import org.voovan.http.server.HttpSession;
import org.voovan.http.websocket.exception.WebSocketFilterException;
import org.voovan.network.IoSession;
import org.voovan.network.exception.SendMessageException;
import org.voovan.tools.collection.Attributes;
import org.voovan.tools.log.Logger;
import java.nio.ByteBuffer;
public class WebSocketSession extends Attributes {
private IoSession socketSession;
private WebSocketRouter webSocketRouter;
private String remoteAddres;
private int remotePort;
private WebSocketType webSocketType;
private boolean masked;
/**
*
* @param socketSession Socket
* @param webSocketRouter WebSocket
* @param webSocketType WebSocket
*/
public WebSocketSession(IoSession socketSession, WebSocketRouter webSocketRouter, WebSocketType webSocketType){
this.socketSession = socketSession;
this.remoteAddres = socketSession.remoteAddress();
this.remotePort = socketSession.remotePort();
this.webSocketRouter = webSocketRouter;
this.webSocketType = webSocketType;
if(this.webSocketType == webSocketType.SERVER){
masked = false;
} else {
masked = true;
}
}
/**
* WebSocket
* @return WebSocket
*/
public String getLocation(){
HttpRequest request = (HttpRequest)socketSession.getAttribute(HttpSessionParam.HTTP_REQUEST);
return request.protocol().getPath();
}
/**
* Http session
* @return HttpSession
*/
public HttpSession getHttpSession(){
HttpRequest request = (HttpRequest)socketSession.getAttribute(HttpSessionParam.HTTP_REQUEST);
if(request.sessionExists()) {
return request.getSession();
} else {
return null;
}
}
/**
* IP
*
* @return IP
*/
public String getRemoteAddres() {
return this.remoteAddres;
}
/**
*
*
* @return
*/
public int getRemotePort() {
return remotePort;
}
/**
* WebSocket
* @return WebSocket
*/
public WebSocketRouter getWebSocketRouter() {
return webSocketRouter;
}
/**
* WebSocket
* @param webSocketRouter WebSocket
*/
public void setWebSocketRouter(WebSocketRouter webSocketRouter) {
this.webSocketRouter = webSocketRouter;
}
/**
* websocket
* @param obj
* @throws SendMessageException
* @throws WebSocketFilterException WebSocket
*/
public void send(Object obj) throws SendMessageException, WebSocketFilterException {
ByteBuffer byteBuffer = (ByteBuffer)webSocketRouter.filterEncoder(this, obj);
WebSocketFrame webSocketFrame = WebSocketFrame.newInstance(true, WebSocketFrame.Opcode.TEXT, masked, byteBuffer);
this.socketSession.syncSend(webSocketFrame);
}
/**
* websocket
* @param obj
* @throws SendMessageException
* @throws WebSocketFilterException WebSocket
*/
public void sendBinary(Object obj) throws SendMessageException, WebSocketFilterException {
ByteBuffer byteBuffer = null;
if(obj instanceof byte[]){
byteBuffer = ByteBuffer.wrap((byte[])obj);
} else if(obj instanceof ByteBuffer) {
byteBuffer = (ByteBuffer)obj;
} else {
byteBuffer = (ByteBuffer)webSocketRouter.filterEncoder(this, obj);
}
WebSocketFrame webSocketFrame = WebSocketFrame.newInstance(true, WebSocketFrame.Opcode.BINARY, masked, byteBuffer);
this.socketSession.syncSend(webSocketFrame);
}
/**
* websocket
* @param webSocketFrame
* @throws SendMessageException
*/
protected void send(WebSocketFrame webSocketFrame) throws SendMessageException {
this.socketSession.syncSend(webSocketFrame);
}
/**
*
* @return true: , false:
*/
public boolean isConnected(){
return socketSession.isConnected();
}
/**
* Socket
* CLOSING
*/
/**
* WebSocket
*/
public void close() {
WebSocketFrame closeWebSocketFrame = WebSocketFrame.newInstance(true, WebSocketFrame.Opcode.CLOSING,
masked, ByteBuffer.wrap(WebSocketTools.intToByteArray(1000, 2)));
try {
send(closeWebSocketFrame);
} catch (SendMessageException e) {
Logger.error("Close WebSocket error, Socket will be close " ,e);
socketSession.close();
}
}
protected IoSession getSocketSession() {
return socketSession;
}
public void setSocketSession(IoSession socketSession) {
this.socketSession = socketSession;
}
} |
package org.hackerrank.java.datastructure;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Array1DPart2
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int[][] sequences = new int[scanner.nextInt()][];
int[] jumps = new int[sequences.length];
for(int i = 0; i < sequences.length; i++)
{
sequences[i] = new int[scanner.nextInt()];
jumps[i] = scanner.nextInt();
for(int j = 0; j < sequences[i].length; j++)
{
sequences[i][j] = scanner.nextInt();
}
}
scanner.close();
for(int i = 0; i < sequences.length; i++)
{
int sum = 0;
for(int j = 0; j < sequences[i].length; j++)
{
sum += sequences[i][j];
}
boolean solveable = sum == 0;
if(!solveable)
{
int index = 0;
while(!solveable)
{
}
}
System.out.println(solveable ? "YES" : "NO");
}
}
int IntArraySum(int[] array; int startIndex)
{
int sum = 0;
for(int i = startIndex; i < array.length; i++)
{
sum += array[i];
}
return sum;
}
} |
package in.uncod.android.widget;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.ListView;
import android.widget.AdapterView;
import android.view.ViewGroup;
import android.view.ViewConfiguration;
import android.view.View;
import android.view.MotionEvent;
import android.util.AttributeSet;
import android.os.Vibrator;
import android.os.Handler;
import android.graphics.Rect;
import android.content.res.TypedArray;
import android.content.Context;
import com.globalmentor.android.content.res.Themes;
import in.uncod.android.R;
import in.uncod.android.view.DragToDeleteManager;
/**
* This class extends ListView to allow drag-and-reorder and drag-to-delete operations
*
* @author cwc
*/
public class MagicListView extends ListView {
/**
* This interface provides callbacks for objects that are observing a MagicListView
*
* @author cwc
*/
public interface MagicListViewListener {
/**
* Called when an item is deleted by the list. The listening object should have the owner of the list's adapter
* handle the deletion appropriately (i.e. confirm deletion with user, then remove the object from the adapter).
*
* @param item
*/
void onItemDelete(Object item);
/**
* Called when an item has been reordered by the list. The listening object should have the owner of the list's
* adapter handle the reorder appropriately (i.e. confirm the reordering, then adjust the ordering of the
* objects in the adapter).
*
* @param movedItem
* @param newParent
*/
void onItemMoved(Object movedItem, Object newParent);
}
private MagicListViewListener mListListener;
private Object mDraggingItem;
private int mDraggingItemPos;
private int mPreferredItemHeight;
private ViewGroup mLastExpandedItem;
private int mTouchSlop;
static final int LONGPRESS_THRESHOLD = 500;
Handler mHandler = new Handler();
Vibrator mVibrator;
private DragToDeleteManager mDragAndDeleteManager;
private int mExpandingLayoutResourceId = -1;
private int mDragHandleView;
private Timer mLongPressTimer;
private Timer mTapTimer;
private boolean mLongPressDrag = false;
private int mLongPressStartX;
private int mLongPressStartY;
int mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
int mTapTimeout = ViewConfiguration.getTapTimeout();
boolean tapTimedOut = false;
List<Integer> excludedItems;
public MagicListView(Context context) {
super(context);
setup(context, null);
}
public MagicListView(Context context, AttributeSet attrs) {
super(context, attrs);
setup(context, attrs);
}
public MagicListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setup(context, attrs);
}
private void setup(Context context, AttributeSet attrs) {
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MagicListView);
mPreferredItemHeight = a.getDimensionPixelSize(R.styleable.MagicListView_preferredItemHeight,
(int) Themes.getListPreferredItemHeightDimension(context));
a.recycle();
mDragAndDeleteManager = new DragToDeleteManager(context);
setSelector(android.R.color.transparent);
}
/**
* Sets the listener that will handle reordering and deletion events
*
* @param listener
*/
public void setReorderAndDeleteListener(MagicListViewListener listener) {
mListListener = listener;
}
/**
* Sets whether this list will allow objects to deleted via dragging
*
* @param allowDelete
*/
public void setDeleteAllowed(boolean allowDelete) {
mDragAndDeleteManager.setDeleteAllowed(allowDelete);
}
public void setExcludedItems(List<Integer> excluded) {
excludedItems = excluded;
}
/**
* Intercepts the 'down' touch event, to make sure we can handle dragging on any child view
*
* @param event
* The motion event
*
* @return The default implementation's return value
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP) {
onTouchEvent(event);
}
return super.onInterceptTouchEvent(event);
}
/* (non-Javadoc)
* @see android.widget.AbsListView#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean handled = false;
int x = (int) event.getX();
int y = (int) event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int itemnum = MagicListView.this.pointToPosition(x, y);
if (itemnum == AdapterView.INVALID_POSITION) {
return super.onTouchEvent(event);
}
mLongPressStartX = x;
mLongPressStartY = y;
handleTouchDown(event, x, itemnum);
handled = true;
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (mDragAndDeleteManager.isDragging()) {
int itemnum = MagicListView.this.pointToPosition(x, y);
handleTouchMove(y, itemnum);
handled = mDragAndDeleteManager.onTouchEvent(event);
}
else {
if (Math.abs(mLongPressStartX - x) > mTouchSlop
|| Math.abs(mLongPressStartY - y) > mTouchSlop) {
if (mTapTimer != null) {
mTapTimer.cancel();
}
if (mLongPressTimer != null) {
synchronized (MagicListView.this) {
mLongPressTimer.cancel();
mLongPressTimer = null;
}
}
}
}
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
handleTouchUp(x, y);
if (tapTimedOut) {
tapTimedOut = false;
handled = true;
}
}
if (!handled)
handled = super.onTouchEvent(event);
return handled;
}
/**
* Sets the resource ID of the view within child item layouts to show/hide when list items are being dragged
*
* @param resourceId
*/
public void setExpandingLayoutResource(int resourceId) {
mExpandingLayoutResourceId = resourceId;
}
/**
* Sets the resource ID of the view within child item layouts that will be used as the handle for dragging
*
* @param resourceId
*/
public void setDragHandleResource(int resourceId) {
mDragHandleView = resourceId;
}
public void setLongPressForDrag(boolean longPress) {
mLongPressDrag = longPress;
}
private void handleTouchUp(int x, int y) {
if (mTapTimer != null) {
mTapTimer.cancel();
}
if (mLongPressTimer != null) {
synchronized (MagicListView.this) {
mLongPressTimer.cancel();
mLongPressTimer = null;
}
}
if (mDragAndDeleteManager.isDeleting()) {
mListListener.onItemDelete(mDraggingItem);
}
else if (mDragAndDeleteManager.isDragging()) {
// Handle the reordering after dropping an item
int itemnum = MagicListView.this.pointToPosition(x, y);
Object newParent = getItemAtPosition(itemnum - 1);
mListListener.onItemMoved(mDraggingItem, newParent);
}
// Collapse the expanded listview item, if it exists
if (mLastExpandedItem != null) {
mLastExpandedItem.setVisibility(View.GONE);
}
mDragAndDeleteManager.stopDragging();
}
private void handleTouchMove(int y, int itemnum) {
// If the user drags an item over another item that isn't the list header or the item's original position,
// expand the designated child of the underlying item's view to give the user the impression of an empty area in
// which to drop the currently dragged item
if (itemnum > this.getHeaderViewsCount() - 1 && itemnum != mDraggingItemPos) {
// Collapse the previously expanded item
if (mLastExpandedItem != null) {
mLastExpandedItem.setVisibility(View.GONE);
}
// Expand the item at the current position
View item = MagicListView.this.getChildAt(itemnum - MagicListView.this.getFirstVisiblePosition());
mLastExpandedItem = (ViewGroup) item.findViewById(mExpandingLayoutResourceId);
if (mLastExpandedItem != null) {
mLastExpandedItem.setVisibility(View.VISIBLE);
}
}
// Hide the view for the currently dragged item, if it would be visible
if (mDraggingItemPos >= getFirstVisiblePosition() && mDraggingItemPos <= getLastVisiblePosition()) {
hideChildView(itemnum);
}
// Handle scrolling of the listview while dragging
int listHeight = getHeight();
int upperBound = Math.min(y - mTouchSlop, listHeight / 3);
int lowerBound = Math.max(y + mTouchSlop, listHeight * 2 / 3);
int speed = 0;
if (y > lowerBound) {
// scroll the list up a bit
speed = y > (getHeight() + lowerBound) / 2 ? 16 : 4;
}
else if (y < upperBound) {
// scroll the list down a bit
speed = y < upperBound / 2 ? -16 : -4;
}
if (speed != 0) {
int ref = pointToPosition(0, getHeight() / 2);
if (ref == AdapterView.INVALID_POSITION) {
// we hit a divider or an invisible view, check somewhere else
ref = pointToPosition(0, getHeight() / 2 + getDividerHeight() + 64);
}
View v = getChildAt(ref - getFirstVisiblePosition());
if (v != null) {
int pos = v.getTop();
setSelectionFromTop(ref, pos - speed);
}
}
}
private void hideChildView(int itemnum) {
int firstVisible = MagicListView.this.getFirstVisiblePosition();
View current = MagicListView.this.getChildAt(mDraggingItemPos - firstVisible);
ViewGroup.LayoutParams lp = current.getLayoutParams();
if (itemnum == mDraggingItemPos) {
lp.height = mPreferredItemHeight;
}
else {
lp.height = 1;
}
current.setLayoutParams(lp);
current.setVisibility(View.INVISIBLE);
layoutChildren();
}
private void handleTouchDown(final MotionEvent event, int x, final int itemnum) {
// Test that the user pressed on the drag handle for the item at these coordinates
final View item = MagicListView.this.getChildAt(itemnum
- MagicListView.this.getFirstVisiblePosition());
if (!mLongPressDrag) {
View dragger = item.findViewById(mDragHandleView);
if (dragger != null) {
Rect r = new Rect();
dragger.getDrawingRect(r);
mDraggingItem = getItemAtPosition(itemnum);
mDraggingItemPos = itemnum;
r.left = dragger.getLeft();
r.right = dragger.getRight();
r.top = dragger.getTop();
r.bottom = dragger.getBottom();
if ((r.left < x) && (x < r.right)) {
// Tell the drag manager that the user is dragging an item
startDrag(event, item, itemnum);
}
}
}
else {
synchronized (MagicListView.this) {
// Only initiate the long-press timer if one isn't already active
if (mLongPressTimer == null && !excludedItems.contains(itemnum)) {
mLongPressTimer = new Timer();
mLongPressTimer.schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
// Task finished, so clear the timer
synchronized (MagicListView.this) {
mLongPressTimer = null;
}
mDraggingItem = getItemAtPosition(itemnum);
mDraggingItemPos = itemnum;
startDrag(event, item, itemnum);
}
});
}
}, mLongPressTimeout + mTapTimeout);
}
}
}
}
private void startDrag(MotionEvent event, View item, int itemnum) {
mDraggingItem = getItemAtPosition(itemnum);
hideChildView(itemnum);
mDragAndDeleteManager.startDragging(item, event, mPreferredItemHeight);
}
/* (non-Javadoc)
* @see android.widget.AbsListView#onDetachedFromWindow()
*/
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// Tell the drag manager to clean itself up, since this view is no longer visible
this.mDragAndDeleteManager.release();
}
} |
package com.marcelherd.uebung2.auto;
import com.marcelherd.uebung1.model.BTree;
import com.marcelherd.uebung1.model.MyBTree;
/**
* A car that uses gasoline as fuel.
*
* @author Manuel Schwalm
* @author Marcel Herd
*/
public class CarDealer {
private BTree cars;
public CarDealer() {
cars = new MyBTree(100);
}
/**
* Returns true if the car dealer is able to incorporate this car into his assortment.
*
* @param car - car that the dealer should incorporate into his assortment
* @return true if the car dealer is able to incorporate this car into his assortment
*/
public boolean offer(Car car) {
return cars.insert(car);
}
/**
* Sells the car and removes it from the dealers assortment.
*
* @param car - car that is being sold
*/
public void sell(Car car) {
cars.delete(car);
}
/**
* Lists alls cars, that the dealer currently has for sale.
*/
public void printCarsForSale() {
cars.printInOrder();
}
/**
* Returns all cars that the dealer is currently offering
*
* @return all cars that the dealer is currently offering
*/
public BTree getCars() {
return cars;
}
} |
package net.yadaframework.web;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_AUTOCLOSE;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_BODY;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_CALLSCRIPT;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_REDIRECT;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_RELOADONCLOSE;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_SEVERITY;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_TITLE;
import static net.yadaframework.core.YadaConstants.KEY_NOTIFICATION_TOTALSEVERITY;
import static net.yadaframework.core.YadaConstants.VAL_NOTIFICATION_SEVERITY_ERROR;
import static net.yadaframework.core.YadaConstants.VAL_NOTIFICATION_SEVERITY_INFO;
import static net.yadaframework.core.YadaConstants.VAL_NOTIFICATION_SEVERITY_OK;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities.EscapeMode;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import net.yadaframework.components.YadaUtil;
import net.yadaframework.core.YadaConfiguration;
import net.yadaframework.core.YadaConstants;
@Service
public class YadaWebUtil {
private final transient Logger log = LoggerFactory.getLogger(getClass());
@Autowired private YadaConfiguration config;
@Autowired private YadaUtil yadaUtil;
public final Pageable FIND_ONE = new PageRequest(0, 1);
// /**
// * Ensures that a paage
// * @param pagePath
// * @return
// */
// public String getLocaleSafeForward(String pagePath) {
// if (config.isLocalePathVariableEnabled()) {
// return "/" + LocaleContextHolder.getLocale().getLanguage() + (pagePath.equals("/")?"":pagePath);
// return pagePath;
/**
* Returns the first language in the request language header as a string.
* @return the language string, like "en_US", or "" if not found
*/
public String getBrowserLanguage() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String languageHeader = StringUtils.trimToEmpty(request.getHeader("Accept-Language")); // en-US,en-GB;q=0.9,en;q=0.8,it;q=0.7,es;q=0.6,la;q=0.5
int pos = languageHeader.indexOf(',');
if (pos>4) {
try {
return languageHeader.substring(0, pos);
} catch (Exception e) {
// Invalid header - ignored
}
}
return "";
}
/**
* Returns the first country in the request language header as a string.
* @return the country string, like "US", or "" if not found
*/
public String getBrowserCountry() {
String browserLanguage = getBrowserLanguage();
int pos = browserLanguage.indexOf('-');
if (pos>1) {
try {
return browserLanguage.substring(pos+1);
} catch (Exception e) {
// Invalid header - ignored
}
}
return "";
}
/**
* Save an uploaded file to a temporary file
* @param attachment
* @return the temporary file holding the uploaded file, or null if no file has bee attached
* @throws IOException
*/
public File saveAttachment(MultipartFile attachment) throws IOException {
if (!attachment.isEmpty()) {
File targetFile = File.createTempFile("upload-", null);
saveAttachment(attachment, targetFile);
return targetFile;
}
return null;
}
/**
* Save an uploaded file to the given target file
* @param attachment
* @param targetFile
* @throws IOException
*/
public void saveAttachment(MultipartFile attachment, File targetFile) throws IOException {
try (InputStream inputStream = attachment.getInputStream(); OutputStream outputStream = new FileOutputStream(targetFile)) {
IOUtils.copy(inputStream, outputStream);
} catch (IOException e) {
throw e;
}
}
/**
* From a given string, creates a "slug" that can be inserted in a url and still be readable.
* @param source the string to convert
* @return the slug
*/
public String makeSlug(String source) {
return makeSlugStatic(source);
}
/**
* From a given string, creates a "slug" that can be inserted in a url and still be readable.
* It is static so that it can be used in Entity objects (no context)
* @param source the string to convert
* @return the slug, which is empty for a null string
*/
public static String makeSlugStatic(String source) {
if (StringUtils.isBlank(source)) {
return "";
}
String slug = source.trim().toLowerCase().replace('à', 'a').replace('è', 'e').replace('é', 'e').replace('ì', 'i').replace('ò', 'o').replace('ù', 'u').replace('.', '-');
slug = slug.replaceAll(" +", "-"); // Spaces become dashes
slug = slug.replaceAll("[^\\w:,;=&!+~\\(\\)@\\*\\$\\'\\-]", "");
slug = StringUtils.removeEnd(slug, ".");
slug = StringUtils.removeEnd(slug, ";");
slug = StringUtils.removeEnd(slug, "\\");
slug = slug.replaceAll("-+", "-"); // Multiple dashes become one dash
return slug;
}
/**
* Decodes a string with URLDecoder, handling the useless try-catch that is needed
* @param source
* @return
*/
public String urlDecode(String source) {
final String encoding = "UTF-8";
try {
return URLDecoder.decode(source, encoding);
} catch (UnsupportedEncodingException e) {
log.error("Invalid encoding: {}", encoding);
}
return source;
}
/**
* Encodes a string with URLEncoder, handling the useless try-catch that is needed
* @param source
* @return
*/
public String urlEncode(String source) {
final String encoding = "UTF-8";
try {
return URLEncoder.encode(source, encoding);
} catch (UnsupportedEncodingException e) {
log.error("Invalid encoding: {}", encoding);
}
return source;
}
/**
* ATTENZIONE: non sempre va!
* @return
*/
public HttpServletRequest getCurrentRequest() {
return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
}
public boolean isAjaxRequest() {
return isAjaxRequest(getCurrentRequest());
}
public boolean isAjaxRequest(HttpServletRequest request) {
String ajaxHeader = request.getHeader("X-Requested-With");
return "XMLHttpRequest".equalsIgnoreCase(ajaxHeader);
}
/**
* Trasforma /res/img/favicon.ico in /res-0002/img/favicon.ico
* @param urlNotVersioned
* @return
*/
public String versionifyResourceUrl(String urlNotVersioned) {
// Esempio: var urlPrefix=[[@{${@yadaWebUtil.versionifyResourceUrl('/res/js/facebook/sdk.js')}}]];
final String resFolder="/" + config.getResourceDir() + "/"; // "/res/"
final int resLen = resFolder.length();
if (urlNotVersioned.startsWith(resFolder)) {
try {
String prefix = urlNotVersioned.substring(0, resLen-1);
String suffix = urlNotVersioned.substring(resLen-1);
return prefix + "-" + config.getApplicationBuild() + suffix;
} catch (Exception e) {
log.error("Impossibile versionificare la url {} (ignored)", urlNotVersioned, e);
}
}
return urlNotVersioned;
}
/**
* Cleans the html content leaving only the following tags: b, em, i, strong, u, br, cite, em, i, p, strong, img, li, ul, ol, sup, sub, s
* @param content html content
* @param extraTags any other tags that you may want to keep, e. g. "a"
* @return
*/
public String cleanContent(String content, String ... extraTags) {
Whitelist allowedTags = Whitelist.simpleText(); // This whitelist allows only simple text formatting: b, em, i, strong, u. All other HTML (tags and attributes) will be removed.
allowedTags.addTags("br", "cite", "em", "i", "p", "strong", "img", "li", "ul", "ol", "sup", "sub", "s");
allowedTags.addTags(extraTags);
allowedTags.addAttributes("p", "style"); // Serve per l'allineamento a destra e sinistra
allowedTags.addAttributes("img", "src", "style", "class");
if (Arrays.asList(extraTags).contains("a")) {
allowedTags.addAttributes("a", "href", "target");
}
Document dirty = Jsoup.parseBodyFragment(content, "");
Cleaner cleaner = new Cleaner(allowedTags);
Document clean = cleaner.clean(dirty);
clean.outputSettings().escapeMode(EscapeMode.xhtml); // Non fa l'escape dei caratteri utf-8
String safe = clean.body().html();
return safe;
}
public String getWebappAddress(HttpServletRequest request) {
int port = request.getServerPort();
String pattern = port==80||port==443?"%s://%s%s":"%s://%s:%d%s";
String myServerAddress = port==80||port==443?
String.format(pattern, request.getScheme(), request.getServerName(), request.getContextPath())
:
String.format(pattern, request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath());
return myServerAddress;
}
/**
* Indica se l'estensione appartiene a un'immagine accettabile
* @param extension e.g. "jpg"
* @return
*/
public boolean isWebImage(String extension) {
extension = extension.toLowerCase();
return extension.equals("jpg")
|| extension.equals("png")
|| extension.equals("gif")
|| extension.equals("tif")
|| extension.equals("tiff")
|| extension.equals("jpeg");
}
/**
* ritorna ad esempio "jpg" lowercase
* @param multipartFile
* @return
*/
public String getFileExtension(MultipartFile multipartFile) {
String result = null;
if (multipartFile!=null) {
String originalName = multipartFile.getOriginalFilename();
result = yadaUtil.getFileExtension(originalName);
}
return result;
}
/**
* Visualizza un errore se non viene fatto redirect
* @param title
* @param message
* @param model
* @deprecated Use YadaNotify instead
*/
@Deprecated
public String modalError(String title, String message, Model model) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_ERROR, null, model);
return "/yada/modalNotify";
}
/**
*
* @param title
* @param message
* @param model
* @return
* @deprecated Use YadaNotify instead
*/
@Deprecated
public String modalInfo(String title, String message, Model model) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_INFO, null, model);
return "/yada/modalNotify";
}
/**
*
* @param title
* @param message
* @param model
* @return
* @deprecated Use YadaNotify instead
*/
@Deprecated
public String modalOk(String title, String message, Model model) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_OK, null, model);
return "/yada/modalNotify";
}
/**
* Visualizza un errore se viene fatto redirect
* @param title
* @param message
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalError(String title, String message, RedirectAttributes redirectAttributes) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_ERROR, redirectAttributes);
}
/**
*
* @param title
* @param message
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalInfo(String title, String message, RedirectAttributes redirectAttributes) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_INFO, redirectAttributes);
}
/**
*
* @param title
* @param message
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalOk(String title, String message, RedirectAttributes redirectAttributes) {
notifyModal(title, message, VAL_NOTIFICATION_SEVERITY_OK, redirectAttributes);
}
/**
* Set the automatic closing time for the notification - no close button is shown
* @param milliseconds
* @param model
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalAutoclose(long milliseconds, Model model) {
model.addAttribute(KEY_NOTIFICATION_AUTOCLOSE, milliseconds);
}
/**
* Set the automatic closing time for the notification - no close button is shown
* @param milliseconds
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalAutoclose(long milliseconds, RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(KEY_NOTIFICATION_AUTOCLOSE, milliseconds);
}
/**
* Set the page to reload when the modal is closed
* @param model
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalReloadOnClose(Model model) {
model.addAttribute(KEY_NOTIFICATION_RELOADONCLOSE, KEY_NOTIFICATION_RELOADONCLOSE);
}
/**
* Set the page to reload when the modal is closed
* @param redirectAttributes
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void modalReloadOnClose(RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(KEY_NOTIFICATION_RELOADONCLOSE, KEY_NOTIFICATION_RELOADONCLOSE);
}
@Deprecated
private void notifyModal(String title, String message, String severity, RedirectAttributes redirectAttributes) {
Map<String, ?> modelMap = redirectAttributes.getFlashAttributes();
// Mette nel flash tre array di stringhe che contengono titolo, messaggio e severity.
if (!modelMap.containsKey(KEY_NOTIFICATION_TITLE)) {
List<String> titles = new ArrayList<String>();
List<String> bodies = new ArrayList<String>();
List<String> severities = new ArrayList<String>();
redirectAttributes.addFlashAttribute(KEY_NOTIFICATION_TITLE, titles);
redirectAttributes.addFlashAttribute(KEY_NOTIFICATION_BODY, bodies);
redirectAttributes.addFlashAttribute(KEY_NOTIFICATION_SEVERITY, severities);
}
// Aggiunge i nuovi valori
((List<String>)modelMap.get(KEY_NOTIFICATION_TITLE)).add(title);
((List<String>)modelMap.get(KEY_NOTIFICATION_BODY)).add(message);
((List<String>)modelMap.get(KEY_NOTIFICATION_SEVERITY)).add(severity);
String newTotalSeverity = calcTotalSeverity(modelMap, severity);
redirectAttributes.addFlashAttribute(KEY_NOTIFICATION_TOTALSEVERITY, newTotalSeverity);
}
/**
* Test if a modal is going to be opened when back to the view (usually after a redirect)
* @param request
* @return true if a modal is going to be opened
* @deprecated Use YadaNotify instead
*/
@Deprecated
public boolean isNotifyModalPending(HttpServletRequest request) {
Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
return flashMap!=null && (
flashMap.containsKey(KEY_NOTIFICATION_TITLE)
|| flashMap.containsKey(KEY_NOTIFICATION_BODY)
|| flashMap.containsKey(KEY_NOTIFICATION_SEVERITY)
);
}
/**
* Da usare direttamente solo quando si vuole fare un redirect dopo aver mostrato un messaggio.
* Se chiamato tante volte, i messaggi si sommano e vengono mostrati tutti all'utente.
* @param title
* @param message
* @param severity a string like YadaConstants.VAL_NOTIFICATION_SEVERITY_OK
* @param redirectSemiurl e.g. "/user/profile"
* @param model
* @see YadaConstants
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void notifyModal(String title, String message, String severity, String redirectSemiurl, Model model) {
if (severity==VAL_NOTIFICATION_SEVERITY_ERROR) {
// Tutte le notifiche di errore vengono loggate a warn (potrebbero non essere degli errori del programma)
log.warn("notifyModal: {} - {}", title, message);
}
// Mette nel model tre array di stringhe che contengono titolo, messaggio e severity.
if (!model.containsAttribute(KEY_NOTIFICATION_TITLE)) {
List<String> titles = new ArrayList<String>();
List<String> bodies = new ArrayList<String>();
List<String> severities = new ArrayList<String>();
model.addAttribute(KEY_NOTIFICATION_TITLE, titles);
model.addAttribute(KEY_NOTIFICATION_BODY, bodies);
model.addAttribute(KEY_NOTIFICATION_SEVERITY, severities);
}
// Aggiunge i nuovi valori
Map<String, Object> modelMap = model.asMap();
((List<String>)modelMap.get(KEY_NOTIFICATION_TITLE)).add(title);
((List<String>)modelMap.get(KEY_NOTIFICATION_BODY)).add(message);
((List<String>)modelMap.get(KEY_NOTIFICATION_SEVERITY)).add(severity);
if (redirectSemiurl!=null) {
model.addAttribute(KEY_NOTIFICATION_REDIRECT, redirectSemiurl);
}
String newTotalSeverity = calcTotalSeverity(modelMap, severity);
model.addAttribute(KEY_NOTIFICATION_TOTALSEVERITY, newTotalSeverity);
}
/**
* Return true if modalError has been called before
* @param model
* @return
* @deprecated Use YadaNotify instead
*/
@Deprecated
public boolean isModalError(Model model) {
return model.asMap().containsValue(VAL_NOTIFICATION_SEVERITY_ERROR);
}
/**
* Return true if for this thread the notifyModal (or a variant) has been called
* @param model
* @return
* @deprecated Use YadaNotify instead
*/
@Deprecated
public boolean isNotifyModalRequested(Model model) {
return model.containsAttribute(KEY_NOTIFICATION_TITLE);
}
@Deprecated
private String calcTotalSeverity(Map<String, ?> modelMap, String lastSeverity) {
// Algoritmo:
// - per cui
String newTotalSeverity = lastSeverity;
String currentTotalSeverity = (String) modelMap.get(KEY_NOTIFICATION_TOTALSEVERITY);
if (VAL_NOTIFICATION_SEVERITY_ERROR.equals(currentTotalSeverity)) {
return currentTotalSeverity; // ERROR wins always
}
if (VAL_NOTIFICATION_SEVERITY_OK.equals(lastSeverity) && VAL_NOTIFICATION_SEVERITY_INFO.equals(currentTotalSeverity)) {
newTotalSeverity = currentTotalSeverity; // INFO wins over OK
}
return newTotalSeverity;
}
// private void notifyModalSetValue(String title, String message, String severity, String redirectSemiurl, Model model) {
// model.addAttribute(KEY_NOTIFICATION_TITLE, title);
// model.addAttribute(KEY_NOTIFICATION_BODY, message);
// model.addAttribute(KEY_NOTIFICATION_SEVERITY, severity);
// if (redirectSemiurl!=null) {
// model.addAttribute(KEY_NOTIFICATION_REDIRECT, redirectSemiurl);
public String getClientIp(HttpServletRequest request) {
String remoteAddr = request.getRemoteAddr();
String forwardedFor = request.getHeader("X-Forwarded-For");
String remoteIp = "?";
if (!StringUtils.isBlank(remoteAddr)) {
remoteIp = remoteAddr;
}
if (!StringUtils.isBlank(forwardedFor)) {
remoteIp = "[for " + forwardedFor + "]";
}
return remoteIp;
}
/**
*
* @param message text to be displayed (can be null for default value)
* @param confirmButton text of the confirm button (can be null for default value)
* @param cancelButton text of the cancel button (can be null for default value)
* @param model
*/
public String modalConfirm(String message, String confirmButton, String cancelButton, Model model) {
return modalConfirm(message, confirmButton, cancelButton, model, false, false);
}
/**
* Show the confirm modal and reloads when the confirm button is pressed, adding the confirmation parameter to the url.
* The modal will be opened on load.
* Usually used by non-ajax methods.
* @param message text to be displayed (can be null for default value)
* @param confirmButton text of the confirm button (can be null for default value)
* @param cancelButton text of the cancel button (can be null for default value)
* @param model
*/
public String modalConfirmAndReload(String message, String confirmButton, String cancelButton, Model model) {
return modalConfirm(message, confirmButton, cancelButton, model, true, true);
}
/**
* Show the confirm modal and optionally reloads when the confirm button is pressed
* @param message text to be displayed (can be null for default value)
* @param confirmButton text of the confirm button (can be null for default value)
* @param cancelButton text of the cancel button (can be null for default value)
* @param model
* @param reloadOnConfirm (optional) when true, the browser will reload on confirm, adding the confirmation parameter to the url
* @param openModal (optional) when true, the modal will be opened. To be used when the call is not ajax
*/
public String modalConfirm(String message, String confirmButton, String cancelButton, Model model, Boolean reloadOnConfirm, Boolean openModal) {
model.addAttribute("message", message);
model.addAttribute("confirmButton", confirmButton);
model.addAttribute("cancelButton", cancelButton);
if (openModal) {
model.addAttribute("openModal", true);
}
if (reloadOnConfirm) {
model.addAttribute("reloadOnConfirm", true);
}
return "/yada/modalConfirm";
}
/**
* Add a script id to call when opening the notification modal
* @param scriptId
* @param model
* @deprecated Use YadaNotify instead
*/
@Deprecated
public void callScriptOnModal(String scriptId, Model model) {
if (!model.containsAttribute(KEY_NOTIFICATION_CALLSCRIPT)) {
List<String> scriptIds = new ArrayList<String>();
model.addAttribute(KEY_NOTIFICATION_CALLSCRIPT, scriptIds);
}
Map<String, Object> modelMap = model.asMap();
((List<String>)modelMap.get(KEY_NOTIFICATION_CALLSCRIPT)).add(scriptId);
}
} |
public class Brlapi {
private long handle;
private int fileDescriptor;;
private BrlapiSettings settings;
public Brlapi (BrlapiSettings settings) throws BrlapiError {
this.settings = new BrlapiSettings();
fileDescriptor = initializeConnection(settings, this.settings);
}
private final native int initializeConnection(
BrlapiSettings clientSettings,
BrlapiSettings usedSettings
) throws BrlapiError;
public final native void closeConnection();
public final static native byte[] loadAuthKey(String path);
public BrlapiSettings getSettings () {
return settings;
}
public int getFileDescriptor () {
return fileDescriptor;
}
public final native String getDriverId () throws BrlapiError;
public final native String getDriverName () throws BrlapiError;
public final native BrlapiSize getDisplaySize () throws BrlapiError;
/*public final native byte[] getDriverInfo() throws BrlapiError;*/
public final native int enterTtyMode (int tty, String driver) throws BrlapiError;
public final native int getTtyPath (int ttys[], String driver) throws BrlapiError;
public final native void leaveTtyMode () throws BrlapiError;
public final native void setFocus (int tty) throws BrlapiError;
public final native void writeText (int cursor, String str) throws BrlapiError;
public final native int writeDots (byte str[]) throws BrlapiError;
public final native void write (BrlapiWriteStruct s) throws BrlapiError;
public final native long readKey(boolean block) throws BrlapiError;
public final native void ignoreKeyRange (long x, long y) throws BrlapiError;
public final native void unignoreKeyRange (long x, long y) throws BrlapiError;
public final native void ignoreKeySet (long s[]) throws BrlapiError;
public final native void unignoreKeySet (long s[]) throws BrlapiError;
public final native void enterRawMode (String driver) throws BrlapiError;
public final native void leaveRawMode () throws BrlapiError;
public final native int sendRaw (byte buf[]) throws BrlapiError;
public final native int recvRaw (byte buf[]) throws BrlapiError;
public final static native String packetType (long type);
} |
package com.funnyhatsoftware.spacedock.data;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
public class EquippedShip extends EquippedShipBase {
private static final String TAG = "EquippedShip";
public EquippedShip() {
super();
}
public EquippedShip(Ship inShip, boolean establishPlaceholders) {
super();
mShip = inShip;
if (establishPlaceholders) {
establishPlaceholders();
}
}
public EquippedShip(Ship inShip) {
super();
mShip = inShip;
}
public boolean getIsResourceSideboard() {
return getShip() == null;
}
public EquippedUpgrade addUpgrade(Upgrade upgrade) {
return addUpgrade(upgrade, null, true);
}
public EquippedUpgrade addUpgrade(Upgrade upgrade, EquippedUpgrade maybeReplace,
boolean establishPlaceholders) {
EquippedUpgrade eu = new EquippedUpgrade();
if (upgrade == null) {
return eu;
}
String upType = upgrade.getUpType();
eu.setUpgrade(upgrade);
if (!upgrade.isPlaceholder()) {
EquippedUpgrade ph = findPlaceholder(upType);
if (ph != null) {
removeUpgrade(ph);
}
}
int limit = upgrade.limitForShip(this);
int current = equipped(upType);
if (current == limit) {
if (maybeReplace == null) {
maybeReplace = firstUpgrade(upType);
}
removeUpgrade(maybeReplace, false);
}
mUpgrades.add(eu);
eu.setEquippedShip(this);
if (establishPlaceholders) {
establishPlaceholders();
}
return eu;
}
private EquippedUpgrade firstUpgrade(String upType) {
for (EquippedUpgrade eu : mUpgrades) {
if (upType.equals(eu.getUpgrade().getUpType())) {
return eu;
}
}
return null;
}
private EquippedUpgrade findPlaceholder(String upType) {
for (EquippedUpgrade eu : mUpgrades) {
if (eu.isPlaceholder() && upType.equals(eu.getUpgrade().getUpType())) {
return eu;
}
}
return null;
}
public void removeUpgrade(EquippedUpgrade eu) {
removeUpgrade(eu, true);
}
private void removeUpgrade(EquippedUpgrade eu, boolean establishPlaceholders) {
if (eu != null) {
mUpgrades.remove(eu);
eu.setEquippedShip(null);
if (establishPlaceholders) {
establishPlaceholders();
}
}
}
public int calculateCost() {
int cost = 0;
if (mShip != null) {
cost = mShip.getCost();
}
for (EquippedUpgrade eu : mUpgrades) {
cost += eu.calculateCost();
}
if (false && getFlagship() != null) { // TODO: Remove this when flagships can be assigned to ships
cost += 10;
}
return cost;
}
public String getTitle() {
if (getIsResourceSideboard()) {
return getSquad().getResource().getTitle();
}
return getShip().getTitle();
}
public String getPlainDescription() {
if (getIsResourceSideboard()) {
return getSquad().getResource().getTitle();
}
return getShip().getPlainDescription();
}
String getDescriptiveTitle() {
if (getIsResourceSideboard()) {
return getSquad().getResource().getTitle();
}
String s = getShip().getDescriptiveTitle();
if (getFlagship() != null) {
s = s + " [FS]";
}
return s;
}
String getUpgradesDescription() {
ArrayList<EquippedUpgrade> sortedUpgrades = getSortedUpgrades();
ArrayList<String> upgradeTitles = new ArrayList<String>();
for (EquippedUpgrade eu : sortedUpgrades) {
Upgrade upgrade = eu.getUpgrade();
if (!upgrade.isPlaceholder()) {
upgradeTitles.add(upgrade.getTitle());
}
}
return TextUtils.join(", ", upgradeTitles);
}
private ArrayList<EquippedUpgrade> getSortedUpgrades() {
ArrayList<EquippedUpgrade> sortedUpgrades = getUpgrades();
Comparator<EquippedUpgrade> comparator = new Comparator<EquippedUpgrade>() {
@Override
public int compare(EquippedUpgrade arg0, EquippedUpgrade arg1) {
return arg0.compareTo(arg1);
}
};
Collections.sort(sortedUpgrades, comparator);
return sortedUpgrades;
}
public ArrayList<EquippedUpgrade> getAllUpgradesExceptPlaceholders() {
ArrayList<EquippedUpgrade> np = new ArrayList<EquippedUpgrade>();
for (EquippedUpgrade eu : getUpgrades()) {
if (!eu.isCaptain() && !eu.isPlaceholder()) {
np.add(eu);
}
}
return np;
}
public String factionCode() {
return getShip().factionCode();
}
public int getBaseCost() {
if (getIsResourceSideboard()) {
return getSquad().getResource().getCost();
}
return getShip().getCost();
}
public int getAttack() {
int v = 0;
Ship ship = getShip();
if (ship != null) {
v = ship.getAttack();
}
Flagship flagship = getFlagship();
if (flagship != null) {
v += flagship.getAttack();
}
return v;
}
public int getAgility() {
int v = 0;
Ship ship = getShip();
if (ship != null) {
v = ship.getAgility();
}
Flagship flagship = getFlagship();
if (flagship != null) {
v += flagship.getAgility();
}
return v;
}
public int getHull() {
int v = 0;
Ship ship = getShip();
if (ship != null) {
v = ship.getHull();
}
Flagship flagship = getFlagship();
if (flagship != null) {
v += flagship.getHull();
}
return v;
}
public int getShield() {
int v = 0;
Ship ship = getShip();
if (ship != null) {
v = ship.getShield();
}
Flagship flagship = getFlagship();
if (flagship != null) {
v += flagship.getShield();
}
return v;
}
public int getTech() {
int v = 0;
Ship ship = getShip();
if (ship != null) {
v = ship.getTech();
}
Flagship flagship = getFlagship();
if (flagship != null) {
v += flagship.getTech();
}
Captain captain = getCaptain();
if (captain != null) {
v += captain.additionalTechSlots();
}
return v;
}
public int getTalent() {
int v = 0;
Captain captain = getCaptain();
if (captain != null) {
v = captain.getTalent();
}
Flagship flagship = getFlagship();
if (flagship != null) {
v += flagship.getTalent();
}
return v;
}
public int getWeapon() {
int v = 0;
Ship ship = getShip();
if (ship != null) {
v = ship.getWeapon();
}
Flagship flagship = getFlagship();
if (flagship != null) {
v += flagship.getWeapon();
}
return v;
}
public int getCrew() {
int v = 0;
Ship ship = getShip();
if (ship != null) {
v = ship.getCrew();
}
Flagship flagship = getFlagship();
if (flagship != null) {
v += flagship.getCrew();
}
Captain captain = getCaptain();
if (captain != null) {
v += captain.additionalCrewSlots();
}
return v;
}
public EquippedUpgrade getEquippedCaptain() {
for (EquippedUpgrade eu : getUpgrades()) {
Upgrade upgrade = eu.getUpgrade();
if (upgrade.getUpType().equals("Captain")) {
return eu;
}
}
return null;
}
public Captain getCaptain() {
EquippedUpgrade equippedCaptain = getEquippedCaptain();
if (equippedCaptain == null) {
return null;
}
return (Captain) equippedCaptain.getUpgrade();
}
public void establishPlaceholders() {
if (getCaptain() == null) {
String faction = shipFaction();
if (faction.equals("Federation") || faction.equals("Bajoran")) {
faction = "Federation";
}
Upgrade zcc = Captain.zeroCostCaptain(faction);
addUpgrade(zcc, null, false);
}
establishPlaceholdersForType("Talent", getTalent());
establishPlaceholdersForType("Crew", getCrew());
establishPlaceholdersForType("Weapon", getWeapon());
establishPlaceholdersForType("Tech", getTech());
}
private void establishPlaceholdersForType(String upType, int limit) {
int current = equipped(upType);
if (current > limit) {
removeOverLimit(upType, current, limit);
} else {
for (int i = current; i < limit; ++i) {
Upgrade upgrade = Upgrade.placeholder(upType);
addUpgrade(upgrade, null, false);
}
}
}
private void removeOverLimit(String upType, int current, int limit) {
int amountToRemove = current - limit;
removeUpgradesOfType(upType, amountToRemove);
}
private void removeUpgradesOfType(String upType, int targetCount) {
ArrayList<EquippedUpgrade> onesToRemove = new ArrayList<EquippedUpgrade>();
ArrayList<EquippedUpgrade> upgrades = getSortedUpgrades();
for (EquippedUpgrade eu : upgrades) {
if (eu.isPlaceholder() && upType.equals(eu.getUpgrade().getUpType())) {
onesToRemove.add(eu);
}
if (onesToRemove.size() == targetCount) {
break;
}
}
if (onesToRemove.size() != targetCount) {
for (EquippedUpgrade eu : upgrades) {
if (upType.equals(eu.getUpgrade().getUpType())) {
onesToRemove.add(eu);
}
if (onesToRemove.size() == targetCount) {
break;
}
}
}
for (EquippedUpgrade eu : onesToRemove) {
removeUpgrade(eu, false);
}
}
private int equipped(String upType) {
int count = 0;
ArrayList<EquippedUpgrade> upgrades = getSortedUpgrades();
for (EquippedUpgrade eu : upgrades) {
if (upType.equals(eu.getUpgrade().getUpType())) {
count += 1;
}
}
return count;
}
public String shipFaction() {
Ship ship = getShip();
if (ship == null) {
return "Federation";
}
return ship.getFaction();
}
public Explanation canAddUpgrade(Upgrade upgrade) {
String msg = String.format("Can't add %s to %s", upgrade.getPlainDescription(),
getPlainDescription());
String upgradeSpecial = upgrade.getSpecial();
if (upgradeSpecial.equals("OnlyJemHadarShips")) {
if (!getShip().isJemhadar()) {
return new Explanation(msg,
"This upgrade can only be added to Jem'hadar ships.");
}
}
if (upgradeSpecial.equals("OnlyForKlingonCaptain")) {
if (!getCaptain().isKlingon()) {
return new Explanation(msg,
"This upgrade can only be added to a Klingon Captain.");
}
}
if (upgradeSpecial.equals("OnlyForRomulanScienceVessel")
|| upgradeSpecial.equals("OnlyForRaptorClassShips")) {
String legalShipClass = upgrade.targetShipClass();
if (!legalShipClass.equals(getShip().getShipClass())) {
return new Explanation(msg, String.format(
"This upgrade can only be installed on ships of class %s.", legalShipClass));
}
}
int limit = upgrade.limitForShip(this);
if (limit <= 0) {
String expl;
if (upgrade.isTalent()) {
expl = String.format("This ship's captain has no %s upgrade symbols.",
upgrade.getUpType());
} else {
expl = String.format("This ship has no %s upgrade symbols on its ship card.",
upgrade.getUpType());
}
return new Explanation(msg, expl);
}
return Explanation.SUCCESS;
}
public EquippedUpgrade containsUpgrade(Upgrade theUpgrade) {
for (EquippedUpgrade eu : mUpgrades) {
if (eu.getUpgrade() == theUpgrade) {
return eu;
}
}
return null;
}
public EquippedUpgrade containsUpgradeWithName(String theName) {
for (EquippedUpgrade eu : mUpgrades) {
if (eu.getUpgrade().getTitle().equals(theName)) {
return eu;
}
}
return null;
}
public EquippedShip duplicate() {
// TODO need to implement duplicate
throw new RuntimeException("Not yet implemented");
}
public void removeFlagship() {
setFlagship(null);
}
public Object getFlagshipFaction() {
Flagship flagship = getFlagship();
if (flagship == null) {
return "";
}
return flagship.getFaction();
}
public EquippedUpgrade mostExpensiveUpgradeOfFaction(String faction) {
ArrayList<EquippedUpgrade> allUpgrades = allUpgradesOfFaction(faction);
if (allUpgrades.isEmpty()) {
return null;
}
EquippedUpgrade mostExpensive = allUpgrades.get(0);
return mostExpensive.isPlaceholder() ? null : mostExpensive;
}
public EquippedUpgrade mostExpensiveUpgradeOfFactionAndType(String faction, String upType) {
ArrayList<EquippedUpgrade> allUpgrades = allUpgradesOfFactionAndType(faction, upType);
if (allUpgrades.isEmpty()) {
return null;
}
EquippedUpgrade mostExpensive = allUpgrades.get(0);
return mostExpensive.isPlaceholder() ? null : mostExpensive;
}
public ArrayList<EquippedUpgrade> allUpgradesOfFaction(
String faction) {
return allUpgradesOfFactionAndType(faction, null);
}
public ArrayList<EquippedUpgrade> allUpgradesOfFactionAndType(
String faction, String upType) {
ArrayList<EquippedUpgrade> allUpgrades = new ArrayList<EquippedUpgrade>();
for (EquippedUpgrade eu : mUpgrades) {
if (!eu.getUpgrade().isCaptain()) {
if (upType == null || upType.equals(eu.getUpgrade().getUpType())) {
if (faction == null || faction.equals(eu.getUpgrade().getFaction())) {
allUpgrades.add(eu);
}
}
}
}
if (allUpgrades.size() > 0) {
if (allUpgrades.size() > 1) {
Comparator<EquippedUpgrade> comparator = new Comparator<EquippedUpgrade>() {
@Override
public int compare(EquippedUpgrade a, EquippedUpgrade b) {
int aCost = a.getUpgrade().getCost();
int bCost = b.getUpgrade().getCost();
if (aCost == bCost) {
return 0;
} else if (aCost > bCost) {
return 1;
}
return -1;
}
};
Collections.sort(allUpgrades, comparator);
}
}
return allUpgrades;
}
// Slot management
public static final int SLOT_TYPE_INVALID = -1;
public static final int SLOT_TYPE_CAPTAIN = 0;
public static final int SLOT_TYPE_CREW = 1;
public static final int SLOT_TYPE_WEAPON = 2;
public static final int SLOT_TYPE_TECH = 3;
public static final int SLOT_TYPE_TALENT = 4;
public static final int SLOT_TYPE_SHIP = 1000;
public static Class[] CLASS_FOR_SLOT = new Class[] {
Captain.class,
Crew.class,
Weapon.class,
Tech.class,
Talent.class,
};
private int getUpgradeIndexOfClass(Class slotClass, int slotIndex) {
for (int i = 0; i < mUpgrades.size(); i++) {
EquippedUpgrade equippedUpgrade = mUpgrades.get(i);
if (equippedUpgrade.getUpgrade().getClass() == slotClass) {
slotIndex
if (slotIndex < 0) {
return i;
}
}
}
return -1;
}
public int getUpgradeIndexAtSlot(int slotType, int slotIndex) {
Class<?> slotClass = CLASS_FOR_SLOT[slotType];
return getUpgradeIndexOfClass(slotClass, slotIndex);
}
public EquippedUpgrade getUpgradeAtSlot(int slotType, int slotIndex) {
int upgradeIndex = getUpgradeIndexAtSlot(slotType, slotIndex);
if (upgradeIndex < 0) {
return null;
}
return mUpgrades.get(upgradeIndex);
}
public Explanation tryEquipUpgrade(Squad squad, int slotType, int slotIndex, String externalId) {
Upgrade upgrade;
if (externalId != null && !externalId.isEmpty()) {
if (slotType == SLOT_TYPE_CAPTAIN) {
upgrade = Universe.getUniverse().getCaptain(externalId);
Explanation explanation = squad.canAddCaptain((Captain) upgrade, this);
if (!explanation.canAdd) {
return explanation; // disallowed, abort!
}
} else {
upgrade = Universe.getUniverse().getUpgrade(externalId);
Explanation explanation = squad.canAddUpgrade(upgrade, this);
if (!explanation.canAdd) {
return explanation; // disallowed, abort!
}
}
} else {
// No ID passed, use placeholder
upgrade = Upgrade.placeholder(CLASS_FOR_SLOT[slotType].getSimpleName());
}
EquippedUpgrade newEu = new EquippedUpgrade();
newEu.setUpgrade(upgrade);
int oldEuIndex = getUpgradeIndexAtSlot(slotType, slotIndex);
if (oldEuIndex >= 0) {
// swap out old upgrade
EquippedUpgrade oldUpgrade = mUpgrades.get(oldEuIndex);
oldUpgrade.setEquippedShip(null);
mUpgrades.set(oldEuIndex, newEu);
} else {
mUpgrades.add(newEu);
}
newEu.setEquippedShip(this);
if (slotType == SLOT_TYPE_CAPTAIN) {
// on captain swap, add placeholders, or clear talent/tech slots as needed
establishPlaceholdersForType("Talent", getTalent());
establishPlaceholdersForType("Tech", getTech());
}
return Explanation.SUCCESS;
}
@SuppressWarnings("unused")
public void dump() {
for (Class c : CLASS_FOR_SLOT) {
int i = 0;
Log.d(TAG, "Equipped " + c.getSimpleName() + "s:");
for (EquippedUpgrade equippedUpgrade : mUpgrades) {
if (c.isInstance(equippedUpgrade.getUpgrade())) {
if (equippedUpgrade.isPlaceholder()) {
Log.d(TAG, " " + i + ", PLACEHOLDER upgrade is "
+ equippedUpgrade.getTitle());
} else {
Log.d(TAG, " " + i + ", upgrade is " + equippedUpgrade.getTitle());
}
i++;
}
}
}
}
public void getFactions(HashSet<String> factions) {
if (mShip != null) {
String faction = mShip.getFaction();
if (faction != null) {
factions.add(faction);
}
for (EquippedUpgrade eu : mUpgrades) {
faction = eu.getFaction();
if (faction != null) {
factions.add(faction);
}
}
}
}
public JSONObject asJSON() throws JSONException {
JSONObject o = new JSONObject();
Ship ship = getShip();
if (ship == null) {
o.put(JSONLabels.JSON_LABEL_SIDEBOARD, true);
} else {
o.put(JSONLabels.JSON_LABEL_SHIP_ID, ship.getExternalId());
o.put(JSONLabels.JSON_LABEL_SHIP_TITLE, ship.getTitle());
Flagship flagship = getFlagship();
if (flagship != null) {
o.put(JSONLabels.JSON_LABEL_FLAGSHIP, flagship.getExternalId());
}
}
o.put(JSONLabels.JSON_LABEL_CAPTAIN, getEquippedCaptain().asJSON());
ArrayList<EquippedUpgrade> sortedUpgrades = getSortedUpgrades();
JSONArray upgrades = new JSONArray();
int index = 0;
for (EquippedUpgrade upgrade : sortedUpgrades) {
if (!upgrade.isPlaceholder() && !upgrade.isCaptain()) {
upgrades.put(index++, upgrade.asJSON());
}
}
o.put(JSONLabels.JSON_LABEL_UPGRADES, upgrades);
return o;
}
public void importUpgrades(Universe universe, JSONObject shipData, boolean strict)
throws JSONException {
JSONObject captainObject = shipData.optJSONObject(JSONLabels.JSON_LABEL_CAPTAIN);
if (captainObject != null) {
String captainId = captainObject.optString(JSONLabels.JSON_LABEL_UPGRADE_ID);
Captain captain = universe.getCaptain(captainId);
addUpgrade(captain, null, false);
} else if (strict) {
throw new RuntimeException("Can't find captain object.");
}
String flagshipId = shipData.optString(JSONLabels.JSON_LABEL_FLAGSHIP);
if (flagshipId.length() > 0) {
Flagship flagship = universe.getFlagship(flagshipId);
if (strict && flagship == null) {
throw new RuntimeException("Can't find flagship '" + flagshipId + "'");
}
setFlagship(flagship);
}
JSONArray upgrades = shipData.optJSONArray(JSONLabels.JSON_LABEL_UPGRADES);
if (upgrades != null) {
for (int i = 0; i < upgrades.length(); ++i) {
JSONObject upgradeData = upgrades.getJSONObject(i);
String upgradeId = upgradeData.optString(JSONLabels.JSON_LABEL_UPGRADE_ID);
Upgrade upgrade = universe.getUpgrade(upgradeId);
if (upgrade != null) {
EquippedUpgrade eu = addUpgrade(upgrade, null, false);
if (upgradeData.optBoolean(JSONLabels.JSON_LABEL_COST_IS_OVERRIDDEN)) {
eu.setOverridden(true);
eu.setOverriddenCost(upgradeData
.optInt(JSONLabels.JSON_LABEL_OVERRIDDEN_COST));
}
} else if (strict) {
throw new RuntimeException("Can't find upgrade '" + upgrade + "'");
}
}
}
establishPlaceholders();
}
} |
package org.jboss.marshalling;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* A class resolver which uses the context classloader to resolve classes.
*/
public class ContextClassResolver extends AbstractClassResolver {
private static final PrivilegedAction<ClassLoader> classLoaderAction = new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
};
/**
* Construct a new instance.
*/
public ContextClassResolver() {
}
/** {@inheritDoc} */
protected ClassLoader getClassLoader() {
return AccessController.doPrivileged(classLoaderAction);
}
} |
package uk.gov.dvla.services.enquiry;
import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.domain.ServiceResult;
import uk.gov.dvla.services.ManagedService;
import uk.gov.dvla.services.NamedService;
public interface DriverEnquiry extends ManagedService
{
public static final String DRIVER_URI = "/driver/";
public static final String FORENAME_PARAM = "fn";
public static final String SURNAME_PARAM = "sn";
public static final String DOB_PARAM = "d";
public static final String GENDER_PARAM = "g";
public static final String POSTCODE_PARAM = "p";
public Driver get(String dln);
public Driver get(Person person);
} |
package com.messagebird;
import com.messagebird.exceptions.GeneralException;
import com.messagebird.objects.*;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
import static org.junit.Assert.assertNull;
public class PurchasedNumbersFilterTest {
@Test
public void testDefaults() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
// Test
assertEquals(10, filter.getLimit());
assertEquals(0, filter.getOffset());
assertEquals(0, filter.getFeatures().size());
assertEquals(0, filter.getTags().size());
assertNull(filter.getNumber());
assertNull(filter.getRegion());
assertNull(filter.getLocality());
assertNull(filter.getType());
}
@Test
public void testAddingFeatures() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
assertEquals(EnumSet.noneOf(PhoneNumberFeature.class), filter.getFeatures());
// Test can add a feature
filter.addFeature(PhoneNumberFeature.SMS);
assertEquals(EnumSet.of(PhoneNumberFeature.SMS), filter.getFeatures());
// Test can have multiple features
filter.addFeature(PhoneNumberFeature.VOICE);
assertEquals(EnumSet.of(PhoneNumberFeature.SMS, PhoneNumberFeature.VOICE), filter.getFeatures());
// Test shouldn't have more than one of each
filter.addFeature(PhoneNumberFeature.SMS);
assertEquals(EnumSet.of(PhoneNumberFeature.SMS, PhoneNumberFeature.VOICE), filter.getFeatures());
filter.addFeature(PhoneNumberFeature.MMS);
assertEquals(EnumSet.of(PhoneNumberFeature.SMS, PhoneNumberFeature.VOICE, PhoneNumberFeature.MMS), filter.getFeatures());
}
@Test
public void testAddingMultipleFeatures() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
assertEquals(EnumSet.noneOf(PhoneNumberFeature.class), filter.getFeatures());
// Test
filter.addFeature(PhoneNumberFeature.SMS, PhoneNumberFeature.VOICE);
assertEquals(EnumSet.of(PhoneNumberFeature.SMS, PhoneNumberFeature.VOICE), filter.getFeatures());
}
@Test
public void testRemovingFeatures() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
// Test
filter.addFeature(PhoneNumberFeature.SMS, PhoneNumberFeature.MMS, PhoneNumberFeature.VOICE);
assertEquals(EnumSet.of(PhoneNumberFeature.SMS, PhoneNumberFeature.VOICE, PhoneNumberFeature.MMS), filter.getFeatures());
filter.removeFeature(PhoneNumberFeature.VOICE);
assertEquals(EnumSet.of(PhoneNumberFeature.SMS, PhoneNumberFeature.MMS), filter.getFeatures());
filter.removeFeature(PhoneNumberFeature.VOICE);
assertEquals(EnumSet.of(PhoneNumberFeature.SMS, PhoneNumberFeature.MMS), filter.getFeatures());
filter.removeFeature(PhoneNumberFeature.SMS, PhoneNumberFeature.MMS);
assertEquals(EnumSet.noneOf(PhoneNumberFeature.class), filter.getFeatures());
}
@Test
public void testAddingTags() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
assertArrayEquals(new String[]{}, filter.getTags().toArray());
// Test
filter.addTag("TEST_TAG");
assertArrayEquals(new String[]{"TEST_TAG"}, filter.getTags().toArray());
filter.addTag("Another test tag");
assertArrayEquals(new String[]{"TEST_TAG", "Another test tag"}, filter.getTags().toArray());
filter.addTag("a", "b", "c");
assertArrayEquals(new String[]{"TEST_TAG", "Another test tag", "a", "b", "c"}, filter.getTags().toArray());
}
@Test
public void testAddingDuplicateTags() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
filter.addTag("a");
filter.addTag("a");
filter.addTag("a", "b", "b", "c", "b");
assertArrayEquals(new String[]{"a", "b", "c"}, filter.getTags().toArray());
}
@Test
public void testRemoveTags() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
filter.addTag("a", "b", "c", "d");
assertArrayEquals(new String[]{"a", "b", "c", "d"}, filter.getTags().toArray());
// Test
filter.removeTag("b");
assertArrayEquals(new String[]{"a", "c", "d"}, filter.getTags().toArray());
filter.removeTag("d");
assertArrayEquals(new String[]{"a", "c"}, filter.getTags().toArray());
filter.removeTag("b", "c", "d");
assertArrayEquals(new String[]{"a"}, filter.getTags().toArray());
}
@Test
public void testClearTags() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
filter.addTag("a", "b", "c", "d");
assertArrayEquals(new String[]{"a", "b", "c", "d"}, filter.getTags().toArray());
// Test
filter.clearTags();
assertArrayEquals(new String[]{}, filter.getTags().toArray());
}
@Test
public void testBasicSetters() {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
assertNull(filter.getNumber());
assertNull(filter.getRegion());
assertNull(filter.getLocality());
assertNull(filter.getType());
// Test
filter.setLimit(23);
filter.setOffset(5);
filter.setNumber("TEST_NUMBER");
filter.setRegion("TEST_REGION");
filter.setLocality("TEST_LOCALITY");
filter.setType(PhoneNumberType.MOBILE);
assertEquals(23, filter.getLimit());
assertEquals(5, filter.getOffset());
assertEquals("TEST_NUMBER", filter.getNumber());
assertEquals("TEST_REGION", filter.getRegion());
assertEquals("TEST_LOCALITY", filter.getLocality());
assertEquals(PhoneNumberType.MOBILE, filter.getType());
}
@Test
public void testToHashMapWithDefaultValues() throws GeneralException {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
HashMap<String, Object> map = filter.toHashMap();
assertEquals(10, map.get("limit"));
assertEquals(0, map.get("offset"));
assertEquals(EnumSet.noneOf(PhoneNumberFeature.class), map.get("features"));
assertEquals(new ArrayList<String>(), map.get("tags"));
}
@Test
public void testToHashMapWithAllValues() throws GeneralException {
// Setup
PurchasedNumbersFilter filter = new PurchasedNumbersFilter();
filter.setLimit(42);
filter.setOffset(24);
filter.setNumber("1234567890");
filter.setRegion("My Region");
filter.setLocality("My Locality");
filter.setType(PhoneNumberType.MOBILE);
filter.addFeature(PhoneNumberFeature.SMS, PhoneNumberFeature.VOICE);
filter.addTag("h", "e", "l", "l", "o");
HashMap<String, Object> map = filter.toHashMap();
assertEquals(42, map.get("limit"));
assertEquals(24, map.get("offset"));
assertEquals("1234567890", map.get("number"));
assertEquals("My Region", map.get("region"));
assertEquals("My Locality", map.get("locality"));
assertEquals("mobile", map.get("type").toString());
assertArrayEquals(new PhoneNumberFeature[]{PhoneNumberFeature.SMS, PhoneNumberFeature.VOICE}, ((Collection<Object>) map.get("features")).toArray());
assertArrayEquals(new String[]{"h", "e", "l", "o"}, ((Collection<Object>) map.get("tags")).toArray());
}
} |
package rogel.io.fopl.proof;
import java.util.HashMap;
import rogel.io.fopl.Expression;
import rogel.io.fopl.Substitution;
import rogel.io.fopl.formulas.Formula;
import rogel.io.fopl.formulas.Predicate;
import rogel.io.fopl.terms.Variable;
/**
* A HornClause is a clause with at most one positive (i.e. unnegated) literal. A HornClause has
* many forms, which have different names. Although they are typically represented as a disjunction
* of literals, the explanation that follows represents them as implications (the underlying
* formulae are logically equivalent):
* <ul>
* <li> A HornClause of the form {@code u <- p ^ q ^ r} is called a <i>definite clause</i>. </li>
* <li> A HornClause of the form {@code u} is called a <i>fact</i>. </li>
* <li> A HornClause of the form {@code p ^ q ^ r} is called a <i>goal clause</i>. </li>
* </ul>
* @author recardona
*/
public class HornClause implements Expression {
/**
* This represents the body of the HornClause. e.g. if we had a HornClause
* {@code u <- p ^ q ^ r}, the antecedent would be {@code p ^ q ^ r}.
*/
private Formula antecedent;
/**
* This represents the assertion of the HornClause. e.g. if we had a HornClause
* {@code u <- p ^ q ^ r}, the consequent would be {@code u}.
*/
private Predicate consequent;
/**
* Constructs a HornClause with just one positive literal. This is a HornClause <i>fact</i>.
* @param fact the Predicate this HornClause asserts.
*/
public HornClause(Predicate fact) {
this(fact, null);
}
/**
* Constructor for a HornClause with one positive literal and a goal clause (which represents
* implicitly disjunctive negated literals).
* @param fact the Predicate this HornClause aims to prove.
* @param goal the GoalClause portion of this HornClause.
*/
public HornClause(Predicate fact, Formula goal) {
this.consequent = fact;
this.antecedent = goal;
}
/**
* A HornClause is definite if it has both an antecedent and a consequent.
* @return true if this HornClause is a definite clause.
*/
public boolean isDefiniteClause() {
return (this.antecedent != null && this.consequent != null);
}
/**
* A HornClause is definite if it has a consequent with no antecedent.
* @return true if this HornClause is a fact.
*/
public boolean isFact() {
return (this.antecedent == null && this.consequent != null);
}
/**
* A HornClause is a goal clause if it has an antecedent with no consequent.
* @return true if this HornClause is a goal clause.
*/
public boolean isGoalClause() {
return (this.antecedent != null && this.consequent == null);
}
/**
* @return the antecedent
*/
public Formula getAntecedent() {
return antecedent;
}
/**
* @return the consequent
*/
public Predicate getConsequent() {
return consequent;
}
/*
* (non-Javadoc)
* @see rogel.io.fopl.Expression#replaceVariables(rogel.io.fopl.Substitution)
*/
@Override
public Expression replaceVariables(Substitution substitution) {
// Replace the Variables in each of these Expressions.
Predicate newConsequent = null;
Formula newAntecedent = null;
if(this.consequent != null) {
newConsequent = (Predicate) this.consequent.replaceVariables(substitution);
}
if(this.antecedent != null) {
newAntecedent = (Formula) this.antecedent.replaceVariables(substitution);
}
return new HornClause(newConsequent, newAntecedent);
}
/*
* (non-Javadoc)
* @see rogel.io.fopl.Expression#standardizeVariablesApart(java.util.HashMap)
*/
@Override
public Expression standardizeVariablesApart(HashMap<Variable, Variable> newVariables) {
// Standardize the Variables in each of these Expressions.
Predicate newConsequent = null;
Formula newAntecedent = null;
if(this.consequent != null) {
newConsequent = (Predicate) this.consequent.standardizeVariablesApart(newVariables);
}
if(this.antecedent != null) {
newAntecedent = (Formula) this.antecedent.standardizeVariablesApart(newVariables);
}
return new HornClause(newConsequent, newAntecedent);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
if(antecedent == null) {
return consequent.toString();
}
else {
return consequent.toString() + " :- " + antecedent.toString();
}
}
} |
package org.sagebionetworks.bridge.services;
import static com.google.common.base.Preconditions.checkNotNull;
import org.sagebionetworks.bridge.dao.DistributedLockDao;
import org.sagebionetworks.bridge.exceptions.BridgeServiceException;
import org.sagebionetworks.bridge.exceptions.ConsentRequiredException;
import org.sagebionetworks.bridge.models.SignIn;
import org.sagebionetworks.bridge.models.SignUp;
import org.sagebionetworks.bridge.models.User;
import org.sagebionetworks.bridge.models.UserSession;
import org.sagebionetworks.bridge.models.healthdata.HealthDataKey;
import org.sagebionetworks.bridge.models.studies.ConsentSignature;
import org.sagebionetworks.bridge.models.studies.Study;
import org.sagebionetworks.bridge.models.studies.Tracker;
import org.sagebionetworks.bridge.redis.RedisKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.stormpath.sdk.account.Account;
public class UserAdminServiceImpl implements UserAdminService {
private static final Logger logger = LoggerFactory.getLogger(UserAdminServiceImpl.class);
private AuthenticationServiceImpl authenticationService;
private ConsentService consentService;
private HealthDataService healthDataService;
private StudyService studyService;
private DistributedLockDao lockDao;
public void setAuthenticationService(AuthenticationServiceImpl authenticationService) {
this.authenticationService = authenticationService;
}
public void setConsentService(ConsentService consentService) {
this.consentService = consentService;
}
public void setHealthDataService(HealthDataService healthDataService) {
this.healthDataService = healthDataService;
}
public void setStudyService(StudyService studyService) {
this.studyService = studyService;
}
public void setDistributedLockDao(DistributedLockDao lockDao) {
this.lockDao = lockDao;
}
@Override
public UserSession createUser(SignUp signUp, Study study, boolean signUserIn, boolean consentUser)
throws BridgeServiceException {
checkNotNull(study, "Study cannot be null");
checkNotNull(signUp, "Sign up cannot be null");
checkNotNull(signUp.getEmail(), "Sign up email cannot be null");
authenticationService.signUp(signUp, study, false);
SignIn signIn = new SignIn(signUp.getUsername(), signUp.getPassword());
UserSession newUserSession = null;
try {
newUserSession = authenticationService.signIn(study, signIn);
} catch (ConsentRequiredException e) {
newUserSession = e.getUserSession();
if (consentUser) {
String sig = String.format("[Signature for %s]", signUp.getEmail());;
ConsentSignature consent = ConsentSignature.create(sig, "1989-08-19", null, null);
consentService.consentToResearch(newUserSession.getUser(), consent, study, false);
}
}
if (!signUserIn) {
authenticationService.signOut(newUserSession.getSessionToken());
newUserSession = null;
}
return newUserSession;
}
@Override
public void deleteUser(String userEmail) throws BridgeServiceException {
checkNotNull(userEmail, "User email cannot be null");
int retryCount = 0;
boolean shouldRetry = true;
while (shouldRetry) {
boolean deleted = deleteUserAttempt(userEmail);
if (deleted) {
return;
}
shouldRetry = retryCount < 5;
retryCount++;
try {
Thread.sleep(100 * 2 ^ retryCount);
} catch(InterruptedException ie) {
throw new BridgeServiceException(ie);
}
}
}
private boolean deleteUserAttempt(String userEmail) {
String key = RedisKey.USER_LOCK.getRedisKey(userEmail);
String lock = null;
try {
lock = lockDao.acquireLock(User.class, key);
Account account = authenticationService.getAccount(userEmail);
if (account != null) {
for (Study study : studyService.getStudies()) {
User user = authenticationService.getSessionFromAccount(study, account).getUser();
deleteUserInStudy(study, account, user);
}
account.delete();
}
return true;
} catch(Throwable t) {
return false;
} finally {
lockDao.releaseLock(User.class, key, lock);
}
}
private boolean deleteUserInStudy(Study study, Account account, User user) throws BridgeServiceException {
checkNotNull(study);
checkNotNull(account);
checkNotNull(user);
try {
consentService.withdrawConsent(user, study);
removeAllHealthDataRecords(study, user);
//String healthCode = user.getHealthCode();
//optionsService.deleteAllParticipantOptions(healthCode);
return true;
} catch (Throwable e) {
logger.error(e.getMessage(), e);
return false;
}
}
private void removeAllHealthDataRecords(Study study, User user) throws BridgeServiceException {
// This user may have never consented to research. Ignore if that's the case.
for (String trackerId : study.getTrackers()) {
Tracker tracker = studyService.getTrackerByIdentifier(trackerId);
HealthDataKey key = new HealthDataKey(study, tracker, user);
healthDataService.deleteHealthDataRecords(key);
}
}
} |
package com.alorma.github.ui.activity;
import android.accounts.Account;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.alorma.github.AccountsHelper;
import com.alorma.github.BuildConfig;
import com.alorma.github.GitskariosSettings;
import com.alorma.github.R;
import com.alorma.github.StoreCredentials;
import com.alorma.github.presenter.NavigationFragment;
import com.alorma.github.sdk.bean.dto.response.Notification;
import com.alorma.github.sdk.bean.dto.response.User;
import com.alorma.github.sdk.services.notifications.GetNotificationsClient;
import com.alorma.github.ui.ErrorHandler;
import com.alorma.github.ui.activity.base.BaseActivity;
import com.alorma.github.ui.fragment.GeneralPeopleFragment;
import com.alorma.github.ui.fragment.events.EventsListFragment;
import com.alorma.github.ui.fragment.events.OrgsEventsListFragment;
import com.alorma.github.ui.fragment.gists.AuthUserGistsFragment;
import com.alorma.github.ui.fragment.gists.AuthUserStarredGistsFragment;
import com.alorma.github.ui.fragment.issues.GeneralIssuesListFragment;
import com.alorma.github.ui.fragment.orgs.OrgsMembersFragment;
import com.alorma.github.ui.fragment.orgs.OrgsReposFragment;
import com.alorma.github.ui.fragment.repos.GeneralReposFragment;
import com.alorma.github.ui.utils.DrawerImage;
import com.alorma.github.utils.AccountUtils;
import com.mikepenz.actionitembadge.library.ActionItemBadge;
import com.mikepenz.actionitembadge.library.utils.BadgeStyle;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.ExpandableDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.util.DrawerImageLoader;
import com.mikepenz.octicons_typeface_library.Octicons;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class MainActivity extends BaseActivity implements NavigationFragment.NavigationCallback {
private Account selectedAccount;
private Fragment lastUsedFragment;
private Drawer resultDrawer;
private int notificationsSizeCount = 0;
private NavigationFragment navigationFragment;
private AccountHeader accountHeader;
private Drawer.OnDrawerItemClickListener drawerListener;
private Map<String, List<IDrawerItem>> drawerItems;
public static void startActivity(Activity context) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AccountsManager accountsFragment = new AccountsManager();
List<Account> accounts = accountsFragment.getAccounts(this);
if (accounts.isEmpty()) {
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
finish();
}
setContentView(R.layout.generic_toolbar_responsive);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
boolean changeLog = checkChangeLog();
if (changeLog) {
View view = findViewById(R.id.content);
Snackbar.make(view, R.string.app_updated, Snackbar.LENGTH_LONG).setAction("Changelog", v -> {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://gitskarios.github.io")));
}).show();
}
}
private boolean checkChangeLog() {
if (getSupportFragmentManager() != null) {
int currentVersion = BuildConfig.VERSION_CODE;
GitskariosSettings settings = new GitskariosSettings(this);
int version = settings.getVersion(0);
if (currentVersion > version) {
settings.saveVersion(currentVersion);
return true;
}
}
return false;
}
@Override
public void onStart() {
super.onStart();
if (resultDrawer == null) {
List<Account> accounts = getAccounts();
if (!accounts.isEmpty()) {
selectedAccount = accounts.get(0);
createDrawer();
selectAccount(selectedAccount);
onUserEventsSelected();
}
}
navigationFragment.setNavigationCallback(this);
}
@Override
protected void onStop() {
navigationFragment.setNavigationCallback(null);
super.onStop();
}
private String getUserExtraName(Account account) {
String accountName = getNameFromAccount(account);
String userMail = AccountsHelper.getUserMail(this, account);
String userName = AccountsHelper.getUserName(this, account);
if (!TextUtils.isEmpty(userMail)) {
return userMail;
} else if (!TextUtils.isEmpty(userName)) {
return userName;
}
return accountName;
}
private String getNameFromAccount(Account account) {
return new AccountUtils().getNameFromAccount(account.name);
}
private void createDrawer() {
accountHeader = buildHeader();
DrawerBuilder drawer = new DrawerBuilder();
drawer.withActivity(this);
drawer.withToolbar(getToolbar());
drawer.withAccountHeader(accountHeader, true);
List<IDrawerItem> userItems = getUserDrawerItems();
for (IDrawerItem userItem : userItems) {
drawer.addDrawerItems(userItem);
}
List<IDrawerItem> allProfilesItems = getStickyDrawerItems();
for (IDrawerItem allProfilesItem : allProfilesItems) {
drawer.addStickyDrawerItems(allProfilesItem);
}
drawerListener = (view, position, drawerItem) -> {
if (drawerItem != null) {
long identifier = drawerItem.getIdentifier();
switch ((int) identifier) {
case R.id.nav_drawer_notifications:
openNotifications();
break;
case R.id.nav_drawer_settings:
onSettingsSelected();
break;
case R.id.nav_drawer_sign_out:
signOut();
return true;
}
}
return false;
};
drawer.withOnDrawerItemClickListener(drawerListener);
resultDrawer = drawer.build();
resultDrawer.setSelection(R.id.nav_drawer_events);
}
private List<IDrawerItem> getUserDrawerItems() {
int iconColor = ContextCompat.getColor(this, R.color.icons);
List<IDrawerItem> items = new ArrayList<>();
items.add(new PrimaryDrawerItem().withName(R.string.menu_events)
.withIcon(Octicons.Icon.oct_calendar)
.withIconColor(iconColor)
.withIdentifier(R.id.nav_drawer_events)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onUserEventsSelected();
return false;
}));
items.add(new PrimaryDrawerItem().withName(R.string.navigation_general_repositories)
.withIcon(Octicons.Icon.oct_repo)
.withIconColor(iconColor)
.withIdentifier(R.id.nav_drawer_repositories)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onReposSelected();
return false;
}));
items.add(new PrimaryDrawerItem().withName(R.string.navigation_people)
.withIcon(Octicons.Icon.oct_organization)
.withIconColor(iconColor)
.withIdentifier(R.id.nav_drawer_people)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onPeopleSelected();
return false;
}));
items.add(new PrimaryDrawerItem().withName(R.string.navigation_issues)
.withIcon(Octicons.Icon.oct_issue_opened)
.withIconColor(iconColor)
.withIdentifier(R.id.nav_drawer_issues)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onIssuesSelected();
return false;
}));
PrimaryDrawerItem myGistsDrawerItem = new PrimaryDrawerItem().withName(R.string.navigation_my_gists)
.withIdentifier(R.id.nav_drawer_gists)
.withLevel(2)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onGistsSelected();
return false;
});
PrimaryDrawerItem starredGistsDrawerItem = new PrimaryDrawerItem().withName(R.string.navigation_gists_starred)
.withIdentifier(R.id.nav_drawer_gists_starred)
.withLevel(2)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onStarredGistsSelected();
return false;
});
items.add(new ExpandableDrawerItem().withName(R.string.navigation_gists)
.withSubItems(myGistsDrawerItem, starredGistsDrawerItem)
.withIcon(Octicons.Icon.oct_gist)
.withIconColor(iconColor)
.withSelectable(false));
return items;
}
private List<IDrawerItem> getStickyDrawerItems() {
int iconColor = ContextCompat.getColor(this, R.color.icons);
List<IDrawerItem> items = new ArrayList<>();
items.add(new SecondaryDrawerItem().withName(R.string.menu_enable_notifications)
.withIdentifier(R.id.nav_drawer_notifications)
.withSelectable(false)
.withIcon(Octicons.Icon.oct_bell)
.withIconColor(iconColor));
items.add(new SecondaryDrawerItem().withName(R.string.navigation_settings)
.withIcon(Octicons.Icon.oct_gear)
.withIconColor(iconColor)
.withIdentifier(R.id.nav_drawer_settings)
.withSelectable(false));
items.add(new DividerDrawerItem());
items.add(new SecondaryDrawerItem().withName(R.string.navigation_sign_out)
.withIcon(Octicons.Icon.oct_sign_out)
.withIconColor(iconColor)
.withIdentifier(R.id.nav_drawer_sign_out)
.withSelectable(false));
return items;
}
private AccountHeader buildHeader() {
DrawerImageLoader.init(new DrawerImage());
AccountHeaderBuilder headerBuilder = new AccountHeaderBuilder().withActivity(this).withHeaderBackground(R.color.md_grey_600);
headerBuilder.withOnAccountHeaderListener((view, profile, current) -> {
if (current) {
User user = new User();
user.login = profile.getName().getText();
Intent launcherIntent = ProfileActivity.createLauncherIntent(MainActivity.this, selectedAccount);
startActivity(launcherIntent);
return true;
} else {
if (profile instanceof ProfileDrawerItem) {
List<IDrawerItem> subItems = drawerItems.get(profile.getName().getText());
if (subItems != null && !subItems.isEmpty()) {
resultDrawer.removeAllItems();
for (IDrawerItem subItem : subItems) {
resultDrawer.addItems(subItem);
}
try {
((PrimaryDrawerItem) subItems.get(0)).getOnDrawerItemClickListener().onItemClick(null, 0, subItems.get(0));
} catch (Exception e) {
e.printStackTrace();
}
resultDrawer.setSelection(R.id.nav_drawer_events, true);
}
}
return false;
}
});
ProfileDrawerItem userDrawerItem = getUserDrawerItem();
drawerItems = new HashMap<>();
drawerItems.put(userDrawerItem.getName().getText(), getUserDrawerItems());
userDrawerItem.withSubItems();
headerBuilder.addProfiles(userDrawerItem);
return headerBuilder.build();
}
@NonNull
private ProfileDrawerItem getOrganizationProfileDrawerItem(com.alorma.github.sdk.core.User user) {
return new ProfileDrawerItem().withName(user.getLogin()).withIcon(user.getAvatar());
}
private List<IDrawerItem> getOrganizationProfileSubItems(com.alorma.github.sdk.core.User user) {
int iconColor = ContextCompat.getColor(this, R.color.icons);
List<IDrawerItem> items = new ArrayList<>();
items.add(new PrimaryDrawerItem().withName("Events")
.withIcon(Octicons.Icon.oct_calendar)
.withIconColor(iconColor)
.withIdentifier(R.id.nav_drawer_events)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onOrgEventsSelected(user.getLogin());
return false;
}));
items.add(new PrimaryDrawerItem().withName("Repositories")
.withIcon(Octicons.Icon.oct_repo)
.withIconColor(iconColor)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onOrgReposSelected(user.getLogin());
return false;
}));
items.add(new PrimaryDrawerItem().withName("Members")
.withIcon(Octicons.Icon.oct_organization)
.withIconColor(iconColor)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onOrgPeopleSelected(user.getLogin());
return false;
}));
items.add(new PrimaryDrawerItem().withName("Teams")
.withIcon(Octicons.Icon.oct_jersey)
.withIconColor(iconColor)
.withEnabled(false)
.withOnDrawerItemClickListener((view, position, drawerItem) -> {
onOrgTeamsSelected(user.getLogin());
return false;
}));
return items;
}
private ProfileDrawerItem getUserDrawerItem() {
String userAvatar = AccountsHelper.getUserAvatar(this, selectedAccount);
ProfileDrawerItem userDrawerItem = new ProfileDrawerItem().withName(getUserExtraName(selectedAccount))
.withEmail(getNameFromAccount(selectedAccount))
.withNameShown(false)
.withIdentifier(selectedAccount.hashCode());
if (!TextUtils.isEmpty(userAvatar)) {
userDrawerItem.withIcon(userAvatar);
}
return userDrawerItem;
}
private void selectAccount(final Account account) {
boolean changingUser = selectedAccount != null && !getNameFromAccount(selectedAccount).equals(getNameFromAccount(account));
this.selectedAccount = account;
accountNameProvider.setName(getNameFromAccount(account));
loadUserOrgs();
StoreCredentials credentials = new StoreCredentials(MainActivity.this);
credentials.clear();
String authToken = AccountsHelper.getUserToken(this, account);
credentials.storeToken(authToken);
credentials.storeUsername(getNameFromAccount(account));
credentials.storeUrl(AccountsHelper.getUrl(this, account));
String url = AccountsHelper.getUrl(this, account);
credentials.storeUrl(url);
if (changingUser) {
lastUsedFragment = null;
}
}
private void loadUserOrgs() {
navigationFragment = new NavigationFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(new NavigationFragment(), "navigation");
ft.commit();
navigationFragment.setNavigationCallback(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
menu.findItem(R.id.action_search)
.setIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_search).color(Color.WHITE).sizeDp(24).respectFontBounds(true));
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (notificationsSizeCount > 0) {
BadgeStyle badgeStyle =
new BadgeStyle(BadgeStyle.Style.DEFAULT, R.layout.menu_action_item_badge, getResources().getColor(R.color.accent),
getResources().getColor(R.color.accent_dark), Color.WHITE, getResources().getDimensionPixelOffset(R.dimen.gapMicro));
ActionItemBadge.update(this, menu.findItem(R.id.action_notifications), Octicons.Icon.oct_bell, badgeStyle, notificationsSizeCount);
} else {
ActionItemBadge.hide(menu.findItem(R.id.action_notifications));
}
return super.onPrepareOptionsMenu(menu);
}
@Override
protected void onResume() {
super.onResume();
checkNotifications();
}
private void checkNotifications() {
GetNotificationsClient client = new GetNotificationsClient();
client.observable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Notification>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(List<Notification> notifications) {
notificationsSizeCount = notifications.size();
invalidateOptionsMenu();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_search) {
Intent intent = SearchActivity.launchIntent(this);
startActivity(intent);
} else if (item.getItemId() == R.id.action_notifications) {
openNotifications();
}
return false;
}
private void openNotifications() {
Intent intent = NotificationsActivity.launchIntent(this);
startActivity(intent);
}
private void setFragment(Fragment fragment) {
setFragment(fragment, true);
}
private void setFragment(Fragment fragment, boolean addToBackStack) {
try {
if (fragment != null && getSupportFragmentManager() != null) {
this.lastUsedFragment = fragment;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (ft != null) {
ft.replace(R.id.content, fragment);
if (addToBackStack) {
ft.addToBackStack(null);
}
ft.commit();
}
}
} catch (Exception e) {
ErrorHandler.onError(this, "MainActivity.setFragment()", e);
}
}
public boolean onReposSelected() {
setFragment(GeneralReposFragment.newInstance(), false);
return true;
}
public boolean onPeopleSelected() {
setFragment(GeneralPeopleFragment.newInstance(), false);
return false;
}
public boolean onIssuesSelected() {
setFragment(GeneralIssuesListFragment.newInstance(), false);
return false;
}
public boolean onGistsSelected() {
AuthUserGistsFragment gistsFragment = AuthUserGistsFragment.newInstance();
setFragment(gistsFragment);
return false;
}
public boolean onStarredGistsSelected() {
AuthUserStarredGistsFragment gistsFragment = AuthUserStarredGistsFragment.newInstance();
setFragment(gistsFragment);
return false;
}
public boolean onUserEventsSelected() {
String user = new StoreCredentials(this).getUserName();
if (user != null) {
setFragment(EventsListFragment.newInstance(user), false);
}
return true;
}
public void onOrgEventsSelected(String orgName) {
OrgsEventsListFragment orgsEventsListFragment = OrgsEventsListFragment.newInstance(orgName);
setFragment(orgsEventsListFragment, true);
}
public void onOrgReposSelected(String orgName) {
OrgsReposFragment orgsReposFragment = OrgsReposFragment.newInstance(orgName);
setFragment(orgsReposFragment, true);
}
public void onOrgPeopleSelected(String orgName) {
OrgsMembersFragment orgsMembersFragment = OrgsMembersFragment.newInstance(orgName);
setFragment(orgsMembersFragment, true);
}
public void onOrgTeamsSelected(String orgName) {
}
public boolean onSettingsSelected() {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return false;
}
public void signOut() {
if (selectedAccount != null) {
removeAccount(selectedAccount, () -> {
StoreCredentials storeCredentials = new StoreCredentials(MainActivity.this);
storeCredentials.clear();
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
});
}
}
@Override
public void onBackPressed() {
if (resultDrawer != null && resultDrawer.isDrawerOpen()) {
resultDrawer.closeDrawer();
} else {
if (lastUsedFragment instanceof EventsListFragment) {
finish();
} else if (resultDrawer != null) {
resultDrawer.setSelection(R.id.nav_drawer_events);
}
}
}
@Override
public void onOrganizationsLoaded(List<com.alorma.github.sdk.core.User> organizations) {
if (accountHeader != null) {
for (com.alorma.github.sdk.core.User organization : organizations) {
ProfileDrawerItem drawerItem = getOrganizationProfileDrawerItem(organization);
drawerItems.put(drawerItem.getName().getText(), getOrganizationProfileSubItems(organization));
drawerItem.withSubItems();
accountHeader.addProfiles(drawerItem);
}
}
}
} |
package com.atti.atti_android.list;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.atti.atti_android.R;
import com.atti.atti_android.person.User;
import java.util.ArrayList;
public class UserListAdapter extends BaseAdapter {
private User u;
private Context context;
private ImageView img;
private TextView text;
private ArrayList<User> user;
public UserListAdapter(Context context) {
this.context = context;
user = new ArrayList<User>();
}
@Override
public int getCount() {
return user.size();
}
@Override
public Object getItem(int position) {
return user.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null)
v = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_view_item, null);
if (u instanceof User)
u = (User) getItem(position);
img = (ImageView) v.findViewById(R.id.profile_img);
text = (TextView) v.findViewById(R.id.name);
text.setText(u.getName());
return v;
}
public void add(User user){
this.user.add(user);
}
} |
package com.google.sps;
import com.google.sps.data.Event;
import com.google.sps.data.User;
import com.google.sps.data.VolunteeringOpportunity;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class EventTest {
private static final String HOST_NAME = "Bob Smith";
private static final String EMAIL = "bobsmith@google.com";
private static final User HOST = new User.Builder(HOST_NAME, EMAIL).build();
private static final String EVENT_NAME = "Team Meeting";
private static final String NEW_EVENT_NAME = "Daily Team Meeting";
private static final String DESCRIPTION = "Daily Team Sync";
private static final Set <String> LABELS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("Tech", "Work")));
private static final String LOCATION = "Remote";
private static final LocalDate DATE = LocalDate.of(2020, 7, 24);
private static final String VOLUNTEER_OPPORTUNITY_NAME = "Volunteer";
private static final int NUM_SPOTS_LEFT = 5;
private static final VolunteeringOpportunity OPPORTUNITY = new VolunteeringOpportunity.Builder(VOLUNTEER_OPPORTUNITY_NAME, NUM_SPOTS_LEFT).build();
private static final Set <VolunteeringOpportunity> OPPORTUNITIES = new HashSet<VolunteeringOpportunity> (Arrays.asList(OPPORTUNITY));
private static final User USER1 = new User.Builder("USER1", "USER1@test.com").build();
private static final User USER2 = new User.Builder("USER2", "USER2@test.com").build();
private static final User USER3 = new User.Builder("USER3", "USER3@test.com").build();
private static final Set <User> ATTENDEES = new HashSet<User> (Arrays.asList(USER1, USER2));
private static final Set <User> NEW_ATTENDEES = new HashSet<User> (Arrays.asList(USER1, USER2, USER3));
/* User creating event
* Verify Builder class is created with correct required and optional fields */
@Test
public void testEventBuild() {
Event event = new Event.Builder(EVENT_NAME, DESCRIPTION, LABELS, LOCATION, DATE, HOST).setOpportunities(OPPORTUNITIES).setAttendees(ATTENDEES).build();
Assert.assertEquals(event.getName(), EVENT_NAME);
Assert.assertEquals(event.getDescription(), DESCRIPTION);
Assert.assertEquals(event.getLabels(), LABELS);
Assert.assertEquals(event.getLocation(), LOCATION);
Assert.assertEquals(event.getDate(), DATE);
Assert.assertEquals(event.getHost(), HOST);
Assert.assertEquals(event.getOpportunities(), OPPORTUNITIES);
Assert.assertEquals(event.getAttendees(), ATTENDEES);
}
/* User editing event
* Verify Event mergeFrom setter sets required and optional field */
@Test
public void setEventFields() {
Event event = new Event.Builder(EVENT_NAME, DESCRIPTION, LABELS, LOCATION, DATE, HOST).build();
Event.Builder changedEventBuilder = event.toBuilder().setAttendees(ATTENDEES).build().toBuilder();
changedEventBuilder.mergeFrom(event);
event = changedEventBuilder.build();
event = event.toBuilder().setName(NEW_EVENT_NAME).build();
Assert.assertEquals(event.getAttendees(), ATTENDEES);
Assert.assertEquals(event.getName(), NEW_EVENT_NAME);
}
/* User adding info to event
* Verify adding attendees */
@Test
public void addAttendeeField() {
Event event = new Event.Builder(EVENT_NAME, DESCRIPTION, LABELS, LOCATION, DATE, HOST).setAttendees(ATTENDEES).build();
Event changedEvent = event.toBuilder().addAttendee(USER3).build();
Assert.assertEquals(changedEvent.getAttendees(), NEW_ATTENDEES);
}
} |
package com.example.administrator.my1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//wz 20177411:37:55
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
} |
package com.example.android.quakereport;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* Helper methods related to requesting and receiving earthquake data from USGS.
*/
public final class QueryUtils {
/** Tag for the log message */
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
/**
* Create a private constructor because no one should ever create a {@link QueryUtils} object.
* This class is only meant to hold static variables and methods, which can be accessed
* directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
*/
private QueryUtils() {
}
/**
* Returns new object from the given string url
*/
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
}
catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the url", e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as a response
*/
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
}
/**
* Return a list of {@link Earthquake} objects that has been built up from
* parsing a JSON response.
*/
public static ArrayList<Earthquake> extractEarthquakes() {
// Create an empty ArrayList that we can start adding earthquakes to
ArrayList<Earthquake> earthquakes = new ArrayList<>();
// Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
// is formatted, a JSONException exception object will be thrown.
// Catch the exception so the app doesn't crash, and print the error message to the logs.
try {
// Create a JSONObject from the SAMPLE_JSON_RESPONSE string
JSONObject baseJsonResponse = new JSONObject(SAMPLE_JSON_RESPONSE);
// Extract the JSONArray associated with the key called "features",
// which represent a list of features (or earthquake).
JSONArray earthquakeArray = baseJsonResponse.getJSONArray("features");
// For each earthquake in the earthquakeArray, create an {@link Earthquake} object
for(int i = 0; i < earthquakeArray.length(); i++) {
// Get single earthquake at position i within the list of earthquakes
JSONObject currentEarthquake = earthquakeArray.getJSONObject(i);
// For given earthquakes, extract the JSONObject associated with the
// key called "properties", which represents a list of all properties
// for that earthquake.
JSONObject properties = currentEarthquake.getJSONObject("properties");
// Extract the value for the key called "mag"
Double magnitude = properties.getDouble("mag");
// Extract the value for the key called "place"
String location = properties.getString("place");
// Extract the value for the key called "time" in long due to Unix time
long time = properties.getLong("time");
//Extract the value for the key called "url"
String url = properties.getString("url");
// Create a new {@link Earthquake} object with the magnitude, location
// and time from JSON response.
Earthquake earthquake = new Earthquake(magnitude, location, time, url);
// Add the new {@link Earthquake} to the list of earthquakes.
earthquakes.add(earthquake);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
}
// Return the list of earthquakes
return earthquakes;
}
} |
package com.example.fernando.farmingfarming;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
public class Profit extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profit);
// Volley volley = new Volley();
final Spinner regionSpinner = (Spinner) findViewById(R.id.profitRegionSpinner);
final Button buttonRegionSpinner = (Button) findViewById(R.id.profitButtonToSpinner);
final Spinner cropSpinner = (Spinner) findViewById(R.id.profitCropSpinner);
final Button buttonCropSpinner = (Button) findViewById(R.id.profitButtonCrop);
final TextView getServerData = (TextView) findViewById(R.id.profitExecute);
//final TextView waiting = (TextView) findViewById(R.id.profitWaiting);
//final TextView output = (TextView) findViewById(R.id.profitOutput);
final SetServerReady serverEnable = new SetServerReady();
int regionID = 0;
//Array adapter for choosing the Region
ArrayAdapter<String> regionAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.regionItems));
// Specify the layout to use when the list of choices appear+
regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
regionSpinner.setAdapter(regionAdapter);
//Array adapter for choosing the crop
ArrayAdapter<String> cropAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.cropItems));
// Specify the layout to use when the list of choices appear+
cropAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
cropSpinner.setAdapter(cropAdapter);
/**
* creating a click listener for the button, then having the spinner displayed
* with all data so that the user doesn't have to click twice for it to open
*/
buttonRegionSpinner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonRegionSpinner.setVisibility(View.INVISIBLE);
regionSpinner.setVisibility(View.VISIBLE);
regionSpinner.performClick();
// region selected
Log.d("Region Set","its set");
serverEnable.setRegion(true);
}
});
buttonCropSpinner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Spinner regionSpinner = (Spinner) findViewById(R.id.profitRegionSpinner);
buttonCropSpinner.setVisibility(View.INVISIBLE);
cropSpinner.setVisibility(View.VISIBLE);
cropSpinner.performClick();
// region selected
Log.d("Crop Set","its set");
serverEnable.setCrop(true);
}
});
getServerData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (serverEnable.getEnabled() == false) {
Log.d("serverenable","no");
} else {
Log.d("serverenable","yes");
// server request URL
int regionID = regionSpinner.getSelectedItemPosition();
Log.d("regionID", " "+regionID);
CreateURL partURL = new CreateURL(regionID);
String serverURL = "http://10.0.2.2:8080/agapp/Corn.php?" + partURL.getURL();
Log.d("server request method",serverURL);
getServerRequestJSON(serverURL, regionID);
Log.d("server request method","completed");
}
}
});
}
private void getServerRequestJSON(String url, int i) {
final TextView output = (TextView) findViewById(R.id.profitOutput);
final TextView waiting = (TextView) findViewById(R.id.profitWaiting);
Log.d("url",url);
Log.d("int"," "+i);
JSONObject jason = null;
/**
* this is where the volley requests occur.
*/
//TODO: need to make sure that the server request actually returns a JSONobject
RequestQueue req = Volley.newRequestQueue(this);
StringRequest serverReq = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// the response is already constructed as a JSONObject
Log.d("actual server req", response.toString());
waiting.setVisibility(View.INVISIBLE);
output.setVisibility(View.VISIBLE);
output.setText("Test: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Error handling
Log.d("actual server req","Something went wrong");
error.printStackTrace();
}
});
Volley.newRequestQueue(this).add(serverReq);
Log.d("request queue", "made it through");
}
} |
package com.example.phong.musicCaster;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.Random;
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
//media player
private MediaPlayer player;
//song list
private ArrayList<Song> songs;
//current position
private int songPosn;
private String songTitle;
private final IBinder musicBind = new MusicBinder();
private boolean shuffle=false;
private Random rand;
public void onCreate() {
//create the service
super.onCreate();
//initialize position
songPosn = 0;
//create player
player = new MediaPlayer();
this.initmusicCaster();
rand = new Random();
}
public void initmusicCaster() {
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setListOfSongs(ArrayList<Song> theSongs) {
songs = theSongs;
}
@Override
public void onCompletion(MediaPlayer mp) {
if(player.getCurrentPosition()>0) {
mp.reset();
playNext();
}
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return musicBind;
}
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public void playSong() {
//play a song
player.reset();
//get song
Song playSong = songs.get(songPosn);
songTitle = playSong.getSongTitle();
//get id
long currSong = playSong.getSongID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
public void onPrepared(MediaPlayer mp) {
//start playback
player.start();
Intent notIntent = new Intent(this, MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(songTitle);
Notification not = builder.build();
startForeground(R.drawable.play, not);
}
public void setSong(int songIndex) {
songPosn = songIndex;
}
public int getPosn() {
return player.getCurrentPosition();
}
public int getDur() {
return player.getDuration();
}
public boolean isPng() {
return player.isPlaying();
}
public void pausePlayer() {
player.pause();
}
public void seek(int posn) {
player.seekTo(posn);
}
public void go() {
player.start();
}
public void playPrev() {
songPosn
if (songPosn < 0) songPosn = songs.size() - 1;
playSong();
}
public void playNext() {
if(shuffle){
int newSong = songPosn;
while(newSong==songPosn){
newSong=rand.nextInt(songs.size());
}
}
else{
songPosn++;
}
if (songPosn >= songs.size()) songPosn = 0;
playSong();
}
public void setShuffle(){
if(shuffle) shuffle=false;
else shuffle=true;
}
public int getSongIndex(){return songPosn;}
} |
package com.fisheradelakin.floridaman;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends Activity {
public static final String URL = "http:
private static final String TAG_TITLE = "title";
private static final String TAG_URL = "url";
ListView listView;
ArrayList<HashMap<String,String>> newsList = new ArrayList<HashMap<String, String>>();
TextView title;
TextView desc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button newStoryButton = (Button) findViewById(R.id.showAnotherStoryButton);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isNetworkAvailable()) {
new JSONParse().execute();
}
}
};
newStoryButton.setOnClickListener(listener);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
} else {
Toast.makeText(this, "No network. Sorry, stories are not available.", Toast.LENGTH_SHORT).show();
}
return isAvailable;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
title = (TextView)findViewById(R.id.title);
desc = (TextView)findViewById(R.id.desc);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting New Stories ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJsonFromUrl(URL);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
JSONObject response = json.getJSONObject("data");
System.out.println(response);
//JSONObject data = response.getJSONObject("data");
JSONArray hotTopics = response.getJSONArray("children");
for(int i=0; i<hotTopics.length(); i++) {
JSONObject topic = hotTopics.getJSONObject(i).getJSONObject("data");
String title = topic.getString(TAG_TITLE);
String url = topic.getString(TAG_URL);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_URL, url);
newsList.add(map);
listView=(ListView)findViewById(R.id.list);
/* ListAdapter adapter = new SimpleAdapter(MainActivity.this, newsList,
R.layout.list_item,
new String[] { TAG_TITLE,TAG_URL}, new int[] {
R.id.title, R.id.desc}); */
ListAdapter adapter = new SimpleAdapter(MainActivity.this, newsList,
R.layout.list_item,
new String[] { TAG_TITLE, TAG_URL}, new int[] {
R.id.title});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String url = TAG_URL;
Intent i = new Intent(Intent.ACTION_VIEW);
// i.setData(Uri.parse(desc.getText().toString()));
i.setData(Uri.parse(url));
startActivity(i);
}
});
System.out.println(title);
System.out.println(url);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} |
package com.ganxin.circlerangeview;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
* Description : View <br/>
* author : WangGanxin <br/>
* date : 2017/3/23 <br/>
* email : mail@wangganxin.me <br/>
*/
public class CircleRangeView extends View {
private int mPadding;
private int mRadius; // padding
private int mStartAngle = 150;
private int mSweepAngle = 240;
private int mSparkleWidth;
private int mCalibrationWidth;
private float mLength1;
private float mCenterX, mCenterY;
private Paint mPaint;
private RectF mRectFProgressArc;
private RectF mRectFCalibrationFArc;
private Rect mRectText;
private CharSequence[] rangeColorArray;
private CharSequence[] rangeValueArray;
private CharSequence[] rangeTextArray;
private int borderColor = ContextCompat.getColor(getContext(), R.color.wdiget_circlerange_border_color);
private int cursorColor = ContextCompat.getColor(getContext(), R.color.wdiget_circlerange_cursor_color);
private int extraTextColor = ContextCompat.getColor(getContext(), R.color.widget_circlerange_extra_color);
private int rangeTextSize = sp2px(34);
private int extraTextSize = sp2px(14);
private int borderSize = dp2px(5);
private int mBackgroundColor;
private int mSection = 0;
private String currentValue;
private List<String> extraList = new ArrayList<>();
private boolean isAnimFinish = true;
private float mAngleWhenAnim;
public CircleRangeView(Context context) {
this(context, null);
}
public CircleRangeView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleRangeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleRangeView);
rangeColorArray = typedArray.getTextArray(R.styleable.CircleRangeView_rangeColorArray);
rangeValueArray = typedArray.getTextArray(R.styleable.CircleRangeView_rangeValueArray);
rangeTextArray = typedArray.getTextArray(R.styleable.CircleRangeView_rangeTextArray);
borderColor = typedArray.getColor(R.styleable.CircleRangeView_borderColor, borderColor);
cursorColor = typedArray.getColor(R.styleable.CircleRangeView_cursorColor, cursorColor);
extraTextColor = typedArray.getColor(R.styleable.CircleRangeView_extraTextColor, extraTextColor);
rangeTextSize = typedArray.getDimensionPixelSize(R.styleable.CircleRangeView_rangeTextSize, rangeTextSize);
extraTextSize = typedArray.getDimensionPixelSize(R.styleable.CircleRangeView_extraTextSize, extraTextSize);
typedArray.recycle();
if (rangeColorArray == null || rangeValueArray == null || rangeTextArray == null) {
throw new IllegalArgumentException("CircleRangeView : rangeColorArray rangeValueArrayrangeTextArray must be not null ");
}
if (rangeColorArray.length != rangeValueArray.length
|| rangeColorArray.length != rangeTextArray.length
|| rangeValueArray.length != rangeTextArray.length) {
throw new IllegalArgumentException("arrays must be equal length");
}
this.mSection = rangeColorArray.length;
mSparkleWidth = dp2px(15);
mCalibrationWidth = dp2px(10);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mRectFProgressArc = new RectF();
mRectFCalibrationFArc = new RectF();
mRectText = new Rect();
mBackgroundColor = android.R.color.transparent;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mPadding = Math.max(
Math.max(getPaddingLeft(), getPaddingTop()),
Math.max(getPaddingRight(), getPaddingBottom())
);
setPadding(mPadding, mPadding, mPadding, mPadding);
mLength1 = mPadding + mSparkleWidth / 2f + dp2px(12);
int width = resolveSize(dp2px(220), widthMeasureSpec);
mRadius = (width - mPadding * 2) / 2;
setMeasuredDimension(width, width - dp2px(30));
mCenterX = mCenterY = getMeasuredWidth() / 2f;
mRectFProgressArc.set(
mPadding + mSparkleWidth / 2f,
mPadding + mSparkleWidth / 2f,
getMeasuredWidth() - mPadding - mSparkleWidth / 2f,
getMeasuredWidth() - mPadding - mSparkleWidth / 2f
);
mRectFCalibrationFArc.set(
mLength1 + mCalibrationWidth / 2f,
mLength1 + mCalibrationWidth / 2f,
getMeasuredWidth() - mLength1 - mCalibrationWidth / 2f,
getMeasuredWidth() - mLength1 - mCalibrationWidth / 2f
);
mPaint.setTextSize(sp2px(10));
mPaint.getTextBounds("0", 0, "0".length(), mRectText);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(ContextCompat.getColor(getContext(), mBackgroundColor));
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(borderSize);
mPaint.setAlpha(80);
mPaint.setColor(borderColor);
canvas.drawArc(mRectFProgressArc, mStartAngle + 1, mSweepAngle - 2, false, mPaint);
mPaint.setAlpha(255);
if (isAnimFinish) {
float[] point = getCoordinatePoint(mRadius - mSparkleWidth / 2f, mStartAngle + calculateAngleWithValue(currentValue));
mPaint.setColor(cursorColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(point[0], point[1], mSparkleWidth / 2f, mPaint);
} else {
float[] point = getCoordinatePoint(mRadius - mSparkleWidth / 2f, mAngleWhenAnim);
mPaint.setColor(cursorColor);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(point[0], point[1], mSparkleWidth / 2f, mPaint);
}
mPaint.setShader(null);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.BLACK);
mPaint.setAlpha(255);
mPaint.setStrokeCap(Paint.Cap.SQUARE);
mPaint.setStrokeWidth(mCalibrationWidth);
if (rangeColorArray != null) {
for (int i = 0; i < rangeColorArray.length; i++) {
mPaint.setColor(Color.parseColor(rangeColorArray[i].toString()));
float mSpaces = mSweepAngle / mSection;
if (i == 0) {
canvas.drawArc(mRectFCalibrationFArc, mStartAngle + 3, mSpaces, false, mPaint);
} else if (i == rangeColorArray.length - 1) {
canvas.drawArc(mRectFCalibrationFArc, mStartAngle + (mSpaces * i), mSpaces, false, mPaint);
} else {
canvas.drawArc(mRectFCalibrationFArc, mStartAngle + (mSpaces * i) + 3, mSpaces, false, mPaint);
}
}
}
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setShader(null);
mPaint.setAlpha(255);
if (rangeColorArray != null && rangeValueArray != null && rangeTextArray != null) {
if (!TextUtils.isEmpty(currentValue)) {
int pos = 0;
for (int i = 0; i < rangeValueArray.length; i++) {
if (rangeValueArray[i].equals(currentValue)) {
pos = i;
break;
}
}
mPaint.setColor(Color.parseColor(rangeColorArray[pos].toString()));
mPaint.setTextAlign(Paint.Align.CENTER);
String txt=rangeTextArray[pos].toString();
if (txt.length() <= 4) {
mPaint.setTextSize(rangeTextSize);
canvas.drawText(txt, mCenterX, mCenterY + dp2px(10), mPaint);
} else {
mPaint.setTextSize(rangeTextSize - 10);
String top = txt.substring(0, 4);
String bottom = txt.substring(4, txt.length());
canvas.drawText(top, mCenterX, mCenterY, mPaint);
canvas.drawText(bottom, mCenterX, mCenterY + dp2px(30), mPaint);
}
}
}
if (extraList != null && extraList.size() > 0) {
mPaint.setAlpha(160);
mPaint.setColor(extraTextColor);
mPaint.setTextSize(extraTextSize);
for (int i = 0; i < extraList.size(); i++) {
canvas.drawText(extraList.get(i), mCenterX, mCenterY + dp2px(50) + i * dp2px(20), mPaint);
}
}
}
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
Resources.getSystem().getDisplayMetrics());
}
private int sp2px(int sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
Resources.getSystem().getDisplayMetrics());
}
/**
*
* @param radius
* @param angle
* @return
*/
private float[] getCoordinatePoint(float radius, float angle) {
float[] point = new float[2];
double arcAngle = Math.toRadians(angle);
if (angle < 90) {
point[0] = (float) (mCenterX + Math.cos(arcAngle) * radius);
point[1] = (float) (mCenterY + Math.sin(arcAngle) * radius);
} else if (angle == 90) {
point[0] = mCenterX;
point[1] = mCenterY + radius;
} else if (angle > 90 && angle < 180) {
arcAngle = Math.PI * (180 - angle) / 180.0;
point[0] = (float) (mCenterX - Math.cos(arcAngle) * radius);
point[1] = (float) (mCenterY + Math.sin(arcAngle) * radius);
} else if (angle == 180) {
point[0] = mCenterX - radius;
point[1] = mCenterY;
} else if (angle > 180 && angle < 270) {
arcAngle = Math.PI * (angle - 180) / 180.0;
point[0] = (float) (mCenterX - Math.cos(arcAngle) * radius);
point[1] = (float) (mCenterY - Math.sin(arcAngle) * radius);
} else if (angle == 270) {
point[0] = mCenterX;
point[1] = mCenterY - radius;
} else {
arcAngle = Math.PI * (360 - angle) / 180.0;
point[0] = (float) (mCenterX + Math.cos(arcAngle) * radius);
point[1] = (float) (mCenterY - Math.sin(arcAngle) * radius);
}
return point;
}
private float calculateAngleWithValue(String level) {
int pos = -1;
for (int j = 0; j < rangeValueArray.length; j++) {
if (rangeValueArray[j].equals(level)) {
pos = j;
break;
}
}
float degreePerSection = 1f * mSweepAngle / mSection;
if (pos == -1) {
return 0;
} else if (pos == 0) {
return degreePerSection / 2;
} else {
return pos * degreePerSection + degreePerSection / 2;
}
}
/**
*
*
* @param value
*/
public void setValueWithAnim(String value) {
setValueWithAnim(value,null);
}
/**
*
*
* @param value
* @param extras
*/
public void setValueWithAnim(String value, List<String> extras) {
if (!isAnimFinish) {
return;
}
this.currentValue = value;
this.extraList=extras;
float degree = calculateAngleWithValue(value);
ValueAnimator degreeValueAnimator = ValueAnimator.ofFloat(mStartAngle, mStartAngle + degree);
degreeValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mAngleWhenAnim = (float) animation.getAnimatedValue();
postInvalidate();
}
});
long delay = 1500;
AnimatorSet animatorSet = new AnimatorSet();
animatorSet
.setDuration(delay)
.playTogether(degreeValueAnimator);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
isAnimFinish = false;
}
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
isAnimFinish = true;
}
@Override
public void onAnimationCancel(Animator animation) {
super.onAnimationCancel(animation);
isAnimFinish = true;
}
});
animatorSet.start();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.