answer stringlengths 17 10.2M |
|---|
package com.fsck.k9.mail.transport;
import android.util.Log;
import com.fsck.k9.K9;
import com.fsck.k9.mail.*;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.filter.Base64;
import com.fsck.k9.mail.filter.EOLConvertingOutputStream;
import com.fsck.k9.mail.filter.LineWrapOutputStream;
import com.fsck.k9.mail.filter.PeekableInputStream;
import com.fsck.k9.mail.filter.SmtpDataStuffing;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.store.TrustManagerFactory;
import com.fsck.k9.mail.store.LocalStore.LocalMessage;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.*;
public class SmtpTransport extends Transport {
public static final int CONNECTION_SECURITY_NONE = 0;
public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1;
public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2;
public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3;
public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4;
public static final String AUTH_PLAIN = "PLAIN";
public static final String AUTH_CRAM_MD5 = "CRAM_MD5";
public static final String AUTH_LOGIN = "LOGIN";
public static final String AUTH_AUTOMATIC = "AUTOMATIC";
String mHost;
int mPort;
String mUsername;
String mPassword;
String mAuthType;
int mConnectionSecurity;
boolean mSecure;
Socket mSocket;
PeekableInputStream mIn;
OutputStream mOut;
private boolean m8bitEncodingAllowed;
private int mLargestAcceptableMessage;
/**
* smtp://user:password@server:port CONNECTION_SECURITY_NONE
* smtp+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL
* smtp+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED
* smtp+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED
* smtp+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL
*
* @param _uri
*/
public SmtpTransport(String _uri) throws MessagingException {
URI uri;
try {
uri = new URI(_uri);
} catch (URISyntaxException use) {
throw new MessagingException("Invalid SmtpTransport URI", use);
}
String scheme = uri.getScheme();
if (scheme.equals("smtp")) {
mConnectionSecurity = CONNECTION_SECURITY_NONE;
mPort = 25;
} else if (scheme.equals("smtp+tls")) {
mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL;
mPort = 25;
} else if (scheme.equals("smtp+tls+")) {
mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED;
mPort = 25;
} else if (scheme.equals("smtp+ssl+")) {
mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED;
mPort = 465;
} else if (scheme.equals("smtp+ssl")) {
mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL;
mPort = 465;
} else {
throw new MessagingException("Unsupported protocol");
}
mHost = uri.getHost();
if (uri.getPort() != -1) {
mPort = uri.getPort();
}
if (uri.getUserInfo() != null) {
try {
String[] userInfoParts = uri.getUserInfo().split(":");
mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8");
if (userInfoParts.length > 1) {
mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8");
}
if (userInfoParts.length > 2) {
mAuthType = userInfoParts[2];
}
} catch (UnsupportedEncodingException enc) {
// This shouldn't happen since the encoding is hardcoded to UTF-8
Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc);
}
}
}
@Override
public void open() throws MessagingException {
try {
InetAddress[] addresses = InetAddress.getAllByName(mHost);
for (int i = 0; i < addresses.length; i++) {
try {
SocketAddress socketAddress = new InetSocketAddress(addresses[i], mPort);
if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED ||
mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) {
SSLContext sslContext = SSLContext.getInstance("TLS");
boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED;
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(mHost, secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
mSecure = true;
} else {
mSocket = new Socket();
mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
}
} catch (ConnectException e) {
if (i < (addresses.length - 1)) {
// there are still other addresses for that host to try
continue;
}
throw new MessagingException("Cannot connect to host", e);
}
break; // connection success
}
// RFC 1047
mSocket.setSoTimeout(SOCKET_READ_TIMEOUT);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024));
mOut = mSocket.getOutputStream();
// Eat the banner
executeSimpleCommand(null);
InetAddress localAddress = mSocket.getLocalAddress();
String localHost = localAddress.getHostName();
String ipAddr = localAddress.getHostAddress();
if (localHost.equals("") || localHost.equals(ipAddr) || localHost.contains("_")) {
// We don't have a FQDN or the hostname contains invalid
// characters (see issue 2143), so use IP address.
if (!ipAddr.equals("")) {
if (localAddress instanceof Inet6Address) {
localHost = "[IPV6:" + ipAddr + "]";
} else {
localHost = "[" + ipAddr + "]";
}
} else {
// If the IP address is no good, set a sane default (see issue 2750).
localHost = "android";
}
}
List<String> results = executeSimpleCommand("EHLO " + localHost);
m8bitEncodingAllowed = results.contains("8BITMIME");
/*
* TODO may need to add code to fall back to HELO I switched it from
* using HELO on non STARTTLS connections because of AOL's mail
* server. It won't let you use AUTH without EHLO.
* We should really be paying more attention to the capabilities
* and only attempting auth if it's available, and warning the user
* if not.
*/
if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL
|| mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) {
if (results.contains("STARTTLS")) {
executeSimpleCommand("STARTTLS");
SSLContext sslContext = SSLContext.getInstance("TLS");
boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED;
sslContext.init(null, new TrustManager[] {
TrustManagerFactory.get(mHost, secure)
}, new SecureRandom());
mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort,
true);
mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(),
1024));
mOut = mSocket.getOutputStream();
mSecure = true;
/*
* Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically,
* Exim.
*/
results = executeSimpleCommand("EHLO " + localHost);
} else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) {
throw new MessagingException("TLS not supported but required");
}
}
boolean useAuthLogin = AUTH_LOGIN.equals(mAuthType);
boolean useAuthPlain = AUTH_PLAIN.equals(mAuthType);
boolean useAuthCramMD5 = AUTH_CRAM_MD5.equals(mAuthType);
boolean authLoginSupported = false;
boolean authPlainSupported = false;
boolean authCramMD5Supported = false;
for (String result : results) {
if (result.matches(".*AUTH.*LOGIN.*$")) {
authLoginSupported = true;
}
if (result.matches(".*AUTH.*PLAIN.*$")) {
authPlainSupported = true;
}
if (result.matches(".*AUTH.*CRAM-MD5.*$")) {
authCramMD5Supported = true;
}
if (result.matches(".*SIZE \\d*$")) {
try {
mLargestAcceptableMessage = Integer.parseInt(result.substring(result.lastIndexOf(' ') + 1));
} catch (Exception e) {
if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Tried to parse " + result + " and get an int out of the last word: " + e);
}
}
}
}
if (mUsername != null && mUsername.length() > 0 &&
mPassword != null && mPassword.length() > 0) {
if (useAuthCramMD5 || authCramMD5Supported) {
if (!authCramMD5Supported && K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Using CRAM_MD5 as authentication method although the " +
"server didn't advertise support for it in EHLO response.");
}
saslAuthCramMD5(mUsername, mPassword);
} else if (useAuthPlain || authPlainSupported) {
if (!authPlainSupported && K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Using PLAIN as authentication method although the " +
"server didn't advertise support for it in EHLO response.");
}
saslAuthPlain(mUsername, mPassword);
} else if (useAuthLogin || authLoginSupported) {
if (!authPlainSupported && K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
Log.d(K9.LOG_TAG, "Using LOGIN as authentication method although the " +
"server didn't advertise support for it in EHLO response.");
}
saslAuthLogin(mUsername, mPassword);
} else {
throw new MessagingException("No valid authentication mechanism found.");
}
}
} catch (SSLException e) {
throw new CertificateValidationException(e.getMessage(), e);
} catch (GeneralSecurityException gse) {
throw new MessagingException(
"Unable to open connection to SMTP server due to security error.", gse);
} catch (IOException ioe) {
throw new MessagingException("Unable to open connection to SMTP server.", ioe);
}
}
@Override
public void sendMessage(Message message) throws MessagingException {
ArrayList<Address> addresses = new ArrayList<Address>();
{
addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.TO)));
addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.CC)));
addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.BCC)));
}
message.setRecipients(RecipientType.BCC, null);
HashMap<String, ArrayList<String>> charsetAddressesMap =
new HashMap<String, ArrayList<String>>();
for (Address address : addresses) {
String addressString = address.getAddress();
String charset = MimeUtility.getCharsetFromAddress(addressString);
ArrayList<String> addressesOfCharset = charsetAddressesMap.get(charset);
if (addressesOfCharset == null) {
addressesOfCharset = new ArrayList<String>();
charsetAddressesMap.put(charset, addressesOfCharset);
}
addressesOfCharset.add(addressString);
}
for (Map.Entry<String, ArrayList<String>> charsetAddressesMapEntry :
charsetAddressesMap.entrySet()) {
String charset = charsetAddressesMapEntry.getKey();
ArrayList<String> addressesOfCharset = charsetAddressesMapEntry.getValue();
message.setCharset(charset);
sendMessageTo(addressesOfCharset, message);
}
}
private void sendMessageTo(ArrayList<String> addresses, Message message)
throws MessagingException {
boolean possibleSend = false;
close();
open();
message.setEncoding(m8bitEncodingAllowed ? "8bit" : null);
// If the message has attachments and our server has told us about a limit on
// the size of messages, count the message's size before sending it
if (mLargestAcceptableMessage > 0 && ((LocalMessage)message).hasAttachments()) {
if (message.calculateSize() > mLargestAcceptableMessage) {
MessagingException me = new MessagingException("Message too large for server");
me.setPermanentFailure(possibleSend);
throw me;
}
}
Address[] from = message.getFrom();
try {
//TODO: Add BODY=8BITMIME parameter if appropriate?
executeSimpleCommand("MAIL FROM:" + "<" + from[0].getAddress() + ">");
for (String address : addresses) {
executeSimpleCommand("RCPT TO:" + "<" + address + ">");
}
executeSimpleCommand("DATA");
EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream(
new SmtpDataStuffing(
new LineWrapOutputStream(
new BufferedOutputStream(mOut, 1024),
1000)));
message.writeTo(msgOut);
// We use BufferedOutputStream. So make sure to call flush() !
msgOut.flush();
possibleSend = true; // After the "\r\n." is attempted, we may have sent the message
executeSimpleCommand("\r\n.");
} catch (Exception e) {
MessagingException me = new MessagingException("Unable to send message", e);
me.setPermanentFailure(possibleSend);
throw me;
} finally {
close();
}
}
@Override
public void close() {
try {
executeSimpleCommand("QUIT");
} catch (Exception e) {
}
try {
mIn.close();
} catch (Exception e) {
}
try {
mOut.close();
} catch (Exception e) {
}
try {
mSocket.close();
} catch (Exception e) {
}
mIn = null;
mOut = null;
mSocket = null;
}
private String readLine() throws IOException {
StringBuffer sb = new StringBuffer();
int d;
while ((d = mIn.read()) != -1) {
if (((char)d) == '\r') {
continue;
} else if (((char)d) == '\n') {
break;
} else {
sb.append((char)d);
}
}
String ret = sb.toString();
if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP)
Log.d(K9.LOG_TAG, "SMTP <<< " + ret);
return ret;
}
private void writeLine(String s, boolean sensitive) throws IOException {
if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) {
final String commandToLog;
if (sensitive && !K9.DEBUG_SENSITIVE) {
commandToLog = "SMTP >>> *sensitive*";
} else {
commandToLog = "SMTP >>> " + s;
}
Log.d(K9.LOG_TAG, commandToLog);
}
byte[] data = s.concat("\r\n").getBytes();
/*
* Important: Send command + CRLF using just one write() call. Using
* multiple calls will likely result in multiple TCP packets and some
* SMTP servers misbehave if CR and LF arrive in separate pakets.
* See issue 799.
*/
mOut.write(data);
mOut.flush();
}
private void checkLine(String line) throws MessagingException {
if (line.length() < 1) {
throw new MessagingException("SMTP response is 0 length");
}
char c = line.charAt(0);
if ((c == '4') || (c == '5')) {
throw new MessagingException(line);
}
}
private List<String> executeSimpleCommand(String command) throws IOException, MessagingException {
return executeSimpleCommand(command, false);
}
private List<String> executeSimpleCommand(String command, boolean sensitive)
throws IOException, MessagingException {
List<String> results = new ArrayList<String>();
if (command != null) {
writeLine(command, sensitive);
}
/*
* Read lines as long as the length is 4 or larger, e.g. "220-banner text here".
* Shorter lines are either errors of contain only a reply code. Those cases will
* be handled by checkLine() below.
*/
String line = readLine();
while (line.length() >= 4) {
if (line.length() > 4) {
// Everything after the first four characters goes into the results array.
results.add(line.substring(4));
}
if (line.charAt(3) != '-') {
// If the fourth character isn't "-" this is the last line of the response.
break;
}
line = readLine();
}
// Check if the reply code indicates an error.
checkLine(line);
return results;
}
// C: AUTH LOGIN
// S: 334 VXNlcm5hbWU6
// C: d2VsZG9u
// S: 334 UGFzc3dvcmQ6
// C: dzNsZDBu
// S: 235 2.0.0 OK Authenticated
// Lines 2-5 of the conversation contain base64-encoded information. The same conversation, with base64 strings decoded, reads:
// C: AUTH LOGIN
// S: 334 Username:
// C: weldon
// S: 334 Password:
// C: w3ld0n
// S: 235 2.0.0 OK Authenticated
private void saslAuthLogin(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
try {
executeSimpleCommand("AUTH LOGIN");
executeSimpleCommand(new String(Base64.encodeBase64(username.getBytes())), true);
executeSimpleCommand(new String(Base64.encodeBase64(password.getBytes())), true);
} catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException("AUTH LOGIN failed (" + me.getMessage()
+ ")");
}
throw me;
}
}
private void saslAuthPlain(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
byte[] data = ("\000" + username + "\000" + password).getBytes();
data = new Base64().encode(data);
try {
executeSimpleCommand("AUTH PLAIN " + new String(data), true);
} catch (MessagingException me) {
if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') {
throw new AuthenticationFailedException("AUTH PLAIN failed (" + me.getMessage()
+ ")");
}
throw me;
}
}
private void saslAuthCramMD5(String username, String password) throws MessagingException,
AuthenticationFailedException, IOException {
List<String> respList = executeSimpleCommand("AUTH CRAM-MD5");
if (respList.size() != 1) {
throw new AuthenticationFailedException("Unable to negotiate CRAM-MD5");
}
String b64Nonce = respList.get(0);
String b64CRAMString = Authentication.computeCramMd5(mUsername, mPassword, b64Nonce);
try {
executeSimpleCommand(b64CRAMString, true);
} catch (MessagingException me) {
throw new AuthenticationFailedException("Unable to negotiate MD5 CRAM");
}
}
} |
package com.jwetherell.algorithms;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import com.jwetherell.algorithms.data_structures.AVLTree;
import com.jwetherell.algorithms.data_structures.BTree;
import com.jwetherell.algorithms.data_structures.BinarySearchTree;
import com.jwetherell.algorithms.data_structures.BinaryHeap;
import com.jwetherell.algorithms.data_structures.Graph.Edge;
import com.jwetherell.algorithms.data_structures.Graph.Vertex;
import com.jwetherell.algorithms.data_structures.Graph;
import com.jwetherell.algorithms.data_structures.HashMap;
import com.jwetherell.algorithms.data_structures.PatriciaTrie;
import com.jwetherell.algorithms.data_structures.RadixTrie;
import com.jwetherell.algorithms.data_structures.RedBlackTree;
import com.jwetherell.algorithms.data_structures.SegmentTree.Data.IntervalData;
import com.jwetherell.algorithms.data_structures.SegmentTree.Data.QuadrantData;
import com.jwetherell.algorithms.data_structures.SegmentTree.Data.RangeMaximumData;
import com.jwetherell.algorithms.data_structures.SegmentTree.Data.RangeMinimumData;
import com.jwetherell.algorithms.data_structures.SegmentTree.Data.RangeSumData;
import com.jwetherell.algorithms.data_structures.SegmentTree.DynamicSegmentTree;
import com.jwetherell.algorithms.data_structures.SegmentTree.FlatSegmentTree;
import com.jwetherell.algorithms.data_structures.SuffixTree;
import com.jwetherell.algorithms.data_structures.TrieMap;
import com.jwetherell.algorithms.data_structures.List;
import com.jwetherell.algorithms.data_structures.Matrix;
import com.jwetherell.algorithms.data_structures.Queue;
import com.jwetherell.algorithms.data_structures.SkipList;
import com.jwetherell.algorithms.data_structures.SplayTree;
import com.jwetherell.algorithms.data_structures.Stack;
import com.jwetherell.algorithms.data_structures.SuffixTrie;
import com.jwetherell.algorithms.data_structures.Treap;
import com.jwetherell.algorithms.data_structures.Trie;
import com.jwetherell.algorithms.graph.BellmanFord;
import com.jwetherell.algorithms.graph.CycleDetection;
import com.jwetherell.algorithms.graph.Dijkstra;
import com.jwetherell.algorithms.graph.FloydWarshall;
import com.jwetherell.algorithms.graph.Johnson;
import com.jwetherell.algorithms.graph.Prim;
import com.jwetherell.algorithms.graph.TopologicalSort;
public class DataStructures {
private static final int NUMBER_OF_TESTS = 5;
private static final Random RANDOM = new Random();
private static final int ARRAY_SIZE = 1000;
private static final int RANDOM_SIZE = 1000*ARRAY_SIZE;
private static final Integer INVALID = RANDOM_SIZE+10;
private static final DecimalFormat FORMAT = new DecimalFormat("0.
private static Integer[] unsorted = null;
private static Integer[] sorted = null;
private static String string = null;
private static int debug = 1; //debug level. 0=None, 1=Time and Memory (if enabled), 2=Time, Memory, data structure debug
private static boolean debugTime = true; //How much time to: add all, remove all, add all items in reverse order, remove all
private static boolean debugMemory = true; //How much memory is used by the data structure
private static boolean validateStructure = true; //Is the data structure valid (passed invariants) and proper size
private static boolean validateContents = true; //Was the item added/removed really added/removed from the structure
private static final int TESTS = 32; //Number of dynamic data structures to test
private static int test = 0;
private static String[] testNames = new String[TESTS];
private static long[][] testResults = new long[TESTS][];
public static void main(String[] args) {
System.out.println("Starting tests.");
boolean passed = true;
for (int i=0; i<NUMBER_OF_TESTS; i++) {
passed = runTests();
if (!passed) break;
}
if (passed) System.out.println("Tests finished. All passed.");
else System.err.println("Tests finished. Detected a failure.");
}
private static boolean runTests() {
test = 0;
System.out.println("Generating data.");
StringBuilder builder = new StringBuilder();
builder.append("Array=");
unsorted = new Integer[ARRAY_SIZE];
java.util.Set<Integer> set = new java.util.HashSet<Integer>();
for (int i=0; i<ARRAY_SIZE; i++) {
Integer j = RANDOM.nextInt(RANDOM_SIZE);
//Make sure there are no duplicates
boolean found = true;
while (found) {
if (set.contains(j)) {
j = RANDOM.nextInt(RANDOM_SIZE);
} else {
unsorted[i] = j;
set.add(j);
found = false;
}
}
unsorted[i] = j;
builder.append(j).append(',');
}
builder.append('\n');
string = builder.toString();
if (debug>1) System.out.println(string);
sorted = Arrays.copyOf(unsorted, unsorted.length);
Arrays.sort(sorted);
System.out.println("Generated data.");
boolean passed = true;
passed = testAVLTree();
if (!passed) {
System.err.println("AVL Tree failed.");
return false;
}
passed = testBTree();
if (!passed) {
System.err.println("B-Tree failed.");
return false;
}
passed = testBST();
if (!passed) {
System.err.println("BST failed.");
return false;
}
passed = testHeap();
if (!passed) {
System.err.println("Heap failed.");
return false;
}
passed = testHashMap();
if (!passed) {
System.err.println("Hash Map failed.");
return false;
}
passed = testList();
if (!passed) {
System.err.println("List failed.");
return false;
}
passed = testPatriciaTrie();
if (!passed) {
System.err.println("Patricia Trie failed.");
return false;
}
passed = testQueue();
if (!passed) {
System.err.println("Queue failed.");
return false;
}
passed = testRadixTrie();
if (!passed) {
System.err.println("Radix Trie failed.");
return false;
}
passed = testRedBlackTree();
if (!passed) {
System.err.println("Red-Black Tree failed.");
return false;
}
passed = testSkipList();
if (!passed) {
System.err.println("Skip List failed.");
return false;
}
passed = testSplayTree();
if (!passed) {
System.err.println("Splay Tree failed.");
return false;
}
passed = testStack();
if (!passed) {
System.err.println("Stack failed.");
return false;
}
passed = testTreap();
if (!passed) {
System.err.println("Treap failed.");
return false;
}
passed = testTrie();
if (!passed) {
System.err.println("Trie failed.");
return false;
}
passed = testTrieMap();
if (!passed) {
System.err.println("Trie Map failed.");
return false;
}
//JAVA DATA STRUCTURES
passed = testJavaHeap();
if (!passed) {
System.err.println("Java Heap failed.");
return false;
}
passed = testJavaHashMap();
if (!passed) {
System.err.println("Java Hash Map failed.");
return false;
}
passed = testJavaList();
if (!passed) {
System.err.println("Java List failed.");
return false;
}
passed = testJavaQueue();
if (!passed) {
System.err.println("Java Queue failed.");
return false;
}
passed = testJavaRedBlackTree();
if (!passed) {
System.err.println("Java Red-Black failed.");
return false;
}
passed = testJavaStack();
if (!passed) {
System.err.println("Java Stack failed.");
return false;
}
passed = testJavaTreeMap();
if (!passed) {
System.err.println("Java Tree Map failed.");
return false;
}
if (debugTime && debugMemory) {
String results = getTestResults(testNames,testResults);
System.out.println(results);
}
//STATIC DATA STRUCTURES
passed = testGraph();
if (!passed) {
System.err.println("Graph failed.");
return false;
}
passed = testMatrix();
if (!passed) {
System.err.println("Matrix failed.");
return false;
}
passed = testSegmentTree();
if (!passed) {
System.err.println("Segment Tree failed.");
return false;
}
passed = testSuffixTree();
if (!passed) {
System.err.println("Suffix Tree failed.");
return false;
}
passed = testSuffixTrie();
if (!passed) {
System.err.println("Suffix Trie failed.");
return false;
}
return true;
}
private static void handleError(Object obj) {
System.err.println(string);
System.err.println(obj.toString());
}
private static boolean testAVLTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//AVL Tree
if (debug>1) System.out.println("AVL Tree");
testNames[test] = "AVL Tree";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
AVLTree<Integer> tree = new AVLTree<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("AVL Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("AVL Tree memory use = "+(memory/count)+" bytes");
}
boolean contains = tree.contains(INVALID);
boolean removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("AVL Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("AVL Tree remove time = "+removeTime/count+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==(unsorted.length-i))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("AVL Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("AVL Tree memory use = "+(memory/count)+" bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("AVL Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("AVL Tree remove time = "+removeTime/count+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("AVL Tree add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("AVL Tree memory use = "+(memory/(count+1))+" bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("AVL Tree lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! AVL Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("AVL Tree remove time = "+removeSortedTime+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("AVL Tree invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testBTree() {
//unsorted = new Integer[]{};
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// B-Tree
if (debug>1) System.out.println("B-Tree with node.");
testNames[test] = "B-Tree";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
BTree<Integer> bTree = new BTree<Integer>(4); //2-3-4 Tree
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
bTree.add(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && !bTree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("B-Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("B-Tree memory use = "+(memory/count)+" bytes");
}
boolean contains = bTree.contains(INVALID);
boolean removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(bTree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
boolean found = bTree.contains(item);
if (!found) return false;
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("B-Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
bTree.remove(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && bTree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("B-Tree remove time = "+removeTime/count+" ms");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
bTree.add(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size()==sorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && !bTree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("B-Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("B-Tree memory use = "+(memory/count)+" bytes");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(bTree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
bTree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("B-Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
bTree.remove(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && bTree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("B-Tree remove time = "+removeTime/count+" ms");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
bTree.add(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && !bTree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("B-Tree add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("B-Tree memory use = "+(memory/(count+1))+" bytes");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(bTree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
bTree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("B-Tree lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
bTree.remove(item);
if (validateStructure && !bTree.validate()) {
System.err.println("YIKES!! B-Tree isn't valid.");
handleError(bTree);
return false;
}
if (validateStructure && !(bTree.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bTree);
return false;
}
if (validateContents && bTree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(bTree);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("B-Tree remove time = "+removeSortedTime+" ms");
}
contains = bTree.contains(INVALID);
removed = bTree.remove(INVALID);
if (contains || removed) {
System.err.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("B-Tree invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testBST() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// BINARY SEARCH TREE
if (debug>1) System.out.println("Binary search tree with node.");
testNames[test] = "Binary Search Tree";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
BinarySearchTree<Integer> bst = new BinarySearchTree<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
bst.add(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && !bst.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("BST add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("BST memory use = "+(memory/count)+" bytes");
}
boolean contains = bst.contains(INVALID);
boolean removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("BST invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(bst.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
bst.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("BST lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
bst.remove(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && bst.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("BST remove time = "+removeTime/count+" ms");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("BST invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
bst.add(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size()==sorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && !bst.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("BST add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("BST memory use = "+(memory/count)+" bytes");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("BST invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(bst.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
bst.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("BST lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
bst.remove(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && bst.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("BST remove time = "+removeTime/count+" ms");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("BST invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
bst.add(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && !bst.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("BST add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("BST memory use = "+(memory/(count+1))+" bytes");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("BST invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(bst.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
bst.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("BST lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
bst.remove(item);
if (validateStructure && !bst.validate()) {
System.err.println("YIKES!! BST isn't valid.");
handleError(bst);
return false;
}
if (validateStructure && !(bst.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(bst);
return false;
}
if (validateContents && bst.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(bst);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("BST remove time = "+removeSortedTime+" ms");
}
contains = bst.contains(INVALID);
removed = bst.remove(INVALID);
if (contains || removed) {
System.err.println("BST invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("BST invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testGraph() {
{
// UNDIRECTED GRAPH
if (debug>1) System.out.println("Undirected Graph.");
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> v1 = new Graph.Vertex<Integer>(1);
verticies.add(v1);
Graph.Vertex<Integer> v2 = new Graph.Vertex<Integer>(2);
verticies.add(v2);
Graph.Vertex<Integer> v3 = new Graph.Vertex<Integer>(3);
verticies.add(v3);
Graph.Vertex<Integer> v4 = new Graph.Vertex<Integer>(4);
verticies.add(v4);
Graph.Vertex<Integer> v5 = new Graph.Vertex<Integer>(5);
verticies.add(v5);
Graph.Vertex<Integer> v6 = new Graph.Vertex<Integer>(6);
verticies.add(v6);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> e1_2 = new Graph.Edge<Integer>(7, v1, v2);
edges.add(e1_2);
Graph.Edge<Integer> e1_3 = new Graph.Edge<Integer>(9, v1, v3);
edges.add(e1_3);
Graph.Edge<Integer> e1_6 = new Graph.Edge<Integer>(14, v1, v6);
edges.add(e1_6);
Graph.Edge<Integer> e2_3 = new Graph.Edge<Integer>(10, v2, v3);
edges.add(e2_3);
Graph.Edge<Integer> e2_4 = new Graph.Edge<Integer>(15, v2, v4);
edges.add(e2_4);
Graph.Edge<Integer> e3_4 = new Graph.Edge<Integer>(11, v3, v4);
edges.add(e3_4);
Graph.Edge<Integer> e3_6 = new Graph.Edge<Integer>(2, v3, v6);
edges.add(e3_6);
Graph.Edge<Integer> e5_6 = new Graph.Edge<Integer>(9, v5, v6);
edges.add(e5_6);
Graph.Edge<Integer> e4_5 = new Graph.Edge<Integer>(6, v4, v5);
edges.add(e4_5);
Graph<Integer> undirected = new Graph<Integer>(verticies,edges);
if (debug>1) System.out.println(undirected.toString());
Graph.Vertex<Integer> start = v1;
if (debug>1) System.out.println("Dijstra's shortest paths of the undirected graph from "+start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map1 = Dijkstra.getShortestPaths(undirected, start);
if (debug>1) System.out.println(getPathMapString(start,map1));
Graph.Vertex<Integer> end = v5;
if (debug>1) System.out.println("Dijstra's shortest path of the undirected graph from "+start.getValue()+" to "+end.getValue());
Graph.CostPathPair<Integer> pair1 = Dijkstra.getShortestPath(undirected, start, end);
if (debug>1) {
if (pair1!=null) System.out.println(pair1.toString());
else System.out.println("No path from "+start.getValue()+" to "+end.getValue());
}
start = v1;
if (debug>1) System.out.println("Bellman-Ford's shortest paths of the undirected graph from "+start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map2 = BellmanFord.getShortestPaths(undirected, start);
if (debug>1) System.out.println(getPathMapString(start,map2));
end = v5;
if (debug>1) System.out.println("Bellman-Ford's shortest path of the undirected graph from "+start.getValue()+" to "+end.getValue());
Graph.CostPathPair<Integer> pair2 = BellmanFord.getShortestPath(undirected, start, end);
if (debug>1) {
if (pair2!=null) System.out.println(pair2.toString());
else System.out.println("No path from "+start.getValue()+" to "+end.getValue());
}
if (debug>1) System.out.println("Prim's minimum spanning tree of the undirected graph from "+start.getValue());
Graph.CostPathPair<Integer> pair = Prim.getMinimumSpanningTree(undirected, start);
if (debug>1) System.out.println(pair.toString());
if (debug>1) System.out.println();
}
{
// DIRECTED GRAPH
if (debug>1) System.out.println("Directed Graph.");
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> v1 = new Graph.Vertex<Integer>(1);
verticies.add(v1);
Graph.Vertex<Integer> v2 = new Graph.Vertex<Integer>(2);
verticies.add(v2);
Graph.Vertex<Integer> v3 = new Graph.Vertex<Integer>(3);
verticies.add(v3);
Graph.Vertex<Integer> v4 = new Graph.Vertex<Integer>(4);
verticies.add(v4);
Graph.Vertex<Integer> v5 = new Graph.Vertex<Integer>(5);
verticies.add(v5);
Graph.Vertex<Integer> v6 = new Graph.Vertex<Integer>(6);
verticies.add(v6);
Graph.Vertex<Integer> v7 = new Graph.Vertex<Integer>(7);
verticies.add(v7);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> e1_2 = new Graph.Edge<Integer>(7, v1, v2);
edges.add(e1_2);
Graph.Edge<Integer> e1_3 = new Graph.Edge<Integer>(9, v1, v3);
edges.add(e1_3);
Graph.Edge<Integer> e1_6 = new Graph.Edge<Integer>(14, v1, v6);
edges.add(e1_6);
Graph.Edge<Integer> e2_3 = new Graph.Edge<Integer>(10, v2, v3);
edges.add(e2_3);
Graph.Edge<Integer> e2_4 = new Graph.Edge<Integer>(15, v2, v4);
edges.add(e2_4);
Graph.Edge<Integer> e3_4 = new Graph.Edge<Integer>(11, v3, v4);
edges.add(e3_4);
Graph.Edge<Integer> e3_6 = new Graph.Edge<Integer>(2, v3, v6);
edges.add(e3_6);
Graph.Edge<Integer> e6_5 = new Graph.Edge<Integer>(9, v6, v5);
edges.add(e6_5);
Graph.Edge<Integer> e4_5 = new Graph.Edge<Integer>(6, v4, v5);
edges.add(e4_5);
Graph.Edge<Integer> e4_7 = new Graph.Edge<Integer>(16, v4, v7);
edges.add(e4_7);
Graph<Integer> directed = new Graph<Integer>(Graph.TYPE.DIRECTED,verticies,edges);
if (debug>1) System.out.println(directed.toString());
Graph.Vertex<Integer> start = v1;
if (debug>1) System.out.println("Dijstra's shortest paths of the directed graph from "+start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map = Dijkstra.getShortestPaths(directed, start);
if (debug>1) System.out.println(getPathMapString(start,map));
Graph.Vertex<Integer> end = v5;
if (debug>1) System.out.println("Dijstra's shortest path of the directed graph from "+start.getValue()+" to "+end.getValue());
Graph.CostPathPair<Integer> pair = Dijkstra.getShortestPath(directed, start, end);
if (debug>1) {
if (pair!=null) System.out.println(pair.toString());
else System.out.println("No path from "+start.getValue()+" to "+end.getValue());
}
start = v1;
if (debug>1) System.out.println("Bellman-Ford's shortest paths of the undirected graph from "+start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map2 = BellmanFord.getShortestPaths(directed, start);
if (debug>1) System.out.println(getPathMapString(start,map2));
end = v5;
if (debug>1) System.out.println("Bellman-Ford's shortest path of the undirected graph from "+start.getValue()+" to "+end.getValue());
Graph.CostPathPair<Integer> pair2 = BellmanFord.getShortestPath(directed, start, end);
if (debug>1) {
if (pair2!=null) System.out.println(pair2.toString());
else System.out.println("No path from "+start.getValue()+" to "+end.getValue());
}
if (debug>1) System.out.println();
}
{
// DIRECTED GRAPH (WITH NEGATIVE WEIGHTS)
if (debug>1) System.out.println("Undirected Graph with Negative Weights.");
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> v1 = new Graph.Vertex<Integer>(1);
verticies.add(v1);
Graph.Vertex<Integer> v2 = new Graph.Vertex<Integer>(2);
verticies.add(v2);
Graph.Vertex<Integer> v3 = new Graph.Vertex<Integer>(3);
verticies.add(v3);
Graph.Vertex<Integer> v4 = new Graph.Vertex<Integer>(4);
verticies.add(v4);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> e1_4 = new Graph.Edge<Integer>(2, v1, v4);
edges.add(e1_4);
Graph.Edge<Integer> e2_1 = new Graph.Edge<Integer>(6, v2, v1);
edges.add(e2_1);
Graph.Edge<Integer> e2_3 = new Graph.Edge<Integer>(3, v2, v3);
edges.add(e2_3);
Graph.Edge<Integer> e3_1 = new Graph.Edge<Integer>(4, v3, v1);
edges.add(e3_1);
Graph.Edge<Integer> e3_4 = new Graph.Edge<Integer>(5, v3, v4);
edges.add(e3_4);
Graph.Edge<Integer> e4_2 = new Graph.Edge<Integer>(-7, v4, v2);
edges.add(e4_2);
Graph.Edge<Integer> e4_3 = new Graph.Edge<Integer>(-3, v4, v3);
edges.add(e4_3);
Graph<Integer> directed = new Graph<Integer>(Graph.TYPE.DIRECTED,verticies,edges);
if (debug>1) System.out.println(directed.toString());
Graph.Vertex<Integer> start = v1;
if (debug>1) System.out.println("Bellman-Ford's shortest paths of the directed graph from "+start.getValue());
Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map2 = BellmanFord.getShortestPaths(directed, start);
if (debug>1) System.out.println(getPathMapString(start,map2));
Graph.Vertex<Integer> end = v3;
if (debug>1) System.out.println("Bellman-Ford's shortest path of the directed graph from "+start.getValue()+" to "+end.getValue());
Graph.CostPathPair<Integer> pair2 = BellmanFord.getShortestPath(directed, start, end);
if (debug>1) {
if (pair2!=null) System.out.println(pair2.toString());
else System.out.println("No path from "+start.getValue()+" to "+end.getValue());
}
if (debug>1) System.out.println("Johnson's all-pairs shortest path of the directed graph.");
Map<Vertex<Integer>, Map<Vertex<Integer>, Set<Edge<Integer>>>> paths = Johnson.getAllPairsShortestPaths(directed);
if (debug>1) {
if (paths==null) System.out.println("Directed graph contains a negative weight cycle.");
else System.out.println(getPathMapString(paths));
}
if (debug>1) System.out.println("Floyd-Warshall's all-pairs shortest path weights of the directed graph.");
Map<Vertex<Integer>, Map<Vertex<Integer>, Integer>> pathWeights = FloydWarshall.getAllPairsShortestPaths(directed);
if (debug>1) System.out.println(getWeightMapString(pathWeights));
if (debug>1) System.out.println();
}
{
// UNDIRECTED GRAPH
if (debug>1) System.out.println("Undirected Graph cycle check.");
java.util.List<Vertex<Integer>> cycledVerticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> cv1 = new Graph.Vertex<Integer>(1);
cycledVerticies.add(cv1);
Graph.Vertex<Integer> cv2 = new Graph.Vertex<Integer>(2);
cycledVerticies.add(cv2);
Graph.Vertex<Integer> cv3 = new Graph.Vertex<Integer>(3);
cycledVerticies.add(cv3);
Graph.Vertex<Integer> cv4 = new Graph.Vertex<Integer>(4);
cycledVerticies.add(cv4);
Graph.Vertex<Integer> cv5 = new Graph.Vertex<Integer>(5);
cycledVerticies.add(cv5);
Graph.Vertex<Integer> cv6 = new Graph.Vertex<Integer>(6);
cycledVerticies.add(cv6);
java.util.List<Edge<Integer>> cycledEdges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> ce1_2 = new Graph.Edge<Integer>(7, cv1, cv2);
cycledEdges.add(ce1_2);
Graph.Edge<Integer> ce2_4 = new Graph.Edge<Integer>(15, cv2, cv4);
cycledEdges.add(ce2_4);
Graph.Edge<Integer> ce3_4 = new Graph.Edge<Integer>(11, cv3, cv4);
cycledEdges.add(ce3_4);
Graph.Edge<Integer> ce3_6 = new Graph.Edge<Integer>(2, cv3, cv6);
cycledEdges.add(ce3_6);
Graph.Edge<Integer> ce5_6 = new Graph.Edge<Integer>(9, cv5, cv6);
cycledEdges.add(ce5_6);
Graph.Edge<Integer> ce4_5 = new Graph.Edge<Integer>(6, cv4, cv5);
cycledEdges.add(ce4_5);
Graph<Integer> undirectedWithCycle = new Graph<Integer>(cycledVerticies,cycledEdges);
if (debug>1) System.out.println(undirectedWithCycle.toString());
if (debug>1) {
System.out.println("Cycle detection of the undirected graph.");
boolean result = CycleDetection.detect(undirectedWithCycle);
System.out.println("result="+result);
System.out.println();
}
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> v1 = new Graph.Vertex<Integer>(1);
verticies.add(v1);
Graph.Vertex<Integer> v2 = new Graph.Vertex<Integer>(2);
verticies.add(v2);
Graph.Vertex<Integer> v3 = new Graph.Vertex<Integer>(3);
verticies.add(v3);
Graph.Vertex<Integer> v4 = new Graph.Vertex<Integer>(4);
verticies.add(v4);
Graph.Vertex<Integer> v5 = new Graph.Vertex<Integer>(5);
verticies.add(v5);
Graph.Vertex<Integer> v6 = new Graph.Vertex<Integer>(6);
verticies.add(v6);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> e1_2 = new Graph.Edge<Integer>(7, v1, v2);
edges.add(e1_2);
Graph.Edge<Integer> e2_4 = new Graph.Edge<Integer>(15, v2, v4);
edges.add(e2_4);
Graph.Edge<Integer> e3_4 = new Graph.Edge<Integer>(11, v3, v4);
edges.add(e3_4);
Graph.Edge<Integer> e3_6 = new Graph.Edge<Integer>(2, v3, v6);
edges.add(e3_6);
Graph.Edge<Integer> e4_5 = new Graph.Edge<Integer>(6, v4, v5);
edges.add(e4_5);
Graph<Integer> undirectedWithoutCycle = new Graph<Integer>(verticies,edges);
if (debug>1) System.out.println(undirectedWithoutCycle.toString());
if (debug>1) {
System.out.println("Cycle detection of the undirected graph.");
boolean result = CycleDetection.detect(undirectedWithoutCycle);
System.out.println("result="+result);
System.out.println();
}
}
{
// DIRECTED GRAPH
if (debug>1) System.out.println("Directed Graph topological sort.");
java.util.List<Vertex<Integer>> verticies = new ArrayList<Vertex<Integer>>();
Graph.Vertex<Integer> cv1 = new Graph.Vertex<Integer>(1);
verticies.add(cv1);
Graph.Vertex<Integer> cv2 = new Graph.Vertex<Integer>(2);
verticies.add(cv2);
Graph.Vertex<Integer> cv3 = new Graph.Vertex<Integer>(3);
verticies.add(cv3);
Graph.Vertex<Integer> cv4 = new Graph.Vertex<Integer>(4);
verticies.add(cv4);
Graph.Vertex<Integer> cv5 = new Graph.Vertex<Integer>(5);
verticies.add(cv5);
Graph.Vertex<Integer> cv6 = new Graph.Vertex<Integer>(6);
verticies.add(cv6);
java.util.List<Edge<Integer>> edges = new ArrayList<Edge<Integer>>();
Graph.Edge<Integer> ce1_2 = new Graph.Edge<Integer>(1, cv1, cv2);
edges.add(ce1_2);
Graph.Edge<Integer> ce2_4 = new Graph.Edge<Integer>(2, cv2, cv4);
edges.add(ce2_4);
Graph.Edge<Integer> ce4_3 = new Graph.Edge<Integer>(3, cv4, cv3);
edges.add(ce4_3);
Graph.Edge<Integer> ce3_6 = new Graph.Edge<Integer>(4, cv3, cv6);
edges.add(ce3_6);
Graph.Edge<Integer> ce5_6 = new Graph.Edge<Integer>(5, cv5, cv6);
edges.add(ce5_6);
Graph.Edge<Integer> ce4_5 = new Graph.Edge<Integer>(6, cv4, cv5);
edges.add(ce4_5);
Graph<Integer> directed = new Graph<Integer>(Graph.TYPE.DIRECTED,verticies,edges);
if (debug>1) System.out.println(directed.toString());
if (debug>1) System.out.println("Topological sort of the directed graph.");
java.util.List<Graph.Vertex<Integer>> results = TopologicalSort.sort(directed);
if (debug>1) {
System.out.println("result="+results);
System.out.println();
}
}
return true;
}
private static boolean testHeap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Min-Heap [array]
if (debug>1) System.out.println("Min-Heap [array].");
testNames[test] = "Min-Heap [array]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
BinaryHeap<Integer> minHeap = new BinaryHeap.BinaryHeapArray<Integer>(BinaryHeap.Type.MIN);
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Min-Heap [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Min-Heap [array] memory use = "+(memory/count)+" bytes");
}
boolean contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Min-Heap [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(minHeap);
return false;
}
}
if (validateStructure && minHeap.getHeadValue()!=null) {
System.err.println("YIKES!! Min-Heap [array] isn't empty.");
handleError(minHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Min-Heap [array] remove time = "+removeTime/count+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [array] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Min-Heap [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Min-Heap [array] memory use = "+(memory/count)+" bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Min-Heap [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(minHeap);
return false;
}
}
if (validateStructure && minHeap.getHeadValue()!=null) {
System.err.println("YIKES!! Min-Heap [array] isn't empty.");
handleError(minHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Min-Heap [array] remove time = "+removeTime/count+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [array] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Min-Heap [array] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Min-Heap [array] memory use = "+(memory/(count+1))+" bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Min-Heap [array] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [array] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Min-Heap [array] remove time = "+removeSortedTime+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [array] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Min-Heap [tree]
if (debug>1) System.out.println("Min-Heap [tree].");
testNames[test] = "Min-Heap [tree]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
BinaryHeap<Integer> minHeap = new BinaryHeap.BinaryHeapTree<Integer>(BinaryHeap.Type.MIN);
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Min-Heap [tree] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Min-Heap [tree] memory use = "+(memory/count)+" bytes");
}
boolean contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [tree] invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Min-Heap [tree] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(minHeap);
return false;
}
}
if (validateStructure && minHeap.getHeadValue()!=null) {
System.err.println("YIKES!! Min-Heap [tree] isn't empty.");
handleError(minHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Min-Heap [tree] remove time = "+removeTime/count+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [tree] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Min-Heap [tree] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Min-Heap [tree] memory use = "+(memory/count)+" bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [tree] invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Min-Heap [tree] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(minHeap);
return false;
}
}
if (validateStructure && minHeap.getHeadValue()!=null) {
System.err.println("YIKES!! Min-Heap [tree] isn't empty.");
handleError(minHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Min-Heap [tree] remove time = "+removeTime/count+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [tree] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
minHeap.add(item);
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && !minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Min-Heap [tree] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Min-Heap [tree] memory use = "+(memory/(count+1))+" bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [tree] invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Min-Heap [tree] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = minHeap.removeHead();
if (validateStructure && !minHeap.validate()) {
System.err.println("YIKES!! Min-Heap [tree] isn't valid.");
handleError(minHeap);
return false;
}
if (validateStructure && !(minHeap.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(minHeap);
return false;
}
if (validateContents && minHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(minHeap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Min-Heap [tree] remove time = "+removeSortedTime+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Min-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Min-Heap [tree] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Max-Heap [array]
if (debug>1) System.out.println("Max-Heap [array].");
testNames[test] = "Max-Heap [array]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
BinaryHeap<Integer> maxHeap = new BinaryHeap.BinaryHeapArray<Integer>(BinaryHeap.Type.MAX);
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Max-Heap [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Max-Heap [array] memory use = "+(memory/count)+" bytes");
}
boolean contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Max-Heap [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(maxHeap);
return false;
}
}
if (validateStructure && maxHeap.getHeadValue()!=null) {
System.err.println("YIKES!! Max-Heap [array] isn't empty.");
handleError(maxHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Max-Heap [array] remove time = "+removeTime/count+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [array] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Max-Heap [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Max-Heap [array] memory use = "+(memory/count)+" bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Max-Heap [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(maxHeap);
return false;
}
}
if (validateStructure && maxHeap.getHeadValue()!=null) {
System.err.println("YIKES!! Max-Heap [array] isn't empty.");
handleError(maxHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Max-Heap [array] remove time = "+removeTime/count+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [array] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Max-Heap [array] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Max-Heap [array] memory use = "+(memory/(count+1))+" bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Max-Heap [array] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [array] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Max-Heap [array] remove time = "+removeSortedTime+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [array] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Max-Heap [tree]
if (debug>1) System.out.println("Max-Heap [tree].");
testNames[test] = "Max-Heap [tree]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
BinaryHeap<Integer> maxHeap = new BinaryHeap.BinaryHeapTree<Integer>(BinaryHeap.Type.MAX);
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Max-Heap [tree] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Max-Heap [tree] memory use = "+(memory/count)+" bytes");
}
boolean contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [tree] invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Max-Heap [tree] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(maxHeap);
return false;
}
}
if (validateStructure && maxHeap.getHeadValue()!=null) {
System.err.println("YIKES!! Max-Heap [tree] isn't empty.");
handleError(maxHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Max-Heap [tree] remove time = "+removeTime/count+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [tree] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Max-Heap [tree] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Max-Heap [tree] memory use = "+(memory/count)+" bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [tree] invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Max-Heap [tree] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(maxHeap);
return false;
}
}
if (validateStructure && maxHeap.getHeadValue()!=null) {
System.err.println("YIKES!! Max-Heap [tree] isn't empty.");
handleError(maxHeap);
return false;
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Max-Heap [tree] remove time = "+removeTime/count+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [tree] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
maxHeap.add(item);
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && !maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Max-Heap [tree] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Max-Heap [tree] memory use = "+(memory/(count+1))+" bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [tree] invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Max-Heap [tree] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = maxHeap.removeHead();
if (validateStructure && !maxHeap.validate()) {
System.err.println("YIKES!! Max-Heap [tree] isn't valid.");
handleError(maxHeap);
return false;
}
if (validateStructure && !(maxHeap.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(maxHeap);
return false;
}
if (validateContents && maxHeap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(maxHeap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Max-Heap [tree] remove time = "+removeSortedTime+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Max-Heap [tree] invalidity check. contains="+contains);
return false;
} else System.out.println("Max-Heap [tree] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testHashMap() {
int key = unsorted.length/2;
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Hash Map
if (debug>1) System.out.println("Hash Map.");
testNames[test] = "Hash Map";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
HashMap<Integer,String> hash = new HashMap<Integer,String>(key);
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
hash.put(item, string);
if (validateStructure && !(hash.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && !hash.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Hash Map add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Hash Map memory use = "+(memory/count)+" bytes");
}
boolean contains = hash.contains(INVALID);
boolean removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(hash.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
hash.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Hash Map lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
hash.remove(item);
if (validateStructure && !(hash.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && hash.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Hash Map remove time = "+removeTime/count+" ms");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
String string = String.valueOf(item);
hash.put(item,string);
if (validateStructure && !(hash.size()==(unsorted.length-i))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && !hash.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Hash Map add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Hash Map memory use = "+(memory/count)+" bytes");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(hash.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
hash.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Hash Map lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
hash.remove(item);
if (validateStructure && !(hash.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && hash.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Hash Map remove time = "+removeTime/count+" ms");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
hash.put(item,string);
if (validateStructure && !(hash.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && !hash.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Hash Map add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Hash Map memory use = "+(memory/(count+1))+" bytes");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(hash.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
hash.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Hash Map lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
hash.remove(item);
if (validateStructure && !(hash.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(hash);
return false;
}
if (validateContents && hash.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(hash);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Hash Map remove time = "+removeSortedTime+" ms");
}
contains = hash.contains(INVALID);
removed = hash.remove(INVALID);
if (contains || removed) {
System.err.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Hash Map invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testJavaHashMap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's Hash Map
if (debug>1) System.out.println("Java's Hash Map.");
testNames[test] = "Java's Hash Map";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
java.util.HashMap<Integer,String> hash = new java.util.HashMap<Integer,String>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
hash.put(item, string);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Hash Map add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Hash Map memory use = "+(memory/count)+" bytes");
}
boolean contains = hash.containsKey(INVALID);
String removed = hash.remove(INVALID);
if (contains || removed!=null) {
System.err.println("Java's Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Hash Map invalidity check. contains="+contains+" removed="+(removed!=null));
if (debug>1) System.out.println(hash.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
hash.containsKey(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Hash Map lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
hash.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Hash Map remove time = "+removeTime/count+" ms");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed!=null) {
System.err.println("Java's Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Hash Map invalidity check. contains="+contains+" removed="+(removed!=null));
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
String string = String.valueOf(item);
hash.put(item,string);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Hash Map add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Hash Map memory use = "+(memory/count)+" bytes");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed!=null) {
System.err.println("Java's Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Hash Map invalidity check. contains="+contains+" removed="+(removed!=null));
if (debug>1) System.out.println(hash.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
hash.containsKey(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Hash Map lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
hash.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Hash Map remove time = "+removeTime/count+" ms");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed!=null) {
System.err.println("Java's Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Hash Map invalidity check. contains="+contains+" removed="+(removed!=null));
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
hash.put(item,string);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's Hash Map add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Hash Map memory use = "+(memory/(count+1))+" bytes");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed!=null) {
System.err.println("Java's Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Hash Map invalidity check. contains="+contains+" removed="+(removed!=null));
if (debug>1) System.out.println(hash.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
hash.containsKey(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Hash Map lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
hash.remove(item);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's Hash Map remove time = "+removeSortedTime+" ms");
}
contains = hash.containsKey(INVALID);
removed = hash.remove(INVALID);
if (contains || removed!=null) {
System.err.println("Java's Hash Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Hash Map invalidity check. contains="+contains+" removed="+(removed!=null));
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testJavaHeap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// MIN-HEAP
if (debug>1) System.out.println("Java's Min-Heap.");
testNames[test] = "Java's Min-Heap";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
java.util.PriorityQueue<Integer> minHeap = new java.util.PriorityQueue<Integer>(10,
new Comparator<Integer>() {
@Override
public int compare(Integer arg0, Integer arg1) {
if (arg0.compareTo(arg1)==-1) return -1;
else if (arg1.compareTo(arg0)==-1) return 1;
return 0;
}
}
);
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
minHeap.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Min-Heap add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Min-Heap memory use = "+(memory/count)+" bytes");
}
boolean contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Min-Heap invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Min-Heap lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
minHeap.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Min-Heap remove time = "+removeTime/count+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Min-Heap invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
minHeap.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Min-Heap add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Min-Heap memory use = "+(memory/count)+" bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Min-Heap invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Min-Heap lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
minHeap.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Min-Heap remove time = "+removeTime/count+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Min-Heap invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
minHeap.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's Min-Heap add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Min-Heap memory use = "+(memory/(count+1))+" bytes");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Min-Heap invalidity check. contains="+contains);
if (debug>1) System.out.println(minHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
minHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Min-Heap lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
minHeap.remove();
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's Min-Heap remove time = "+removeSortedTime+" ms");
}
contains = minHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Min-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Min-Heap invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// MAX-HEAP
if (debug>1) System.out.println("Java's Max-Heap.");
testNames[test] = "Java's Max-Heap";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
java.util.PriorityQueue<Integer> maxHeap = new java.util.PriorityQueue<Integer>(10,
new Comparator<Integer>() {
@Override
public int compare(Integer arg0, Integer arg1) {
if (arg0.compareTo(arg1)==1) return -1;
else if (arg1.compareTo(arg0)==1) return 1;
return 0;
}
}
);
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
maxHeap.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Max-Heap add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Max-Heap memory use = "+(memory/count)+" bytes");
}
boolean contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Max-Heap invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Max-Heap lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
maxHeap.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Max-Heap remove time = "+removeTime/count+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Max-Heap invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
maxHeap.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Max-Heap add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Max-Heap memory use = "+(memory/count)+" bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Max-Heap invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Max-Heap lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
maxHeap.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Max-Heap remove time = "+removeTime/count+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Max-Heap invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
maxHeap.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's Max-Heap add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Max-Heap memory use = "+(memory/(count+1))+" bytes");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Max-Heap invalidity check. contains="+contains);
if (debug>1) System.out.println(maxHeap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
maxHeap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Max-Heap lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
maxHeap.remove();
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's Max-Heap remove time = "+removeSortedTime+" ms");
}
contains = maxHeap.contains(INVALID);
if (contains) {
System.err.println("Java's Max-Heap invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Max-Heap invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testJavaList() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's List [array]
if (debug>1) System.out.println("Java's List [array].");
testNames[test] = "Java's List [array]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
java.util.ArrayList<Integer> list = new java.util.ArrayList<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
list.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's List [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's List [array] memory use = "+(memory/count)+" bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's List [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
Integer item = unsorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's List [array] remove time = "+removeTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
list.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's List [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's List [array] memory use = "+(memory/count)+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's List [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
Integer item = unsorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's List [array] remove time = "+removeTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
list.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's List [array] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's List [array] memory use = "+(memory/(count+1))+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's List [array] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
Integer item = sorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's List [array] remove time = "+removeSortedTime+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [array] invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's List [linked]
if (debug>1) System.out.println("Java's List [linked].");
testNames[test] = "Java's List [linked]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
java.util.LinkedList<Integer> list = new java.util.LinkedList<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
list.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's List [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's List [linked] memory use = "+(memory/count)+" bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's List [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
Integer item = unsorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's List [linked] remove time = "+removeTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
list.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's List [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's List [linked] memory use = "+(memory/count)+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's List [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
Integer item = unsorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's List [linked] remove time = "+removeTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
list.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's List [linked] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's List [linked] memory use = "+(memory/(count+1))+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's List [linked] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
Integer item = sorted[i];
list.remove(item);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's List [linked] remove time = "+removeSortedTime+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's List [linked] invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testJavaQueue() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's Queue [array]
if (debug>1) System.out.println("Java's Queue [array].");
testNames[test] = "Java's Queue [array]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
java.util.Queue<Integer> queue = new java.util.ArrayDeque<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
queue.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Queue [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Queue [array] memory use = "+(memory/count)+" bytes");
}
boolean contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Queue [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
int size = queue.size();
for (int i=0; i<size; i++) {
queue.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Queue [array] remove time = "+removeTime/count+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [array] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
queue.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Queue [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Queue [array] memory use = "+(memory/count)+" bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Queue [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
queue.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Queue [array] remove time = "+removeTime/count+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [array] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
queue.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's Queue [array] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Queue [array] memory use = "+(memory/(count+1))+" bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Queue [array] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
queue.remove();
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's Queue [array] remove time = "+removeSortedTime+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [array] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// LinkedQueue
if (debug>1) System.out.println("Java's Queue [linked].");
testNames[test] = "Java's Queue [linked]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
java.util.Queue<Integer> queue = new java.util.LinkedList<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
queue.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Queue [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Queue [linked] memory use = "+(memory/count)+" bytes");
}
boolean contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Queue [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
int size = queue.size();
for (int i=0; i<size; i++) {
queue.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Queue [linked] remove time = "+removeTime/count+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [linked] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
queue.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Queue [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Queue [linked] memory use = "+(memory/count)+" bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Queue [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
queue.remove();
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Queue [linked] remove time = "+removeTime/count+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [linked] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
queue.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's Queue [linked] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Queue [linked] memory use = "+(memory/(count+1))+" bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Queue [linked] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
queue.remove();
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's Queue [linked] remove time = "+removeSortedTime+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Java's Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Queue [linked] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testJavaRedBlackTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Java's Red-Black Tree
if (debug>1) System.out.println("Java's Red-Black Tree");
testNames[test] = "Java's RedBlack Tree";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
java.util.TreeSet<Integer> tree = new java.util.TreeSet<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Red-Black Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Red-Black Tree memory use = "+(memory/count)+" bytes");
}
boolean contains = tree.contains(INVALID);
boolean removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Red-Black lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Red-Black Tree remove time = "+removeTime/count+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
tree.add(item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Red-Black Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Red-Black Tree memory use = "+(memory/count)+" bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Red-Black Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Red-Black Tree remove time = "+removeTime/count+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
tree.add(item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's Red-Black Tree add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Red-Black Tree memory use = "+(memory/(count+1))+" bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Red-Black Tree lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
tree.remove(item);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's Red-Black Tree remove time = "+removeSortedTime+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testJavaStack() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Java's Stack [vector]
if (debug>1) System.out.println("Java's Stack [vector].");
testNames[test] = "Java's Stack [vector]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
Stack<Integer> stack = new Stack.ArrayStack<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Stack [vector] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Stack [vector] memory use = "+(memory/count)+" bytes");
}
boolean contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Stack [vector] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Stack [vector] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
int size = stack.size();
for (int i=0; i<size; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Stack [vector] remove time = "+removeTime/count+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Stack [vector] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Stack [vector] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Stack [vector] memory use = "+(memory/count)+" bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Stack [vector] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Stack [vector] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Stack [vector] remove time = "+removeTime/count+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Stack [vector] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's Stack [vector] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Stack [vector] memory use = "+(memory/(count+1))+" bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Stack [vector] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Stack [vector] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = stack.pop();
if (validateStructure && !(stack.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's Stack [vector] remove time = "+removeSortedTime+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Java's Stack [vector] invalidity check. contains="+contains);
return false;
} else System.out.println("Java's Stack [vector] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testJavaTreeMap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Java's Tree Map
if (debug>1) System.out.println("Java's Tree Map.");
testNames[test] = "Java's Tree Map";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
java.util.TreeMap<String,Integer> trieMap = new java.util.TreeMap<String,Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Tree Map add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Tree Map memory use = "+(memory/count)+" bytes");
}
String invalid = INVALID.toString();
boolean contains = trieMap.containsKey(invalid);
Integer removed = trieMap.remove(invalid);
if (contains || removed!=null) {
System.err.println("Java's Tree Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Tree Map invalidity check. contains="+contains+" removed="+(removed!=null));
if (debug>1) System.out.println(trieMap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trieMap.containsKey(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Tree Map lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Tree Map remove time = "+removeTime/count+" ms");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed!=null) {
System.err.println("Java's Tree Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Tree Map invalidity check. contains="+contains+" removed="+(removed!=null));
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Java's Tree Map add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Tree Map memory use = "+(memory/count)+" bytes");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed!=null) {
System.err.println("Java's Tree Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Tree Map invalidity check. contains="+contains+" removed="+(removed!=null));
if (debug>1) System.out.println(trieMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trieMap.containsKey(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Tree Map lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Java's Tree Map remove time = "+removeTime/count+" ms");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed!=null) {
System.err.println("Java's Tree Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Tree Map invalidity check. contains="+contains+" removed="+(removed!=null));
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
trieMap.put(string,item);
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Java's Tree Map add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Java's Tree Map memory use = "+(memory/(count+1))+" bytes");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed!=null) {
System.err.println("Java's Tree Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Tree Map invalidity check. contains="+contains+" removed="+(removed!=null));
if (debug>1) System.out.println(trieMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
trieMap.containsKey(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Java's Tree Map lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Java's Tree Map remove time = "+removeSortedTime+" ms");
}
contains = trieMap.containsKey(invalid);
removed = trieMap.remove(invalid);
if (contains || removed!=null) {
System.err.println("Java's Tree Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Java's Tree Map invalidity check. contains="+contains+" removed="+(removed!=null));
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testList() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// List [array]
if (debug>1) System.out.println("List [array].");
testNames[test] = "List [array]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
List<Integer> list = new List.ArrayList<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
list.add(item);
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("List [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("List [array] memory use = "+(memory/count)+" bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [array] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("List [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
list.remove(item);
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("List [array] remove time = "+removeTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [array] invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
list.add(item);
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("List [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("List [array] memory use = "+(memory/count)+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [array] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("List [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
list.remove(item);
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("List [array] remove time = "+removeTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [array] invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
list.add(item);
if (validateStructure && !(list.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("List [array] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("List [array] memory use = "+(memory/(count+1))+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [array] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("List [array] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
list.remove(item);
if (validateStructure && !(list.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("List [array] remove time = "+removeSortedTime+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [array] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [array] invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// List [linked]
if (debug>1) System.out.println("List [linked].");
testNames[test] = "List [linked]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
List<Integer> list = new List.LinkedList<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
list.add(item);
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("List [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("List [linked] memory use = "+(memory/count)+" bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("List [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
list.remove(item);
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("List [linked] remove time = "+removeTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
list.add(item);
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("List [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("List [linked] memory use = "+(memory/count)+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("List [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
list.remove(item);
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(list);
return false;
}
if (validateStructure && !(list.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("List [linked] remove time = "+removeTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
list.add(item);
if (validateStructure && !(list.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("List [linked] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("List [linked] memory use = "+(memory/(count+1))+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("List [linked] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
list.remove(item);
if (validateStructure && !(list.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("List [linked] remove time = "+removeSortedTime+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("List [linked] invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testMatrix() {
{
// MATRIX
if (debug>1) System.out.println("Matrix.");
Matrix<Integer> matrix1 = new Matrix<Integer>(4,3);
matrix1.set(0, 0, 14);
matrix1.set(0, 1, 9);
matrix1.set(0, 2, 3);
matrix1.set(1, 0, 2);
matrix1.set(1, 1, 11);
matrix1.set(1, 2, 15);
matrix1.set(2, 0, 0);
matrix1.set(2, 1, 12);
matrix1.set(2, 2, 17);
matrix1.set(3, 0, 5);
matrix1.set(3, 1, 2);
matrix1.set(3, 2, 3);
Matrix<Integer> matrix2 = new Matrix<Integer>(3,2);
matrix2.set(0, 0, 12);
matrix2.set(0, 1, 25);
matrix2.set(1, 0, 9);
matrix2.set(1, 1, 10);
matrix2.set(2, 0, 8);
matrix2.set(2, 1, 5);
if (debug>1) System.out.println("Matrix multiplication.");
Matrix<Integer> matrix3 = matrix1.multiply(matrix2);
if (debug>1) System.out.println(matrix3);
int rows = 2;
int cols = 2;
int counter = 0;
Matrix<Integer> matrix4 = new Matrix<Integer>(rows,cols);
for (int r=0; r<rows; r++) {
for (int c=0; c<cols; c++) {
matrix4.set(r, c, counter++);
}
}
if (debug>1) System.out.println("Matrix subtraction.");
Matrix<Integer> matrix5 = matrix4.subtract(matrix4);
if (debug>1) System.out.println(matrix5);
if (debug>1) System.out.println("Matrix addition.");
Matrix<Integer> matrix6 = matrix4.add(matrix4);
if (debug>1) System.out.println(matrix6);
Matrix<Integer> matrix7 = new Matrix<Integer>(2,2);
matrix7.set(0, 0, 1);
matrix7.set(0, 1, 2);
matrix7.set(1, 0, 3);
matrix7.set(1, 1, 4);
Matrix<Integer> matrix8 = new Matrix<Integer>(2,2);
matrix8.set(0, 0, 1);
matrix8.set(0, 1, 2);
matrix8.set(1, 0, 3);
matrix8.set(1, 1, 4);
if (debug>1) System.out.println("Matrix multiplication.");
Matrix<Integer> matrix9 = matrix7.multiply(matrix8);
if (debug>1) System.out.println(matrix9);
}
return true;
}
private static boolean testPatriciaTrie() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Patricia Trie
if (debug>1) System.out.println("Patricia Trie.");
testNames[test] = "Patricia Trie";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
PatriciaTrie<String> trie = new PatriciaTrie<String>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! "+string+" doesn't exist.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Patricia Trie add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Patricia Trie memory use = "+(memory/count)+" bytes");
}
String invalid = INVALID.toString();
boolean contains = trie.contains(invalid);
boolean removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trie.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Patricia Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! "+string+" still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Patricia Trie remove time = "+removeTime/count+" ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size()==(unsorted.length-i))) {
System.err.println("YIKES!! "+string+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! "+string+" doesn't exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Patricia Trie add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Patricia Trie memory use = "+(memory/count)+" bytes");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trie.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Patricia Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+string+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! "+string+" still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Patricia Trie remove time = "+removeTime/count+" ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Patricia Tree add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Patricia Tree memory use = "+(memory/(count+1))+" bytes");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trie.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Patricia Tree lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Patricia Tree remove time = "+removeSortedTime+" ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Patricia Trie invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testQueue() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Queue [array]
if (debug>1) System.out.println("Queue [array].");
testNames[test] = "Queue [array]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
Queue<Integer> queue = new Queue.ArrayQueue<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Queue [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Queue [array] memory use = "+(memory/count)+" bytes");
}
boolean contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Queue [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
int size = queue.size();
for (int i=0; i<size; i++) {
int item = queue.dequeue();
if (validateStructure && !(queue.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! "+item+" still exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Queue [array] remove time = "+removeTime/count+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [array] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Queue [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Queue [array] memory use = "+(memory/count)+" bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Queue [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = queue.dequeue();
if (validateStructure && !(queue.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! "+item+" still exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Queue [array] remove time = "+removeTime/count+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [array] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Queue [array] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Queue [array] memory use = "+(memory/(count+1))+" bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Queue [array] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = queue.dequeue();
if (validateStructure && !(queue.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Queue [array] remove time = "+removeSortedTime+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [array] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// LinkedQueue
if (debug>1) System.out.println("Queue [linked].");
testNames[test] = "Queue [linked]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
Queue<Integer> queue = new Queue.LinkedQueue<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Queue [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Queue [linked] memory use = "+(memory/count)+" bytes");
}
boolean contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Queue [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
int size = queue.size();
for (int i=0; i<size; i++) {
int item = queue.dequeue();
if (validateStructure && !(queue.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! "+item+" still exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Queue [linked] remove time = "+removeTime/count+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [linked] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Queue [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Queue [linked] memory use = "+(memory/count)+" bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Queue [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = queue.dequeue();
if (validateStructure && !(queue.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! "+item+" still exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Queue [linked] remove time = "+removeTime/count+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [linked] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
queue.enqueue(item);
if (validateStructure && !(queue.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && !queue.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Queue [linked] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Queue [linked] memory use = "+(memory/(count+1))+" bytes");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(queue.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
queue.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Queue [linked] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = queue.dequeue();
if (validateStructure && !(queue.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(queue);
return false;
}
if (validateContents && queue.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(queue);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Queue [linked] remove time = "+removeSortedTime+" ms");
}
contains = queue.contains(INVALID);
if (contains) {
System.err.println("Queue [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Queue [linked] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testRadixTrie() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Radix Trie (map)
if (debug>1) System.out.println("Radix Trie (map).");
testNames[test] = "Radix Trie (map)";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
RadixTrie<String,Integer> tree = new RadixTrie<String,Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
tree.put(string, item);
if (validateStructure && !(tree.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(string)) {
System.err.println("YIKES!! "+string+" doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Radix Trie add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Radix Trie memory use = "+(memory/count)+" bytes");
}
String invalid = INVALID.toString();
boolean contains = tree.contains(invalid);
boolean removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
tree.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Radix Trie lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
tree.remove(string);
if (validateStructure && !(tree.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(string)) {
System.err.println("YIKES!! "+string+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Radix Trie remove time = "+removeTime/count+" ms");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
String string = String.valueOf(item);
tree.put(string, item);
if (validateStructure && !(tree.size()==(unsorted.length-i))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(string)) {
System.err.println("YIKES!! "+string+" doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Radix Trie add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Radix Trie memory use = "+(memory/count)+" bytes");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
tree.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Radix Trie lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
tree.remove(string);
if (validateStructure && !(tree.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(string)) {
System.err.println("YIKES!! "+string+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Radix Trie remove time = "+removeTime/count+" ms");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
tree.put(string,item);
if (validateStructure && !(tree.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(string)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Radix Trie add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Radix Trie memory use = "+(memory/(count+1))+" bytes");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
tree.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Radix Trie lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
String string = String.valueOf(item);
tree.remove(string);
if (validateStructure && !(tree.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(string)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Radix Trie remove time = "+removeSortedTime+" ms");
}
contains = tree.contains(invalid);
removed = tree.remove(invalid);
if (contains || removed) {
System.err.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Radix Trie invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testRedBlackTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Red-Black Tree
if (debug>1) System.out.println("Red-Black Tree");
testNames[test] = "RedBlack Tree";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
RedBlackTree<Integer> tree = new RedBlackTree<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Red-Black Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Red-Black Tree memory use = "+(memory/count)+" bytes");
}
boolean contains = tree.contains(INVALID);
boolean removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Red-Black lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Red-Black Tree remove time = "+removeTime/count+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==(unsorted.length-i))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Red-Black Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Red-Black Tree memory use = "+(memory/count)+" bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Red-Black Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Red-Black Tree remove time = "+removeTime/count+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
tree.add(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && !tree.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Red-Black Tree add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Red-Black Tree memory use = "+(memory/(count+1))+" bytes");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(tree.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
tree.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Red-Black Tree lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
tree.remove(item);
if (validateStructure && !tree.validate()) {
System.err.println("YIKES!! Red-Black Tree isn't valid.");
handleError(tree);
return false;
}
if (validateStructure && !(tree.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(tree);
return false;
}
if (validateContents && tree.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(tree);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Red-Black Tree remove time = "+removeSortedTime+" ms");
}
contains = tree.contains(INVALID);
removed = tree.remove(INVALID);
if (contains || removed) {
System.err.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Red-Black Tree invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testSegmentTree() {
{
//Quadrant Segment tree
if (debug>1) System.out.println("Quadrant Segment Tree.");
java.util.List<QuadrantData> segments = new ArrayList<QuadrantData>();
segments.add(new QuadrantData(0, 1, 0, 0, 0)); //first point in the 0th quadrant
segments.add(new QuadrantData(1, 0, 1, 0, 0)); //second point in the 1st quadrant
segments.add(new QuadrantData(2, 0, 0, 1, 0)); //third point in the 2nd quadrant
segments.add(new QuadrantData(3, 0, 0, 0, 1)); //fourth point in the 3rd quadrant
FlatSegmentTree<QuadrantData> tree = new FlatSegmentTree<QuadrantData>(segments);
if (debug>1) System.out.println(tree);
QuadrantData query = tree.query(0, 3);
if (debug>1) System.out.println("0->3: "+query+"\n");
query = tree.query(2, 3);
if (debug>1) System.out.println("2->3: "+query+"\n");
query = tree.query(0, 2);
if (debug>1) System.out.println("0->2: "+query+"\n");
if (debug>1) System.out.println();
}
{
//Range Maximum Segment tree
if (debug>1) System.out.println("Range Maximum Segment Tree.");
java.util.List<RangeMaximumData<Integer>> segments = new ArrayList<RangeMaximumData<Integer>>();
segments.add(new RangeMaximumData<Integer>(0, (Integer)4));
segments.add(new RangeMaximumData<Integer>(1, (Integer)2));
segments.add(new RangeMaximumData<Integer>(2, (Integer)6));
segments.add(new RangeMaximumData<Integer>(3, (Integer)3));
segments.add(new RangeMaximumData<Integer>(4, (Integer)1));
segments.add(new RangeMaximumData<Integer>(5, (Integer)5));
segments.add(new RangeMaximumData<Integer>(6, (Integer)0));
segments.add(new RangeMaximumData<Integer>(7, 17, (Integer)7));
segments.add(new RangeMaximumData<Integer>(21, (Integer)10));
FlatSegmentTree<RangeMaximumData<Integer>> tree = new FlatSegmentTree<RangeMaximumData<Integer>>(segments,3);
if (debug>1) System.out.println(tree);
RangeMaximumData<Integer> query = tree.query(0, 7);
if (debug>1) System.out.println("0->7: "+query+"\n");
query = tree.query(0, 21);
if (debug>1) System.out.println("0->21: "+query+"\n");
query = tree.query(2, 5);
if (debug>1) System.out.println("2->5: "+query+"\n");
query = tree.query(7);
if (debug>1) System.out.println("7: "+query+"\n");
if (debug>1) System.out.println();
}
{
//Range Minimum Segment tree
if (debug>1) System.out.println("Range Minimum Segment Tree.");
java.util.List<RangeMinimumData<Integer>> segments = new ArrayList<RangeMinimumData<Integer>>();
segments.add(new RangeMinimumData<Integer>(0, (Integer)4));
segments.add(new RangeMinimumData<Integer>(1, (Integer)2));
segments.add(new RangeMinimumData<Integer>(2, (Integer)6));
segments.add(new RangeMinimumData<Integer>(3, (Integer)3));
segments.add(new RangeMinimumData<Integer>(4, (Integer)1));
segments.add(new RangeMinimumData<Integer>(5, (Integer)5));
segments.add(new RangeMinimumData<Integer>(6, (Integer)0));
segments.add(new RangeMinimumData<Integer>(17, (Integer)7));
FlatSegmentTree<RangeMinimumData<Integer>> tree = new FlatSegmentTree<RangeMinimumData<Integer>>(segments,5);
if (debug>1) System.out.println(tree);
RangeMinimumData<Integer> query = tree.query(0, 7);
if (debug>1) System.out.println("0->7: "+query+"\n");
query = tree.query(0, 17);
if (debug>1) System.out.println("0->17: "+query+"\n");
query = tree.query(1, 3);
if (debug>1) System.out.println("1->3: "+query+"\n");
query = tree.query(7);
if (debug>1) System.out.println("7: "+query+"\n");
if (debug>1) System.out.println();
}
{
//Range Sum Segment tree
if (debug>1) System.out.println("Range Sum Segment Tree.");
java.util.List<RangeSumData<Integer>> segments = new ArrayList<RangeSumData<Integer>>();
segments.add(new RangeSumData<Integer>(0, (Integer)4));
segments.add(new RangeSumData<Integer>(1, (Integer)2));
segments.add(new RangeSumData<Integer>(2, (Integer)6));
segments.add(new RangeSumData<Integer>(3, (Integer)3));
segments.add(new RangeSumData<Integer>(4, (Integer)1));
segments.add(new RangeSumData<Integer>(5, (Integer)5));
segments.add(new RangeSumData<Integer>(6, (Integer)0));
segments.add(new RangeSumData<Integer>(17, (Integer)7));
FlatSegmentTree<RangeSumData<Integer>> tree = new FlatSegmentTree<RangeSumData<Integer>>(segments,10);
if (debug>1) System.out.println(tree);
RangeSumData<Integer> query = tree.query(0, 8);
if (debug>1) System.out.println("0->8: "+query+"\n");
query = tree.query(0, 17);
if (debug>1) System.out.println("0->17: "+query+"\n");
query = tree.query(2, 5);
if (debug>1) System.out.println("2->5: "+query+"\n");
query = tree.query(10, 17);
if (debug>1) System.out.println("10->17: "+query+"\n");
query = tree.query(16);
if (debug>1) System.out.println("16: "+query+"\n");
query = tree.query(17);
if (debug>1) System.out.println("17: "+query+"\n");
if (debug>1) System.out.println();
}
{
//Interval Segment tree
if (debug>1) System.out.println("Interval Segment Tree.");
java.util.List<IntervalData<String>> segments = new ArrayList<IntervalData<String>>();
segments.add((new IntervalData<String>(2, 6, "RED")));
segments.add((new IntervalData<String>(3, 5, "ORANGE")));
segments.add((new IntervalData<String>(4, 11, "GREEN")));
segments.add((new IntervalData<String>(5, 10, "DARK_GREEN")));
segments.add((new IntervalData<String>(8, 12, "BLUE")));
segments.add((new IntervalData<String>(9, 14, "PURPLE")));
segments.add((new IntervalData<String>(13, 15, "BLACK")));
DynamicSegmentTree<IntervalData<String>> tree = new DynamicSegmentTree<IntervalData<String>>(segments);
if (debug>1) System.out.println(tree);
IntervalData<String> query = tree.query(2);
if (debug>1) System.out.println("2: "+query);
query = tree.query(4); //Stabbing query
if (debug>1) System.out.println("4: "+query);
query = tree.query(9); //Stabbing query
if (debug>1) System.out.println("9: "+query);
query = tree.query(1, 16); //Range query
if (debug>1) System.out.println("1->16: "+query);
query = tree.query(7, 14); //Range query
if (debug>1) System.out.println("7->14: "+query);
if (debug>1) System.out.println();
}
{
//Lifespan Interval Segment tree
if (debug>1) System.out.println("Lifespan Interval Segment Tree.");
java.util.List<IntervalData<String>> segments = new ArrayList<IntervalData<String>>();
segments.add((new IntervalData<String>(1888, 1971, "Stravinsky")));
segments.add((new IntervalData<String>(1874, 1951, "Schoenberg")));
segments.add((new IntervalData<String>(1843, 1907, "Grieg")));
segments.add((new IntervalData<String>(1779, 1828, "Schubert")));
segments.add((new IntervalData<String>(1756, 1791, "Mozart")));
segments.add((new IntervalData<String>(1585, 1672, "Schuetz")));
DynamicSegmentTree<IntervalData<String>> tree = new DynamicSegmentTree<IntervalData<String>>(segments,25);
if (debug>1) System.out.println(tree);
IntervalData<String> query = tree.query(1890);
if (debug>1) System.out.println("1890: "+query);
query = tree.query(1909); //Stabbing query
if (debug>1) System.out.println("1909: "+query);
query = tree.query(1792, 1903); //Range query
if (debug>1) System.out.println("1792->1903: "+query);
query = tree.query(1776, 1799); //Range query
if (debug>1) System.out.println("1776->1799: "+query);
if (debug>1) System.out.println();
}
return true;
}
private static boolean testSkipList() {
{
long count = 0;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
// SkipList only works with sorted items
if (debug>1) System.out.println("Skip List.");
testNames[test] = "Skip List";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
SkipList<Integer> list = new SkipList<Integer>();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
list.add(item);
if (validateStructure && !(list.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Skip List add time = "+(addSortedTime/count)+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Skip List memory use = "+(memory/count)+" bytes");
}
boolean contains = list.contains(INVALID);
boolean removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Skip List invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Skip List invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Skip List lookup time = "+(lookupTime/count)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
list.remove(item);
if (validateStructure && !(list.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Skip List remove time = "+(removeSortedTime/count)+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Skip List invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Skip List invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
list.add(item);
if (validateStructure && !(list.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && !list.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Skip List add time = "+(addSortedTime/count)+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Skip List memory use = "+(memory/count)+" bytes");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Skip List invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Skip List invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(list.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
list.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Skip List lookup time = "+(lookupTime/count)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
list.remove(item);
if (validateStructure && !(list.size()==(sorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(list);
return false;
}
if (validateContents && list.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(list);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Skip List remove time = "+removeSortedTime/count+" ms");
}
contains = list.contains(INVALID);
removed = list.remove(INVALID);
if (contains || removed) {
System.err.println("Skip List invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Skip List invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{0,0,addSortedTime/count,removeSortedTime/count,lookupTime/count,memory/count};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testSplayTree() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Splay Tree
if (debug>1) System.out.println("Splay Tree.");
testNames[test] = "Splay Tree";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
SplayTree<Integer> splay = new SplayTree<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
splay.add(item);
if (validateStructure && !(splay.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && !splay.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Splay Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Splay Tree memory use = "+(memory/count)+" bytes");
}
boolean contains = splay.contains(INVALID);
boolean removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(splay.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
splay.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Splay Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
splay.remove(item);
if (validateStructure && !(splay.size()==((unsorted.length-1)-i))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && splay.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Splay Tree remove time = "+removeTime/count+" ms");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
splay.add(item);
if (validateStructure && !(splay.size()==(unsorted.length-i))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && !splay.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Splay Tree add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Splay Tree memory use = "+(memory/count)+" bytes");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(splay.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
splay.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Splay Tree lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
splay.remove(item);
if (validateStructure && !(splay.size()==((unsorted.length-1)-i))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && splay.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Splay Tree remove time = "+removeTime/count+" ms");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
splay.add(item);
if (validateStructure && !(splay.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && !splay.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Splay Tree add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Splay Tree memory use = "+(memory/(count+1))+" bytes");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(splay.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
splay.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Splay Tree lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
splay.remove(item);
if (validateStructure && !(splay.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(splay);
return false;
}
if (validateContents && splay.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(splay);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Splay Tree remove time = "+removeSortedTime+" ms");
}
contains = splay.contains(INVALID);
removed = splay.remove(INVALID);
if (contains || removed) {
System.err.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Splay Tree invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testStack() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Stack [array]
if (debug>1) System.out.println("Stack [array].");
testNames[test] = "Stack [array]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
Stack<Integer> stack = new Stack.ArrayStack<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Stack [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Stack [array] memory use = "+(memory/count)+" bytes");
}
boolean contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Stack [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
int size = stack.size();
for (int i=0; i<size; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Stack [array] remove time = "+removeTime/count+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [array] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Stack [array] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Stack [array] memory use = "+(memory/count)+" bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Stack [array] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Stack [array] remove time = "+removeTime/count+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [array] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Stack [array] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Stack [array] memory use = "+(memory/(count+1))+" bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [array] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Stack [array] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = stack.pop();
if (validateStructure && !(stack.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Stack [array] remove time = "+removeSortedTime+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [array] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [array] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
// Stack [linked]
if (debug>1) System.out.println("Stack [linked].");
testNames[test] = "Stack [linked]";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
Stack<Integer> stack = new Stack.LinkedStack<Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Stack [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Stack [linked] memory use = "+(memory/count)+" bytes");
}
boolean contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Stack [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
int size = stack.size();
for (int i=0; i<size; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Stack [linked] remove time = "+removeTime/count+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [linked] invalidity check. contains="+contains);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Stack [linked] add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Stack [linked] memory use = "+(memory/count)+" bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Stack [linked] lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = stack.pop();
if (validateStructure && !(stack.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Stack [linked] remove time = "+removeTime/count+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [linked] invalidity check. contains="+contains);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
stack.push(item);
if (validateStructure && !(stack.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && !stack.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Stack [linked] add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Stack [linked] memory use = "+(memory/(count+1))+" bytes");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [linked] invalidity check. contains="+contains);
if (debug>1) System.out.println(stack.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
stack.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Stack [linked] lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = stack.pop();
if (validateStructure && !(stack.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(stack);
return false;
}
if (validateContents && stack.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(stack);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Stack [linked] remove time = "+removeSortedTime+" ms");
}
contains = stack.contains(INVALID);
if (contains) {
System.err.println("Stack [linked] invalidity check. contains="+contains);
return false;
} else System.out.println("Stack [linked] invalidity check. contains="+contains);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testSuffixTree() {
{
//Suffix Tree
if (debug>1) System.out.println("Suffix Tree.");
String bookkeeper = "bookkeeper";
SuffixTree<String> tree = new SuffixTree<String>(bookkeeper);
if (debug>1) System.out.println(tree.toString());
if (debug>1) System.out.println(tree.getSuffixes());
boolean exists = tree.doesSubStringExist(bookkeeper);
if (!exists) {
System.err.println("YIKES!! "+bookkeeper+" doesn't exists.");
handleError(tree);
return false;
}
String failed = "booker";
exists = tree.doesSubStringExist(failed);
if (exists) {
System.err.println("YIKES!! "+failed+" exists.");
handleError(tree);
return false;
}
String pass = "kkee";
exists = tree.doesSubStringExist(pass);
if (!exists) {
System.err.println("YIKES!! "+pass+" doesn't exists.");
handleError(tree);
return false;
}
if (debug>1) System.out.println();
}
return true;
}
private static boolean testSuffixTrie() {
{
//Suffix Trie
if (debug>1) System.out.println("Suffix Trie.");
String bookkeeper = "bookkeeper";
SuffixTrie<String> trie = new SuffixTrie<String>(bookkeeper);
if (debug>1) System.out.println(trie.toString());
if (debug>1) System.out.println(trie.getSuffixes());
boolean exists = trie.doesSubStringExist(bookkeeper);
if (!exists) {
System.err.println("YIKES!! "+bookkeeper+" doesn't exists.");
handleError(trie);
return false;
}
String failed = "booker";
exists = trie.doesSubStringExist(failed);
if (exists) {
System.err.println("YIKES!! "+failed+" exists.");
handleError(trie);
return false;
}
String pass = "kkee";
exists = trie.doesSubStringExist(pass);
if (!exists) {
System.err.println("YIKES!! "+pass+" doesn't exists.");
handleError(trie);
return false;
}
if (debug>1) System.out.println();
}
return true;
}
private static boolean testTreap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Treap
if (debug>1) System.out.println("Treap.");
testNames[test] = "Treap";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
Treap<Integer> treap = new Treap<Integer>(unsorted.length*2);
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
treap.add(item);
if (validateStructure && !(treap.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.1");
handleError(treap);
return false;
}
if (validateContents && !treap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Treap add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Treap memory use = "+(memory/count)+" bytes");
}
boolean contains = treap.contains(INVALID);
boolean removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Treap invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(treap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
treap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Treap lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
treap.remove(item);
if (validateStructure && !(treap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.2");
handleError(treap);
return false;
}
if (validateContents && treap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Treap remove time = "+removeTime/count+" ms");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Treap invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
treap.add(item);
if (validateStructure && !(treap.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.3");
handleError(treap);
return false;
}
if (validateContents && !treap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Treap add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Treap memory use = "+(memory/count)+" bytes");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Treap invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(treap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
treap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Treap lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
treap.remove(item);
if (validateStructure && !(treap.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.4");
handleError(treap);
return false;
}
if (validateContents && treap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Treap remove time = "+removeTime/count+" ms");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Treap invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
treap.add(item);
if (validateStructure && !(treap.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(treap);
return false;
}
if (validateContents && !treap.contains(item)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Treap add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Treap memory use = "+(memory/(count+1))+" bytes");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Treap invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(treap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
treap.contains(item);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Treap lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
treap.remove(item);
if (validateStructure && !(treap.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(treap);
return false;
}
if (validateContents && treap.contains(item)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(treap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Treap remove time = "+removeSortedTime+" ms");
}
contains = treap.contains(INVALID);
removed = treap.remove(INVALID);
if (contains || removed) {
System.err.println("Treap invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Treap invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testTrie() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Trie.
if (debug>1) System.out.println("Trie.");
testNames[test] = "Trie";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
Trie<String> trie = new Trie<String>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! "+string+" doesn't exist.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Trie add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Trie memory use = "+(memory/count)+" bytes");
}
String invalid = INVALID.toString();
boolean contains = trie.contains(invalid);
boolean removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trie.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Trie lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! "+string+" still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Trie remove time = "+removeTime/count+" ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size()==unsorted.length-i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! "+string+" doesn't exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Trie add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Trie memory use = "+(memory/count)+" bytes");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trie.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Trie lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size()==unsorted.length-(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! "+string+" still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Trie remove time = "+removeTime/count+" ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
trie.add(string);
if (validateStructure && !(trie.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && !trie.contains(string)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Trie add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Trie memory use = "+(memory/(count+1))+" bytes");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trie.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
trie.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Trie lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
String string = String.valueOf(item);
trie.remove(string);
if (validateStructure && !(trie.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trie);
return false;
}
if (validateContents && trie.contains(string)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(trie);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Trie remove time = "+removeSortedTime+" ms");
}
contains = trie.contains(invalid);
removed = trie.remove(invalid);
if (contains || removed) {
System.err.println("Trie invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static boolean testTrieMap() {
{
long count = 0;
long addTime = 0L;
long removeTime = 0L;
long beforeAddTime = 0L;
long afterAddTime = 0L;
long beforeRemoveTime = 0L;
long afterRemoveTime = 0L;
long memory = 0L;
long beforeMemory = 0L;
long afterMemory = 0L;
//Trie Map
if (debug>1) System.out.println("Trie Map.");
testNames[test] = "Trie Map";
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
TrieMap<String,Integer> trieMap = new TrieMap<String,Integer>();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
if (validateStructure && !(trieMap.size()==i+1)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && !trieMap.contains(string)) {
System.err.println("YIKES!! "+string+" doesn't exist.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Trie Map add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Trie Map memory use = "+(memory/count)+" bytes");
}
String invalid = INVALID.toString();
boolean contains = trieMap.contains(invalid);
boolean removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trieMap.toString());
long lookupTime = 0L;
long beforeLookupTime = 0L;
long afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trieMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Trie Map lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
if (validateStructure && !(trieMap.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && trieMap.contains(string)) {
System.err.println("YIKES!! "+string+" still exists.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Trie Map remove time = "+removeTime/count+" ms");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
count++;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddTime = System.currentTimeMillis();
for (int i=unsorted.length-1; i>=0; i
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.put(string, item);
if (validateStructure && !(trieMap.size()==(unsorted.length-i))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && !trieMap.contains(string)) {
System.err.println("YIKES!! "+string+" doesn't exist.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterAddTime = System.currentTimeMillis();
addTime += afterAddTime-beforeAddTime;
if (debug>0) System.out.println("Trie Map add time = "+addTime/count+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Trie Map memory use = "+(memory/count)+" bytes");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trieMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : unsorted) {
String string = String.valueOf(item);
trieMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Trie Map lookup time = "+lookupTime/count+" ms");
}
if (debugTime) beforeRemoveTime = System.currentTimeMillis();
for (int i=0; i<unsorted.length; i++) {
int item = unsorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
if (validateStructure && !(trieMap.size()==(unsorted.length-(i+1)))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && trieMap.contains(string)) {
System.err.println("YIKES!! "+string+" still exists.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterRemoveTime = System.currentTimeMillis();
removeTime += afterRemoveTime-beforeRemoveTime;
if (debug>0) System.out.println("Trie Map remove time = "+removeTime/count+" ms");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
//sorted
long addSortedTime = 0L;
long removeSortedTime = 0L;
long beforeAddSortedTime = 0L;
long afterAddSortedTime = 0L;
long beforeRemoveSortedTime = 0L;
long afterRemoveSortedTime = 0L;
if (debugMemory) beforeMemory = DataStructures.getMemoryUse();
if (debugTime) beforeAddSortedTime = System.currentTimeMillis();
for (int i=0; i<sorted.length; i++) {
int item = sorted[i];
String string = String.valueOf(item);
trieMap.put(string,item);
if (validateStructure && !(trieMap.size()==(i+1))) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && !trieMap.contains(string)) {
System.err.println("YIKES!! "+item+" doesn't exist.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterAddSortedTime = System.currentTimeMillis();
addSortedTime += afterAddSortedTime-beforeAddSortedTime;
if (debug>0) System.out.println("Trie Map add time = "+addSortedTime+" ms");
}
if (debugMemory) {
afterMemory = DataStructures.getMemoryUse();
memory += afterMemory-beforeMemory;
if (debug>0) System.out.println("Trie Map memory use = "+(memory/(count+1))+" bytes");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
if (debug>1) System.out.println(trieMap.toString());
lookupTime = 0L;
beforeLookupTime = 0L;
afterLookupTime = 0L;
if (debugTime) beforeLookupTime = System.currentTimeMillis();
for (int item : sorted) {
String string = String.valueOf(item);
trieMap.contains(string);
}
if (debugTime) {
afterLookupTime = System.currentTimeMillis();
lookupTime += afterLookupTime-beforeLookupTime;
if (debug>0) System.out.println("Trie Map lookup time = "+lookupTime/(count+1)+" ms");
}
if (debugTime) beforeRemoveSortedTime = System.currentTimeMillis();
for (int i=sorted.length-1; i>=0; i
int item = sorted[i];
String string = String.valueOf(item);
trieMap.remove(string);
if (validateStructure && !(trieMap.size()==i)) {
System.err.println("YIKES!! "+item+" caused a size mismatch.");
handleError(trieMap);
return false;
}
if (validateContents && trieMap.contains(string)) {
System.err.println("YIKES!! "+item+" still exists.");
handleError(trieMap);
return false;
}
}
if (debugTime) {
afterRemoveSortedTime = System.currentTimeMillis();
removeSortedTime += afterRemoveSortedTime-beforeRemoveSortedTime;
if (debug>0) System.out.println("Trie Map remove time = "+removeSortedTime+" ms");
}
contains = trieMap.contains(invalid);
removed = trieMap.remove(invalid);
if (contains || removed) {
System.err.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
return false;
} else System.out.println("Trie Map invalidity check. contains="+contains+" removed="+removed);
testResults[test++] = new long[]{addTime/count,removeTime/count,addSortedTime,removeSortedTime,lookupTime/(count+1),memory/(count+1)};
if (debug>1) System.out.println();
}
return true;
}
private static final String getTestResults(String[] names, long[][] results) {
StringBuilder resultsBuilder = new StringBuilder();
int KB = 1000;
int MB = 1000*KB;
double SECOND = 1000;
double MINUTES = 60*SECOND;
resultsBuilder.append("Data Structure ").append("\t");
resultsBuilder.append("Add time").append("\t").append("Remove time").append("\t");
resultsBuilder.append("Sorted add time").append("\t").append("Sorted Remove time").append("\t");
resultsBuilder.append("Lookup time").append("\t");
resultsBuilder.append("Size");
resultsBuilder.append("\n");
for (int i=0; i<TESTS; i++) {
String name = names[i];
long[] result = results[i];
if (name!=null && result!=null) {
if (name.length()<20) {
StringBuilder nameBuilder = new StringBuilder(name);
for (int j=name.length(); j<20; j++) {
nameBuilder.append(" ");
}
name = nameBuilder.toString();
}
resultsBuilder.append(name).append("\t");
double addTime = result[0];
String addTimeString = null;
if (addTime>MINUTES) {
addTime = addTime/MINUTES;
addTimeString = FORMAT.format(addTime)+" m";
} else if (addTime>SECOND) {
addTime = addTime/SECOND;
addTimeString = FORMAT.format(addTime)+" s";
} else {
addTimeString = FORMAT.format(addTime)+" ms";
}
double removeTime = result[1];
String removeTimeString = null;
if (removeTime>MINUTES) {
removeTime = removeTime/MINUTES;
removeTimeString = FORMAT.format(removeTime)+" m";
} else if (removeTime>SECOND) {
removeTime = removeTime/SECOND;
removeTimeString = FORMAT.format(removeTime)+" s";
} else {
removeTimeString = FORMAT.format(removeTime)+" ms";
}
resultsBuilder.append(addTimeString).append("\t\t");
resultsBuilder.append(removeTimeString).append("\t\t");
//sorted
addTime = result[2];
addTimeString = null;
if (addTime>MINUTES) {
addTime = addTime/MINUTES;
addTimeString = FORMAT.format(addTime)+" m";
} else if (addTime>SECOND) {
addTime = addTime/SECOND;
addTimeString = FORMAT.format(addTime)+" s";
} else {
addTimeString = FORMAT.format(addTime)+" ms";
}
removeTime = result[3];
removeTimeString = null;
if (removeTime>MINUTES) {
removeTime = removeTime/MINUTES;
removeTimeString = FORMAT.format(removeTime)+" m";
} else if (removeTime>SECOND) {
removeTime = removeTime/SECOND;
removeTimeString = FORMAT.format(removeTime)+" s";
} else {
removeTimeString = FORMAT.format(removeTime)+" ms";
}
resultsBuilder.append(addTimeString).append("\t\t");
resultsBuilder.append(removeTimeString).append("\t\t\t");
double lookupTime = result[4];
String lookupTimeString = null;
if (lookupTime>MINUTES) {
lookupTime = lookupTime/MINUTES;
lookupTimeString = FORMAT.format(lookupTime)+" m";
} else if (lookupTime>SECOND) {
lookupTime = lookupTime/SECOND;
lookupTimeString = FORMAT.format(lookupTime)+" s";
} else {
lookupTimeString = FORMAT.format(lookupTime)+" ms";
}
resultsBuilder.append(lookupTimeString).append("\t\t");
long size = result[5];
String sizeString = null;
if (size>MB) {
size = size/MB;
sizeString = size+" MB";
} else if (size>KB) {
size = size/KB;
sizeString = size+" KB";
} else {
sizeString = size+" Bytes";
}
resultsBuilder.append(sizeString);
resultsBuilder.append("\n");
}
}
return resultsBuilder.toString();
}
private static final String getPathMapString(Graph.Vertex<Integer> start, Map<Graph.Vertex<Integer>, Graph.CostPathPair<Integer>> map) {
StringBuilder builder = new StringBuilder();
for (Graph.Vertex<Integer> v : map.keySet()) {
Graph.CostPathPair<Integer> pair = map.get(v);
builder.append("From ").append(start.getValue()).append(" to vertex=").append(v.getValue()).append("\n");
if (pair!=null) builder.append(pair.toString()).append("\n");
}
return builder.toString();
}
private static final String getPathMapString(Map<Vertex<Integer>, Map<Vertex<Integer>, Set<Edge<Integer>>>> paths) {
StringBuilder builder = new StringBuilder();
for (Graph.Vertex<Integer> v : paths.keySet()) {
Map<Vertex<Integer>, Set<Edge<Integer>>> map = paths.get(v);
for (Graph.Vertex<Integer> v2 : map.keySet()) {
builder.append("From=").append(v.getValue()).append(" to=").append(v2.getValue()).append("\n");
Set<Graph.Edge<Integer>> path = map.get(v2);
builder.append(path).append("\n");
}
}
return builder.toString();
}
private static final String getWeightMapString(Map<Vertex<Integer>, Map<Vertex<Integer>, Integer>> paths) {
StringBuilder builder = new StringBuilder();
for (Graph.Vertex<Integer> v : paths.keySet()) {
Map<Vertex<Integer>, Integer> map = paths.get(v);
for (Graph.Vertex<Integer> v2 : map.keySet()) {
builder.append("From=").append(v.getValue()).append(" to=").append(v2.getValue()).append("\n");
Integer weight = map.get(v2);
builder.append(weight).append("\n");
}
}
return builder.toString();
}
private static final long getMemoryUse() {
putOutTheGarbage();
long totalMemory = Runtime.getRuntime().totalMemory();
putOutTheGarbage();
long freeMemory = Runtime.getRuntime().freeMemory();
return (totalMemory - freeMemory);
}
private static final void putOutTheGarbage() {
collectGarbage();
collectGarbage();
}
private static final long fSLEEP_INTERVAL = 75;
private static final void collectGarbage() {
try {
System.gc();
Thread.sleep(fSLEEP_INTERVAL);
System.runFinalization();
Thread.sleep(fSLEEP_INTERVAL);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
} |
package javax.enterprise.inject; |
package com.kapouta.katools;
import java.util.Vector;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView.Renderer;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public abstract class KTouchQueuedRenderer implements Renderer, OnTouchListener {
Vector<MotionEventData> events = null;
private boolean two_pointers_down;
public KTouchQueuedRenderer() {
events = new Vector<MotionEventData>();
this.two_pointers_down = false;
}
@Override
public synchronized void onDrawFrame(GL10 gl) {
if (events.size() > 0) {
MotionEventData curr_event = events.remove(0);
switch (curr_event.action) {
case MotionEvent.ACTION_DOWN:
this.onTouchDown(curr_event.x1, curr_event.y1);
break;
case MotionEvent.ACTION_MOVE:
this.onTouchMove(curr_event.x1, curr_event.y1);
break;
case MotionEvent.ACTION_UP:
this.onTouchUp(curr_event.x1, curr_event.y1);
break;
case MotionEvent.ACTION_POINTER_2_DOWN: {
this.two_pointers_down = true;
this.onTouchUp(curr_event.x1, curr_event.y1);
this.onDualTouchDown(curr_event.x1, curr_event.y1, curr_event.x2, curr_event.y2);
break;
}
case MotionEvent.ACTION_POINTER_1_UP:
case MotionEvent.ACTION_POINTER_2_UP: {
this.two_pointers_down = false;
this.onDualTouchUp(curr_event.x1, curr_event.y1, curr_event.x2, curr_event.y2);
break;
}
default:
System.out.println("Unknown: " + curr_event);
}
}
}
@Override
public void onSurfaceChanged(GL10 arg0, int arg1, int arg2) {
}
@Override
public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
}
public void onTouchDown(float x, float y) {
System.out.println("One DOWN ( " + x + " , " + y + " )");
}
public void onTouchMove(float x, float y) {
System.out.println("One MOVE ( " + x + " , " + y + " )");
}
public void onTouchUp(float x, float y) {
System.out.println("One UP ( " + x + " , " + y + " )");
}
public void onDualTouchDown(float x1, float y1, float x2, float y2) {
System.out.println("Two DOWN ( " + x1 + " , " + y1 + " ; " + x2 + " , " + y2 + " ) ");
}
public void onDualTouchMove(float x1, float y1, float x2, float y2) {
System.out.println("Two MOVE ( " + x1 + " , " + y1 + " ; " + x2 + " , " + y2 + " ) ");
}
public void onDualTouchUp(float x1, float y1, float x2, float y2) {
System.out.println("Two UP ( " + x1 + " , " + y1 + " ; " + x2 + " , " + y2 + " ) ");
}
@Override
public boolean onTouch(View view, MotionEvent event) {
if (MotionEvent.ACTION_MOVE != event.getAction() || events.size() == 0)
events.add(new MotionEventData(event));
System.out.println(":: " + event);
return true;
}
protected class MotionEventData {
float x1, y1, x2, y2;
int action;
public MotionEventData(MotionEvent event) {
int pid0 = event.getPointerId(0);
int pid1 = event.getPointerId(1);
x1 = event.getX(pid0);
y1 = event.getY(pid0);
x2 = event.getX(pid1);
y2 = event.getY(pid1);
action = event.getAction();
}
public String toString() {
return "A[" + action + "] P1( " + x1 + " , " + y1 + " ) P2 " + x2 + " , " + y2 + " )";
}
}
} |
package ru.job4j.convert;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Converts two-dimension array to list and back side.
*
* @author abondarev.
* @since 19.08.2017
*/
public class ConvertList {
/**
* Converts array specified as parameter into list.
*
* @param array of integers
* @return List<Integer>
*/
public List<Integer> toList(int[][] array) {
List<Integer> result = new ArrayList<>();
for (int[] part : array) {
for (int item : part) {
result.add(item);
}
}
return result;
}
/**
* Converts list into a two-dimension array.
*
* @param list for conversion.
* @return array.
*/
public int[][] toArray(List<Integer> list) {
int sideLen = (int) (Math.sqrt(list.size()) + 1);
int[][] result = new int[sideLen][sideLen];
int row = 0;
int col = 0;
for (Integer item : list) {
if (item != null) {
result[row][col++] = item;
if (col >= sideLen) {
col = 0;
row++;
}
}
}
if (result[sideLen - 1][0] == 0) {
result = Arrays.copyOf(result, sideLen - 1);
}
return result;
}
/**
* Convert list of array of integer into list of integer.
*
* @param list for converting.
* @return converted list.
*/
public List<Integer> convert(List<int[]> list) {
List<Integer> result = new ArrayList<>();
for (int[] part : list) {
if (part != null) {
for (int item : part) {
result.add(item);
}
}
}
return result;
}
} |
package com.lysdev.transperthcached;
// Standard library
import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;
// android sdk
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
// Joda
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.LocalTime;
// Project specific
import com.lysdev.transperthcached.timetable.StopTimetable;
import com.lysdev.transperthcached.timetable.Timetable;
import com.lysdev.transperthcached.timetable.Visit;
import com.lysdev.transperthcached.timetable.VisitComparator;
import com.lysdev.transperthcached.ui.DatePickerFragment;
import com.lysdev.transperthcached.ui.OkDialog;
import com.lysdev.transperthcached.ui.TimePickerFragment;
public class MainActivity extends FragmentActivity {
private Timetable timetable;
ListView stop_display;
EditText stop_num_widget;
ArrayAdapter<String> stop_display_source;
public DateTime show_for_date; // public so the ui fragment can pass back data
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.timetable = new Timetable();
Log.d("TransperthCached", "initializing");
try {
this.timetable.initialize(getApplicationContext());
} catch (java.lang.Error e) {
ok_dialog("Could not initialize database", null);
throw new java.lang.Error(e.toString());
} catch (java.io.IOException e) {
ok_dialog("Could not initialize database", null);
throw new java.lang.Error(e.toString());
}
Log.d("TransperthCached", "initialized");
loadSaveInstanceState(savedInstanceState);
setupUI();
if (savedInstanceState != null) {
// cannot set this till the ui is setup
stop_num_widget.setText(
savedInstanceState.getString("stop_number")
);
}
}
protected void setupUI() {
stop_display = (ListView) findViewById(R.id.visits);
stop_num_widget = (EditText) findViewById(R.id.stop_number);
ArrayList<String> visits = new ArrayList<String>();
stop_display_source = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
visits
);
stop_display.setAdapter(stop_display_source);
show_for_date = new DateTime();
updateTimeButtonText();
updateDateButtonText();
}
protected void loadSaveInstanceState(Bundle inState) {
if (inState == null) {
show_for_date = new DateTime();
} else {
show_for_date = DateTime.parse(
inState.getString("show_for_date")
);
}
}
protected void onSaveInstanceState(Bundle outState) {
outState.putString("show_for_date", show_for_date.toString());
outState.putString("stop_number", stop_num_widget.getText().toString());
}
protected void onDestroy() {
super.onDestroy();
this.timetable.onDestroy();
}
private void ok_dialog(String title, String message) {
OkDialog dialog = new OkDialog();
Bundle args = new Bundle();
args.putString("title", title);
args.putString("message", message);
dialog.setArguments(args);
// dialog.setTargetFragment(this, 0);
dialog.show(getSupportFragmentManager(), "TransperthCached");
}
public void showForStop(View view) {
hideSoftKeyboard();
String stop_num = stop_num_widget.getText().toString();
if (stop_num == null) return;
if (stop_num.length() != 5) {
ok_dialog("Bad stop", "Please provide a 5 digit stop number");
stop_display_source.clear();
return;
}
StopTimetable stop_timetable = this.timetable.getVisitsForStop(stop_num);
if (stop_timetable == null) {
String error = String.format("No such stop as %s", stop_num);
Log.d("TransperthCached", error);
stop_display_source.clear();
ok_dialog("Bad stop", error);
return;
}
Vector<Visit> forDayType = stop_timetable.getForWeekdayNumber(
show_for_date.getDayOfWeek()
);
if (forDayType == null || forDayType.isEmpty()) {
String error = String.format(
"No stops on (%s) for %s",
DateTimeFormat.forPattern("hh:mmaa, EEE, MMMM dd, yyyy").print(
show_for_date
), stop_num
);
Log.d("TransperthCached", error);
stop_display_source.clear();
ok_dialog("No stops", error);
return;
}
LocalTime forTime = this.show_for_date.toLocalTime();
Vector<Visit> valid = new Vector<Visit>();
for (Visit visit : forDayType) {
if (visit.time.isAfter(forTime)) {
valid.add(visit);
}
}
Collections.sort(valid, new VisitComparator());
if (valid.isEmpty()) {
String error = "No more stops today";
Log.d("TransperthCached", error);
stop_display_source.clear();
ok_dialog("No stops", error);
return;
}
displayVisits(valid);
}
public void hideSoftKeyboard() {
InputMethodManager inputMethodManager;
inputMethodManager = (InputMethodManager) getSystemService(
Activity.INPUT_METHOD_SERVICE
);
inputMethodManager.hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(),
0
);
}
public void timeSelectButtonClicked(View v) {
hideSoftKeyboard();
DialogFragment newFragment = new TimePickerFragment(
this, this.show_for_date.toLocalTime()
);
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void updateTimeButtonText() {
Button button = (Button) findViewById(R.id.time_select_button);
button.setText(
DateTimeFormat.forPattern("hh:mmaa").print(
show_for_date.toLocalTime()
)
);
}
public void dateSelectButtonClicked(View v) {
hideSoftKeyboard();
DialogFragment newFragment = new DatePickerFragment(
this, this.show_for_date
);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void updateDateButtonText() {
Button button = (Button) findViewById(R.id.date_select_button);
button.setText(
DateTimeFormat.forPattern("EEE, MMMM dd, yyyy").print(
show_for_date
)
);
}
private void displayVisits(Vector<Visit> visits) {
// clear so we can display the new data
Log.d("TransperthCached", "Clearing display");
stop_display_source.clear();
Log.d("TransperthCached", "Displaying");
for (Visit visit : visits) {
Log.d("TransperthCached", "Displaying: " + visit.toString());
stop_display_source.add(
String.format(
"%s : %s",
visit.route_number,
visit.formatTime()
// visit.time.toString()
)
);
}
}
} |
package cn.jingzhuan.lib.chart2.base;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Build;
import androidx.annotation.FloatRange;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.view.ScaleGestureDetectorCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.EdgeEffect;
import android.widget.OverScroller;
import cn.jingzhuan.lib.chart.R;
import cn.jingzhuan.lib.chart.Zoomer;
import cn.jingzhuan.lib.chart.event.OnLoadMoreKlineListener;
import cn.jingzhuan.lib.chart.utils.ForceAlign.XForce;
import cn.jingzhuan.lib.chart.Viewport;;
import cn.jingzhuan.lib.chart.component.Axis;
import cn.jingzhuan.lib.chart.component.AxisX;
import cn.jingzhuan.lib.chart.component.AxisY;
import cn.jingzhuan.lib.chart.component.Highlight;
import cn.jingzhuan.lib.chart.event.OnViewportChangeListener;
import cn.jingzhuan.lib.chart.utils.ForceAlign;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class Chart extends BitmapCachedChart {
protected AxisY mAxisLeft = new AxisY(AxisY.LEFT_INSIDE);
protected AxisY mAxisRight = new AxisY(AxisY.RIGHT_INSIDE);
protected AxisX mAxisTop = new AxisX(AxisX.TOP);
protected AxisX mAxisBottom = new AxisX(AxisX.BOTTOM);
// State objects and values related to gesture tracking.
private ScaleGestureDetector mScaleGestureDetector;
private GestureDetector mGestureDetector;
private OverScroller mScroller;
private Zoomer mZoomer;
private PointF mZoomFocalPoint = new PointF();
private RectF mScrollerStartViewport = new RectF(); // Used only for zooms and flings.
private boolean mScaleXEnable = true;
private boolean mDraggingToMoveEnable = true;
private boolean mDoubleTapToZoom = false;
private boolean mScaleGestureEnable = true;
private boolean mHighlightDisable = false;
protected List<OnTouchPointChangeListener> mTouchPointChangeListeners;
private List<OnViewportChangeListener> mOnViewportChangeListeners;
protected OnViewportChangeListener mInternalViewportChangeListener;
protected OnLoadMoreKlineListener mOnLoadMoreKlineListener;
/**
* The scaling factor for a single zoom 'step'.
*
* @see #zoomIn()
* @see #zoomOut()
*/
private static final float ZOOM_AMOUNT = 0.2f;
private final Point mSurfaceSizeBuffer = new Point();
// Edge effect / overscroll tracking objects.
private EdgeEffect mEdgeEffectLeft;
private EdgeEffect mEdgeEffectRight;
private boolean mEdgeEffectLeftActive;
private boolean mEdgeEffectRightActive;
private boolean isTouching = false;
private boolean isShowRange = false;
protected Highlight[] mHighlights;
protected boolean canLoadMore = true;
private float scaleSensitivity = 1f;
private boolean canZoomIn = true;
private boolean canZoomOut = true;
public Chart(Context context) {
this(context, null, 0);
}
public Chart(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public Chart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public Chart(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs, R.styleable.Chart, defStyleAttr, defStyleAttr);
mTouchPointChangeListeners = Collections.synchronizedList(new ArrayList<OnTouchPointChangeListener>());
mOnViewportChangeListeners = Collections.synchronizedList(new ArrayList<OnViewportChangeListener>());
mAxisTop.setGridLineEnable(false);
mAxisTop.setLabelEnable(false);
try {
List<Axis> axisList = new ArrayList<>(4);
axisList.add(mAxisLeft);
axisList.add(mAxisRight);
axisList.add(mAxisTop);
axisList.add(mAxisBottom);
float labelTextSize = a.getDimension(R.styleable.Chart_labelTextSize, 28);
float labelSeparation = a.getDimensionPixelSize(R.styleable.Chart_labelSeparation, 10);
float gridThickness = a.getDimension(R.styleable.Chart_gridThickness, 2);
float axisThickness = a.getDimension(R.styleable.Chart_axisThickness, 2);
int gridColor = a.getColor(R.styleable.Chart_gridColor, Color.GRAY);
int axisColor = a.getColor(R.styleable.Chart_axisColor, Color.GRAY);
int labelTextColor = a.getColor(R.styleable.Chart_labelTextColor, Color.GRAY);
for (Axis axis : axisList) {
axis.setLabelTextSize(labelTextSize);
axis.setLabelTextColor(labelTextColor);
axis.setLabelSeparation(labelSeparation);
axis.setGridColor(gridColor);
axis.setGridThickness(gridThickness);
axis.setAxisColor(axisColor);
axis.setAxisThickness(axisThickness);
}
} finally {
a.recycle();
}
initChart();
setupInteractions(context);
setupEdgeEffect(context);
}
public abstract void initChart();
public abstract void highlightValue(Highlight highlight);
public abstract void cleanHighlight();
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
getContentRect().set(
getPaddingLeft() + (mAxisLeft.isInside() ? 0 : mAxisLeft.getLabelWidth()),
getPaddingTop(),
getWidth() - getPaddingRight() - (mAxisRight.isInside() ? 0 : mAxisRight.getLabelWidth()),
getHeight() - getPaddingBottom() - mAxisBottom.getLabelHeight()
);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int minChartSize = getResources().getDimensionPixelSize(R.dimen.jz_chart_min_size);
setMeasuredDimension(
Math.max(getSuggestedMinimumWidth(),
resolveSize(minChartSize + getPaddingLeft()
+ (mAxisLeft.isInside() ? 0 : mAxisLeft.getLabelWidth())
+ getPaddingRight(),
widthMeasureSpec)),
Math.max(getSuggestedMinimumHeight(),
resolveSize(minChartSize + getPaddingTop()
+ (mAxisBottom.isInside() ? 0 : mAxisBottom.getLabelHeight())
+ getPaddingBottom(),
heightMeasureSpec)));
}
protected abstract int getEntryIndexByCoordinate(float x, float y);
private void setupInteractions(Context context) {
mScaleGestureDetector = new ScaleGestureDetector(context, mScaleGestureListener);
mGestureDetector = new GestureDetector(context, mGestureListener);
mGestureDetector.setIsLongpressEnabled(true);
mScroller = new OverScroller(context);
mZoomer = new Zoomer(context);
}
/**
* Finds the lib point (i.e. within the lib's domain and range) represented by the
* given pixel coordinates, if that pixel is within the lib region described by
* {@link #mContentRect}. If the point is found, the "dest" argument is set to the point and
* this function returns true. Otherwise, this function returns false and "dest" is unchanged.
*/
private boolean hitTest(float x, float y, PointF dest) {
if (!mContentRect.contains((int) x, (int) y)) {
return false;
}
dest.set(mCurrentViewport.left
+ mCurrentViewport.width()
* (x - mContentRect.left) / mContentRect.width(),
mCurrentViewport.top
+ mCurrentViewport.height()
* (y - mContentRect.bottom) / -mContentRect.height());
return true;
}
/**
* The scale listener, used for handling multi-finger scale gestures.
*/
private final ScaleGestureDetector.OnScaleGestureListener mScaleGestureListener
= new ScaleGestureDetector.SimpleOnScaleGestureListener() {
/**
* This is the active focal point in terms of the viewport. Could be a local
* variable but kept here to minimize per-frame allocations.
*/
private PointF viewportFocus = new PointF();
private float lastSpanX;
@Override
public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
if (!isScaleGestureEnable()) return super.onScaleBegin(scaleGestureDetector);
lastSpanX = scaleGestureDetector.getCurrentSpanX();
return true;
}
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
if (!isScaleXEnable()) return false;
if (!isScaleGestureEnable()) return super.onScale(scaleGestureDetector);
float spanX = scaleGestureDetector.getCurrentSpanX();
boolean zoomIn = lastSpanX > spanX;
boolean zoomOut = spanX > lastSpanX;
boolean canZoom = Math.abs(Math.abs(lastSpanX) - Math.abs(spanX)) >= 5f;
if (zoomIn) {
setCanZoomOut(true);
if (!isCanZoomIn())
return false;
}
if (zoomOut) {
setCanZoomIn(true);
if (!isCanZoomOut())
return false;
}
float scaleSpanX = lastSpanX;
if (canZoom) {
if (zoomIn)
lastSpanX = lastSpanX * scaleSensitivity;
else if (zoomOut)
scaleSpanX = spanX * scaleSensitivity;
}
float newWidth;
if (canZoom) {
if (zoomOut)
newWidth = lastSpanX / scaleSpanX * mCurrentViewport.width();
else
newWidth = lastSpanX / spanX * mCurrentViewport.width();
} else
newWidth = lastSpanX / spanX * mCurrentViewport.width();
if (newWidth < mCurrentViewport.width() && mCurrentViewport.width() < 0.001) {
return true;
}
float focusX = scaleGestureDetector.getFocusX();
float focusY = scaleGestureDetector.getFocusY();
if (canZoom) {
if (zoomIn)
focusX *= scaleSensitivity;
else if (zoomOut)
focusX /= scaleSensitivity;
}
hitTest(focusX, focusY, viewportFocus);
mCurrentViewport.left = viewportFocus.x
- newWidth * (focusX - mContentRect.left)
/ mContentRect.width();
mCurrentViewport.right = mCurrentViewport.left + newWidth;
mCurrentViewport.constrainViewport();
triggerViewportChange();
lastSpanX = spanX;
return true;
}
};
protected abstract void onTouchPoint(MotionEvent e);
/**
* The gesture listener, used for handling simple gestures such as double touches, scrolls,
* and flings.
*/
private final GestureDetector.SimpleOnGestureListener mGestureListener
= new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
releaseEdgeEffects();
mScrollerStartViewport.set(mCurrentViewport);
mScroller.forceFinished(true);
postInvalidateOnAnimation();
return true;
}
@Override
public void onLongPress(MotionEvent e) {
onTouchPoint(e);
e.setAction(MotionEvent.ACTION_UP);
mGestureDetector.onTouchEvent(e);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (isClickable() && hasOnClickListeners()) {
cleanHighlight();
performClick();
} else {
int index = getEntryIndexByCoordinate(e.getX(), e.getY());
if (index >= 0) {
if (mHighlights != null || mHighlightDisable) {
cleanHighlight();
} else {
onTouchPoint(e);
}
} else {
cleanHighlight();
if (isClickable() && hasOnClickListeners()) {
performClick();
}
}
}
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
if (mDoubleTapToZoom) {
mZoomer.forceFinished(true);
if (hitTest(e.getX(), e.getY(), mZoomFocalPoint)) {
mZoomer.startZoom(ZOOM_AMOUNT);
}
postInvalidateOnAnimation();
}
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (!isDraggingToMoveEnable()) {
onTouchPoint(e2);
return super.onScroll(e1, e2, distanceX, distanceY);
}
// Scrolling uses math based on the viewport (as opposed to math using pixels).
/**
* Pixel offset is the offset in screen pixels, while viewport offset is the
* offset within the current viewport. For additional information on surface sizes
* and pixel offsets, see the docs for {@link computeScrollSurfaceSize()}. For
* additional information about the viewport, see the comments for
* {@link mCurrentViewport}.
*/
float viewportOffsetX = distanceX * mCurrentViewport.width() / mContentRect.width();
// float viewportOffsetY = -distanceY * mCurrentViewport.height() / mContentRect.height();
computeScrollSurfaceSize(mSurfaceSizeBuffer);
int scrolledX = (int) (mSurfaceSizeBuffer.x
* (mCurrentViewport.left + viewportOffsetX - Viewport.AXIS_X_MIN)
/ (Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN));
boolean canScrollX = mCurrentViewport.left > Viewport.AXIS_X_MIN
|| mCurrentViewport.right < Viewport.AXIS_X_MAX;
setViewportBottomLeft(
mCurrentViewport.left + viewportOffsetX
);
if (canScrollX && scrolledX < 0) {
mEdgeEffectLeft.onPull(scrolledX / (float) mContentRect.width());
mEdgeEffectLeftActive = true;
if (canLoadMore && mOnLoadMoreKlineListener != null) {
mOnLoadMoreKlineListener.onLoadMoreKline(scrolledX);
}
canLoadMore = false;
} else {
canLoadMore = true;
}
if (canScrollX && scrolledX > mSurfaceSizeBuffer.x - mContentRect.width()) {
mEdgeEffectRight.onPull((scrolledX - mSurfaceSizeBuffer.x + mContentRect.width())
/ (float) mContentRect.width());
mEdgeEffectRightActive = true;
}
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (!isDraggingToMoveEnable()) return super.onFling(e1, e2, velocityX, velocityY);
fling((int) -velocityX);
if (!isDraggingToMoveEnable()) {
onTouchPoint(e2);
}
return true;
}
};
protected void triggerViewportChange() {
postInvalidateOnAnimation();
if (mInternalViewportChangeListener != null) {
mInternalViewportChangeListener.onViewportChange(mCurrentViewport);
}
if (mOnViewportChangeListeners != null && !mOnViewportChangeListeners.isEmpty()) {
synchronized (this) {
for (OnViewportChangeListener mOnViewportChangeListener : mOnViewportChangeListeners) {
try {
mOnViewportChangeListener.onViewportChange(mCurrentViewport);
} catch (Exception e) {
Log.e("Chart", "onViewportChange", e);
}
}
}
}
}
private void fling(int velocityX) {
if (!canLoadMore) return;
releaseEdgeEffects();
// Flings use math in pixels (as opposed to math based on the viewport).
computeScrollSurfaceSize(mSurfaceSizeBuffer);
mScrollerStartViewport.set(mCurrentViewport);
int startX = (int) (mSurfaceSizeBuffer.x * (mScrollerStartViewport.left - Viewport.AXIS_X_MIN) / (
Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN));
mScroller.forceFinished(true);
mScroller.fling(
startX,
0,
velocityX,
0,
0, mSurfaceSizeBuffer.x - mContentRect.width(),
0, mSurfaceSizeBuffer.y - mContentRect.height(),
mContentRect.width() / 2,
0);
postInvalidateOnAnimation();
}
/**
* Computes the current scrollable surface size, in pixels. For example, if the entire lib
* area is visible, this is simply the current size of {@link #mContentRect}. If the lib
* is zoomed in 200% in both directions, the returned size will be twice as large horizontally
* and vertically.
*/
private void computeScrollSurfaceSize(Point out) {
out.set((int) (mContentRect.width() * (Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN)
/ mCurrentViewport.width()),
(int) (mContentRect.height() * (Viewport.AXIS_Y_MAX - Viewport.AXIS_Y_MIN)
/ mCurrentViewport.height()));
}
/**
* Smoothly zooms the lib in one step.
*/
public void zoomIn() {
zoom(ZOOM_AMOUNT);
}
/**
* Smoothly zooms the lib out one step.
*/
public void zoomOut() {
zoom(-ZOOM_AMOUNT);
}
public void zoom(float scalingFactor) {
mScrollerStartViewport.set(mCurrentViewport);
mZoomer.forceFinished(true);
mZoomer.startZoom(scalingFactor);
mZoomFocalPoint.set(
(mCurrentViewport.right + mCurrentViewport.left) / 2,
(mCurrentViewport.bottom + mCurrentViewport.top) / 2);
triggerViewportChange();
}
public void zoomOut(@XForce int forceAlignX) {
mScrollerStartViewport.set(mCurrentViewport);
mZoomer.forceFinished(true);
mZoomer.startZoom(-ZOOM_AMOUNT);
float forceX;
switch (forceAlignX) {
case ForceAlign.LEFT:
forceX = mCurrentViewport.left;
break;
case ForceAlign.RIGHT:
forceX = mCurrentViewport.right;
break;
case ForceAlign.CENTER:
forceX = (mCurrentViewport.right + mCurrentViewport.left) / 2;
break;
default:
forceX = (mCurrentViewport.right + mCurrentViewport.left) / 2;
break;
}
mZoomFocalPoint.set(forceX,
(mCurrentViewport.bottom + mCurrentViewport.top) / 2);
postInvalidateOnAnimation();
}
/**
* Smoothly zooms the lib in one step.
*/
public void zoomIn(@XForce int forceAlignX) {
mScrollerStartViewport.set(mCurrentViewport);
mZoomer.forceFinished(true);
mZoomer.startZoom(ZOOM_AMOUNT);
float forceX;
switch (forceAlignX) {
case ForceAlign.LEFT:
forceX = mCurrentViewport.left;
break;
case ForceAlign.RIGHT:
forceX = mCurrentViewport.right;
break;
case ForceAlign.CENTER:
forceX = (mCurrentViewport.right + mCurrentViewport.left) / 2;
break;
default:
forceX = (mCurrentViewport.right + mCurrentViewport.left) / 2;
break;
}
mZoomFocalPoint.set(forceX,
(mCurrentViewport.bottom + mCurrentViewport.top) / 2);
triggerViewportChange();
}
@Override
public void computeScroll() {
super.computeScroll();
boolean needsInvalidate = false;
if (mScroller.computeScrollOffset()) {
// The scroller isn't finished, meaning a fling or programmatic pan operation is
// currently active.
computeScrollSurfaceSize(mSurfaceSizeBuffer);
int currX = mScroller.getCurrX();
boolean canScrollX = (mCurrentViewport.left > Viewport.AXIS_X_MIN
|| mCurrentViewport.right < Viewport.AXIS_X_MAX);
if (canScrollX
&& currX < 0
&& mEdgeEffectLeft.isFinished()
&& !mEdgeEffectLeftActive) {
mEdgeEffectLeft.onAbsorb((int) mScroller.getCurrVelocity());
mEdgeEffectLeftActive = true;
needsInvalidate = true;
} else if (canScrollX
&& currX > (mSurfaceSizeBuffer.x - mContentRect.width())
&& mEdgeEffectRight.isFinished()
&& !mEdgeEffectRightActive) {
mEdgeEffectRight.onAbsorb((int) mScroller.getCurrVelocity());
mEdgeEffectRightActive = true;
needsInvalidate = true;
}
float currXRange = Viewport.AXIS_X_MIN + (Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN)
* currX / mSurfaceSizeBuffer.x;
setViewportBottomLeft(currXRange);
}
if (mZoomer.computeZoom()) {
// Performs the zoom since a zoom is in progress (either programmatically or via
// double-touch).
float newWidth = (1f - mZoomer.getCurrZoom()) * mScrollerStartViewport.width();
float newHeight = (1f - mZoomer.getCurrZoom()) * mScrollerStartViewport.height();
float pointWithinViewportX = (mZoomFocalPoint.x - mScrollerStartViewport.left)
/ mScrollerStartViewport.width();
float pointWithinViewportY = (mZoomFocalPoint.y - mScrollerStartViewport.top)
/ mScrollerStartViewport.height();
mCurrentViewport.set(
mZoomFocalPoint.x - newWidth * pointWithinViewportX,
mZoomFocalPoint.y - newHeight * pointWithinViewportY,
mZoomFocalPoint.x + newWidth * (1 - pointWithinViewportX),
mZoomFocalPoint.y + newHeight * (1 - pointWithinViewportY));
mCurrentViewport.constrainViewport();
needsInvalidate = true;
}
if (needsInvalidate) {
triggerViewportChange();
}
}
/**
* Sets the current viewport (defined by {@link #mCurrentViewport}) to the given
* X and Y positions. Note that the Y value represents the topmost pixel position, and thus
* the bottom of the {@link #mCurrentViewport} rectangle. For more details on why top and
* bottom are flipped, see {@link #mCurrentViewport}.
*/
private void setViewportBottomLeft(float x) {
/**
* Constrains within the scroll range. The scroll range is simply the viewport extremes
* (AXIS_X_MAX, etc.) minus the viewport size. For example, if the extrema were 0 and 10,
* and the viewport size was 2, the scroll range would be 0 to 8.
*/
float curWidth = mCurrentViewport.width();
x = Math.max(Viewport.AXIS_X_MIN, Math.min(x, Viewport.AXIS_X_MAX - curWidth));
mCurrentViewport.left = x;
mCurrentViewport.right = x + curWidth;
mCurrentViewport.constrainViewport();
triggerViewportChange();
}
/**
* Sets the lib's current viewport.
*
* @see #getCurrentViewport()
*/
public void setCurrentViewport(RectF viewport) {
mCurrentViewport.set(viewport.left, viewport.top, viewport.right, viewport.bottom);
mCurrentViewport.constrainViewport();
triggerViewportChange();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
isTouching = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
isTouching = false;
}
boolean retVal = event.getPointerCount() > 1 && mScaleGestureDetector.onTouchEvent(event);
retVal = mGestureDetector.onTouchEvent(event) || retVal;
return retVal || super.onTouchEvent(event);
}
protected void setupEdgeEffect(Context context) {
// Sets up edge effects
mEdgeEffectLeft = new EdgeEffect(context);
mEdgeEffectRight = new EdgeEffect(context);
}
/**
* Draws the overscroll "glow" at the four edges of the lib region, if necessary. The edges
* of the lib region are stored in {@link #mContentRect}.
*
* @see EdgeEffect
*/
protected void drawEdgeEffectsUnclipped(Canvas canvas) {
// The methods below rotate and translate the canvas as needed before drawing the glow,
// since EdgeEffectCompat always draws a top-glow at 0,0.
boolean needsInvalidate = false;
if (!mEdgeEffectLeft.isFinished()) {
final int restoreCount = canvas.save();
canvas.translate(mContentRect.left, mContentRect.bottom);
canvas.rotate(-90, 0, 0);
mEdgeEffectLeft.setSize(mContentRect.height(), mContentRect.width());
if (mEdgeEffectLeft.draw(canvas)) {
needsInvalidate = true;
}
canvas.restoreToCount(restoreCount);
}
if (!mEdgeEffectRight.isFinished()) {
final int restoreCount = canvas.save();
canvas.translate(mContentRect.right, mContentRect.top);
canvas.rotate(90, 0, 0);
mEdgeEffectRight.setSize(mContentRect.height(), mContentRect.width());
if (mEdgeEffectRight.draw(canvas)) {
needsInvalidate = true;
}
canvas.restoreToCount(restoreCount);
}
if (needsInvalidate) {
triggerViewportChange();
}
}
private void releaseEdgeEffects() {
mEdgeEffectLeftActive
= mEdgeEffectRightActive
= false;
mEdgeEffectLeft.onRelease();
mEdgeEffectRight.onRelease();
}
public AxisY getAxisLeft() {
return mAxisLeft;
}
public AxisY getAxisRight() {
return mAxisRight;
}
public AxisX getAxisTop() {
return mAxisTop;
}
public AxisX getAxisBottom() {
return mAxisBottom;
}
public void addOnViewportChangeListener(OnViewportChangeListener onViewportChangeListener) {
synchronized (this) {
this.mOnViewportChangeListeners.add(onViewportChangeListener);
}
}
public boolean isScaleXEnable() {
return mScaleXEnable;
}
public void setScaleXEnable(boolean scaleXEnable) {
this.mScaleXEnable = scaleXEnable;
}
public void setDoubleTapToZoom(boolean doubleTapToZoom) {
this.mDoubleTapToZoom = doubleTapToZoom;
}
public float getScaleSensitivity() {
return scaleSensitivity;
}
public void setScaleSensitivity(float scaleSensitivity) {
this.scaleSensitivity = scaleSensitivity;
}
public boolean isCanZoomIn() {
return canZoomIn;
}
public void setCanZoomIn(boolean canZoomIn) {
this.canZoomIn = canZoomIn;
}
public boolean isCanZoomOut() {
return canZoomOut;
}
public void setCanZoomOut(boolean canZoomOut) {
this.canZoomOut = canZoomOut;
}
public interface OnTouchPointChangeListener {
void touch(float x, float y);
}
public void addOnTouchPointChangeListener(OnTouchPointChangeListener touchPointChangeListener) {
synchronized (this) {
this.mTouchPointChangeListeners.add(touchPointChangeListener);
}
}
public void removeOnTouchPointChangeListener(OnTouchPointChangeListener touchPointChangeListener) {
synchronized (this) {
this.mTouchPointChangeListeners.remove(touchPointChangeListener);
}
}
public void setDraggingToMoveEnable(boolean draggingToMoveEnable) {
this.mDraggingToMoveEnable = draggingToMoveEnable;
}
public boolean isDraggingToMoveEnable() {
return mDraggingToMoveEnable;
}
public void moveLeft() {
moveLeft(0.2f);
}
public void moveRight() {
moveRight(0.2f);
}
public void moveLeft(@FloatRange(from = 0f, to = 1.0f) float percent) {
releaseEdgeEffects();
computeScrollSurfaceSize(mSurfaceSizeBuffer);
mScrollerStartViewport.set(mCurrentViewport);
float moveDistance = mContentRect.width() * percent;
int startX = (int) (mSurfaceSizeBuffer.x * (mScrollerStartViewport.left - Viewport.AXIS_X_MIN)
/ (Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN));
if (!mScroller.isFinished()) {
mScroller.forceFinished(true);
}
mScroller.startScroll(startX, 0, (int) -moveDistance, 0, 300);
postInvalidateOnAnimation();
}
public void moveRight(@FloatRange(from = 0f, to = 1.0f) float percent) {
// releaseEdgeEffects();
computeScrollSurfaceSize(mSurfaceSizeBuffer);
mScrollerStartViewport.set(mCurrentViewport);
float moveDistance = mContentRect.width() * percent;
int startX = (int) (mSurfaceSizeBuffer.x * (mScrollerStartViewport.left - Viewport.AXIS_X_MIN)
/ (Viewport.AXIS_X_MAX - Viewport.AXIS_X_MIN));
if (!mScroller.isFinished()) {
mScroller.forceFinished(true);
}
mScroller.startScroll(startX, 0, (int) moveDistance, 0, 300);
postInvalidateOnAnimation();
}
public void setInternalViewportChangeListener(
OnViewportChangeListener mInternalViewportChangeListener) {
this.mInternalViewportChangeListener = mInternalViewportChangeListener;
}
public void setScaleGestureEnable(boolean mScaleGestureEnable) {
this.mScaleGestureEnable = mScaleGestureEnable;
}
public boolean isScaleGestureEnable() {
return mScaleGestureEnable;
}
public boolean isHighlightDisable() {
return mHighlightDisable;
}
public void setHighlightDisable(boolean highlightDisable) {
this.mHighlightDisable = highlightDisable;
}
public Zoomer getZoomer() {
return mZoomer;
}
public boolean isTouching() {
return isTouching;
}
public boolean getRangeEnable() {
return isShowRange;
}
public void setRangeEnable(boolean showRange) {
isShowRange = showRange;
}
public void setOnLoadMoreKlineListener(OnLoadMoreKlineListener onLoadMoreKlineListener) {
this.mOnLoadMoreKlineListener = onLoadMoreKlineListener;
}
} |
package com.nucleus.android;
import java.nio.Buffer;
import java.nio.IntBuffer;
import com.nucleus.opengl.GLES20Wrapper;
public class AndroidGLES20Wrapper extends GLES20Wrapper {
@Override
public void glAttachShader(int program, int shader) {
android.opengl.GLES20.glAttachShader(program, shader);
}
@Override
public void glLinkProgram(int program) {
android.opengl.GLES20.glLinkProgram(program);
}
@Override
public void glShaderSource(int shader, String shaderSource) {
android.opengl.GLES20.glShaderSource(shader, shaderSource);
}
@Override
public void glCompileShader(int shader) {
android.opengl.GLES20.glCompileShader(shader);
}
@Override
public int glCreateShader(int type) {
return android.opengl.GLES20.glCreateShader(type);
}
@Override
public int glCreateProgram() {
return android.opengl.GLES20.glCreateProgram();
}
@Override
public void glGetShaderiv(int shader, int pname, IntBuffer params) {
android.opengl.GLES20.glGetShaderiv(shader, pname, params);
}
@Override
public int glGetError() {
return android.opengl.GLES20.glGetError();
}
@Override
public void glGetProgramiv(int program, int pname, int[] params, int offset) {
android.opengl.GLES20.glGetProgramiv(program, pname, params, offset);
}
@Override
public void glGetActiveAttrib(int program, int index, int bufsize, int[] length, int lengthOffset, int[] size,
int sizeOffset, int[] type, int typeOffset, byte[] name, int nameOffset) {
android.opengl.GLES20.glGetActiveAttrib(program, index, bufsize, length, lengthOffset, size, sizeOffset, type,
typeOffset, name, nameOffset);
}
@Override
public int glGetUniformLocation(int program, String name) {
return android.opengl.GLES20.glGetUniformLocation(program, name);
}
@Override
public int glGetAttribLocation(int program, String name) {
return android.opengl.GLES20.glGetAttribLocation(program, name);
}
@Override
public void glVertexAttribPointer(int index, int size, int type, boolean normalized, int stride, Buffer ptr) {
android.opengl.GLES20.glVertexAttribPointer(index, size, type, normalized, stride, ptr);
}
@Override
public void glEnableVertexAttribArray(int index) {
android.opengl.GLES20.glEnableVertexAttribArray(index);
}
@Override
public void glUniformMatrix4fv(int location, int count, boolean transpose, float[] v, int offset) {
android.opengl.GLES20.glUniformMatrix4fv(location, count, transpose, v, offset);
}
@Override
public void glDrawArrays(int mode, int first, int count) {
android.opengl.GLES20.glDrawArrays(mode, first, count);
}
@Override
public void glBindAttribLocation(int program, int index, String name) {
android.opengl.GLES20.glBindAttribLocation(program, index, name);
}
@Override
public void glGetActiveUniform(int program, int index, int bufsize, int[] length, int lengthOffset, int[] size,
int sizeOffset, int[] type, int typeOffset, byte[] name, int nameOffset) {
android.opengl.GLES20.glGetActiveUniform(program, index, bufsize, length, lengthOffset, size, sizeOffset, type,
typeOffset, name, nameOffset);
}
@Override
public void glUseProgram(int program) {
android.opengl.GLES20.glUseProgram(program);
}
@Override
public void glViewport(int x, int y, int width, int height) {
android.opengl.GLES20.glViewport(x, y, width, height);
}
@Override
public String glGetShaderInfoLog(int shader) {
return android.opengl.GLES20.glGetShaderInfoLog(shader);
}
@Override
public String glGetProgramInfoLog(int program) {
return android.opengl.GLES20.glGetProgramInfoLog(program);
}
@Override
public void glGenTextures(int count, int[] textures, int offset) {
android.opengl.GLES20.glGenTextures(count, textures, offset);
}
@Override
public void glActiveTexture(int texture) {
android.opengl.GLES20.glActiveTexture(texture);
}
@Override
public void glBindTexture(int target, int texture) {
android.opengl.GLES20.glBindTexture(target, texture);
}
@Override
public String glGetString(int name) {
return android.opengl.GLES20.glGetString(name);
}
@Override
public void glUniform4fv(int location, int count, float[] v, int offset) {
android.opengl.GLES20.glUniform4fv(location, count, v, offset);
}
@Override
public void glTexParameterf(int target, int pname, float param) {
android.opengl.GLES20.glTexParameterf(target, pname, param);
}
@Override
public void glTexParameteri(int target, int pname, int param) {
android.opengl.GLES20.glTexParameteri(target, pname, param);
}
@Override
public void glClearColor(float red, float green, float blue, float alpha) {
android.opengl.GLES20.glClearColor(red, green, blue, alpha);
}
@Override
public void glClear(int mask) {
android.opengl.GLES20.glClear(mask);
}
@Override
public void glDisable(int cap) {
android.opengl.GLES20.glDisable(cap);
}
@Override
public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format,
int type, Buffer pixels) {
android.opengl.GLES20.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
}
@Override
public void glDrawElements(int mode, int count, int type, Buffer indices) {
android.opengl.GLES20.glDrawElements(mode, count, type, indices);
}
@Override
public void glBlendEquationSeparate(int modeRGB, int modeAlpha) {
android.opengl.GLES20.glBlendEquationSeparate(modeRGB, modeAlpha);
}
@Override
public void glBlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
android.opengl.GLES20.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
@Override
public void glEnable(int cap) {
android.opengl.GLES20.glEnable(cap);
}
} |
package com.opencms.file.mySql;
import javax.servlet.http.*;
import java.util.*;
import java.net.*;
import java.io.*;
import source.org.apache.java.io.*;
import source.org.apache.java.util.*;
import com.opencms.core.*;
import com.opencms.file.*;
import com.opencms.template.*;
public class CmsResourceBroker extends com.opencms.file.genericSql.CmsResourceBroker {
public com.opencms.file.genericSql.CmsDbAccess createDbAccess(Configurations configurations) throws CmsException
{
return new com.opencms.file.mySql.CmsDbAccess(configurations);
}
/**
* Reads a project from the Cms.
*
* <B>Security</B>
* All users are granted.
*
* @param currentUser The user who requested this method.
* @param currentProject The current project of the user.
* @param task The task to read the project of.
*
* @exception CmsException Throws CmsException if something goes wrong.
*/
public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException
{
// read the parent of the task, until it has no parents.
while (task.getParent() != 0)
{
task = readTask(currentUser, currentProject, task.getParent());
}
return m_dbAccess.readProject(task);
}
} |
package com.psddev.dari.db;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.psddev.dari.util.ConversionException;
import com.psddev.dari.util.Converter;
import com.psddev.dari.util.ErrorUtils;
import com.psddev.dari.util.ObjectToIterable;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.StorageItem;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.TypeDefinition;
import com.psddev.dari.util.UuidUtils;
/** Represents the state of an object stored in the database. */
public class State implements Map<String, Object> {
public static final String ID_KEY = "_id";
public static final String TYPE_KEY = "_type";
public static final String LABEL_KEY = "_label";
/**
* {@linkplain Query#getOptions Query option} that contains the object
* whose fields are being resolved automatically.
*/
public static final String REFERENCE_RESOLVING_QUERY_OPTION = "dari.referenceResolving";
public static final String REFERENCE_FIELD_QUERY_OPTION = "dari.referenceField";
public static final String UNRESOLVED_TYPE_IDS_QUERY_OPTION = "dari.unresolvedTypeIds";
private static final String ATOMIC_OPERATIONS_EXTRA = "dari.atomicOperations";
private static final int STATUS_FLAG_OFFSET = 16;
private static final int STATUS_FLAG_MASK = -1 >>> STATUS_FLAG_OFFSET;
private static final int ALL_RESOLVED_FLAG = 1 << 0;
private static final int RESOLVE_TO_REFERENCE_ONLY_FLAG = 1 << 1;
private static final int RESOLVE_WITHOUT_CACHE = 1 << 2;
private static final int RESOLVE_USING_MASTER = 1 << 3;
private static final int RESOLVE_INVISIBLE = 1 << 4;
private static final ThreadLocal<List<Listener>> LISTENERS_LOCAL = new ThreadLocal<List<Listener>>();
private final Map<Class<?>, Object> linkedObjects = new LinkedHashMap<Class<?>, Object>();
private Database database;
private UUID id;
private UUID typeId;
private final Map<String, Object> rawValues = new LinkedHashMap<String, Object>();
private Map<String, Object> extras;
private Map<ObjectField, List<String>> errors;
private volatile int flags;
public static State getInstance(Object object) {
if (object == null) {
return null;
} else if (object instanceof State) {
return (State) object;
} else if (object instanceof Recordable) {
return ((Recordable) object).getState();
} else {
throw new IllegalArgumentException(String.format(
"Can't retrieve state from an instance of [%s]!",
object.getClass().getName()));
}
}
/**
* Links the given {@code object} to this state so that changes on
* either side are copied over.
*/
public void linkObject(Object object) {
if (object != null) {
linkedObjects.put(object.getClass(), object);
}
}
/**
* Unlinks the given {@code object} from this state so that changes
* on either side are no longer copied over.
*/
public void unlinkObject(Object object) {
if (object != null) {
linkedObjects.remove(object.getClass());
}
}
/**
* Returns the effective originating database.
*
* <p>This method will check the following:</p>
*
* <ul>
* <li>{@linkplain #getRealDatabase Real originating database}.</li>
* <li>{@linkplain Database.Static#getDefault Default database}.</li>
* <li>{@linkplain ObjectType#getSourceDatabase Source database}.</li>
* <li>
*
* @return Never {@code null}.
*/
public Database getDatabase() {
if (database == null) {
Database newDatabase = Database.Static.getDefault();
this.database = newDatabase;
ObjectType type = getType();
if (type != null) {
newDatabase = type.getSourceDatabase();
if (newDatabase != null) {
this.database = newDatabase;
}
}
}
return database;
}
/**
* Returns the real originating database.
*
* @return May be {@code null}.
*/
public Database getRealDatabase() {
return database;
}
/**
* Sets the originating database.
*
* @param database May be {@code null}.
*/
public void setDatabase(Database database) {
this.database = database;
}
/** Returns the unique ID. */
public UUID getId() {
if (id == null) {
setId(UuidUtils.createSequentialUuid());
}
return this.id;
}
/** Sets the unique ID. */
public void setId(UUID id) {
this.id = id;
}
/** Returns the type ID. */
public UUID getTypeId() {
if (typeId == null) {
UUID newTypeId = UuidUtils.ZERO_UUID;
if (!linkedObjects.isEmpty()) {
Database database = getDatabase();
if (database != null) {
ObjectType type = database.getEnvironment().getTypeByClass(linkedObjects.keySet().iterator().next());
if (type != null) {
newTypeId = type.getId();
}
}
}
typeId = newTypeId;
}
return typeId;
}
public UUID getVisibilityAwareTypeId() {
ObjectType type = getType();
if (type != null) {
updateVisibilities(getDatabase().getEnvironment().getIndexes());
updateVisibilities(type.getIndexes());
@SuppressWarnings("unchecked")
List<String> visibilities = (List<String>) get("dari.visibilities");
if (visibilities != null && !visibilities.isEmpty()) {
String field = visibilities.get(visibilities.size() - 1);
Object value = toSimpleValue(get(field), false);
if (value != null) {
byte[] typeId = UuidUtils.toBytes(getTypeId());
byte[] md5 = StringUtils.md5(field + "/" + value.toString().trim().toLowerCase(Locale.ENGLISH));
for (int i = 0, length = typeId.length; i < length; ++ i) {
typeId[i] ^= md5[i];
}
return UuidUtils.fromBytes(typeId);
}
}
}
return getTypeId();
}
private void updateVisibilities(List<ObjectIndex> indexes) {
@SuppressWarnings("unchecked")
List<String> visibilities = (List<String>) get("dari.visibilities");
for (ObjectIndex index : indexes) {
if (index.isVisibility()) {
String field = index.getField();
Object value = toSimpleValue(index.getValue(this), false);
if (value == null) {
if (visibilities != null) {
visibilities.remove(field);
if (visibilities.isEmpty()) {
remove("dari.visibilities");
}
}
} else {
if (visibilities == null) {
visibilities = new ArrayList<String>();
put("dari.visibilities", visibilities);
}
if (!visibilities.contains(field)) {
visibilities.add(field);
}
}
}
}
}
/** Sets the type ID. */
public void setTypeId(UUID typeId) {
this.typeId = typeId;
}
/** Returns the type. */
public ObjectType getType() {
ObjectType type = getDatabase().getEnvironment().getTypeById(getTypeId());
if (type == null) {
// During the bootstrapping process, the type for the root
// type is not available, so fake it here.
for (Object object : linkedObjects.values()) {
if (object instanceof ObjectType && getId().equals(getTypeId())) {
type = (ObjectType) object;
type.setObjectClassName(ObjectType.class.getName());
type.initialize();
}
break;
}
}
return type;
}
/**
* Sets the type. This method may also change the originating
* database based on the the given {@code type}.
*/
public void setType(ObjectType type) {
if (type == null) {
setTypeId(null);
} else {
setTypeId(type.getId());
setDatabase(type.getState().getDatabase());
}
}
/**
* Returns {@code true} if this state is visible (all visibility-indexed
* fields are {@code null}).
*/
public boolean isVisible() {
return ObjectUtils.isBlank(get("dari.visibilities"));
}
public ObjectField getField(String name) {
ObjectField field = getDatabase().getEnvironment().getField(name);
if (field == null) {
ObjectType type = getType();
if (type != null) {
field = type.getField(name);
}
}
return field;
}
/** Returns the status. */
public StateStatus getStatus() {
int statusFlag = flags >>> STATUS_FLAG_OFFSET;
for (StateStatus status : StateStatus.values()) {
if (statusFlag == status.getFlag()) {
return status;
}
}
return null;
}
/**
* Returns {@code true} if this state has never been saved to the
* database.
*/
public boolean isNew() {
return (flags >>> STATUS_FLAG_OFFSET) == 0;
}
private boolean checkStatus(StateStatus status) {
return ((flags >>> STATUS_FLAG_OFFSET) & status.getFlag()) > 0;
}
/**
* Returns {@code true} if this state was recently deleted from the
* database.
*/
public boolean isDeleted() {
return checkStatus(StateStatus.DELETED);
}
/**
* Returns {@code true} if this state only contains the reference
* to the object (ID and type ID).
*/
public boolean isReferenceOnly() {
return checkStatus(StateStatus.REFERENCE_ONLY);
}
/**
* Sets the status. This method will also clear all pending atomic
* operations and existing validation errors.
*/
public void setStatus(StateStatus status) {
flags &= STATUS_FLAG_MASK;
if (status != null) {
flags |= status.getFlag() << STATUS_FLAG_OFFSET;
}
getExtras().remove(ATOMIC_OPERATIONS_EXTRA);
if (errors != null) {
errors.clear();
}
}
/** Returns the map of all the fields values. */
public Map<String, Object> getValues() {
resolveReferences();
return this;
}
/** Sets the map of all the values. */
public void setValues(Map<String, Object> values) {
clear();
putAll(values);
}
/**
* Returns a map of all values converted to only simple types:
* {@code null}, {@link java.lang.Boolean}, {@link java.lang.Number},
* {@link java.lang.String}, {@link java.util.ArrayList}, or
* {@link java.util.LinkedHashMap}.
*/
public Map<String, Object> getSimpleValues() {
Map<String, Object> values = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Object> entry : getValues().entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
ObjectField field = getField(name);
if (field == null) {
values.put(name, toSimpleValue(value, false));
} else if (value != null && !(value instanceof Metric)) {
values.put(name, toSimpleValue(value, field.isEmbedded()));
}
}
values.put(StateValueUtils.ID_KEY, getId().toString());
values.put(StateValueUtils.TYPE_KEY, getTypeId().toString());
return values;
}
/**
* Similar to {@link #getSimpleValues()} but only returns those values
* with fields strictly defined on this State's type.
* @deprecated No replacement
* @see #getSimpleValues()
*/
@Deprecated
public Map<String, Object> getSimpleFieldedValues() {
Map<String, Object> values = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Object> e : getValues().entrySet()) {
String name = e.getKey();
ObjectField field = getField(name);
if (field != null) {
values.put(name, toSimpleValue(e.getValue(), field.isEmbedded()));
}
}
values.put(StateValueUtils.ID_KEY, getId().toString());
values.put(StateValueUtils.TYPE_KEY, getTypeId().toString());
return values;
}
/**
* Converts the given {@code value} into an instance of one of
* the simple types listed in {@link #getSimpleValues}.
*/
private static Object toSimpleValue(Object value, boolean isEmbedded) {
if (value == null) {
return null;
}
Iterable<Object> valueIterable = ObjectToIterable.iterable(value);
if (valueIterable != null) {
List<Object> list = new ArrayList<Object>();
for (Object item : valueIterable) {
list.add(toSimpleValue(item, isEmbedded));
}
return list;
} else if (value instanceof Map) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
Object key = entry.getKey();
if (key != null) {
map.put(key.toString(), toSimpleValue(entry.getValue(), isEmbedded));
}
}
return map;
} else if (value instanceof Query) {
return ((Query<?>) value).getState().getSimpleValues();
} else if (value instanceof Metric) {
return null;
} else if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
if (valueState.isNew()) {
ObjectType type;
if (isEmbedded ||
((type = valueState.getType()) != null &&
type.isEmbedded())) {
return valueState.getSimpleValues();
}
}
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put(StateValueUtils.REFERENCE_KEY, valueState.getId().toString());
map.put(StateValueUtils.TYPE_KEY, valueState.getTypeId().toString());
return map;
} else if (value instanceof Boolean ||
value instanceof Number ||
value instanceof String) {
return value;
} else if (value instanceof Character ||
value instanceof CharSequence ||
value instanceof String ||
value instanceof URI ||
value instanceof URL ||
value instanceof UUID) {
return value.toString();
} else if (value instanceof Date) {
return ((Date) value).getTime();
} else if (value instanceof Enum) {
return ((Enum<?>) value).name();
} else {
return toSimpleValue(ObjectUtils.to(Map.class, value), isEmbedded);
}
}
/**
* Returns the value associated with the given {@code path}.
*
* @param path If {@code null}, returns {@code null}.
* @return May be {@code null}.
*/
public Object getByPath(String path) {
if (path == null) {
return null;
}
DatabaseEnvironment environment = getDatabase().getEnvironment();
Object value = this;
KEY: for (String key; path != null; ) {
int slashAt = path.indexOf('/');
if (slashAt > -1) {
key = path.substring(0, slashAt);
path = path.substring(slashAt + 1);
} else {
key = path;
path = null;
}
if (key.indexOf('.') > -1 &&
environment.getTypeByName(key) != null) {
continue;
}
if (value instanceof Recordable) {
value = ((Recordable) value).getState();
}
if (key.endsWith("()")) {
if (value instanceof State) {
key = key.substring(0, key.length() - 2);
Class<?> keyClass = null;
int dotAt = key.lastIndexOf('.');
if (dotAt > -1) {
keyClass = ObjectUtils.getClassByName(key.substring(0, dotAt));
key = key.substring(dotAt + 1);
}
if (keyClass == null) {
value = ((State) value).getOriginalObject();
keyClass = value.getClass();
} else {
value = ((State) value).as(keyClass);
}
for (Class<?> c = keyClass; c != null; c = c.getSuperclass()) {
try {
Method keyMethod = c.getDeclaredMethod(key);
keyMethod.setAccessible(false);
value = keyMethod.invoke(value);
continue KEY;
} catch (IllegalAccessException error) {
throw new IllegalStateException(error);
} catch (InvocationTargetException error) {
ErrorUtils.rethrow(error.getCause());
} catch (NoSuchMethodException error) {
// Try to find the method in the super class.
}
}
}
return null;
}
if (value instanceof State) {
State valueState = (State) value;
if (ID_KEY.equals(key)) {
value = valueState.getId();
} else if (TYPE_KEY.equals(key)) {
value = valueState.getType();
} else if (LABEL_KEY.equals(key)) {
value = valueState.getLabel();
} else {
value = valueState.get(key);
}
} else if (value instanceof Map) {
value = ((Map<?, ?>) value).get(key);
} else if (value instanceof List) {
Integer index = ObjectUtils.to(Integer.class, key);
if (index != null) {
List<?> list = (List<?>) value;
int listSize = list.size();
if (index < 0) {
index += listSize;
}
if (index >= 0 && index < listSize) {
value = list.get(index);
continue;
}
}
return null;
} else {
return null;
}
}
return value;
}
public Map<String, Object> getRawValues() {
return rawValues;
}
/**
* Returns the field associated with the given {@code name} as an
* instance of the given {@code returnType}. This version of get will
* not trigger reference resolution which avoids a round-trip to the
* database.
*/
public Object getRawValue(String name) {
Object value = rawValues;
for (String part : StringUtils.split(name, "/")) {
if (value == null) {
break;
} else if (value instanceof Recordable) {
value = ((Recordable) value).getState().getValue(part);
} else if (value instanceof Map) {
value = ((Map<?, ?>) value).get(part);
} else if (value instanceof List) {
Integer index = ObjectUtils.to(Integer.class, part);
if (index != null) {
List<?> list = (List<?>) value;
if (index >= 0 && index < list.size()) {
value = list.get(index);
continue;
}
}
value = null;
break;
}
}
return value;
}
/** Puts the given field value at given name. */
@SuppressWarnings("unchecked")
public void putByPath(String name, Object value) {
Map<String, Object> parent = getValues();
String[] parts = StringUtils.split(name, "/");
int last = parts.length - 1;
for (int i = 0; i < last; i ++) {
String part = parts[i];
Object child = parent.get(part);
if (child instanceof Recordable) {
parent = ((Recordable) child).getState().getValues();
} else {
if (!(child instanceof Map)) {
child = new LinkedHashMap<String, Object>();
parent.put(part, child);
}
parent = (Map<String, Object>) child;
}
}
parent.put(parts[last], value);
}
/** Returns the indexes for the ObjectType returned by {@link #getType()}
* as well as any embedded indexes on this State. */
public Set<ObjectIndex> getIndexes() {
Set<ObjectIndex> indexes = new LinkedHashSet<ObjectIndex>();
ObjectType type = getType();
if (type != null) {
indexes.addAll(type.getIndexes());
for (Map.Entry<String, Object> entry : getValues().entrySet()) {
ObjectField field = getField(entry.getKey());
if (field != null) {
getEmbeddedIndexes(indexes, null, field, entry.getValue());
}
}
}
return indexes;
}
/** Recursively gathers all the embedded Indexes for this State object. */
private void getEmbeddedIndexes(Set<ObjectIndex> indexes,
String parentFieldName,
ObjectField field, Object fieldValue) {
if (fieldValue instanceof Recordable) {
State state = State.getInstance(fieldValue);
ObjectType type = state.getType();
if (type == null) {
return;
}
if (field.isEmbedded() || type.isEmbedded()) {
for (ObjectIndex i : type.getIndexes()) {
ObjectIndex index = new ObjectIndex(getType(), null);
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
if (parentFieldName != null) {
builder.append(parentFieldName).append('/');
builder2.append(parentFieldName).append('/');
}
builder.append(field.getInternalName()).append('/');
builder2.append(field.getInternalName()).append('/');
builder.append(i.getField());
builder2.append(i.getUniqueName());
String fieldName = builder.toString();
index.setField(fieldName);
index.setType(i.getType());
index.setUnique(i.isUnique());
// get the declaring class of the first level field name
int slashAt = fieldName.indexOf('/');
String firstLevelFieldName = fieldName.substring(0, slashAt);
ObjectField firstLevelField = getField(firstLevelFieldName);
if (firstLevelField != null && firstLevelField.getJavaDeclaringClassName() != null) {
index.setJavaDeclaringClassName(firstLevelField.getJavaDeclaringClassName());
} else {
index.setJavaDeclaringClassName(getType().getObjectClassName());
}
indexes.add(index);
ObjectIndex index2 = new ObjectIndex(getType(), null);
index2.setName(builder2.toString());
index2.setField(index.getField());
index2.setType(index.getType());
index2.setUnique(index.isUnique());
index2.setJavaDeclaringClassName(index.getJavaDeclaringClassName());
indexes.add(index2);
}
if (parentFieldName == null) {
parentFieldName = field.getInternalName();
} else {
parentFieldName += "/" + field.getInternalName();
}
Map<String, Object> values = state.getValues();
for (Map.Entry<String, Object> entry : values.entrySet()) {
ObjectField objectField = state.getField(entry.getKey());
if (objectField != null) {
getEmbeddedIndexes(indexes, parentFieldName,
objectField, entry.getValue());
}
}
}
} else if (fieldValue instanceof Map) {
for (Map.Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet()) {
getEmbeddedIndexes(indexes, parentFieldName, field, entry.getValue());
}
} else if (fieldValue instanceof Iterable) {
for (Object listItem : (Iterable<?>) fieldValue) {
getEmbeddedIndexes(indexes, parentFieldName, field, listItem);
}
}
}
/**
* Returns an unmodifiable list of all the atomic operations pending on
* this record.
*/
public List<AtomicOperation> getAtomicOperations() {
Map<String, Object> extras = getExtras();
@SuppressWarnings("unchecked")
List<AtomicOperation> ops = (List<AtomicOperation>) extras.get(ATOMIC_OPERATIONS_EXTRA);
if (ops == null) {
ops = new ArrayList<AtomicOperation>();
extras.put(ATOMIC_OPERATIONS_EXTRA, ops);
}
return ops;
}
// Queues up an atomic operation and updates the internal state.
private void queueAtomicOperation(AtomicOperation operation) {
operation.execute(this);
getAtomicOperations().add(operation);
}
/**
* Increments the field associated with the given {@code name} by the
* given {@code value}. If the field contains a non-numeric value, it
* will be set to 0 first.
*/
public void incrementAtomically(String name, double value) {
queueAtomicOperation(new AtomicOperation.Increment(name, value));
}
/**
* Decrements the field associated with the given {@code name} by the
* given {@code value}. If the field contains a non-numeric value, it
* will be set to 0 first.
*/
public void decrementAtomically(String name, double value) {
incrementAtomically(name, -value);
}
/**
* Adds the given {@code value} to the collection field associated with
* the given {@code name}.
*/
public void addAtomically(String name, Object value) {
queueAtomicOperation(new AtomicOperation.Add(name, value));
}
/**
* Removes all instances of the given {@code value} in the collection
* field associated with the given {@code name}.
*/
public void removeAtomically(String name, Object value) {
queueAtomicOperation(new AtomicOperation.Remove(name, value));
}
/**
* Replaces the field value at the given {@code name} with the given
* {@code value}. If the object changes in the database before
* {@link #save()} is called, {@link AtomicOperation.ReplacementException}
* will be thrown.
*/
public void replaceAtomically(String name, Object value) {
queueAtomicOperation(new AtomicOperation.Replace(name, getValue(name), value));
}
/**
* Puts the given {@code value} into the field associated with the
* given {@code name} atomically.
*/
public void putAtomically(String name, Object value) {
queueAtomicOperation(new AtomicOperation.Put(name, value));
}
/** Returns all the fields with validation errors from this record. */
public Set<ObjectField> getErrorFields() {
return errors != null ?
Collections.unmodifiableSet(errors.keySet()) :
Collections.<ObjectField>emptySet();
}
/**
* Returns all the validation errors for the given field from this
* record.
*/
public List<String> getErrors(ObjectField field) {
if (errors != null) {
List<String> messages = errors.get(field);
if (messages != null && !messages.isEmpty()) {
return Collections.unmodifiableList(messages);
}
}
return Collections.emptyList();
}
/** Returns true if this record has any validation errors. */
public boolean hasAnyErrors() {
if (errors != null) {
for (List<String> messages : errors.values()) {
if (messages != null && !messages.isEmpty()) {
return true;
}
}
}
ObjectType type = getType();
if (type != null) {
for (ObjectField field : type.getFields()) {
if (hasErrorsForValue(get(field.getInternalName()), field.isEmbedded())) {
return true;
}
}
}
return false;
}
private boolean hasErrorsForValue(Object value, boolean embedded) {
if (value instanceof Map) {
value = ((Map<?, ?>) value).values();
}
if (value instanceof Iterable) {
for (Object item : (Iterable<?>) value) {
if (hasErrorsForValue(item, embedded)) {
return true;
}
}
} else if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
if (embedded) {
if (valueState.hasAnyErrors()) {
return true;
}
} else {
ObjectType valueType = valueState.getType();
if (valueType != null && valueType.isEmbedded() && valueState.hasAnyErrors()) {
return true;
}
}
}
return false;
}
/**
* Returns true if the given field in this record has any validation
* errors.
*/
public boolean hasErrors(ObjectField field) {
return errors != null && errors.get(field).size() > 0;
}
public void clearAllErrors() {
errors = null;
}
/** Returns a modifiable map of all the extras values from this state. */
public Map<String, Object> getExtras() {
if (extras == null) {
extras = new LinkedHashMap<String, Object>();
}
return extras;
}
/**
* Returns the extra value associated with the given {@code name} from
* this state.
*/
public Object getExtra(String name) {
return extras != null ? extras.get(name) : null;
}
public void addError(ObjectField field, String message) {
if (errors == null) {
errors = new LinkedHashMap<ObjectField, List<String>>();
}
List<String> messages = errors.get(field);
if (messages == null) {
messages = new ArrayList<String>();
errors.put(field, messages);
}
messages.add(message);
}
public boolean isResolveToReferenceOnly() {
return (flags & RESOLVE_TO_REFERENCE_ONLY_FLAG) != 0;
}
public void setResolveToReferenceOnly(boolean resolveToReferenceOnly) {
if (resolveToReferenceOnly) {
flags |= RESOLVE_TO_REFERENCE_ONLY_FLAG;
} else {
flags &= ~RESOLVE_TO_REFERENCE_ONLY_FLAG;
}
}
public boolean isResolveUsingCache() {
return (flags & RESOLVE_WITHOUT_CACHE) == 0;
}
public void setResolveUsingCache(boolean resolveUsingCache) {
if (resolveUsingCache) {
flags &= ~RESOLVE_WITHOUT_CACHE;
} else {
flags |= RESOLVE_WITHOUT_CACHE;
}
}
public boolean isResolveUsingMaster() {
return (flags & RESOLVE_USING_MASTER) != 0;
}
public void setResolveUsingMaster(boolean resolveUsingMaster) {
if (resolveUsingMaster) {
flags |= RESOLVE_USING_MASTER;
} else {
flags &= ~RESOLVE_USING_MASTER;
}
}
public boolean isResolveInvisible() {
return (flags & RESOLVE_INVISIBLE) != 0;
}
public void setResolveInvisible(boolean resolveInvisible) {
if (resolveInvisible) {
flags |= RESOLVE_INVISIBLE;
} else {
flags &= ~RESOLVE_INVISIBLE;
}
}
/** Returns a descriptive label for this state. */
public String getLabel() {
Object object = getOriginalObject();
return object instanceof Record ?
((Record) object).getLabel() :
getDefaultLabel();
}
// To check for circular references in resolving labels.
private static final ThreadLocal<Map<UUID, String>> LABEL_CACHE = new ThreadLocal<Map<UUID, String>>();
/**
* Returns the default, descriptive label for this state.
* Fields specified in {@link Recordable.LabelFields} are used to
* construct it. If the referenced field value contains a state,
* it may call itself, but not more than once per state.
*/
protected String getDefaultLabel() {
ObjectType type = getType();
if (type != null) {
StringBuilder label = new StringBuilder();
for (String field : type.getLabelFields()) {
Object value = getValue(field);
if (value != null) {
String valueString;
if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
UUID valueId = valueState.getId();
Map<UUID, String> cache = LABEL_CACHE.get();
boolean isFirst = false;
if (cache == null) {
cache = new HashMap<UUID, String>();
LABEL_CACHE.set(cache);
isFirst = true;
}
try {
if (cache.containsKey(valueId)) {
valueString = cache.get(valueId);
if (valueString == null) {
valueString = valueId.toString();
}
} else {
cache.put(valueId, null);
valueString = valueState.getLabel();
cache.put(valueId, valueString);
}
} finally {
if (isFirst) {
LABEL_CACHE.remove();
}
}
} else if (value instanceof Iterable<?>) {
StringBuilder iterableLabel = new StringBuilder();
iterableLabel.append('[');
for (Object item : (Iterable<?>) value) {
if (item instanceof Recordable) {
iterableLabel.append(((Recordable) item).getState().getLabel());
} else {
iterableLabel.append(item.toString());
}
iterableLabel.append(", ");
}
if (iterableLabel.length() > 2) {
iterableLabel.setLength(iterableLabel.length() - 2);
}
iterableLabel.append(']');
valueString = iterableLabel.toString();
} else {
valueString = value.toString();
}
if (valueString.length() > 0) {
label.append(valueString);
label.append(' ');
}
}
}
if (label.length() > 0) {
label.setLength(label.length() - 1);
return label.toString();
}
}
return getId().toString();
}
/** Returns a storage item that can be used to preview this state. */
public StorageItem getPreview() {
ObjectType type = getType();
if (type != null) {
String field = type.getPreviewField();
if (!ObjectUtils.isBlank(field)) {
return (StorageItem) getValue(field);
}
}
return null;
}
/**
* Returns the label that identifies the current visibility in effect.
*
* @return May be {@code null}.
* @see VisibilityLabel
*/
public String getVisibilityLabel() {
@SuppressWarnings("unchecked")
List<String> visibilities = (List<String>) get("dari.visibilities");
if (visibilities != null && !visibilities.isEmpty()) {
String fieldName = visibilities.get(visibilities.size() - 1);
ObjectField field = getField(fieldName);
if (field != null) {
Class<?> fieldDeclaring = ObjectUtils.getClassByName(field.getJavaDeclaringClassName());
if (fieldDeclaring != null &&
VisibilityLabel.class.isAssignableFrom(fieldDeclaring)) {
return ((VisibilityLabel) as(fieldDeclaring)).createVisibilityLabel(field);
}
}
return ObjectUtils.to(String.class, get(fieldName));
}
return null;
}
public void prefetch() {
prefetch(getValues());
}
private void prefetch(Object object) {
if (object instanceof Map) {
for (Object item : ((Map<?, ?>) object).values()) {
prefetch(item);
}
} else if (object instanceof Iterable) {
for (Object item : (Iterable<?>) object) {
prefetch(item);
}
}
}
/**
* Returns an instance of the given {@code modificationClass} linked
* to this state.
*/
public <T> T as(Class<T> objectClass) {
@SuppressWarnings("unchecked")
T object = (T) linkedObjects.get(objectClass);
if (object == null) {
object = TypeDefinition.getInstance(objectClass).newInstance();
((Recordable) object).setState(this);
copyRawValuesToJavaFields(object);
}
return object;
}
/** Returns the original object. */
public Object getOriginalObject() {
for (Object object : linkedObjects.values()) {
if (!(object instanceof Modification)) {
return object;
}
}
throw new IllegalStateException("No original object!");
}
/** Returns a set of all objects that can be used with this state. */
@SuppressWarnings("all")
public Collection<Record> getObjects() {
List<Record> objects = new ArrayList<Record>();
objects.addAll((Collection) linkedObjects.values());
return objects;
}
public void beforeFieldGet(String name) {
List<Listener> listeners = LISTENERS_LOCAL.get();
if (listeners != null && !listeners.isEmpty()) {
for (Listener listener : listeners) {
listener.beforeFieldGet(this, name);
}
}
}
/**
* Resolves the reference possibly stored in the given {@code field}.
* This method doesn't need to be used directly in typical cases, because
* it will be called automatically by {@link LazyLoadEnhancer}.
*
* @param field If {@code null}, resolves all references.
*/
public void resolveReference(String field) {
if ((flags & ALL_RESOLVED_FLAG) != 0) {
return;
}
synchronized (this) {
if ((flags & ALL_RESOLVED_FLAG) != 0) {
return;
}
flags |= ALL_RESOLVED_FLAG;
if (linkedObjects.isEmpty()) {
return;
}
Object object = linkedObjects.values().iterator().next();
Map<UUID, Object> references = StateValueUtils.resolveReferences(getDatabase(), object, rawValues.values(), field);
Map<String, Object> resolved = new HashMap<String, Object>();
for (Map.Entry<? extends String, ? extends Object> e : rawValues.entrySet()) {
UUID id = StateValueUtils.toIdIfReference(e.getValue());
if (id != null) {
resolved.put(e.getKey(), references.get(id));
}
}
for (Map.Entry<String, Object> e : resolved.entrySet()) {
put(e.getKey(), e.getValue());
}
}
}
/**
* Resolves all references to other objects. This method doesn't need to
* be used directly in typical cases, because it will be called
* automatically by {@link LazyLoadEnhancer}.
*/
public void resolveReferences() {
resolveReference(null);
}
/**
* Returns {@code true} if the field values in this state is valid.
* The validation rules are typically read from annotations such as
* {@link Recordable.FieldRequired}.
*/
public boolean validate() {
ObjectType type = getType();
if (type != null) {
for (ObjectField field : type.getFields()) {
field.validate(this);
validateValue(get(field.getInternalName()), field.isEmbedded());
}
}
DatabaseEnvironment environment = getDatabase().getEnvironment();
for (ObjectField field : environment.getFields()) {
field.validate(this);
}
return !hasAnyErrors();
}
private void validateValue(Object value, boolean embedded) {
if (value instanceof Map) {
value = ((Map<?, ?>) value).values();
}
if (value instanceof Iterable) {
for (Object item : (Iterable<?>) value) {
validateValue(item, embedded);
}
} else if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
if (embedded) {
valueState.validate();
} else {
ObjectType valueType = valueState.getType();
if (valueType != null && valueType.isEmbedded()) {
valueState.validate();
}
}
}
}
private void copyJavaFieldsToRawValues() {
DatabaseEnvironment environment = getDatabase().getEnvironment();
for (Object object : linkedObjects.values()) {
Class<?> objectClass = object.getClass();
ObjectType type = environment.getTypeByClass(objectClass);
if (type == null) {
continue;
}
for (ObjectField field : type.getFields()) {
Field javaField = field.getJavaField(objectClass);
if (javaField == null ||
!javaField.getDeclaringClass().getName().equals(field.getJavaDeclaringClassName())) {
continue;
}
try {
rawValues.put(field.getInternalName(), javaField.get(object));
} catch (IllegalAccessException ex) {
throw new IllegalStateException(ex);
}
}
}
}
void copyRawValuesToJavaFields(Object object) {
Class<?> objectClass = object.getClass();
ObjectType type = getDatabase().getEnvironment().getTypeByClass(objectClass);
if (type == null) {
return;
}
for (ObjectField field : type.getFields()) {
String key = field.getInternalName();
Object value = StateValueUtils.toJavaValue(getDatabase(), object, field, field.getInternalType(), rawValues.get(key));
rawValues.put(key, value);
Field javaField = field.getJavaField(objectClass);
if (javaField != null) {
setJavaField(field, javaField, object, key, value);
}
}
}
private static final Converter CONVERTER; static {
CONVERTER = new Converter();
CONVERTER.putAllStandardFunctions();
CONVERTER.setThrowError(true);
}
private void setJavaField(
ObjectField field,
Field javaField,
Object object,
String key,
Object value) {
if (!javaField.getDeclaringClass().getName().equals(field.getJavaDeclaringClassName())) {
return;
}
try {
Type javaFieldType = javaField.getGenericType();
if ((!javaField.getType().isPrimitive() &&
!Number.class.isAssignableFrom(javaField.getType())) &&
(javaFieldType instanceof Class ||
((value instanceof StateValueList ||
value instanceof StateValueMap ||
value instanceof StateValueSet) &&
ObjectField.RECORD_TYPE.equals(field.getInternalItemType())))) {
try {
javaField.set(object, value);
return;
} catch (IllegalArgumentException error) {
// Ignore since it will be retried below.
}
}
try {
if (javaFieldType instanceof TypeVariable) {
javaField.set(object, value);
} else if (javaFieldType instanceof Class &&
((Class<?>) javaFieldType).isPrimitive()) {
javaField.set(object, ObjectUtils.to(javaFieldType, value));
} else {
javaField.set(object, CONVERTER.convert(javaFieldType, value));
}
} catch (RuntimeException error) {
Throwable cause;
if (error instanceof ConversionException) {
cause = error.getCause();
if (cause == null) {
cause = error;
}
} else {
cause = error;
}
rawValues.put("dari.trash." + key, value);
rawValues.put("dari.trashError." + key, cause.getClass().getName());
rawValues.put("dari.trashErrorMessage." + key, cause.getMessage());
}
} catch (IllegalAccessException error) {
throw new IllegalStateException(error);
}
}
@Override
public void clear() {
rawValues.clear();
DatabaseEnvironment environment = getDatabase().getEnvironment();
for (Object object : linkedObjects.values()) {
Class<?> objectClass = object.getClass();
ObjectType type = environment.getTypeByClass(objectClass);
if (type == null) {
continue;
}
for (ObjectField field : type.getFields()) {
Field javaField = field.getJavaField(objectClass);
if (javaField == null) {
continue;
}
try {
javaField.set(object, ObjectUtils.to(javaField.getGenericType(), null));
} catch (IllegalAccessException ex) {
throw new IllegalStateException(ex);
}
}
}
}
@Override
public boolean containsKey(Object key) {
return rawValues.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
copyJavaFieldsToRawValues();
return rawValues.containsKey(value);
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
copyJavaFieldsToRawValues();
return rawValues.entrySet();
}
@Override
public Object get(Object key) {
if (!(key instanceof String)) {
return null;
}
resolveReferences();
for (Object object : linkedObjects.values()) {
Class<?> objectClass = object.getClass();
ObjectType type = getDatabase().getEnvironment().getTypeByClass(objectClass);
if (type == null) {
continue;
}
ObjectField field = type.getField((String) key);
if (field == null) {
continue;
}
Field javaField = field.getJavaField(objectClass);
if (javaField == null) {
continue;
}
Object value;
try {
value = javaField.get(object);
} catch (IllegalAccessException ex) {
throw new IllegalStateException(ex);
}
rawValues.put(field.getInternalName(), value);
return value;
}
return rawValues.get(key);
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Set<String> keySet() {
return rawValues.keySet();
}
@Override
public Object put(String key, Object value) {
if (key == null) {
return null;
}
if (key.startsWith("_")) {
if (key.equals(StateValueUtils.ID_KEY)) {
setId(ObjectUtils.to(UUID.class, value));
} else if (key.equals(StateValueUtils.TYPE_KEY)) {
setTypeId(ObjectUtils.to(UUID.class, value));
}
return null;
}
boolean first = true;
for (Object object : linkedObjects.values()) {
ObjectField field = State.getInstance(object).getField(key);
if (first) {
value = StateValueUtils.toJavaValue(getDatabase(), object, field, field != null ? field.getInternalType() : null, value);
first = false;
}
if (field != null) {
Field javaField = field.getJavaField(object.getClass());
if (javaField != null) {
setJavaField(field, javaField, object, key, value);
}
}
}
return rawValues.put(key, value);
}
@Override
public void putAll(Map<? extends String, ? extends Object> map) {
if (!linkedObjects.isEmpty()) {
Object object = linkedObjects.values().iterator().next();
if (object != null && getType() != null && getType().isLazyLoaded()) {
for (Map.Entry<? extends String, ? extends Object> e : map.entrySet()) {
String key = e.getKey();
Object value = e.getValue();
if (StateValueUtils.toIdIfReference(value) != null) {
rawValues.put(key, value);
} else {
put(key, value);
}
}
flags &= ~ALL_RESOLVED_FLAG;
return;
} else {
rawValues.putAll(map);
resolveReferences();
}
}
for (Map.Entry<? extends String, ? extends Object> e : map.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@Override
public Object remove(Object key) {
if (key instanceof String) {
Object oldValue = put((String) key, null);
rawValues.remove(key);
return oldValue;
} else {
return null;
}
}
@Override
public int size() {
return rawValues.size() + 2;
}
@Override
public Collection<Object> values() {
copyJavaFieldsToRawValues();
return rawValues.values();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof State) {
State otherState = (State) other;
return getId().equals(otherState.getId());
} else {
return false;
}
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{database=").append(getDatabase());
sb.append(", status=").append(getStatus());
sb.append(", id=").append(getId());
sb.append(", typeId=").append(getTypeId());
sb.append(", simpleValues=").append(getSimpleValues());
sb.append(", extras=").append(extras);
sb.append(", errors=").append(errors);
sb.append('}');
return sb.toString();
}
private transient Map<String, Object> modifications;
public Map<String, Object> getAs() {
if (modifications == null) {
modifications = Collections.<String, Object>unmodifiableMap(CacheBuilder.
newBuilder().
build(new CacheLoader<String, Object>() {
@Override
public Object load(String modificationClassName) {
Class<?> modificationClass = ObjectUtils.getClassByName(modificationClassName);
if (modificationClass != null) {
return as(modificationClass);
} else {
throw new IllegalArgumentException(String.format(
"[%s] isn't a valid class name!", modificationClassName));
}
}
}).
asMap());
}
return modifications;
}
/** @see Database#beginWrites() */
public boolean beginWrites() {
return getDatabase().beginWrites();
}
/** @see Database#commitWrites() */
public boolean commitWrites() {
return getDatabase().commitWrites();
}
/** @see Database#endWrites() */
public boolean endWrites() {
return getDatabase().endWrites();
}
/**
* {@linkplain Database#save Saves} this state to the
* {@linkplain #getDatabase originating database}.
*/
public void save() {
getDatabase().save(this);
}
/**
* Saves this state {@linkplain Database#beginIsolatedWrites immediately}
* to the {@linkplain #getDatabase originating database}.
*/
public void saveImmediately() {
Database database = getDatabase();
database.beginIsolatedWrites();
try {
database.save(this);
database.commitWrites();
} finally {
database.endWrites();
}
}
/**
* Saves this state {@linkplain Database#commitWritesEventually eventually}
* to the {@linkplain #getDatabase originating database}.
*/
public void saveEventually() {
Database database = getDatabase();
database.beginWrites();
try {
database.save(this);
database.commitWritesEventually();
} finally {
database.endWrites();
}
}
/**
* {@linkplain Database#saveUnsafely Saves} this state to the
* {@linkplain #getDatabase originating database} without validating
* the data.
*/
public void saveUnsafely() {
getDatabase().saveUnsafely(this);
}
public void saveUniquely() {
ObjectType type = getType();
if (type == null) {
throw new IllegalStateException("No type!");
}
Query<?> query = Query.fromType(type).noCache().master();
for (ObjectIndex index : type.getIndexes()) {
if (index.isUnique()) {
for (String field : index.getFields()) {
Object value = get(field);
query.and(field + " = ?", value != null ? value : Query.MISSING_VALUE);
}
}
}
if (query.getPredicate() == null) {
throw new IllegalStateException("No unique indexes!");
}
Exception lastError = null;
for (int i = 0; i < 10; ++ i) {
Object object = query.first();
if (object != null) {
setValues(State.getInstance(object).getValues());
return;
} else {
try {
saveImmediately();
return;
} catch (Exception error) {
lastError = error;
}
}
}
ErrorUtils.rethrow(lastError);
}
/**
* {@linkplain Database#index Indexes} this state data in the
* {@linkplain #getDatabase originating database}.
*/
public void index() {
getDatabase().index(this);
}
/**
* {@linkplain Database#delete Deletes} this state from the
* {@linkplain #getDatabase originating database}.
*/
public void delete() {
getDatabase().delete(this);
}
/**
* Deletes this state {@linkplain Database#beginIsolatedWrites immediately}
* from the {@linkplain #getDatabase originating database}.
*/
public void deleteImmediately() {
Database database = getDatabase();
database.beginIsolatedWrites();
try {
database.delete(this);
database.commitWrites();
} finally {
database.endWrites();
}
}
public abstract static class Listener {
public void beforeFieldGet(State state, String name) {
}
}
/** {@link State} utility methods. */
public static final class Static {
public static void addListener(Listener listener) {
List<Listener> listeners = LISTENERS_LOCAL.get();
if (listeners == null) {
listeners = new ArrayList<Listener>();
LISTENERS_LOCAL.set(listeners);
}
listeners.add(listener);
}
public static void removeListener(Listener listener) {
List<Listener> listeners = LISTENERS_LOCAL.get();
if (listeners != null) {
listeners.remove(listener);
if (listeners.isEmpty()) {
LISTENERS_LOCAL.remove();
}
}
}
}
/** @deprecated Use {@link #getSimpleValues} instead. */
@Deprecated
public Map<String, Object> getJsonObject() {
return getSimpleValues();
}
/** @deprecated Use {@link #getSimpleValues} and {@link ObjectUtils#toJson} instead. */
@Deprecated
public String getJsonString() {
return ObjectUtils.toJson(getSimpleValues());
}
/** @deprecated Use {@link #setValues} and {@link ObjectUtils#fromJson} instead. */
@Deprecated
@SuppressWarnings("unchecked")
public void setJsonString(String json) {
setValues((Map<String, Object>) ObjectUtils.fromJson(json));
}
/** @deprecated Use {@link #setStatus} instead. */
@Deprecated
public void markSaved() {
setStatus(StateStatus.SAVED);
}
/** @deprecated Use {@link #setStatus} instead. */
@Deprecated
public void markDeleted() {
setStatus(StateStatus.DELETED);
}
/** @deprecated Use {@link #setStatus} instead. */
@Deprecated
public void markReadonly() {
setStatus(StateStatus.REFERENCE_ONLY);
}
/** @deprecated Use {@link #isResolveReferenceOnly} instead. */
@Deprecated
public boolean isResolveReferenceOnly() {
return isResolveToReferenceOnly();
}
/** @deprecated Use {@link #isResolveReferenceOnly} instead. */
@Deprecated
public void setResolveReferenceOnly(boolean isResolveReferenceOnly) {
setResolveToReferenceOnly(isResolveReferenceOnly);
}
/** @deprecated Use {@link #incrementAtomically} instead. */
@Deprecated
public void incrementValue(String name, double value) {
incrementAtomically(name, value);
}
/** @deprecated Use {@link #decrementAtomically} instead. */
@Deprecated
public void decrementValue(String name, double value) {
decrementAtomically(name, value);
}
/** @deprecated Use {@link #addAtomically} instead. */
@Deprecated
public void addValue(String name, Object value) {
addAtomically(name, value);
}
/** @deprecated Use {@link #removeAtomically} instead. */
@Deprecated
public void removeValue(String name, Object value) {
removeAtomically(name, value);
}
/** @deprecated Use {@link #replaceAtomically} instead. */
@Deprecated
public void replaceValue(String name, Object value) {
replaceAtomically(name, value);
}
/** @deprecated Use {@link #getByPath} instead. */
@Deprecated
public Object getValue(String path) {
return getByPath(path);
}
/** @deprecated Use {@link #putByPath} instead. */
@Deprecated
public void putValue(String path, Object value) {
putByPath(path, value);
}
} |
package dr.app.beauti.options;
import dr.app.beauti.types.*;
import dr.evomodel.coalescent.VariableDemographicModel;
import dr.evomodelxml.speciation.BirthDeathModelParser;
import dr.evomodelxml.speciation.BirthDeathSerialSamplingModelParser;
import dr.math.MathUtils;
import java.util.List;
/**
* @author Alexei Drummond
* @author Andrew Rambaut
* @author Walter Xie
*/
public class PartitionTreePrior extends PartitionOptions {
private PartitionTreeModel treeModel; // only used when not sharing same prior
private TreePriorType nodeHeightPrior = TreePriorType.CONSTANT;
private TreePriorParameterizationType parameterization = TreePriorParameterizationType.GROWTH_RATE;
private int skylineGroupCount = 10;
private TreePriorParameterizationType skylineModel = TreePriorParameterizationType.CONSTANT_SKYLINE;
private TreePriorParameterizationType skyrideSmoothing = TreePriorParameterizationType.TIME_AWARE_SKYRIDE;
// AR - this seems to be set to taxonCount - 1 so we don't need to
// have a settable variable...
// public int skyrideIntervalCount = 1;
private VariableDemographicModel.Type extendedSkylineModel = VariableDemographicModel.Type.LINEAR;
private double birthDeathSamplingProportion = 1.0;
private PopulationSizeModelType populationSizeModel = PopulationSizeModelType.CONTINUOUS_CONSTANT;
private boolean fixedTree = false;
public PartitionTreePrior(BeautiOptions options, PartitionTreeModel treeModel) {
super(options, treeModel.getName());
this.treeModel = treeModel;
}
/**
* A copy constructor
*
* @param options the beauti options
* @param name the name of the new model
* @param source the source model
*/
public PartitionTreePrior(BeautiOptions options, String name, PartitionTreePrior source) {
super(options, name);
this.treeModel = source.treeModel;
this.nodeHeightPrior = source.nodeHeightPrior;
this.parameterization = source.parameterization;
this.skylineGroupCount = source.skylineGroupCount;
this.skylineModel = source.skylineModel;
this.skyrideSmoothing = source.skyrideSmoothing;
this.birthDeathSamplingProportion = source.birthDeathSamplingProportion;
this.fixedTree = source.fixedTree;
}
protected void initModelParaAndOpers() {
createParameterJeffreysPrior("constant.popSize", "coalescent population size parameter",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY);
createParameterJeffreysPrior("exponential.popSize", "coalescent population size parameter",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY);
createParameterLaplacePrior("exponential.growthRate", "coalescent growth rate parameter",
PriorScaleType.GROWTH_RATE_SCALE, 0.0, 0.001, 1.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
createParameterGammaPrior("exponential.doublingTime", "coalescent doubling time parameter",
PriorScaleType.NONE, 100.0, 0.001, 1000, 0.0, Double.POSITIVE_INFINITY, true);
createParameterJeffreysPrior("logistic.popSize", "coalescent population size parameter",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY);
createParameterLaplacePrior("logistic.growthRate", "coalescent logistic growth rate parameter",
PriorScaleType.GROWTH_RATE_SCALE, 0.0, 0.001, 1.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
createParameterGammaPrior("logistic.doublingTime", "coalescent doubling time parameter",
PriorScaleType.NONE, 100.0, 0.001, 1000, 0.0, Double.POSITIVE_INFINITY, true);
createParameterGammaPrior("logistic.t50", "logistic shape parameter",
PriorScaleType.NONE, 1.0, 0.001, 1000, 0.0, Double.POSITIVE_INFINITY, true);
createParameterJeffreysPrior("expansion.popSize", "coalescent population size parameter",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.POSITIVE_INFINITY);
createParameterLaplacePrior("expansion.growthRate", "coalescent expansion growth rate parameter",
PriorScaleType.GROWTH_RATE_SCALE, 0.0, 0.001, 1.0, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
createParameterGammaPrior("expansion.doublingTime", "coalescent doubling time parameter",
PriorScaleType.NONE, 100.0, 0.001, 1000, 0.0, Double.POSITIVE_INFINITY, true);
createParameterUniformPrior("expansion.ancestralProportion", "ancestral population proportion",
PriorScaleType.NONE, 0.1, 0.0, 1.0, 0.0, 1.0);
createParameterUniformPrior("skyline.popSize", "Bayesian Skyline population sizes",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY);
createParameter("skyline.groupSize", "Bayesian Skyline group sizes");
// skyride.logPopSize is log unit unlike other popSize
createParameterUniformPrior("skyride.logPopSize", "GMRF Bayesian skyride population sizes (log unit)",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.MAX_VALUE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
createParameter("skyride.groupSize", "GMRF Bayesian skyride group sizes (for backward compatibility)");
createParameterGammaPrior("skyride.precision", "GMRF Bayesian skyride precision",
PriorScaleType.NONE, 1.0, 0.001, 1000, 0.0, Double.POSITIVE_INFINITY, true);
createParameterUniformPrior("demographic.popSize", "Extended Bayesian Skyline population sizes",
PriorScaleType.TIME_SCALE, 1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY);
createParameter("demographic.indicators", "Extended Bayesian Skyline population switch", 0.0);
createParameterJeffreysPrior("demographic.populationMean", "Extended Bayesian Skyline population prior mean",
PriorScaleType.TIME_SCALE, 1, 0, Double.POSITIVE_INFINITY);
createDiscreteStatistic("demographic.populationSizeChanges", "Average number of population change points"); // POISSON_PRIOR
createParameterUniformPrior("yule.birthRate", "Yule speciation process birth rate",
PriorScaleType.BIRTH_RATE_SCALE, 1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY);
createParameterUniformPrior(BirthDeathModelParser.MEAN_GROWTH_RATE_PARAM_NAME, "Birth-Death speciation process rate",
PriorScaleType.BIRTH_RATE_SCALE, 0.01, 0.0, 100000.0, 0.0, Double.POSITIVE_INFINITY);
createParameterUniformPrior(BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME, "Birth-Death speciation process relative death rate",
PriorScaleType.NONE, 0.5, 0.0, 1.0, 0.0, Double.POSITIVE_INFINITY);
createParameterBetaDistributionPrior(BirthDeathModelParser.BIRTH_DEATH + "." + BirthDeathModelParser.SAMPLE_PROB,
"Birth-Death the proportion of taxa sampled from birth-death tree",
PriorScaleType.NONE, 0.01, 1.0, 1.0, 0.0, 0.0, Double.POSITIVE_INFINITY);
createParameterUniformPrior(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.LAMBDA,
"Birth-Death speciation process rate", PriorScaleType.BIRTH_RATE_SCALE,
0.01, 0.0, 100000.0, 0.0, Double.POSITIVE_INFINITY);
createParameterUniformPrior(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.RELATIVE_MU,
"Birth-Death relative death rate", PriorScaleType.NONE,
0.5, 0.0, 1.0, 0.0, Double.POSITIVE_INFINITY);
createParameterBetaDistributionPrior(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.SAMPLE_PROBABILITY,
"Birth-Death the proportion of taxa sampled from birth death tree", PriorScaleType.NONE,
0.01, 1.0, 1.0, 0.0, 0.0, Double.POSITIVE_INFINITY);
createParameterUniformPrior(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.PSI,
"Birth-Death rate of sampling taxa through time", PriorScaleType.NONE,
0.05, 0.0, 100.0, 0.0, Double.POSITIVE_INFINITY);
createParameterUniformPrior(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.ORIGIN,
"Birth-Death the time of the lineage originated (must > root height)", PriorScaleType.ORIGIN_SCALE,
1.0, 0.0, Double.MAX_VALUE, 0.0, Double.POSITIVE_INFINITY);
createParameterUniformPrior(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.SAMPLED_REMAIN_INFECTIOUS,
"Birth-Death the probabilty that a sampled individual continues being infectious after sample event", PriorScaleType.NONE,
0.01, 0.0, 1.0, 0.0, 1.0); // 0 <= r <= 1
createParameterUniformPrior(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.FINAL_TIME_INTERVAL,
"Birth-Death the time in the past when the process starts with the first individual", PriorScaleType.NONE,
80.0, 0.0, 1000.0, 0.0, Double.POSITIVE_INFINITY);
createScaleOperator("constant.popSize", demoTuning, demoWeights);
createScaleOperator("exponential.popSize", demoTuning, demoWeights);
createOperator("exponential.growthRate", OperatorType.RANDOM_WALK, 1.0, demoWeights);
createScaleOperator("exponential.doublingTime", demoTuning, demoWeights);
createScaleOperator("logistic.popSize", demoTuning, demoWeights);
createOperator("logistic.growthRate", OperatorType.RANDOM_WALK, 1.0, demoWeights);
// createScaleOperator("logistic.growthRate", demoTuning, demoWeights);
createScaleOperator("logistic.doublingTime", demoTuning, demoWeights);
createScaleOperator("logistic.t50", demoTuning, demoWeights);
createScaleOperator("expansion.popSize", demoTuning, demoWeights);
createOperator("expansion.growthRate", OperatorType.RANDOM_WALK, 1.0, demoWeights);
// createScaleOperator("expansion.growthRate", demoTuning, demoWeights);
createScaleOperator("expansion.doublingTime", demoTuning, demoWeights);
createScaleOperator("expansion.ancestralProportion", demoTuning, demoWeights);
createScaleOperator("skyline.popSize", demoTuning, demoWeights * 5);
createOperator("skyline.groupSize", OperatorType.INTEGER_DELTA_EXCHANGE, 1.0, demoWeights * 2);
createOperator("demographic.populationMean", OperatorType.SCALE, 0.9, demoWeights);
createOperator("demographic.indicators", OperatorType.BITFLIP, 1, 2 * treeWeights);
// hack pass distribution in name
createOperatorUsing2Parameters("demographic.popSize", "demographic.populationMeanDist", "", "demographic.popSize",
"demographic.indicators", OperatorType.SAMPLE_NONACTIVE, 1, 5 * demoWeights);
createOperatorUsing2Parameters("demographic.scaleActive", "demographic.scaleActive", "", "demographic.popSize",
"demographic.indicators", OperatorType.SCALE_WITH_INDICATORS, 0.5, 2 * demoWeights);
createOperatorUsing2Parameters("gmrfGibbsOperator", "gmrfGibbsOperator", "Gibbs sampler for GMRF", "skyride.logPopSize",
"skyride.precision", OperatorType.GMRF_GIBBS_OPERATOR, 2, 2);
createScaleOperator("yule.birthRate", demoTuning, demoWeights);
createScaleOperator(BirthDeathModelParser.MEAN_GROWTH_RATE_PARAM_NAME, demoTuning, demoWeights);
createScaleOperator(BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME, demoTuning, demoWeights);
createScaleOperator(BirthDeathModelParser.BIRTH_DEATH + "." + BirthDeathModelParser.SAMPLE_PROB, demoTuning, demoWeights);
createScaleOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.LAMBDA, demoTuning, 1);
createScaleOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.RELATIVE_MU, demoTuning, 1);
createScaleOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.SAMPLE_PROBABILITY, demoTuning, 1);
createScaleOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.PSI, demoTuning, 1); // todo random worl op ?
createScaleOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.ORIGIN, demoTuning, 1);
createScaleOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.SAMPLED_REMAIN_INFECTIOUS, demoTuning, 1);
createScaleOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.FINAL_TIME_INTERVAL, demoTuning, 1);
// createOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
// + BirthDeathSerialSamplingModelParser.SAMPLED_REMAIN_INFECTIOUS,
// OperatorType.RANDOM_WALK, 1.0, demoWeights);
}
/**
* return a list of parameters that are required
*
* @param params the parameter list
*/
public void selectParameters(List<Parameter> params) {
setAvgRootAndRate();
if (nodeHeightPrior == TreePriorType.CONSTANT) {
params.add(getParameter("constant.popSize"));
} else if (nodeHeightPrior == TreePriorType.EXPONENTIAL) {
params.add(getParameter("exponential.popSize"));
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
params.add(getParameter("exponential.growthRate"));
} else {
params.add(getParameter("exponential.doublingTime"));
}
} else if (nodeHeightPrior == TreePriorType.LOGISTIC) {
params.add(getParameter("logistic.popSize"));
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
params.add(getParameter("logistic.growthRate"));
} else {
params.add(getParameter("logistic.doublingTime"));
}
params.add(getParameter("logistic.t50"));
} else if (nodeHeightPrior == TreePriorType.EXPANSION) {
params.add(getParameter("expansion.popSize"));
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
params.add(getParameter("expansion.growthRate"));
} else {
params.add(getParameter("expansion.doublingTime"));
}
params.add(getParameter("expansion.ancestralProportion"));
} else if (nodeHeightPrior == TreePriorType.SKYLINE) {
params.add(getParameter("skyline.popSize"));
} else if (nodeHeightPrior == TreePriorType.EXTENDED_SKYLINE) {
params.add(getParameter("demographic.populationSizeChanges"));
params.add(getParameter("demographic.populationMean"));
} else if (nodeHeightPrior == TreePriorType.GMRF_SKYRIDE) {
// params.add(getParameter("skyride.popSize")); // force user to use GMRF, not allowed to change
params.add(getParameter("skyride.precision"));
} else if (nodeHeightPrior == TreePriorType.YULE) {
params.add(getParameter("yule.birthRate"));
} else if (nodeHeightPrior == TreePriorType.BIRTH_DEATH || nodeHeightPrior == TreePriorType.BIRTH_DEATH_INCOM_SAMP) {
params.add(getParameter(BirthDeathModelParser.MEAN_GROWTH_RATE_PARAM_NAME));
params.add(getParameter(BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME));
if (nodeHeightPrior == TreePriorType.BIRTH_DEATH_INCOM_SAMP)
params.add(getParameter(BirthDeathModelParser.BIRTH_DEATH + "." + BirthDeathModelParser.SAMPLE_PROB));
} else if (nodeHeightPrior == TreePriorType.BIRTH_DEATH_SERI_SAMP || nodeHeightPrior == TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM) {
params.add(getParameter(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.LAMBDA));
params.add(getParameter(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.RELATIVE_MU));
params.add(getParameter(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.SAMPLE_PROBABILITY));
Parameter psi = getParameter(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.PSI);
if (options.maximumTipHeight > 0) psi.initial = MathUtils.round(1/options.maximumTipHeight, 4);
params.add(psi);
params.add(getParameter(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.ORIGIN));
if (nodeHeightPrior == TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM) {
params.add(getParameter(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.SAMPLED_REMAIN_INFECTIOUS));
params.add(getParameter(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.FINAL_TIME_INTERVAL));
}
}
}
/**
* return a list of operators that are required
*
* @param ops the operator list
*/
public void selectOperators(List<Operator> ops) {
if (nodeHeightPrior == TreePriorType.CONSTANT) {
ops.add(getOperator("constant.popSize"));
} else if (nodeHeightPrior == TreePriorType.EXPONENTIAL) {
ops.add(getOperator("exponential.popSize"));
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
ops.add(getOperator("exponential.growthRate"));
} else {
ops.add(getOperator("exponential.doublingTime"));
}
} else if (nodeHeightPrior == TreePriorType.LOGISTIC) {
ops.add(getOperator("logistic.popSize"));
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
ops.add(getOperator("logistic.growthRate"));
} else {
ops.add(getOperator("logistic.doublingTime"));
}
ops.add(getOperator("logistic.t50"));
} else if (nodeHeightPrior == TreePriorType.EXPANSION) {
ops.add(getOperator("expansion.popSize"));
if (parameterization == TreePriorParameterizationType.GROWTH_RATE) {
ops.add(getOperator("expansion.growthRate"));
} else {
ops.add(getOperator("expansion.doublingTime"));
}
ops.add(getOperator("expansion.ancestralProportion"));
} else if (nodeHeightPrior == TreePriorType.SKYLINE) {
ops.add(getOperator("skyline.popSize"));
ops.add(getOperator("skyline.groupSize"));
} else if (nodeHeightPrior == TreePriorType.GMRF_SKYRIDE) {
ops.add(getOperator("gmrfGibbsOperator"));
} else if (nodeHeightPrior == TreePriorType.EXTENDED_SKYLINE) {
ops.add(getOperator("demographic.populationMean"));
ops.add(getOperator("demographic.popSize"));
ops.add(getOperator("demographic.indicators"));
ops.add(getOperator("demographic.scaleActive"));
} else if (nodeHeightPrior == TreePriorType.YULE) {
ops.add(getOperator("yule.birthRate"));
} else if (nodeHeightPrior == TreePriorType.BIRTH_DEATH || nodeHeightPrior == TreePriorType.BIRTH_DEATH_INCOM_SAMP) {
ops.add(getOperator(BirthDeathModelParser.MEAN_GROWTH_RATE_PARAM_NAME));
ops.add(getOperator(BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME));
if (nodeHeightPrior == TreePriorType.BIRTH_DEATH_INCOM_SAMP)
ops.add(getOperator(BirthDeathModelParser.BIRTH_DEATH + "." + BirthDeathModelParser.SAMPLE_PROB));
} else if (nodeHeightPrior == TreePriorType.BIRTH_DEATH_SERI_SAMP || nodeHeightPrior == TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM) {
ops.add(getOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.LAMBDA));
ops.add(getOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.RELATIVE_MU));
ops.add(getOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.SAMPLE_PROBABILITY));
ops.add(getOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.PSI));
ops.add(getOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.ORIGIN));
if (nodeHeightPrior == TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM) {
ops.add(getOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.SAMPLED_REMAIN_INFECTIOUS));
ops.add(getOperator(BirthDeathSerialSamplingModelParser.BDSS + "."
+ BirthDeathSerialSamplingModelParser.FINAL_TIME_INTERVAL));
}
}
}
public String getPrefix() {
String prefix = "";
if (options.getPartitionTreePriors().size() > 1) {//|| options.isSpeciesAnalysis()
// There is more than one active partition model, or doing species analysis
prefix += getName() + ".";
}
return prefix;
}
public PartitionTreeModel getTreeModel() {
return treeModel;
}
// public void setTreeModel(PartitionTreeModel treeModel) {
// this.treeModel = treeModel;
public TreePriorType getNodeHeightPrior() {
return nodeHeightPrior;
}
public void setNodeHeightPrior(TreePriorType nodeHeightPrior) {
this.nodeHeightPrior = nodeHeightPrior;
}
public TreePriorParameterizationType getParameterization() {
return parameterization;
}
public void setParameterization(TreePriorParameterizationType parameterization) {
this.parameterization = parameterization;
}
public int getSkylineGroupCount() {
return skylineGroupCount;
}
public void setSkylineGroupCount(int skylineGroupCount) {
this.skylineGroupCount = skylineGroupCount;
}
public TreePriorParameterizationType getSkylineModel() {
return skylineModel;
}
public void setSkylineModel(TreePriorParameterizationType skylineModel) {
this.skylineModel = skylineModel;
}
public TreePriorParameterizationType getSkyrideSmoothing() {
return skyrideSmoothing;
}
public void setSkyrideSmoothing(TreePriorParameterizationType skyrideSmoothing) {
this.skyrideSmoothing = skyrideSmoothing;
}
public double getBirthDeathSamplingProportion() {
return birthDeathSamplingProportion;
}
public void setBirthDeathSamplingProportion(double birthDeathSamplingProportion) {
this.birthDeathSamplingProportion = birthDeathSamplingProportion;
}
public boolean isFixedTree() {
return fixedTree;
}
public void setFixedTree(boolean fixedTree) {
this.fixedTree = fixedTree;
}
public void setExtendedSkylineModel(VariableDemographicModel.Type extendedSkylineModel) {
this.extendedSkylineModel = extendedSkylineModel;
}
public VariableDemographicModel.Type getExtendedSkylineModel() {
return extendedSkylineModel;
}
public PopulationSizeModelType getPopulationSizeModel() {
return populationSizeModel;
}
public void setPopulationSizeModel(PopulationSizeModelType populationSizeModel) {
this.populationSizeModel = populationSizeModel;
}
public BeautiOptions getOptions() {
return options;
}
} |
package de.kleppmann.maniation.maths;
import java.text.DecimalFormat;
import java.util.List;
public class SparseMatrix implements Matrix {
private int rows, columns;
private Slice[] slices;
private SparseMatrix transpose, inverse;
private SparseMatrix(boolean nonsense, int rows, int columns, Slice[] slices) {
// Create transpose
this.rows = columns;
this.columns = rows;
this.slices = new Slice[slices.length];
for (int i=0; i<slices.length; i++) {
this.slices[i] = new SliceTranspose(slices[i]);
}
}
private SparseMatrix(int nonsense, int rows, int columns, Slice[] slices) {
// Create inverse
this.rows = rows;
this.columns = columns;
this.slices = new Slice[slices.length];
for (int i=0; i<slices.length; i++) {
if (slices[i].getStartColumn() != slices[i].getStartRow())
throw new UnsupportedOperationException();
this.slices[i] = new SliceInverse(slices[i]);
}
}
public SparseMatrix(int rows, int columns, Slice[] slices) {
this.rows = rows;
this.columns = columns;
List<Slice> sList = new java.util.ArrayList<Slice>();
for (Slice s : slices) {
Matrix m = s.getMatrix();
if (m instanceof SparseMatrix) {
for (Slice s2 : ((SparseMatrix) m).slices)
sList.add(new SliceOffset(s2, s.getStartRow(), s.getStartColumn()));
} else sList.add(s);
}
this.slices = sList.toArray(new Slice[sList.size()]);
this.transpose = new SparseMatrix(true, rows, columns, this.slices);
this.transpose.transpose = this;
try {
this.inverse = new SparseMatrix(1, rows, columns, this.slices);
this.inverse.inverse = this;
} catch (UnsupportedOperationException e) {
this.inverse = null;
}
}
public int getRows() {
return this.rows;
}
public int getColumns() {
return this.columns;
}
public double getComponent(int row, int column) {
for (Slice s : slices) {
if ((row >= s.getStartRow()) && (row - s.getStartRow() < s.getMatrix().getRows()) &&
(column >= s.getStartColumn()) &&
(column - s.getStartColumn() < s.getMatrix().getColumns()))
return s.getMatrix().getComponent(row - s.getStartRow(), column - s.getStartColumn());
}
return 0.0;
}
public SparseMatrix transpose() {
return this.transpose;
}
public SparseMatrix inverse() {
if (this.inverse != null) return this.inverse;
throw new UnsupportedOperationException();
}
public SparseMatrix mult(double scalar) {
Slice[] scaled = new Slice[slices.length];
for (int i=0; i<slices.length; i++) scaled[i] = new SliceScaled(slices[i], scalar);
return new SparseMatrix(rows, columns, scaled);
}
public Matrix mult(Matrix other) {
if (this.getColumns() != other.getRows()) throw new IllegalArgumentException();
double[][] t = new double[getRows()][other.getColumns()];
for (int i=0; i<rows; i++)
for (int j=0; j<other.getColumns(); j++) {
t[i][j] = 0.0;
for (int k=0; k<columns; k++)
t[i][j] += getComponent(i,k)*other.getComponent(k,j);
}
return new MatrixImpl(t);
}
public Vector mult(Vector vec) {
if (this.getColumns() != vec.getDimension()) throw new IllegalArgumentException();
double[] result = new double[this.getRows()];
for (int i=0; i<result.length; i++) result[i] = 0.0;
for (Slice slice : slices) {
double[] subvec = new double[slice.getMatrix().getColumns()];
int offs = slice.getStartColumn();
for (int i=0; i<subvec.length; i++) subvec[i] = vec.getComponent(offs+i);
Vector prod = slice.getMatrix().mult(new VectorImpl(subvec));
offs = slice.getStartRow();
for (int i=prod.getDimension()-1; i>=0; i
result[i+offs] += prod.getComponent(i);
}
return new VectorImpl(result);
}
public Matrix add(Matrix other) {
if ((getRows() != other.getRows()) || (getColumns() != other.getColumns()))
throw new IllegalArgumentException();
double[][] t = new double[getRows()][getColumns()];
for (int i=0; i<rows; i++)
for (int j=0; j<columns; j++)
t[i][j] = getComponent(i,j) + other.getComponent(i,j);
return new MatrixImpl(t);
}
public Matrix subtract(Matrix other) {
if ((getRows() != other.getRows()) || (getColumns() != other.getColumns()))
throw new IllegalArgumentException();
double[][] t = new double[getRows()][getColumns()];
for (int i=0; i<rows; i++)
for (int j=0; j<columns; j++)
t[i][j] = getComponent(i,j) - other.getComponent(i,j);
return new MatrixImpl(t);
}
@Override
public String toString() {
DecimalFormat format = new DecimalFormat("
String result = "[";
for (int i=0; i<getRows(); i++)
for (int j=0; j<getColumns(); j++) {
result += format.format(getComponent(i,j));
if (j < getColumns() - 1) result += ", "; else
if (i < getRows() - 1) result += "; "; else result += "]";
}
return result;
}
public interface Slice {
int getStartRow();
int getStartColumn();
Matrix getMatrix();
}
public static class SliceImpl implements Slice {
private Matrix m;
private int startRow, startColumn;
public SliceImpl(Matrix m, int startRow, int startColumn) {
this.m = m; this.startRow = startRow; this.startColumn = startColumn;
}
public int getStartRow() {
return startRow;
}
public int getStartColumn() {
return startColumn;
}
public Matrix getMatrix() {
return m;
}
}
private static class SliceTranspose implements Slice {
private Slice origin;
public SliceTranspose(Slice origin) {
this.origin = origin;
}
public Matrix getMatrix() {
return origin.getMatrix().transpose();
}
public int getStartColumn() {
return origin.getStartRow();
}
public int getStartRow() {
return origin.getStartColumn();
}
}
private static class SliceInverse implements Slice {
private Slice origin;
public SliceInverse(Slice origin) {
if (origin.getStartRow() != origin.getStartColumn())
throw new UnsupportedOperationException();
this.origin = origin;
}
public Matrix getMatrix() {
return origin.getMatrix().inverse();
}
public int getStartColumn() {
return origin.getStartColumn();
}
public int getStartRow() {
return origin.getStartRow();
}
}
private static class SliceScaled implements Slice {
private Matrix scaled;
private int row, col;
public SliceScaled(Slice origin, double factor) {
this.scaled = origin.getMatrix().mult(factor);
this.row = origin.getStartRow();
this.col = origin.getStartColumn();
}
public Matrix getMatrix() {
return scaled;
}
public int getStartColumn() {
return col;
}
public int getStartRow() {
return row;
}
}
private static class SliceOffset implements Slice {
private Slice original;
private int rowOffset, colOffset;
public SliceOffset(Slice original, int rowOffset, int colOffset) {
this.original = original;
this.rowOffset = rowOffset; this.colOffset = colOffset;
}
public Matrix getMatrix() {
return original.getMatrix();
}
public int getStartColumn() {
return original.getStartColumn()+colOffset;
}
public int getStartRow() {
return original.getStartRow()+rowOffset;
}
}
} |
package dr.evomodel.arg.likelihood;
import dr.evolution.alignment.PatternList;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.util.TaxonList;
import dr.evomodel.arg.ARGModel;
import dr.evomodel.arg.ARGTree;
import dr.evomodel.arg.operators.ARGPartitioningOperator;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.DefaultBranchRateModel;
import dr.evomodel.sitemodel.SiteModel;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.treelikelihood.*;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.xml.*;
import java.util.logging.Logger;
import java.util.*;
/**
* ARGLikelihood - implements a Likelihood Function for sequences on an ancestral recombination graph.
*
* @author Marc Suchard
* @version $Id: ARGLikelihood.java,v 1.3 2006/10/23 04:13:41 msuchard Exp $
*/
public class ARGLikelihood extends AbstractARGLikelihood {
public static final String ARG_LIKELIHOOD = "argTreeLikelihood";
public static final String USE_AMBIGUITIES = "useAmbiguities";
public static final String STORE_PARTIALS = "storePartials";
public static final String USE_SCALING = "useScaling";
/**
* Constructor.
*/
public ARGLikelihood(PatternList patternList,
ARGModel treeModel,
SiteModel siteModel,
BranchRateModel branchRateModel,
boolean useAmbiguities,
boolean storePartials,
boolean useScaling) {
super(ARG_LIKELIHOOD, patternList, treeModel);
partition = treeModel.addLikelihoodCalculator(this);
this.storePartials = storePartials;
this.useAmbiguities = useAmbiguities;
try {
this.siteModel = siteModel;
addModel(siteModel);
this.frequencyModel = siteModel.getFrequencyModel();
addModel(frequencyModel);
integrateAcrossCategories = siteModel.integrateAcrossCategories();
this.categoryCount = siteModel.getCategoryCount();
if (integrateAcrossCategories) {
if (patternList.getDataType() instanceof dr.evolution.datatype.Nucleotides) {
if (NativeNucleotideLikelihoodCore.isAvailable()) {
Logger.getLogger("dr.evomodel").info("TreeLikelihood using native nucleotide likelihood core");
likelihoodCore = new NativeNucleotideLikelihoodCore();
} else {
Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java nucleotide likelihood core");
likelihoodCore = new NucleotideLikelihoodCore();
}
} else if (patternList.getDataType() instanceof dr.evolution.datatype.AminoAcids) {
if (NativeAminoAcidLikelihoodCore.isAvailable()) {
Logger.getLogger("dr.evomodel").info("TreeLikelihood using native amino acid likelihood core");
likelihoodCore = new NativeAminoAcidLikelihoodCore();
} else {
Logger.getLogger("dr.evomodel").info("TreeLikelihood using java likelihood core");
likelihoodCore = new AminoAcidLikelihoodCore();
}
} else if (patternList.getDataType() instanceof dr.evolution.datatype.Codons) {
Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java codon likelihood core");
// likelihoodCore = new CodonLikelihoodCore(patternList.getStateCount());
this.useAmbiguities = true;
throw new RuntimeException("Still need to merge codon likelihood core");
} else {
if (patternList.getDataType() instanceof dr.evolution.datatype.HiddenNucleotides &&
NativeCovarionLikelihoodCore.isAvailable()) {
Logger.getLogger("dr.evomodel").info("TreeLikelihood using native covarion likelihood core");
likelihoodCore = new NativeCovarionLikelihoodCore();
} else {
Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java general likelihood core");
likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
}
}
} else {
Logger.getLogger("dr.evomodel").info("TreeLikelihood using Java general likelihood core");
likelihoodCore = new GeneralLikelihoodCore(patternList.getStateCount());
}
Logger.getLogger("dr.evomodel").info(" " + (useAmbiguities ? "Using" : "Ignoring") + " ambiguities in tree likelihood.");
Logger.getLogger("dr.evomodel").info(" Partial likelihood scaling " + (useScaling ? "on." : "off."));
if (branchRateModel != null) {
this.branchRateModel = branchRateModel;
Logger.getLogger("dr.evomodel").info("Branch rate model used: " + branchRateModel.getModelName());
} else {
this.branchRateModel = new DefaultBranchRateModel();
}
addModel(this.branchRateModel);
probabilities = new double[stateCount * stateCount];
// likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories, useScaling);
likelihoodCore.initialize(nodeCount, patternCount, categoryCount, integrateAcrossCategories);
int extNodeCount = treeModel.getExternalNodeCount();
int intNodeCount = treeModel.getInternalNodeCount();
for (int i = 0; i < extNodeCount; i++) {
// Find the id of tip i in the patternList
String id = treeModel.getTaxonId(i);
int index = patternList.getTaxonIndex(id);
// System.err.println("id = "+id+" index = "+index);
if (index == -1) {
throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() +
", is not found in patternList, " + patternList.getId());
}
if (useAmbiguities) {
setPartials(likelihoodCore, patternList, categoryCount, index, i);
} else {
setStates(likelihoodCore, patternList, index, i);
}
}
// System.exit(-1);
for (int i = 0; i < intNodeCount; i++) {
likelihoodCore.createNodePartials(extNodeCount + i);
}
} catch (TaxonList.MissingTaxonException mte) {
throw new RuntimeException(mte.toString());
}
}
// ModelListener IMPLEMENTATION
private static final boolean NO_CACHING = false;
/**
* Handles model changed events from the submodels.
*/
protected void handleModelChangedEvent(Model model, Object object, int index) {
if (NO_CACHING) {
reconstructTree = true;
updateAllNodes();
}
if (model == treeModel) {
if (object instanceof ARGModel.TreeChangedEvent) {
ARGModel.TreeChangedEvent event = (ARGModel.TreeChangedEvent) object;
if (event.isSizeChanged() ) {
updateAllNodes(); // TODO Update only affected portion of tree
reconstructTree = true;
} else if (event.isNodeChanged()) {
// If a node event occurs the node and its two child nodes
// are flagged for updating (this will result in everything
// above being updated as well. Node events occur when a node
// is added to a branch, removed from a branch or its height or
// rate changes.
NodeRef treeNode = mapARGNodesToTreeNodes.get(event.getNode());
if ( treeNode != null ) {
if (event.isHeightChanged() || event.isRateChanged()) {
updateNodeAndChildren(treeNode);
} else {
reconstructTree = true;
// updateNodeAndChildren(treeNode); // TODO This doesn't work with sizeChange; why???
updateAllNodes();
}
}
} else if (event.isTreeChanged()) {
// Full tree events result in a complete updating of the tree likelihood
// These include adding and removing nodes
// TODO ARG rearrangements still call this; they should not
reconstructTree = true;
updateAllNodes();
} else {
// Other event types are ignored (probably trait changes).
throw new RuntimeException("Another tree event has occured (possibly a trait change).");
}
} else if (object instanceof ARGPartitioningOperator.PartitionChangedEvent) {
final boolean[] updatePartition = ((ARGPartitioningOperator.PartitionChangedEvent) object).getUpdatedPartitions();
if (updatePartition[partition]) {
reconstructTree = true;
updateAllNodes(); // TODO Probably does not affect entire tree; fix
}
} else if (object instanceof Parameter) {
// ignore, most of these are handled in isNodeChanged()
} else
throw new RuntimeException("Unexpected ARGModel update "+object.getClass());
} else if (model == branchRateModel) {
// TODO Only update affected branches
updateAllNodes();
} else if (model == frequencyModel) {
updateAllNodes();
} else if (model instanceof SiteModel) {
updateAllNodes();
} else {
throw new RuntimeException("Unknown componentChangedEvent");
}
super.handleModelChangedEvent(model, object, index);
}
// Model IMPLEMENTATION
/**
* Stores the additional state other than model components
*/
protected void storeState() {
if (storePartials) {
likelihoodCore.storeState();
}
super.storeState();
}
/**
* Restore the additional stored state
*/
protected void restoreState() {
if (storePartials) {
likelihoodCore.restoreState();
} else {
updateAllNodes();
}
reconstructTree = true; // currently the tree is not cached, because the ARG that generates it is cached
super.restoreState();
}
private int getUnusedInt(Map<NodeRef,Integer> inMap) {
Collection<Integer> intSet = inMap.values();
int i = tree.getExternalNodeCount();
while( intSet.contains(i) )
i++;
return i;
}
private Set<NodeRef> unsetNodes = null;
private void reconstructTree() {
oldTree = tree;
oldMapARGNodesToInts = mapARGNodesToInts;
tree = new ARGTree(treeModel, partition);
reconstructTree = false;
mapARGNodesToInts = new HashMap<NodeRef,Integer>(tree.getInternalNodeCount());
mapARGNodesToTreeNodes = tree.getMapping();
if (oldTree == null) {
// First initialization
for(int i=0; i<tree.getInternalNodeCount(); i++) {
NodeRef node = tree.getInternalNode(i);
mapARGNodesToInts.put(treeModel.getMirrorNode(node),node.getNumber());
}
} else {
// Need to renumber
if (unsetNodes == null)
unsetNodes = new HashSet<NodeRef>();
else
unsetNodes.clear();
// Copy over numbers for nodes that still exist in tree
for (int i = 0; i < tree.getInternalNodeCount(); i++) {
NodeRef newNode = tree.getInternalNode(i);
NodeRef argNode = treeModel.getMirrorNode(newNode);
if (oldMapARGNodesToInts.containsKey(argNode)) { // was in old tree
int oldNumber = oldMapARGNodesToInts.get(argNode);
treeModel.setNodeNumber(newNode,oldNumber);
mapARGNodesToInts.put(argNode,oldNumber);
} else // was not in old tree
unsetNodes.add(newNode);
}
// Set unused numbers for nodes that are new and mark for update
for (NodeRef node : unsetNodes) {
int newNumber = getUnusedInt(mapARGNodesToInts);
treeModel.setNodeNumber(node,newNumber);
mapARGNodesToInts.put(node,newNumber);
updateNode[newNumber] = true;
}
}
}
// Likelihood IMPLEMENTATION
/**
* Calculate the log likelihood of the current state.
*
* @return the log likelihood.
*/
protected double calculateLogLikelihood() {
if (reconstructTree) {
reconstructTree();
}
NodeRef root = tree.getRoot();
if (rootPartials == null) {
rootPartials = new double[patternCount * stateCount];
}
if (patternLogLikelihoods == null) {
patternLogLikelihoods = new double[patternCount];
}
if (!integrateAcrossCategories) {
if (siteCategories == null) {
siteCategories = new int[patternCount];
}
for (int i = 0; i < patternCount; i++) {
siteCategories[i] = siteModel.getCategoryOfSite(i);
}
}
try {
traverse(tree, root);
} catch (NegativeBranchLengthException e) {
System.err.println("Negative branch length found, trying to return 0 likelihood");
return Double.NEGATIVE_INFINITY;
}
/**
* Traverse the tree calculating partial likelihoods.
*
* @return whether the partials for this node were recalculated.
*/
private boolean traverse(Tree tree, NodeRef node) throws NegativeBranchLengthException {
boolean update = false;
int nodeNum = node.getNumber();
// System.err.println(nodeNum);
NodeRef parent = tree.getParent(node);
// First update the transition probability matrix(ices) for this branch
if (parent != null && updateNode[nodeNum]) {
double branchRate = branchRateModel.getBranchRate(tree, node);
// Get the operational time of the branch
double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node));
if (branchTime < 0.0) {
if (!DEBUG) {
throw new RuntimeException("Negative branch length: " + branchTime);
} else{
throw new NegativeBranchLengthException();
}
}
for (int i = 0; i < categoryCount; i++) {
double branchLength = siteModel.getRateForCategory(i) * branchTime;
siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probabilities);
likelihoodCore.setNodeMatrix(nodeNum, i, probabilities);
}
update = true;
}
// If the node is internal, update the partial likelihoods.
if (!tree.isExternal(node)) {
int nodeCount = tree.getChildCount(node);
if (nodeCount != 2)
throw new RuntimeException("binary trees only!");
// Traverse down the two child nodes
NodeRef child1 = tree.getChild(node, 0);
boolean update1 = traverse(tree, child1);
NodeRef child2 = tree.getChild(node, 1);
boolean update2 = traverse(tree, child2);
// If either child node was updated then update this node too
if (update1 || update2) {
int childNum1 = child1.getNumber();
int childNum2 = child2.getNumber();
if (integrateAcrossCategories) {
likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum);
} else {
likelihoodCore.calculatePartials(childNum1, childNum2, nodeNum,
siteCategories);
}
if (parent == null) {
// No parent this is the root of the tree -
// calculate the pattern likelihoods
double[] frequencies = frequencyModel.getFrequencies();
if (integrateAcrossCategories) {
// moved this call to here, because non-integrating siteModels don't need to support it - AD
double[] proportions = siteModel.getCategoryProportions();
likelihoodCore.integratePartials(nodeNum, proportions, rootPartials);
} else {
likelihoodCore.getPartials(nodeNum, rootPartials);
}
likelihoodCore.calculateLogLikelihoods(rootPartials, frequencies, patternLogLikelihoods);
}
update = true;
}
}
return update;
}
/**
* The XML parser
*/
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return ARG_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
boolean useAmbiguities = false;
boolean storePartials = true;
boolean useScaling = false;
if (xo.hasAttribute(USE_AMBIGUITIES)) {
useAmbiguities = xo.getBooleanAttribute(USE_AMBIGUITIES);
}
if (xo.hasAttribute(STORE_PARTIALS)) {
storePartials = xo.getBooleanAttribute(STORE_PARTIALS);
}
if (xo.hasAttribute(USE_SCALING)) {
useScaling = xo.getBooleanAttribute(USE_SCALING);
}
PatternList patternList = (PatternList) xo.getChild(PatternList.class);
ARGModel treeModel = (ARGModel) xo.getChild(ARGModel.class);
SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class);
BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class);
return new ARGLikelihood(patternList, treeModel, siteModel, branchRateModel, useAmbiguities, storePartials, useScaling);
}
/**
* XML Serializer for parallelization
*
*/
// public Element toXML() {
// Element likelihoodElement
// INSTANCE VARIABLES
/**
* the frequency model for these sites
*/
protected FrequencyModel frequencyModel = null;
/**
* the site model for these sites
*/
protected SiteModel siteModel = null;
/**
* the branch rate model
*/
protected BranchRateModel branchRateModel = null;
private boolean storePartials = false;
private boolean integrateAcrossCategories = false;
/**
* the categories for each site
*/
protected int[] siteCategories = null;
/**
* the root partial likelihoods
*/
protected double[] rootPartials = null;
/**
* the pattern likelihoods
*/
protected double[] patternLogLikelihoods = null;
/**
* the number of rate categories
*/
protected int categoryCount;
/**
* an array used to store transition probabilities
*/
protected double[] probabilities;
/**
* the LikelihoodCore
*/
protected LikelihoodCore likelihoodCore;
private boolean useAmbiguities;
private boolean reconstructTree = true;
private ARGTree tree = null;
private ARGTree oldTree;
private Map<NodeRef,Integer> mapARGNodesToInts = null;
private Map<NodeRef,Integer> oldMapARGNodesToInts;
private Map<NodeRef,NodeRef> mapARGNodesToTreeNodes = null;
private static final boolean DEBUG = true;
} |
// CreateConfiguration.java --
// CreateConfiguration.java is part of ElectricCommander.
package ecplugins.esx.client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.xml.client.Node;
import com.electriccloud.commander.gwt.client.FormBase;
import com.electriccloud.commander.gwt.client.legacyrequests.CommanderRequestCallback;
import com.electriccloud.commander.gwt.client.legacyrequests.RunProcedureRequest;
import com.electriccloud.commander.gwt.client.requests.CgiRequestProxy;
import com.electriccloud.commander.gwt.client.requests.FormBuilderLoader;
import com.electriccloud.commander.gwt.client.responses.CommanderError;
import com.electriccloud.commander.gwt.client.ui.CredentialEditor;
import com.electriccloud.commander.gwt.client.ui.FormBuilder;
import com.electriccloud.commander.gwt.client.ui.FormTable;
import com.electriccloud.commander.gwt.client.ui.SimpleErrorBox;
import com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder;
import static com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder.createPageUrl;
import static com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder.createUrl;
import static com.electriccloud.commander.gwt.client.ComponentBaseFactory.getPluginName;
/**
* Create ESX Configuration.
*/
public class CreateConfiguration
extends FormBase
{
public CreateConfiguration()
{
super("New ESX Configuration", "ESX Configurations");
CommanderUrlBuilder urlBuilder = createPageUrl(getPluginName(),
"configurations");
setDefaultRedirectToUrl(urlBuilder.buildString());
}
@Override protected FormTable initializeFormTable()
{
FormBuilder fb = new FormBuilder();
return fb;
}
@Override protected void load()
{
FormBuilder fb = (FormBuilder) getFormTable();
setStatus("Loading...");
FormBuilderLoader loader = new FormBuilderLoader(fb, this);
loader.setCustomEditorPath("/plugins/EC-ESX"
+ "/project/ui_forms/ESXCreateConfigForm");
loader.load();
clearStatus();
}
@Override protected void submit()
{
setStatus("Saving...");
clearAllErrors();
FormBuilder fb = (FormBuilder) getFormTable();
if (!fb.validate()) {
clearStatus();
return;
}
// Build runProcedure request
RunProcedureRequest request = new RunProcedureRequest(
"/plugins/EC-ESX/project", "CreateConfiguration");
Map<String, String> params = fb.getValues();
Collection<String> credentialParams = fb.getCredentialIds();
for (String paramName : params.keySet()) {
if (credentialParams.contains(paramName)) {
CredentialEditor credential = fb.getCredential(paramName);
request.addCredentialParameter(paramName, credential.getUsername(), credential.getPassword());
}
else {
request.addActualParameter(paramName, params.get(paramName));
}
}
// Launch the procedure
registerCallback(request.getRequestId(),
new CommanderRequestCallback() {
@Override public void handleError(Node responseNode)
{
addErrorMessage(new CommanderError(responseNode));
}
@Override public void handleResponse(Node responseNode)
{
if (getLog().isDebugEnabled()) {
getLog().debug(
"Commander runProcedure request returned: "
+ responseNode);
}
waitForJob(getNodeValueByName(responseNode, "jobId"));
}
});
if (getLog().isDebugEnabled()) {
getLog().debug("Issuing Commander request: " + request);
}
doRequest(request);
}
private void waitForJob(final String jobId)
{
CgiRequestProxy cgiRequestProxy = new CgiRequestProxy(
getPluginName(), "esxMonitor.cgi");
Map<String, String> cgiParams = new HashMap<String, String>();
cgiParams.put("jobId", jobId);
// Pass debug flag to CGI, which will use it to determine whether to
// clean up a successful job
if ("1".equals(getGetParameter("debug"))) {
cgiParams.put("debug", "1");
}
try {
cgiRequestProxy.issueGetRequest(cgiParams, new RequestCallback() {
@Override public void onError(
Request request,
Throwable exception)
{
addErrorMessage("CGI request failed: ", exception);
}
@Override public void onResponseReceived(
Request request,
Response response)
{
String responseString = response.getText();
if (getLog().isDebugEnabled()) {
getLog().debug(
"CGI response received: " + responseString);
}
if (responseString.startsWith("Success")) {
// We're done!
cancel();
}
else {
SimpleErrorBox error = new SimpleErrorBox(
"Error occurred during configuration creation: "
+ responseString);
CommanderUrlBuilder urlBuilder = createUrl(
"jobDetails.php")
.setParameter("jobId", jobId);
error.add(
new Anchor("(See job for details)",
urlBuilder.buildString()));
addErrorMessage(error);
}
}
});
}
catch (RequestException e) {
addErrorMessage("CGI request failed: ", e);
}
}
} |
package edu.iu.grid.oim.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import com.divrep.DivRepEvent;
import com.divrep.DivRepEventListener;
import com.divrep.common.DivRepButton;
import com.divrep.common.DivRepTextArea;
import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.db.ContactModel;
import edu.iu.grid.oim.model.db.GridAdminModel;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.db.record.GridAdminRecord;
import edu.iu.grid.oim.view.BootMenuView;
import edu.iu.grid.oim.view.BootPage;
import edu.iu.grid.oim.view.CertificateMenuView;
import edu.iu.grid.oim.view.IView;
import edu.iu.grid.oim.view.divrep.BootDialogForm;
import edu.iu.grid.oim.view.divrep.form.GridAdminRequestForm;
public class GridAdminServlet extends ServletBase {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(GridAdminServlet.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
UserContext context = new UserContext(request);
//construct view
BootMenuView menuview = new BootMenuView(context, "certificate");;
BootPage page = new BootPage(context, menuview, new Content(context), null);
page.render(response.getWriter());
}
class Content implements IView {
UserContext context;
public Content(UserContext context) {
this.context = context;
}
@Override
public void render(PrintWriter out) {
Authorization auth = context.getAuthorization();
ContactModel cmodel = new ContactModel(context);
GridAdminModel model = new GridAdminModel(context);
try {
LinkedHashMap<String, ArrayList<ContactRecord>> recs = model.getAll();
/*
Collections.sort(recs, new Comparator<GridAdminRecord> (){
public int compare(GridAdminRecord a, GridAdminRecord b) {
//TODO - correct algorithm is to split domain by ., then compare each token in reverse order
String ar = reverse(a.domain);
String br = reverse(b.domain);
return (ar.compareTo(br));
}
public String reverse(String in) {
int length = in.length();
StringBuilder reverse = new StringBuilder();
for(int i = length; i > 0; --i) {
char result = in.charAt(i-1);
reverse.append(result);
}
return reverse.toString();
}
});
*/
out.write("<div id=\"content\">");
out.write("<div class=\"row-fluid\">");
out.write("<div class=\"span3\">");
CertificateMenuView menu = new CertificateMenuView(context, "gridadmin");
menu.render(out);
out.write("</div>"); //span3
out.write("<div class=\"span9\">");
if(auth.allows("admin_gridadmin")) {
out.write("<a class=\"pull-right btn\" href=\"gridadminedit\"><i class=\"icon-plus\"></i> Add New Domain</a>");
} else if(auth.isUser()) {
final GridAdminRequestForm form = new GridAdminRequestForm(context);
form.render(out);
DivRepButton request = new DivRepButton(context.getPageRoot(), "Request for GridAdmin Enrollment");
request.addClass("btn");
request.addClass("pull-right");
request.render(out);
request.addEventListener(new DivRepEventListener() {
@Override
public void handleEvent(DivRepEvent e) {
form.show();
}});
}
out.write("<h2>GridAdmins</h2>");
if(auth.allows("admin_gridadmin")) {
out.write("<table class=\"table\">");
} else {
out.write("<table class=\"table nohover\">");
}
out.write("<thead><tr><th>Domain</th><th>GridAdmins</th><th></th></tr></thead>");
out.write("<tbody>");
for(String domain : recs.keySet()) {
out.write("<tr>");
out.write("<td>"+StringEscapeUtils.escapeHtml(domain)+"</td>");
out.write("<td><ul>");
for(ContactRecord ga : recs.get(domain)) {
out.write("<li>"+StringEscapeUtils.escapeHtml(ga.name)+"</li>");
}
out.write("</ul></td>");
out.write("<td>");
if(auth.allows("admin_gridadmin")) {
out.write("<a href=\"gridadminedit?domain="+domain+"\" class=\"btn btn-mini\">Edit</a>");
}
out.write("</td>");
out.write("</tr>");
}
out.write("</tbody>");
out.write("</table>");
out.write("</div>"); //span9
out.write("</div>"); //row-fluid
out.write("</div>"); //content
} catch (SQLException e) {
log.error("Failed to construct gridadmin list", e);
}
}
}
/*
private SideContentView createSideView()
{
SideContentView view = new SideContentView();
view.add(new HtmlView("<a class=\"btn\" href=\"gridadminedit\">Add New GridAdmin</a>"));
return view;
}
*/
} |
package com.mikepenz.fastadapter_extensions.utilities;
import android.util.Log;
import com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.IAdapter;
import com.mikepenz.fastadapter.IExpandable;
import com.mikepenz.fastadapter.IItem;
import com.mikepenz.fastadapter.IItemAdapter;
import com.mikepenz.fastadapter.ISubItem;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
public class SubItemUtil {
/**
* returns a set of selected items, regardless of their visibility
*
* @param adapter the adapter instance
* @return a set of all selected items and subitems
*/
public static Set<IItem> getSelectedItems(FastAdapter adapter) {
Set<IItem> selections = new HashSet<>();
int length = adapter.getItemCount();
List<IItem> items = new ArrayList<>();
for (int i = 0; i < length; i++) {
items.add(adapter.getItem(i));
}
updateSelectedItemsWithCollapsed(selections, items);
return selections;
}
private static void updateSelectedItemsWithCollapsed(Set<IItem> selected, List<IItem> items) {
int length = items.size();
for (int i = 0; i < length; i++) {
if (items.get(i).isSelected()) {
selected.add(items.get(i));
}
if (items.get(i) instanceof IExpandable && ((IExpandable) items.get(i)).getSubItems() != null) {
updateSelectedItemsWithCollapsed(selected, ((IExpandable) items.get(i)).getSubItems());
}
}
}
/**
* counts the items in the adapter, respecting subitems regardless of there current visibility
*
* @param adapter the adapter instance
* @param predicate predicate against which each item will be checked before counting it
* @return number of items in the adapter that apply to the predicate
*/
public static int countItems(final IItemAdapter adapter, IPredicate predicate) {
return countItems(adapter.getAdapterItems(), true, false, predicate);
}
/**
* counts the items in the adapter, respecting subitems regardless of there current visibility
*
* @param adapter the adapter instance
* @param countHeaders if true, headers will be counted as well
* @return number of items in the adapter
*/
public static int countItems(final IItemAdapter adapter, boolean countHeaders) {
return countItems(adapter.getAdapterItems(), countHeaders, false, null);
}
private static int countItems(List<IItem> items, boolean countHeaders, boolean subItemsOnly, IPredicate predicate) {
return getAllItems(items, countHeaders, subItemsOnly, predicate).size();
}
/**
* retrieves a list of the items in the adapter, respecting subitems regardless of there current visibility
*
* @param adapter the adapter instance
* @param predicate predicate against which each item will be checked before adding it to the result
* @return list of items in the adapter that apply to the predicate
*/
public static List<IItem> getAllItems(final IItemAdapter adapter, IPredicate predicate) {
return getAllItems(adapter.getAdapterItems(), true, false, predicate);
}
/**
* retrieves a list of the items in the adapter, respecting subitems regardless of there current visibility
*
* @param adapter the adapter instance
* @param countHeaders if true, headers will be counted as well
* @return list of items in the adapter
*/
public static List<IItem> getAllItems(final IItemAdapter adapter, boolean countHeaders) {
return getAllItems(adapter.getAdapterItems(), countHeaders, false, null);
}
private static List<IItem> getAllItems(List<IItem> items, boolean countHeaders, boolean subItemsOnly, IPredicate predicate) {
List<IItem> res = new ArrayList<>();
if (items == null || items.size() == 0) {
return res;
}
int temp;
int itemCount = items.size();
IItem item;
List<IItem> subItems;
for (int i = 0; i < itemCount; i++) {
item = items.get(i);
if (item instanceof IExpandable && ((IExpandable) item).getSubItems() != null) {
subItems = ((IExpandable) item).getSubItems();
if (predicate == null) {
if (subItems != null && subItems.size() > 0)
res.addAll(subItems);
res.addAll(getAllItems(subItems, countHeaders, true, predicate));
if (countHeaders) {
res.add(item);
}
} else {
temp = subItems != null ? subItems.size() : 0;
for (int j = 0; j < temp; j++) {
if (predicate.apply(subItems.get(j))) {
res.add(subItems.get(j));
}
}
if (countHeaders && predicate.apply(item)) {
res.add(item);
}
}
}
// in some cases, we must manually check, if the item is a sub item, process is optimised as much as possible via the subItemsOnly parameter already
// sub items will be counted in above if statement!
else if (!subItemsOnly && getParent(item) == null) {
if (predicate == null) {
res.add(item);
} else if (predicate.apply(item)) {
res.add(item);
}
}
}
return res;
}
/**
* counts the selected items in the adapter underneath an expandable item, recursively
*
* @param adapter the adapter instance
* @param header the header who's selected children should be counted
* @return number of selected items underneath the header
*/
public static <T extends IItem & IExpandable> int countSelectedSubItems(final FastAdapter adapter, T header) {
Set<IItem> selections = getSelectedItems(adapter);
return countSelectedSubItems(selections, header);
}
public static <T extends IItem & IExpandable> int countSelectedSubItems(Set<IItem> selections, T header) {
int count = 0;
List<IItem> subItems = header.getSubItems();
int items = header.getSubItems() != null ? header.getSubItems().size() : 0;
for (int i = 0; i < items; i++) {
if (selections.contains(subItems.get(i))) {
count++;
}
if (subItems.get(i) instanceof IExpandable && ((IExpandable) subItems.get(i)).getSubItems() != null) {
count += countSelectedSubItems(selections, (T) subItems.get(i));
}
}
return count;
}
/**
* select or unselect all sub itmes underneath an expandable item
*
* @param adapter the adapter instance
* @param header the header who's children should be selected or deselected
* @param select the new selected state of the sub items
*/
public static <T extends IItem & IExpandable> void selectAllSubItems(final FastAdapter adapter, T header, boolean select) {
selectAllSubItems(adapter, header, select, false);
}
/**
* select or unselect all sub itmes underneath an expandable item
*
* @param adapter the adapter instance
* @param header the header who's children should be selected or deselected
* @param select the new selected state of the sub items
* @param notifyParent true, if the parent should be notified about the changes of it's children selection state
*/
public static <T extends IItem & IExpandable> void selectAllSubItems(final FastAdapter adapter, T header, boolean select, boolean notifyParent) {
int subItems = header.getSubItems().size();
int position = adapter.getPosition(header);
if (header.isExpanded()) {
for (int i = 0; i < subItems; i++) {
if (((IItem)header.getSubItems().get(i)).isSelectable()) {
if (select) {
adapter.select(position + i + 1);
} else {
adapter.deselect(position + i + 1);
}
}
if (header.getSubItems().get(i) instanceof IExpandable)
selectAllSubItems(adapter, header, select, notifyParent);
}
} else {
for (int i = 0; i < subItems; i++) {
if (((IItem)header.getSubItems().get(i)).isSelectable()) {
((IItem) header.getSubItems().get(i)).withSetSelected(select);
}
if (header.getSubItems().get(i) instanceof IExpandable)
selectAllSubItems(adapter, header, select, notifyParent);
}
}
// we must notify the view only!
if (notifyParent && position >= 0) {
adapter.notifyItemChanged(position);
}
}
private static <T extends IExpandable & IItem> T getParent(IItem item) {
if (item instanceof ISubItem) {
return (T) ((ISubItem) item).getParent();
}
return null;
}
/**
* deletes all selected items from the adapter respecting if the are sub items or not
* subitems are removed from their parents sublists, main items are directly removed
*
* @param deleteEmptyHeaders if true, empty headers will be removed from the adapter
* @return List of items that have been removed from the adapter
*/
public static List<IItem> deleteSelected(final FastAdapter fastAdapter, boolean notifyParent, boolean deleteEmptyHeaders) {
List<IItem> deleted = new ArrayList<>();
// we use a LinkedList, because this has performance advantages when modifying the listIterator during iteration!
// Modifying list is O(1)
LinkedList<IItem> selectedItems = new LinkedList<>(getSelectedItems(fastAdapter));
Log.d("DELETE", "selectedItems: " + selectedItems.size());
// we delete item per item from the adapter directly or from the parent
// if keepEmptyHeaders is false, we add empty headers to the selected items set via the iterator, so that they are processed in the loop as well
IItem item, parent;
int pos, parentPos;
boolean expanded;
ListIterator<IItem> it = selectedItems.listIterator();
while (it.hasNext()) {
item = it.next();
pos = fastAdapter.getPosition(item);
// search for parent - if we find one, we remove the item from the parent's subitems directly
parent = getParent(item);
if (parent != null) {
parentPos = fastAdapter.getPosition(parent);
boolean success = ((IExpandable) parent).getSubItems().remove(item);
Log.d("DELETE", "success=" + success + " | deletedId=" + item.getIdentifier() + " | parentId=" + parent.getIdentifier() + " (sub items: " + ((IExpandable) parent).getSubItems().size() + ") | parentPos=" + parentPos);
// check if parent is expanded and notify the adapter about the removed item, if necessary (only if parent is visible)
if (parentPos != -1 && ((IExpandable) parent).isExpanded()) {
fastAdapter.notifyAdapterSubItemsChanged(parentPos, ((IExpandable) parent).getSubItems().size() + 1);
}
// if desired, notify the parent about it's changed items (only if parent is visible!)
if (parentPos != -1 && notifyParent) {
expanded = ((IExpandable) parent).isExpanded();
fastAdapter.notifyAdapterItemChanged(parentPos);
// expand the item again if it was expanded before calling notifyAdapterItemChanged
if (expanded) {
fastAdapter.expand(parentPos);
}
}
deleted.add(item);
if (deleteEmptyHeaders && ((IExpandable) parent).getSubItems().size() == 0) {
it.add(parent);
it.previous();
}
} else if (pos != -1) {
// if we did not find a parent, we remove the item from the adapter
IAdapter adapter = fastAdapter.getAdapter(pos);
boolean success = false;
if (adapter instanceof IItemAdapter) {
success = ((IItemAdapter) adapter).remove(pos) != null;
}
boolean isHeader = item instanceof IExpandable && ((IExpandable) item).getSubItems() != null;
Log.d("DELETE", "success=" + success + " | deletedId=" + item.getIdentifier() + "(" + (isHeader ? "EMPTY HEADER" : "ITEM WITHOUT HEADER") + ")");
deleted.add(item);
}
}
Log.d("DELETE", "deleted (incl. empty headers): " + deleted.size());
return deleted;
}
/**
* notifies sub items, if they are currently extended
*
* @param adapter the adapter
* @param identifiers set of identifiers that should be notified
*/
public static <ITEM extends IItem & IExpandable> void notifyItemsChanged(final FastAdapter adapter, Set<Long> identifiers) {
int i;
IItem item;
for (i = 0; i < adapter.getItemCount(); i++) {
item = adapter.getItem(i);
if (item instanceof IExpandable) {
notifyItemsChanged(adapter, (ITEM) item, identifiers, true);
}
else if (identifiers.contains(item.getIdentifier())) {
adapter.notifyAdapterItemChanged(i);
}
}
}
/**
* notifies sub items, if they are currently extended
*
* @param adapter the adapter
* @param header the expandable header that should be checked (incl. sub items)
* @param identifiers set of identifiers that should be notified
* @param checkSubItems true, if sub items of headers items should be checked recursively
*/
public static <T extends IItem & IExpandable> void notifyItemsChanged(final FastAdapter adapter, T header, Set<Long> identifiers, boolean checkSubItems) {
int subItems = header.getSubItems().size();
int position = adapter.getPosition(header);
// 1) check header itself
if (identifiers.contains(header.getIdentifier()))
adapter.notifyAdapterItemChanged(position);
// 2) check sub items, recursively
if (header.isExpanded()) {
for (int i = 0; i < subItems; i++) {
if (identifiers.contains(((IItem)header.getSubItems().get(i)).getIdentifier())) {
// Log.d("NOTIFY", "Position=" + position + ", i=" + i);
adapter.notifyAdapterItemChanged(position + i + 1);
}
if (checkSubItems && header.getSubItems().get(i) instanceof IExpandable) {
notifyItemsChanged(adapter, header, identifiers, true);
}
}
}
}
public interface IPredicate<T> {
boolean apply(T data);
}
} |
package edu.washington.escience.myria.io;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.Objects;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.fasterxml.jackson.annotation.JsonProperty;
import edu.washington.escience.myria.coordinator.CatalogException;
public class UriSink implements DataSink {
/** Required for Java serialization. */
private static final long serialVersionUID = 1L;
@JsonProperty
private final URI uri;
public UriSink(@JsonProperty(value = "uri", required = true) String uri) throws CatalogException {
if (uri.contains("s3")) {
uri = uri.replace("s3", "s3n");
}
this.uri = URI.create(Objects.requireNonNull(uri, "Parameter uri cannot be null"));
if (!this.uri.getScheme().equals("hdfs") && !this.uri.getScheme().equals("s3n")) {
throw new CatalogException("URI must be an HDFS or S3 URI");
}
}
@Override
public OutputStream getOutputStream() throws IOException {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(uri, conf);
Path rootPath = new Path(uri);
return fs.create(rootPath);
}
} |
package com.carlosdelachica.easyrecycleradapters.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.carlosdelachica.easyrecycleradapters.adapter.debouncedlisteners.DebouncedOnClickListener;
import com.carlosdelachica.easyrecycleradapters.adapter.debouncedlisteners.DebouncedOnLongClickListener;
import java.util.ArrayList;
import java.util.List;
import static com.carlosdelachica.easyrecycleradapters.adapter.EasyViewHolder.OnItemClickListener;
import static com.carlosdelachica.easyrecycleradapters.adapter.EasyViewHolder.OnItemLongClickListener;
public class EasyRecyclerAdapter extends RecyclerView.Adapter<EasyViewHolder> {
private List<Object> dataList = new ArrayList<>();
private BaseEasyViewHolderFactory viewHolderFactory;
private List<Class> valueClassTypes = new ArrayList<>();
private OnItemClickListener itemClickListener;
private OnItemLongClickListener longClickListener;
public EasyRecyclerAdapter(Context context, Class valueClass,
Class<? extends EasyViewHolder> easyViewHolderClass) {
this(context);
bind(valueClass, easyViewHolderClass);
}
public EasyRecyclerAdapter(Context context) {
this(new BaseEasyViewHolderFactory(context));
}
public EasyRecyclerAdapter(BaseEasyViewHolderFactory easyViewHolderFactory, Class valueClass,
Class<? extends EasyViewHolder> easyViewHolderClass) {
this(easyViewHolderFactory);
bind(valueClass, easyViewHolderClass);
}
public EasyRecyclerAdapter(BaseEasyViewHolderFactory easyViewHolderFactory) {
this.viewHolderFactory = easyViewHolderFactory;
}
public void bind(Class valueClass, Class<? extends EasyViewHolder> viewHolder) {
valueClassTypes.add(valueClass);
viewHolderFactory.bind(valueClass, viewHolder);
}
@Override public EasyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
EasyViewHolder easyViewHolder = viewHolderFactory.create(valueClassTypes.get(viewType), parent);
bindListeners(easyViewHolder);
return easyViewHolder;
}
private void bindListeners(EasyViewHolder easyViewHolder) {
if (easyViewHolder != null) {
easyViewHolder.setItemClickListener(itemClickListener);
easyViewHolder.setLongClickListener(longClickListener);
}
}
@Override public void onBindViewHolder(EasyViewHolder holder, int position) {
holder.bindTo(dataList.get(position));
}
@Override public int getItemViewType(int position) {
return valueClassTypes.indexOf(dataList.get(position).getClass());
}
@Override public int getItemCount() {
return dataList.size();
}
public void add(Object object, int position) {
dataList.add(position, object);
notifyItemInserted(position);
}
public void add(Object object) {
dataList.add(object);
notifyItemInserted(getIndex(object));
}
public void addAll(List<?> objects) {
dataList.clear();
appendAll(objects);
}
public void appendAll(List<?> objects) {
if (objects == null) {
throw new IllegalArgumentException("objects can not be null");
}
dataList.addAll(objects);
notifyDataSetChanged();
}
public boolean update(Object data, int position) {
Object oldData = dataList.set(position, data);
if (oldData != null) {
notifyItemChanged(position);
}
return oldData != null;
}
public boolean remove(Object data) {
if (dataList.contains(data)) {
return remove(getIndex(data));
}
return false;
}
public boolean remove(int position) {
boolean validIndex = isValidIndex(position);
if (validIndex) {
dataList.remove(position);
notifyItemRemoved(position);
}
return validIndex;
}
public void clear() {
dataList.clear();
notifyDataSetChanged();
}
public Object get(int position) {
return dataList.get(position);
}
public int getIndex(Object item) {
return dataList.indexOf(item);
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void setOnClickListener(final OnItemClickListener listener) {
this.itemClickListener = new DebouncedOnClickListener() {
@Override public boolean onDebouncedClick(View v, int position) {
if(listener != null) listener.onItemClick(position, v);
return true;
}
};
}
public void setOnLongClickListener(final OnItemLongClickListener listener) {
this.longClickListener = new DebouncedOnLongClickListener() {
@Override public boolean onDebouncedClick(View v, int position) {
if(listener != null) return listener.onLongItemClicked(position, v);
return false;
}
};
}
private boolean isValidIndex(int position) {
return position >= 0 && position < getItemCount();
}
} |
package com.nhl.link.move.runtime.extractor.model;
import com.nhl.link.move.LmRuntimeException;
import com.nhl.link.move.extractor.model.ExtractorModelContainer;
import com.nhl.link.move.runtime.LmRuntimeBuilder;
import org.apache.cayenne.di.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* An {@link IExtractorModelLoader} that resolves
* {@link ExtractorModelContainer} locations against a specified root directory.
*
* @since 1.4
*/
public class FileExtractorModelLoader extends BaseExtractorModelLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(FileExtractorModelLoader.class);
private File rootDir;
public FileExtractorModelLoader(@Inject(LmRuntimeBuilder.FILE_EXTRACTOR_MODEL_ROOT_DIR) File rootDir) {
LOGGER.info("Extractor XML files will be located under '{}'", rootDir);
this.rootDir = rootDir;
}
@Override
protected Reader getXmlSource(String name) throws IOException {
File file = getFile(name);
LOGGER.info("Will extract XML from {}", file.getAbsolutePath());
return new InputStreamReader(new FileInputStream(file), "UTF-8");
}
@Override
public boolean needsReload(ExtractorModelContainer container) {
return container.getLoadedOn() < getFile(container.getLocation()).lastModified();
}
protected File getFile(String name) {
if (!name.endsWith(".xml")) {
name += ".xml";
}
File file = new File(rootDir, name);
if (!file.exists()) {
throw new LmRuntimeException(file.getAbsolutePath() + " does not exist");
}
if (!file.isFile()) {
throw new LmRuntimeException(file.getAbsolutePath() + " is not a file");
}
return file;
}
} |
package liquibase.integration.commandline;
import liquibase.resource.ResourceAccessor;
import liquibase.util.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* Implementation of liquibase.FileOpener for the command line app.
*
* @see liquibase.resource.ResourceAccessor
*/
public class CommandLineResourceAccessor implements ResourceAccessor {
private ClassLoader loader;
public CommandLineResourceAccessor(ClassLoader loader) {
this.loader = loader;
}
public InputStream getResourceAsStream(String file) throws IOException {
URL resource = loader.getResource(file);
if (resource == null) {
// One more try. People are often confused about leading
// slashes in resource paths...
if (file.startsWith("/")) {
resource = loader.getResource(file.substring(1));
}
if (resource == null) {
throw new IOException(file + " could not be found");
}
}
return resource.openStream();
}
public Enumeration<URL> getResources(String packageName) throws IOException {
return loader.getResources(packageName);
}
public ClassLoader toClassLoader() {
return loader;
}
@Override
public String toString() {
String description;
if (loader instanceof URLClassLoader) {
List<String> urls = new ArrayList<String>();
for (URL url : ((URLClassLoader) loader).getURLs()) {
urls.add(url.toExternalForm());
}
description = StringUtils.join(urls, ",");
} else {
description = loader.getClass().getName();
}
return getClass().getName()+"("+ description +")";
}
} |
package liquibase.statementexecute;
import liquibase.database.Database;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.MaxDBDatabase;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.database.core.SQLiteDatabase;
import liquibase.database.core.SybaseASADatabase;
import liquibase.database.core.SybaseDatabase;
import liquibase.database.core.CacheDatabase;
import liquibase.database.core.*;
import liquibase.datatype.DataTypeFactory;
import liquibase.test.DatabaseTestContext;
import liquibase.statement.*;
import liquibase.statement.core.AddColumnStatement;
import liquibase.statement.core.CreateTableStatement;
import java.util.List;
import java.util.ArrayList;
import org.junit.Test;
public class AddColumnExecutorTest extends AbstractExecuteTest {
protected static final String TABLE_NAME = "table_name";
@Override
protected List<? extends SqlStatement> setupStatements(Database database) {
ArrayList<CreateTableStatement> statements = new ArrayList<CreateTableStatement>();
CreateTableStatement table = new CreateTableStatement(null, null, TABLE_NAME);
table.addColumn("id", DataTypeFactory.getInstance().fromDescription("int"), null, new NotNullConstraint());
statements.add(table);
if (database.supportsSchemas()) {
table = new CreateTableStatement(DatabaseTestContext.ALT_CATALOG, DatabaseTestContext.ALT_SCHEMA, TABLE_NAME);
table.addColumn("id", DataTypeFactory.getInstance().fromDescription("int"), null, new NotNullConstraint());
statements.add(table);
}
return statements;
}
@SuppressWarnings("unchecked")
@Test
public void generateSql_autoIncrement() throws Exception {
this.statementUnderTest = new AddColumnStatement(null, "table_name", "column_name", "int", null, new AutoIncrementConstraint("column_name"));
assertCorrect("alter table table_name add column_name serial", InformixDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int default autoincrement null", SybaseASADatabase.class);
assertCorrect("alter table [table_name] add [column_name] serial", PostgresDatabase.class);
assertCorrect("alter table [dbo].[table_name] add [column_name] int identity", MSSQLDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int identity null", SybaseDatabase.class);
assertCorrect("not supported. fixme!!", SQLiteDatabase.class);
assertCorrect("alter table table_name add column_name int auto_increment_clause");
}
@SuppressWarnings("unchecked")
@Test
public void generateSql_notNull() throws Exception {
this.statementUnderTest = new AddColumnStatement(null, null, "table_name", "column_name", "int", 42, new NotNullConstraint());
assertCorrect("alter table [table_name] add [column_name] int not null default 42", CacheDatabase.class, MaxDBDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int default 42 not null", SybaseASADatabase.class, SybaseDatabase.class);
assertCorrect("alter table table_name add column_name int not null default 42", PostgresDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int not null constraint df_table_name_column_name default 42", MSSQLDatabase.class);
assertCorrect("alter table table_name add column_name int not null default 42", MySQLDatabase.class);
assertCorrect("not supported. fixme!!", SQLiteDatabase.class);
assertCorrect("ALTER TABLE [table_name] ADD [column_name] int DEFAULT 42 NOT NULL");
}
@SuppressWarnings("unchecked")
@Test
public void fullNoConstraints() throws Exception {
this.statementUnderTest = new AddColumnStatement(null, null, "table_name", "column_name", "int", 42);
assertCorrect("alter table [table_name] add [column_name] int default 42 null", SybaseDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int constraint df_table_name_column_name default 42", MSSQLDatabase.class);
// assertCorrect("alter table [table_name] add [column_name] integer default 42", SQLiteDatabase.class);
assertCorrect("not supported. fixme!!", SQLiteDatabase.class);
assertCorrect("alter table table_name add column_name int default 42", PostgresDatabase.class, InformixDatabase.class, OracleDatabase.class, DerbyDatabase.class, HsqlDatabase.class, DB2Database.class, H2Database.class, CacheDatabase.class, FirebirdDatabase.class, MaxDBDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int default 42 null", SybaseASADatabase.class);
assertCorrect("alter table table_name add column_name int null default 42", MySQLDatabase.class);
assertCorrectOnRest("ALTER TABLE [table_name] ADD [column_name] int DEFAULT 42");
}
@SuppressWarnings("unchecked")
@Test
public void autoIncrement() throws Exception {
this.statementUnderTest = new AddColumnStatement(null, TABLE_NAME, "column_name", "int", null, new AutoIncrementConstraint());
assertCorrect("ALTER TABLE [dbo].[table_name] ADD [column_name] int auto_increment_clause", MSSQLDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int default autoincrement null", SybaseASADatabase.class);
assertCorrect("alter table [table_name] add [column_name] int identity null", SybaseDatabase.class);
assertCorrect("alter table [table_name] add [column_name] serial", PostgresDatabase.class, InformixDatabase.class);
assertCorrect("not supported. fixme!!", SQLiteDatabase.class);
assertCorrectOnRest("ALTER TABLE [table_name] ADD [column_name] int auto_increment_clause");
}
@SuppressWarnings("unchecked")
@Test
public void notNull() throws Exception {
this.statementUnderTest = new AddColumnStatement(null, null, TABLE_NAME, "column_name", "int", 42, new NotNullConstraint());
assertCorrect("ALTER TABLE [table_name] ADD [column_name] int DEFAULT 42 NOT NULL", SybaseASADatabase.class, SybaseDatabase.class);
assertCorrect("alter table table_name add column_name int default 42 not null", InformixDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int not null constraint df_table_name_column_name default 42", MSSQLDatabase.class);
assertCorrect("alter table table_name add column_name int default 42 not null", OracleDatabase.class, DerbyDatabase.class, HsqlDatabase.class, DB2Database.class, H2Database.class, FirebirdDatabase.class, DB2iDatabase.class);
assertCorrect("not supported. fixme!!", SQLiteDatabase.class);
assertCorrectOnRest("ALTER TABLE [table_name] ADD [column_name] int NOT NULL DEFAULT 42");
}
@SuppressWarnings("unchecked")
@Test
public void generateSql_primaryKey() throws Exception {
this.statementUnderTest = new AddColumnStatement(null, "table_name", "column_name", "int", null, new PrimaryKeyConstraint());
assertCorrect("alter table [table_name] add [column_name] int not null primary key", HsqlDatabase.class, MaxDBDatabase.class);
assertCorrect("alter table [table_name] add [column_name] int primary key not null", SybaseASADatabase.class, SybaseDatabase.class);
assertCorrect("alter table [dbo].[table_name] add [column_name] int not null primary key", MSSQLDatabase.class);
assertCorrect("alter table table_name add column_name int not null primary key", PostgresDatabase.class);
assertCorrect("alter table `table_name` add `column_name` int not null primary key", MySQLDatabase.class);
assertCorrect("ALTER TABLE [table_name] ADD [column_name] int PRIMARY KEY NOT NULL");
}
@SuppressWarnings("unchecked")
@Test
public void generateSql_foreignKey() throws Exception {
this.statementUnderTest = new AddColumnStatement(null, "table_name", "column_name", "int", null, new PrimaryKeyConstraint(), new ForeignKeyConstraint("fk_test_fk", "table_name(column_name)"));
assertCorrect(new String[] {"alter table [table_name] add [column_name] int not null primary key", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"}, HsqlDatabase.class, MaxDBDatabase.class);
assertCorrect(new String[] {"alter table [table_name] add [column_name] int primary key not null", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"}, SybaseASADatabase.class, SybaseDatabase.class);
assertCorrect(new String[] {"alter table [dbo].[table_name] add [column_name] int not null primary key", "alter table [dbo].[table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [dbo].[table_name]([column_name])"}, MSSQLDatabase.class);
assertCorrect(new String[] {"alter table table_name add column_name int not null primary key", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"}, PostgresDatabase.class);
assertCorrect(new String[] {"alter table `table_name` add `column_name` int not null primary key", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"}, MySQLDatabase.class);
assertCorrect(new String[] {"ALTER TABLE [table_name] ADD [column_name] int PRIMARY KEY NOT NULL", "alter table [table_name] add constraint foreign key ([column_name]) references [table_name]([column_name]) constraint [fk_test_fk]"}, InformixDatabase.class);
assertCorrect(new String[] {"ALTER TABLE [table_name] ADD [column_name] int PRIMARY KEY NOT NULL", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"});
}
} |
package com.powsybl.loadflow.validation;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.powsybl.iidm.network.Bus;
import com.powsybl.iidm.network.Line;
import com.powsybl.iidm.network.Network;
import com.powsybl.iidm.network.TwoWindingsTransformer;
import com.powsybl.loadflow.validation.io.ValidationWriter;
/**
*
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
*/
public final class FlowsValidation {
private static final Logger LOGGER = LoggerFactory.getLogger(FlowsValidation.class);
private FlowsValidation() {
}
public static boolean checkFlows(String id, double r, double x, double rho1, double rho2, double u1, double u2, double theta1, double theta2, double alpha1,
double alpha2, double g1, double g2, double b1, double b2, float p1, float q1, float p2, float q2, boolean connected1,
boolean connected2, boolean mainComponent1, boolean mainComponent2, ValidationConfig config, Writer writer) {
Objects.requireNonNull(id);
Objects.requireNonNull(config);
Objects.requireNonNull(writer);
try (ValidationWriter flowsWriter = ValidationUtils.createValidationWriter(id, config, writer, ValidationType.FLOWS)) {
return checkFlows(id, r, x, rho1, rho2, u1, u2, theta1, theta2, alpha1, alpha2, g1, g2, b1, b2, p1, q1, p2, q2, connected1, connected2,
mainComponent1, mainComponent2, config, flowsWriter);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static boolean checkFlows(String id, double r, double x, double rho1, double rho2, double u1, double u2, double theta1, double theta2, double alpha1,
double alpha2, double g1, double g2, double b1, double b2, float p1, float q1, float p2, float q2, boolean connected1,
boolean connected2, boolean mainComponent1, boolean mainComponent2, ValidationConfig config, ValidationWriter flowsWriter) {
Objects.requireNonNull(id);
Objects.requireNonNull(config);
Objects.requireNonNull(flowsWriter);
boolean validated = true;
try {
double fixedX = x;
if (Math.abs(fixedX) < config.getEpsilonX() && config.applyReactanceCorrection()) {
LOGGER.info("x {} -> {}", fixedX, config.getEpsilonX());
fixedX = config.getEpsilonX();
}
double z = Math.hypot(r, fixedX);
double y = 1 / z;
double ksi = Math.atan2(r, fixedX);
double computedU1 = computeU(connected1, connected2, u1, u2, rho1, rho2, g1, b1, y, ksi);
double computedU2 = computeU(connected2, connected1, u2, u1, rho2, rho1, g2, b2, y, ksi);
double computedTheta1 = computeTheta(connected1, connected2, theta1, theta2, alpha1, alpha2, computedU1, computedU2, rho1, rho2, g1, b1, y, ksi);
double computedTheta2 = computeTheta(connected2, connected1, theta2, theta1, alpha2, alpha1, computedU2, computedU1, rho2, rho1, g2, b2, y, ksi);
double p1Calc = connected1 ? rho1 * rho2 * computedU1 * computedU2 * y * Math.sin(computedTheta1 - computedTheta2 - ksi + alpha1 - alpha2) + rho1 * rho1 * computedU1 * computedU1 * (y * Math.sin(ksi) + g1) : Float.NaN;
double q1Calc = connected1 ? -rho1 * rho2 * computedU1 * computedU2 * y * Math.cos(computedTheta1 - computedTheta2 - ksi + alpha1 - alpha2) + rho1 * rho1 * computedU1 * computedU1 * (y * Math.cos(ksi) - b1) : Float.NaN;
double p2Calc = connected2 ? rho2 * rho1 * computedU2 * computedU1 * y * Math.sin(computedTheta2 - computedTheta1 - ksi + alpha2 - alpha1) + rho2 * rho2 * computedU2 * computedU2 * (y * Math.sin(ksi) + g2) : Float.NaN;
double q2Calc = connected2 ? -rho2 * rho1 * computedU2 * computedU1 * y * Math.cos(computedTheta2 - computedTheta1 - ksi + alpha2 - alpha1) + rho2 * rho2 * computedU2 * computedU2 * (y * Math.cos(ksi) - b2) : Float.NaN;
if (!connected1) {
validated &= checkDisconnectedTerminal(id, "1", p1, p1Calc, q1, q1Calc, config);
}
if (!connected2) {
validated &= checkDisconnectedTerminal(id, "2", p2, p2Calc, q2, q2Calc, config);
}
if (connected1 && mainComponent1) {
validated &= checkConnectedTerminal(id, "1", p1, p1Calc, q1, q1Calc, config);
}
if (connected2 && mainComponent2) {
validated &= checkConnectedTerminal(id, "2", p2, p2Calc, q2, q2Calc, config);
}
flowsWriter.write(id, p1, p1Calc, q1, q1Calc, p2, p2Calc, q2, q2Calc, r, x, g1, g2, b1, b2, rho1, rho2, alpha1, alpha2, u1, u2, theta1, theta2, z, y, ksi,
connected1, connected2, mainComponent1, mainComponent2, validated);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return validated;
}
private static double computeU(boolean connected, boolean otherConnected, double u, double otherU, double rho, double otherRho, double g, double b, double y, double ksi) {
if (connected) {
return u;
}
if (!otherConnected) {
return u;
}
double z1 = y * Math.sin(ksi) + g;
double z2 = y * Math.cos(ksi) - b;
return 1 / Math.sqrt(z1 * z1 + z2 * z2) * (otherRho / rho) * y * otherU;
}
private static double computeTheta(boolean connected, boolean otherConnected, double theta, double otherTheta, double alpha, double otherAlpha, double u, double otherU,
double rho, double otherRho, double g, double b, double y, double ksi) {
if (connected) {
return theta;
}
if (!otherConnected) {
return theta;
}
double z1 = y * Math.sin(ksi) + g;
double z2 = y * Math.cos(ksi) - b;
double phi = -(-otherTheta - ksi + alpha - otherAlpha);
double cosTheatMinusPhi = rho / otherRho * u / otherU * (Math.cos(ksi) - b / y);
return Math.atan(-z1 / z2) + phi + (cosTheatMinusPhi < 0 ? Math.PI : 0);
}
private static boolean checkDisconnectedTerminal(String id, String terminalNumber, float p, double pCalc, float q, double qCalc, ValidationConfig config) {
boolean validated = true;
if (!Float.isNaN(p) && Math.abs(p) > config.getThreshold()) {
LOGGER.warn("{} {}: {} disconnected P{} {} {}", ValidationType.FLOWS, ValidationUtils.VALIDATION_ERROR, id, terminalNumber, p, pCalc);
validated = false;
}
if (!Float.isNaN(q) && Math.abs(q) > config.getThreshold()) {
LOGGER.warn("{} {}: {} disconnected Q{} {} {}", ValidationType.FLOWS, ValidationUtils.VALIDATION_ERROR, id, terminalNumber, q, qCalc);
validated = false;
}
return validated;
}
private static boolean checkConnectedTerminal(String id, String terminalNumber, float p, double pCalc, float q, double qCalc, ValidationConfig config) {
boolean validated = true;
if ((Double.isNaN(pCalc) && !config.areOkMissingValues()) || Math.abs(p - pCalc) > config.getThreshold()) {
LOGGER.warn("{} {}: {} P{} {} {}", ValidationType.FLOWS, ValidationUtils.VALIDATION_ERROR, id, terminalNumber, p, pCalc);
validated = false;
}
if ((Double.isNaN(qCalc) && !config.areOkMissingValues()) || Math.abs(q - qCalc) > config.getThreshold()) {
LOGGER.warn("{} {}: {} Q{} {} {}", ValidationType.FLOWS, ValidationUtils.VALIDATION_ERROR, id, terminalNumber, q, qCalc);
validated = false;
}
return validated;
}
public static boolean checkFlows(Line l, ValidationConfig config, Writer writer) {
Objects.requireNonNull(l);
Objects.requireNonNull(config);
Objects.requireNonNull(writer);
try (ValidationWriter flowsWriter = ValidationUtils.createValidationWriter(l.getId(), config, writer, ValidationType.FLOWS)) {
return checkFlows(l, config, flowsWriter);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static boolean checkFlows(Line l, ValidationConfig config, ValidationWriter flowsWriter) {
Objects.requireNonNull(l);
Objects.requireNonNull(config);
Objects.requireNonNull(flowsWriter);
float p1 = l.getTerminal1().getP();
float q1 = l.getTerminal1().getQ();
float p2 = l.getTerminal2().getP();
float q2 = l.getTerminal2().getQ();
Bus bus1 = l.getTerminal1().getBusView().getBus();
Bus bus2 = l.getTerminal2().getBusView().getBus();
double r = l.getR();
double x = l.getX();
double rho1 = 1f;
double rho2 = 1f;
double u1 = bus1 != null ? bus1.getV() : Double.NaN;
double u2 = bus2 != null ? bus2.getV() : Double.NaN;
double theta1 = bus1 != null ? Math.toRadians(bus1.getAngle()) : Double.NaN;
double theta2 = bus2 != null ? Math.toRadians(bus2.getAngle()) : Double.NaN;
double alpha1 = 0f;
double alpha2 = 0f;
double g1 = l.getG1();
double g2 = l.getG2();
double b1 = l.getB1();
double b2 = l.getB2();
boolean connected1 = bus1 != null ? true : false;
boolean connected2 = bus2 != null ? true : false;
Bus connectableBus1 = l.getTerminal1().getBusView().getConnectableBus();
Bus connectableBus2 = l.getTerminal2().getBusView().getConnectableBus();
boolean connectableMainComponent1 = connectableBus1 != null ? connectableBus1.isInMainConnectedComponent() : false;
boolean connectableMainComponent2 = connectableBus2 != null ? connectableBus2.isInMainConnectedComponent() : false;
boolean mainComponent1 = bus1 != null ? bus1.isInMainConnectedComponent() : connectableMainComponent1;
boolean mainComponent2 = bus2 != null ? bus2.isInMainConnectedComponent() : connectableMainComponent2;
return checkFlows(l.getId(), r, x, rho1, rho2, u1, u2, theta1, theta2, alpha1, alpha2, g1, g2, b1, b2, p1, q1, p2, q2, connected1, connected2,
mainComponent1, mainComponent2, config, flowsWriter);
}
public static boolean checkFlows(TwoWindingsTransformer twt, ValidationConfig config, Writer writer) {
Objects.requireNonNull(twt);
Objects.requireNonNull(config);
Objects.requireNonNull(writer);
try (ValidationWriter flowsWriter = ValidationUtils.createValidationWriter(twt.getId(), config, writer, ValidationType.FLOWS)) {
return checkFlows(twt, config, flowsWriter);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static boolean checkFlows(TwoWindingsTransformer twt, ValidationConfig config, ValidationWriter flowsWriter) {
Objects.requireNonNull(twt);
Objects.requireNonNull(config);
Objects.requireNonNull(flowsWriter);
if (twt.getRatioTapChanger() != null && twt.getPhaseTapChanger() != null) {
throw new AssertionError();
}
float p1 = twt.getTerminal1().getP();
float q1 = twt.getTerminal1().getQ();
float p2 = twt.getTerminal2().getP();
float q2 = twt.getTerminal2().getQ();
Bus bus1 = twt.getTerminal1().getBusView().getBus();
Bus bus2 = twt.getTerminal2().getBusView().getBus();
float r = (float) getR(twt);
float x = (float) getX(twt);
double g1 = getG1(twt, config);
double g2 = config.getLoadFlowParameters().isSpecificCompatibility() ? twt.getG() / 2 : 0f;
double b1 = getB1(twt, config);
double b2 = config.getLoadFlowParameters().isSpecificCompatibility() ? twt.getB() / 2 : 0f;
double rho1 = getRho1(twt);
double rho2 = 1f;
double u1 = bus1 != null ? bus1.getV() : Double.NaN;
double u2 = bus2 != null ? bus2.getV() : Double.NaN;
double theta1 = bus1 != null ? Math.toRadians(bus1.getAngle()) : Double.NaN;
double theta2 = bus2 != null ? Math.toRadians(bus2.getAngle()) : Double.NaN;
double alpha1 = twt.getPhaseTapChanger() != null ? Math.toRadians(twt.getPhaseTapChanger().getCurrentStep().getAlpha()) : 0f;
double alpha2 = 0f;
boolean connected1 = bus1 != null ? true : false;
boolean connected2 = bus2 != null ? true : false;
Bus connectableBus1 = twt.getTerminal1().getBusView().getConnectableBus();
Bus connectableBus2 = twt.getTerminal2().getBusView().getConnectableBus();
boolean connectableMainComponent1 = connectableBus1 != null ? connectableBus1.isInMainConnectedComponent() : false;
boolean connectableMainComponent2 = connectableBus2 != null ? connectableBus2.isInMainConnectedComponent() : false;
boolean mainComponent1 = bus1 != null ? bus1.isInMainConnectedComponent() : connectableMainComponent1;
boolean mainComponent2 = bus2 != null ? bus2.isInMainConnectedComponent() : connectableMainComponent2;
return checkFlows(twt.getId(), r, x, rho1, rho2, u1, u2, theta1, theta2, alpha1, alpha2, g1, g2, b1, b2, p1, q1, p2, q2, connected1, connected2,
mainComponent1, mainComponent2, config, flowsWriter);
}
private static double getValue(float initialValue, float rtcStepValue, float ptcStepValue) {
return initialValue * (1 + rtcStepValue / 100) * (1 + ptcStepValue / 100);
}
private static double getR(TwoWindingsTransformer twt) {
return getValue(twt.getR(),
twt.getRatioTapChanger() != null ? twt.getRatioTapChanger().getCurrentStep().getR() : 0,
twt.getPhaseTapChanger() != null ? twt.getPhaseTapChanger().getCurrentStep().getR() : 0);
}
private static double getX(TwoWindingsTransformer twt) {
return getValue(twt.getX(),
twt.getRatioTapChanger() != null ? twt.getRatioTapChanger().getCurrentStep().getX() : 0,
twt.getPhaseTapChanger() != null ? twt.getPhaseTapChanger().getCurrentStep().getX() : 0);
}
private static double getG1(TwoWindingsTransformer twt, ValidationConfig config) {
return getValue(config.getLoadFlowParameters().isSpecificCompatibility() ? twt.getG() / 2 : twt.getG(),
twt.getRatioTapChanger() != null ? twt.getRatioTapChanger().getCurrentStep().getG() : 0,
twt.getPhaseTapChanger() != null ? twt.getPhaseTapChanger().getCurrentStep().getG() : 0);
}
private static double getB1(TwoWindingsTransformer twt, ValidationConfig config) {
return getValue(config.getLoadFlowParameters().isSpecificCompatibility() ? twt.getB() / 2 : twt.getB(),
twt.getRatioTapChanger() != null ? twt.getRatioTapChanger().getCurrentStep().getB() : 0,
twt.getPhaseTapChanger() != null ? twt.getPhaseTapChanger().getCurrentStep().getB() : 0);
}
private static double getRho1(TwoWindingsTransformer twt) {
double rho1 = twt.getRatedU2() / twt.getRatedU1();
if (twt.getRatioTapChanger() != null) {
rho1 *= twt.getRatioTapChanger().getCurrentStep().getRho();
}
if (twt.getPhaseTapChanger() != null) {
rho1 *= twt.getPhaseTapChanger().getCurrentStep().getRho();
}
return rho1;
}
public static boolean checkFlows(Network network, ValidationConfig config, Writer writer) {
Objects.requireNonNull(network);
Objects.requireNonNull(config);
Objects.requireNonNull(writer);
try (ValidationWriter flowsWriter = ValidationUtils.createValidationWriter(network.getId(), config, writer, ValidationType.FLOWS)) {
return checkFlows(network, config, flowsWriter);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static boolean checkFlows(Network network, ValidationConfig config, Path file) throws IOException {
Objects.requireNonNull(network);
Objects.requireNonNull(config);
Objects.requireNonNull(file);
try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
return checkFlows(network, config, writer);
}
}
public static boolean checkFlows(Network network, ValidationConfig config, ValidationWriter flowsWriter) {
Objects.requireNonNull(network);
Objects.requireNonNull(config);
Objects.requireNonNull(flowsWriter);
LOGGER.info("Checking flows of network {}", network.getId());
boolean linesValidated = network.getLineStream()
.sorted(Comparator.comparing(Line::getId))
.map(l -> checkFlows(l, config, flowsWriter))
.reduce(Boolean::logicalAnd).orElse(true);
boolean transformersValidated = network.getTwoWindingsTransformerStream()
.sorted(Comparator.comparing(TwoWindingsTransformer::getId))
.map(t -> checkFlows(t, config, flowsWriter))
.reduce(Boolean::logicalAnd).orElse(true);
return linesValidated && transformersValidated;
}
} |
package gcm2sbml.gui.modelview;
import gcm2sbml.gui.GCM2SBMLEditor;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.util.GlobalConstants;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import javax.xml.bind.JAXBElement.GlobalScope;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.model.mxICell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxConstants;
import com.mxgraph.util.mxPoint;
import com.mxgraph.view.mxGraph;
import com.mxgraph.view.mxStylesheet;
/**
* @author Tyler tpatterson80@gmail.com
*
*/
public class BioGraph extends mxGraph {
private static final int DEFAULT_SPECIES_WIDTH = 100;
private static final int DEFAULT_SPECIES_HEIGHT = 30;
private static final int DEFAULT_COMPONENT_WIDTH = 80;
private static final int DEFAULT_COMPONENT_HEIGHT = 40;
private double DIS_BETWEEN_NEIGHBORING_EDGES = 35.0;
private double SECOND_SELF_INFLUENCE_DISTANCE = 20;
/**
* Map species to their graph nodes by id. This map is
* (or at least, should always be) kept up-to-date whenever
* a node is added or deleted.
*/
private HashMap<String, mxCell> speciesToMxCellMap;
private HashMap<String, mxCell> influencesToMxCellMap;
private HashMap<String, mxCell> componentsToMxCellMap;
private HashMap<String, mxCell> componentsConnectionsToMxCellMap;
private GCMFile gcm;
private GCM2SBMLEditor gcm2sbml; // needed to pull up editor windows
public final String CELL_NOT_FULLY_CONNECTED = "cell not fully connected";
private final String CELL_VALUE_NOT_FOUND = "cell value not found";
private void initializeMaps(){
speciesToMxCellMap = new HashMap<String, mxCell>();
componentsToMxCellMap = new HashMap<String, mxCell>();
influencesToMxCellMap = new HashMap<String, mxCell>();
componentsConnectionsToMxCellMap = new HashMap<String, mxCell>();
}
public BioGraph(GCMFile gcm, GCM2SBMLEditor gcm2sbml){
super();
// Turn editing off to prevent mxGraph from letting the user change the
// label on the cell. We want to do this using the property windows.
this.setCellsEditable(false);
this.gcm = gcm;
this.gcm2sbml = gcm2sbml;
this.initializeMaps();
createStyleSheets();
}
public void bringUpEditorForCell(mxCell cell){
if(getCellType(cell) == GlobalConstants.SPECIES){
gcm2sbml.launchSpeciesPanel(cell.getId());
}else if(getCellType(cell) == GlobalConstants.INFLUENCE){
// if an edge, make sure it isn't connected
// to a component - which aren't really influences at all.
if( getCellType(cell.getSource()) == GlobalConstants.SPECIES &&
getCellType(cell.getTarget()) == GlobalConstants.SPECIES)
gcm2sbml.launchInfluencePanel(cell.getId());
}else if(getCellType(cell) == GlobalConstants.COMPONENT){
//gcm2sbml.displayChooseComponentDialog(true, null, false, cell.getId());
gcm2sbml.launchComponentPanel(cell.getId());
}
// refresh everything.
this.buildGraph();
}
public void updateAllSpeciesPosition(){
for(mxCell cell:this.speciesToMxCellMap.values()){
updateInternalPosition(cell);
}
for(mxCell cell:this.componentsToMxCellMap.values()){
updateInternalPosition(cell);
}
}
/**
* Given a cell that must be a species or component,
* update the internal model to reflect it's coordinates.
* Called when a cell is dragged with the GUI.
*/
public void updateInternalPosition(mxCell cell){
Properties prop = ((CellValueObject)cell.getValue()).prop;
mxGeometry geom = cell.getGeometry();
prop.setProperty("graphx", String.valueOf(geom.getX()));
prop.setProperty("graphy", String.valueOf(geom.getY()));
prop.setProperty("graphwidth", String.valueOf(geom.getWidth()));
prop.setProperty("graphheight", String.valueOf(geom.getHeight()));
}
/**
* returns GlobalConstants.SPECIES, GlobalConstants.COMPONENT, GlobalConstants.INFLUENCE, or GlobalConstants.COMPONENT_CONNECTION.
* @param cell
*/
public String getCellType(mxCell cell){
if(cell.isEdge()){
String sourceType = getCellType(cell.getSource());
String targetType = getCellType(cell.getTarget());
if(sourceType == CELL_VALUE_NOT_FOUND || targetType == CELL_VALUE_NOT_FOUND){
return CELL_NOT_FULLY_CONNECTED;
}else if(sourceType == GlobalConstants.COMPONENT || targetType == GlobalConstants.COMPONENT){
return GlobalConstants.COMPONENT_CONNECTION;
}else{
return GlobalConstants.INFLUENCE;
}
}else{
Properties prop = ((CellValueObject)(cell.getValue())).prop;
if(gcm.getSpecies().containsValue(prop))
return GlobalConstants.SPECIES;
else if(gcm.getComponents().containsValue(prop))
return GlobalConstants.COMPONENT;
else
return CELL_VALUE_NOT_FOUND;
}
}
public String getCellType(mxICell cell){return getCellType((mxCell)cell);}
/**
* Given a cell, return the list that it belongs to.
*/
public HashMap<String, Properties> getPropertiesList(mxCell cell){
String type = this.getCellType(cell);
if(type == GlobalConstants.SPECIES)
return gcm.getSpecies();
else if(type == GlobalConstants.COMPONENT)
return gcm.getComponents();
else if(type == GlobalConstants.INFLUENCE)
return gcm.getInfluences();
else if(type == GlobalConstants.COMPONENT_CONNECTION)
throw new Error("Component Connectiosn don't have properties!");
else
throw new Error("Invalid type: " + type);
}
/**
* A convenience function
* @param cell
* @return
*/
public Properties getCellProperties(mxCell cell){
return getPropertiesList(cell).get(cell.getId());
}
public Properties getCellProperties(mxICell cell){
return getCellProperties((mxCell)cell);
}
// /**
// * Overwrite the parent insertVertex and additionally put the vertex into our hashmap.
// * @return
// */
// public Object insertVertex(Object parent, String id, Object value, double x, double y, double width, double height){
// Object ret = super.insertVertex(parent, id, value, x, y, width, height);
// this.speciesToMxCellMap.put(id, (mxCell)ret);
// return ret;
public mxCell getSpeciesCell(String id){
return speciesToMxCellMap.get(id);
}
public mxCell getComponentCell(String id){
return componentsToMxCellMap.get(id);
}
/**
* public Object insertEdge(Object parent,
String id,
Object value,
Object source,
Object target,
String style)
*/
@Override
public Object insertEdge(Object parent, String id, Object value, Object source, Object target, String style){
Object ret = super.insertEdge(parent, id, value, source, target, style);
this.influencesToMxCellMap.put(id, (mxCell)ret);
return ret;
}
public mxCell getInfluence(String id){
return (influencesToMxCellMap.get(id));
}
/**
* called after a species is deleted. Make sure to delete it from
* the internal model.
* @param id
*/
public void speciesRemoved(String id){
this.speciesToMxCellMap.remove(id);
}
public void influenceRemoved(String id){
this.influencesToMxCellMap.remove(id);
}
/**
* Builds the graph based on the internal representation
* @return
*/
public boolean isBuilding = false;
public boolean buildGraph(){
this.isBuilding = true;
// remove all the components from the graph if there are any
this.selectAll();
this.removeCells();
initializeMaps();
assert(this.gcm != null);
// Start an undo transaction
this.getModel().beginUpdate();
boolean needsPositioning = false;
// add species
for(String sp:gcm.getSpecies().keySet()){ // SPECIES
if(createGraphSpeciesFromModel(sp))
needsPositioning = true;
}
// add all components
for(String comp:gcm.getComponents().keySet()){
if(createGraphComponentFromModel(comp))
needsPositioning = true;
}
// add all the edges
for(String inf:gcm.getInfluences().keySet()){
this.insertEdge(this.getDefaultParent(), inf, "",
this.getSpeciesCell(GCMFile.getInput(inf)),
this.getSpeciesCell(GCMFile.getOutput(inf))
);
updateInfluenceVisuals(inf);
}
addEdgeOffsets();
this.getModel().endUpdate();
this.isBuilding = false;
return needsPositioning;
}
/**
* Loop through all the edges and add control points to reposition them
* if they are laying over the top of any other edges.
*/
public void addEdgeOffsets(){
// Make a hash where the key is a string built from the ids of the source and destination
// of all the edges. The source and destination will be sorted so that the same two
// source-destination pair will always map to the same key. The value is a list
// of edges. That way if there are ever more then one edge between pairs,
// we can modify the geometry so they don't overlap.
HashMap<String, Vector<mxCell>> edgeHash = new HashMap<String, Vector<mxCell>>();
// build a temporary structure mapping sets of edge endpoints to edges
// map species
for(String inf:gcm.getInfluences().keySet()){
String endA = GCMFile.getInput(inf);
String endB = GCMFile.getOutput(inf);
if(endA.compareToIgnoreCase(endB) == 1){
// swap the strings
String t = endA;
endA = endB;
endB = t;
}
String key = endA + " " + endB;
mxCell cell = this.getInfluence(inf);
if(edgeHash.containsKey(key) == false)
edgeHash.put(key, new Vector<mxCell>());
edgeHash.get(key).add(cell);
}
// map components edges
Pattern getPropNamePattern = Pattern.compile("^type_([\\w\\_\\d]+)");
for(String compName:gcm.getComponents().keySet()){
Properties comp = gcm.getComponents().get(compName);
for(Object propNameO:comp.keySet()){
String propName = propNameO.toString();
if(propName.startsWith("type_")){
Matcher matcher = getPropNamePattern.matcher(propName);
matcher.find();
String t = matcher.group(0);
String compInternalName = matcher.group(1);
String targetName = comp.get(compInternalName).toString();
String type = comp.get(propName).toString(); // Input or Output
String key = compName + " "+type+" " + targetName;
mxCell cell = componentsConnectionsToMxCellMap.get(key);
String simpleKey = compName + " " + targetName;
if(edgeHash.containsKey(simpleKey) == false)
edgeHash.put(simpleKey, new Vector<mxCell>());
edgeHash.get(simpleKey).add(cell);
}
}
}
// loop through every set of edge endpoints and then move them if needed.
for(Vector<mxCell> vec:edgeHash.values()){
if(vec.size() > 1){
mxCell source = (mxCell)vec.get(0).getSource();
mxCell target = (mxCell)vec.get(0).getTarget();
// find the end and center points
mxGeometry t;
t = source.getGeometry();
mxPoint sp = new mxPoint(t.getCenterX(), t.getCenterY());
t = target.getGeometry();
mxPoint tp = new mxPoint(t.getCenterX(), t.getCenterY());
mxPoint cp = new mxPoint((tp.getX()+sp.getX())/2.0, (tp.getY()+sp.getY())/2.0);
// check for self-influence
if(source == target){
mxCell c = vec.get(0);
mxGeometry geom = c.getGeometry();
// set the self-influence's point to the left of the influence.
// This causes the graph library to draw it rounded in that direction.
mxPoint p = new mxPoint(
cp.getX() - t.getWidth()/2-SECOND_SELF_INFLUENCE_DISTANCE,
cp.getY()
);
Vector<mxPoint> points = new Vector<mxPoint>();
points.add(p);
geom.setPoints(points);
c.setGeometry(geom);
continue;
}
// make a unit vector that points in the direction perpendicular to the
// direction from one endpoint to the other. 90 degrees rotated means flip
// the x and y coordinates.
mxPoint dVec = new mxPoint(-(sp.getY()-tp.getY()), sp.getX()-tp.getX());
double magnitude = Math.sqrt(dVec.getX()*dVec.getX() + dVec.getY()*dVec.getY());
// avoid divide-by-zero errors
magnitude = Math.max(magnitude, .1);
// normalize
dVec.setX(dVec.getX()/magnitude);
dVec.setY(dVec.getY()/magnitude);
// loop through all the edges, create a new midpoint and apply it.
// also move the edge center to the midpoint so that labels won't be
// on top of each other.
for(int i=0; i<vec.size(); i++){
double offset = i-(vec.size()-1.0)/2.0;
mxCell edge = vec.get(i);
//cell.setGeometry(new mxGeometry(0, 0, 100, 100));
mxGeometry geom = edge.getGeometry();
Vector<mxPoint> points = new Vector<mxPoint>();
mxPoint p = new mxPoint(
cp.getX()+dVec.getX()*offset*DIS_BETWEEN_NEIGHBORING_EDGES,
cp.getY()+dVec.getY()*offset*DIS_BETWEEN_NEIGHBORING_EDGES
);
points.add(p);
geom.setPoints(points);
// geom.setX(p.getX());
// geom.setY(p.getY());
edge.setGeometry(geom);
}
}
}
// for(Object edgeo:this.getSelectionCell()){
// mxCell edge = (mxCell)edgeo;
// int s = edge.getSource().getEdgeCount();
// int t = edge.getTarget().getEdgeCount()
// if(edge.getSource().getEdgeCount() > 1 && edge.getTarget().getEdgeCount() > 1){
// // the source and target have multiple edges, now loop through them all...
// //cell.setGeometry(new mxGeometry(0, 0, 100, 100));
// mxGeometry geom = new mxGeometry();
// Vector<mxPoint> points = new Vector<mxPoint>();
// mxPoint p = new mxPoint(50.0, 50.0);
// points.add(p);
// geom.setPoints(points);
// edge.setGeometry(geom);
}
// Keep track of how many elements did not have positioning info.
// This allows us to stack them in the topleft corner until they
// are positioned by the user or a layout algorithm.
int unpositionedSpeciesComponentCount = 0;
private boolean createGraphComponentFromModel(String id){
//{invb={ID=invb, gcm=inv.gcm}
//{invb={ID=invb, gcm=inv.gcm}, i1={b=S3, ID=i1, a=S1, gcm=inv.gcm, type_b=Output, type_a=Input}}
boolean needsPositioning = false;
Properties prop = gcm.getComponents().get(id);
double x = Double.parseDouble(prop.getProperty("graphx", "-9999"));
double y = Double.parseDouble(prop.getProperty("graphy", "-9999"));;
double width = Double.parseDouble(prop.getProperty("graphwidth", String.valueOf(DEFAULT_COMPONENT_WIDTH)));;
double height = Double.parseDouble(prop.getProperty("graphheight", String.valueOf(DEFAULT_COMPONENT_HEIGHT)));
if(x < -9998 || y < -9998){
unpositionedSpeciesComponentCount += 1;
needsPositioning = true;
// Line the unpositioned species up nicely. The mod is there as a rough
// and dirty way to prevent
// them going off the bottom or right hand side of the screen.
x = (unpositionedSpeciesComponentCount%50) * 20;
y = (unpositionedSpeciesComponentCount%10) * (DEFAULT_SPECIES_HEIGHT + 10);
}
String label = id + "\n" + prop.getProperty("gcm").replace(".gcm", "");
CellValueObject cvo = new CellValueObject(label, prop);
Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, x, y, width, height);
this.componentsToMxCellMap.put(id, (mxCell)insertedVertex);
this.setComponentStyles(id);
// now draw the edges that connect the component
for (Object propName : prop.keySet()) {
if (!propName.toString().equals("gcm")
&& !propName.toString().equals(GlobalConstants.ID)
&& prop.keySet().contains("type_" + propName)) {
Object createdEdge;
if (prop.getProperty("type_" + propName).equals("Output")) {
// output, the arrow should point out to the species
createdEdge = this.insertEdge(this.getDefaultParent(), "", "",
insertedVertex,
this.getSpeciesCell(prop.getProperty(propName.toString()).toString())
);
String key = id + " Output " + prop.getProperty(propName.toString()).toString();
componentsConnectionsToMxCellMap.put(key, (mxCell)createdEdge);
}
else {
// input, the arrow should point in from the species
createdEdge = this.insertEdge(this.getDefaultParent(), "", "",
this.getSpeciesCell(prop.getProperty(propName.toString()).toString()),
insertedVertex
);
String key = id + " Input " + prop.getProperty(propName.toString()).toString();
componentsConnectionsToMxCellMap.put(key, (mxCell)createdEdge);
}
this.updateComponentConnectionVisuals((mxCell)createdEdge, propName.toString());
}
}
return needsPositioning;
}
/**
* returns the name of the component-to-species connection
* @param compName
* @param speciesName
* @return
*/
private String getComponentConnectionName(String compName, String speciesName){
return compName + " (component connection) " + speciesName;
}
/**
* creates a vertex on the graph using the internal model.
* @param id
*
* @return: A bool, true if the species had to be positioned.
*/
private boolean createGraphSpeciesFromModel(String sp){
Properties prop = gcm.getSpecies().get(sp);
double x = Double.parseDouble(prop.getProperty("graphx", "-9999"));
double y = Double.parseDouble(prop.getProperty("graphy", "-9999"));;
double width = Double.parseDouble(prop.getProperty("graphwidth", String.valueOf(DEFAULT_SPECIES_WIDTH)));;
double height = Double.parseDouble(prop.getProperty("graphheight", String.valueOf(DEFAULT_SPECIES_HEIGHT)));
String id = prop.getProperty("ID", "");
if (id==null) {
id = prop.getProperty("label", "");
}
/*
String id = !(prop.getProperty(GlobalConstants.NAME, "").equals("")) ?
prop.getProperty(GlobalConstants.NAME) :
!prop.getProperty("ID", "").equals("") ? prop.getProperty("ID", ""):
prop.getProperty("label");
*/
boolean needsPositioning = false;
if(x < -9998 || y < -9998){
unpositionedSpeciesComponentCount += 1;
needsPositioning = true;
// Line the unpositioned species up nicely. The mod is there as a rough
// and dirty way to prevent
// them going off the bottom or right hand side of the screen.
x = (unpositionedSpeciesComponentCount%50) * 20;
y = (unpositionedSpeciesComponentCount%10) * (DEFAULT_SPECIES_HEIGHT + 10);
}
CellValueObject cvo = new CellValueObject(id, prop);
Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, x, y, width, height);
this.speciesToMxCellMap.put(id, (mxCell)insertedVertex);
this.setSpeciesStyles(sp);
return needsPositioning;
}
/**
* Given an id, update the style of the influence based on the internal model.
*/
private void updateInfluenceVisuals(String id){
Properties prop = gcm.getInfluences().get(id);
if(prop == null)
throw new Error("Invalid id '"+id+"'. Valid ids were:" + String.valueOf(gcm.getInfluences().keySet()));
// build the edge style
// Look in mxConstants to see all the pre-built styles.
String style = "defaultEdge;" + mxConstants.STYLE_ENDARROW + "=";
if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.ACTIVATION))
style += mxConstants.ARROW_CLASSIC;
else if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.REPRESSION))
style += mxConstants.ARROW_OVAL;
else
style += mxConstants.ARROW_OPEN; // This should never happen.
// apply the style
mxCell cell = this.getInfluence(id);
cell.setStyle(style);
// apply the label
String label = prop.getProperty(GlobalConstants.PROMOTER, "");
cell.setValue(label);
};
public void updateComponentConnectionVisuals(mxCell cell, String label){
//cell.setStyle(mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN);
cell.setStyle("COMPONENT_EDGE");
cell.setValue("Port " + label);
// position the label as intelligently as possible
mxGeometry geom = cell.getGeometry();
if(this.getCellType(cell.getSource()) == GlobalConstants.COMPONENT){
geom.setX(-.6);
}else{
geom.setX(.6);
}
cell.setGeometry(geom);
}
/**
* Builds the style sheets that will be used by the graph.
*/
public void createStyleSheets(){
mxStylesheet stylesheet = this.getStylesheet();
// Species
Hashtable<String, Object> style = new Hashtable<String, Object>();
style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE);
style.put(mxConstants.STYLE_OPACITY, 50);
style.put(mxConstants.STYLE_FONTCOLOR, "#774400");
//style.put(mxConstants.RECTANGLE_ROUNDING_FACTOR, .2);
style.put(mxConstants.STYLE_ROUNDED, true);
stylesheet.putCellStyle("SPECIES", style);
// components
style = new Hashtable<String, Object>();
style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE);
style.put(mxConstants.STYLE_OPACITY, 30);
style.put(mxConstants.STYLE_FONTCOLOR, "#774400");
style.put(mxConstants.STYLE_ROUNDED, false);
style.put(mxConstants.STYLE_FILLCOLOR, "#FFAA00");
style.put(mxConstants.STYLE_STROKECOLOR, "#AA7700");
stylesheet.putCellStyle("COMPONENT", style);
style = new Hashtable<String, Object>();
style.put(mxConstants.STYLE_OPACITY, 100);
style.put(mxConstants.STYLE_FONTCOLOR, "#774400");
style.put(mxConstants.STYLE_FILLCOLOR, "#FFAA00");
style.put(mxConstants.STYLE_STROKECOLOR, "#AA7700");
style.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_OPEN);
stylesheet.putCellStyle("COMPONENT_EDGE", style);
}
private void setSpeciesStyles(String id){
String style="SPECIES;";
mxCell cell = this.getSpeciesCell(id);
cell.setStyle(style);
}
private void setComponentStyles(String id){
String style="COMPONENT;";
mxCell cell = this.getComponentCell(id);
cell.setStyle(style);
}
/**
* Creates an influence based on an already created edge.
*/
public void addInfluence(mxCell cell, String id, String constType){
Properties prop = new Properties();
prop.setProperty(GlobalConstants.NAME, id);
prop.setProperty(GlobalConstants.TYPE, constType);
gcm.getInfluences().put(id, prop);
this.influencesToMxCellMap.put(id, cell);
updateInfluenceVisuals(id);
}
/**
* creates and adds a new species.
* @param id: the new id. If null the id will be generated
* @param x
* @param y
*/
private int creatingSpeciesID = 0;
public void createSpecies(String id, float x, float y){
if(id == null){
do{
creatingSpeciesID++;
id = "S" + String.valueOf(creatingSpeciesID);
}while(gcm.getSpecies().containsKey(id));
}
Properties prop = new Properties();
prop.setProperty(GlobalConstants.NAME, "");
prop.setProperty("label", id);
prop.setProperty("ID", id);
prop.setProperty("Type", "normal");
prop.setProperty("graphwidth", String.valueOf(DEFAULT_SPECIES_WIDTH));
prop.setProperty("graphheight", String.valueOf(DEFAULT_SPECIES_HEIGHT));
centerVertexOverPoint(prop, x, y);
gcm.getSpecies().put(id, prop);
this.getModel().beginUpdate();
this.createGraphSpeciesFromModel(id);
this.getModel().endUpdate();
gcm2sbml.refresh();
}
/**
* Given a properties list (species or components) and some coords, center over that point.
*/
public void centerVertexOverPoint(Properties prop, double x, double y){
x -= Double.parseDouble(prop.getProperty("graphwidth", "60"))/2.0;
y -= Double.parseDouble(prop.getProperty("graphheight", "20"))/2.0;
prop.setProperty("graphx", String.valueOf(x));
prop.setProperty("graphy", String.valueOf(y));
}
public void applyLayout(String ident, mxGraphComponent graphComponent){
Layouting.applyLayout(ident, this, graphComponent);
}
/**
* The object that gets set as the mxCell value object.
* It is basically a way to store a property and label.
*/
public class CellValueObject extends Object implements Serializable{
private static final long serialVersionUID = 918273645;
public Properties prop;
public String label;
@Override
public String toString(){
return this.label;
}
private void writeObject(ObjectOutputStream oos)
throws IOException {
oos.writeObject(label);
oos.writeObject(prop);
}
private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
label = ois.readObject().toString();
prop = (Properties)ois.readObject();
}
public CellValueObject(String label, Properties prop){
if(prop == null || label == null)
throw new Error("Neither Properties nor label can not be null!");
this.label = label;
this.prop = prop;
}
}
//////////////////////////////////////// ANIMATION TYPE STUFF ////////////////////////////////
private static final double extraAnimationWidth = 30.0;
private static final double extraAnimationHeight = 20;
public void setSpeciesAnimationValue(String s, double value){
mxCell cell = this.speciesToMxCellMap.get(s);
// String newCol = String.valueOf(value / 100 * 16);
// cell.setStyle(mxConstants.STYLE_FILLCOLOR, "#FFAA00", newCol);
mxGeometry priorGeom = cell.getGeometry();
mxGeometry geom = new mxGeometry();
geom.setWidth(extraAnimationWidth + value*.5);
geom.setHeight(extraAnimationHeight + value*.5);
geom.setX(priorGeom.getCenterX() - geom.getWidth()*.5);
geom.setY(priorGeom.getCenterY() - geom.getHeight()*.5);
cell.setGeometry(geom);
}
} |
package gcm2sbml.network;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.parser.GCMParser;
import gcm2sbml.util.GlobalConstants;
import gcm2sbml.util.Utility;
import gcm2sbml.visitor.AbstractPrintVisitor;
import gcm2sbml.visitor.PrintActivatedBindingVisitor;
import gcm2sbml.visitor.PrintActivatedProductionVisitor;
import gcm2sbml.visitor.PrintBiochemicalVisitor;
import gcm2sbml.visitor.PrintDecaySpeciesVisitor;
import gcm2sbml.visitor.PrintDimerizationVisitor;
import gcm2sbml.visitor.PrintRepressionBindingVisitor;
import gcm2sbml.visitor.PrintSpeciesVisitor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.sbml.libsbml.ASTNode;
import org.sbml.libsbml.Constraint;
import org.sbml.libsbml.EventAssignment;
import org.sbml.libsbml.FunctionDefinition;
import org.sbml.libsbml.InitialAssignment;
import org.sbml.libsbml.KineticLaw;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.ModifierSpeciesReference;
import org.sbml.libsbml.Rule;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.SBMLWriter;
import org.sbml.libsbml.Species;
import org.sbml.libsbml.SpeciesReference;
import org.sbml.libsbml.Unit;
import org.sbml.libsbml.UnitDefinition;
import org.sbml.libsbml.libsbml;
import biomodelsim.BioSim;
/**
* This class represents a genetic network
*
* @author Nam
*
*/
public class GeneticNetwork {
private String separator;
/**
* Constructor
*
* @param species
* a hashmap of species
* @param stateMap
* a hashmap of statename to species name
* @param promoters
* a hashmap of promoters
*/
public GeneticNetwork(HashMap<String, SpeciesInterface> species,
HashMap<String, SpeciesInterface> stateMap,
HashMap<String, Promoter> promoters) {
this(species, stateMap, promoters, null);
}
/**
* Constructor
*/
public GeneticNetwork() {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
}
/**
* Constructor
*
* @param species
* a hashmap of species
* @param stateMap
* a hashmap of statename to species name
* @param promoters
* a hashmap of promoters
* @param gcm
* a gcm file containing extra information
*/
public GeneticNetwork(HashMap<String, SpeciesInterface> species,
HashMap<String, SpeciesInterface> stateMap,
HashMap<String, Promoter> promoters, GCMFile gcm) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
this.species = species;
this.stateMap = stateMap;
this.promoters = promoters;
this.properties = gcm;
AbstractPrintVisitor.setGCMFile(gcm);
initialize();
}
public void buildTemplate(HashMap<String, SpeciesInterface> species,
HashMap<String, Promoter> promoters, String gcm, String filename) {
GCMFile file = new GCMFile(currentRoot);
file.load(currentRoot+gcm);
AbstractPrintVisitor.setGCMFile(file);
setSpecies(species);
setPromoters(promoters);
SBMLDocument document = new SBMLDocument(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
currentDocument = document;
Model m = document.createModel();
document.setModel(m);
Utility.addCompartments(document, compartment);
document.getModel().getCompartment(compartment).setSize(1);
SBMLWriter writer = new SBMLWriter();
printSpecies(document);
printOnlyPromoters(document);
try {
PrintStream p = new PrintStream(new FileOutputStream(filename));
m.setName("Created from " + gcm);
m.setId(new File(filename).getName().replace(".xml", ""));
p.print(writer.writeToString(document));
p.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Loads in a properties file
*
* @param filename
* the file to load
*/
public void loadProperties(GCMFile gcm) {
properties = gcm;
dimerizationAbstraction = gcm.getDimAbs();
biochemicalAbstraction = gcm.getBioAbs();
}
public void setSBMLFile(String file) {
sbmlDocument = file;
}
public void setSBML(SBMLDocument doc) {
document = doc;
}
/**
* Outputs the network to an SBML file
*
* @param filename
* @return the sbml document
*/
public SBMLDocument outputSBML(String filename) {
SBMLDocument document = new SBMLDocument(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
currentDocument = document;
Model m = document.createModel();
document.setModel(m);
Utility.addCompartments(document, compartment);
document.getModel().getCompartment(compartment).setSize(1);
return outputSBML(filename, document);
}
public SBMLDocument outputSBML(String filename, SBMLDocument document) {
try {
Model m = document.getModel();
//checkConsistancy(document);
SBMLWriter writer = new SBMLWriter();
//printParameters(document);
printSpecies(document);
printPromoters(document);
printRNAP(document);
printDecay(document);
// System.out.println(counter++);
//checkConsistancy(document);
if (!dimerizationAbstraction) {
printDimerization(document);
}
if (!biochemicalAbstraction) {
printBiochemical(document);
}
// System.out.println(counter++);
//checkConsistancy(document);
printPromoterProduction(document);
// System.out.println(counter++);
//checkConsistancy(document);
printPromoterBinding(document);
// System.out.println(counter++);
//checkConsistancy(document);
//printComponents(document, filename);
PrintStream p = new PrintStream(new FileOutputStream(filename));
m.setName("Created from " + new File(filename).getName().replace("xml", "gcm"));
m.setId(new File(filename).getName().replace(".xml", ""));
p.print(writer.writeToString(document));
p.close();
return document;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Unable to output to SBML");
}
}
/**
* Merges an SBML file network to an SBML file
*
* @param filename
* @return the sbml document
*/
public SBMLDocument mergeSBML(String filename) {
try {
if (document == null) {
if (sbmlDocument.equals("")) {
return outputSBML(filename);
}
SBMLDocument document = BioSim.readSBML(currentRoot + sbmlDocument);
// checkConsistancy(document);
currentDocument = document;
return outputSBML(filename, document);
}
else {
currentDocument = document;
return outputSBML(filename, document);
}
}
catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Unable to output to SBML");
}
}
/**
* Merges an SBML file network to an SBML file
*
* @param filename
* @return the sbml document
*/
public SBMLDocument mergeSBML(String filename, SBMLDocument document) {
try {
currentDocument = document;
return outputSBML(filename, document);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Unable to output to SBML");
}
}
/**
* Prints the parameters to the SBMLDocument
* @param document the document to print to
*/
private void printParameters(SBMLDocument document) {
if (properties != null) {
for (String s : properties.getGlobalParameters().keySet()) {
String param = properties.getParameter(s);
//Utility.addGlobalParameter(document, new Parameter())
}
}
}
/**
* Prints each promoter binding
*
* @param document
* the SBMLDocument to print to
*/
private void printPromoterBinding(SBMLDocument document) {
double rnap = .033;
double rep = .05;
double act = .0033;
double kdimer = .05;
double kbio = .05;
double kcoop = 1;
double dimer = 1;
if (properties != null) {
kbio = Double.parseDouble(properties
.getParameter(GlobalConstants.KBIO_STRING));
kdimer = Double.parseDouble(properties
.getParameter(GlobalConstants.KASSOCIATION_STRING));
rnap = Double.parseDouble(properties
.getParameter(GlobalConstants.RNAP_BINDING_STRING));
rep = Double.parseDouble(properties
.getParameter(GlobalConstants.KREP_STRING));
act = Double.parseDouble(properties
.getParameter(GlobalConstants.KACT_STRING));
kcoop = Double.parseDouble(properties
.getParameter(GlobalConstants.COOPERATIVITY_STRING));
dimer = Double.parseDouble(properties
.getParameter(GlobalConstants.MAX_DIMER_STRING));
}
for (Promoter p : promoters.values()) {
// First setup RNAP binding
if (p.getOutputs().size()==0) continue;
org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
r.setId("R_RNAP_" + p.getId());
r.addReactant(Utility.SpeciesReference("RNAP", 1));
r.addReactant(Utility.SpeciesReference(p.getId(), 1));
r.addProduct(Utility.SpeciesReference("RNAP_" + p.getId(), 1));
r.setReversible(true);
KineticLaw kl = r.createKineticLaw();
kl.addParameter(Utility.Parameter("kf", rnap, getMoleTimeParameter(2)));
kl.addParameter(Utility.Parameter("kr", 1, getMoleTimeParameter(1)));
kl.setFormula("kf*" + "RNAP*" + p.getId() + "-kr*RNAP_"
+ p.getId());
Utility.addReaction(document, r);
// Next setup activated binding
PrintActivatedBindingVisitor v = new PrintActivatedBindingVisitor(
document, p, act, kdimer, kcoop, kbio,
dimer);
v.setBiochemicalAbstraction(biochemicalAbstraction);
v.setDimerizationAbstraction(dimerizationAbstraction);
v.setCooperationAbstraction(cooperationAbstraction);
v.run();
// Next setup repression binding
p.getRepressors();
PrintRepressionBindingVisitor v2 = new PrintRepressionBindingVisitor(
document, p, rep, kdimer, kcoop, kbio,
dimer);
v2.setBiochemicalAbstraction(biochemicalAbstraction);
v2.setDimerizationAbstraction(dimerizationAbstraction);
v2.setCooperationAbstraction(cooperationAbstraction);
v2.run();
}
}
/**
* Prints each promoter production values
*
* @param document
* the SBMLDocument to print to
*/
private void printPromoterProduction(SBMLDocument document) {
double basal = .0001;
double koc = .25;
int stoc = 1;
double act = .25;
if (properties != null) {
basal = Double.parseDouble(properties
.getParameter(GlobalConstants.KBASAL_STRING));
koc = Double.parseDouble(properties
.getParameter(GlobalConstants.OCR_STRING));
stoc = Integer.parseInt(properties
.getParameter(GlobalConstants.STOICHIOMETRY_STRING));
act = Double.parseDouble(properties
.getParameter(GlobalConstants.ACTIVED_STRING));
}
for (Promoter p : promoters.values()) {
if (p.getOutputs().size()==0) continue;
if (p.getActivators().size() > 0 && p.getRepressors().size() == 0) {
org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
r.setId("R_basal_production_" + p.getId());
r.addModifier(Utility.ModifierSpeciesReference("RNAP_" + p.getId()));
for (SpeciesInterface species : p.getOutputs()) {
r.addProduct(Utility.SpeciesReference(species.getId(), stoc));
}
r.setReversible(false);
r.setFast(false);
KineticLaw kl = r.createKineticLaw();
if (p.getProperty(GlobalConstants.KBASAL_STRING) != null) {
kl.addParameter(Utility.Parameter("basal", Double.parseDouble(p
.getProperty(GlobalConstants.KBASAL_STRING)),
getMoleTimeParameter(1)));
} else {
kl.addParameter(Utility.Parameter("basal", basal,
getMoleTimeParameter(1)));
}
kl.setFormula("basal*" + "RNAP_" + p.getId());
Utility.addReaction(document, r);
PrintActivatedProductionVisitor v = new PrintActivatedProductionVisitor(
document, p, p.getActivators(), act, stoc);
v.run();
} else if (p.getActivators().size() == 0
&& p.getRepressors().size() >= 0) {
org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
r.setId("R_production_" + p.getId());
r.addModifier(Utility.ModifierSpeciesReference("RNAP_" + p.getId()));
for (SpeciesInterface species : p.getOutputs()) {
r.addProduct(Utility.SpeciesReference(species.getId(), stoc));
}
r.setReversible(false);
r.setFast(false);
KineticLaw kl = r.createKineticLaw();
if (p.getProperty(GlobalConstants.OCR_STRING) != null) {
kl.addParameter(Utility.Parameter("koc", Double.parseDouble(p
.getProperty(GlobalConstants.OCR_STRING)),
getMoleTimeParameter(1)));
} else {
kl.addParameter(Utility.Parameter("koc", koc,
getMoleTimeParameter(1)));
}
kl.setFormula("koc*" + "RNAP_" + p.getId());
Utility.addReaction(document, r);
} else {
// TODO: Should ask Chris how to handle
// Both activated and repressed
org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
r.setId("R_basal_production_" + p.getId());
r.addModifier(Utility.ModifierSpeciesReference("RNAP_" + p.getId()));
for (SpeciesInterface species : p.getOutputs()) {
r.addProduct(Utility.SpeciesReference(species.getId(), stoc));
}
r.setReversible(false);
r.setFast(false);
KineticLaw kl = r.createKineticLaw();
if (p.getProperty(GlobalConstants.KBASAL_STRING) != null) {
kl.addParameter(Utility.Parameter("basal", Double.parseDouble(p
.getProperty(GlobalConstants.KBASAL_STRING)),
getMoleTimeParameter(1)));
} else {
kl.addParameter(Utility.Parameter("basal", basal,
getMoleTimeParameter(1)));
}
kl.setFormula("basal*" + "RNAP_" + p.getId());
Utility.addReaction(document, r);
PrintActivatedProductionVisitor v = new PrintActivatedProductionVisitor(
document, p, p.getActivators(), act, stoc);
v.run();
}
}
}
/**
* Prints the decay reactions
*
* @param document
* the SBML document
*/
private void printDecay(SBMLDocument document) {
// Check to see if number of promoters is a property, if not, default to
double decay = .0075;
if (properties != null) {
decay = Double.parseDouble(properties
.getParameter(GlobalConstants.KDECAY_STRING));
}
PrintDecaySpeciesVisitor visitor = new PrintDecaySpeciesVisitor(
document, species.values(), decay);
visitor.setBiochemicalAbstraction(biochemicalAbstraction);
visitor.setDimerizationAbstraction(dimerizationAbstraction);
visitor.run();
}
/**
* Prints the dimerization reactions
*
* @param document
* the SBML document to print to
*/
private void printDimerization(SBMLDocument document) {
double kdimer = .05;
double dimer = 2;
if (properties != null) {
kdimer = Double.parseDouble(properties
.getParameter(GlobalConstants.KASSOCIATION_STRING));
dimer = Double.parseDouble(properties
.getParameter(GlobalConstants.MAX_DIMER_STRING));
}
PrintDimerizationVisitor visitor = new PrintDimerizationVisitor(
document, species.values(), kdimer, dimer);
visitor.setBiochemicalAbstraction(biochemicalAbstraction);
visitor.setDimerizationAbstraction(dimerizationAbstraction);
visitor.run();
}
private void printBiochemical(SBMLDocument document) {
double kbio = .05;
if (properties != null) {
kbio = Double.parseDouble(properties
.getParameter(GlobalConstants.KBIO_STRING));
}
PrintBiochemicalVisitor visitor = new PrintBiochemicalVisitor(document,
species.values(), kbio);
visitor.setBiochemicalAbstraction(biochemicalAbstraction);
visitor.setDimerizationAbstraction(dimerizationAbstraction);
visitor.run();
}
/**
* Prints the species in the network
*
* @param document
* the SBML document
*/
private void printSpecies(SBMLDocument document) {
double init = 0;
if (properties != null) {
init = Double.parseDouble(properties
.getParameter(GlobalConstants.INITIAL_STRING));
}
PrintSpeciesVisitor visitor = new PrintSpeciesVisitor(document, species
.values(), compartment, init);
visitor.setBiochemicalAbstraction(biochemicalAbstraction);
visitor.setDimerizationAbstraction(dimerizationAbstraction);
visitor.run();
}
private ASTNode updateMathVar(ASTNode math, String origVar, String newVar) {
String s = updateFormulaVar(myFormulaToString(math), origVar, newVar);
return myParseFormula(s);
}
private String myFormulaToString(ASTNode mathFormula) {
String formula = libsbml.formulaToString(mathFormula);
formula = formula.replaceAll("arccot", "acot");
formula = formula.replaceAll("arccoth", "acoth");
formula = formula.replaceAll("arccsc", "acsc");
formula = formula.replaceAll("arccsch", "acsch");
formula = formula.replaceAll("arcsec", "asec");
formula = formula.replaceAll("arcsech", "asech");
formula = formula.replaceAll("arccosh", "acosh");
formula = formula.replaceAll("arcsinh", "asinh");
formula = formula.replaceAll("arctanh", "atanh");
String newformula = formula.replaceFirst("00e", "0e");
while (!(newformula.equals(formula))) {
formula = newformula;
newformula = formula.replaceFirst("0e\\+", "e+");
newformula = newformula.replaceFirst("0e-", "e-");
}
formula = formula.replaceFirst("\\.e\\+", ".0e+");
formula = formula.replaceFirst("\\.e-", ".0e-");
return formula;
}
private String updateFormulaVar(String s, String origVar, String newVar) {
s = " " + s + " ";
s = s.replace(" " + origVar + " ", " " + newVar + " ");
s = s.replace(" " + origVar + "(", " " + newVar + "(");
s = s.replace("(" + origVar + ")", "(" + newVar + ")");
s = s.replace("(" + origVar + " ", "(" + newVar + " ");
s = s.replace("(" + origVar + ",", "(" + newVar + ",");
s = s.replace(" " + origVar + ")", " " + newVar + ")");
s = s.replace(" " + origVar + "^", " " + newVar + "^");
return s.trim();
}
private ASTNode myParseFormula(String formula) {
ASTNode mathFormula = libsbml.parseFormula(formula);
if (mathFormula == null)
return null;
setTimeAndTrigVar(mathFormula);
return mathFormula;
}
private void setTimeAndTrigVar(ASTNode node) {
if (node.getType() == libsbml.AST_NAME) {
if (node.getName().equals("t")) {
node.setType(libsbml.AST_NAME_TIME);
}
else if (node.getName().equals("time")) {
node.setType(libsbml.AST_NAME_TIME);
}
}
if (node.getType() == libsbml.AST_FUNCTION) {
if (node.getName().equals("acot")) {
node.setType(libsbml.AST_FUNCTION_ARCCOT);
}
else if (node.getName().equals("acoth")) {
node.setType(libsbml.AST_FUNCTION_ARCCOTH);
}
else if (node.getName().equals("acsc")) {
node.setType(libsbml.AST_FUNCTION_ARCCSC);
}
else if (node.getName().equals("acsch")) {
node.setType(libsbml.AST_FUNCTION_ARCCSCH);
}
else if (node.getName().equals("asec")) {
node.setType(libsbml.AST_FUNCTION_ARCSEC);
}
else if (node.getName().equals("asech")) {
node.setType(libsbml.AST_FUNCTION_ARCSECH);
}
else if (node.getName().equals("acosh")) {
node.setType(libsbml.AST_FUNCTION_ARCCOSH);
}
else if (node.getName().equals("asinh")) {
node.setType(libsbml.AST_FUNCTION_ARCSINH);
}
else if (node.getName().equals("atanh")) {
node.setType(libsbml.AST_FUNCTION_ARCTANH);
}
}
for (int c = 0; c < node.getNumChildren(); c++)
setTimeAndTrigVar(node.getChild(c));
}
private void updateVarId(boolean isSpecies, String origId, String newId, SBMLDocument document) {
if (origId.equals(newId))
return;
Model model = document.getModel();
for (int i = 0; i < model.getNumSpecies(); i++) {
org.sbml.libsbml.Species species = (org.sbml.libsbml.Species) model.getListOfSpecies().get(i);
if (species.getCompartment().equals(origId)) {
species.setCompartment(newId);
}
if (species.getSpeciesType().equals(origId)) {
species.setSpeciesType(newId);
}
}
for (int i = 0; i < model.getNumCompartments(); i++) {
org.sbml.libsbml.Compartment compartment = (org.sbml.libsbml.Compartment) model.getListOfCompartments().get(i);
if (compartment.getCompartmentType().equals(origId)) {
compartment.setCompartmentType(newId);
}
}
for (int i = 0; i < model.getNumReactions(); i++) {
org.sbml.libsbml.Reaction reaction = (org.sbml.libsbml.Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getProduct(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
specRef.getStoichiometryMath().setMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
}
}
}
if (isSpecies) {
for (int j = 0; j < reaction.getNumModifiers(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
ModifierSpeciesReference specRef = reaction.getModifier(j);
if (origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getReactant(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
specRef.getStoichiometryMath().setMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
}
}
}
reaction.getKineticLaw().setMath(
updateMathVar(reaction.getKineticLaw().getMath(), origId, newId));
}
if (model.getNumInitialAssignments() > 0) {
for (int i = 0; i < model.getNumInitialAssignments(); i++) {
InitialAssignment init = (InitialAssignment) model.getListOfInitialAssignments().get(i);
if (origId.equals(init.getSymbol())) {
init.setSymbol(newId);
}
init.setMath(updateMathVar(init.getMath(), origId, newId));
}
}
if (model.getNumRules() > 0) {
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) model.getListOfRules().get(i);
if (rule.isSetVariable() && origId.equals(rule.getVariable())) {
rule.setVariable(newId);
}
rule.setMath(updateMathVar(rule.getMath(), origId, newId));
}
}
if (model.getNumConstraints() > 0) {
for (int i = 0; i < model.getNumConstraints(); i++) {
Constraint constraint = (Constraint) model.getListOfConstraints().get(i);
constraint.setMath(updateMathVar(constraint.getMath(), origId, newId));
}
}
if (model.getNumEvents() > 0) {
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) model.getListOfEvents().get(i);
if (event.isSetTrigger()) {
event.getTrigger().setMath(updateMathVar(event.getTrigger().getMath(), origId, newId));
}
if (event.isSetDelay()) {
event.getDelay().setMath(updateMathVar(event.getDelay().getMath(), origId, newId));
}
for (int j = 0; j < event.getNumEventAssignments(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(origId)) {
ea.setVariable(newId);
}
if (ea.isSetMath()) {
ea.setMath(updateMathVar(ea.getMath(), origId, newId));
}
}
}
}
}
private void unionSBML(SBMLDocument mainDoc, SBMLDocument doc, String compName) {
Model m = doc.getModel();
for (int i = 0; i < m.getNumCompartmentTypes(); i ++) {
org.sbml.libsbml.CompartmentType c = m.getCompartmentType(i);
String newName = compName + "_" + c.getId();
updateVarId(false, c.getId(), newName, doc);
c.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumCompartmentTypes(); j ++) {
if (mainDoc.getModel().getCompartmentType(j).getId().equals(c.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addCompartmentType(c);
}
}
for (int i = 0; i < m.getNumCompartments(); i ++) {
org.sbml.libsbml.Compartment c = m.getCompartment(i);
String newName = compName + "_" + c.getId();
updateVarId(false, c.getId(), newName, doc);
c.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumCompartments(); j ++) {
if (mainDoc.getModel().getCompartment(j).getId().equals(c.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addCompartment(c);
}
}
for (int i = 0; i < m.getNumSpeciesTypes(); i ++) {
org.sbml.libsbml.SpeciesType s = m.getSpeciesType(i);
String newName = compName + "_" + s.getId();
updateVarId(false, s.getId(), newName, doc);
s.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumSpeciesTypes(); j ++) {
if (mainDoc.getModel().getSpeciesType(j).getId().equals(s.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addSpeciesType(s);
}
}
for (int i = 0; i < m.getNumSpecies(); i ++) {
Species spec = m.getSpecies(i);
if (!spec.getId().equals("RNAP")) {
String newName = compName + "_" + spec.getId();
for (Object port : properties.getComponents().get(compName).keySet()) {
if (spec.getId().equals((String) port)) {
newName = "_" + compName + "_" + properties.getComponents().get(compName).getProperty((String) port);
int removeDeg = -1;
for (int j = 0; j < m.getNumReactions(); j ++) {
org.sbml.libsbml.Reaction r = m.getReaction(j);
if (r.getId().equals("Degradation_" + spec.getId())) {
removeDeg = j;
}
}
if (removeDeg != -1) {
m.getListOfReactions().remove(removeDeg);
}
}
}
updateVarId(true, spec.getId(), newName, doc);
spec.setId(newName);
}
}
for (int i = 0; i < m.getNumSpecies(); i ++) {
Species spec = m.getSpecies(i);
if (spec.getId().startsWith("_" + compName + "_")) {
updateVarId(true, spec.getId(), spec.getId().substring(2 + compName.length()), doc);
spec.setId(spec.getId().substring(2 + compName.length()));
}
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumSpecies(); j ++) {
if (mainDoc.getModel().getSpecies(j).getId().equals(spec.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addSpecies(spec);
}
}
for (int i = 0; i < m.getNumParameters(); i ++) {
org.sbml.libsbml.Parameter p = m.getParameter(i);
String newName = compName + "_" + p.getId();
updateVarId(false, p.getId(), newName, doc);
p.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumParameters(); j ++) {
if (mainDoc.getModel().getParameter(j).getId().equals(p.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addParameter(p);
}
}
for (int i = 0; i < m.getNumReactions(); i ++) {
org.sbml.libsbml.Reaction r = m.getReaction(i);
String newName = compName + "_" + r.getId();
updateVarId(false, r.getId(), newName, doc);
r.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumReactions(); j ++) {
if (mainDoc.getModel().getReaction(j).getId().equals(r.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addReaction(r);
}
}
for (int i = 0; i < m.getNumInitialAssignments(); i ++) {
InitialAssignment init = (InitialAssignment) m.getListOfInitialAssignments().get(i);
mainDoc.getModel().addInitialAssignment(init);
}
for (int i = 0; i < m.getNumRules(); i++) {
org.sbml.libsbml.Rule r = m.getRule(i);
mainDoc.getModel().addRule(r);
}
for (int i = 0; i < m.getNumConstraints(); i++) {
Constraint constraint = (Constraint) m.getListOfConstraints().get(i);
mainDoc.getModel().addConstraint(constraint);
}
for (int i = 0; i < m.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) m.getListOfEvents().get(i);
String newName = compName + "_" + event.getId();
updateVarId(false, event.getId(), newName, doc);
event.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumEvents(); j ++) {
if (mainDoc.getModel().getEvent(j).getId().equals(event.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addEvent(event);
}
}
for (int i = 0; i < m.getNumUnitDefinitions(); i ++) {
UnitDefinition u = m.getUnitDefinition(i);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumUnitDefinitions(); j ++) {
if (mainDoc.getModel().getUnitDefinition(j).getId().equals(u.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addUnitDefinition(u);
}
}
for (int i = 0; i < m.getNumFunctionDefinitions(); i ++) {
FunctionDefinition f = m.getFunctionDefinition(i);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumFunctionDefinitions(); j ++) {
if (mainDoc.getModel().getFunctionDefinition(j).getId().equals(f.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addFunctionDefinition(f);
}
}
}
private void printComponents(SBMLDocument document, String filename) {
for (String s : properties.getComponents().keySet()) {
GCMParser parser = new GCMParser(currentRoot + separator +
properties.getComponents().get(s).getProperty("gcm"));
parser.setParameters(properties.getParameters());
GeneticNetwork network = parser.buildNetwork();
SBMLDocument d = network.mergeSBML(filename);
unionSBML(document, d, s);
}
}
/**
* Prints the promoters in the network
*
* @param document
* the SBML document
*/
private void printPromoters(SBMLDocument document) {
// Check to see if number of promoters is a property, if not, default to
String numPromoters = "1";
if (properties != null) {
numPromoters = properties
.getParameter(GlobalConstants.PROMOTER_COUNT_STRING);
}
for (Promoter promoter : promoters.values()) {
if (promoter.getOutputs().size()==0) continue;
// First print out the promoter, and promoter bound to RNAP
String tempPromoters = numPromoters;
if (promoter.getProperty(GlobalConstants.PROMOTER_COUNT_STRING) != null) {
tempPromoters = promoter
.getProperty(GlobalConstants.PROMOTER_COUNT_STRING);
}
Species s = Utility.makeSpecies(promoter.getId(), compartment,
Double.parseDouble(tempPromoters));
if ((promoter.getProperties() != null) &&
(promoter.getProperties().containsKey(GlobalConstants.NAME))) {
s.setName(promoter.getProperty(GlobalConstants.NAME));
}
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
s = Utility.makeSpecies("RNAP_" + promoter.getId(), compartment,
0);
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
// Now cycle through all activators and repressors and add those
// bindings
for (SpeciesInterface species : promoter.getActivators()) {
s = Utility.makeSpecies("RNAP_" + promoter.getId() + "_"
+ species.getId(), compartment, 0);
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
}
for (SpeciesInterface species : promoter.getRepressors()) {
s = Utility.makeSpecies("bound_" + promoter.getId() + "_"
+ species.getId(), compartment, 0);
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
}
}
}
/**
* Prints the promoters in the network
*
* @param document
* the SBML document
*/
private void printOnlyPromoters(SBMLDocument document) {
// Check to see if number of promoters is a property, if not, default to
String numPromoters = "1";
if (properties != null) {
numPromoters = properties
.getParameter(GlobalConstants.PROMOTER_COUNT_STRING);
}
for (Promoter promoter : promoters.values()) {
// First print out the promoter, and promoter bound to RNAP
String tempPromoters = numPromoters;
if (promoter.getProperty(GlobalConstants.PROMOTER_COUNT_STRING) != null) {
tempPromoters = promoter
.getProperty(GlobalConstants.PROMOTER_COUNT_STRING);
}
Species s = Utility.makeSpecies(promoter.getId(), compartment,
Double.parseDouble(tempPromoters));
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
}
}
/**
* Prints the RNAP molecule to the document
*
* @param document
* the SBML document
*/
private void printRNAP(SBMLDocument document) {
double rnap = 30;
if (properties != null) {
rnap = Double.parseDouble(properties
.getParameter(GlobalConstants.RNAP_STRING));
}
Species s = Utility.makeSpecies("RNAP", compartment, rnap);
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
}
/**
* Initializes the network
*
*/
private void initialize() {
buildDimers();
buildPromoters();
buildBiochemical();
}
/**
* Configurates the promoters
*
*/
private void buildPromoters() {
for (Promoter promoter : promoters.values()) {
for (Reaction reaction : promoter.getActivatingReactions()) {
if (!reaction.isBiochemical() && reaction.getDimer() <= 1 &&
!reaction.getInputState().equals("none")) {
promoter.addActivator(stateMap
.get(reaction.getInputState()));
promoter.addToReactionMap(stateMap.get(reaction
.getInputState()), reaction);
}
if (!reaction.getOutputState().equals("none")) {
promoter.addOutput(stateMap.get(reaction.getOutputState()));
}
}
for (Reaction reaction : promoter.getRepressingReactions()) {
if (!reaction.isBiochemical() && reaction.getDimer() <= 1 &&
!reaction.getInputState().equals("none")) {
promoter.addRepressor(stateMap
.get(reaction.getInputState()));
promoter.addToReactionMap(stateMap.get(reaction
.getInputState()), reaction);
}
if (!reaction.getOutputState().equals("none")) {
promoter.addOutput(stateMap.get(reaction.getOutputState()));
}
}
}
}
/**
* Builds the dimer list from reactions and species and adds it to the
* promoter as input.
*/
private void buildDimers() {
// First go through all species list and add all dimers found to hashMap
HashMap<String, SpeciesInterface> dimers = new HashMap<String, SpeciesInterface>();
/*for (SpeciesInterface specie : species.values()) {
int dimerValue = 1;
if (properties != null) {
dimerValue = (int) Integer.parseInt((properties
.getParameter(GlobalConstants.MAX_DIMER_STRING)));
}
if (specie.getProperty(GlobalConstants.MAX_DIMER_STRING) != null) {
dimerValue = (int) Integer.parseInt(specie
.getProperty(GlobalConstants.MAX_DIMER_STRING));
}
if (dimerValue >= 2) {
DimerSpecies dimer = new DimerSpecies(specie, specie.getProperties());
dimer.addProperty(GlobalConstants.KDECAY_STRING, "0");
dimers.put(dimer.getId(), dimer);
}
}*/
// Now go through reaction list to see if any are missed
for (Promoter promoter : promoters.values()) {
for (Reaction reaction : promoter.getActivatingReactions()) {
if (reaction.getDimer() > 1) {
SpeciesInterface specie = stateMap.get(reaction.getInputState());
specie.addProperty(GlobalConstants.MAX_DIMER_STRING, "" + reaction.getDimer());
DimerSpecies dimer = new DimerSpecies(specie, specie.getProperties());
dimers.put(dimer.getId(), dimer);
promoter.addToReactionMap(dimer, reaction);
promoter.getActivators().add(dimer);
}
}
for (Reaction reaction : promoter.getRepressingReactions()) {
if (reaction.getDimer() > 1) {
SpeciesInterface specie = stateMap.get(reaction.getInputState());
specie.addProperty(GlobalConstants.MAX_DIMER_STRING, "" + reaction.getDimer());
DimerSpecies dimer = new DimerSpecies(specie, specie.getProperties());
dimers.put(dimer.getId(), dimer);
promoter.addToReactionMap(dimer, reaction);
promoter.getRepressors().add(dimer);
}
}
}
// Now put dimers back into network
for (SpeciesInterface specie : dimers.values()) {
species.put(specie.getId(), specie);
}
}
/**
* Builds the biochemical species, and adds it to the promoter as input
*/
private void buildBiochemical() {
// Cycle through each promoter
for (Promoter promoter : promoters.values()) {
// keep track of all activating and repressing reactions in separate
// lists
ArrayList<SpeciesInterface> biochem = new ArrayList<SpeciesInterface>();
ArrayList<Reaction> reactions = new ArrayList<Reaction>();
for (Reaction reaction : promoter.getActivatingReactions()) {
if (reaction.isBiochemical()) {
reactions.add(reaction);
SpeciesInterface bioSpecie = stateMap.get(reaction.getInputState());
//bioSpecie.addProperty(GlobalConstants.KBIO_STRING, "" + reaction.getProperty(GlobalConstants.KBIO_STRING));
biochem.add(bioSpecie);
}
}
if (biochem.size() == 1) {
throw new IllegalStateException(
"Must have more than 1 biochemical reaction");
} else if (biochem.size() >= 2) {
BiochemicalSpecies bio = new BiochemicalSpecies(biochem, biochem.get(0).getProperties());
promoter.addActivator(bio);
for (Reaction reaction : reactions) {
promoter.addToReactionMap(bio, reaction);
}
bio.addProperty(GlobalConstants.KDECAY_STRING, "0");
species.put(bio.getId(), bio);
}
biochem = new ArrayList<SpeciesInterface>();
reactions = new ArrayList<Reaction>();
for (Reaction reaction : promoter.getRepressingReactions()) {
if (reaction.isBiochemical()) {
reactions.add(reaction);
SpeciesInterface bioSpecie = stateMap.get(reaction.getInputState());
//bioSpecie.addProperty(GlobalConstants.KBIO_STRING, "" + reaction.getProperty(GlobalConstants.KBIO_STRING));
biochem.add(bioSpecie);
}
}
if (biochem.size() == 1) {
throw new IllegalStateException(
"Must have more than 1 biochemical reaction");
} else if (biochem.size() >= 2) {
BiochemicalSpecies bio = new BiochemicalSpecies(biochem, biochem.get(0).getProperties());
for (Reaction reaction : reactions) {
promoter.addToReactionMap(bio, reaction);
}
promoter.addRepressor(bio);
bio.addProperty(GlobalConstants.KDECAY_STRING, "0");
species.put(bio.getId(), bio);
}
}
}
public HashMap<String, SpeciesInterface> getSpecies() {
return species;
}
public void setSpecies(HashMap<String, SpeciesInterface> species) {
this.species = species;
}
public HashMap<String, SpeciesInterface> getStateMap() {
return stateMap;
}
public void setStateMap(HashMap<String, SpeciesInterface> stateMap) {
this.stateMap = stateMap;
}
public HashMap<String, Promoter> getPromoters() {
return promoters;
}
public void setPromoters(HashMap<String, Promoter> promoters) {
this.promoters = promoters;
}
public GCMFile getProperties() {
return properties;
}
public void setProperties(GCMFile properties) {
this.properties = properties;
}
/**
* Checks the consistancy of the document
*
* @param doc
* the SBML document to check
*/
private void checkConsistancy(SBMLDocument doc) {
if (doc.checkConsistency() > 0) {
for (int i = 0; i < doc.getNumErrors(); i++) {
System.out.println(doc.getError(i).getMessage());
}
}
}
private String sbmlDocument = "";
private SBMLDocument document = null;
private static SBMLDocument currentDocument = null;
private static String currentRoot = "";
private boolean biochemicalAbstraction = false;
private boolean dimerizationAbstraction = false;
private boolean cooperationAbstraction = false;
private HashMap<String, SpeciesInterface> species = null;
private HashMap<String, SpeciesInterface> stateMap = null;
private HashMap<String, Promoter> promoters = null;
private GCMFile properties = null;
private String compartment = "default";
/**
* Returns the curent SBML document being built
*
* @return the curent SBML document being built
*/
public static SBMLDocument getCurrentDocument() {
return currentDocument;
}
/**
* Sets the current root
* @param root the root directory
*/
public static void setRoot(String root) {
currentRoot = root;
}
public static String getUnitString(ArrayList<String> unitNames,
ArrayList<Integer> exponents, ArrayList<Integer> multiplier,
Model model) {
// First build the name of the unit and see if it exists, start by
// sorting the units to build a unique string
for (int i = 0; i < unitNames.size(); i++) {
for (int j = i; j > 0; j
if (unitNames.get(j - 1).compareTo(unitNames.get(i)) > 0) {
Integer tempD = multiplier.get(j);
Integer tempI = exponents.get(j);
String tempS = unitNames.get(j);
multiplier.set(j, multiplier.get(j - 1));
unitNames.set(j, unitNames.get(j - 1));
exponents.set(j, exponents.get(j - 1));
multiplier.set(j - 1, tempD);
unitNames.set(j - 1, tempS);
exponents.set(j - 1, tempI);
}
}
}
UnitDefinition t = new UnitDefinition(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
String name = "u_";
for (int i = 0; i < unitNames.size(); i++) {
String sign = "";
if (exponents.get(i).intValue() < 0) {
sign = "n";
}
name = name + multiplier.get(i) + "_" + unitNames.get(i) + "_"
+ sign + Math.abs(exponents.get(i)) + "_";
Unit u = t.createUnit();
u.setKind(libsbml.UnitKind_forName(unitNames.get(i)));
u.setExponent(exponents.get(i).intValue());
u.setMultiplier(multiplier.get(i).intValue());
u.setScale(0);
}
name = name.substring(0, name.length() - 1);
t.setId(name);
if (model.getUnitDefinition(name) == null) {
model.addUnitDefinition(t);
}
return name;
}
/**
* Returns a unit name for a parameter based on the number of molecules
* involved
*
* @param numMolecules
* the number of molecules involved
* @return a unit name
*/
public static String getMoleTimeParameter(int numMolecules) {
ArrayList<String> unitS = new ArrayList<String>();
ArrayList<Integer> unitE = new ArrayList<Integer>();
ArrayList<Integer> unitM = new ArrayList<Integer>();
if (numMolecules > 1) {
unitS.add("mole");
unitE.add(new Integer(-(numMolecules - 1)));
unitM.add(new Integer(0));
}
unitS.add("second");
unitE.add(new Integer(-1));
unitM.add(new Integer(0));
return GeneticNetwork.getUnitString(unitS, unitE, unitM,
currentDocument.getModel());
}
/**
* Returns a unit name for a parameter based on the number of molecules
* involved
*
* @param numMolecules
* the number of molecules involved
* @return a unit name
*/
public static String getMoleParameter(int numMolecules) {
ArrayList<String> unitS = new ArrayList<String>();
ArrayList<Integer> unitE = new ArrayList<Integer>();
ArrayList<Integer> unitM = new ArrayList<Integer>();
unitS.add("mole");
unitE.add(new Integer(-(numMolecules - 1)));
unitM.add(new Integer(0));
return GeneticNetwork.getUnitString(unitS, unitE, unitM,
currentDocument.getModel());
}
public static String getMoleParameter(String numMolecules) {
return getMoleParameter(Integer.parseInt(numMolecules));
}
} |
package wombat.scheme;
import java.io.*;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import wombat.scheme.util.InteropAPI;
/**
* Class to wrap Petite bindings.
*/
public class Petite {
static final boolean DEBUG_INTEROP = false;
/**
* Run from the command line, providing a REPL.
*
* @param args
* Ignored.
* @throws URISyntaxException
* If we botched the files from the JAR.
*/
public static void main(String[] args) throws URISyntaxException {
try {
final Petite p = new Petite();
final Scanner s = new Scanner(System.in);
Thread t = new Thread("Petite REPL") {
public void run() {
while (p.isRunning()) {
if (p.hasOutput()) {
System.out.println(p.getOutput());
System.out.print(">> ");
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
};
t.setDaemon(true);
t.start();
while (p.isRunning()) {
if (p.isReady() && s.hasNextLine()) {
String cmd = s.nextLine();
p.sendCommand(cmd);
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
static final String os = System.getProperty("os.name").toLowerCase();
static final boolean IsWindows = os.indexOf("win") != -1;
static final boolean IsOSX = os.indexOf("mac") != -1;
static final boolean IsLinux = (os.indexOf("nux") != -1) || (os.indexOf("nix") != -1);
static final boolean Is64Bit = System.getProperty("os.arch").indexOf("64") != -1;
static final char Prompt1 = '|';
static final char Prompt2 = '`';
static final char Interop = '!';
boolean RestartOnCollapse;
boolean Running;
boolean Starting;
boolean SeenPrompt1;
boolean Ready;
boolean InInterop;
StringBuffer Buffer;
StringBuffer InteropBuffer;
Lock BufferLock;
Writer ToPetite;
Reader FromPetite;
Process NativeProcess;
Thread FromPetiteThread;
// The root is either this directory or a nested 'lib' directory.
static File[] searchDirs;
static {
try {
searchDirs = new File[] {
new File("").getCanonicalFile(),
new File(new File("").getCanonicalFile(), "lib")
.getCanonicalFile(),
new File(Petite.class.getProtectionDomain().getCodeSource()
.getLocation().toURI().getPath())
.getCanonicalFile(),
new File(new File(Petite.class.getProtectionDomain()
.getCodeSource().getLocation().toURI().getPath()),
"lib").getCanonicalFile(),
new File(Petite.class.getProtectionDomain().getCodeSource()
.getLocation().toURI().getPath()).getParentFile()
.getCanonicalFile(),
new File(
new File(Petite.class.getProtectionDomain()
.getCodeSource().getLocation().toURI()
.getPath()).getParentFile(), "lib")
.getCanonicalFile(), };
} catch (IOException ex) {
} catch (URISyntaxException e) {
}
};
/**
* Create a new Petite thread.
*
* @throws IOException
* If we fail to access the Petite process.
* @throws URISyntaxException
* If we have problems getting the path from a JAR file.
*/
public Petite() throws IOException, URISyntaxException {
// Connect to an initial Petite session.
connect();
}
/**
* (Re)connect the Petite process.
*
* @throws IOException
* If we couldn't connect.
* @throws URISyntaxException
* If we have problems getting the path from a JAR file.
*/
private void connect() throws IOException, URISyntaxException {
System.err.println("Petite connecting");
// Reset the wrapper state (necessary in the case of a reconnect).
Starting = true;
SeenPrompt1 = false;
Ready = false;
Running = true;
InInterop = false;
RestartOnCollapse = true;
if (Buffer == null)
Buffer = new StringBuffer();
else
Buffer.delete(0, Buffer.length());
if (InteropBuffer == null)
InteropBuffer = new StringBuffer();
else
InteropBuffer.delete(0, InteropBuffer.length());
BufferLock = new ReentrantLock();
// Find the correct Petite directory.
File pdir = null;
for (File dir : searchDirs) {
System.out.println("Looking in " + dir + " for petite.");
if (dir != null && dir.exists() && dir.isDirectory()) {
for (String path : dir.list()) {
if (path.startsWith("petite") && path.endsWith(IsWindows ? "win" : IsOSX ? "osx" : IsLinux ? "linux" : "unknown")) {
pdir = new File(dir, path);
System.out.println("Found: " + pdir);
break;
}
}
}
if (pdir != null)
break;
}
// If it didn't we may have to look for zip files.
if (pdir == null) {
System.out.println("Petite not find, looking for an archive.");
for (File dir : searchDirs) {
System.out
.println("Looking in " + dir + " for petite archive.");
if (dir != null && dir.exists() && dir.isDirectory()) {
for (String path : dir.list()) {
if (path.startsWith("petite")
&& path.endsWith((IsWindows ? "win"
: IsOSX ? "osx" : IsLinux ? "linux"
: "unknown")
+ ".zip")) {
ZipFile zip = new ZipFile(new File(dir, path));
System.out.println("Found: " + zip);
@SuppressWarnings("unchecked")
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip
.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.isDirectory()) {
System.out.println("\tunzipping: "
+ entry.getName());
new File(dir, entry.getName())
.getCanonicalFile().mkdirs();
} else {
System.out.println("\tunzipping: "
+ entry.getName());
new File(dir, entry.getName())
.getCanonicalFile().getParentFile()
.mkdirs();
File targetFile = new File(dir,
entry.getName());
InputStream in = zip.getInputStream(entry);
OutputStream out = new BufferedOutputStream(
new FileOutputStream(targetFile));
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) >= 0)
out.write(buffer, 0, len);
in.close();
out.close();
targetFile.setExecutable(true);
}
}
zip.close();
// Try again.
connect();
return;
}
}
}
}
}
// If we made it this far without a directory, something broke. :(
if (pdir == null)
throw new IOException("Unable to find Petite directory.");
String petiteBinary = null;
String petiteBoot = null;
if (IsWindows) {
petiteBinary = "petite.exe";
petiteBoot = "petite.boot";
} else {
if (Is64Bit) {
petiteBinary = "petite64";
petiteBoot = "petite64.boot";
} else {
petiteBinary = "petite";
petiteBoot = "petite.boot";
}
}
System.out.println("Binary: " + petiteBinary + ", Boot: " + petiteBoot);
// Create the process builder.
ProcessBuilder pb = new ProcessBuilder(
new File(pdir, petiteBinary).getCanonicalPath(),
"-b",
new File(pdir, petiteBoot).getCanonicalPath()
);
pb.directory(pdir.getParentFile().getParentFile());
pb.redirectErrorStream(true);
// Start the process.
NativeProcess = pb.start();
// Set up the print writer.
ToPetite = new PrintWriter(NativeProcess.getOutputStream());
FromPetite = new InputStreamReader(NativeProcess.getInputStream());
// Immediately send the command to reset the prompt.
reset();
// Create a listener thread.
if (FromPetiteThread == null) {
FromPetiteThread = new PetiteIOThread();
FromPetiteThread.setDaemon(true);
FromPetiteThread.start();
}
// Show down the thread when done.
Runtime.getRuntime().addShutdownHook(new Thread("Petite Shutdown") {
public void run() {
NativeProcess.destroy();
}
});
}
/**
* Reset Petite's environment.
*/
public void reset() {
// Actually clear the environment
sendCommand("(interaction-environment (copy-environment (scheme-environment)
// So that (eq? 'A 'a) =>
sendCommand("(case-sensitive
// So that gensyms look at least semi-sane (it's not like anyone will
// need them)
sendCommand("(print-gensym
// To test infinite loops
sendCommand("(define (omega) ((lambda (x) (x x)) (lambda (x) (x x))))");
// Fix error message that give define/lambda names
sendCommand("(import (wombat define))");
// Reset the library directories.
sendCommand("(library-directories '((\"lib\" . \"lib\") (\".\" . \".\") (\"..\" . \"..\") (\"dist\" . \"dist\") (\"dist/lib\" . \"dist/lib\")))");
// Make sure that the prompt is set as we want it
sendCommand("(waiter-prompt-string \"|`\")");
}
/**
* Check if the process is ready.
*
* @return If the process is ready.
*/
public boolean isReady() {
return Ready;
}
/**
* Check if the process is still running.
*
* @return If the process is still running.
*/
public boolean isRunning() {
return Running;
}
/**
* Stop the running process.
*
* @throws IOException
* If we cannot connect.
* @throws URISyntaxException
* Botched file from JAR.
*/
public void stop() throws IOException, URISyntaxException {
System.err.println("Petite stopping");
// Shut down the old connection.
RestartOnCollapse = false;
Ready = false;
BufferLock.lock();
Buffer.delete(0, Buffer.length());
BufferLock.unlock();
NativeProcess.destroy();
try {
NativeProcess.waitFor();
} catch (InterruptedException e) {
}
}
/**
* Stop and restart.
*
* @throws IOException
* If we cannot connect.
* @throws URISyntaxException
* Botched file from JAR.
*/
public void restart() throws IOException, URISyntaxException {
System.err.println("Petite restarting");
stop();
connect();
}
/**
* If the output buffer has any content.
*
* @return True or false.
*/
public boolean hasOutput() {
return !Starting && (Buffer.length() > 0);
}
/**
* Get the contents of the output buffer.
*
* @return The output buffer.
*/
public String getOutput() {
BufferLock.lock();
String output = Buffer.toString();
Buffer.delete(0, Buffer.length());
BufferLock.unlock();
return output;
}
/**
* Send a command to the Petite process.
*
* @param cmd
* The command to send.
*/
public void sendCommand(String cmd) {
try {
// Swap out lambda character for string
cmd = cmd.replace("\u03BB", "lambda");
// Send it, make sure there's a newline.
// Use flush to force it.
ToPetite.write(cmd);
if (!cmd.endsWith("\n"))
ToPetite.write("\n");
ToPetite.flush();
Ready = false;
} catch (Exception e) {
System.err.println("Unable to execute command");
Buffer.append("\nException: Unable to execute command\n");
}
}
private final class PetiteIOThread extends Thread {
PetiteIOThread() { super("Petite IO"); }
public void run() {
char c;
try {
while (true) {
c = (char) FromPetite.read();
BufferLock.lock();
// Ignore end of file characters.
if (c == (char) 65535) {
}
// Potential start of a prompt.
else if (c == Prompt1) {
SeenPrompt1 = true;
}
// The whole prompt.
else if (SeenPrompt1 && c == Prompt2) {
SeenPrompt1 = false;
if (Starting) {
Buffer.delete(0, Buffer.length());
Starting = false;
}
Ready = true;
}
// Switch to interop mode on Prompt1 + Interop
else if (SeenPrompt1 && c == Interop) {
SeenPrompt1 = false;
if (InInterop) {
String[] parts = InteropBuffer.toString()
.split(" ", 2);
String key = parts[0];
String val = (parts.length > 1 ? parts[1]
: null);
if (DEBUG_INTEROP) System.out.println("calling interop: " + key + " with " + val); // debug
String result = InteropAPI
.interop(key, val);
if (DEBUG_INTEROP) System.out.println("interop returns: " + (result.length() > 10 ? result .subSequence(0, 10) + "..." : result)); // debug
if (result != null) {
ToPetite.write(result + " ");
ToPetite.flush();
}
if (DEBUG_INTEROP) System.out.println("exiting interop");
Ready = true;
InteropBuffer.delete(0, InteropBuffer.length());
InInterop = false;
} else {
if (DEBUG_INTEROP) System.out.println("entering interop"); // debug
InInterop = true;
}
}
// Thought it was a prompt, but we were wrong.
// Remember to store the first half of the prompt.
else if (SeenPrompt1) {
SeenPrompt1 = false;
if (InInterop) {
InteropBuffer.append(Prompt1);
InteropBuffer.append(c);
} else {
Buffer.append(Prompt1);
Buffer.append(c);
}
}
// Normal case, no new characters.
else {
if (InInterop) {
InteropBuffer.append(c);
} else {
Buffer.append(c);
}
}
BufferLock.unlock();
}
} catch (Exception e) {
System.err.println("Petite buffer is broken");
Buffer.append("\nException: Petite buffer is broken\n");
e.printStackTrace();
if (BufferLock.tryLock())
BufferLock.unlock();
// If we get here, Petite has collapsed.
// Destroy the connected process and restart.
if (RestartOnCollapse) {
try {
restart();
} catch (Exception e2) {
}
}
}
}
}
} |
package gcm2sbml.network;
import gcm2sbml.parser.CompatibilityFixer;
import gcm2sbml.parser.GCMFile;
import gcm2sbml.parser.GCMParser;
import gcm2sbml.util.GlobalConstants;
import gcm2sbml.util.Utility;
import gcm2sbml.visitor.AbstractPrintVisitor;
import gcm2sbml.visitor.PrintActivatedBindingVisitor;
import gcm2sbml.visitor.PrintActivatedProductionVisitor;
import gcm2sbml.visitor.PrintComplexVisitor;
import gcm2sbml.visitor.PrintDecaySpeciesVisitor;
import gcm2sbml.visitor.PrintRepressionBindingVisitor;
import gcm2sbml.visitor.PrintSpeciesVisitor;
import java.awt.Dimension;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.sbml.libsbml.ASTNode;
import org.sbml.libsbml.Constraint;
import org.sbml.libsbml.EventAssignment;
import org.sbml.libsbml.FunctionDefinition;
import org.sbml.libsbml.InitialAssignment;
import org.sbml.libsbml.KineticLaw;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.ModifierSpeciesReference;
import org.sbml.libsbml.Rule;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.SBMLWriter;
import org.sbml.libsbml.Species;
import org.sbml.libsbml.SpeciesReference;
import org.sbml.libsbml.Unit;
import org.sbml.libsbml.UnitDefinition;
import org.sbml.libsbml.libsbml;
import biomodelsim.BioSim;
/**
* This class represents a genetic network
*
* @author Nam
*
*/
public class GeneticNetwork {
private String separator;
/**
* Constructor
*
* @param species
* a hashmap of species
* @param stateMap
* a hashmap of statename to species name
* @param promoters
* a hashmap of promoters
*/
public GeneticNetwork(HashMap<String, SpeciesInterface> species,
HashMap<String, ArrayList<PartSpecies>> complexMap,
HashMap<String, Promoter> promoters) {
this(species, complexMap, promoters, null);
}
/**
* Constructor
*/
public GeneticNetwork() {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
}
/**
* Constructor
*
* @param species
* a hashmap of species
* @param stateMap
* a hashmap of statename to species name
* @param promoters
* a hashmap of promoters
* @param gcm
* a gcm file containing extra information
*/
public GeneticNetwork(HashMap<String, SpeciesInterface> species,
HashMap<String, ArrayList<PartSpecies>> complexMap,
HashMap<String, Promoter> promoters,
GCMFile gcm) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
this.species = species;
this.promoters = promoters;
this.complexMap = complexMap;
this.properties = gcm;
AbstractPrintVisitor.setGCMFile(gcm);
initialize();
}
public void buildTemplate(HashMap<String, SpeciesInterface> species,
HashMap<String, Promoter> promoters, String gcm, String filename) {
GCMFile file = new GCMFile(currentRoot);
file.load(currentRoot+gcm);
AbstractPrintVisitor.setGCMFile(file);
setSpecies(species);
setPromoters(promoters);
SBMLDocument document = new SBMLDocument(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
currentDocument = document;
Model m = document.createModel();
document.setModel(m);
Utility.addCompartments(document, compartment);
document.getModel().getCompartment(compartment).setSize(1);
SBMLWriter writer = new SBMLWriter();
printSpecies(document);
printOnlyPromoters(document);
try {
PrintStream p = new PrintStream(new FileOutputStream(filename));
m.setName("Created from " + gcm);
m.setId(new File(filename).getName().replace(".xml", ""));
m.setVolumeUnits("litre");
m.setSubstanceUnits("mole");
p.print(writer.writeToString(document));
p.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Loads in a properties file
*
* @param filename
* the file to load
*/
public void loadProperties(GCMFile gcm) {
properties = gcm;
complexAbstraction = gcm.getBioAbs();
}
public void setSBMLFile(String file) {
sbmlDocument = file;
}
public void setSBML(SBMLDocument doc) {
document = doc;
}
/**
* Outputs the network to an SBML file
*
* @param filename
* @return the sbml document
*/
public SBMLDocument outputSBML(String filename) {
SBMLDocument document = new SBMLDocument(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
currentDocument = document;
Model m = document.createModel();
document.setModel(m);
Utility.addCompartments(document, compartment);
document.getModel().getCompartment(compartment).setSize(1);
return outputSBML(filename, document);
}
public SBMLDocument outputSBML(String filename, SBMLDocument document) {
try {
Model m = document.getModel();
//checkConsistancy(document);
SBMLWriter writer = new SBMLWriter();
//printParameters(document);
printSpecies(document);
printPromoters(document);
printRNAP(document);
printDecay(document);
printPromoterProduction(document);
printPromoterBinding(document);
if (!complexAbstraction)
printComplexBinding(document);
PrintStream p = new PrintStream(new FileOutputStream(filename));
m.setName("Created from " + new File(filename).getName().replace("xml", "gcm"));
m.setId(new File(filename).getName().replace(".xml", ""));
m.setVolumeUnits("litre");
m.setSubstanceUnits("mole");
if (document != null) {
document.setConsistencyChecks(libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, true);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, true);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_SBO_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_OVERDETERMINED_MODEL, true);
long numErrors = document.checkConsistency();
if (numErrors > 0) {
String message = "";
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",
message += i + ":" + error + "\n";
}
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(BioSim.frame, scroll, "Generated SBML Has Errors",
JOptionPane.ERROR_MESSAGE);
}
}
p.print(writer.writeToString(document));
p.close();
return document;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Unable to output to SBML");
}
}
/**
* Merges an SBML file network to an SBML file
*
* @param filename
* @return the sbml document
*/
public SBMLDocument mergeSBML(String filename) {
try {
if (document == null) {
if (sbmlDocument.equals("")) {
return outputSBML(filename);
}
SBMLDocument document = BioSim.readSBML(currentRoot + sbmlDocument);
// checkConsistancy(document);
currentDocument = document;
return outputSBML(filename, document);
}
else {
currentDocument = document;
return outputSBML(filename, document);
}
}
catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Unable to output to SBML");
}
}
/**
* Merges an SBML file network to an SBML file
*
* @param filename
* @return the sbml document
*/
public SBMLDocument mergeSBML(String filename, SBMLDocument document) {
try {
currentDocument = document;
return outputSBML(filename, document);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Unable to output to SBML");
}
}
/**
* Prints each promoter binding
*
* @param document
* the SBMLDocument to print to
*/
private void printPromoterBinding(SBMLDocument document) {
for (Promoter p : promoters.values()) {
// First setup RNAP binding
if (p.getOutputs().size()==0) continue;
org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
r.setId("R_RNAP_" + p.getId());
r.addReactant(Utility.SpeciesReference("RNAP", 1));
r.addReactant(Utility.SpeciesReference(p.getId(), 1));
r.addProduct(Utility.SpeciesReference("RNAP_" + p.getId(), 1));
r.setReversible(true);
r.setFast(false);
KineticLaw kl = r.createKineticLaw();
kl.addParameter(Utility.Parameter(kRnapString, p.getKrnap(), getMoleParameter(2)));
kl.addParameter(Utility.Parameter("kr", 1, getMoleTimeParameter(1)));
kl.setFormula("kr*" + kRnapString + "*" + "RNAP*" + p.getId() + "-kr*RNAP_"
+ p.getId());
Utility.addReaction(document, r);
// Next setup activated binding
PrintActivatedBindingVisitor v = new PrintActivatedBindingVisitor(
document, p);
v.setCooperationAbstraction(cooperationAbstraction);
v.setComplexAbstraction(complexAbstraction);
v.run();
// Next setup repression binding
PrintRepressionBindingVisitor v2 = new PrintRepressionBindingVisitor(
document, p);
v2.setCooperationAbstraction(cooperationAbstraction);
v2.setComplexAbstraction(complexAbstraction);
v2.run();
}
}
/**
* Prints each promoter production values
*
* @param document
* the SBMLDocument to print to
*/
private void printPromoterProduction(SBMLDocument document) {
for (Promoter p : promoters.values()) {
if (p.getOutputs().size()==0) continue;
org.sbml.libsbml.Reaction r = new org.sbml.libsbml.Reaction(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
r.addModifier(Utility.ModifierSpeciesReference("RNAP_" + p.getId()));
for (SpeciesInterface species : p.getOutputs()) {
r.addProduct(Utility.SpeciesReference(species.getId(), p.getStoich()));
}
r.setReversible(false);
r.setFast(false);
KineticLaw kl = r.createKineticLaw();
if (p.getActivators().size() > 0) {
r.setId("R_basal_production_" + p.getId());
kl.addParameter(Utility.Parameter(kBasalString, p.getKbasal(),
getMoleTimeParameter(1)));
kl.setFormula(kBasalString + "*" + "RNAP_" + p.getId());
} else {
r.setId("R_constitutive_production_" + p.getId());
kl.addParameter(Utility.Parameter(kOcString, p.getKoc(),
getMoleTimeParameter(1)));
kl.setFormula(kOcString + "*" + "RNAP_" + p.getId());
}
Utility.addReaction(document, r);
if (p.getActivators().size() > 0) {
PrintActivatedProductionVisitor v = new PrintActivatedProductionVisitor(
document, p);
v.run();
}
}
}
/**
* Prints the decay reactions
*
* @param document
* the SBML document
*/
private void printDecay(SBMLDocument document) {
PrintDecaySpeciesVisitor visitor = new PrintDecaySpeciesVisitor(
document, species.values());
visitor.setComplexAbstraction(complexAbstraction);
visitor.run();
}
/**
* Prints the species in the network
*
* @param document
* the SBML document
*/
private void printSpecies(SBMLDocument document) {
PrintSpeciesVisitor visitor = new PrintSpeciesVisitor(document, species
.values(), compartment);
visitor.setComplexAbstraction(complexAbstraction);
visitor.run();
}
private void printComplexBinding(SBMLDocument document) {
PrintComplexVisitor v = new PrintComplexVisitor(document, species.values());
v.run();
}
private ASTNode updateMathVar(ASTNode math, String origVar, String newVar) {
String s = updateFormulaVar(myFormulaToString(math), origVar, newVar);
return myParseFormula(s);
}
private String myFormulaToString(ASTNode mathFormula) {
String formula = libsbml.formulaToString(mathFormula);
formula = formula.replaceAll("arccot", "acot");
formula = formula.replaceAll("arccoth", "acoth");
formula = formula.replaceAll("arccsc", "acsc");
formula = formula.replaceAll("arccsch", "acsch");
formula = formula.replaceAll("arcsec", "asec");
formula = formula.replaceAll("arcsech", "asech");
formula = formula.replaceAll("arccosh", "acosh");
formula = formula.replaceAll("arcsinh", "asinh");
formula = formula.replaceAll("arctanh", "atanh");
String newformula = formula.replaceFirst("00e", "0e");
while (!(newformula.equals(formula))) {
formula = newformula;
newformula = formula.replaceFirst("0e\\+", "e+");
newformula = newformula.replaceFirst("0e-", "e-");
}
formula = formula.replaceFirst("\\.e\\+", ".0e+");
formula = formula.replaceFirst("\\.e-", ".0e-");
return formula;
}
private String updateFormulaVar(String s, String origVar, String newVar) {
s = " " + s + " ";
s = s.replace(" " + origVar + " ", " " + newVar + " ");
s = s.replace(" " + origVar + "(", " " + newVar + "(");
s = s.replace("(" + origVar + ")", "(" + newVar + ")");
s = s.replace("(" + origVar + " ", "(" + newVar + " ");
s = s.replace("(" + origVar + ",", "(" + newVar + ",");
s = s.replace(" " + origVar + ")", " " + newVar + ")");
s = s.replace(" " + origVar + "^", " " + newVar + "^");
return s.trim();
}
private ASTNode myParseFormula(String formula) {
ASTNode mathFormula = libsbml.parseFormula(formula);
if (mathFormula == null)
return null;
setTimeAndTrigVar(mathFormula);
return mathFormula;
}
private void setTimeAndTrigVar(ASTNode node) {
if (node.getType() == libsbml.AST_NAME) {
if (node.getName().equals("t")) {
node.setType(libsbml.AST_NAME_TIME);
}
else if (node.getName().equals("time")) {
node.setType(libsbml.AST_NAME_TIME);
}
}
if (node.getType() == libsbml.AST_FUNCTION) {
if (node.getName().equals("acot")) {
node.setType(libsbml.AST_FUNCTION_ARCCOT);
}
else if (node.getName().equals("acoth")) {
node.setType(libsbml.AST_FUNCTION_ARCCOTH);
}
else if (node.getName().equals("acsc")) {
node.setType(libsbml.AST_FUNCTION_ARCCSC);
}
else if (node.getName().equals("acsch")) {
node.setType(libsbml.AST_FUNCTION_ARCCSCH);
}
else if (node.getName().equals("asec")) {
node.setType(libsbml.AST_FUNCTION_ARCSEC);
}
else if (node.getName().equals("asech")) {
node.setType(libsbml.AST_FUNCTION_ARCSECH);
}
else if (node.getName().equals("acosh")) {
node.setType(libsbml.AST_FUNCTION_ARCCOSH);
}
else if (node.getName().equals("asinh")) {
node.setType(libsbml.AST_FUNCTION_ARCSINH);
}
else if (node.getName().equals("atanh")) {
node.setType(libsbml.AST_FUNCTION_ARCTANH);
}
}
for (int c = 0; c < node.getNumChildren(); c++)
setTimeAndTrigVar(node.getChild(c));
}
private void updateVarId(boolean isSpecies, String origId, String newId, SBMLDocument document) {
if (origId.equals(newId))
return;
Model model = document.getModel();
for (int i = 0; i < model.getNumSpecies(); i++) {
org.sbml.libsbml.Species species = (org.sbml.libsbml.Species) model.getListOfSpecies().get(i);
if (species.getCompartment().equals(origId)) {
species.setCompartment(newId);
}
if (species.getSpeciesType().equals(origId)) {
species.setSpeciesType(newId);
}
}
for (int i = 0; i < model.getNumCompartments(); i++) {
org.sbml.libsbml.Compartment compartment = (org.sbml.libsbml.Compartment) model.getListOfCompartments().get(i);
if (compartment.getCompartmentType().equals(origId)) {
compartment.setCompartmentType(newId);
}
}
for (int i = 0; i < model.getNumReactions(); i++) {
org.sbml.libsbml.Reaction reaction = (org.sbml.libsbml.Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getProduct(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
specRef.getStoichiometryMath().setMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
}
}
}
if (isSpecies) {
for (int j = 0; j < reaction.getNumModifiers(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
ModifierSpeciesReference specRef = reaction.getModifier(j);
if (origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getReactant(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
specRef.getStoichiometryMath().setMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
}
}
}
reaction.getKineticLaw().setMath(
updateMathVar(reaction.getKineticLaw().getMath(), origId, newId));
}
if (model.getNumInitialAssignments() > 0) {
for (int i = 0; i < model.getNumInitialAssignments(); i++) {
InitialAssignment init = (InitialAssignment) model.getListOfInitialAssignments().get(i);
if (origId.equals(init.getSymbol())) {
init.setSymbol(newId);
}
init.setMath(updateMathVar(init.getMath(), origId, newId));
}
}
if (model.getNumRules() > 0) {
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) model.getListOfRules().get(i);
if (rule.isSetVariable() && origId.equals(rule.getVariable())) {
rule.setVariable(newId);
}
rule.setMath(updateMathVar(rule.getMath(), origId, newId));
}
}
if (model.getNumConstraints() > 0) {
for (int i = 0; i < model.getNumConstraints(); i++) {
Constraint constraint = (Constraint) model.getListOfConstraints().get(i);
constraint.setMath(updateMathVar(constraint.getMath(), origId, newId));
}
}
if (model.getNumEvents() > 0) {
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) model.getListOfEvents().get(i);
if (event.isSetTrigger()) {
event.getTrigger().setMath(updateMathVar(event.getTrigger().getMath(), origId, newId));
}
if (event.isSetDelay()) {
event.getDelay().setMath(updateMathVar(event.getDelay().getMath(), origId, newId));
}
for (int j = 0; j < event.getNumEventAssignments(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(origId)) {
ea.setVariable(newId);
}
if (ea.isSetMath()) {
ea.setMath(updateMathVar(ea.getMath(), origId, newId));
}
}
}
}
}
private void unionSBML(SBMLDocument mainDoc, SBMLDocument doc, String compName) {
Model m = doc.getModel();
for (int i = 0; i < m.getNumCompartmentTypes(); i ++) {
org.sbml.libsbml.CompartmentType c = m.getCompartmentType(i);
String newName = compName + "_" + c.getId();
updateVarId(false, c.getId(), newName, doc);
c.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumCompartmentTypes(); j ++) {
if (mainDoc.getModel().getCompartmentType(j).getId().equals(c.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addCompartmentType(c);
}
}
for (int i = 0; i < m.getNumCompartments(); i ++) {
org.sbml.libsbml.Compartment c = m.getCompartment(i);
String newName = compName + "_" + c.getId();
updateVarId(false, c.getId(), newName, doc);
c.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumCompartments(); j ++) {
if (mainDoc.getModel().getCompartment(j).getId().equals(c.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addCompartment(c);
}
}
for (int i = 0; i < m.getNumSpeciesTypes(); i ++) {
org.sbml.libsbml.SpeciesType s = m.getSpeciesType(i);
String newName = compName + "_" + s.getId();
updateVarId(false, s.getId(), newName, doc);
s.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumSpeciesTypes(); j ++) {
if (mainDoc.getModel().getSpeciesType(j).getId().equals(s.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addSpeciesType(s);
}
}
for (int i = 0; i < m.getNumSpecies(); i ++) {
Species spec = m.getSpecies(i);
if (!spec.getId().equals("RNAP")) {
String newName = compName + "_" + spec.getId();
for (Object port : properties.getComponents().get(compName).keySet()) {
if (spec.getId().equals((String) port)) {
newName = "_" + compName + "_" + properties.getComponents().get(compName).getProperty((String) port);
int removeDeg = -1;
for (int j = 0; j < m.getNumReactions(); j ++) {
org.sbml.libsbml.Reaction r = m.getReaction(j);
if (r.getId().equals("Degradation_" + spec.getId())) {
removeDeg = j;
}
}
if (removeDeg != -1) {
m.getListOfReactions().remove(removeDeg);
}
}
}
updateVarId(true, spec.getId(), newName, doc);
spec.setId(newName);
}
}
for (int i = 0; i < m.getNumSpecies(); i ++) {
Species spec = m.getSpecies(i);
if (spec.getId().startsWith("_" + compName + "_")) {
updateVarId(true, spec.getId(), spec.getId().substring(2 + compName.length()), doc);
spec.setId(spec.getId().substring(2 + compName.length()));
}
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumSpecies(); j ++) {
if (mainDoc.getModel().getSpecies(j).getId().equals(spec.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addSpecies(spec);
}
}
for (int i = 0; i < m.getNumParameters(); i ++) {
org.sbml.libsbml.Parameter p = m.getParameter(i);
String newName = compName + "_" + p.getId();
updateVarId(false, p.getId(), newName, doc);
p.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumParameters(); j ++) {
if (mainDoc.getModel().getParameter(j).getId().equals(p.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addParameter(p);
}
}
for (int i = 0; i < m.getNumReactions(); i ++) {
org.sbml.libsbml.Reaction r = m.getReaction(i);
String newName = compName + "_" + r.getId();
updateVarId(false, r.getId(), newName, doc);
r.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumReactions(); j ++) {
if (mainDoc.getModel().getReaction(j).getId().equals(r.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addReaction(r);
}
}
for (int i = 0; i < m.getNumInitialAssignments(); i ++) {
InitialAssignment init = (InitialAssignment) m.getListOfInitialAssignments().get(i);
mainDoc.getModel().addInitialAssignment(init);
}
for (int i = 0; i < m.getNumRules(); i++) {
org.sbml.libsbml.Rule r = m.getRule(i);
mainDoc.getModel().addRule(r);
}
for (int i = 0; i < m.getNumConstraints(); i++) {
Constraint constraint = (Constraint) m.getListOfConstraints().get(i);
mainDoc.getModel().addConstraint(constraint);
}
for (int i = 0; i < m.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) m.getListOfEvents().get(i);
String newName = compName + "_" + event.getId();
updateVarId(false, event.getId(), newName, doc);
event.setId(newName);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumEvents(); j ++) {
if (mainDoc.getModel().getEvent(j).getId().equals(event.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addEvent(event);
}
}
for (int i = 0; i < m.getNumUnitDefinitions(); i ++) {
UnitDefinition u = m.getUnitDefinition(i);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumUnitDefinitions(); j ++) {
if (mainDoc.getModel().getUnitDefinition(j).getId().equals(u.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addUnitDefinition(u);
}
}
for (int i = 0; i < m.getNumFunctionDefinitions(); i ++) {
FunctionDefinition f = m.getFunctionDefinition(i);
boolean add = true;
for (int j = 0; j < mainDoc.getModel().getNumFunctionDefinitions(); j ++) {
if (mainDoc.getModel().getFunctionDefinition(j).getId().equals(f.getId())) {
add = false;
}
}
if (add) {
mainDoc.getModel().addFunctionDefinition(f);
}
}
}
private void printComponents(SBMLDocument document, String filename) {
for (String s : properties.getComponents().keySet()) {
GCMParser parser = new GCMParser(currentRoot + separator +
properties.getComponents().get(s).getProperty("gcm"));
parser.setParameters(properties.getParameters());
GeneticNetwork network = parser.buildNetwork();
SBMLDocument d = network.mergeSBML(filename);
unionSBML(document, d, s);
}
}
/**
* Prints the promoters in the network
*
* @param document
* the SBML document
*/
private void printPromoters(SBMLDocument document) {
for (Promoter p : promoters.values()) {
if (p.getOutputs().size()==0) continue;
// First print out the promoter, and promoter bound to RNAP
Species s = Utility.makeSpecies(p.getId(), compartment,
p.getPcount());
if ((p.getProperties() != null) &&
(p.getProperties().containsKey(GlobalConstants.NAME))) {
s.setName(p.getProperty(GlobalConstants.NAME));
}
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
s = Utility.makeSpecies("RNAP_" + p.getId(), compartment,
0);
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
// Now cycle through all activators and repressors and add those
// bindings
for (SpeciesInterface specie : p.getActivators()) {
s = Utility.makeSpecies("RNAP_" + p.getId() + "_"
+ specie.getId(), compartment, 0);
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
}
for (SpeciesInterface specie : p.getRepressors()) {
s = Utility.makeSpecies("bound_" + p.getId() + "_"
+ specie.getId(), compartment, 0);
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
}
}
}
/**
* Prints the promoters in the network
*
* @param document
* the SBML document
*/
private void printOnlyPromoters(SBMLDocument document) {
for (Promoter p : promoters.values()) {
Species s = Utility.makeSpecies(p.getId(), compartment,
p.getPcount());
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
}
}
/**
* Prints the RNAP molecule to the document
*
* @param document
* the SBML document
*/
private void printRNAP(SBMLDocument document) {
double rnap = 30;
if (properties != null) {
rnap = Double.parseDouble(properties
.getParameter(GlobalConstants.RNAP_STRING));
}
Species s = Utility.makeSpecies("RNAP", compartment, rnap);
s.setHasOnlySubstanceUnits(true);
Utility.addSpecies(document, s);
}
/**
* Initializes the network
*
*/
private void initialize() {
buildComplexes();
}
/**
* Configures the promoters
*
*/
private void buildComplexes() {
for (Promoter p : promoters.values()) {
for (Reaction r : p.getActivatingReactions()) {
String inputId = r.getInput();
if (complexMap.containsKey(inputId)) {
ComplexSpecies c = new ComplexSpecies(species.get(inputId),
complexMap.get(inputId));
p.addActivator(inputId, c);
species.put(inputId, c);
}
String outputId = r.getOutput();
if (!r.getOutput().equals("none")) {
p.addOutput(outputId, species.get(outputId));
}
}
for (Reaction r : p.getRepressingReactions()) {
String inputId = r.getInput();
if (complexMap.containsKey(inputId)) {
ComplexSpecies c = new ComplexSpecies(species.get(inputId),
complexMap.get(inputId));
p.addRepressor(inputId, c);
species.put(inputId, c);
}
String outputId = r.getOutput();
if (!r.getOutput().equals("none")) {
p.addOutput(outputId, species.get(outputId));
}
}
}
}
public HashMap<String, SpeciesInterface> getSpecies() {
return species;
}
public void setSpecies(HashMap<String, SpeciesInterface> species) {
this.species = species;
}
public HashMap<String, Promoter> getPromoters() {
return promoters;
}
public void setPromoters(HashMap<String, Promoter> promoters) {
this.promoters = promoters;
}
public GCMFile getProperties() {
return properties;
}
public void setProperties(GCMFile properties) {
this.properties = properties;
}
/**
* Checks the consistancy of the document
*
* @param doc
* the SBML document to check
*/
private void checkConsistancy(SBMLDocument doc) {
if (doc.checkConsistency() > 0) {
for (int i = 0; i < doc.getNumErrors(); i++) {
System.out.println(doc.getError(i).getMessage());
}
}
}
private String sbmlDocument = "";
private SBMLDocument document = null;
private static SBMLDocument currentDocument = null;
private static String currentRoot = "";
private boolean cooperationAbstraction = false;
private boolean complexAbstraction = false;
private HashMap<String, SpeciesInterface> species = null;
private HashMap<String, Promoter> promoters = null;
private HashMap<String, ArrayList<PartSpecies>> complexMap = null;
private GCMFile properties = null;
private String compartment = "default";
private String kRnapString = CompatibilityFixer
.getSBMLName(GlobalConstants.RNAP_BINDING_STRING);
private String kBasalString = CompatibilityFixer
.getSBMLName(GlobalConstants.KBASAL_STRING);
private String kOcString = CompatibilityFixer
.getSBMLName(GlobalConstants.OCR_STRING);
/**
* Returns the curent SBML document being built
*
* @return the curent SBML document being built
*/
public static SBMLDocument getCurrentDocument() {
return currentDocument;
}
/**
* Sets the current root
* @param root the root directory
*/
public static void setRoot(String root) {
currentRoot = root;
}
public static String getUnitString(ArrayList<String> unitNames,
ArrayList<Integer> exponents, ArrayList<Integer> multiplier,
Model model) {
// First build the name of the unit and see if it exists, start by
// sorting the units to build a unique string
for (int i = 0; i < unitNames.size(); i++) {
for (int j = i; j > 0; j
if (unitNames.get(j - 1).compareTo(unitNames.get(i)) > 0) {
Integer tempD = multiplier.get(j);
Integer tempI = exponents.get(j);
String tempS = unitNames.get(j);
multiplier.set(j, multiplier.get(j - 1));
unitNames.set(j, unitNames.get(j - 1));
exponents.set(j, exponents.get(j - 1));
multiplier.set(j - 1, tempD);
unitNames.set(j - 1, tempS);
exponents.set(j - 1, tempI);
}
}
}
UnitDefinition t = new UnitDefinition(BioSim.SBML_LEVEL, BioSim.SBML_VERSION);
String name = "u_";
for (int i = 0; i < unitNames.size(); i++) {
String sign = "";
if (exponents.get(i).intValue() < 0) {
sign = "n";
}
name = name + multiplier.get(i) + "_" + unitNames.get(i) + "_"
+ sign + Math.abs(exponents.get(i)) + "_";
Unit u = t.createUnit();
u.setKind(libsbml.UnitKind_forName(unitNames.get(i)));
u.setExponent(exponents.get(i).intValue());
u.setMultiplier(multiplier.get(i).intValue());
u.setScale(0);
}
name = name.substring(0, name.length() - 1);
t.setId(name);
if (model.getUnitDefinition(name) == null) {
model.addUnitDefinition(t);
}
return name;
}
/**
* Returns a unit name for a parameter based on the number of molecules
* involved
*
* @param numMolecules
* the number of molecules involved
* @return a unit name
*/
public static String getMoleTimeParameter(int numMolecules) {
ArrayList<String> unitS = new ArrayList<String>();
ArrayList<Integer> unitE = new ArrayList<Integer>();
ArrayList<Integer> unitM = new ArrayList<Integer>();
if (numMolecules > 1) {
unitS.add("mole");
unitE.add(new Integer(-(numMolecules - 1)));
unitM.add(new Integer(1));
}
unitS.add("second");
unitE.add(new Integer(-1));
unitM.add(new Integer(1));
return GeneticNetwork.getUnitString(unitS, unitE, unitM,
currentDocument.getModel());
}
/**
* Returns a unit name for a parameter based on the number of molecules
* involved
*
* @param numMolecules
* the number of molecules involved
* @return a unit name
*/
public static String getMoleParameter(int numMolecules) {
ArrayList<String> unitS = new ArrayList<String>();
ArrayList<Integer> unitE = new ArrayList<Integer>();
ArrayList<Integer> unitM = new ArrayList<Integer>();
unitS.add("mole");
unitE.add(new Integer(-(numMolecules - 1)));
unitM.add(new Integer(1));
return GeneticNetwork.getUnitString(unitS, unitE, unitM,
currentDocument.getModel());
}
public static String getMoleParameter(String numMolecules) {
return getMoleParameter(Integer.parseInt(numMolecules));
}
} |
package ol;
import ol.View;
import ol.MapOptions;
import ol.ViewOptions;
import ol.proj.Projection;
import ol.OLFactory;
import ol.proj.ProjectionOptions;
/**
*
* @author Tino Desjardins
*
*/
public class MapTest extends GwtOL3BaseTestCase {
public void testMapCreation() {
injectUrlAndTest(new TestWithInjection() {
@Override
public void test() {
ProjectionOptions projectionOptions = OLFactory.createOptions();
projectionOptions.setCode("EPSG:21781");
projectionOptions.setUnits("m");
Projection projection = new Projection(projectionOptions);
ViewOptions viewOptions = OLFactory.createOptions();
viewOptions.setProjection(projection);
View view = new View(viewOptions);
Coordinate centerCoordinate = OLFactory.createCoordinate(660000, 190000);
view.setCenter(centerCoordinate);
view.setZoom(9);
final MapOptions mapOptions = OLFactory.createOptions();
mapOptions.setTarget("map");
mapOptions.setView(view);
Map map = new Map(mapOptions);
assertNotNull(map);
}
});
}
} |
package org.motechproject.server.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.model.InitiateCallData;
import org.motechproject.server.service.ivr.IVRService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This is an interactive test. In order to run that test please make sure that Asterisk, Voiceglue and VXML application
* are properly configures, up and running. Your SIP phone configured to use the "SIP/1001" account and that account registered
* in Asterisk.
*
* In order to run unit test
* - start your soft phone
* - run the initiateCallTest()
* Your soft phone should start ringing. Answer the phone, you should hear a voice message specified in the voice XML document retrieved
* from the URL specified as a value of the voiceXmlUrl property of the ivrServise bean. See testApplicationContext.xml.
*
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/testIVRAppContext.xml"})
public class IVRServiceImplIT {
@Autowired
private IVRService ivrService;
@Test
public void initiateCallTest() throws Exception{
InitiateCallData initiateCallData = new InitiateCallData(1L, "SIP/1001", 5000, "http://10.0.1.29:8080/TamaIVR/reminder/wt");
ivrService.initiateCall(initiateCallData);
}
} |
package org.navalplanner.business.orders.entities;
import static org.navalplanner.business.i18n.I18nHelper._;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang.Validate;
import org.hibernate.validator.AssertTrue;
import org.hibernate.validator.InvalidValue;
import org.hibernate.validator.Valid;
import org.joda.time.LocalDate;
import org.navalplanner.business.advance.bootstrap.PredefinedAdvancedTypes;
import org.navalplanner.business.advance.entities.AdvanceAssignment;
import org.navalplanner.business.advance.entities.AdvanceType;
import org.navalplanner.business.advance.entities.DirectAdvanceAssignment;
import org.navalplanner.business.advance.entities.IndirectAdvanceAssignment;
import org.navalplanner.business.advance.exceptions.DuplicateAdvanceAssignmentForOrderElementException;
import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlobalAdvanceException;
import org.navalplanner.business.common.IntegrationEntity;
import org.navalplanner.business.common.Registry;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.labels.entities.Label;
import org.navalplanner.business.materials.entities.MaterialAssignment;
import org.navalplanner.business.orders.daos.IOrderDAO;
import org.navalplanner.business.orders.entities.SchedulingState.Type;
import org.navalplanner.business.orders.entities.TaskSource.TaskSourceSynchronization;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.business.planner.entities.TaskElement;
import org.navalplanner.business.planner.entities.TaskPositionConstraint;
import org.navalplanner.business.qualityforms.entities.QualityForm;
import org.navalplanner.business.qualityforms.entities.TaskQualityForm;
import org.navalplanner.business.requirements.entities.CriterionRequirement;
import org.navalplanner.business.requirements.entities.DirectCriterionRequirement;
import org.navalplanner.business.requirements.entities.IndirectCriterionRequirement;
import org.navalplanner.business.scenarios.entities.OrderVersion;
import org.navalplanner.business.scenarios.entities.Scenario;
import org.navalplanner.business.templates.entities.OrderElementTemplate;
import org.navalplanner.business.trees.ITreeNode;
import org.navalplanner.business.util.deepcopy.DeepCopy;
public abstract class OrderElement extends IntegrationEntity implements
ICriterionRequirable, ITreeNode<OrderElement> {
protected InfoComponent infoComponent = new InfoComponent();
private Date initDate;
private Date deadline;
@Valid
protected Set<DirectAdvanceAssignment> directAdvanceAssignments = new HashSet<DirectAdvanceAssignment>();
@Valid
protected Set<MaterialAssignment> materialAssignments = new HashSet<MaterialAssignment>();
@Valid
protected Set<Label> labels = new HashSet<Label>();
protected Set<TaskQualityForm> taskQualityForms = new HashSet<TaskQualityForm>();
protected Set<CriterionRequirement> criterionRequirements = new HashSet<CriterionRequirement>();
protected OrderLineGroup parent;
protected CriterionRequirementOrderElementHandler criterionRequirementHandler =
CriterionRequirementOrderElementHandler.getInstance();
/**
* This field is transient
*/
private SchedulingState schedulingState = null;
private OrderElementTemplate template;
private BigDecimal lastAdvanceMeausurementForSpreading = BigDecimal.ZERO;
private Boolean dirtyLastAdvanceMeasurementForSpreading = true;
private SumChargedHours sumChargedHours = SumChargedHours.create();
public OrderElementTemplate getTemplate() {
return template;
}
private String externalCode;
private Map<OrderVersion, SchedulingDataForVersion> schedulingDatasForVersion = new HashMap<OrderVersion, SchedulingDataForVersion>();
protected void removeVersion(OrderVersion orderVersion) {
schedulingDatasForVersion.remove(orderVersion);
for (OrderElement each : getChildren()) {
each.removeVersion(orderVersion);
}
}
private SchedulingDataForVersion.Data current = null;
public SchedulingDataForVersion.Data getCurrentSchedulingData() {
if (current == null) {
throw new IllegalStateException(
"in order to use scheduling state related data "
+ "useSchedulingDataFor(OrderVersion orderVersion) "
+ "must be called first");
}
return current;
}
private void schedulingDataNowPointsTo(DeepCopy deepCopy,
OrderVersion version) {
current = getCurrentSchedulingData().pointsTo(deepCopy, version,
schedulingVersionFor(version));
for (OrderElement each : getChildren()) {
each.schedulingDataNowPointsTo(deepCopy, version);
}
}
protected void addNeededReplaces(DeepCopy deepCopy,
OrderVersion newOrderVersion) {
SchedulingDataForVersion currentVersion = getCurrentSchedulingData()
.getVersion();
SchedulingDataForVersion newSchedulingVersion = schedulingVersionFor(newOrderVersion);
deepCopy.replace(currentVersion, newSchedulingVersion);
for (OrderElement each : getChildren()) {
each.addNeededReplaces(deepCopy, newOrderVersion);
}
}
public SchedulingState getSchedulingState() {
if (schedulingState == null) {
schedulingState = SchedulingState.createSchedulingState(
getSchedulingStateType(), getChildrenStates(),
getCurrentSchedulingData().onTypeChangeListener());
}
return schedulingState;
}
private List<SchedulingState> getChildrenStates() {
List<SchedulingState> result = new ArrayList<SchedulingState>();
for (OrderElement each : getChildren()) {
result.add(each.getSchedulingState());
}
return result;
}
public boolean hasSchedulingDataBeingModified() {
return getCurrentSchedulingData().hasPendingChanges()
|| someSchedullingDataModified();
}
private boolean someSchedullingDataModified() {
for (OrderElement each : getChildren()) {
if (each.hasSchedulingDataBeingModified()) {
return true;
}
}
return false;
}
protected boolean isSchedulingDataInitialized() {
return current != null;
}
public void useSchedulingDataFor(OrderVersion orderVersion) {
useSchedulingDataFor(orderVersion, true);
}
public void useSchedulingDataFor(OrderVersion orderVersion,
boolean recursive) {
Validate.notNull(orderVersion);
SchedulingDataForVersion schedulingVersion = schedulingVersionFor(orderVersion);
if (recursive) {
for (OrderElement each : getChildren()) {
each.useSchedulingDataFor(orderVersion);
}
}
current = schedulingVersion.makeAvailableFor(orderVersion);
}
private SchedulingDataForVersion schedulingVersionFor(
OrderVersion orderVersion) {
SchedulingDataForVersion currentSchedulingData = schedulingDatasForVersion
.get(orderVersion);
if (currentSchedulingData == null) {
currentSchedulingData = SchedulingDataForVersion
.createInitialFor(this);
schedulingDatasForVersion.put(orderVersion, currentSchedulingData);
}
return currentSchedulingData;
}
public SchedulingDataForVersion getCurrentSchedulingDataForVersion() {
return getCurrentSchedulingData().getVersion();
}
protected void writeSchedulingDataChanges() {
getCurrentSchedulingData().writeSchedulingDataChanges();
for (OrderElement each : getChildren()) {
each.writeSchedulingDataChanges();
}
}
protected void writeSchedulingDataChangesTo(DeepCopy deepCopy,
OrderVersion newOrderVersion) {
schedulingDataNowPointsTo(deepCopy, newOrderVersion);
writeSchedulingDataChanges();
}
protected void removeSpuriousDayAssignments(Scenario scenario) {
removeAtNotCurrent(scenario);
removeAtCurrent(scenario);
for (OrderElement each : getChildren()) {
each.removeSpuriousDayAssignments(scenario);
}
}
private void removeAtNotCurrent(Scenario scenario) {
SchedulingDataForVersion currentDataForVersion = getCurrentSchedulingDataForVersion();
for (Entry<OrderVersion, SchedulingDataForVersion> each : schedulingDatasForVersion
.entrySet()) {
SchedulingDataForVersion dataForVersion = each.getValue();
if (!currentDataForVersion.equals(dataForVersion)) {
dataForVersion.removeSpuriousDayAssignments(scenario);
}
}
}
private void removeAtCurrent(Scenario scenario) {
TaskElement associatedTaskElement = getAssociatedTaskElement();
if (associatedTaskElement != null) {
associatedTaskElement.removePredecessorsDayAssignmentsFor(scenario);
}
}
public List<TaskSourceSynchronization> calculateSynchronizationsNeeded() {
SchedulingDataForVersion schedulingDataForVersion = getCurrentSchedulingData()
.getVersion();
return calculateSynchronizationsNeeded(schedulingDataForVersion);
}
private List<TaskSourceSynchronization> calculateSynchronizationsNeeded(
SchedulingDataForVersion schedulingDataForVersion) {
List<TaskSourceSynchronization> result = new ArrayList<TaskSourceSynchronization>();
if (isSchedulingPoint()) {
result
.addAll(synchronizationForSchedulingPoint(schedulingDataForVersion));
} else if (isSuperElementPartialOrCompletelyScheduled()) {
removeUnscheduled(result);
if (wasASchedulingPoint()) {
result.add(taskSourceRemoval());
}
result
.add(synchronizationForSuperelement(schedulingDataForVersion));
} else if (schedulingState.isNoScheduled()) {
removeTaskSource(result);
}
return result;
}
private TaskSourceSynchronization synchronizationForSuperelement(
SchedulingDataForVersion schedulingState) {
List<TaskSourceSynchronization> childrenSynchronizations = childrenSynchronizations();
if (thereIsNoTaskSource()) {
getCurrentSchedulingData().requestedCreationOf(
TaskSource.createForGroup(schedulingState));
return TaskSource.mustAddGroup(getTaskSource(),
childrenSynchronizations);
} else {
return getTaskSource().modifyGroup(childrenSynchronizations);
}
}
private boolean wasASchedulingPoint() {
return getTaskSource() != null
&& getTaskSource().getTask() instanceof Task;
}
private List<TaskSourceSynchronization> childrenSynchronizations() {
List<TaskSourceSynchronization> childrenOfGroup = new ArrayList<TaskSourceSynchronization>();
for (OrderElement orderElement : getSomewhatScheduledOrderElements()) {
childrenOfGroup.addAll(orderElement
.calculateSynchronizationsNeeded());
}
return childrenOfGroup;
}
private void removeUnscheduled(List<TaskSourceSynchronization> result) {
for (OrderElement orderElement : getNoScheduledOrderElements()) {
orderElement.removeTaskSource(result);
}
}
private List<TaskSourceSynchronization> synchronizationForSchedulingPoint(
SchedulingDataForVersion schedulingState) {
if (thereIsNoTaskSource()) {
getCurrentSchedulingData().requestedCreationOf(
TaskSource.create(schedulingState, getHoursGroups()));
return Collections.singletonList(TaskSource
.mustAdd(getTaskSource()));
} else if (getTaskSource().getTask().isLeaf()) {
return Collections.singletonList(getTaskSource()
.withCurrentHoursGroup(getHoursGroups()));
} else {
return synchronizationsForFromPartiallyScheduledToSchedulingPoint(schedulingState);
}
}
private List<TaskSourceSynchronization> synchronizationsForFromPartiallyScheduledToSchedulingPoint(
SchedulingDataForVersion schedulingState) {
List<TaskSourceSynchronization> result = new ArrayList<TaskSourceSynchronization>();
for (TaskSource each : getTaskSourcesFromBottomToTop()) {
OrderElement orderElement = each.getOrderElement();
result.add(orderElement.taskSourceRemoval());
}
TaskSource newTaskSource = TaskSource.create(schedulingState,
getHoursGroups());
getCurrentSchedulingData().requestedCreationOf(newTaskSource);
result.add(TaskSource.mustAdd(newTaskSource));
return result;
}
private boolean thereIsNoTaskSource() {
return getTaskSource() == null;
}
private List<OrderElement> getSomewhatScheduledOrderElements() {
List<OrderElement> result = new ArrayList<OrderElement>();
for (OrderElement orderElement : getChildren()) {
if (orderElement.getSchedulingStateType().isSomewhatScheduled()) {
result.add(orderElement);
}
}
return result;
}
private List<OrderElement> getNoScheduledOrderElements() {
List<OrderElement> result = new ArrayList<OrderElement>();
for (OrderElement orderElement : getChildren()) {
if (orderElement.getSchedulingState().isNoScheduled()) {
result.add(orderElement);
}
}
return result;
}
private void removeTaskSource(List<TaskSourceSynchronization> result) {
removeChildrenTaskSource(result);
if (getTaskSource() != null) {
result.add(taskSourceRemoval());
}
}
private TaskSourceSynchronization taskSourceRemoval() {
Validate.notNull(getTaskSource());
TaskSourceSynchronization result = TaskSource
.mustRemove(getTaskSource());
getCurrentSchedulingData().taskSourceRemovalRequested();
return result;
}
private void removeChildrenTaskSource(List<TaskSourceSynchronization> result) {
List<OrderElement> children = getChildren();
for (OrderElement each : children) {
each.removeTaskSource(result);
}
}
private boolean isSuperElementPartialOrCompletelyScheduled() {
return getSchedulingState().isSomewhatScheduled();
}
public void initializeType(SchedulingState.Type type) {
if (!isNewObject()) {
throw new IllegalStateException();
}
getCurrentSchedulingData().initializeType(type);
schedulingState = null;
}
public void initializeTemplate(OrderElementTemplate template) {
if (!isNewObject()) {
throw new IllegalStateException();
}
if (this.template != null) {
throw new IllegalStateException("already initialized");
}
this.template = template;
}
public boolean isSchedulingPoint() {
return getSchedulingState().getType() == Type.SCHEDULING_POINT;
}
public OrderLineGroup getParent() {
return parent;
}
public TaskElement getAssociatedTaskElement() {
if (getTaskSource() == null) {
return null;
} else {
return getTaskSource().getTask();
}
}
protected void setParent(OrderLineGroup parent) {
this.parent = parent;
}
public abstract Integer getWorkHours();
public abstract List<HoursGroup> getHoursGroups();
public String getName() {
return getInfoComponent().getName();
}
public void setName(String name) {
this.getInfoComponent().setName(name);
}
public abstract boolean isLeaf();
public abstract List<OrderElement> getChildren();
private static Date copy(Date date) {
return date != null ? new Date(date.getTime()) : date;
}
public Date getInitDate() {
return copy(initDate);
}
public void setInitDate(Date initDate) {
this.initDate = initDate;
}
public Date getDeadline() {
return copy(deadline);
}
public void setDeadline(Date deadline) {
this.deadline = deadline;
}
public void setDescription(String description) {
this.getInfoComponent().setDescription(description);
}
public String getDescription() {
return getInfoComponent().getDescription();
}
public abstract OrderLine toLeaf();
public abstract OrderLineGroup toContainer();
public boolean isScheduled() {
return getTaskSource() != null;
}
public boolean checkAtLeastOneHoursGroup() {
return (getHoursGroups().size() > 0);
}
public boolean isFormatCodeValid(String code) {
if (code.contains("_")) {
return false;
}
if (code.equals("")) {
return false;
}
return true;
}
public void setCode(String code) {
this.getInfoComponent().setCode(code);
}
public String getCode() {
return getInfoComponent().getCode();
}
public abstract OrderElementTemplate createTemplate();
public abstract DirectAdvanceAssignment getReportGlobalAdvanceAssignment();
public abstract DirectAdvanceAssignment getAdvanceAssignmentByType(AdvanceType type);
public DirectAdvanceAssignment getDirectAdvanceAssignmentByType(
AdvanceType advanceType) {
if (advanceType != null) {
for (DirectAdvanceAssignment directAdvanceAssignment : getDirectAdvanceAssignments()) {
if (directAdvanceAssignment.getAdvanceType().getId().equals(
advanceType.getId())) {
return directAdvanceAssignment;
}
}
}
return null;
}
public Set<DirectAdvanceAssignment> getDirectAdvanceAssignments() {
return Collections.unmodifiableSet(directAdvanceAssignments);
}
protected abstract Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments();
public abstract Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignments(
AdvanceType advanceType);
public abstract Set<IndirectAdvanceAssignment> getAllIndirectAdvanceAssignments(
AdvanceType advanceType);
public abstract Set<DirectAdvanceAssignment> getDirectAdvanceAssignmentsOfSubcontractedOrderElements();
protected abstract Set<DirectAdvanceAssignment> getAllDirectAdvanceAssignmentsReportGlobal();
public void removeAdvanceAssignment(AdvanceAssignment advanceAssignment) {
if (directAdvanceAssignments.contains(advanceAssignment)) {
directAdvanceAssignments.remove(advanceAssignment);
if (this.getParent() != null) {
this.getParent().removeIndirectAdvanceAssignment(
advanceAssignment.getAdvanceType());
removeChildrenAdvanceInParents(this.getParent());
}
markAsDirtyLastAdvanceMeasurementForSpreading();
}
}
public Set<Label> getLabels() {
return Collections.unmodifiableSet(labels);
}
public void setLabels(Set<Label> labels) {
this.labels = labels;
}
public void addLabel(Label label) {
Validate.notNull(label);
if (!checkAncestorsNoOtherLabelRepeated(label)) {
throw new IllegalArgumentException(
_("Some ancestor has the same label assigned, "
+ "so this element is already inheriting this label"));
}
removeLabelOnChildren(label);
labels.add(label);
}
public void removeLabel(Label label) {
labels.remove(label);
}
/**
* Validate if the advanceAssignment can be added to the order element.The
* list of advanceAssignments must be attached.
* @param advanceAssignment
* must be attached
* @throws DuplicateValueTrueReportGlobalAdvanceException
* @throws DuplicateAdvanceAssignmentForOrderElementException
*/
public void addAdvanceAssignment(
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
checkNoOtherGlobalAdvanceAssignment(newAdvanceAssignment);
checkAncestorsNoOtherAssignmentWithSameAdvanceType(this,
newAdvanceAssignment);
checkChildrenNoOtherAssignmentWithSameAdvanceType(this,
newAdvanceAssignment);
newAdvanceAssignment.setOrderElement(this);
this.directAdvanceAssignments.add(newAdvanceAssignment);
if (this.getParent() != null) {
addChildrenAdvanceInParents(this.getParent());
this.getParent().addIndirectAdvanceAssignment(
newAdvanceAssignment.createIndirectAdvanceFor(this.getParent()));
}
}
public void addChildrenAdvanceInParents(OrderLineGroup parent) {
if ((parent != null) && (!parent.existChildrenAdvance())) {
parent.addChildrenAdvanceOrderLineGroup();
addChildrenAdvanceInParents(parent.getParent());
}
}
public void removeChildrenAdvanceInParents(OrderLineGroup parent) {
if ((parent != null) && (parent.existChildrenAdvance())
&& (!itsChildsHasAdvances(parent))) {
parent.removeChildrenAdvanceOrderLineGroup();
removeChildrenAdvanceInParents(parent.getParent());
}
}
private boolean itsChildsHasAdvances(OrderElement orderElement) {
for (OrderElement child : orderElement.getChildren()) {
if ((!child.getIndirectAdvanceAssignments().isEmpty())
|| (!child.getDirectAdvanceAssignments().isEmpty())) {
return true;
}
if (itsChildsHasAdvances(child)) {
return true;
}
}
return false;
}
protected void checkNoOtherGlobalAdvanceAssignment(
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateValueTrueReportGlobalAdvanceException {
if (!newAdvanceAssignment.getReportGlobalAdvance()) {
return;
}
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if (directAdvanceAssignment.getReportGlobalAdvance()) {
throw new DuplicateValueTrueReportGlobalAdvanceException(
_("Cannot spread two progress in the same task"),
this, OrderElement.class);
}
}
}
/**
* It checks there are no {@link DirectAdvanceAssignment} with the same type
* in {@link OrderElement} and ancestors
*
* @param orderElement
* @param newAdvanceAssignment
* @throws DuplicateAdvanceAssignmentForOrderElementException
*/
private void checkAncestorsNoOtherAssignmentWithSameAdvanceType(
OrderElement orderElement,
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateAdvanceAssignmentForOrderElementException {
for (DirectAdvanceAssignment directAdvanceAssignment : orderElement
.getDirectAdvanceAssignments()) {
if (AdvanceType.equivalentInDB(directAdvanceAssignment
.getAdvanceType(), newAdvanceAssignment.getAdvanceType())) {
throw new DuplicateAdvanceAssignmentForOrderElementException(
_("Duplicate Progress Assignment For Task"),
this,
OrderElement.class);
}
}
if (orderElement.getParent() != null) {
checkAncestorsNoOtherAssignmentWithSameAdvanceType(orderElement
.getParent(), newAdvanceAssignment);
}
}
/**
* It checks there are no {@link AdvanceAssignment} with the same type in
* orderElement and its children
* @param orderElement
* @param newAdvanceAssignment
* @throws DuplicateAdvanceAssignmentForOrderElementException
*/
protected void checkChildrenNoOtherAssignmentWithSameAdvanceType(
OrderElement orderElement,
DirectAdvanceAssignment newAdvanceAssignment)
throws DuplicateAdvanceAssignmentForOrderElementException {
if (orderElement
.existsDirectAdvanceAssignmentWithTheSameType(newAdvanceAssignment
.getAdvanceType())) {
throw new DuplicateAdvanceAssignmentForOrderElementException(
_("Duplicate Progress Assignment For Task"),
this,
OrderElement.class);
}
if (!orderElement.getChildren().isEmpty()) {
for (OrderElement child : orderElement.getChildren()) {
checkChildrenNoOtherAssignmentWithSameAdvanceType(child,
newAdvanceAssignment);
}
}
}
public boolean existsDirectAdvanceAssignmentWithTheSameType(AdvanceType type) {
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if (AdvanceType.equivalentInDB(directAdvanceAssignment
.getAdvanceType(), type)) {
return true;
}
}
return false;
}
public BigDecimal getAdvancePercentage() {
if ((dirtyLastAdvanceMeasurementForSpreading == null)
|| dirtyLastAdvanceMeasurementForSpreading) {
lastAdvanceMeausurementForSpreading = getAdvancePercentage(null);
dirtyLastAdvanceMeasurementForSpreading = false;
}
return lastAdvanceMeausurementForSpreading;
}
public abstract BigDecimal getAdvancePercentage(LocalDate date);
public abstract Set<IndirectAdvanceAssignment> getIndirectAdvanceAssignments();
public abstract DirectAdvanceAssignment calculateFakeDirectAdvanceAssignment(
IndirectAdvanceAssignment indirectAdvanceAssignment);
public abstract BigDecimal getAdvancePercentageChildren();
public List<OrderElement> getAllChildren() {
List<OrderElement> children = getChildren();
List<OrderElement> result = new ArrayList<OrderElement>();
for (OrderElement orderElement : children) {
result.add(orderElement);
result.addAll(orderElement.getAllChildren());
}
return result;
}
public void setCriterionRequirements(
Set<CriterionRequirement> criterionRequirements) {
this.criterionRequirements = criterionRequirements;
}
@Valid
@Override
public Set<CriterionRequirement> getCriterionRequirements() {
return Collections.unmodifiableSet(criterionRequirements);
}
/*
* Operations to manage the criterion requirements of a orderElement
* (remove, adding, update of the criterion requirement of the orderElement
* such as the descendent's criterion requirement)
*/
public void setValidCriterionRequirement(IndirectCriterionRequirement requirement,boolean valid){
requirement.setValid(valid);
criterionRequirementHandler.propagateValidCriterionRequirement(this,
requirement.getParent(), valid);
}
public void removeDirectCriterionRequirement(DirectCriterionRequirement criterionRequirement){
criterionRequirementHandler.propagateRemoveCriterionRequirement(this,
criterionRequirement);
removeCriterionRequirement(criterionRequirement);
}
@Override
public void removeCriterionRequirement(CriterionRequirement requirement) {
criterionRequirements.remove(requirement);
if (requirement instanceof IndirectCriterionRequirement) {
((IndirectCriterionRequirement)requirement).getParent().
getChildren().remove((IndirectCriterionRequirement)requirement);
}
}
@Override
public void addCriterionRequirement(
CriterionRequirement criterionRequirement) {
criterionRequirementHandler.addCriterionRequirement(this, criterionRequirement);
}
public void addDirectCriterionRequirement(
CriterionRequirement criterionRequirement) {
criterionRequirementHandler.addDirectCriterionRequirement(this, criterionRequirement);
}
public void addIndirectCriterionRequirement(
IndirectCriterionRequirement criterionRequirement) {
criterionRequirementHandler.addIndirectCriterionRequirement(this,
criterionRequirement);
}
protected void basicAddCriterionRequirement(
CriterionRequirement criterionRequirement) {
criterionRequirement.setOrderElement(this);
this.criterionRequirements.add(criterionRequirement);
}
public void updateCriterionRequirements() {
criterionRequirementHandler.updateMyCriterionRequirements(this);
criterionRequirementHandler.propagateUpdateCriterionRequirements(this);
}
public boolean canAddCriterionRequirement(
DirectCriterionRequirement newRequirement) {
return criterionRequirementHandler.canAddCriterionRequirement(this,
newRequirement);
}
protected Set<IndirectCriterionRequirement> getIndirectCriterionRequirement() {
return criterionRequirementHandler.getIndirectCriterionRequirement(criterionRequirements);
}
public void updatePositionConstraintOf(Task task) {
applyConstraintsInOrderElementParents(task);
}
public void applyInitialPositionConstraintTo(Task task) {
boolean applied = applyConstraintsInOrderElementParents(task);
if (applied) {
return;
}
if (getOrder().isScheduleBackwards()) {
task.getPositionConstraint().asLateAsPossible();
} else {
task.getPositionConstraint().asSoonAsPossible();
}
}
/**
* Searches for init date or end constraints on order element and order
* element parents.
*
* @param task
* @return <code>true</code> if a constraint have been applied, otherwise
* <code>false</code>
*/
private boolean applyConstraintsInOrderElementParents(Task task) {
boolean scheduleBackwards = getOrder().isScheduleBackwards();
OrderElement current = this;
while (current != null) {
boolean applied = current.applyConstraintBasedOnInitOrEndDate(task,
scheduleBackwards);
if (applied) {
return true;
}
current = current.getParent();
}
return false;
}
protected boolean applyConstraintBasedOnInitOrEndDate(Task task,
boolean scheduleBackwards) {
TaskPositionConstraint constraint = task.getPositionConstraint();
if (getInitDate() != null
&& (getDeadline() == null || !scheduleBackwards)) {
constraint.notEarlierThan(
LocalDate.fromDateFields(this.getInitDate()));
return true;
}
if (getDeadline() != null) {
constraint.finishNotLaterThan(
LocalDate.fromDateFields(this.getDeadline()));
return true;
}
return false;
}
public Set<DirectCriterionRequirement> getDirectCriterionRequirement() {
return criterionRequirementHandler
.getDirectCriterionRequirement(criterionRequirements);
}
public SchedulingState.Type getSchedulingStateType() {
return getCurrentSchedulingData().getSchedulingStateType();
}
public TaskSource getTaskSource() {
return getCurrentSchedulingData().getTaskSource();
}
public Set<TaskElement> getTaskElements() {
if (getTaskSource() == null) {
return Collections.emptySet();
}
return Collections.singleton(getTaskSource().getTask());
}
public List<TaskSource> getTaskSourcesFromBottomToTop() {
List<TaskSource> result = new ArrayList<TaskSource>();
taskSourcesFromBottomToTop(result);
return result;
}
public List<TaskSource> getAllScenariosTaskSourcesFromBottomToTop() {
List<TaskSource> result = new ArrayList<TaskSource>();
allScenariosTaskSourcesFromBottomToTop(result);
return result;
}
public List<SchedulingDataForVersion> getSchedulingDatasForVersionFromBottomToTop() {
List<SchedulingDataForVersion> result = new ArrayList<SchedulingDataForVersion>();
schedulingDataForVersionFromBottomToTop(result);
return result;
}
private void schedulingDataForVersionFromBottomToTop(
List<SchedulingDataForVersion> result) {
for (OrderElement each : getChildren()) {
each.schedulingDataForVersionFromBottomToTop(result);
}
result.addAll(schedulingDatasForVersion.values());
}
private void taskSourcesFromBottomToTop(List<TaskSource> result) {
for (OrderElement each : getChildren()) {
each.taskSourcesFromBottomToTop(result);
}
if (getTaskSource() != null) {
result.add(getTaskSource());
}
}
private void allScenariosTaskSourcesFromBottomToTop(List<TaskSource> result) {
for (OrderElement each : getChildren()) {
each.allScenariosTaskSourcesFromBottomToTop(result);
}
for (Entry<OrderVersion, SchedulingDataForVersion> each : schedulingDatasForVersion
.entrySet()) {
TaskSource taskSource = each.getValue().getTaskSource();
if (taskSource != null) {
result.add(taskSource);
}
}
}
@Valid
public Set<MaterialAssignment> getMaterialAssignments() {
return Collections.unmodifiableSet(materialAssignments);
}
public void addMaterialAssignment(MaterialAssignment materialAssignment) {
materialAssignments.add(materialAssignment);
materialAssignment.setOrderElement(this);
}
public void removeMaterialAssignment(MaterialAssignment materialAssignment) {
materialAssignments.remove(materialAssignment);
}
public BigDecimal getTotalMaterialAssigmentUnits() {
BigDecimal result = BigDecimal.ZERO;
final Set<MaterialAssignment> materialAssigments = getMaterialAssignments();
for (MaterialAssignment each: materialAssigments) {
result = result.add(each.getUnits());
}
return result;
}
public BigDecimal getTotalMaterialAssigmentPrice() {
BigDecimal result = new BigDecimal(0);
final Set<MaterialAssignment> materialAssigments = getMaterialAssignments();
for (MaterialAssignment each: materialAssigments) {
result = result.add(each.getTotalPrice());
}
return result;
}
public Order getOrder() {
if (parent == null) {
return null;
}
return parent.getOrder();
}
@Valid
public Set<TaskQualityForm> getTaskQualityForms() {
return Collections.unmodifiableSet(taskQualityForms);
}
public Set<QualityForm> getQualityForms() {
Set<QualityForm> result = new HashSet<QualityForm>();
for (TaskQualityForm each : taskQualityForms) {
result.add(each.getQualityForm());
}
return result;
}
public void setTaskQualityFormItems(Set<TaskQualityForm> taskQualityForms) {
this.taskQualityForms = taskQualityForms;
}
public TaskQualityForm addTaskQualityForm(QualityForm qualityForm)
throws ValidationException {
ckeckUniqueQualityForm(qualityForm);
TaskQualityForm taskQualityForm = TaskQualityForm.create(this,
qualityForm);
this.taskQualityForms.add(taskQualityForm);
return taskQualityForm;
}
public void removeTaskQualityForm(TaskQualityForm taskQualityForm) {
this.taskQualityForms.remove(taskQualityForm);
}
private void ckeckUniqueQualityForm(QualityForm qualityForm)
throws ValidationException, IllegalArgumentException {
Validate.notNull(qualityForm);
for (TaskQualityForm taskQualityForm : getTaskQualityForms()) {
if (qualityForm.equals(taskQualityForm.getQualityForm())) {
throw new ValidationException(new InvalidValue(_(
"{0} already exists", qualityForm.getName()),
QualityForm.class, "name", qualityForm.getName(),
qualityForm));
}
}
}
@Override
public boolean checkConstraintUniqueCode() {
// the automatic checking of this constraint is avoided because it uses
// the wrong code property
return true;
}
@AssertTrue(message = "a label can not be assigned twice in the same branch")
public boolean checkConstraintLabelNotRepeatedInTheSameBranch() {
return checkConstraintLabelNotRepeatedInTheSameBranch(new HashSet<Label>());
}
private boolean checkConstraintLabelNotRepeatedInTheSameBranch(
HashSet<Label> parentLabels) {
HashSet<Label> withThisLabels = new HashSet<Label>(parentLabels);
for (Label label : getLabels()) {
if (containsLabel(withThisLabels, label)) {
return false;
}
withThisLabels.add(label);
}
for (OrderElement child : getChildren()) {
if (!child
.checkConstraintLabelNotRepeatedInTheSameBranch(withThisLabels)) {
return false;
}
}
return true;
}
private boolean containsLabel(HashSet<Label> labels, Label label) {
for (Label each : labels) {
if (each.isEqualTo(label)) {
return true;
}
}
return false;
}
private boolean checkAncestorsNoOtherLabelRepeated(Label newLabel) {
for (Label label : labels) {
if (label.isEqualTo(newLabel)) {
return false;
}
}
if (parent != null) {
if (!((OrderElement) parent)
.checkAncestorsNoOtherLabelRepeated(newLabel)) {
return false;
}
}
return true;
}
private void removeLabelOnChildren(Label newLabel) {
Label toRemove = null;
for (Label label : labels) {
if (label.equals(newLabel)) {
toRemove = label;
break;
}
}
if (toRemove != null) {
removeLabel(toRemove);
}
for (OrderElement child : getChildren()) {
child.removeLabelOnChildren(newLabel);
}
}
public boolean containsOrderElement(String code) {
for (OrderElement child : getChildren()) {
if (child.getCode().equals(code)) {
return true;
}
}
return false;
}
public OrderElement getOrderElement(String code) {
if (code == null) {
return null;
}
for (OrderElement child : getChildren()) {
if (child.getCode().equals(code)) {
return child;
}
}
return null;
}
public boolean containsLabel(String code) {
for (Label label : getLabels()) {
if (label.getCode().equals(code)) {
return true;
}
}
return false;
}
public boolean containsMaterialAssignment(String materialCode) {
for (MaterialAssignment materialAssignment : getMaterialAssignments()) {
if (materialAssignment.getMaterial().getCode().equals(materialCode)) {
return true;
}
}
return false;
}
public MaterialAssignment getMaterialAssignment(String materialCode) {
for (MaterialAssignment materialAssignment : getMaterialAssignments()) {
if (materialAssignment.getMaterial().getCode().equals(materialCode)) {
return materialAssignment;
}
}
return null;
}
public DirectAdvanceAssignment getDirectAdvanceAssignmentSubcontractor() {
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
if (directAdvanceAssignment.getAdvanceType().getUnitName().equals(
PredefinedAdvancedTypes.SUBCONTRACTOR.getTypeName())) {
return directAdvanceAssignment;
}
}
return null;
}
public DirectAdvanceAssignment addSubcontractorAdvanceAssignment()
throws DuplicateValueTrueReportGlobalAdvanceException,
DuplicateAdvanceAssignmentForOrderElementException {
boolean reportGlobalAdvance = false;
if (getReportGlobalAdvanceAssignment() == null) {
reportGlobalAdvance = true;
}
DirectAdvanceAssignment directAdvanceAssignment = DirectAdvanceAssignment
.create(reportGlobalAdvance, new BigDecimal(100));
directAdvanceAssignment
.setAdvanceType(PredefinedAdvancedTypes.SUBCONTRACTOR.getType());
addAdvanceAssignment(directAdvanceAssignment);
return directAdvanceAssignment;
}
@Valid
public InfoComponent getInfoComponent() {
if (infoComponent == null) {
infoComponent = new InfoComponent();
}
return infoComponent;
}
@Override
public OrderElement getThis() {
return this;
}
public void setExternalCode(String externalCode) {
this.externalCode = externalCode;
}
public String getExternalCode() {
return externalCode;
}
public void moveCodeToExternalCode() {
setExternalCode(getCode());
setCode(null);
for (OrderElement child : getChildren()) {
child.moveCodeToExternalCode();
}
}
public abstract OrderLine calculateOrderLineForSubcontract();
public Set<MaterialAssignment> getAllMaterialAssignments() {
Set<MaterialAssignment> result = new HashSet<MaterialAssignment>();
result.addAll(getMaterialAssignments());
for (OrderElement orderElement : getChildren()) {
result.addAll(orderElement.getAllMaterialAssignments());
}
return result;
}
/**
* Calculate if the tasks of the planification point has finished
*/
public boolean isFinishPlanificationPointTask() {
// look up into the order elements tree
TaskElement task = lookToUpAssignedTask();
if (task != null) {
return task.getOrderElement().isFinishedAdvance();
}
// look down into the order elements tree
List<TaskElement> listTask = lookToDownAssignedTask();
if (!listTask.isEmpty()) {
for (TaskElement taskElement : listTask) {
if (!taskElement.getOrderElement().isFinishedAdvance()) {
return false;
}
}
}
// not exist assigned task
IOrderDAO orderDAO = Registry.getOrderDAO();
return (orderDAO.loadOrderAvoidingProxyFor(this))
.isFinishedAdvance();
}
private TaskElement lookToUpAssignedTask() {
OrderElement current = this;
while (current != null) {
if (isSchedulingPoint()) {
return getAssociatedTaskElement();
}
current = current.getParent();
}
return null;
}
private List<TaskElement> lookToDownAssignedTask() {
List<TaskElement> resultTask = new ArrayList<TaskElement>();
for (OrderElement child : getAllChildren()) {
if (child.isSchedulingPoint()) {
TaskElement task = child.getAssociatedTaskElement();
if (task != null) {
resultTask.add(task);
}
}
}
return resultTask;
}
public boolean isFinishedAdvance() {
BigDecimal measuredProgress = getAdvancePercentage();
measuredProgress = (measuredProgress.setScale(0, BigDecimal.ROUND_UP)
.multiply(new BigDecimal(100)));
return (measuredProgress.compareTo(new BigDecimal(100)) == 0);
}
@Override
protected IIntegrationEntityDAO<OrderElement> getIntegrationEntityDAO() {
return Registry.getOrderElementDAO();
}
public void markAsDirtyLastAdvanceMeasurementForSpreading() {
if (parent != null) {
parent.markAsDirtyLastAdvanceMeasurementForSpreading();
}
dirtyLastAdvanceMeasurementForSpreading = true;
}
public void setSumChargedHours(SumChargedHours sumChargedHours) {
this.sumChargedHours = sumChargedHours;
}
public SumChargedHours getSumChargedHours() {
return sumChargedHours;
}
public void updateAdvancePercentageTaskElement() {
BigDecimal advancePercentage = this.getAdvancePercentage();
if (this.getTaskSource() != null) {
if (this.getTaskSource().getTask() != null) {
this.getTaskSource().getTask().setAdvancePercentage(
advancePercentage);
}
}
}
public static void checkConstraintOrderUniqueCode(OrderElement order) {
OrderElement repeatedOrder;
// Check no code is repeated in this order
if (order instanceof OrderLineGroup) {
repeatedOrder = ((OrderLineGroup) order).findRepeatedOrderCode();
if (repeatedOrder != null) {
throw new ValidationException(_(
"Repeated Project code {0} in Project {1}",
repeatedOrder.getCode(), repeatedOrder.getName()));
}
}
// Check no code is repeated within the DB
repeatedOrder = Registry.getOrderElementDAO()
.findRepeatedOrderCodeInDB(order);
if (repeatedOrder != null) {
throw new ValidationException(_(
"Repeated Project code {0} in Project {1}",
repeatedOrder.getCode(), repeatedOrder.getName()));
}
}
public void setCodeAutogenerated(Boolean codeAutogenerated) {
if (getOrder().equals(this)) {
super.setCodeAutogenerated(codeAutogenerated);
}
}
public Boolean isCodeAutogenerated() {
if (getOrder().equals(this)) {
return super.isCodeAutogenerated();
}
return getOrder() != null ? getOrder().isCodeAutogenerated() : false;
}
@AssertTrue(message = "a quality form can not be assigned twice to the same order element")
public boolean checkConstraintUniqueQualityForm() {
Set<QualityForm> qualityForms = new HashSet<QualityForm>();
for (TaskQualityForm each : taskQualityForms) {
QualityForm qualityForm = each.getQualityForm();
if (qualityForms.contains(qualityForm)) {
return false;
}
qualityForms.add(qualityForm);
}
return true;
}
} |
package com.yahoo.vespa.hosted.provision.provisioning;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.ClusterMembership;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.config.provision.Flavor;
import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.SystemName;
import com.yahoo.vespa.hosted.provision.Node;
import com.yahoo.vespa.hosted.provision.NodeList;
import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.Agent;
import com.yahoo.vespa.hosted.provision.node.Allocation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Used to manage a list of nodes during the node reservation process
* in order to fulfill the nodespec.
*
* @author bratseth
*/
class NodeAllocation {
/** List of all nodes in node-repository */
private final NodeList allNodes;
/** The application this list is for */
private final ApplicationId application;
/** The cluster this list is for */
private final ClusterSpec cluster;
/** The requested nodes of this list */
private final NodeSpec requestedNodes;
/** The node candidates this has accepted so far, keyed on hostname */
private final Map<String, NodeCandidate> nodes = new LinkedHashMap<>();
/** The number of already allocated nodes accepted and not retired */
private int accepted = 0;
/** The number of already allocated nodes accepted and not retired and not needing resize */
private int acceptedWithoutResizingRetired = 0;
/** The number of nodes rejected because of clashing parentHostname */
private int rejectedDueToClashingParentHost = 0;
/** The number of nodes rejected due to exclusivity constraints */
private int rejectedDueToExclusivity = 0;
private int rejectedDueToInsufficientRealResources = 0;
/** The number of nodes that just now was changed to retired */
private int wasRetiredJustNow = 0;
/** The node indexes to verify uniqueness of each members index */
private final Set<Integer> indexes = new HashSet<>();
/** The next membership index to assign to a new node */
private final Supplier<Integer> nextIndex;
private final NodeRepository nodeRepository;
private final NodeResourceLimits nodeResourceLimits;
NodeAllocation(NodeList allNodes, ApplicationId application, ClusterSpec cluster, NodeSpec requestedNodes,
Supplier<Integer> nextIndex, NodeRepository nodeRepository) {
this.allNodes = allNodes;
this.application = application;
this.cluster = cluster;
this.requestedNodes = requestedNodes;
this.nextIndex = nextIndex;
this.nodeRepository = nodeRepository;
nodeResourceLimits = new NodeResourceLimits(nodeRepository);
}
/**
* Offer some nodes to this. The nodes may have an allocation to a different application or cluster,
* an allocation to this cluster, or no current allocation (in which case one is assigned).
*
* Note that if unallocated nodes are offered before allocated nodes, this will unnecessarily
* reject allocated nodes due to index duplicates.
*
* @param nodesPrioritized the nodes which are potentially on offer. These may belong to a different application etc.
* @return the subset of offeredNodes which was accepted, with the correct allocation assigned
*/
List<Node> offer(List<NodeCandidate> nodesPrioritized) {
List<Node> accepted = new ArrayList<>();
for (NodeCandidate candidate : nodesPrioritized) {
if (candidate.allocation().isPresent()) {
Allocation allocation = candidate.allocation().get();
ClusterMembership membership = allocation.membership();
if ( ! allocation.owner().equals(application)) continue; // wrong application
if ( ! membership.cluster().satisfies(cluster)) continue; // wrong cluster id/type
if ((! candidate.isSurplus || saturated()) && ! membership.cluster().group().equals(cluster.group())) continue; // wrong group and we can't or have no reason to change it
if ( candidate.state() == Node.State.active && allocation.isRemovable()) continue; // don't accept; causes removal
if ( indexes.contains(membership.index())) continue; // duplicate index (just to be sure)
boolean resizeable = requestedNodes.considerRetiring() && candidate.isResizable;
boolean acceptToRetire = acceptToRetire(candidate);
if ((! saturated() && hasCompatibleFlavor(candidate) && requestedNodes.acceptable(candidate)) || acceptToRetire) {
candidate = candidate.withNode();
if (candidate.isValid())
accepted.add(acceptNode(candidate, shouldRetire(candidate, nodesPrioritized), resizeable));
}
}
else if (! saturated() && hasCompatibleFlavor(candidate)) {
if (requestedNodes.type() == NodeType.tenant && ! nodeResourceLimits.isWithinRealLimits(candidate, cluster)) {
++rejectedDueToInsufficientRealResources;
continue;
}
if ( violatesParentHostPolicy(candidate)) {
++rejectedDueToClashingParentHost;
continue;
}
if ( violatesExclusivity(candidate)) {
++rejectedDueToExclusivity;
continue;
}
if (candidate.wantToRetire()) {
continue;
}
candidate = candidate.allocate(application,
ClusterMembership.from(cluster, nextIndex.get()),
requestedNodes.resources().orElse(candidate.resources()),
nodeRepository.clock().instant());
if (candidate.isValid())
accepted.add(acceptNode(candidate, false, false));
}
}
return accepted;
}
private boolean shouldRetire(NodeCandidate candidate, List<NodeCandidate> candidates) {
if ( ! requestedNodes.considerRetiring())
return candidate.allocation().map(a -> a.membership().retired()).orElse(false); // don't second-guess if already retired
if ( ! nodeResourceLimits.isWithinRealLimits(candidate, cluster)) return true;
if (violatesParentHostPolicy(candidate)) return true;
if ( ! hasCompatibleFlavor(candidate)) return true;
if (candidate.wantToRetire()) return true;
if (candidate.preferToRetire() && candidate.replacableBy(candidates)) return true;
if (violatesExclusivity(candidate)) return true;
return false;
}
private boolean violatesParentHostPolicy(NodeCandidate candidate) {
return checkForClashingParentHost() && offeredNodeHasParentHostnameAlreadyAccepted(candidate);
}
private boolean checkForClashingParentHost() {
return nodeRepository.zone().system() == SystemName.main &&
nodeRepository.zone().environment().isProduction() &&
! application.instance().isTester();
}
private boolean offeredNodeHasParentHostnameAlreadyAccepted(NodeCandidate candidate) {
for (NodeCandidate acceptedNode : nodes.values()) {
if (acceptedNode.parentHostname().isPresent() && candidate.parentHostname().isPresent() &&
acceptedNode.parentHostname().get().equals(candidate.parentHostname().get())) {
return true;
}
}
return false;
}
private boolean violatesExclusivity(NodeCandidate candidate) {
if (candidate.parentHostname().isEmpty()) return false;
// In dynamic provisioned zones a node requiring exclusivity must be on a host that has exclusiveTo equal to its owner
if (nodeRepository.zone().getCloud().dynamicProvisioning())
return requestedNodes.isExclusive() &&
! candidate.parent.flatMap(Node::exclusiveTo).map(application::equals).orElse(false);
// In non-dynamic provisioned zones we require that if either of the nodes on the host requires exclusivity,
// then all the nodes on the host must have the same owner
for (Node nodeOnHost : allNodes.childrenOf(candidate.parentHostname().get())) {
if (nodeOnHost.allocation().isEmpty()) continue;
if (requestedNodes.isExclusive() || nodeOnHost.allocation().get().membership().cluster().isExclusive()) {
if ( ! nodeOnHost.allocation().get().owner().equals(application)) return true;
}
}
return false;
}
/**
* Returns whether this node should be accepted into the cluster even if it is not currently desired
* (already enough nodes, or wrong flavor).
* Such nodes will be marked retired during finalization of the list of accepted nodes.
* The conditions for this are:
*
* This is a stateful node. These must always be retired before being removed to allow the cluster to
* migrate away data.
*
* This is a container node and it is not desired due to having the wrong flavor. In this case this
* will (normally) obtain for all the current nodes in the cluster and so retiring before removing must
* be used to avoid removing all the current nodes at once, before the newly allocated replacements are
* initialized. (In the other case, where a container node is not desired because we have enough nodes we
* do want to remove it immediately to get immediate feedback on how the size reduction works out.)
*/
private boolean acceptToRetire(NodeCandidate candidate) {
if (candidate.state() != Node.State.active) return false;
if (! candidate.allocation().get().membership().cluster().group().equals(cluster.group())) return false;
if (candidate.allocation().get().membership().retired()) return true; // don't second-guess if already retired
if (! requestedNodes.considerRetiring()) return false;
return cluster.isStateful() ||
(cluster.type() == ClusterSpec.Type.container && !hasCompatibleFlavor(candidate));
}
private boolean hasCompatibleFlavor(NodeCandidate candidate) {
return requestedNodes.isCompatible(candidate.flavor(), nodeRepository.flavors()) || candidate.isResizable;
}
private Node acceptNode(NodeCandidate candidate, boolean shouldRetire, boolean resizeable) {
Node node = candidate.toNode();
if (node.allocation().isPresent()) // Record the currently requested resources
node = node.with(node.allocation().get().withRequestedResources(requestedNodes.resources().orElse(node.resources())));
if (! shouldRetire) {
accepted++;
// We want to allocate new nodes rather than unretiring with resize, so count without those
// for the purpose of deciding when to stop accepting nodes (saturation)
if (node.allocation().isEmpty()
|| ! ( requestedNodes.needsResize(node) && node.allocation().get().membership().retired()))
acceptedWithoutResizingRetired++;
if (resizeable && ! ( node.allocation().isPresent() && node.allocation().get().membership().retired()))
node = resize(node);
if (node.state() != Node.State.active) // reactivated node - wipe state that deactivated it
node = node.unretire().removable(false);
} else {
++wasRetiredJustNow;
node = node.retire(nodeRepository.clock().instant());
}
if ( ! node.allocation().get().membership().cluster().equals(cluster)) {
// group may be different
node = setCluster(cluster, node);
}
candidate = candidate.withNode(node);
indexes.add(node.allocation().get().membership().index());
nodes.put(node.hostname(), candidate);
return node;
}
private Node resize(Node node) {
NodeResources hostResources = allNodes.parentOf(node).get().flavor().resources();
return node.with(new Flavor(requestedNodes.resources().get()
.with(hostResources.diskSpeed())
.with(hostResources.storageType())));
}
private Node setCluster(ClusterSpec cluster, Node node) {
ClusterMembership membership = node.allocation().get().membership().with(cluster);
return node.with(node.allocation().get().with(membership));
}
/** Returns true if no more nodes are needed in this list */
private boolean saturated() {
return requestedNodes.saturatedBy(acceptedWithoutResizingRetired);
}
/** Returns true if the content of this list is sufficient to meet the request */
boolean fulfilled() {
return requestedNodes.fulfilledBy(accepted());
}
/** Returns true if this allocation was already fulfilled and resulted in no new changes */
public boolean fulfilledAndNoChanges() {
return fulfilled() && reservableNodes().isEmpty() && newNodes().isEmpty();
}
/**
* Returns {@link FlavorCount} describing the node deficit for the given {@link NodeSpec}.
*
* @return empty if the requested spec is already fulfilled. Otherwise returns {@link FlavorCount} containing the
* flavor and node count required to cover the deficit.
*/
Optional<FlavorCount> nodeDeficit() {
if (nodeType() != NodeType.config && nodeType() != NodeType.tenant) {
return Optional.empty(); // Requests for these node types never have a deficit
}
return Optional.of(new FlavorCount(requestedNodes.resources().orElseGet(NodeResources::unspecified),
requestedNodes.fulfilledDeficitCount(accepted())))
.filter(flavorCount -> flavorCount.getCount() > 0);
}
/** Returns the indices to use when provisioning hosts for this */
List<Integer> provisionIndices(int count) {
if (count < 1) throw new IllegalArgumentException("Count must be positive");
NodeType hostType = requestedNodes.type().hostType();
// Tenant hosts have a continuously increasing index
if (hostType == NodeType.host) return nodeRepository.database().readProvisionIndices(count);
// Infrastructure hosts have fixed indices, starting at 1
Set<Integer> currentIndices = allNodes.nodeType(hostType)
.stream()
.map(Node::hostname)
// TODO(mpolden): Use cluster index instead of parsing hostname, once all
// config servers have been replaced once and have switched
// to compact indices
.map(NodeAllocation::parseIndex)
.collect(Collectors.toSet());
List<Integer> indices = new ArrayList<>(count);
for (int i = 1; indices.size() < count; i++) {
if (!currentIndices.contains(i)) {
indices.add(i);
}
}
return indices;
}
/** The node type this is allocating */
NodeType nodeType() {
return requestedNodes.type();
}
/**
* Make the number of <i>non-retired</i> nodes in the list equal to the requested number
* of nodes, and retire the rest of the list. Only retire currently active nodes.
* Prefer to retire nodes of the wrong flavor.
* Make as few changes to the retired set as possible.
*
* @return the final list of nodes
*/
List<Node> finalNodes() {
int currentRetiredCount = (int) nodes.values().stream().filter(node -> node.allocation().get().membership().retired()).count();
int deltaRetiredCount = requestedNodes.idealRetiredCount(nodes.size(), currentRetiredCount) - currentRetiredCount;
if (deltaRetiredCount > 0) { // retire until deltaRetiredCount is 0
for (NodeCandidate candidate : byRetiringPriority(nodes.values())) {
if ( ! candidate.allocation().get().membership().retired() && candidate.state() == Node.State.active) {
candidate = candidate.withNode();
candidate = candidate.withNode(candidate.toNode().retire(Agent.application, nodeRepository.clock().instant()));
nodes.put(candidate.toNode().hostname(), candidate);
if (--deltaRetiredCount == 0) break;
}
}
}
else if (deltaRetiredCount < 0) { // unretire until deltaRetiredCount is 0
for (NodeCandidate candidate : byUnretiringPriority(nodes.values())) {
if ( candidate.allocation().get().membership().retired() && hasCompatibleFlavor(candidate) ) {
candidate = candidate.withNode();
if (candidate.isResizable)
candidate = candidate.withNode(resize(candidate.toNode()));
candidate = candidate.withNode(candidate.toNode().unretire());
nodes.put(candidate.toNode().hostname(), candidate);
if (++deltaRetiredCount == 0) break;
}
}
}
for (NodeCandidate candidate : nodes.values()) {
// Set whether the node is exclusive
candidate = candidate.withNode();
Allocation allocation = candidate.allocation().get();
candidate = candidate.withNode(candidate.toNode().with(allocation.with(allocation.membership()
.with(allocation.membership().cluster().exclusive(requestedNodes.isExclusive())))));
nodes.put(candidate.toNode().hostname(), candidate);
}
return nodes.values().stream().map(n -> n.toNode()).collect(Collectors.toList());
}
List<Node> reservableNodes() {
// Include already reserved nodes to extend reservation period and to potentially update their cluster spec.
EnumSet<Node.State> reservableStates = EnumSet.of(Node.State.inactive, Node.State.ready, Node.State.reserved);
return nodesFilter(n -> ! n.isNew && reservableStates.contains(n.state()));
}
List<Node> newNodes() {
return nodesFilter(n -> n.isNew);
}
private List<Node> nodesFilter(Predicate<NodeCandidate> predicate) {
return nodes.values().stream()
.filter(predicate)
.map(n -> n.toNode())
.collect(Collectors.toList());
}
/** Returns the number of nodes accepted this far */
private int accepted() {
if (nodeType() == NodeType.tenant) return accepted;
// Infrastructure nodes are always allocated by type. Count all nodes as accepted so that we never exceed
// the wanted number of nodes for the type.
return allNodes.nodeType(nodeType()).size();
}
/** Prefer to retire nodes we want the least */
private List<NodeCandidate> byRetiringPriority(Collection<NodeCandidate> candidates) {
return candidates.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}
/** Prefer to unretire nodes we don't want to retire, and otherwise those with lower index */
private List<NodeCandidate> byUnretiringPriority(Collection<NodeCandidate> candidates) {
return candidates.stream()
.sorted(Comparator.comparing(NodeCandidate::wantToRetire)
.thenComparing(n -> n.allocation().get().membership().index()))
.collect(Collectors.toList());
}
public String outOfCapacityDetails() {
List<String> reasons = new ArrayList<>();
if (rejectedDueToExclusivity > 0)
reasons.add("host exclusivity constraints");
if (rejectedDueToClashingParentHost > 0)
reasons.add("insufficient nodes available on separate physical hosts");
if (wasRetiredJustNow > 0)
reasons.add("retirement of allocated nodes");
if (rejectedDueToInsufficientRealResources > 0)
reasons.add("insufficient real resources on hosts");
if (reasons.isEmpty()) return "";
return ": Not enough nodes available due to " + String.join(", ", reasons);
}
private static Integer parseIndex(String hostname) {
// Node index is the first number appearing in the hostname, before the first dot
try {
return Integer.parseInt(hostname.replaceFirst("^\\D+(\\d+)\\..*", "$1"));
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Could not parse index from hostname '" + hostname + "'", e);
}
}
static class FlavorCount {
private final NodeResources flavor;
private final int count;
private FlavorCount(NodeResources flavor, int count) {
this.flavor = flavor;
this.count = count;
}
NodeResources getFlavor() {
return flavor;
}
int getCount() {
return count;
}
}
} |
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
package org.opennms.web.svclayer.support;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import org.opennms.netmgt.config.siteStatusViews.Category;
import org.opennms.netmgt.config.siteStatusViews.RowDef;
import org.opennms.netmgt.config.siteStatusViews.Rows;
import org.opennms.netmgt.config.siteStatusViews.View;
import org.opennms.netmgt.dao.CategoryDao;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.model.AggregateStatusDefinition;
import org.opennms.netmgt.model.AggregateStatusView;
import org.opennms.netmgt.model.OnmsCategory;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.web.svclayer.AggregateStatus;
import org.opennms.web.svclayer.dao.SiteStatusViewConfigDao;
import junit.framework.TestCase;
public class DefaultSiteStatusServiceTest extends TestCase {
private NodeDao m_nodeDao;
private CategoryDao m_categoryDao;
private SiteStatusViewConfigDao m_siteStatusViewConfigDao;
public void setUp() throws Exception {
super.setUp();
m_nodeDao = createMock(NodeDao.class);
m_categoryDao = createMock(CategoryDao.class);
m_siteStatusViewConfigDao = createMock(SiteStatusViewConfigDao.class);
}
public void testBogus() {
// Empty test so JUnit doesn't complain about not having any tests to run
}
public void FIXMEtestCreateAggregateStatusUsingNodeId() {
Collection<AggregateStatus> aggrStati;
Collection<AggregateStatusDefinition> defs = new HashSet<AggregateStatusDefinition>();
OnmsCategory catRouters = new OnmsCategory("routers");
OnmsCategory catSwitches = new OnmsCategory("switches");
AggregateStatusDefinition definition =
new AggregateStatusDefinition("Routers/Switches", new HashSet<OnmsCategory>(Arrays.asList(new OnmsCategory[]{ catRouters, catSwitches })));
defs.add(definition);
OnmsCategory catServers = new OnmsCategory("servers");
definition =
new AggregateStatusDefinition("Servers", new HashSet<OnmsCategory>(Arrays.asList(new OnmsCategory[]{ catServers })));
defs.add(definition);
DefaultSiteStatusViewService aggregateSvc = new DefaultSiteStatusViewService();
aggregateSvc.setNodeDao(m_nodeDao);
aggregateSvc.setCategoryDao(m_categoryDao);
aggregateSvc.setSiteStatusViewConfigDao(m_siteStatusViewConfigDao);
OnmsNode node = new OnmsNode();
node.setId(1);
node.getAssetRecord().setBuilding("HQ");
Collection<OnmsNode> nodes = new ArrayList<OnmsNode>();
nodes.add(node);
for (AggregateStatusDefinition def : defs) {
expect(m_nodeDao.findAllByVarCharAssetColumnCategoryList("building", "HQ", def.getCategories())).andReturn(nodes);
}
for (OnmsNode n : nodes) {
expect(m_nodeDao.load(n.getId())).andReturn(n);
}
replay(m_nodeDao);
expect(m_categoryDao.findByName("switches")).andReturn(catSwitches);
expect(m_categoryDao.findByName("routers")).andReturn(catRouters);
expect(m_categoryDao.findByName("servers")).andReturn(catServers);
replay(m_categoryDao);
Rows rows = new Rows();
RowDef rowDef = new RowDef();
Category category = new Category();
category.setName("servers");
rowDef.addCategory(category);
rows.addRowDef(rowDef);
rows = new Rows();
rowDef = new RowDef();
category = new Category();
category.setName("switches");
rowDef.addCategory(category);
category = new Category();
category.setName("routers");
rowDef.addCategory(category);
rows.addRowDef(rowDef);
View view = new View();
view.setRows(rows);
expect(m_siteStatusViewConfigDao.getView("building")).andReturn(view);
replay(m_siteStatusViewConfigDao);
aggrStati = aggregateSvc.createAggregateStatusesUsingNodeId(node.getId(), "building");
verify(m_nodeDao);
verify(m_categoryDao);
verify(m_siteStatusViewConfigDao);
assertNotNull(aggrStati);
}
public void FIXMEtestCreateAggregateStatusUsingBuilding() {
Collection<AggregateStatus> aggrStati;
Collection<AggregateStatusDefinition> defs = new HashSet<AggregateStatusDefinition>();
AggregateStatusDefinition definition =
new AggregateStatusDefinition("Routers/Switches", new HashSet<OnmsCategory>(Arrays.asList(new OnmsCategory[]{ new OnmsCategory("routers"), new OnmsCategory("switches") })));
defs.add(definition);
definition =
new AggregateStatusDefinition("Servers", new HashSet<OnmsCategory>(Arrays.asList(new OnmsCategory[]{ new OnmsCategory("servers") })));
defs.add(definition);
DefaultSiteStatusViewService aggregateSvc = new DefaultSiteStatusViewService();
aggregateSvc.setNodeDao(m_nodeDao);
OnmsNode node = new OnmsNode();
Collection<OnmsNode> nodes = new ArrayList<OnmsNode>();
nodes.add(node);
for (AggregateStatusDefinition def : defs) {
expect(m_nodeDao.findAllByVarCharAssetColumnCategoryList("building", "HQ", def.getCategories())).andReturn(nodes);
}
replay(m_nodeDao);
AggregateStatusView view = new AggregateStatusView();
view.setName("building");
view.setColumnValue("HQ");
view.setTableName("assets");
view.setStatusDefinitions(new LinkedHashSet<AggregateStatusDefinition>(defs));
aggrStati = aggregateSvc.createAggregateStatusUsingAssetColumn(view);
verify(m_nodeDao);
assertNotNull(aggrStati);
}
} |
package org.onebeartoe.modeling.openscad.test.suite;
import org.testng.annotations.Test;
public class SegunanimousTest extends OpenScadTestSuiteTest
{
protected String outputPath = "src/main/generated-openscad/";
public SegunanimousTest() throws Exception
{
}
@Test()
public void test()
{
System.out.println("testguino");
}
// @Override
protected String getOutfileName()
{
return "unanimous.scad";
}
@Test()
public void testSomething()
{
System.out.println("test something from " + getClass().getName());
}
@Override
public void willItWork()
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
} |
package org.eclipse.emf.ecp.view.table.vaadin;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecp.view.model.vaadin.ECPFVaadinViewRenderer;
import org.eclipse.emf.ecp.view.model.vaadin.ECPVaadinView;
import org.eclipse.emf.ecp.view.spi.model.VControl;
import org.eclipse.emf.ecp.view.spi.model.VDomainModelReference;
import org.eclipse.emf.ecp.view.spi.model.VView;
import org.eclipse.emf.ecp.view.spi.model.VViewFactory;
import org.eclipse.emf.ecp.view.spi.table.model.VTableControl;
import org.eclipse.emf.ecp.view.spi.table.model.VTableDomainModelReference;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.lunifera.runtime.web.vaadin.databinding.VaadinObservables;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
public class EditDialog extends Window {
private final EObject selection;
private Adapter objectChangeAdapter;
private ComposedAdapterFactory composedAdapterFactory;
private AdapterFactoryItemDelegator adapterFactoryItemDelegator;
private final VTableControl tableControl;
private Button okButton;
public EditDialog(final EObject selection, VTableControl tableControl) {
this.selection = selection;
this.tableControl = tableControl;
composedAdapterFactory = new ComposedAdapterFactory(new AdapterFactory[] {
new ReflectiveItemProviderAdapterFactory(),
new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE) });
adapterFactoryItemDelegator = new AdapterFactoryItemDelegator(composedAdapterFactory);
setCaption(adapterFactoryItemDelegator.getText(selection));
objectChangeAdapter = new AdapterImpl() {
@Override
public void notifyChanged(Notification msg) {
setCaption(adapterFactoryItemDelegator.getText(selection));
}
};
selection.eAdapters().add(objectChangeAdapter);
initUi();
setResizable(true);
setWidth(40, Unit.PERCENTAGE);
center();
}
private void initUi() {
final VView view = getView();
VaadinObservables.activateRealm(UI.getCurrent());
ECPVaadinView ecpVaadinView = ECPFVaadinViewRenderer.INSTANCE.render(selection, view);
VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
Component component = ecpVaadinView.getComponent();
layout.addComponent(component);
okButton = new Button("Ok", new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
close();
}
});
layout.addComponent(okButton);
layout.setComponentAlignment(okButton, Alignment.TOP_RIGHT);
setContent(layout);
}
private VView getView() {
final VView vView = VViewFactory.eINSTANCE.createView();
for (final VDomainModelReference column : VTableDomainModelReference.class.cast(
tableControl.getDomainModelReference()).getColumnDomainModelReferences()) {
final VControl vControl = VViewFactory.eINSTANCE.createControl();
vControl.setDomainModelReference(EcoreUtil.copy(column));
boolean controlReadOnly = tableControl.isReadonly() || !tableControl.isEnabled();
// controlReadOnly = TableConfigurationHelper.isReadOnly(tableControl, column);
vControl.setReadonly(controlReadOnly);
vView.getChildren().add(vControl);
}
return vView;
}
@Override
public void close() {
if (objectChangeAdapter != null) {
selection.eAdapters().remove(objectChangeAdapter);
}
if (composedAdapterFactory != null) {
composedAdapterFactory.dispose();
}
super.close();
}
} |
package org.eclipse.mylar.ui.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.ui.InterestFilter;
import org.eclipse.mylar.ui.MylarImages;
import org.eclipse.mylar.ui.MylarUiPlugin;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.IActionDelegate2;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
/**
* @author Mik Kersten
*/
public abstract class AbstractInterestFilterAction extends Action implements IViewActionDelegate, IActionDelegate2 {
public static final String PREF_ID_PREFIX = "org.eclipse.mylar.ui.interest.filter.";
protected String prefId;
protected IAction initAction = null;
private boolean isSelfManaged = false;
protected ViewerFilter interestFilter;
public AbstractInterestFilterAction(InterestFilter interestFilter) {
super();
this.interestFilter = interestFilter;
setText("Filter uninteresting");
setImageDescriptor(MylarImages.INTEREST_FILTERING);
setToolTipText("Filter uninteresting elements");
}
public void init(IAction action) {
initAction = action;
setChecked(action.isChecked());
}
public void init(IViewPart view) {
String id = view.getSite().getId();
prefId = PREF_ID_PREFIX + id;//.substring(id.lastIndexOf('.') + 1);
}
public void run(IAction action) {
setChecked(action.isChecked());
valueChanged(action, action.isChecked(), true);
}
/**
* This operation is expensive.
*/
public void update() {
valueChanged(initAction, MylarPlugin.getDefault().getPreferenceStore().getBoolean(prefId), false);
}
protected void valueChanged(IAction action, final boolean on, boolean store) {
try {
action.setChecked(on);
if (store && MylarPlugin.getDefault() != null) MylarPlugin.getDefault().getPreferenceStore().setValue(prefId, on);
StructuredViewer viewer = getViewer();
if (viewer != null) {
if (on) {
installInterestFilter(getViewer());
if (!isSelfManaged) MylarUiPlugin.getDefault().getUiUpdateManager().addManagedViewer(viewer);
} else {
uninstallInterestFilter(getViewer());
if (!isSelfManaged) MylarUiPlugin.getDefault().getUiUpdateManager().removeManagedViewer(viewer);
}
refreshViewer();
if (on && viewer instanceof TreeViewer) {
((TreeViewer)viewer).expandAll();
}
} else {
// ignore, failure to install is ok if there is no outline when attempted
}
} catch (Throwable t) {
MylarPlugin.fail(t, "Could not install viewer manager on: " + prefId, false);
}
}
protected abstract StructuredViewer getViewer() ;
public abstract void refreshViewer();
protected void installInterestFilter(StructuredViewer viewer) {
try {
if (viewer != null) {
boolean found = false;
for (int i = 0; i < viewer.getFilters().length; i++) {
ViewerFilter filter = viewer.getFilters()[i];
if (filter instanceof InterestFilter) found = true;
}
if (!found) viewer.addFilter(interestFilter);
} else {
MylarPlugin.log("Could not install interest filter", this);
}
} catch (Throwable t) {
MylarPlugin.fail(t, "Could not install viewer fitler on: " + prefId, false);
}
}
protected void uninstallInterestFilter(StructuredViewer viewer) {
if (viewer != null) {
for (int i = 0; i < viewer.getFilters().length; i++) {
ViewerFilter filter = viewer.getFilters()[i];
if (filter instanceof InterestFilter) {
viewer.removeFilter(filter);
}
}
} else {
MylarPlugin.log("Could not uninstall interest filter", this);
}
}
public void selectionChanged(IAction action, ISelection selection) {
// ignore
}
public void dispose() {
// don't need to do anything here
}
public void runWithEvent(IAction action, Event event) {
run(action);
}
public void setViewerIsSelfManaged(boolean isSelfManaged) {
this.isSelfManaged = isSelfManaged;
}
} |
package org.metaborg.spt.core.run;
import org.metaborg.core.messages.IMessage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Concrete instance of the output of evaluating a test expectation when running the test on Spoofax languages.
*/
public final class SpoofaxTestExpectationOutput implements ISpoofaxTestExpectationOutput {
private final boolean success;
private final List<IMessage> messages;
private final List<ISpoofaxFragmentResult> fragmentResults;
/**
* Initializes a new instance of the {@link SpoofaxTestExpectationOutput} class.
*
* @param success whether the test expectation was met
* @param messages the messages returned by evaluating the test expectation
* @param fragmentResults the results of the fragments that where part of the expectation
*/
public SpoofaxTestExpectationOutput(boolean success, Collection<IMessage> messages, Collection<ISpoofaxFragmentResult> fragmentResults) {
this.success = success;
this.messages = copyFromCollection(messages);
this.fragmentResults = copyFromCollection(fragmentResults);
}
@Override public boolean isSuccessful() {
return success;
}
@Override public List<IMessage> getMessages() {
return messages;
}
@Override public List<ISpoofaxFragmentResult> getFragmentResults() {
return fragmentResults;
}
/**
* Copies the given collection.
*
* @param collection the collection to copy
* @param <T> the type of elements in the collection
* @return the copied collection
*/
private static <T> List<T> copyFromCollection(Collection<T> collection) {
if (collection.isEmpty()) {
return Collections.emptyList();
} else if (collection.size() == 1) {
return Collections.singletonList(collection.iterator().next());
} else {
return new ArrayList<>(collection);
}
}
} |
package vg.civcraft.mc.civmodcore.world.locations.global;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.block.Block;
import vg.civcraft.mc.civmodcore.CivModCorePlugin;
import vg.civcraft.mc.civmodcore.world.locations.chunkmeta.CacheState;
import vg.civcraft.mc.civmodcore.world.locations.chunkmeta.XZWCoord;
import vg.civcraft.mc.civmodcore.world.locations.chunkmeta.block.BlockBasedChunkMeta;
public class GlobalLocationTracker<T extends LocationTrackable> {
private Map<Location, T> tracked;
private GlobalTrackableDAO<T> dao;
private Map<Location, T> deleted;
private Map<Location, T> modified;
private Map<XZWCoord, Map<Location, T>> perChunk;
public GlobalLocationTracker(GlobalTrackableDAO<T> dao) {
this.tracked = new HashMap<>();
this.dao = dao;
this.deleted = new HashMap<>();
this.modified = new HashMap<>();
this.perChunk = new HashMap<>();
}
public synchronized void initFromDB() {
dao.loadAll(this::putUnmodified);
}
public void handleChunkLoad(Chunk chunk) {
Map<Location, T> perChunkMap = perChunk.get(XZWCoord.fromChunk(chunk));
if (perChunkMap != null) {
for(Map.Entry<Location,T> entry : perChunkMap.entrySet()) {
int x = BlockBasedChunkMeta.modulo(entry.getKey().getBlockX());
int z = BlockBasedChunkMeta.modulo(entry.getKey().getBlockZ());
Block block = chunk.getBlock(x, entry.getKey().getBlockY(), z);
entry.getValue().onChunkLoad(block);
}
}
}
public void handleChunkUnload(Chunk chunk) {
Map<Location, T> perChunkMap = perChunk.get(XZWCoord.fromChunk(chunk));
if (perChunkMap != null) {
for(Map.Entry<Location,T> entry : perChunkMap.entrySet()) {
int x = BlockBasedChunkMeta.modulo(entry.getKey().getBlockX());
int z = BlockBasedChunkMeta.modulo(entry.getKey().getBlockZ());
Block block = chunk.getBlock(x, entry.getKey().getBlockY(), z);
entry.getValue().onChunkUnload(block);
}
}
}
public void persist() {
persistDeleted();
persistModified();
}
private void persistDeleted() {
List<T> list;
synchronized (this.deleted) {
if (this.deleted.isEmpty())
return;
list = new ArrayList<>();
list.addAll(this.deleted.values());
this.deleted.clear();
}
list.forEach(dao::delete);
}
private void persistModified() {
List<T> list;
synchronized (this.modified) {
if (this.modified.isEmpty())
return;
list = new ArrayList<>();
list.addAll(this.modified.values());
this.modified.clear();
}
for (T t : list) {
switch (t.getCacheState()) {
case DELETED:
dao.delete(t);
break;
case MODIFIED:
dao.update(t);
break;
case NEW:
dao.insert(t);
break;
case NORMAL:
default:
break;
}
t.setCacheState(CacheState.NORMAL);
}
}
public synchronized T get(Location loc) {
return tracked.get(loc);
}
public void put(T trackable) {
putUnmodified(trackable);
synchronized (this.modified) {
this.modified.put(trackable.getLocation(), trackable);
}
}
private synchronized void putUnmodified(T trackable) {
tracked.put(trackable.getLocation(), trackable);
Map<Location, T> chunkSpecificData = perChunk.computeIfAbsent(XZWCoord.fromLocation(
trackable.getLocation()), s -> new HashMap<>());
chunkSpecificData.put(trackable.getLocation(), trackable);
}
public synchronized T remove(Location loc) {
T removed = tracked.remove(loc);
if (removed != null && removed.getCacheState() != CacheState.NEW) {
Map<Location, T> chunkSpecificData = perChunk.computeIfAbsent(XZWCoord.fromLocation(
loc), s -> new HashMap<>());
if (removed != chunkSpecificData.remove(loc)) {
CivModCorePlugin.getInstance().getLogger().severe("Data removed from per chunk tracking did "
+ "not match data in global tracking");
}
synchronized (this.deleted) {
this.deleted.put(loc, removed);
}
}
return removed;
}
public synchronized T remove(T trackable) {
return remove(trackable.getLocation());
}
} |
package org.gluu.persist.ldap.operation.impl;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;
import org.gluu.persist.exception.operation.ConfigurationException;
import org.gluu.persist.operation.auth.PasswordEncryptionMethod;
import org.gluu.util.ArrayHelper;
import org.gluu.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.unboundid.ldap.sdk.BindRequest;
import com.unboundid.ldap.sdk.FailoverServerSet;
import com.unboundid.ldap.sdk.GetEntryLDAPConnectionPoolHealthCheck;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPConnectionOptions;
import com.unboundid.ldap.sdk.LDAPConnectionPool;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.ldap.sdk.SimpleBindRequest;
import com.unboundid.util.ssl.SSLUtil;
import com.unboundid.util.ssl.TrustAllTrustManager;
import com.unboundid.util.ssl.TrustStoreTrustManager;
/**
* @author Yuriy Movchan
*/
public class LdapConnectionProvider {
private static final Logger LOG = LoggerFactory.getLogger(LdapConnectionProvider.class);
private static final int DEFAULT_SUPPORTED_LDAP_VERSION = 2;
private static final String DEFAULT_SUBSCHEMA_SUBENTRY = "cn=schema";
private static final String[] SSL_PROTOCOLS = {"TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"};
private LDAPConnectionPool connectionPool;
private ResultCode creationResultCode;
private int supportedLDAPVersion = DEFAULT_SUPPORTED_LDAP_VERSION;
private String subschemaSubentry = DEFAULT_SUBSCHEMA_SUBENTRY;
private String[] servers;
private String[] addresses;
private int[] ports;
private String bindDn;
private String bindPassword;
private boolean useSSL;
private ArrayList<PasswordEncryptionMethod> additionalPasswordMethods;
private ArrayList<String> binaryAttributes, certificateAttributes;
private boolean supportsSubtreeDeleteRequestControl;
protected LdapConnectionProvider() {
}
public LdapConnectionProvider(Properties props) {
create(props);
}
protected void create(Properties props) {
try {
init(props);
} catch (LDAPException ex) {
creationResultCode = ex.getResultCode();
Properties clonedProperties = (Properties) props.clone();
if (clonedProperties.getProperty("bindPassword") != null) {
clonedProperties.setProperty("bindPassword", "REDACTED");
}
LOG.error("Failed to create connection pool with properties: " + clonedProperties, ex);
} catch (Exception ex) {
Properties clonedProperties = (Properties) props.clone();
if (clonedProperties.getProperty("bindPassword") != null) {
clonedProperties.setProperty("bindPassword", "REDACTED");
}
LOG.error("Failed to create connection pool with properties: " + clonedProperties, ex);
}
}
/**
* This method is used to create LDAPConnectionPool
*
* @throws NumberFormatException
* @throws LDAPException
* @throws GeneralSecurityException
* @throws EncryptionException
* @throws EncryptionException
*/
protected void init(Properties props) throws NumberFormatException, LDAPException, GeneralSecurityException {
String serverProp = props.getProperty("servers");
this.servers = serverProp.split(",");
this.addresses = new String[this.servers.length];
this.ports = new int[this.servers.length];
for (int i = 0; i < this.servers.length; i++) {
String str = this.servers[i];
int idx = str.indexOf(":");
if (idx == -1) {
throw new ConfigurationException("Ldap server settings should be in format server:port");
}
this.addresses[i] = str.substring(0, idx).trim();
this.ports[i] = Integer.parseInt(str.substring(str.indexOf(":") + 1, str.length()));
}
BindRequest bindRequest = null;
if (StringHelper.isEmpty(props.getProperty("bindDN"))) {
this.bindDn = null;
this.bindPassword = null;
bindRequest = new SimpleBindRequest();
} else {
this.bindDn = props.getProperty("bindDN");
this.bindPassword = props.getProperty("bindPassword");
bindRequest = new SimpleBindRequest(this.bindDn, this.bindPassword);
}
LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions();
connectionOptions.setConnectTimeoutMillis(100 * 1000);
connectionOptions.setAutoReconnect(true);
this.useSSL = Boolean.valueOf(props.getProperty("useSSL")).booleanValue();
SSLUtil sslUtil = null;
FailoverServerSet failoverSet;
if (this.useSSL) {
String sslTrustStoreFile = props.getProperty("ssl.trustStoreFile");
String sslTrustStorePin = props.getProperty("ssl.trustStorePin");
String sslTrustStoreFormat = props.getProperty("ssl.trustStoreFormat");
if (StringHelper.isEmpty(sslTrustStoreFile) && StringHelper.isEmpty(sslTrustStorePin)) {
sslUtil = new SSLUtil(new TrustAllTrustManager());
} else {
TrustStoreTrustManager trustStoreTrustManager = new TrustStoreTrustManager(sslTrustStoreFile, sslTrustStorePin.toCharArray(),
sslTrustStoreFormat, true);
sslUtil = new SSLUtil(trustStoreTrustManager);
}
failoverSet = new FailoverServerSet(this.addresses, this.ports, sslUtil.createSSLSocketFactory(SSL_PROTOCOLS[0]), connectionOptions);
} else {
failoverSet = new FailoverServerSet(this.addresses, this.ports, connectionOptions);
}
int maxConnections = StringHelper.toInt(props.getProperty("maxconnections"), 10);
this.connectionPool = createConnectionPoolWithWaitImpl(props, failoverSet, bindRequest, connectionOptions, maxConnections, sslUtil);
if (this.connectionPool != null) {
this.connectionPool.setCreateIfNecessary(true);
String connectionMaxWaitTime = props.getProperty("connection.max-wait-time-millis");
if (StringHelper.isNotEmpty(connectionMaxWaitTime)) {
this.connectionPool.setMaxWaitTimeMillis(Long.parseLong(connectionMaxWaitTime));
}
String maxConnectionAge = props.getProperty("connection.max-age-time-millis");
if (StringHelper.isNotEmpty(connectionMaxWaitTime)) {
this.connectionPool.setMaxConnectionAgeMillis(Long.parseLong(maxConnectionAge));
}
boolean onCheckoutHealthCheckEnabled = StringHelper.toBoolean(props.getProperty("connection-pool.health-check.on-checkout.enabled"), false);
long healthCheckIntervalMillis = StringHelper.toLong(props.getProperty("connection-pool.health-check.interval-millis"), 0);
long healthCheckMaxResponsetimeMillis = StringHelper.toLong(props.getProperty("connection-pool.health-check.max-response-time-millis"), 0);
boolean backgroundHealthCheckEnabled = !onCheckoutHealthCheckEnabled && (healthCheckIntervalMillis > 0);
// Because otherwise it has no effect anyway
if (backgroundHealthCheckEnabled) {
this.connectionPool.setHealthCheckIntervalMillis(healthCheckIntervalMillis);
}
if (onCheckoutHealthCheckEnabled || backgroundHealthCheckEnabled) {
GetEntryLDAPConnectionPoolHealthCheck healthChecker = new GetEntryLDAPConnectionPoolHealthCheck(// entryDN (null means root DSE)
null, // maxResponseTime
healthCheckMaxResponsetimeMillis, // invokeOnCreate
false, // invokeOnCheckout
onCheckoutHealthCheckEnabled, // invokeOnRelease
false, // invokeForBackgroundChecks
backgroundHealthCheckEnabled, // invokeOnException
false);
this.connectionPool.setHealthCheck(healthChecker);
}
}
this.additionalPasswordMethods = new ArrayList<PasswordEncryptionMethod>();
if (props.containsKey("additionalPasswordMethods")) {
String[] additionalPasswordMethodsArray = StringHelper.split(props.get("additionalPasswordMethods").toString(), ",");
for (String additionalPasswordMethod : additionalPasswordMethodsArray) {
PasswordEncryptionMethod passwordEncryptionMethod = PasswordEncryptionMethod.getMethod(additionalPasswordMethod);
if (passwordEncryptionMethod != null) {
this.additionalPasswordMethods.add(passwordEncryptionMethod);
}
}
}
LOG.debug("Adding support for password methods: " + this.additionalPasswordMethods);
this.binaryAttributes = new ArrayList<String>();
if (props.containsKey("binaryAttributes")) {
String[] binaryAttrs = StringHelper.split(props.get("binaryAttributes").toString().toLowerCase(), ",");
this.binaryAttributes.addAll(Arrays.asList(binaryAttrs));
}
LOG.debug("Using next binary attributes: " + this.binaryAttributes);
this.certificateAttributes = new ArrayList<String>();
if (props.containsKey("certificateAttributes")) {
String[] binaryAttrs = StringHelper.split(props.get("certificateAttributes").toString().toLowerCase(), ",");
this.certificateAttributes.addAll(Arrays.asList(binaryAttrs));
}
LOG.debug("Using next binary certificateAttributes: " + this.certificateAttributes);
this.supportedLDAPVersion = determineSupportedLdapVersion();
this.subschemaSubentry = determineSubschemaSubentry();
this.supportsSubtreeDeleteRequestControl = supportsSubtreeDeleteRequestControl();
this.creationResultCode = ResultCode.SUCCESS;
}
private LDAPConnectionPool createConnectionPoolWithWaitImpl(Properties props, FailoverServerSet failoverSet, BindRequest bindRequest,
LDAPConnectionOptions connectionOptions, int maxConnections, SSLUtil sslUtil) throws LDAPException {
int connectionPoolMaxWaitTimeSeconds = StringHelper.toInt(props.getProperty("connection-pool-max-wait-time"), 30);
LOG.debug("Using LDAP connection pool timeout: '" + connectionPoolMaxWaitTimeSeconds + "'");
LDAPConnectionPool createdConnectionPool = null;
LDAPException lastException = null;
int attempt = 0;
long currentTime = System.currentTimeMillis();
long maxWaitTime = currentTime + connectionPoolMaxWaitTimeSeconds * 1000;
do {
attempt++;
if (attempt > 0) {
LOG.info("Attempting to create connection pool: " + attempt);
}
try {
createdConnectionPool = createConnectionPoolImpl(failoverSet, bindRequest, connectionOptions, maxConnections, sslUtil);
break;
} catch (LDAPException ex) {
if (ex.getResultCode().intValue() != ResultCode.CONNECT_ERROR_INT_VALUE) {
throw ex;
}
lastException = ex;
}
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
LOG.error("Exception happened in sleep", ex);
return null;
}
currentTime = System.currentTimeMillis();
} while (maxWaitTime > currentTime);
if ((createdConnectionPool == null) && (lastException != null)) {
throw lastException;
}
return createdConnectionPool;
}
private LDAPConnectionPool createConnectionPoolImpl(FailoverServerSet failoverSet, BindRequest bindRequest,
LDAPConnectionOptions connectionOptions, int maxConnections, SSLUtil sslUtil) throws LDAPException {
LDAPConnectionPool createdConnectionPool;
try {
createdConnectionPool = new LDAPConnectionPool(failoverSet, bindRequest, maxConnections);
} catch (LDAPException ex) {
if (!this.useSSL) {
throw ex;
}
// Error when LDAP server not supports specified encryption
if (ex.getResultCode() != ResultCode.SERVER_DOWN) {
throw ex;
}
LOG.info("Attempting to use older SSL protocols", ex);
createdConnectionPool = createSSLConnectionPoolWithPreviousProtocols(sslUtil, bindRequest, connectionOptions, maxConnections);
if (createdConnectionPool == null) {
throw ex;
}
}
return createdConnectionPool;
}
private LDAPConnectionPool createSSLConnectionPoolWithPreviousProtocols(SSLUtil sslUtil, BindRequest bindRequest,
LDAPConnectionOptions connectionOptions, int maxConnections) throws LDAPException {
for (int i = 1; i < SSL_PROTOCOLS.length; i++) {
String protocol = SSL_PROTOCOLS[i];
try {
FailoverServerSet failoverSet = new FailoverServerSet(this.addresses, this.ports, sslUtil.createSSLSocketFactory(protocol),
connectionOptions);
LDAPConnectionPool connectionPool = new LDAPConnectionPool(failoverSet, bindRequest, maxConnections);
LOG.info("Server supports: '" + protocol + "'");
return connectionPool;
} catch (GeneralSecurityException ex) {
LOG.debug("Server not supports: '" + protocol + "'", ex);
} catch (LDAPException ex) {
// Error when LDAP server not supports specified encryption
if (ex.getResultCode() != ResultCode.SERVER_DOWN) {
throw ex;
}
LOG.debug("Server not supports: '" + protocol + "'", ex);
}
}
return null;
}
private int determineSupportedLdapVersion() {
int resultSupportedLDAPVersion = LdapConnectionProvider.DEFAULT_SUPPORTED_LDAP_VERSION;
boolean validConnection = isValidConnection();
if (!validConnection) {
return resultSupportedLDAPVersion;
}
try {
String[] supportedLDAPVersions = connectionPool.getRootDSE().getAttributeValues("supportedLDAPVersion");
if (ArrayHelper.isEmpty(supportedLDAPVersions)) {
return resultSupportedLDAPVersion;
}
for (String supportedLDAPVersion : supportedLDAPVersions) {
resultSupportedLDAPVersion = Math.max(resultSupportedLDAPVersion, Integer.parseInt(supportedLDAPVersion));
}
} catch (Exception ex) {
LOG.error("Failed to determine supportedLDAPVersion", ex);
}
return resultSupportedLDAPVersion;
}
private String determineSubschemaSubentry() {
String resultSubschemaSubentry = LdapConnectionProvider.DEFAULT_SUBSCHEMA_SUBENTRY;
boolean validConnection = isValidConnection();
if (!validConnection) {
return resultSubschemaSubentry;
}
try {
String subschemaSubentry = connectionPool.getRootDSE().getAttributeValue("subschemaSubentry");
if (StringHelper.isEmpty(subschemaSubentry)) {
return resultSubschemaSubentry;
}
resultSubschemaSubentry = subschemaSubentry;
} catch (Exception ex) {
LOG.error("Failed to determine subschemaSubentry", ex);
}
return resultSubschemaSubentry;
}
private boolean supportsSubtreeDeleteRequestControl() {
boolean supportsSubtreeDeleteRequestControl = false;
boolean validConnection = isValidConnection();
if (!validConnection) {
return supportsSubtreeDeleteRequestControl;
}
try {
supportsSubtreeDeleteRequestControl = connectionPool.getRootDSE()
.supportsControl(com.unboundid.ldap.sdk.controls.SubtreeDeleteRequestControl.SUBTREE_DELETE_REQUEST_OID);
} catch (Exception ex) {
LOG.error("Failed to determine if LDAP server supports Subtree Delete Request Control", ex);
}
return supportsSubtreeDeleteRequestControl;
}
private boolean isValidConnection() {
if (StringHelper.isEmptyString(bindDn) || StringHelper.isEmptyString(bindPassword)) {
return false;
}
if (connectionPool == null) {
return false;
}
return true;
}
public int getSupportedLDAPVersion() {
return supportedLDAPVersion;
}
public String getSubschemaSubentry() {
return subschemaSubentry;
}
public boolean isSupportsSubtreeDeleteRequestControl() {
return supportsSubtreeDeleteRequestControl;
}
/**
* This method is used to get LDAP connection from connectionPool if the
* connection is not available it will return new connection
*
* @return LDAPConnection from the connectionPool
* @throws LDAPException
*/
public LDAPConnection getConnection() throws LDAPException {
return connectionPool.getConnection();
}
/**
* Use this method to get connection pool instance;
*
* @return LDAPConnectionPool
* @throws LDAPException
* @throws NumberFormatException
*/
/**
* Use this static method to release LDAPconnection to LDAPConnectionpool
*
* @param connection
*/
public void releaseConnection(LDAPConnection connection) {
connectionPool.releaseConnection(connection);
}
/**
* This method to release back the connection after a exception occured
*
* @param connection
* @param ex
* (LDAPException)
*/
public void releaseConnection(LDAPConnection connection, LDAPException ex) {
connectionPool.releaseConnectionAfterException(connection, ex);
}
/**
* This method is used to release back a connection that is no longer been used
* or fit to be used
*
* @param connection
*/
public void closeDefunctConnection(LDAPConnection connection) {
connectionPool.releaseDefunctConnection(connection);
}
public LDAPConnectionPool getConnectionPool() {
return connectionPool;
}
public void closeConnectionPool() {
connectionPool.close();
}
public boolean isConnected() {
if (connectionPool == null) {
return false;
}
boolean isConnected = false;
try {
LDAPConnection connection = getConnection();
try {
isConnected = connection.isConnected();
} finally {
releaseConnection(connection);
}
} catch (LDAPException ex) {
}
return isConnected;
}
public ResultCode getCreationResultCode() {
return creationResultCode;
}
public void setCreationResultCode(ResultCode creationResultCode) {
this.creationResultCode = creationResultCode;
}
public boolean isCreated() {
return ResultCode.SUCCESS == this.creationResultCode;
}
public String[] getServers() {
return servers;
}
public String[] getAddresses() {
return addresses;
}
public int[] getPorts() {
return ports;
}
public String getBindDn() {
return bindDn;
}
public String getBindPassword() {
return bindPassword;
}
public boolean isUseSSL() {
return useSSL;
}
public final ArrayList<PasswordEncryptionMethod> getAdditionalPasswordMethods() {
return additionalPasswordMethods;
}
public ArrayList<String> getBinaryAttributes() {
return binaryAttributes;
}
public ArrayList<String> getCertificateAttributes() {
return certificateAttributes;
}
public boolean isBinaryAttribute(String attributeName) {
if (StringHelper.isEmpty(attributeName)) {
return false;
}
return binaryAttributes.contains(attributeName.toLowerCase());
}
public boolean isCertificateAttribute(String attributeName) {
String realAttributeName = getCertificateAttributeName(attributeName);
return certificateAttributes.contains(realAttributeName.toLowerCase());
}
public String getCertificateAttributeName(String attributeName) {
if (StringHelper.isEmpty(attributeName)) {
return attributeName;
}
if (attributeName.endsWith(";binary")) {
return attributeName.substring(0, attributeName.length() - 7);
}
return attributeName;
}
} |
package com.redshape.persistence.dao.query;
import com.redshape.persistence.dao.query.expressions.IExpression;
import com.redshape.persistence.dao.query.statements.IStatement;
import com.redshape.persistence.entities.IEntity;
import java.util.List;
import java.util.Map;
/**
* @author nikelin
*/
public class NamedQuery implements IQuery {
private IQuery query;
private String name;
public NamedQuery( IQuery query, String name ) {
this.query = query;
this.name = name;
}
@Override
public IQuery where( IExpression expression ) {
return this.query.where(expression);
}
@SuppressWarnings("unchecked")
@Override
public <T extends IEntity> Class<T> getEntityClass() {
return (Class<T>) this.query.getEntityClass();
}
@Override
public boolean hasAttribute( String name ) {
return this.query.hasAttribute(name);
}
@Override
public <T> Map<String, T> getAttributes() {
return this.query.getAttributes();
}
@Override
public <T extends IExpression> T getExpression() {
return this.query.<T>getExpression();
}
@Override
public boolean isStatic() {
return this.query.isStatic();
}
public String getName() {
return this.name;
}
@Override
public IQuery setAttribute(String name, Object value) {
this.query.setAttribute(name, value);
return this;
}
@Override
public <T> T getAttribute(String name) throws QueryExecutorException {
return this.query.<T>getAttribute(name);
}
@Override
public int getOffset() {
return this.query.getOffset();
}
@Override
public IQuery setOffset( int offset ) {
this.query.setOffset(offset);
return this;
}
@Override
public int getLimit() {
return this.query.getLimit();
}
@Override
public IQuery setLimit( int limit ) {
this.query.setLimit(limit);
return this;
}
@Override
public IQuery setAttributes(Map<String, Object> attributes) {
this.query.setAttributes(attributes);
return this;
}
@Override
public List<IStatement> select() {
return this.query.select();
}
@Override
public IQuery select(IStatement... statements) {
this.query.select(statements);
return this;
}
@Override
public OrderDirection orderDirection() {
return this.query.orderDirection();
}
@Override
public IStatement orderField() {
return this.query.orderField();
}
@Override
public IQuery orderBy(IStatement field, OrderDirection direction) {
this.query.orderBy(field, direction);
return this;
}
@Override
public List<IStatement> groupBy() {
return this.query.groupBy();
}
@Override
public IQuery groupBy(IStatement... statements) {
return this.query.groupBy(statements);
}
@Override
public IEntity entity() {
return this.query.entity();
}
@Override
public IQuery entity(IEntity entity) {
this.query.entity(entity);
return this;
}
@Override
public boolean isNative() {
return this.query.isNative();
}
@Override
public IQuery duplicate() {
return this.query.duplicate();
}
@Override
public boolean isUpdate() {
return query.isUpdate();
}
@Override
public boolean isCount() {
return query.isUpdate();
}
@Override
public boolean isRemove() {
return query.isRemove();
}
@Override
public boolean isCreate() {
return query.isCreate();
}
} |
package org.elasticsearch.xpack.monitoring.resolver.indices;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.xpack.monitoring.test.MonitoringIntegTestCase;
import org.junit.After;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.greaterThan;
@ClusterScope(scope = Scope.TEST, numClientNodes = 0)
@LuceneTestCase.AwaitsFix(bugUrl = "https://github.com/elastic/x-pack-elasticsearch/issues/496")
public class IndicesStatsTests extends MonitoringIntegTestCase {
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(MonitoringSettings.INTERVAL.getKey(), "-1")
.put("xpack.monitoring.exporters.default_local.type", "local")
.build();
}
@After
public void cleanup() throws Exception {
disableMonitoringInterval();
wipeMonitoringIndices();
}
public void testIndicesStats() throws Exception {
logger.debug("--> creating some indices for future indices stats");
final int nbIndices = randomIntBetween(1, 5);
for (int i = 0; i < nbIndices; i++) {
createIndex("stat-" + i);
}
final long[] nbDocsPerIndex = new long[nbIndices];
for (int i = 0; i < nbIndices; i++) {
nbDocsPerIndex[i] = randomIntBetween(1, 50);
for (int j = 0; j < nbDocsPerIndex[i]; j++) {
client().prepareIndex("stat-" + i, "type1").setSource("num", i).get();
}
}
logger.debug("--> wait for indices stats collector to collect stats for all primaries shards");
assertBusy(new Runnable() {
@Override
public void run() {
flush();
refresh();
for (int i = 0; i < nbIndices; i++) {
IndicesStatsResponse indicesStats = client().admin().indices().prepareStats().get();
assertThat(indicesStats.getPrimaries().getDocs().getCount(), greaterThan(0L));
}
}
});
updateMonitoringInterval(3L, TimeUnit.SECONDS);
waitForMonitoringIndices();
logger.debug("--> wait for indices stats collector to collect global stat");
awaitMonitoringDocsCount(greaterThan(0L), IndicesStatsResolver.TYPE);
logger.debug("--> searching for monitoring documents of type [{}]", IndicesStatsResolver.TYPE);
SearchResponse response = client().prepareSearch().setTypes(IndicesStatsResolver.TYPE).get();
assertThat(response.getHits().getTotalHits(), greaterThan(0L));
logger.debug("--> checking that every document contains the expected fields");
for (SearchHit searchHit : response.getHits().getHits()) {
Map<String, Object> fields = searchHit.getSourceAsMap();
for (String filter : IndicesStatsResolver.FILTERS) {
assertContains(filter, fields);
}
}
logger.debug("--> indices stats successfully collected");
}
} |
package com.intellij.externalSystem;
import com.intellij.buildsystem.model.unified.UnifiedDependency;
import org.junit.Test;
public class GradleDependencyUpdaterTest extends GradleDependencyUpdaterTestBase {
@Test
public void testAddDependency() throws Exception {
importProjectFromTemplate();
assertTrue(myModifierService.supports(getModule("project")));
myModifierService.addDependency(getModule("project"),
new UnifiedDependency("group", "artifact", "1.0", null));
importProject();
assertScriptChanged();
assertModuleLibDep("project.main", "Gradle: group:artifact:1.0");
}
@Test
public void testUpdateDependencyShortNotation() throws Exception {
importProjectFromTemplate();
assertTrue(myModifierService.supports(getModule("project")));
myModifierService.updateDependency(getModule("project"),
new UnifiedDependency("group", "artifact", "1.0", null),
new UnifiedDependency("group", "artifact", "2.0", null));
importProject();
assertScriptChanged();
assertModuleLibDeps("project.main", "Gradle: group:artifact:2.0", "Gradle: another:artifact:1.0");
}
@Test
public void testUpdateDependencyLongNotation() throws Exception {
importProjectFromTemplate();
assertTrue(myModifierService.supports(getModule("project")));
myModifierService.updateDependency(getModule("project"),
new UnifiedDependency("group", "artifact", "1.0", null),
new UnifiedDependency("group", "artifact", "2.0", null));
importProject();
assertScriptChanged();
assertModuleLibDeps("project.main", "Gradle: group:artifact:2.0", "Gradle: another:artifact:1.0");
}
@Test
public void testRemoveDependency() throws Exception {
importProjectFromTemplate();
assertTrue(myModifierService.supports(getModule("project")));
myModifierService.removeDependency(getModule("project"),
new UnifiedDependency("group", "artifact", "1.0", null));
importProject();
assertScriptChanged();
assertModuleLibDeps("project.main", "Gradle: another:artifact:1.0");
}
@Test
public void testUpdateDependencyWithVariableLongNotation() throws Exception {
importProjectFromTemplate();
assertTrue(myModifierService.supports(getModule("project")));
myModifierService.updateDependency(getModule("project"),
new UnifiedDependency("group", "artifact", "1.0", null),
new UnifiedDependency("group", "artifact", "2.0", null));
importProject();
assertScriptChanged();
}
@Test
public void testUpdateDependencyWithExtVariableLongNotation() throws Exception {
importProjectFromTemplate();
assertTrue(myModifierService.supports(getModule("project")));
myModifierService.updateDependency(getModule("project"),
new UnifiedDependency("group", "artifact", "1.0", null),
new UnifiedDependency("group", "artifact", "2.0", null));
importProject();
assertScriptChanged();
}
} |
package org.csstudio.opibuilder.util;
import org.diirt.vtype.AlarmSeverity;
/**
* BEAST alarm info for PV Widgets.
* Holds the BeastDataSource channel name, blinking state, current & latched BEAST severity.
*
* @author Boris Versic
*/
public final class BeastAlarmInfo {
private String alarmPVChannelName;
private boolean isBeastChannelConnected;
private BeastAlarmSeverityLevel latchedSeverity;
private BeastAlarmSeverityLevel currentSeverity;
private int alarmPVsCount;
/**
* The blinking "state" for the Beast Alarm alert: 0 = default color, 1 = severity color.
*/
private int beastAlertBlinkState = 0;
public BeastAlarmInfo() {
alarmPVChannelName = "";
isBeastChannelConnected = false;
latchedSeverity = BeastAlarmSeverityLevel.OK;
currentSeverity = BeastAlarmSeverityLevel.OK;
}
/**
* Get the Current severity of the BEAST alarm.
* @return the Current Severity of the BEAST alarm, see {@link BeastAlarmSeverityLevel}.
*/
public BeastAlarmSeverityLevel getCurrentSeverity() {
return currentSeverity;
}
/**
* Get the AlarmSeverity of the Current BEAST alarm severity.
* Returns the {@link AlarmSeverity} of the Current {@link BeastAlarmSeverityLevel},
* i.e. without the ack/unack distinction.
*
* @return the AlarmSeverity of the BEAST alarm Current Severity.
*/
public AlarmSeverity getCurrentAlarmSeverity() {
return currentSeverity.getAlarmSeverity();
}
/**
* Set the Current severity of the BEAST alarm.
* @param currentSeverity the Current Severity of the BEAST alarm, see {@link BeastAlarmSeverityLevel}.
*/
public void setCurrentSeverity(BeastAlarmSeverityLevel currentSeverity) {
this.currentSeverity = currentSeverity;
}
/**
* Get the Latched severity of the BEAST alarm.
* @return the Latched Severity of the BEAST alarm, see {@link BeastAlarmSeverityLevel}.
*/
public BeastAlarmSeverityLevel getLatchedSeverity() {
return currentSeverity;
}
/**
* Get the AlarmSeverity of the Latched BEAST alarm severity.
* Returns the {@link AlarmSeverity} of the Latched {@link BeastAlarmSeverityLevel},
* i.e. without the ack/unack distinction.
*
* @return the AlarmSeverity of the BEAST alarm Latched Severity.
*/
public AlarmSeverity getLatchedAlarmSeverity() {
return latchedSeverity.getAlarmSeverity();
}
/**
* Set the Latched severity of the BEAST alarm.
* @param latchedSeverity the Latched Severity of the BEAST alarm, see {@link BeastAlarmSeverityLevel}.
*/
public void setLatchedSeverity(BeastAlarmSeverityLevel latchedSeverity) {
this.latchedSeverity = latchedSeverity;
}
/**
* Get the next color to be used for blinking the Beast Alarm alert:
* {@code 0} = default color (used for {@link AlarmSeverity#OK}),
* {@code 1} = current severity color
*
* @return the blinking "state" for the Beast Alarm alert
*/
public int getBeastAlertBlinkState() {
return beastAlertBlinkState;
}
/**
* Set the blinking "state" for the Beast Alarm alert:
* passing {@code 0} will use the default color ({@link AlarmSeverity#OK}) for the next Blink change,
* {@code 1} will use the current severity's color.
*
* @param beastAlertBlinkState the beastAlertBlinkState to set
*/
public void setBeastAlertBlinkState(int beastAlertBlinkState) {
this.beastAlertBlinkState = beastAlertBlinkState;
}
/**
* Set the BeastDataSource Channel name for this BEAST Alarm.
* @param channelName the BeastDataSource Channel name to set
*/
public void setBeastChannelName(String channelName) {
alarmPVChannelName = channelName;
}
/**
* Get the BeastDataSource Channel name of this BEAST Alarm.
* @return the BeastDataSource Channel name of this BEAST Alarm
*/
public String getBeastChannelName() {
return alarmPVChannelName;
}
/**
* Get the BeastDataSource Channel name of this BEAST Alarm without the scheme/channel protocol (the initial "beast://").
* @return the BeastDataSource Channel name of this BEAST Alarm without the scheme
*/
public String getBeastChannelNameWithoutScheme() {
if (alarmPVChannelName.length() > 8)
return alarmPVChannelName.substring(8);
return "";
}
/**
* Is the Latched BEAST alarm Acknowledged ?
* See {@link BeastAlarmSeverityLevel#isActive}.
*
* @return {@code true} if (latched) severity indicates an acknowledged alarm state,
* {@code false} for unacknowledged alarm or OK
*/
public boolean isAcknowledged() {
return !latchedSeverity.isActive() && latchedSeverity != BeastAlarmSeverityLevel.OK;
}
/**
* Is the Latched BEAST alarm Active (not OK or Acknowledged) ?
* See {@link BeastAlarmSeverityLevel#isActive}.
*
* @return {@code true} if latched severity indicates an active alarm,
* {@code false} for acknowledged or OK state
*/
public boolean isLatchedAlarmActive() {
return latchedSeverity.isActive();
}
/**
* Is the Latched BEAST alarm OK ?
* @return {@code true} if the Latched Severity is OK, {@code false} for any other state.
*/
public boolean isLatchedAlarmOK() {
return latchedSeverity == BeastAlarmSeverityLevel.OK;
}
/**
* Is the Current BEAST alarm Active (not OK or Acknowledged) ?
* See {@link BeastAlarmSeverityLevel#isActive}.
*
* @return {@code true} if current severity indicates an active alarm,
* {@code false} for acknowledged or OK state
*/
public boolean isCurrentAlarmActive() {
return currentSeverity.isActive();
}
/**
* Reset the Current and Latched severities for this BEAST alarm and set the beastAlertBlinkState to 0.
*/
public void reset() {
latchedSeverity = BeastAlarmSeverityLevel.OK;
currentSeverity = BeastAlarmSeverityLevel.OK;
beastAlertBlinkState = 0;
}
/**
* Is the BeastDataSource channel for this PV connected ?
* @return {@code true} if the PVReader reported it successfully connected or we received at least
* one ValueChanged event from it, {@code false} otherwise.
*/
public boolean isBeastChannelConnected() {
return isBeastChannelConnected;
}
/**
* Set the current BeastDataSource connection status.
* @param connected {@code true} if the PVReader reported it successfully connected or we received at least
* one ValueChanged event from it, {@code false} otherwise.
*/
public void setBeastChannelConnected(boolean connected) {
isBeastChannelConnected = connected;
}
/**
* Get the number of PVs in alarm state.
* @return The number of PVs whose Latched severity is not {@code SeverityLevel.OK}.
*/
public int getAlarmPVsCount() {
return alarmPVsCount;
}
/**
* Set the number of PVs in alarm state.
* @param count The number of PVs whose Latched severity is not {@code SeverityLevel.OK}.
*/
public void setAlarmPVsCount(int count) {
alarmPVsCount = count;
}
} |
package org.eclipse.xtext.junit4.internal;
import static org.eclipse.xtext.xbase.lib.IterableExtensions.*;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.xtext.util.Files;
import org.junit.Test;
/**
* @author dhuebner - Initial contribution and API
*/
public class InternalBuilderTest {
@Test
public void test() throws CoreException, FileNotFoundException {
reportMemoryState("Starting build.");
try {
clearJdtIndex();
ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
} finally {
clearJdtIndex();
reportMemoryState("Finished build.");
}
final IMarker[] markers = ResourcesPlugin.getWorkspace().getRoot()
.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
List<String> errors = new ArrayList<String>();
for (IMarker marker : markers) {
String msg = MarkerUtilities.getMessage(marker);
if (MarkerUtilities.getSeverity(marker) == IMarker.SEVERITY_ERROR) {
errors.add(msg);
}
}
List<String> top10;
if (errors.size() > 10) {
top10 = toList(take(errors, 10));
} else {
top10 = errors;
}
assertTrue("Problems found (" + top10.size() + " of " + errors.size() + "): " + join(errors, ", "),
errors.isEmpty());
}
private void clearJdtIndex() throws FileNotFoundException {
File jdtMetadata = JavaCore.getPlugin().getStateLocation().toFile();
boolean success = Files.sweepFolder(jdtMetadata);
System.out.println("Clean up index " + jdtMetadata.getAbsolutePath() + ": "
+ (success ? "success" : "fail"));
}
private void reportMemoryState(String reportName) {
System.out.println(reportName + " Memory max=" + Runtime.getRuntime().maxMemory() / (1024 * 1024) + "m, total="
+ Runtime.getRuntime().totalMemory() / (1024 * 1024) + "m, free=" + Runtime.getRuntime().freeMemory()
/ (1024 * 1024) + "m");
}
} |
package org.jkiss.dbeaver.tools.transfer.wizard;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.tools.transfer.IDataTransferConsumer;
import org.jkiss.dbeaver.tools.transfer.IDataTransferProducer;
import org.jkiss.dbeaver.tools.transfer.IDataTransferSettings;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
/**
* Data transfer job
*/
public class DataTransferJob extends AbstractJob {
private DataTransferSettings settings;
public DataTransferJob(DataTransferSettings settings)
{
super(CoreMessages.data_transfer_wizard_job_name);
this.settings = settings;
setUser(true);
}
@Override
public boolean belongsTo(Object family)
{
return family == settings;
}
@Override
protected IStatus run(DBRProgressMonitor monitor)
{
boolean hasErrors = false;
long startTime = System.currentTimeMillis();
for (; ;) {
DataTransferPipe transferPipe = settings.acquireDataPipe(monitor);
if (transferPipe == null) {
break;
}
if (!transferData(monitor, transferPipe)) {
hasErrors = true;
}
}
showResult(System.currentTimeMillis() - startTime, hasErrors);
return Status.OK_STATUS;
}
private void showResult(final long time, final boolean hasErrors)
{
UIUtils.showMessageBox(
null,
"Data transfer",
"Data transfer completed " + (hasErrors ? "with errors " : "") + "(" + RuntimeUtils.formatExecutionTime(time) + ")",
hasErrors ? SWT.ICON_ERROR : SWT.ICON_INFORMATION);
}
private boolean transferData(DBRProgressMonitor monitor, DataTransferPipe transferPipe)
{
IDataTransferProducer producer = transferPipe.getProducer();
IDataTransferConsumer consumer = transferPipe.getConsumer();
IDataTransferSettings consumerSettings = settings.getNodeSettings(consumer);
setName(NLS.bind(CoreMessages.data_transfer_wizard_job_container_name,
CommonUtils.truncateString(producer.getSourceObject().getName(), 200)));
IDataTransferSettings nodeSettings = settings.getNodeSettings(producer);
try {
//consumer.initTransfer(producer.getSourceObject(), consumerSettings, );
producer.transferData(
monitor,
consumer,
nodeSettings);
consumer.finishTransfer(monitor, false);
return true;
} catch (Exception e) {
new DataTransferErrorJob(e).schedule();
return false;
}
}
} |
package com.opengamma.livedata.client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.fudgemsg.FudgeContext;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.FudgeMsgEnvelope;
import org.fudgemsg.mapping.FudgeDeserializer;
import org.fudgemsg.mapping.FudgeSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.livedata.LiveDataSpecification;
import com.opengamma.livedata.LiveDataValueUpdateBean;
import com.opengamma.livedata.LiveDataValueUpdateBeanFudgeBuilder;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.livedata.msg.LiveDataSubscriptionRequest;
import com.opengamma.livedata.msg.LiveDataSubscriptionResponse;
import com.opengamma.livedata.msg.LiveDataSubscriptionResponseMsg;
import com.opengamma.livedata.msg.LiveDataSubscriptionResult;
import com.opengamma.livedata.msg.SubscriptionType;
import com.opengamma.transport.FudgeMessageReceiver;
import com.opengamma.transport.FudgeRequestSender;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.PublicAPI;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
/**
* A client that talks to a remote LiveData server through an unspecified protocol.
* Possibilities are JMS, Fudge, direct socket connection, and so on.
*/
@PublicAPI
public class DistributedLiveDataClient extends AbstractLiveDataClient implements FudgeMessageReceiver {
private static final Logger s_logger = LoggerFactory.getLogger(DistributedLiveDataClient.class);
// Injected Inputs:
private final FudgeContext _fudgeContext;
private final FudgeRequestSender _subscriptionRequestSender;
private final DistributedEntitlementChecker _entitlementChecker;
/**
* An exception will be thrown when doing a snapshot if no reply is received from the server
* within this time. Milliseconds.
*/
private static final long TIMEOUT = 30000;
public DistributedLiveDataClient(
FudgeRequestSender subscriptionRequestSender,
FudgeRequestSender entitlementRequestSender) {
this(subscriptionRequestSender, entitlementRequestSender, OpenGammaFudgeContext.getInstance());
}
public DistributedLiveDataClient(
FudgeRequestSender subscriptionRequestSender,
FudgeRequestSender entitlementRequestSender,
FudgeContext fudgeContext) {
ArgumentChecker.notNull(subscriptionRequestSender, "Subscription request sender");
ArgumentChecker.notNull(entitlementRequestSender, "Entitlement request sender");
ArgumentChecker.notNull(fudgeContext, "Fudge Context");
_subscriptionRequestSender = subscriptionRequestSender;
_fudgeContext = fudgeContext;
_entitlementChecker = new DistributedEntitlementChecker(entitlementRequestSender, fudgeContext);
}
/**
* @return the subscriptionRequestSender
*/
public FudgeRequestSender getSubscriptionRequestSender() {
return _subscriptionRequestSender;
}
/**
* @return the fudgeContext
*/
public FudgeContext getFudgeContext() {
return _fudgeContext;
}
@Override
protected void cancelPublication(LiveDataSpecification fullyQualifiedSpecification) {
s_logger.info("Request made to cancel publication of {}", fullyQualifiedSpecification);
// TODO kirk 2009-10-28 -- This should handle an unsubscription request. For now,
// however, we can just make do with allowing the heartbeat to time out.
}
@Override
protected void handleSubscriptionRequest(Collection<SubscriptionHandle> subHandles) {
ArgumentChecker.notEmpty(subHandles, "Subscription handle collection");
// Determine common user and subscription type
UserPrincipal user = null;
SubscriptionType type = null;
ArrayList<LiveDataSpecification> specs = new ArrayList<LiveDataSpecification>();
for (SubscriptionHandle subHandle : subHandles) {
specs.add(new LiveDataSpecification(subHandle.getRequestedSpecification()));
if (user == null) {
user = subHandle.getUser();
} else if (!user.equals(subHandle.getUser())) {
throw new OpenGammaRuntimeException("Not all usernames are equal");
}
if (type == null) {
type = subHandle.getSubscriptionType();
} else if (!type.equals(subHandle.getSubscriptionType())) {
throw new OpenGammaRuntimeException("Not all subscription types are equal");
}
}
// Build request message
LiveDataSubscriptionRequest subReqMessage = new LiveDataSubscriptionRequest(user, type, specs);
FudgeMsg requestMessage = subReqMessage.toFudgeMsg(new FudgeSerializer(getFudgeContext()));
// Build response receiver
FudgeMessageReceiver responseReceiver;
if (type == SubscriptionType.SNAPSHOT) {
responseReceiver = new SnapshotResponseReceiver(subHandles);
} else {
responseReceiver = new TopicBasedSubscriptionResponseReceiver(subHandles);
}
getSubscriptionRequestSender().sendRequest(requestMessage, responseReceiver);
}
/**
* Common functionality for receiving subscription responses from the server.
*/
private abstract class AbstractSubscriptionResponseReceiver implements FudgeMessageReceiver {
private final Map<LiveDataSpecification, SubscriptionHandle> _spec2SubHandle;
private final Map<SubscriptionHandle, LiveDataSubscriptionResponse> _successResponses = new HashMap<SubscriptionHandle, LiveDataSubscriptionResponse>();
private final Map<SubscriptionHandle, LiveDataSubscriptionResponse> _failedResponses = new HashMap<SubscriptionHandle, LiveDataSubscriptionResponse>();
private UserPrincipal _user;
public AbstractSubscriptionResponseReceiver(Collection<SubscriptionHandle> subHandles) {
_spec2SubHandle = new HashMap<LiveDataSpecification, SubscriptionHandle>();
for (SubscriptionHandle subHandle : subHandles) {
_spec2SubHandle.put(subHandle.getRequestedSpecification(), subHandle);
}
}
public UserPrincipal getUser() {
return _user;
}
public void setUser(UserPrincipal user) {
_user = user;
}
public Map<LiveDataSpecification, SubscriptionHandle> getSpec2SubHandle() {
return _spec2SubHandle;
}
public Map<SubscriptionHandle, LiveDataSubscriptionResponse> getSuccessResponses() {
return _successResponses;
}
public Map<SubscriptionHandle, LiveDataSubscriptionResponse> getFailedResponses() {
return _failedResponses;
}
@Override
public void messageReceived(FudgeContext fudgeContext, FudgeMsgEnvelope envelope) {
try {
if ((envelope == null) || (envelope.getMessage() == null)) {
throw new OpenGammaRuntimeException("Got a message that can't be deserialized from a Fudge message.");
}
FudgeMsg msg = envelope.getMessage();
LiveDataSubscriptionResponseMsg responseMessage = LiveDataSubscriptionResponseMsg.fromFudgeMsg(new FudgeDeserializer(getFudgeContext()), msg);
if (responseMessage.getResponses().isEmpty()) {
throw new OpenGammaRuntimeException("Got empty subscription response " + responseMessage);
}
messageReceived(responseMessage);
} catch (Exception e) {
s_logger.error("Failed to process response message", e);
for (SubscriptionHandle handle : getSpec2SubHandle().values()) {
if (handle.getSubscriptionType() != SubscriptionType.SNAPSHOT) {
subscriptionRequestFailed(handle, new LiveDataSubscriptionResponse(
handle.getRequestedSpecification(),
LiveDataSubscriptionResult.INTERNAL_ERROR,
e.toString(),
null,
null,
null));
}
}
}
}
private void messageReceived(LiveDataSubscriptionResponseMsg responseMessage) {
parseResponse(responseMessage);
processResponse();
sendResponse();
}
private void parseResponse(LiveDataSubscriptionResponseMsg responseMessage) {
for (LiveDataSubscriptionResponse response : responseMessage.getResponses()) {
SubscriptionHandle handle = getSpec2SubHandle().get(response.getRequestedSpecification());
if (handle == null) {
throw new OpenGammaRuntimeException("Could not find handle corresponding to request " + response.getRequestedSpecification());
}
if (getUser() != null && !getUser().equals(handle.getUser())) {
throw new OpenGammaRuntimeException("Not all usernames are equal");
}
setUser(handle.getUser());
if (response.getSubscriptionResult() == LiveDataSubscriptionResult.SUCCESS) {
getSuccessResponses().put(handle, response);
} else {
getFailedResponses().put(handle, response);
}
}
}
protected void processResponse() {
}
protected void sendResponse() {
Map<SubscriptionHandle, LiveDataSubscriptionResponse> responses = new HashMap<SubscriptionHandle, LiveDataSubscriptionResponse>();
responses.putAll(getSuccessResponses());
responses.putAll(getFailedResponses());
for (Map.Entry<SubscriptionHandle, LiveDataSubscriptionResponse> successEntry : responses.entrySet()) {
SubscriptionHandle handle = successEntry.getKey();
LiveDataSubscriptionResponse response = successEntry.getValue();
handle.subscriptionResultReceived(response);
}
}
}
/**
* Some market data requests are snapshot requests; this means that they do not require a JMS subscription.
*/
private class SnapshotResponseReceiver extends AbstractSubscriptionResponseReceiver {
public SnapshotResponseReceiver(Collection<SubscriptionHandle> subHandles) {
super(subHandles);
}
}
/**
* Some market data requests are non-snapshot requests where market data is continuously read from a JMS topic;
* this means they require a JMS subscription.
* <p>
* As per LIV-19, after we've subscribed to the market data (and started getting deltas), we do a snapshot
* to make sure we get a full initial image of the data. Things are done in this order (first subscribe, then snapshot)
* so we don't lose any ticks. See LIV-19.
*/
private class TopicBasedSubscriptionResponseReceiver extends AbstractSubscriptionResponseReceiver {
public TopicBasedSubscriptionResponseReceiver(Collection<SubscriptionHandle> subHandles) {
super(subHandles);
}
@Override
protected void processResponse() {
try {
// Phase 1. Create a subscription to market data topic
startReceivingTicks();
// Phase 2. After we've subscribed to the market data (and started getting deltas), snapshot it
snapshot();
} catch (RuntimeException e) {
s_logger.error("Failed to process subscription response", e);
// This is unexpected. Fail everything.
for (LiveDataSubscriptionResponse response : getSuccessResponses().values()) {
response.setSubscriptionResult(LiveDataSubscriptionResult.INTERNAL_ERROR);
response.setUserMessage(e.toString());
}
getFailedResponses().putAll(getSuccessResponses());
getSuccessResponses().clear();
}
}
private void startReceivingTicks() {
Map<SubscriptionHandle, LiveDataSubscriptionResponse> resps = getSuccessResponses();
List<String> distributionSpecs = new ArrayList<String>(resps.size());
for (Map.Entry<SubscriptionHandle, LiveDataSubscriptionResponse> entry : resps.entrySet()) {
DistributedLiveDataClient.this.subscriptionStartingToReceiveTicks(entry.getKey(), entry.getValue());
distributionSpecs.add(entry.getValue().getTickDistributionSpecification());
}
DistributedLiveDataClient.this.startReceivingTicks(distributionSpecs);
}
private void snapshot() {
ArrayList<LiveDataSpecification> successLiveDataSpecs = new ArrayList<LiveDataSpecification>();
for (LiveDataSubscriptionResponse response : getSuccessResponses().values()) {
successLiveDataSpecs.add(response.getRequestedSpecification());
}
Collection<LiveDataSubscriptionResponse> snapshots = DistributedLiveDataClient.this.snapshot(getUser(), successLiveDataSpecs, TIMEOUT);
for (LiveDataSubscriptionResponse response : snapshots) {
SubscriptionHandle handle = getSpec2SubHandle().get(response.getRequestedSpecification());
if (handle == null) {
throw new OpenGammaRuntimeException("Could not find handle corresponding to request " + response.getRequestedSpecification());
}
// could be that even though subscription to the JMS topic (phase 1) succeeded, snapshot (phase 2) for some reason failed.
// in the sub-second interval between phases 1 and 2!
// Not so. In fact for a system like Bloomberg, because of the lag in subscription, the LiveDataServer
// may in fact think that you can successfully subscribe, but then when the snapshot is requested we detect
// that it's not a valid code. So this is the time that we've actually poked the underlying data provider
// to check.
// In addition, it may be that for a FireHose server we didn't have the full SoW on the initial request
// but now we do.
if (response.getSubscriptionResult() == LiveDataSubscriptionResult.SUCCESS) {
handle.addSnapshotOnHold(response.getSnapshot());
} else {
getSuccessResponses().remove(handle);
getFailedResponses().put(handle, response);
}
}
}
@Override
protected void sendResponse() {
super.sendResponse();
for (Map.Entry<SubscriptionHandle, LiveDataSubscriptionResponse> successEntry : getSuccessResponses().entrySet()) {
SubscriptionHandle handle = successEntry.getKey();
LiveDataSubscriptionResponse response = successEntry.getValue();
subscriptionRequestSatisfied(handle, response);
}
for (Map.Entry<SubscriptionHandle, LiveDataSubscriptionResponse> failedEntry : getFailedResponses().entrySet()) {
SubscriptionHandle handle = failedEntry.getKey();
LiveDataSubscriptionResponse response = failedEntry.getValue();
subscriptionRequestFailed(handle, response);
// this is here just to clean up. It's safe to call stopReceivingTicks()
// even if no JMS subscription actually exists.
stopReceivingTicks(response.getTickDistributionSpecification());
}
}
}
/**
* @param tickDistributionSpecification JMS topic name
*/
public void startReceivingTicks(Collection<String> tickDistributionSpecification) {
// Default no-op.
}
public void stopReceivingTicks(String tickDistributionSpecification) {
// Default no-op.
}
// REVIEW kirk 2009-10-28 -- This is just a braindead way of getting ticks to come in
// until we can get a handle on the construction of receivers based on responses.
@Override
public void messageReceived(FudgeContext fudgeContext,
FudgeMsgEnvelope msgEnvelope) {
FudgeMsg fudgeMsg = msgEnvelope.getMessage();
LiveDataValueUpdateBean update = LiveDataValueUpdateBeanFudgeBuilder.fromFudgeMsg(new FudgeDeserializer(fudgeContext), fudgeMsg);
valueUpdate(update);
}
@Override
public Map<LiveDataSpecification, Boolean> isEntitled(UserPrincipal user,
Collection<LiveDataSpecification> requestedSpecifications) {
return _entitlementChecker.isEntitled(user, requestedSpecifications);
}
@Override
public boolean isEntitled(UserPrincipal user, LiveDataSpecification requestedSpecification) {
return _entitlementChecker.isEntitled(user, requestedSpecification);
}
} |
package pl.grzeslowski.jsupla.protocol.api.channelvalues;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
public final class ChannelValueSwitch<T> {
private final Callback<T> callback;
public ChannelValueSwitch(final Callback<T> callback) {
this.callback = requireNonNull(callback);
}
public T doSwitch(ChannelValue channelValue) {
if (channelValue instanceof DecimalValue) {
return callback.onDecimalValue((DecimalValue) channelValue);
} else if (channelValue instanceof OnOff) {
return callback.onOnOff((OnOff) channelValue);
} else if (channelValue instanceof OpenClose) {
return callback.onOpenClose((OpenClose) channelValue);
} else if (channelValue instanceof PercentValue) {
return callback.onPercentValue((PercentValue) channelValue);
} else if (channelValue instanceof RgbValue) {
return callback.onRgbValue((RgbValue) channelValue);
} else if (channelValue instanceof StoppableOpenClose) {
return callback.onStoppableOpenClose((StoppableOpenClose) channelValue);
} else if (channelValue instanceof TemperatureAndHumidityValue) {
return callback.onTemperatureAndHumidityValue((TemperatureAndHumidityValue) channelValue);
} else if (channelValue instanceof UnknownValue) {
return callback.onUnknownValue((UnknownValue) channelValue);
} else {
throw new IllegalArgumentException(format("Don't know where to dispatch channel value with class %s! " +
"This should NEVER occur on production!",
channelValue.getClass().getSimpleName()));
}
}
@SuppressWarnings("UnusedReturnValue")
public interface Callback<T> {
T onDecimalValue(DecimalValue decimalValue);
T onOnOff(OnOff onOff);
T onOpenClose(OpenClose openClose);
T onPercentValue(PercentValue percentValue);
T onRgbValue(RgbValue rgbValue);
T onStoppableOpenClose(StoppableOpenClose stoppableOpenClose);
T onTemperatureAndHumidityValue(TemperatureAndHumidityValue temperatureAndHumidityValue);
T onUnknownValue(UnknownValue unknownValue);
}
} |
package org.ow2.proactive_grid_cloud_portal.scheduler.dto;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.ow2.proactive.db.types.BigString;
@XmlRootElement
public class JobStateData {
@XmlTransient
private static ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(Inclusion.NON_NULL);
private String name;
private String priority;
private String owner;
private JobInfoData jobInfo;
private String projectName;
private Map<String, TaskStateData> tasks;
private Map<String, BigString> genericInformations = new HashMap<String, BigString>();
public Map<String, BigString> getGenericInformations() {
return genericInformations;
}
public void setGenericInformations(Map<String, BigString> genericInformations) {
this.genericInformations = genericInformations;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public JobInfoData getJobInfo() {
return jobInfo;
}
public void setJobInfo(JobInfoData jobInfo) {
this.jobInfo = jobInfo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return jobInfo.getJobId().getId();
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public Map<String, TaskStateData> getTasks() {
return tasks;
}
public void setTasks(Map<String, TaskStateData> tasks) {
this.tasks = tasks;
}
@Override
public String toString() {
try {
return mapper.writeValueAsString(this);
} catch (Exception e) {
return "JobStateData{" + "name='" + name + '\'' + ", priority='" + priority + '\'' + ", owner='" +
owner + '\'' + ", jobInfo=" + jobInfo + ", projectName='" + projectName + '\'' + ", tasks=" +
tasks + ", genericInformation=" + genericInformations + '}';
}
}
} |
package org.ow2.proactive.scheduler.util;
import static org.ow2.proactive.utils.ClasspathUtils.findSchedulerHome;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.rmi.AlreadyBoundException;
import java.security.KeyException;
import java.util.List;
import javax.security.auth.login.LoginException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.config.CentralPAPropertyRepository;
import org.objectweb.proactive.core.config.ProActiveConfiguration;
import org.objectweb.proactive.core.remoteobject.AbstractRemoteObjectFactory;
import org.objectweb.proactive.core.remoteobject.RemoteObjectFactory;
import org.objectweb.proactive.core.util.ProActiveInet;
import org.objectweb.proactive.extensions.pamr.PAMRConfig;
import org.objectweb.proactive.extensions.pamr.router.Router;
import org.objectweb.proactive.extensions.pamr.router.RouterConfig;
import org.objectweb.proactive.utils.JVMPropertiesPreloader;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.resourcemanager.RMFactory;
import org.ow2.proactive.resourcemanager.authentication.RMAuthentication;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.frontend.ResourceManager;
import org.ow2.proactive.resourcemanager.nodesource.NodeSource;
import org.ow2.proactive.resourcemanager.nodesource.infrastructure.LocalInfrastructure;
import org.ow2.proactive.resourcemanager.nodesource.policy.RestartDownNodesPolicy;
import org.ow2.proactive.resourcemanager.utils.RMStarter;
import org.ow2.proactive.scheduler.SchedulerFactory;
import org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface;
import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties;
import org.ow2.proactive.scripting.InvalidScriptException;
import org.ow2.proactive.scripting.ScriptHandler;
import org.ow2.proactive.scripting.ScriptLoader;
import org.ow2.proactive.scripting.ScriptResult;
import org.ow2.proactive.scripting.SimpleScript;
import org.ow2.proactive.utils.FileToBytesConverter;
import org.ow2.proactive.utils.JettyStarter;
import org.ow2.proactive.utils.PAMRRouterStarter;
import org.ow2.proactive.utils.SecurityPolicyLoader;
import org.ow2.proactive.utils.Tools;
import org.ow2.proactive.web.WebProperties;
/**
* SchedulerStarter will start a new Scheduler on the local host connected to the given Resource Manager.<br>
* If no Resource Manager is specified, it will try first to connect a local one. If not succeed, it will create one on
* the localHost started with 4 local nodes.<br>
* The scheduling policy can be specified at startup. If not given, it will use the default one.<br>
* Start with -h option for more help.<br>
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
public class SchedulerStarter {
private static Logger logger = Logger.getLogger(SchedulerStarter.class);
private static final int DEFAULT_NODES_TIMEOUT = 120 * 1000;
private static final int DISCOVERY_DEFAULT_PORT = 64739;
private static BroadcastDiscovery discoveryService;
private static SchedulerHsqldbStarter hsqldbServer;
protected static SchedulerAuthenticationInterface schedAuthInter;
protected static String rmURL;
protected static byte[] credentials;
/**
* Start the scheduler creation process.
*/
public static void main(String[] args) {
configureSchedulerAndRMAndPAHomes();
configureSecurityManager();
configureLogging();
configureDerby();
args = JVMPropertiesPreloader.overrideJVMProperties(args);
Options options = getOptions();
try {
CommandLine commandLine = getCommandLine(args, options);
if (commandLine.hasOption("h")) {
displayHelp(options);
} else {
start(commandLine);
}
} catch (Exception e) {
logger.error("Error when starting the scheduler", e);
displayHelp(options);
System.exit(6);
}
}
protected static CommandLine getCommandLine(String[] args, Options options) throws ParseException {
CommandLineParser parser = new DefaultParser();
return parser.parse(options, args);
}
protected static void start(CommandLine commandLine) throws Exception {
ProActiveConfiguration.load(); // force properties loading to find out if PAMR router should be started
if (!commandLine.hasOption("no-router")) {
startRouter();
}
hsqldbServer = new SchedulerHsqldbStarter();
hsqldbServer.startIfNeeded();
String rmUrl = getRmUrl(commandLine);
setCleanDatabaseProperties(commandLine);
setCleanNodesourcesProperty(commandLine);
rmUrl = connectToOrStartResourceManager(commandLine, rmUrl);
if (commandLine.hasOption("rm-only")) {
return;
}
SchedulerAuthenticationInterface schedulerAuthenticationInterface = startScheduler(commandLine, rmUrl);
schedAuthInter = schedulerAuthenticationInterface;
rmURL = rmUrl;
if (!commandLine.hasOption("no-rest")) {
List<String> applicationUrls = (new JettyStarter().deployWebApplications(rmUrl,
schedulerAuthenticationInterface.getHostURL()));
if (applicationUrls != null) {
for (String applicationUrl : applicationUrls) {
if (applicationUrl.endsWith("/rest")) {
if (!PASchedulerProperties.SCHEDULER_REST_URL.isSet()) {
PASchedulerProperties.SCHEDULER_REST_URL.updateProperty(applicationUrl);
}
}
}
}
}
addShutdownMessageHook();
executeStartScripts();
}
private static void startRouter() throws Exception {
if (needToStartRouter()) {
RouterConfig config = new RouterConfig();
int routerPort = PAMRConfig.PA_NET_ROUTER_PORT.getValue();
config.setPort(routerPort);
config.setNbWorkerThreads(Runtime.getRuntime().availableProcessors());
config.setReservedAgentConfigFile(new File(System.getProperty(PASchedulerProperties.SCHEDULER_HOME.getKey()) +
PAMRRouterStarter.PATH_TO_ROUTER_CONFIG_FILE));
Router.createAndStart(config);
logger.info("The router created on " + ProActiveInet.getInstance().getHostname() + ":" + routerPort);
}
}
private static boolean needToStartRouter() {
return isPamrProtocolUsed() && isPamrHostLocalhost();
}
private static boolean isPamrHostLocalhost() {
try {
return isThisMyIpAddress(InetAddress.getByName(PAMRConfig.PA_NET_ROUTER_ADDRESS.getValue()));
} catch (UnknownHostException e) {
return false;
}
}
public static boolean isThisMyIpAddress(InetAddress addr) {
// Check if the address is a valid special local or loop back
if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
return true;
// Check if the address is defined on any interface
try {
return NetworkInterface.getByInetAddress(addr) != null;
} catch (SocketException e) {
return false;
}
}
private static boolean isPamrProtocolUsed() {
return CentralPAPropertyRepository.PA_COMMUNICATION_PROTOCOL.getValue().contains("pamr") ||
CentralPAPropertyRepository.PA_COMMUNICATION_ADDITIONAL_PROTOCOLS.getValue().contains("pamr");
}
private static SchedulerAuthenticationInterface startScheduler(CommandLine commandLine, String rmUrl)
throws Exception {
String policyFullName = getPolicyFullName(commandLine);
logger.info("Starting the scheduler...");
SchedulerAuthenticationInterface sai = SchedulerFactory.startLocal(new URI(rmUrl), policyFullName);
startDiscovery(commandLine, rmUrl);
logger.info("The scheduler created on " + sai.getHostURL());
return sai;
}
private static void startDiscovery(CommandLine commandLine, String urlToDiscover)
throws ParseException, SocketException, UnknownHostException {
if (!commandLine.hasOption("no-discovery")) {
int discoveryPort = readIntOption(commandLine, "discovery-port", DISCOVERY_DEFAULT_PORT);
discoveryService = new BroadcastDiscovery(discoveryPort, urlToDiscover);
discoveryService.start();
}
}
private static String connectToOrStartResourceManager(CommandLine commandLine, String rmUrl)
throws ProActiveException, URISyntaxException, ParseException {
if (rmUrl != null) {
try {
logger.info("Connecting to the resource manager on " + rmUrl);
int rmConnectionTimeout = PASchedulerProperties.RESOURCE_MANAGER_CONNECTION_TIMEOUT.getValueAsInt();
SchedulerFactory.waitAndJoinRM(new URI(rmUrl), rmConnectionTimeout);
} catch (Exception e) {
logger.error("ERROR while connecting to the RM on " + rmUrl + ", no RM found !");
System.exit(2);
}
} else {
rmUrl = getLocalAdress();
URI uri = new URI(rmUrl);
//trying to connect to a started local RM
try {
SchedulerFactory.tryJoinRM(uri);
logger.info("Connected to the existing resource manager at " + uri);
} catch (Exception e) {
int defaultNodesNumber = PAResourceManagerProperties.RM_NB_LOCAL_NODES.getValueAsInt();
// -1 means that the number of local nodes depends of the number of cores in the local machine
if (defaultNodesNumber == -1) {
defaultNodesNumber = RMStarter.DEFAULT_NODES_NUMBER;
}
int numberLocalNodes = readIntOption(commandLine, "localNodes", defaultNodesNumber);
int nodeTimeoutValue = readIntOption(commandLine, "timeout", DEFAULT_NODES_TIMEOUT);
startResourceManager(numberLocalNodes, nodeTimeoutValue);
}
}
return rmUrl;
}
private static void setCleanDatabaseProperties(CommandLine commandLine) {
if (commandLine.hasOption("c")) {
PASchedulerProperties.SCHEDULER_DB_HIBERNATE_DROPDB.updateProperty("true");
PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB.updateProperty("true");
}
}
private static void setCleanNodesourcesProperty(CommandLine commandLine) {
if (commandLine.hasOption("clean-nodesources")) {
PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB_NODESOURCES.updateProperty("true");
}
}
private static String getRmUrl(CommandLine commandLine) {
String rmUrl = null;
if (commandLine.hasOption("u")) {
rmUrl = commandLine.getOptionValue("u");
logger.info("RM URL : " + rmUrl);
}
return rmUrl;
}
private static String getPolicyFullName(CommandLine commandLine) {
String policyFullName = PASchedulerProperties.SCHEDULER_DEFAULT_POLICY.getValueAsString();
if (commandLine.hasOption("p")) {
policyFullName = commandLine.getOptionValue("p");
logger.info("Used policy : " + policyFullName);
}
return policyFullName;
}
private static void addShutdownMessageHook() {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
logger.info("Shutting down...");
if (discoveryService != null) {
discoveryService.stop();
}
// WARNING: do not close embedded HSQLDB server in a shutdown hook.
// Multiple shutdown hooks are defined. Some are used for instance
// by the Resource Manager to remove node sources before termination.
// If the database is closed before completing the last operation, then
// some errors will occur (see logs).
// Besides, checking the state of the Scheduler and RM by registering
// an event listener or even by polling with periodic method calls will
// not work since Scheduler and RM are Active Objects and these are
// terminated by other shutdown hooks executed before the current one.
// The database connection should be closed by Hibernate when
// the datasource is closed. If not, the HSQLDB server will handle
// in the worst case the JVM shutdown as an accidental machine failure.
}
}));
}
private static void displayHelp(Options options) {
HelpFormatter hf = new HelpFormatter();
hf.setWidth(120);
hf.printHelp("proactive-server" + Tools.shellExtension(), options, true);
}
protected static Options getOptions() {
Options options = new Options();
Option help = new Option("h", "help", false, "to display this help");
help.setArgName("help");
help.setRequired(false);
options.addOption(help);
Option rmURL = new Option("u", "rmURL", true, "the resource manager URL (default: localhost)");
rmURL.setArgName("rmURL");
rmURL.setRequired(false);
options.addOption(rmURL);
Option policy = new Option("p",
"policy",
true,
"the complete name of the scheduling policy to use (default: org.ow2.proactive.scheduler.policy.DefaultPolicy)");
policy.setArgName("policy");
policy.setRequired(false);
options.addOption(policy);
Option noDeploy = new Option("ln",
"localNodes",
true,
"the number of local nodes to start (can be 0; default: " +
RMStarter.DEFAULT_NODES_NUMBER + ")");
noDeploy.setArgName("localNodes");
noDeploy.setRequired(false);
options.addOption(noDeploy);
Option nodeTimeout = new Option("t",
"timeout",
true,
"timeout used to start the nodes (only useful with local nodes; default: " +
DEFAULT_NODES_TIMEOUT + "ms)");
nodeTimeout.setArgName("timeout");
nodeTimeout.setRequired(false);
options.addOption(nodeTimeout);
options.addOption(new Option("c",
"clean",
false,
"clean scheduler and resource manager databases (default: false)"));
options.addOption(Option.builder()
.longOpt("clean-nodesources")
.desc("drop all previously created nodesources from resource manager database (default: false)")
.build());
options.addOption(Option.builder()
.longOpt("rm-only")
.desc("start only resource manager (implies --no-rest; default: false)")
.build());
options.addOption(Option.builder()
.longOpt("no-rest")
.desc("do not deploy REST server and wars from dist/war (default: false)")
.build());
options.addOption(Option.builder()
.longOpt("no-router")
.desc("do not deploy PAMR Router (default: false)")
.build());
options.addOption(Option.builder()
.longOpt("no-discovery")
.desc("do not run discovery service for nodes (default: false)")
.build());
options.addOption(Option.builder("dp")
.longOpt("discovery-port")
.desc("discovery service port for nodes (default: " + DISCOVERY_DEFAULT_PORT + ")")
.hasArg()
.argName("port")
.build());
return options;
}
private static int readIntOption(CommandLine cmd, String optionName, int defaultValue) throws ParseException {
int value = defaultValue;
if (cmd.hasOption(optionName)) {
try {
value = Integer.parseInt(cmd.getOptionValue(optionName));
} catch (Exception nfe) {
throw new ParseException("Wrong value for " + optionName + " option: " + cmd.getOptionValue("t"));
}
}
return value;
}
private static void startResourceManager(final int numberLocalNodes, final int nodeTimeoutValue) {
final Thread rmStarter = new Thread() {
public void run() {
try {
//Starting a local RM using default deployment descriptor
RMFactory.setOsJavaProperty();
logger.info("Starting the resource manager...");
RMAuthentication rmAuth = RMFactory.startLocal();
if (numberLocalNodes > 0) {
addLocalNodes(rmAuth, numberLocalNodes, nodeTimeoutValue);
}
logger.info("The resource manager with " + numberLocalNodes + " local nodes created on " +
rmAuth.getHostURL());
} catch (AlreadyBoundException abe) {
logger.error("The resource manager already exists on local host", abe);
System.exit(4);
} catch (Exception aoce) {
logger.error("Unable to create local resource manager", aoce);
System.exit(5);
}
}
};
rmStarter.start();
}
private static void addLocalNodes(RMAuthentication rmAuth, int numberLocalNodes, int nodeTimeoutValue)
throws LoginException, KeyException, IOException {
//creating default node source
ResourceManager rman = rmAuth.login(Credentials.getCredentials(PAResourceManagerProperties.getAbsolutePath(PAResourceManagerProperties.RM_CREDS.getValueAsString())));
//first im parameter is default rm url
byte[] creds = FileToBytesConverter.convertFileToByteArray(new File(PAResourceManagerProperties.getAbsolutePath(PAResourceManagerProperties.RM_CREDS.getValueAsString())));
rman.createNodeSource(NodeSource.DEFAULT_LOCAL_NODES_NODE_SOURCE_NAME,
LocalInfrastructure.class.getName(),
new Object[] { creds, numberLocalNodes, nodeTimeoutValue, "" },
RestartDownNodesPolicy.class.getName(),
new Object[] { "ALL", "ALL", "10000" });
credentials = creds;
}
private static String getLocalAdress() throws ProActiveException {
RemoteObjectFactory rof = AbstractRemoteObjectFactory.getDefaultRemoteObjectFactory();
return rof.getBaseURI().toString();
}
private static void configureSchedulerAndRMAndPAHomes() {
setPropIfNotAlreadySet(PASchedulerProperties.SCHEDULER_HOME.getKey(), findSchedulerHome());
String schedHome = System.getProperty(PASchedulerProperties.SCHEDULER_HOME.getKey());
setPropIfNotAlreadySet(PAResourceManagerProperties.RM_HOME.getKey(), schedHome);
setPropIfNotAlreadySet(CentralPAPropertyRepository.PA_HOME.getName(), schedHome);
setPropIfNotAlreadySet(CentralPAPropertyRepository.PA_CONFIGURATION_FILE.getName(),
schedHome + "/config/network/server.ini");
}
protected static void configureSecurityManager() {
SecurityPolicyLoader.configureSecurityManager(System.getProperty(PASchedulerProperties.SCHEDULER_HOME.getKey()) +
"/config/security.java.policy-server",
PASchedulerProperties.POLICY_RELOAD_FREQUENCY_IN_SECONDS.getValueAsLong());
}
protected static void configureLogging() {
String schedHome = System.getProperty(PASchedulerProperties.SCHEDULER_HOME.getKey());
String defaultLog4jConfig = schedHome + "/config/log/server.properties";
if (setPropIfNotAlreadySet(CentralPAPropertyRepository.LOG4J.getName(), defaultLog4jConfig))
PropertyConfigurator.configure(defaultLog4jConfig);
setPropIfNotAlreadySet("java.util.logging.config.file", defaultLog4jConfig);
setPropIfNotAlreadySet("derby.stream.error.file", schedHome + "/logs/Database.log");
}
protected static void configureDerby() {
setPropIfNotAlreadySet("derby.locks.deadlockTimeout", "1");
}
protected static boolean setPropIfNotAlreadySet(String name, Object value) {
boolean notSet = System.getProperty(name) == null;
if (notSet)
System.setProperty(name, value.toString());
return notSet;
}
private static void executeStartScripts() throws InvalidScriptException, IOException {
// Nothing to do if no script path is specified
if (!PASchedulerProperties.SCHEDULER_STARTSCRIPTS_PATHS.isSet())
return;
// Retrieve the start scripts paths
List<String> scriptsPaths = PASchedulerProperties.SCHEDULER_STARTSCRIPTS_PATHS.getValueAsList(";");
// Scripts binding
ScriptHandler scriptHandler = ScriptLoader.createLocalHandler();
scriptHandler.addBindings(PASchedulerProperties.getPropertiesAsHashMap());
scriptHandler.addBindings(PAResourceManagerProperties.getPropertiesAsHashMap());
scriptHandler.addBindings(WebProperties.getPropertiesAsHashMap());
// Execute all the listed scripts
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os, true);
ScriptResult scriptResult;
File scriptFile;
for (String scriptPath : scriptsPaths) {
scriptFile = new File(PASchedulerProperties.getAbsolutePath(scriptPath));
if (scriptFile.exists()) {
logger.info("Executing " + scriptPath);
scriptResult = scriptHandler.handle(new SimpleScript(scriptFile, new String[0]), ps, ps);
if (scriptResult.errorOccured()) {
// Close streams before throwing
os.close();
ps.close();
throw new InvalidScriptException("Failed to execute script: " +
scriptResult.getException().getMessage(),
scriptResult.getException());
}
logger.info(os.toString());
os.reset();
} else
logger.warn("Start script " + scriptPath + " not found");
}
// Close streams
os.close();
ps.close();
}
} |
package org.eclipse.persistence.sdo.helper.delegates;
import commonj.sdo.DataObject;
import commonj.sdo.helper.HelperContext;
import commonj.sdo.helper.XMLDocument;
import commonj.sdo.impl.HelperProvider;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.WeakHashMap;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import org.eclipse.persistence.sdo.SDOConstants;
import org.eclipse.persistence.sdo.helper.SDOClassLoader;
import org.eclipse.persistence.sdo.helper.SDOXMLHelper;
import org.eclipse.persistence.logging.AbstractSessionLog;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.XMLMarshaller;
import org.eclipse.persistence.oxm.XMLUnmarshaller;
import org.eclipse.persistence.sessions.Project;
import org.xml.sax.InputSource;
/**
* <p><b>Purpose</b>: Helper to XML documents into DataObects and DataObjects into XML documents.
* <p><b>Responsibilities</b>:<ul>
* <li> Finds the appropriate SDOXMLHelperDelegate for the classLoader and delegates work to that
* <li> Load methods create commonj.sdo.XMLDocument objects from XML (unmarshal)
* <li> Save methods create XML from commonj.sdo.XMLDocument and commonj.sdo.DataObject objects (marshal)
* </ul>
*/
public class SDOXMLHelperDelegator implements SDOXMLHelper {
private Map sdoXMLHelperDelegates;
// hold the context containing all helpers so that we can preserve inter-helper relationships
private HelperContext aHelperContext;
public SDOXMLHelperDelegator() {
//aHelperContext = HelperProvider.getDefaultContext();
sdoXMLHelperDelegates = new WeakHashMap();
}
public SDOXMLHelperDelegator(HelperContext aContext) {
super();
aHelperContext = aContext;
sdoXMLHelperDelegates = new WeakHashMap();
}
/**
* The specified TimeZone will be used for all String to date object
* conversions. By default the TimeZone from the JVM is used.
*/
public void setTimeZone(TimeZone timeZone) {
getSDOXMLHelperDelegate().setTimeZone(timeZone);
}
/**
* By setting this flag to true the marshalled date objects marshalled to
* the XML schema types time and dateTime will be qualified by a time zone.
* By default time information is not time zone qualified.
*/
public void setTimeZoneQualified(boolean timeZoneQualified) {
getSDOXMLHelperDelegate().setTimeZoneQualified(timeZoneQualified);
}
public XMLDocument load(String inputString) {
return getSDOXMLHelperDelegate().load(inputString);
}
public XMLDocument load(InputStream inputStream) throws IOException {
return getSDOXMLHelperDelegate().load(inputStream);
}
public XMLDocument load(InputStream inputStream, String locationURI, Object options) throws IOException {
return getSDOXMLHelperDelegate().load(inputStream, locationURI, options);
}
public XMLDocument load(InputSource inputSource, String locationURI, Object options) throws IOException {
return getSDOXMLHelperDelegate().load(inputSource, locationURI, options);
}
public XMLDocument load(Reader inputReader, String locationURI, Object options) throws IOException {
return getSDOXMLHelperDelegate().load(inputReader, locationURI, options);
}
public XMLDocument load(Source source, String locationURI, Object options) throws IOException {
return getSDOXMLHelperDelegate().load(source, locationURI, options);
}
public String save(DataObject dataObject, String rootElementURI, String rootElementName) {
return getSDOXMLHelperDelegate().save(dataObject, rootElementURI, rootElementName);
}
public void save(DataObject dataObject, String rootElementURI, String rootElementName, OutputStream outputStream) throws IOException {
getSDOXMLHelperDelegate().save(dataObject, rootElementURI, rootElementName, outputStream);
}
public void save(XMLDocument xmlDocument, OutputStream outputStream, Object options) throws IOException {
getSDOXMLHelperDelegate().save(xmlDocument, outputStream, options);
}
public void save(XMLDocument xmlDocument, Writer outputWriter, Object options) throws IOException {
getSDOXMLHelperDelegate().save(xmlDocument, outputWriter, options);
}
public void save(XMLDocument xmlDocument, Result result, Object options) throws IOException {
getSDOXMLHelperDelegate().save(xmlDocument, result, options);
}
public XMLDocument createDocument(DataObject dataObject, String rootElementURI, String rootElementName) {
return getSDOXMLHelperDelegate().createDocument(dataObject, rootElementURI, rootElementName);
}
public void setLoader(SDOClassLoader loader) {
getSDOXMLHelperDelegate().setLoader(loader);
}
public SDOClassLoader getLoader() {
return getSDOXMLHelperDelegate().getLoader();
}
public void setXmlContext(XMLContext xmlContext) {
getSDOXMLHelperDelegate().setXmlContext(xmlContext);
}
public XMLContext getXmlContext() {
return getSDOXMLHelperDelegate().getXmlContext();
}
public void addDescriptor(XMLDescriptor descriptor) {
getSDOXMLHelperDelegate().addDescriptor(descriptor);
}
public void addDescriptors(List descriptors) {
getSDOXMLHelperDelegate().addDescriptors(descriptors);
}
public void setTopLinkProject(Project toplinkProject) {
getSDOXMLHelperDelegate().setTopLinkProject(toplinkProject);
}
public Project getTopLinkProject() {
return getSDOXMLHelperDelegate().getTopLinkProject();
}
public void setXmlMarshaller(XMLMarshaller xmlMarshaller) {
getSDOXMLHelperDelegate().setXmlMarshaller(xmlMarshaller);
}
public XMLMarshaller getXmlMarshaller() {
return getSDOXMLHelperDelegate().getXmlMarshaller();
}
public void setXmlUnmarshaller(XMLUnmarshaller xmlUnmarshaller) {
getSDOXMLHelperDelegate().setXmlUnmarshaller(xmlUnmarshaller);
}
public XMLUnmarshaller getXmlUnmarshaller() {
return getSDOXMLHelperDelegate().getXmlUnmarshaller();
}
/**
* INTERNAL:
* This function returns the current or parent ClassLoader.
* We return the parent application ClassLoader when running in a J2EE client either in a
* web or ejb container to match a weak reference to a particular helpercontext.
*/
private ClassLoader getContextClassLoader() {
/**
* Classloader levels: (oc4j specific
* 0 - APP.web (servlet/jsp) or APP.wrapper (ejb) or
* 1 - APP.root (parent for helperContext)
* 2 - default.root
* 3 - system.root
* 4 - oc4j.10.1.3 (remote EJB) or org.eclipse.persistence:11.1.1.0.0
* 5 - api:1.4.0
* 6 - jre.extension:0.0.0
* 7 - jre.bootstrap:1.5.0_07 (with various J2SE versions)
* */
// Kludge for running in OC4J - from WebServices group
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if ((classLoader.getParent() != null) && (classLoader.toString().indexOf(SDOConstants.CLASSLOADER_EJB_FRAGMENT) != -1)) {
// we are running in a servlet container
AbstractSessionLog.getLog().log(AbstractSessionLog.FINEST, "{0} matched classLoader: {1} to parent cl: {2}",
new Object[] {getClass().getName(), classLoader.toString(), classLoader.getParent().toString()}, false);
classLoader = classLoader.getParent();
// check if we are running in an ejb container
} else if ((classLoader.getParent() != null) && (classLoader.toString().indexOf(SDOConstants.CLASSLOADER_WEB_FRAGMENT) != -1)) {
// we are running in a local ejb container
AbstractSessionLog.getLog().log(AbstractSessionLog.FINEST, "{0} matched classLoader: {1} to parent cl: {2}",
new Object[] {getClass().getName(), classLoader.toString(), classLoader.getParent().toString()}, false);
classLoader = classLoader.getParent();
} else {
// we are running in a J2SE client (toString() contains a JVM hash) or an unmatched container level
}
return classLoader;
}
/**
* INTERNAL:
* @return
*/
private SDOXMLHelperDelegate getSDOXMLHelperDelegate() {
ClassLoader contextClassLoader = getContextClassLoader();
SDOXMLHelperDelegate sdoXMLHelperDelegate = (SDOXMLHelperDelegate)sdoXMLHelperDelegates.get(contextClassLoader);
if (null == sdoXMLHelperDelegate) {
sdoXMLHelperDelegate = new SDOXMLHelperDelegate(getHelperContext());
sdoXMLHelperDelegates.put(contextClassLoader, sdoXMLHelperDelegate);
AbstractSessionLog.getLog().log(AbstractSessionLog.FINEST, "{0} creating new {1} keyed on classLoader: {2}",
new Object[] {getClass().getName(), sdoXMLHelperDelegate, contextClassLoader.toString()}, false);
}
return sdoXMLHelperDelegate;
}
public HelperContext getHelperContext() {
if(null == aHelperContext) {
aHelperContext = HelperProvider.getDefaultContext();
}
return aHelperContext;
}
public void setHelperContext(HelperContext helperContext) {
aHelperContext = helperContext;
}
public void setDirty(boolean value) {
getSDOXMLHelperDelegate().setDirty(value);
}
public void reset() {
getSDOXMLHelperDelegate().reset();
}
} |
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.persistence.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import com.kyloth.serleena.common.Checkpoint;
import com.kyloth.serleena.common.CheckpointReachedTelemetryEvent;
import com.kyloth.serleena.common.DirectAccessList;
import com.kyloth.serleena.common.EmergencyContact;
import com.kyloth.serleena.common.GeoPoint;
import com.kyloth.serleena.common.IQuadrant;
import com.kyloth.serleena.common.ListAdapter;
import com.kyloth.serleena.common.NoSuchWeatherForecastException;
import com.kyloth.serleena.common.Quadrant;
import com.kyloth.serleena.common.TelemetryEvent;
import com.kyloth.serleena.common.UserPoint;
import com.kyloth.serleena.persistence.IExperienceStorage;
import com.kyloth.serleena.persistence.IWeatherStorage;
import com.kyloth.serleena.persistence.NoSuchQuadrantException;
import com.kyloth.serleena.persistence.WeatherForecastEnum;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import static java.lang.Math.floor;
public class SerleenaSQLiteDataSource implements ISerleenaSQLiteDataSource {
private SerleenaDatabase dbHelper;
public SerleenaSQLiteDataSource(SerleenaDatabase dbHelper) {
if (dbHelper == null)
throw new IllegalArgumentException("Illegal null database");
this.dbHelper = dbHelper;
}
/**
* Implementazione di ISerleenaSQLiteDataSource.getTracks().
*
* Viene eseguita una query sul database per ottenere gli ID di tutti i
* Percorsi associati all'Esperienza specificata, da cui vengono creati
* rispettivi oggetti SQLiteDAOTrack.
*
* @param experience Esperienza di cui si vogliono ottenere i Percorsi.
* @return Insieme enumerabile di Percorsi.
*/
@Override
public Iterable<SQLiteDAOTrack> getTracks(SQLiteDAOExperience experience) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String where = "track_experience = " + experience.id();
Cursor result = db.query(SerleenaDatabase.TABLE_TRACKS,
new String[] { "track_id, track_name" }, where, null, null,
null, null);
ArrayList<SQLiteDAOTrack> list = new ArrayList<SQLiteDAOTrack>();
int idIndex = result.getColumnIndexOrThrow("track_id");
int nameIndex = result.getColumnIndexOrThrow("track_name");
while (result.moveToNext()) {
int trackId = result.getInt(idIndex);
String name = result.getString(nameIndex);
list.add(new SQLiteDAOTrack(
getCheckpoints(trackId), trackId, name, this));
}
result.close();
return list;
}
/**
* Restituisce i checkpoint di un Percorso.
*
* @param trackId ID del percorso di cui si vogliono ottenere i Checkpoint.
* @return Elenco di checkpoint del Percorso specificato.
*/
private DirectAccessList<Checkpoint> getCheckpoints(int trackId) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String where = "checkpoint_track = " + trackId;
String orderBy = "checkpoint_num ASC";
Cursor result = db.query(SerleenaDatabase.TABLE_CHECKPOINTS,
new String[] { "checkpoint_latitude", "checkpoint_longitude"},
where, null, null, null, orderBy);
ArrayList<Checkpoint> list = new ArrayList<Checkpoint>();
int latIndex = result.getColumnIndexOrThrow("checkpoint_latitude");
int lonIndex = result.getColumnIndexOrThrow("checkpoint_longitude");
while (result.moveToNext()) {
double lat = result.getDouble(latIndex);
double lon = result.getDouble(lonIndex);
list.add(new Checkpoint(lat, lon));
}
result.close();
return new ListAdapter<Checkpoint>(list);
}
/**
* Implementazione di ISerleenaSQLiteDataSource.getTelemetries().
*
* Viene eseguita una query sul database per ottenere gli ID di tutti i
* Tracciamenti associati al Percorso specificato, da cui vengono creati
* rispettivi oggetti SQLiteDAOTelemetry.
*
* @param track Percorso di cui si vogliono ottenere i Tracciamenti.
* @return Insieme enumerabile di Tracciamenti.
*/
@Override
public Iterable<SQLiteDAOTelemetry> getTelemetries(SQLiteDAOTrack track) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String where = "telem_track = " + track.id();
Cursor result = db.query(SerleenaDatabase.TABLE_TELEMETRIES,
new String[]{"telem_id"}, where, null, null, null, null);
ArrayList<SQLiteDAOTelemetry> list = new
ArrayList<SQLiteDAOTelemetry>();
int columnIndex = result.getColumnIndexOrThrow("telem_id");
while (result.moveToNext()) {
int telemId = result.getInt(columnIndex);
Iterable<TelemetryEvent> events = getTelemetryEvents(telemId);
list.add(new SQLiteDAOTelemetry(telemId, events));
}
result.close();
return list;
}
/**
* Implementazione di ISerleenaSQLiteDataSource.getUserPoints().
*
* Viene eseguita una query sul database per ottenere i Punti Utente
* associati all'Esperienza specificata.
*
* @param experience Esperienza di cui si vogliono ottenere i Punti Utente.
* @return Insieme enumerabile di Punti Utente.
*/
@Override
public Iterable<UserPoint> getUserPoints(SQLiteDAOExperience experience) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String where = "userpoint_experience = " + experience.id();
Cursor result = db.query(SerleenaDatabase.TABLE_USER_POINTS,
new String[] { "userpoint_x", "userpoint_y" }, where, null,
null, null, null);
int latIndex = result.getColumnIndexOrThrow("userpoint_x");
int lonIndex = result.getColumnIndexOrThrow("userpoint_y");
ArrayList<UserPoint> list = new ArrayList<UserPoint>();
while (result.moveToNext()) {
double latitude = result.getDouble(latIndex);
double longitude = result.getDouble(lonIndex);
list.add(new UserPoint(latitude, longitude));
}
result.close();
return list;
}
/**
* Implementazione di ISerleenaSQLiteDataSource.addUserPoint().
*
* @param experience Esperienza a cui aggiungere il punto utente.
* @param point Punto utente da aggiungere.
*/
@Override
public void addUserPoint(SQLiteDAOExperience experience, UserPoint point) {
ContentValues values = new ContentValues();
SQLiteDatabase db = dbHelper.getWritableDatabase();
values.put("userpoint_x", point.latitude());
values.put("userpoint_y", point.longitude());
values.put("userpoint_experience", experience.id());
db.insert(SerleenaDatabase.TABLE_USER_POINTS, null, values);
}
/**
* Implementazione di ISerleenaSQLiteDataSource.createTelemetry().
*
* @param events Eventi di tracciamento da cui costruire il Tracciamento.
* @param track Percorso a cui associare il Tracciamento.
*/
@Override
public void createTelemetry(Iterable<TelemetryEvent> events,
SQLiteDAOTrack track) {
if (events == null && track == null)
throw new IllegalArgumentException();
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("telem_track", track.id());
long newId = db.insert(SerleenaDatabase.TABLE_TELEMETRIES, null, values);
for (TelemetryEvent event : events) {
values = new ContentValues();
if (event instanceof CheckpointReachedTelemetryEvent) {
CheckpointReachedTelemetryEvent eventc =
(CheckpointReachedTelemetryEvent) event;
values.put("eventc_timestamp", eventc.timestamp());
values.put("eventc_value", eventc.checkpointNumber());
values.put("eventc_telem", newId);
db.insert(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP, null,values);
}
}
}
/**
* Implementazione di IPersistenceDataSource.getExperiences().
*
* Ritorna un'enumerazione di tutte le Esperienze presenti nel database,
* dietro interfaccia IExperienceStorage.
*
* @return Insieme enumerabile di Esperienze.
* @see com.kyloth.serleena.persistence.IPersistenceDataSource
*/
@Override
public Iterable<IExperienceStorage> getExperiences() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor result = db.query(SerleenaDatabase.TABLE_EXPERIENCES,
new String[]{"experience_id", "experience_name"}, null,
null, null, null, null);
int idIndex = result.getColumnIndexOrThrow("experience_id");
int nameIndex = result.getColumnIndexOrThrow("experience_name");
ArrayList<IExperienceStorage> list =
new ArrayList<IExperienceStorage>();
while (result.moveToNext()) {
int id = result.getInt(idIndex);
String name = result.getString(nameIndex);
list.add(new SQLiteDAOExperience(name, id, this));
}
result.close();
return list;
}
@Override
public IQuadrant getQuadrant(GeoPoint location, SQLiteDAOExperience exp)
throws NoSuchQuadrantException {
if (location == null)
throw new IllegalArgumentException("Illegal null location");
if (exp == null)
throw new IllegalArgumentException("Illegal null experience");
SQLiteDatabase db = dbHelper.getReadableDatabase();
String where =
"`raster_nw_corner_latitude` >= " +
location.latitude() + " AND " +
"`raster_nw_corner_longitude` <= " +
location.longitude() + " AND " +
"`raster_se_corner_latitude` <= " +
location.latitude() + " AND " +
"`raster_se_corner_longitude` >= " +
location.longitude() + " AND " +
"`raster_experience` = " +
exp.id();
Cursor result = db.query(SerleenaDatabase.TABLE_RASTERS,
new String[]{
"raster_nw_corner_latitude",
"raster_nw_corner_longitude",
"raster_se_corner_latitude",
"raster_se_corner_longitude",
"raster_base64"
},
where, null, null, null, null);
int nwLatIndex =
result.getColumnIndexOrThrow("raster_nw_corner_latitude");
int nwLonIndex =
result.getColumnIndexOrThrow("raster_nw_corner_longitude");
int seLatIndex =
result.getColumnIndexOrThrow("raster_se_corner_latitude");
int seLonIndex =
result.getColumnIndexOrThrow("raster_se_corner_longitude");
int base64Index =
result.getColumnIndexOrThrow("raster_base64");
if (result.moveToNext()) {
double nwLat = result.getDouble(nwLatIndex);
double nwLon = result.getDouble(nwLonIndex);
double seLat = result.getDouble(seLatIndex);
double seLon = result.getDouble(seLonIndex);
byte[] data = Base64.decode(
result.getString(base64Index), Base64.DEFAULT);
return new Quadrant(
new GeoPoint(nwLat, nwLon),
new GeoPoint(seLat, seLon),
BitmapFactory.decodeByteArray(data, 0, data.length));
} else
throw new NoSuchQuadrantException();
}
@Override
public DirectAccessList<EmergencyContact> getContacts(GeoPoint location) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
ArrayList<EmergencyContact> list = new ArrayList<EmergencyContact>();
String where = "`contact_nw_corner_latitude` >= " +
location.latitude() + " AND " +
"`contact_nw_corner_longitude` <= " +
location.longitude() + " AND " +
"`contact_se_corner_latitude` <= " +
location.latitude() + " AND " +
"`contact_se_corner_longitude` >= " +
location.longitude();
Cursor result = db.query(SerleenaDatabase.TABLE_CONTACTS,
new String[]{"contact_name", "contact_value"}, where,
null, null, null, null);
int nameIndex = result.getColumnIndexOrThrow("contact_name");
int valueIndex = result.getColumnIndexOrThrow("contact_value");
while (result.moveToNext()) {
String name = result.getString(nameIndex);
String value = result.getString(valueIndex);
list.add(new EmergencyContact(name, value));
}
result.close();
return new ListAdapter<EmergencyContact>(list);
}
/**
* Restituisce gli eventi di Tracciamento associati al Tracciamento con ID
* specificato, memorizzati nel database SQLite.
*
* @param id ID del Tracciamento di cui si vogliono ottenere gli eventi.
* @return Insieme enumerabile di eventi di Tracciamento.
*/
private Iterable<TelemetryEvent> getTelemetryEvents(int id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
ArrayList<TelemetryEvent> list = new ArrayList<TelemetryEvent>();
String where = "eventc_telem = " + id;
Cursor result = db.query(SerleenaDatabase.TABLE_TELEM_EVENTS_CHECKP,
new String[]{"eventc_timestamp", "eventc_value"},
where, null, null, null, null);
int timestampIndex = result.getColumnIndexOrThrow("eventc_timestamp");
int valueIndex = result.getColumnIndexOrThrow("eventc_value");
while (result.moveToNext()) {
int time = result.getInt(timestampIndex);
int value = Integer.parseInt(result.getString(valueIndex));
TelemetryEvent event =
new CheckpointReachedTelemetryEvent(time, value);
list.add(event);
}
result.close();
return list;
}
/**
* Restituisce le previsioni, comprensive di condizione metereologica e
* temperatura, per una posizione geografica e un intervallo di tempo
* specificati.
*
* @param location Posizione geografica di cui si vogliono ottenere le
* previsioni.
* @param time Punto temporale di cui si vogliono
* ottenere le previsioni, in UNIX time.
* @return Previsioni metereologiche.
*/
@Override
public IWeatherStorage getWeatherInfo(GeoPoint location, Date date)
throws IllegalArgumentException, NoSuchWeatherForecastException {
if (date == null)
throw new IllegalArgumentException("Illegal null date");
if (location == null)
throw new IllegalArgumentException("Illegal null location");
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(date.getTime());
if (c.get(Calendar.HOUR_OF_DAY) != 00 ||
c.get(Calendar.MINUTE) != 00 ||
c.get(Calendar.SECOND) != 00 ||
c.get(Calendar.MILLISECOND) != 00) {
throw new IllegalArgumentException("Illegal date, 00:00:00.000 required");
}
SQLiteDatabase db = dbHelper.getReadableDatabase();
String where =
"weather_date = " + (date.getTime()/1000) + " AND " +
"`weather_nw_corner_latitude` >= " +
location.latitude() + " AND " +
"`weather_nw_corner_longitude` <= " +
location.longitude() + " AND " +
"`weather_se_corner_latitude` <= " +
location.latitude() + " AND " +
"`weather_se_corner_longitude` >= " +
location.longitude();
Cursor result = db.query(SerleenaDatabase.TABLE_WEATHER_FORECASTS,
new String[]{
"weather_condition_morning",
"weather_temperature_morning",
"weather_condition_afternoon",
"weather_temperature_afternoon",
"weather_condition_night",
"weather_temperature_night"
},
where, null, null, null, null);
int conditionMorningIndex = result.getColumnIndex("weather_condition_morning");
int temperatureMorningIndex = result.getColumnIndex("weather_temperature_morning");
int conditionAfternoonIndex = result.getColumnIndex("weather_condition_afternoon");
int temperatureAfternoonIndex = result.getColumnIndex("weather_temperature_afternoon");
int conditionNightIndex = result.getColumnIndex("weather_condition_night");
int temperatureNightIndex = result.getColumnIndex("weather_temperature_night");
if (result.moveToNext()) {
return new SQLiteDAOWeather(
WeatherForecastEnum.values()[result.getInt(conditionMorningIndex)],
WeatherForecastEnum.values()[result.getInt(conditionAfternoonIndex)],
WeatherForecastEnum.values()[result.getInt(conditionNightIndex)],
result.getInt(temperatureMorningIndex),
result.getInt(temperatureAfternoonIndex),
result.getInt(temperatureNightIndex),
date);
} else {
throw new NoSuchWeatherForecastException();
}
}
} |
package de.uniulm.omi.cloudiator.lance.lca.containers.docker;
import de.uniulm.omi.cloudiator.lance.lca.GlobalRegistryAccessor;
import de.uniulm.omi.cloudiator.lance.lca.LcaRegistryConstants;
import de.uniulm.omi.cloudiator.lance.lca.LcaRegistryConstants.Identifiers;
import de.uniulm.omi.cloudiator.lance.lca.container.ComponentInstanceId;
import de.uniulm.omi.cloudiator.lance.lca.container.port.PortRegistryTranslator;
import de.uniulm.omi.cloudiator.lance.lca.containers.docker.connector.DockerConnector;
import de.uniulm.omi.cloudiator.lance.lca.containers.docker.connector.DockerException;
import de.uniulm.omi.cloudiator.lance.lca.registry.RegistrationException;
import de.uniulm.omi.cloudiator.lance.lifecycle.LifecycleHandler;
import de.uniulm.omi.cloudiator.lance.lifecycle.LifecycleHandlerType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//Todo: Handle sockets inside of Set
/* Executes a script inside the container, that processes the 'ip:port'
vaLues of associated dyngroup components inside the registry */
class DockerDynHandler extends Thread {
private static final Logger LOGGER = LoggerFactory.getLogger(DockerContainerManager.class);
private final String dynHandlerVal;
private final String updateScriptFilePath;
private final DockerConnector client;
private Map<ComponentInstanceId,String> socketsBefore;
private Map<ComponentInstanceId,String> socketsAfter;
private GlobalRegistryAccessor accessor;
private String containerName;
private volatile boolean running;
DockerDynHandler(String containerName, String dynHandlerVal, String updateScriptFilePath, DockerConnector client) {
this.containerName = containerName;
this.dynHandlerVal = dynHandlerVal;
this.updateScriptFilePath = updateScriptFilePath;
this.client = client;
socketsBefore = new HashMap<>();
socketsAfter = new HashMap<>();
accessor = null;
this.running = false;
}
public void setAccessor(GlobalRegistryAccessor accessor) {
this.accessor = accessor;
}
@Override
public void run() {
this.running = true;
Map<ComponentInstanceId,Map<String,String>> runningDumps = new HashMap<>();
LOGGER.info(String
.format("Starting dynamic Handler: %s.", containerName));
do {
try {
if(accessor==null) {
LOGGER.error("Docker Dyn Handler cannot continue working as it cannot access the registry.");
return;
}
runningDumps = accessor.getRunningDumps();
debugRunningDumps(runningDumps);
socketsAfter = filterHandlerGroupSocks(runningDumps);
final SocketsDiff socketsDiff = calcSocketsDiff(runningDumps);
if(socketsDiff.hasDiff()) {
executeUpdate();
}
if(socketsDiff.hasDestroyed()) {
syncDestruction(socketsDiff.socketsDestroyed);
}
socketsBefore = socketsAfter;
} catch (RegistrationException e) {
LOGGER.error(String
.format("Cannot access registry properly in Dyn Handler component."));
} catch (DockerException e) {
LOGGER.error(String
.format("Cannot execute dynamic update inside Dyn Handler container: %s.", containerName));
}
} while (running);
}
/* If a Dyn Component is about to be destroyed, it waits (thread.wait) for the DynHandler to execute the update
* accordingly AND syncing the Dyn Component's state to PRE_STOP in the registry before it can continue (i.e.
* breaking out of thread.wait)*/
private void syncDestruction(Map<ComponentInstanceId,String> destrSocks) throws RegistrationException {
for(Map.Entry<ComponentInstanceId,String> sock: destrSocks.entrySet()) {
LOGGER.warn(String
.format("Setting Dynamic Component Instance %s Container_Status to a temporally inconsistent state"
+ " for synchronisation purposes.", sock.getKey()));
accessor.syncDynamicDestructionStatus(sock.getKey());
}
}
private void executeUpdate() throws DockerException {
final String execString = buildExecInsideContainerString(socketsAfter, updateScriptFilePath);
LOGGER.info(String
.format("Starting dynamic update via docker cli command: %s.", execString));
client.executeSingleDockerCommand(execString);
}
private SocketsDiff calcSocketsDiff(Map<ComponentInstanceId,Map<String,String>> runningDumps) {
Map<ComponentInstanceId, String> socketsKept = new HashMap<>();
Map<ComponentInstanceId, String> socketsNew = new HashMap<>();
Map<ComponentInstanceId, String> socketsDestroyed = new HashMap<>();
Map<ComponentInstanceId, String> socketsOrphaned = new HashMap<>();
for (Map.Entry<ComponentInstanceId, String> socketBefore : socketsBefore.entrySet()) {
boolean found = false;
final String beforeKey = socketBefore.getKey().toString();
final String beforeVal = socketBefore.getValue();
//todo: use map.get instead of 2nd loop
for (Map.Entry<ComponentInstanceId, String> socketAfter : socketsAfter.entrySet()) {
final String afterKey = socketAfter.getKey().toString();
final String afterVal = socketAfter.getValue();
if (beforeKey.equals(afterKey) && beforeVal.equals(afterVal)) {
socketsKept.put(socketBefore.getKey(),socketBefore.getValue());
found = true;
}
}
if(found==false) {
final ComponentInstanceId cId = socketBefore.getKey();
/* component with compatible dynamic group and running not a valid
* socket anymore (e.g. port was dynamically set to -1) -> lorphaned */
if (runningDumps.get(cId)!=null) {
socketsOrphaned.put(socketBefore.getKey(), socketBefore.getValue());
LOGGER.warn("Got orphaned socket %s",socketBefore.getValue());
} else {
socketsDestroyed.put(socketBefore.getKey(), socketBefore.getValue());
}
}
}
for (Map.Entry<ComponentInstanceId, String> socketAfter : socketsAfter.entrySet()) {
final String keptSocket = socketsKept.get(socketAfter.getKey());
if( keptSocket != null && keptSocket.equals(socketAfter.getValue())) {
continue;
}
socketsNew.put(socketAfter.getKey(), socketAfter.getValue());
}
SocketsDiff diff = new SocketsDiff();
diff.socketsKept = socketsKept;
diff.socketsNew = socketsNew;
diff.socketsDestroyed = socketsDestroyed;
diff.socketsOrphaned = socketsOrphaned;
return diff;
}
private Map<ComponentInstanceId, String> filterHandlerGroupSocks(Map<ComponentInstanceId,Map<String, String>> readyDumps) throws RegistrationException {
Map<ComponentInstanceId, String> socks = new HashMap<>();
final String dynGroupKey = LcaRegistryConstants.regEntries.get(Identifiers.DYN_GROUP_KEY);
for(Map.Entry<ComponentInstanceId,Map<String,String>> compDump: readyDumps.entrySet()) {
if(compDump.getValue() == null || compDump.getValue().get(dynGroupKey) == null) {
continue;
}
Map<String,String> dumpMap = compDump.getValue();
String dynGroupVal = dumpMap.get(dynGroupKey);
debugDynComparison(dynGroupVal, dynHandlerVal);
if(dynGroupVal.equals(dynHandlerVal)) {
final String socket = buildSocket(dumpMap, containerName);
debugPortParse(socket);
if (!socket.equals("")) {
socks.put(compDump.getKey(), buildSocket(dumpMap, containerName));
}
}
}
return socks;
}
private String buildExecInsideContainerString(
Map<ComponentInstanceId,String> sockets, String updateScriptFilePath) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<ComponentInstanceId,String> entry : sockets.entrySet()) {
final String s = entry.getValue();
sb.append(s);
sb.append(" ");
}
final String socketsStr = sb.toString();
final String commandStr = "exec -ti " + containerName + " " + updateScriptFilePath + " "
+ socketsStr;
return commandStr;
}
//todo: check port values: i.e. convert to int
private static String buildSocket(Map<String, String> compDump, String cName) throws RegistrationException {
final String ipVal = PortRegistryTranslator.getHierarchicalHostname(PortRegistryTranslator.PORT_HIERARCHY_1, compDump);
final String portVal = getPortVal(compDump);
if(!isValidPort(portVal)) {
LOGGER.warn(String
.format("Found port value -1 for a socket in Dynamic Handler %s. Skipping it"
+ "...", cName));
return "";
}
final String socket = ipVal + ":" + portVal;
return socket;
}
//todo: check port values: i.e. convert to int
private static boolean isValidPort(String port) {
if(port.equals("-1")) {
return false;
}
return true;
}
private static String getPortVal(Map<String, String> compDump) throws RegistrationException {
String retVal = "";
for(Map.Entry<String,String> entry: compDump.entrySet()) {
final String key = entry.getKey();
if(key.matches("^[^\\s]*CLOUD[^\\s]+Port$")) {
retVal = entry.getValue();
}
if(key.matches("^[^\\s]*CLOUD[^\\s]+I[Nn][Pp]$")) {
retVal = entry.getValue();
}
}
if(retVal.equals("")) {
throw new RegistrationException("Dynamic Component has no public port set.");
}
return retVal;
}
//todo: better get this String from PortRegistryTranslator
public synchronized void setRunning(boolean running) {
this.running = running;
}
public boolean isRunning() {
return running;
}
//debugging
private static void debugRunningDumps(Map<ComponentInstanceId,Map<String,String>> dumps) {
if(dumps == null || dumps.size() == 0) {
LOGGER.debug(String.format("Running dumps is empty!"));
return;
}
for(Map.Entry<ComponentInstanceId,Map<String,String>> entry: dumps.entrySet()) {
if(entry.getValue() == null) {
LOGGER.debug(String.format("Got empty map for Component instance: %s", entry.getKey()));
continue;
}
Map<String,String> dumpMap = entry.getValue();
for(Map.Entry<String,String> strMap: dumpMap.entrySet()) {
LOGGER.debug(String.format("Found key: %s, value: %s, for running instance %s.", strMap.getKey(),
strMap.getValue(), entry.getKey()));
}
}
}
private static void debugDynComparison(String str1, String str2) {
LOGGER.debug(String.format("Comparing Strings: %s, %s", str1, str2));
if(str1.equals(str2)) {
LOGGER.debug(String.format("Strings are euqal!"));
} else {
LOGGER.debug(String.format("Strings are not euqal!"));
}
}
private void debugPortParse(String socket) {
LOGGER.debug(String.format("Found valid socket: %s!", socket));
}
/* Provides info about the diff in the available sockets */
private static class SocketsDiff {
public Map<ComponentInstanceId,String> socketsKept;
public Map<ComponentInstanceId,String> socketsNew;
public Map<ComponentInstanceId,String> socketsDestroyed;
/* If socket disappeared, but has STATUS!=STOP -> orphaned, could be because PORT has
* become -1 and socket was hence filtered out in method filterHandlerGroupSocks
* -> isValidPort */
public Map<ComponentInstanceId,String> socketsOrphaned;
private SocketsDiff() {
socketsKept = new HashMap<>();
socketsNew = new HashMap<>();
socketsDestroyed = new HashMap<>();
socketsOrphaned = new HashMap<>();
}
/* Did smth change between two iterations? */
private boolean hasDiff() {
if(socketsDestroyed.size()==0 && socketsNew.size()==0) {
return false;
}
return true;
}
private boolean hasDestroyed() {
return (socketsDestroyed.size() > 0) ? true : false;
}
}
} |
package fi.nls.oskari.service.capabilities;
import fi.mml.map.mapwindow.service.wms.LayerNotFoundInCapabilitiesException;
import fi.mml.map.mapwindow.service.wms.WebMapService;
import fi.mml.map.mapwindow.service.wms.WebMapServiceFactory;
import fi.mml.map.mapwindow.service.wms.WebMapServiceParseException;
import fi.nls.oskari.domain.map.OskariLayer;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.layer.formatters.LayerJSONFormatterWFS;
import fi.nls.oskari.map.layer.formatters.LayerJSONFormatterWMS;
import fi.nls.oskari.map.layer.formatters.LayerJSONFormatterWMTS;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.wmts.domain.ResourceUrl;
import fi.nls.oskari.wmts.domain.WMTSCapabilities;
import fi.nls.oskari.wmts.domain.WMTSCapabilitiesLayer;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.data.wfs.internal.WFSGetCapabilities;
import org.geotools.ows.wms.Layer;
import org.geotools.ows.wms.WMSCapabilities;
import org.json.JSONArray;
import org.json.JSONObject;
import org.oskari.service.wfs3.WFS3Service;
import static fi.nls.oskari.service.capabilities.CapabilitiesConstants.KEY_STYLES;
public class OskariLayerCapabilitiesHelper {
private static final Logger LOG = LogFactory.getLogger(OskariLayerCapabilitiesHelper.class);
private static final String KEY_NAME = "name";
/**
* Tries to parse WMS GetCapabilities response
* @return the parsed WebMapService
* @throws WebMapServiceParseException if something goes wrong
* @throws LayerNotFoundInCapabilitiesException if layer can't be found in capabilities
*/
@Deprecated
public static WebMapService parseWMSCapabilities(String xml, OskariLayer ml)
throws WebMapServiceParseException, LayerNotFoundInCapabilitiesException {
// flush cache, otherwise only db is updated but code retains the old cached version
WebMapServiceFactory.flushCache(ml.getId());
return WebMapServiceFactory.createFromXML(ml.getName(), xml);
}
@Deprecated
public static void setPropertiesFromCapabilitiesWMS(WebMapService wms,
OskariLayer ml, Set<String> systemCRSs) {
JSONObject caps = LayerJSONFormatterWMS.createCapabilitiesJSON(wms, systemCRSs);
ml.setCapabilities(caps);
ml.setCapabilitiesLastUpdated(new Date());
//TODO: similiar parsing for WMS GetCapabilities for admin layerselector and this
// Parsing is processed twice:
// 1st with geotools parsing for admin layerselector (styles are not parsered correct in all cases)
// 2nd in this class
// Fix default style, if no legendimage setup
String style = getDefaultStyle(ml, caps);
if (style != null) {
ml.setStyle(style);
}
}
public static void setPropertiesFromCapabilitiesWMS(WMSCapabilities capa, Layer capabilitiesLayer,
OskariLayer ml, Set<String> systemCRSs) {
JSONObject caps = LayerJSONFormatterWMS.createCapabilitiesJSON(capa, capabilitiesLayer, systemCRSs);
ml.setCapabilities(caps);
ml.setCapabilitiesLastUpdated(new Date());
}
public static void setDefaultStyleFromCapabilitiesJSON(OskariLayer ml) {
JSONArray styles = ml.getCapabilities().optJSONArray(KEY_STYLES);
String style = "";
if (styles != null && styles.length() > 0) {
style = JSONHelper.optString(JSONHelper.getJSONObject(styles, 0), "name");
}
ml.setStyle(style);
}
@Deprecated
private static String getDefaultStyle(OskariLayer ml, final JSONObject caps) {
String style = null;
if (ml.getId() == -1 && ml.getLegendImage() == null && caps.has(KEY_STYLES)) {
// Take 1st style name for default - geotools parsing is not always correct
JSONArray styles = JSONHelper.getJSONArray(caps, KEY_STYLES);
if (styles.length() == 0) {
return null;
}
JSONObject jstyle = JSONHelper.getJSONObject(styles, 0);
if (jstyle != null) {
style = JSONHelper.getStringFromJSON(jstyle, KEY_NAME, null);
return style;
}
}
return style;
}
public static void setPropertiesFromCapabilitiesWMTS(WMTSCapabilities caps,
OskariLayer ml, Set<String> systemCRSs) {
int id = ml.getId();
String name = ml.getName();
WMTSCapabilitiesLayer layer = caps.getLayer(name);
if (layer == null) {
String err = "Can not find Layer from GetCapabilities"
+ " layer id:" + id + " name: " + name;
LOG.warn(err);
throw new IllegalArgumentException(err);
}
ResourceUrl resUrl = layer.getResourceUrlByType("tile");
JSONObject options = ml.getOptions();
if (resUrl != null) {
JSONHelper.putValue(options, "requestEncoding", "REST");
JSONHelper.putValue(options, "format", resUrl.getFormat());
JSONHelper.putValue(options, "urlTemplate", resUrl.getTemplate());
} else {
LOG.debug("Layer", id, name, "does not report to support WMTS using RESTful");
options.remove("requestEncoding");
options.remove("format");
options.remove("urlTemplate");
}
JSONObject jscaps = LayerJSONFormatterWMTS.createCapabilitiesJSON(layer, systemCRSs);
ml.setCapabilities(jscaps);
ml.setCapabilitiesLastUpdated(new Date());
}
public static void setPropertiesFromCapabilitiesWFS(WFSDataStore data, OskariLayer ml,
Set<String> systemCRSs) throws ServiceException {
try {
SimpleFeatureSource source = data.getFeatureSource(ml.getName());
WFSGetCapabilities capa = data.getWfsClient().getCapabilities();
setPropertiesFromCapabilitiesWFS(capa, source, ml, systemCRSs);
} catch (IOException e) {
throw new IllegalArgumentException("Can't find layer: " + ml.getName());
}
}
public static void setPropertiesFromCapabilitiesWFS(WFSGetCapabilities capa, SimpleFeatureSource source, OskariLayer ml,
Set<String> systemCRSs) throws ServiceException {
ml.setCapabilities(LayerJSONFormatterWFS.createCapabilitiesJSON(capa, source, systemCRSs));
ml.setCapabilitiesLastUpdated(new Date());
}
public static void setPropertiesFromCapabilitiesOAPIF(WFS3Service service, OskariLayer ml,
Set<String> systemCRSs) {
ml.setCapabilities(LayerJSONFormatterWFS.createCapabilitiesJSON(service, ml.getName(), systemCRSs));
ml.setCapabilitiesLastUpdated(new Date());
}
} |
package io.sniffy.test;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class SharedConnectionDataSourceTest {
private DataSource targetDataSource;
@Mock
private DataSource mockDataSouce;
@Before
public void setupTargetDataSource() {
JdbcDataSource h2DataSource = new JdbcDataSource();
h2DataSource.setURL("jdbc:h2:mem:");
targetDataSource = h2DataSource;
}
@Test
public void testSameConnectionReturnedForAllThreads() throws SQLException, ExecutionException, InterruptedException {
SharedConnectionDataSource sharedConnectionDataSource = new SharedConnectionDataSource(targetDataSource);
{
Connection masterConnection = sharedConnectionDataSource.getConnection();
Connection slaveConnection = newSingleThreadExecutor().submit((Callable<Connection>) sharedConnectionDataSource::getConnection).get();
assertNotEquals(masterConnection, slaveConnection);
}
sharedConnectionDataSource.setCurrentThreadAsMaster();
try (Connection masterConnection = sharedConnectionDataSource.getConnection();
Connection slaveConnection = newSingleThreadExecutor().submit(
(Callable<Connection>) sharedConnectionDataSource::getConnection).get()
) {
assertEquals(masterConnection, slaveConnection);
} finally {
sharedConnectionDataSource.resetMasterConnection();
}
{
Connection masterConnection = sharedConnectionDataSource.getConnection();
Connection slaveConnection = newSingleThreadExecutor().submit((Callable<Connection>) sharedConnectionDataSource::getConnection).get();
assertNotEquals(masterConnection, slaveConnection);
}
}
@Test
public void testSlaveConnectionCloseIgnored() throws SQLException, ExecutionException, InterruptedException {
SharedConnectionDataSource sharedConnectionDataSource = new SharedConnectionDataSource(targetDataSource);
sharedConnectionDataSource.setCurrentThreadAsMaster();
try (Connection masterConnection = sharedConnectionDataSource.getConnection();
Connection slaveConnection = newSingleThreadExecutor().submit(
(Callable<Connection>) sharedConnectionDataSource::getConnection).get()
) {
assertEquals(masterConnection, slaveConnection);
slaveConnection.close();
assertFalse(slaveConnection.isClosed());
} finally {
sharedConnectionDataSource.resetMasterConnection();
}
}
@Test
public void testStatementGetConnectionReturnsProxy() throws SQLException, InterruptedException {
SharedConnectionDataSource sharedConnectionDataSource = new SharedConnectionDataSource(targetDataSource);
sharedConnectionDataSource.setCurrentThreadAsMaster();
try (Connection masterConnection = sharedConnectionDataSource.getConnection();
PreparedStatement preparedStatement = masterConnection.prepareStatement("SELECT 1 FROM DUAL")) {
assertEquals(masterConnection, preparedStatement.getConnection());
} finally {
sharedConnectionDataSource.resetMasterConnection();
}
}
@Test
public void testGetLogWriterCallsTarget() throws SQLException {
SharedConnectionDataSource sharedConnectionDataSource = new SharedConnectionDataSource(mockDataSouce);
PrintWriter printWriter = new PrintWriter(new ByteArrayOutputStream());
when(mockDataSouce.getLogWriter()).thenReturn(printWriter);
assertEquals(printWriter, sharedConnectionDataSource.getLogWriter());
verify(mockDataSouce).getLogWriter();
verifyNoMoreInteractions(mockDataSouce);
}
@Test
public void testSetLogWriterCallsTarget() throws SQLException {
SharedConnectionDataSource sharedConnectionDataSource = new SharedConnectionDataSource(mockDataSouce);
AtomicReference<PrintWriter> captured = new AtomicReference<>();
doAnswer(invocation -> {
captured.set(invocation.getArgumentAt(0, PrintWriter.class)); return null;
}).when(mockDataSouce).setLogWriter(any(PrintWriter.class));
PrintWriter printWriter = new PrintWriter(new ByteArrayOutputStream());
sharedConnectionDataSource.setLogWriter(printWriter);
assertEquals(printWriter, captured.get());
verify(mockDataSouce).setLogWriter(any(PrintWriter.class));
verifyNoMoreInteractions(mockDataSouce);
}
} |
package de.andreasgiemza.mangadownloader.sites.implementations.englishscanlationgroups;
import de.andreasgiemza.mangadownloader.sites.Site;
import de.andreasgiemza.mangadownloader.sites.extend.FoOlSlide;
/**
*
* @author Andreas Giemza <andreas@giemza.net>
*/
public class S2scans extends FoOlSlide implements Site {
public S2scans() {
super("http://reader.s2smanga.com", "/directory/");
}
} |
package org.rstudio.studio.client.workbench.views.source.editors.text.themes;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayInteger;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.LinkElement;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.Timer;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.rstudio.core.client.ColorUtil.RGBColor;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.dom.DomUtils;
import org.rstudio.core.client.widget.Operation;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.DelayedProgressRequestCallback;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditorThemeChangedEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.themes.model.ThemeServerOperations;
import java.util.HashMap;
import java.util.function.Consumer;
@Singleton
public class AceThemes
{
@Inject
public AceThemes(ThemeServerOperations themeServerOperations,
final Provider<UIPrefs> prefs,
EventBus events)
{
themeServerOperations_ = themeServerOperations;
events_ = events;
prefs_ = prefs;
themes_ = new HashMap<>();
docRootUrl_ = null;
prefs.get().theme().bind(theme -> applyTheme(theme));
}
private void applyTheme(Document document, final AceTheme theme)
{
// Build a relative path to avoid having to register 80000 theme URI handlers on the server.
int pathUpCount = 0;
String currentUrl = document.getURL();
if (null == docRootUrl_)
{
docRootUrl_ = currentUrl;
}
else if (!currentUrl.equals(docRootUrl_) &&
currentUrl.indexOf(docRootUrl_) == 0)
{
pathUpCount = currentUrl.substring(docRootUrl_.length()).split("/").length;
}
// Build the URL.
StringBuilder urlBuilder = new StringBuilder();
for (int i = 0; i < pathUpCount; ++i)
{
urlBuilder.append("../");
}
urlBuilder.append(theme.getUrl())
.append("?dark=")
.append(theme.isDark() ? "1" : "0");
LinkElement currentStyleEl = document.createLinkElement();
currentStyleEl.setType("text/css");
currentStyleEl.setRel("stylesheet");
currentStyleEl.setId(linkId_);
currentStyleEl.setHref(urlBuilder.toString());
Element oldStyleEl = document.getElementById(linkId_);
if (null != oldStyleEl)
{
document.getBody().replaceChild(currentStyleEl, oldStyleEl);
}
else
{
document.getBody().appendChild(currentStyleEl);
}
if(theme.isDark())
document.getBody().addClassName("editor_dark");
else
document.getBody().removeClassName("editor_dark");
// Deferred so that the browser can render the styles.
new Timer()
{
@Override
public void run()
{
events_.fireEvent(new EditorThemeChangedEvent(theme));
// synchronize the effective background color with the desktop
if (Desktop.isDesktop())
{
// find 'rstudio_container' element (note that this may not exist
// in some satellite windows; e.g. the Git window)
Element el = Document.get().getElementById("rstudio_container");
if (el == null)
return;
Style style = DomUtils.getComputedStyles(el);
String color = style.getBackgroundColor();
RGBColor parsed = RGBColor.fromCss(color);
JsArrayInteger colors = JsArrayInteger.createArray(3).cast();
colors.set(0, parsed.red());
colors.set(1, parsed.green());
colors.set(2, parsed.blue());
Desktop.getFrame().setBackgroundColor(colors);
Desktop.getFrame().syncToEditorTheme(theme.isDark());
el = DomUtils.getElementsByClassName("rstheme_toolbarWrapper")[0];
style = DomUtils.getComputedStyles(el);
color = style.getBackgroundColor();
parsed = RGBColor.fromCss(color);
Desktop.getFrame().changeTitleBarColor(parsed.red(), parsed.green(), parsed.blue());
}
}
}.schedule(100);
}
private void applyTheme(final AceTheme theme)
{
applyTheme(Document.get(), theme);
}
public void applyTheme(Document document)
{
applyTheme(document, prefs_.get().theme().getValue());
}
public void getThemes(
Consumer<HashMap<String, AceTheme>> themeConsumer,
ProgressIndicator indicator)
{
themeServerOperations_.getThemes(
new DelayedProgressRequestCallback<JsArray<AceTheme>>(indicator)
{
@Override
public void onSuccess(JsArray<AceTheme> jsonThemeArray)
{
themes_.clear();
int len = jsonThemeArray.length();
for (int i = 0; i < len; ++i)
{
AceTheme theme = jsonThemeArray.get(i);
themes_.put(theme.getName(), theme);
}
if (len == 0)
Debug.logWarning("Server was unable to find any installed themes.");
themeConsumer.accept(themes_);
}
});
}
public void addTheme(
String themeLocation,
Consumer<String> stringConsumer,
Consumer<String> errorMessageConsumer)
{
themeServerOperations_.addTheme(new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String result)
{
stringConsumer.accept(result);
}
@Override
public void onError(ServerError error)
{
errorMessageConsumer.accept(error.getUserMessage());
}
}, themeLocation);
}
public void removeTheme(
String themeName,
Consumer<String> errorMessageConsumer,
Operation afterOperation)
{
if (!themes_.containsKey(themeName))
{
errorMessageConsumer.accept("The specified theme does not exist");
}
else if (themes_.get(themeName).isDefaultTheme())
{
errorMessageConsumer.accept("The specified theme is a default RStudio theme and cannot be removed.");
}
else
{
themeServerOperations_.removeTheme(
new ServerRequestCallback<Void>()
{
@Override
public void onResponseReceived(Void response)
{
themes_.remove(themeName);
afterOperation.execute();
}
@Override
public void onError(ServerError error)
{
errorMessageConsumer.accept(error.getUserMessage());
}
},
themeName);
}
}
// This function can be used to get the name of a theme without adding it to RStudio. It is not
// used to get the name of an existing theme.
public void getThemeName(
String themeLocation,
Consumer<String> stringConsumer,
Consumer<String> errorMessageConsumer)
{
themeServerOperations_.getThemeName(
new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String result)
{
stringConsumer.accept(result);
}
@Override
public void onError(ServerError error)
{
errorMessageConsumer.accept(error.getUserMessage());
}
},
themeLocation);
}
private ThemeServerOperations themeServerOperations_;
private final EventBus events_;
private final Provider<UIPrefs> prefs_;
private final String linkId_ = "rstudio-acethemes-linkelement";
private HashMap<String, AceTheme> themes_;
private String docRootUrl_;
} |
package org.rstudio.studio.client.workbench.views.source.editors.text.themes;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayInteger;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.LinkElement;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.Timer;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.rstudio.core.client.ColorUtil.RGBColor;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.dom.DomUtils;
import org.rstudio.core.client.widget.Operation;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.DelayedProgressRequestCallback;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditorThemeChangedEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.themes.model.ThemeServerOperations;
import java.util.HashMap;
import java.util.function.Consumer;
@Singleton
public class AceThemes
{
@Inject
public AceThemes(ThemeServerOperations themeServerOperations,
final Provider<UIPrefs> prefs,
EventBus events)
{
themeServerOperations_ = themeServerOperations;
events_ = events;
prefs_ = prefs;
themes_ = new HashMap<>();
prefs.get().theme().bind(theme -> applyTheme(theme));
}
private void applyTheme(Document document, final AceTheme theme)
{
Element oldStyleEl = document.getElementById(linkId_);
LinkElement currentStyleEl = document.createLinkElement();
currentStyleEl.setType("text/css");
currentStyleEl.setRel("stylesheet");
currentStyleEl.setId(linkId_);
currentStyleEl.setHref(theme.getUrl() + "?dark=" + (theme.isDark() ? "1" : "0"));
if (null != oldStyleEl)
{
document.getBody().replaceChild(currentStyleEl, oldStyleEl);
}
else
{
document.getBody().appendChild(currentStyleEl);
}
if(theme.isDark())
document.getBody().addClassName("editor_dark");
else
document.getBody().removeClassName("editor_dark");
// Deferred so that the browser can render the styles.
new Timer()
{
@Override
public void run()
{
events_.fireEvent(new EditorThemeChangedEvent(theme));
// synchronize the effective background color with the desktop
if (Desktop.isDesktop())
{
Element el = Document.get().getElementById("rstudio_container");
Style style = DomUtils.getComputedStyles(el);
String color = style.getBackgroundColor();
RGBColor parsed = RGBColor.fromCss(color);
JsArrayInteger colors = JsArrayInteger.createArray(3).cast();
colors.set(0, parsed.red());
colors.set(1, parsed.green());
colors.set(2, parsed.blue());
Desktop.getFrame().setBackgroundColor(colors);
Desktop.getFrame().syncToEditorTheme(theme.isDark());
el = DomUtils.getElementsByClassName("rstheme_toolbarWrapper")[0];
style = DomUtils.getComputedStyles(el);
color = style.getBackgroundColor();
parsed = RGBColor.fromCss(color);
Desktop.getFrame().changeTitleBarColor(parsed.red(), parsed.green(), parsed.blue());
}
}
}.schedule(100);
}
private void applyTheme(final AceTheme theme)
{
applyTheme(Document.get(), theme);
}
public void applyTheme(Document document)
{
applyTheme(document, prefs_.get().theme().getValue());
}
public void getThemes(
Consumer<HashMap<String, AceTheme>> themeConsumer,
ProgressIndicator indicator)
{
themeServerOperations_.getThemes(
new DelayedProgressRequestCallback<JsArray<AceTheme>>(indicator)
{
@Override
public void onSuccess(JsArray<AceTheme> jsonThemeArray)
{
themes_.clear();
int len = jsonThemeArray.length();
for (int i = 0; i < len; ++i)
{
AceTheme theme = jsonThemeArray.get(i);
themes_.put(theme.getName(), theme);
}
if (len == 0)
Debug.logWarning("Server was unable to find any installed themes.");
themeConsumer.accept(themes_);
}
});
}
public void addTheme(
String themeLocation,
Consumer<String> stringConsumer,
Consumer<String> errorMessageConsumer)
{
themeServerOperations_.addTheme(new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String result)
{
stringConsumer.accept(result);
}
@Override
public void onError(ServerError error)
{
errorMessageConsumer.accept(error.getUserMessage());
}
}, themeLocation);
}
public void removeTheme(
String themeName,
Consumer<String> errorMessageConsumer,
Operation afterOperation)
{
if (!themes_.containsKey(themeName))
{
errorMessageConsumer.accept("The specified theme does not exist");
}
else if (themes_.get(themeName).isDefaultTheme())
{
errorMessageConsumer.accept("The specified theme is a default RStudio theme and cannot be removed.");
}
else
{
themeServerOperations_.removeTheme(
new ServerRequestCallback<Void>()
{
@Override
public void onResponseReceived(Void response)
{
themes_.remove(themeName);
afterOperation.execute();
}
@Override
public void onError(ServerError error)
{
errorMessageConsumer.accept(error.getUserMessage());
}
},
themeName);
}
}
// This function can be used to get the name of a theme without adding it to RStudio. It is not
// used to get the name of an existing theme.
public void getThemeName(
String themeLocation,
Consumer<String> stringConsumer,
Consumer<String> errorMessageConsumer)
{
themeServerOperations_.getThemeName(
new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String result)
{
stringConsumer.accept(result);
}
@Override
public void onError(ServerError error)
{
errorMessageConsumer.accept(error.getUserMessage());
}
},
themeLocation);
}
private ThemeServerOperations themeServerOperations_;
private final EventBus events_;
private final Provider<UIPrefs> prefs_;
private final String linkId_ = "rstudio-acethemes-linkelement";
private HashMap<String, AceTheme> themes_;
} |
package ca.corefacility.bioinformatics.irida.ria.web.services;
import java.security.Principal;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import ca.corefacility.bioinformatics.irida.model.announcements.Announcement;
import ca.corefacility.bioinformatics.irida.model.announcements.AnnouncementUserJoin;
import ca.corefacility.bioinformatics.irida.model.user.User;
import ca.corefacility.bioinformatics.irida.repositories.specification.AnnouncementSpecification;
import ca.corefacility.bioinformatics.irida.repositories.specification.UserSpecification;
import ca.corefacility.bioinformatics.irida.ria.web.announcements.dto.AnnouncementRequest;
import ca.corefacility.bioinformatics.irida.ria.web.announcements.dto.AnnouncementTableModel;
import ca.corefacility.bioinformatics.irida.ria.web.components.datatables.DataTablesParams;
import ca.corefacility.bioinformatics.irida.ria.web.components.datatables.DataTablesResponse;
import ca.corefacility.bioinformatics.irida.ria.web.components.datatables.config.DataTablesRequest;
import ca.corefacility.bioinformatics.irida.ria.web.components.datatables.models.DataTablesResponseModel;
import ca.corefacility.bioinformatics.irida.ria.web.models.datatables.DTAnnouncementUser;
import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableRequest;
import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableResponse;
import ca.corefacility.bioinformatics.irida.service.AnnouncementService;
import ca.corefacility.bioinformatics.irida.service.user.UserService;
/**
* A utility class for formatting responses for the admin announcements page UI.
*/
@Component
public class UIAnnouncementsService {
private final AnnouncementService announcementService;
private final UserService userService;
@Autowired
public UIAnnouncementsService(AnnouncementService announcementService, UserService userService) {
this.announcementService = announcementService;
this.userService = userService;
}
/**
* Returns a paged list of announcements for an administrator.
*
* @param tableRequest details about the current page of the table requested
* @return a {@link TableResponse} containing the list of announcements.
*/
public TableResponse<AnnouncementTableModel> getAnnouncementsAdmin(@RequestBody TableRequest tableRequest) {
final Page<Announcement> page = announcementService.search(
AnnouncementSpecification.searchAnnouncement(tableRequest.getSearch()),
PageRequest.of(tableRequest.getCurrent(), tableRequest.getPageSize(), tableRequest.getSort()));
final List<AnnouncementTableModel> announcements = page.getContent()
.stream()
.map(AnnouncementTableModel::new)
.collect(Collectors.toList());
return new TableResponse<>(announcements, page.getTotalElements());
}
/**
* Creates a new announcement
*
* @param announcementRequest details about the announcement to create.
* @param principal the currently logged in user
*/
public void createNewAnnouncement(@RequestBody AnnouncementRequest announcementRequest, Principal principal) {
User user = userService.getUserByUsername(principal.getName());
Announcement announcement = new Announcement("title placeholder", announcementRequest.getMessage(), false, user);
announcementService.create(announcement);
}
/**
* Update an existing announcement
*
* @param announcementRequest - the details of the announcement to update.
*/
public void updateAnnouncement(@RequestBody AnnouncementRequest announcementRequest) {
Announcement announcement = announcementService.read(announcementRequest.getId());
announcement.setTitle(announcementRequest.getTitle());
announcement.setMessage(announcementRequest.getMessage());
announcement.setPriority(announcementRequest.getPriority());
announcementService.update(announcement);
}
/**
* Delete an existing announcement.
*
* @param announcementRequest - the announcement to delete
*/
public void deleteAnnouncement(@RequestBody AnnouncementRequest announcementRequest) {
announcementService.delete(announcementRequest.getId());
}
/**
* Get user read status for current announcement
* @param announcementID {@link Long} identifier for the {@link Announcement}
* @param params {@link DataTablesParams} parameters for current DataTable
* @return {@link DataTablesResponse} containing the list of users.
*/
public @ResponseBody
DataTablesResponse getUserAnnouncementInfoTable(
@PathVariable Long announcementID,
final @DataTablesRequest DataTablesParams params) {
final Announcement currentAnnouncement = announcementService.read(announcementID);
final Page<User> page = userService.search(
UserSpecification.searchUser(params.getSearchValue()), PageRequest.of(params.getCurrentPage(), params.getLength(), params.getSort()));
final List<DataTablesResponseModel> announcementUsers = page.getContent().stream()
.map(user -> new DTAnnouncementUser(user, userHasRead(user, currentAnnouncement)))
.collect(Collectors.toList());
return new DataTablesResponse(params, page, announcementUsers);
}
/**
* Utility method for checking whether the {@link Announcement} has been read by the {@link User}
*
* @param user
* The user we want to check
* @param announcement
* The announcement we want to check.
* @return {@link AnnouncementUserJoin} representing that the user has read the announcement, or null
* if the user hasn't read the announcement.
*/
private AnnouncementUserJoin userHasRead(final User user, final Announcement announcement) {
final List<AnnouncementUserJoin> readUsers = announcementService.getReadUsersForAnnouncement(announcement);
final Optional<AnnouncementUserJoin> currentAnnouncement = readUsers.stream()
.filter(j -> j.getObject().equals(user)).findAny();
return currentAnnouncement.orElse(null);
}
} |
package net.sf.taverna.t2.activities.wsdl.servicedescriptions;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.Icon;
import net.sf.taverna.t2.activities.wsdl.WSDLActivity;
import net.sf.taverna.t2.activities.wsdl.WSDLActivityConfigurationBean;
import net.sf.taverna.t2.servicedescriptions.ServiceDescription;
import net.sf.taverna.t2.workflowmodel.processor.activity.Activity;
public class WSDLServiceDescription extends
ServiceDescription<WSDLActivityConfigurationBean> {
private static final String WSDL = "WSDL @ ";
private String use;
private URI uri;
private String style;
private String operation;
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
public URI getURI() {
return uri;
}
public void setURI(URI url) {
this.uri = url;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getType() {
return "WSDL";
}
@Override
public String toString() {
return operation;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Icon getIcon() {
return WSDLServiceProvider.wsdlIcon;
}
public Class<? extends Activity<WSDLActivityConfigurationBean>> getActivityClass() {
return WSDLActivity.class;
}
public WSDLActivityConfigurationBean getActivityConfiguration() {
WSDLActivityConfigurationBean bean = new WSDLActivityConfigurationBean();
bean.setWsdl(getURI().toASCIIString());
bean.setOperation(getOperation());
return bean;
}
public String getName() {
return getOperation();
}
@SuppressWarnings("unchecked")
public List<? extends Comparable> getPath() {
return Collections.singletonList(WSDL + getURI());
}
public boolean isTemplateService() {
return false;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WSDLServiceDescription)) {
return false;
}
WSDLServiceDescription other = (WSDLServiceDescription) obj;
return getIdentifyingData().equals(other.getIdentifyingData());
}
@Override
public int hashCode() {
return getIdentifyingData().hashCode();
}
protected List<Object> getIdentifyingData() {
return Arrays.<Object> asList(getURI(), getOperation());
}
} |
package org.broadinstitute.hellbender.tools.coveragemodel.germline;
import com.google.common.collect.ImmutableMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.spark.api.java.JavaSparkContext;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.ArgumentCollection;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.barclay.help.DocumentedFeature;
import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions;
import org.broadinstitute.hellbender.cmdline.programgroups.CopyNumberProgramGroup;
import org.broadinstitute.hellbender.engine.spark.SparkContextFactory;
import org.broadinstitute.hellbender.exceptions.UserException;
import org.broadinstitute.hellbender.tools.coveragemodel.CoverageModelArgumentCollection;
import org.broadinstitute.hellbender.tools.coveragemodel.CoverageModelEMAlgorithm;
import org.broadinstitute.hellbender.tools.coveragemodel.CoverageModelEMWorkspace;
import org.broadinstitute.hellbender.tools.coveragemodel.CoverageModelParameters;
import org.broadinstitute.hellbender.tools.exome.*;
import org.broadinstitute.hellbender.tools.exome.germlinehmm.IntegerCopyNumberState;
import org.broadinstitute.hellbender.tools.exome.germlinehmm.IntegerCopyNumberTransitionMatrixCollection;
import org.broadinstitute.hellbender.tools.exome.germlinehmm.IntegerCopyNumberTransitionProbabilityCacheCollection;
import org.broadinstitute.hellbender.tools.exome.sexgenotyper.ContigGermlinePloidyAnnotationTableReader;
import org.broadinstitute.hellbender.tools.exome.sexgenotyper.GermlinePloidyAnnotatedTargetCollection;
import org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeDataCollection;
import org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeTableReader;
import org.broadinstitute.hellbender.utils.SparkToggleCommandLineProgram;
import org.broadinstitute.hellbender.utils.Utils;
import org.broadinstitute.hellbender.utils.gcs.BucketUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.*;
import java.util.ArrayList;
import java.util.Map;
/**
* Models and denoises coverage profiles and detects germline copy number variation
*
* <p>The tool requires the following parameters:
*
* <dl>
* <dt>Job type (specified via argument --jobType)</dt>
*
* <dt>Combined raw or GC corrected (but not proportional) read counts table (specified via argument
* --input). The format is described in {@link ReadCountCollectionUtils}</dt>
*
* <dt>Sample sex genotypes table (specified via argument --sexGenotypeTable). The format is described
* in {@link SexGenotypeTableReader}</dt>
*
* <dt>Germline contig ploidy annotations for all sex genotypes (specified via argument
* --contigAnnotationsTable). The format is described in {@link ContigGermlinePloidyAnnotationTableReader}</dt>
*
* <dt>Prior transition probabilities between different copy number states (specified via argument
* --copyNumberTransitionPriorTable). The format is described in
* {@link IntegerCopyNumberTransitionMatrixCollection.IntegerCopyNumberTransitionMatrixCollectionReader}</dt>
*
* <dt>Output path for inferred model parameters, posteriors, and checkpoints (specified via argument
* --outputPath) </dt>
* </dl>
* </p>
*
* <p>The tool automatically uses Spark clusters if available. Otherwise, it will run in the single-machine
* (local) mode. If running the tool on a single machine, be sure to disable Spark
* altogether (--disableSpark true) since a local Spark context will only add unnecessary overhead.</p>
*
* <p>To make an effective PoN with at least 50 samples will require use of a Spark cluster.</p>
*
* <h3>Examples</h3>
*
* <p>To make CNV calls and simultaneously create a Panel of Normals (PoN), use --jobType LEARN_AND_CALL:</p>
* <pre>
* java -Xmx16g -jar $gatk_jar GermlineCNVCaller \
* --jobType LEARN_AND_CALL \
* --input combined_read_counts.tsv \
* --contigAnnotationsTable grch37_contig_annotations.tsv \
* --copyNumberTransitionPriorTable grch37_germline_CN_priors.tsv \
* --outputPath learn_and_call_results \
* --sexGenotypeTable SEX_GENOTYPES.tsv \
* --disableSpark true
* </pre>
*
* <p>
* This creates a directory of results.
* The model_final and posteriors_final folders contain the PoN and CNV calls, respectively.
* </p>
*
* <p>To make CNV calls using a Panel of Normals (PoN), use --jobType CALL_ONLY:</p>
*
* <pre>
* java -Xmx4g -jar $gatk_jar GermlineCNVCaller \
* --jobType CALL_ONLY \
* --input combined_read_counts.tsv \
* --inputModelPath learn_and_call_results/model_final \
* --contigAnnotationsTable grch37_contig_annotations.tsv \
* --copyNumberTransitionPriorTable grch37_germline_CN_priors.tsv \
* --outputPath call_only_results \
* --sexGenotypeTable SEX_GENOTYPES.tsv \
* --disableSpark true
* </pre>
*
* <p>
* Within the outputPath, the posteriors_final folder contains the CNV calls,
* as well as various metrics relating the model to each sample.
* In turn, the segments folder contains the per-sample CNV calls.
* </p>
*
* @author Mehrtash Babadi <mehrtash@broadinstitute.org>
*/
@CommandLineProgramProperties(
summary = "Performs coverage profile modelling, denoising, and detecting germline copy number variation",
oneLineSummary = "Performs coverage profile modelling, denoising, and detecting germline copy number variation",
programGroup = CopyNumberProgramGroup.class
)
@DocumentedFeature
public final class GermlineCNVCaller extends SparkToggleCommandLineProgram {
private static final long serialVersionUID = -1149969750485027900L;
public enum JobType {
/**
* Learn model parameters and calculate posteriors
*/
LEARN_AND_CALL,
/**
* Take a previously-learned set of model parameters and calculate posteriors
*/
CALL_ONLY
}
private static final Logger logger = LogManager.getLogger(GermlineCNVCaller.class);
public static final String FINAL_MODEL_SUBDIR = "model_final";
public static final String FINAL_POSTERIORS_SUBDIR = "posteriors_final";
public static final String CONTIG_PLOIDY_ANNOTATIONS_TABLE_LONG_NAME = "contigAnnotationsTable";
public static final String CONTIG_PLOIDY_ANNOTATIONS_TABLE_SHORT_NAME = "CAT";
public static final String SAMPLE_SEX_GENOTYPE_TABLE_LONG_NAME = "sexGenotypeTable";
public static final String SAMPLE_SEX_GENOTYPE_TABLE_SHORT_NAME = "SGT";
public static final String COPY_NUMBER_TRANSITION_PRIOR_TABLE_LONG_NAME = "copyNumberTransitionPriorTable";
public static final String COPY_NUMBER_TRANSITION_PRIOR_TABLE_SHORT_NAME = "CNT";
public static final String OUTPUT_PATH_LONG_NAME = "outputPath";
public static final String OUTPUT_PATH_SHORT_NAME = "O";
public static final String INPUT_MODEL_PATH_LONG_NAME = "inputModelPath";
public static final String INPUT_MODEL_PATH_SHORT_NAME = "IMP";
public static final String JOB_TYPE_LONG_NAME = "jobType";
public static final String JOB_TYPE_SHORT_NAME = "JT";
public static final String INPUT_READ_COUNTS_TABLE_LONG_NAME = StandardArgumentDefinitions.INPUT_LONG_NAME;
public static final String INPUT_READ_COUNTS_TABLE_SHORT_NAME = StandardArgumentDefinitions.INPUT_SHORT_NAME;
@Argument(
doc = "Combined read count collection URI. Combined raw or GC corrected (but not proportional) " +
"read counts table. Can be for a cohort or for a single sample.",
fullName = INPUT_READ_COUNTS_TABLE_LONG_NAME,
shortName = INPUT_READ_COUNTS_TABLE_SHORT_NAME,
optional = false
)
protected String readCountsURI;
@Argument(
doc = "Contig ploidy annotations URI. For an example fuke for the human reference, see the GATK Resource Bundle.",
fullName = CONTIG_PLOIDY_ANNOTATIONS_TABLE_LONG_NAME,
shortName = CONTIG_PLOIDY_ANNOTATIONS_TABLE_SHORT_NAME,
optional = false
)
protected String contigPloidyAnnotationsURI;
@Argument(
doc = "Sample sex genotypes URI. Either from TargetCoverageSexGenotyper " +
"or a table listing the known sex genotypes of each sample. " +
"Only two columns, labeled SAMPLE_NAME and SEX_GENOTYPE, are required. " +
"The SEX_GENOTYPE column values must match those of the contigAnnotationsTable.</p>",
fullName = SAMPLE_SEX_GENOTYPE_TABLE_LONG_NAME,
shortName = SAMPLE_SEX_GENOTYPE_TABLE_SHORT_NAME,
optional = false
)
protected String sampleSexGenotypesURI;
@Argument(
doc = "Copy number transition prior table URI. Lists per contig and against the sex states, " +
"the relative file paths to files that in turn list in tsv format the copy number transition priors. " +
"For an example set of files for the human reference, see the GATK Resource Bundle.",
fullName = COPY_NUMBER_TRANSITION_PRIOR_TABLE_LONG_NAME,
shortName = COPY_NUMBER_TRANSITION_PRIOR_TABLE_SHORT_NAME,
optional = false
)
protected String copyNumberTransitionPriorTableURI;
@Argument(
doc = "Output path for saving the model, posteriors, and checkpoints",
fullName = OUTPUT_PATH_LONG_NAME,
shortName = OUTPUT_PATH_SHORT_NAME,
optional = false
)
protected String outputPath;
@Argument(
doc = "The tool can be run in two modes by specifying the job type (LEARN_AND_CALL or CALL_ONLY). " +
"LEARN_AND_CALL learns model parameters from coverage profiles, saves the model (Panel of Normals or PoN), " +
"as well as various posteriors (copy number, sample-specific biases, read depth, " +
"model-compatibility log likelihoods, etc.) to disk.\n" +
"CALL_ONLY takes a previously learned model (PoN) from the argument " +
"--inputModelPath, and calculates various posteriors, i.e. makes copy number variation calls",
fullName = JOB_TYPE_LONG_NAME,
shortName = JOB_TYPE_SHORT_NAME,
optional = false
)
protected JobType jobType;
@Argument(
doc = "Input model (panel of normals) path",
fullName = INPUT_MODEL_PATH_LONG_NAME,
shortName = INPUT_MODEL_PATH_SHORT_NAME,
optional = true
)
protected String modelPath = null;
@ArgumentCollection
protected final CoverageModelArgumentCollection params = new CoverageModelArgumentCollection();
@ArgumentCollection
protected final TargetArgumentCollection optionalTargets = new TargetArgumentCollection();
/* custom serializers */
private static final Map<String, String> coverageModellerExtraSparkProperties = ImmutableMap.of(
"spark.kryo.registrator",
"org.nd4j.Nd4jRegistrator,org.broadinstitute.hellbender.utils.spark.UnmodifiableCollectionsRegistrator");
/**
* Override doWork to inject custom Nd4j serializer and set a temporary checkpointing path
*/
@Override
protected Object doWork() {
/* validate parameters */
params.validate();
JavaSparkContext ctx = null;
if (!isDisableSpark) {
/* create the spark context */
final Map<String, String> sparkProperties = sparkArgs.getSparkProperties();
appendExtraSparkProperties(sparkProperties, coverageModellerExtraSparkProperties);
ctx = SparkContextFactory.getSparkContext(getProgramName(), sparkProperties, sparkArgs.getSparkMaster());
ctx.setCheckpointDir(params.getRDDCheckpointingPath());
} else {
logger.info("Spark disabled. sparkMaster option (" + sparkArgs.getSparkMaster() + ") ignored.");
}
try {
runPipeline(ctx);
return null;
} finally {
afterPipeline(ctx);
}
}
/**
* Checks {@param originalProperties} for keys present in {@param extraProperties}. For new keys,
* it adds the value. For existing keys, it appends the value in a comma-separated fashion.
*
* @param originalProperties a non-null key-value {@link Map}
* @param extraProperties a non-null key-value {@link Map}
*/
private void appendExtraSparkProperties(@Nonnull final Map<String, String> originalProperties,
@Nonnull final Map<String, String> extraProperties) {
extraProperties.keySet().forEach(key ->
originalProperties.put(key, originalProperties.containsKey(key)
? originalProperties.get(key) + "," + extraProperties.get(key)
: extraProperties.get(key)));
}
/**
* The main routine
*
* @param ctx a nullable Spark context
*/
@Override
protected void runPipeline(@Nullable JavaSparkContext ctx) {
final TargetCollection<Target> optionalTargetsCollections = optionalTargets.readTargetCollection(true);
if (optionalTargetsCollections == null) {
logger.info("No target file was provided: using all targets in the combined read counts table");
}
logger.info("Parsing the read counts table...");
final ReadCountCollection readCounts = loadReadCountCollection(optionalTargetsCollections);
logger.info("Parsing the sample sex genotypes table...");
final SexGenotypeDataCollection sexGenotypeDataCollection = loadSexGenotypeDataCollection();
logger.info("Parsing the germline contig ploidy annotation table...");
final GermlinePloidyAnnotatedTargetCollection ploidyAnnotatedTargetCollection =
loadGermlinePloidyAnnotatedTargetCollection(readCounts);
logger.info("Parsing the copy number transition prior table and initializing the caches...");
final IntegerCopyNumberTransitionProbabilityCacheCollection transitionProbabilityCacheCollection =
createIntegerCopyNumberTransitionProbabilityCacheCollection();
final IntegerCopyNumberExpectationsCalculator integerCopyNumberExpectationsCalculator =
new IntegerCopyNumberExpectationsCalculator(transitionProbabilityCacheCollection,
params.getMinLearningReadCount());
final CoverageModelParameters model = getCoverageModelParameters();
Utils.validateArg(model != null || !jobType.equals(JobType.CALL_ONLY),
"Model parameters are not given; can not run the tool in the CALL_ONLY mode.");
logger.info("Initializing the EM algorithm workspace...");
final IntegerCopyNumberReferenceStateFactory referenceStateFactory =
new IntegerCopyNumberReferenceStateFactory(ploidyAnnotatedTargetCollection);
final CoverageModelEMWorkspace<IntegerCopyNumberState> workspace = new CoverageModelEMWorkspace<>(
readCounts, ploidyAnnotatedTargetCollection, sexGenotypeDataCollection,
integerCopyNumberExpectationsCalculator, params, model, referenceStateFactory, ctx);
final CoverageModelEMAlgorithm<IntegerCopyNumberState> algo = new CoverageModelEMAlgorithm<>(params,
workspace);
switch (jobType) {
case LEARN_AND_CALL:
algo.runExpectationMaximization();
logger.info("Saving the model to disk...");
workspace.writeModel(new File(outputPath, FINAL_MODEL_SUBDIR).getAbsolutePath());
break;
case CALL_ONLY:
algo.runExpectation();
break;
default:
throw new UnsupportedOperationException(String.format("\"%s\" is not recognized as a supported job type",
jobType.name()));
}
logger.info("Saving posteriors to disk...");
workspace.writePosteriors(new File(outputPath, FINAL_POSTERIORS_SUBDIR).getAbsolutePath(),
CoverageModelEMWorkspace.PosteriorVerbosityLevel.EXTENDED);
}
private CoverageModelParameters getCoverageModelParameters() {
CoverageModelParameters model;
if (modelPath != null) {
logger.info("Loading model parameters...");
model = CoverageModelParameters.read(modelPath);
} else {
model = null;
}
return model;
}
private IntegerCopyNumberTransitionProbabilityCacheCollection createIntegerCopyNumberTransitionProbabilityCacheCollection() {
IntegerCopyNumberTransitionProbabilityCacheCollection transitionProbabilityCacheCollection;
try (final Reader copyNumberTransitionPriorTableReader = getReaderFromURI(copyNumberTransitionPriorTableURI)) {
final String parentURI = new File(copyNumberTransitionPriorTableURI).getParent();
final IntegerCopyNumberTransitionMatrixCollection transitionMatrixCollection =
IntegerCopyNumberTransitionMatrixCollection.read(copyNumberTransitionPriorTableReader, parentURI);
transitionProbabilityCacheCollection = new IntegerCopyNumberTransitionProbabilityCacheCollection(
transitionMatrixCollection, true);
} catch (final IOException ex) {
throw new RuntimeException("Could not close the copy number transition prior table reader", ex);
}
return transitionProbabilityCacheCollection;
}
private GermlinePloidyAnnotatedTargetCollection loadGermlinePloidyAnnotatedTargetCollection(@Nonnull final ReadCountCollection readCounts) {
GermlinePloidyAnnotatedTargetCollection ploidyAnnotatedTargetCollection;
try (final Reader ploidyAnnotationsReader = getReaderFromURI(contigPloidyAnnotationsURI)) {
ploidyAnnotatedTargetCollection = new GermlinePloidyAnnotatedTargetCollection(ContigGermlinePloidyAnnotationTableReader
.readContigGermlinePloidyAnnotationsFromReader(contigPloidyAnnotationsURI, ploidyAnnotationsReader),
new ArrayList<>(readCounts.targets()));
} catch (final IOException ex) {
throw new RuntimeException("Could not close the germline contig ploidy annotations table reader", ex);
}
return ploidyAnnotatedTargetCollection;
}
private SexGenotypeDataCollection loadSexGenotypeDataCollection() {
SexGenotypeDataCollection sexGenotypeDataCollection;
try (final Reader sexGenotypeDataCollectionReader = getReaderFromURI(sampleSexGenotypesURI)) {
sexGenotypeDataCollection = new SexGenotypeDataCollection(sexGenotypeDataCollectionReader,
sampleSexGenotypesURI);
} catch (final IOException ex) {
throw new RuntimeException("Could not close the input sample sex genotypes table reader", ex);
}
return sexGenotypeDataCollection;
}
private ReadCountCollection loadReadCountCollection(@Nullable final TargetCollection<Target> targetsCollections) {
ReadCountCollection readCounts;
try (final Reader readCountsReader = getReaderFromURI(readCountsURI)) {
if (targetsCollections == null) {
readCounts = ReadCountCollectionUtils.parse(readCountsReader, readCountsURI);
} else {
readCounts = ReadCountCollectionUtils.parse(readCountsReader, readCountsURI, targetsCollections, true);
}
} catch (final IOException ex) {
throw new UserException.CouldNotReadInputFile("Could not parse the read counts table", ex);
}
return readCounts;
}
/**
* Takes a URI string (a local file, a Google bucket file, or an HDFS file) and returns a {@link Reader}
*
* @param path input URI string
* @return an instance of {@link Reader}
*/
private Reader getReaderFromURI(@Nonnull final String path) {
final InputStream inputStream = BucketUtils.openFile(path);
return new BufferedReader(new InputStreamReader(inputStream));
}
} |
package org.spongepowered.common.mixin.core.network.play;
import com.google.common.collect.ImmutableList;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.minecraft.command.CommandSource;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.ServerPlayNetHandler;
import net.minecraft.network.play.client.CAnimateHandPacket;
import net.minecraft.network.play.client.CPlayerPacket;
import net.minecraft.network.play.client.CTabCompletePacket;
import net.minecraft.network.play.client.CUpdateSignPacket;
import net.minecraft.network.play.client.CUseEntityPacket;
import net.minecraft.network.play.server.STabCompletePacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerList;
import net.minecraft.tileentity.SignTileEntity;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.objectweb.asm.Opcodes;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.entity.Sign;
import org.spongepowered.api.command.CommandCause;
import org.spongepowered.api.command.exception.CommandException;
import org.spongepowered.api.command.manager.CommandMapping;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.data.type.HandType;
import org.spongepowered.api.data.value.ListValue;
import org.spongepowered.api.entity.living.Humanoid;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.event.CauseStackManager;
import org.spongepowered.api.event.EventContextKeys;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.block.entity.ChangeSignEvent;
import org.spongepowered.api.event.entity.InteractEntityEvent;
import org.spongepowered.api.event.entity.MoveEntityEvent;
import org.spongepowered.api.event.entity.RotateEntityEvent;
import org.spongepowered.api.event.entity.living.AnimateHandEvent;
import org.spongepowered.api.event.entity.living.player.RespawnPlayerEvent;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Constant;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyConstant;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.common.SpongeCommon;
import org.spongepowered.common.accessor.entity.EntityAccessor;
import org.spongepowered.common.accessor.network.play.client.CPlayerPacketAccessor;
import org.spongepowered.common.bridge.network.NetworkManagerHolderBridge;
import org.spongepowered.common.bridge.server.management.PlayerListBridge;
import org.spongepowered.common.command.manager.SpongeCommandManager;
import org.spongepowered.common.command.registrar.BrigadierBasedRegistrar;
import org.spongepowered.common.command.registrar.BrigadierCommandRegistrar;
import org.spongepowered.common.data.value.ImmutableSpongeListValue;
import org.spongepowered.common.event.ShouldFire;
import org.spongepowered.common.event.SpongeCommonEventFactory;
import org.spongepowered.common.event.tracking.PhaseTracker;
import org.spongepowered.common.hooks.PlatformHooks;
import org.spongepowered.common.item.util.ItemStackUtil;
import org.spongepowered.common.util.Constants;
import org.spongepowered.common.util.VecHelper;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
@Mixin(ServerPlayNetHandler.class)
public abstract class ServerPlayNetHandlerMixin implements NetworkManagerHolderBridge {
private static final String[] IMPL$ZERO_LENGTH_STRING_ARRAY = new String[0];
private static final String[] IMPL$EMPTY_COMMAND_ARRAY = new String[] { "" };
// @formatter:off
@Shadow @Final public NetworkManager connection;
@Shadow public ServerPlayerEntity player;
@Shadow @Final private MinecraftServer server;
@Shadow private Vector3d awaitingPositionFromClient;
@Shadow private double firstGoodX;
@Shadow private double firstGoodY;
@Shadow private double firstGoodZ;
@Shadow private int receivedMovePacketCount;
@Shadow private int knownMovePacketCount;
@Shadow private int tickCount;
@Shadow private int awaitingTeleportTime;
@Shadow protected abstract boolean shadow$isSingleplayerOwner();
@Shadow public abstract void shadow$teleport(double x, double y, double z, float yaw, float pitch);
// @formatter:on
@Nullable private Entity impl$targetedEntity = null;
@Override
public NetworkManager bridge$getConnection() {
return this.connection;
}
@Inject(method = "handleCustomCommandSuggestions", at = @At(value = "NEW", target = "com/mojang/brigadier/StringReader", remap = false),
cancellable = true)
private void impl$getSuggestionsFromNonBrigCommand(final CTabCompletePacket p_195518_1_, final CallbackInfo ci) {
final String rawCommand = p_195518_1_.getCommand();
final String[] command = this.impl$extractCommandString(rawCommand);
try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) {
frame.pushCause(this.player);
final CommandCause cause = CommandCause.create();
final SpongeCommandManager manager = ((SpongeCommandManager) Sponge.getCommandManager());
if (!rawCommand.contains(" ")) {
final SuggestionsBuilder builder = new SuggestionsBuilder(command[0], 0);
if (command[0].isEmpty()) {
manager.getAliasesForCause(cause).forEach(builder::suggest);
} else {
manager.getAliasesThatStartWithForCause(cause, command[0]).forEach(builder::suggest);
}
this.connection.send(new STabCompletePacket(p_195518_1_.getId(), builder.build()));
ci.cancel();
} else {
final Optional<CommandMapping> mappingOptional =
manager.getCommandMapping(command[0].toLowerCase(Locale.ROOT)).filter(x -> !(x.getRegistrar() instanceof BrigadierBasedRegistrar));
if (mappingOptional.isPresent()) {
final CommandMapping mapping = mappingOptional.get();
if (mapping.getRegistrar().canExecute(cause, mapping)) {
try {
final SuggestionsBuilder builder = new SuggestionsBuilder(rawCommand, rawCommand.lastIndexOf(" ") + 1);
mapping.getRegistrar().suggestions(cause, mapping, command[0], command[1]).forEach(builder::suggest);
this.connection.send(new STabCompletePacket(p_195518_1_.getId(), builder.build()));
} catch (final CommandException e) {
cause.sendMessage(Identity.nil(), Component.text("Unable to create suggestions for your tab completion"));
this.connection.send(new STabCompletePacket(p_195518_1_.getId(), Suggestions.empty().join()));
}
} else {
this.connection.send(new STabCompletePacket(p_195518_1_.getId(), Suggestions.empty().join()));
}
ci.cancel();
}
}
}
}
@Redirect(method = "handleCustomCommandSuggestions",
at = @At(value = "INVOKE",
target = "Lcom/mojang/brigadier/CommandDispatcher;parse(Lcom/mojang/brigadier/StringReader;Ljava/lang/Object;)Lcom/mojang/brigadier/ParseResults;",
remap = false
)
)
private ParseResults<CommandSource> impl$informParserThisIsASuggestionCheck(final CommandDispatcher<CommandSource> commandDispatcher,
final StringReader command,
final Object source) {
return BrigadierCommandRegistrar.INSTANCE.getDispatcher().parse(command, (CommandSource) source, true);
}
/**
* Specifically hooks the reach distance to use the forge hook.
*/
@ModifyConstant(
method = "handleInteract",
constant = @Constant(doubleValue = 36.0D)
)
private double impl$getPlatformReach(final double thirtySix) {
final Entity targeted = this.impl$targetedEntity;
this.impl$targetedEntity = null;
return PlatformHooks.getInstance().getGeneralHooks().getEntityReachDistanceSq(this.player, targeted);
}
@Inject(method = "handleMovePlayer",
at = @At(
value = "FIELD",
opcode = Opcodes.GETFIELD,
target = "Lnet/minecraft/network/play/ServerPlayNetHandler;awaitingPositionFromClient:Lnet/minecraft/util/math/vector/Vector3d;"
),
slice = @Slice(
from = @At(
value = "FIELD",
target = "Lnet/minecraft/entity/player/ServerPlayerEntity;wonGame:Z"
),
to = @At(
value = "FIELD",
target = "Lnet/minecraft/network/play/ServerPlayNetHandler;tickCount:I",
ordinal = 1
)
),
cancellable = true
)
private void impl$callMoveEntityEvent(final CPlayerPacket packetIn, final CallbackInfo ci) {
// If the movement is modified we pretend that the player has queuedEndExit = true
// so that vanilla wont process that packet further
final CPlayerPacketAccessor packetInAccessor = (CPlayerPacketAccessor) packetIn;
// During login, minecraft sends a packet containing neither the 'moving' or 'rotating' flag set - but only once.
// We don't fire an event to avoid confusing plugins.
if (!packetInAccessor.accessor$hasPos() && !packetInAccessor.accessor$hasRot()) {
return;
}
final boolean goodMovementPacket = this.receivedMovePacketCount - this.knownMovePacketCount <= 5;
final boolean fireMoveEvent = goodMovementPacket && packetInAccessor.accessor$hasPos() && ShouldFire.MOVE_ENTITY_EVENT;
final boolean fireRotationEvent = goodMovementPacket && packetInAccessor.accessor$hasRot() && ShouldFire.ROTATE_ENTITY_EVENT;
final ServerPlayer player = (ServerPlayer) this.player;
final org.spongepowered.math.vector.Vector3d fromRotation = new org.spongepowered.math.vector.Vector3d(packetIn.getYRot(this.player
.yRot), packetIn.getXRot(this.player.xRot), 0);
// Use the position of the last movement with an event or the current player position if never called
// We need this because we ignore very small position changes as to not spam as many move events.
final org.spongepowered.math.vector.Vector3d fromPosition = player.getPosition();
org.spongepowered.math.vector.Vector3d toPosition = new org.spongepowered.math.vector.Vector3d(packetIn.getX(this.player.getX()),
packetIn.getY(this.player.getY()), packetIn.getZ(this.player.getZ()));
org.spongepowered.math.vector.Vector3d toRotation = new org.spongepowered.math.vector.Vector3d(packetIn.getYRot(this.player.yRot),
packetIn.getXRot(this.player.xRot), 0);
final boolean significantRotation = fromRotation.distanceSquared(toRotation) > (.15f * .15f);
final org.spongepowered.math.vector.Vector3d originalToPosition = toPosition;
boolean cancelMovement = false;
boolean cancelRotation = false;
// Call move & rotate event as needed...
if (fireMoveEvent) {
final MoveEntityEvent event = SpongeEventFactory.createMoveEntityEvent(PhaseTracker.getCauseStackManager().getCurrentCause(), (ServerPlayer) this.player, fromPosition,
toPosition, toPosition);
if (SpongeCommon.postEvent(event)) {
cancelMovement = true;
} else {
toPosition = event.getDestinationPosition();
}
}
if (significantRotation && fireRotationEvent) {
final RotateEntityEvent event = SpongeEventFactory.createRotateEntityEvent(PhaseTracker.getCauseStackManager().getCurrentCause(), (ServerPlayer) this.player, fromRotation,
toRotation);
if (SpongeCommon.postEvent(event)) {
cancelRotation = true;
} else {
toRotation = event.getToRotation();
}
}
// At this point, we cancel out and let the "confirmed teleport" code run through to update the
// player position and update the player's relation in the chunk manager.
if (cancelMovement) {
if (packetInAccessor.accessor$hasRot() && !cancelRotation) {
// Rest the rotation here
((EntityAccessor) this.player).invoker$setRot((float) toRotation.getX(), (float) toRotation.getY());
}
final float yaw = packetInAccessor.accessor$hasRot() && !cancelRotation ? (float) toRotation.getX() : this.player.yRot;
final float pitch = packetInAccessor.accessor$hasRot() && !cancelRotation ? (float) toRotation.getY() : this.player.xRot;
this.awaitingTeleportTime = this.tickCount;
// Then, we set the location, as if the player was teleporting
this.shadow$teleport(fromPosition.getX(), fromPosition.getY(), fromPosition.getZ(), yaw, pitch);
ci.cancel();
return;
}
// Handle event results
if (!toPosition.equals(originalToPosition)) {
// Check if we have to say it's a "teleport" vs a standard move
final double d4 = packetIn.getX(this.player.getX());
final double d5 = packetIn.getY(this.player.getY());
final double d6 = packetIn.getZ(this.player.getZ());
final double d7 = d4 - this.firstGoodX;
final double d8 = d5 - this.firstGoodY;
final double d9 = d6 - this.firstGoodZ;
final double d10 = this.player.getDeltaMovement().lengthSqr();
final double d11 = d7 * d7 + d8 * d8 + d9 * d9;
final float f2 = this.player.isFallFlying() ? 300.0F : 100.0F;
final int i = this.receivedMovePacketCount - this.knownMovePacketCount;
if (d11 - d10 > (double)(f2 * (float)i) && !this.shadow$isSingleplayerOwner()) {
// At this point, we need to set the target position so the teleport code forces it
this.awaitingPositionFromClient = VecHelper.toVanillaVector3d(toPosition);
((EntityAccessor) this.player).invoker$setRot((float) toRotation.getX(), (float) toRotation.getY());
// And reset the position update so the force set is done.
this.awaitingTeleportTime = this.tickCount - Constants.Networking.MAGIC_TRIGGER_TELEPORT_CONFIRM_DIFF;
} else {
// otherwise, set the data back onto the packet
packetInAccessor.accessor$hasPos(true);
packetInAccessor.accessor$x(toPosition.getX());
packetInAccessor.accessor$y(toPosition.getY());
packetInAccessor.accessor$z(toPosition.getZ());
}
}
}
@Inject(method = "handleInteract", cancellable = true,
at = @At(value = "INVOKE",
target = "Lnet/minecraft/entity/Entity;interactAt(Lnet/minecraft/entity/player/PlayerEntity;Lnet/minecraft/util/math/vector/Vector3d;Lnet/minecraft/util/Hand;)Lnet/minecraft/util/ActionResultType;"),
locals = LocalCapture.CAPTURE_FAILHARD
)
public void impl$onRightClickAtEntity(final CUseEntityPacket packetIn, final CallbackInfo ci, final ServerWorld serverworld, final Entity entity) {
final ItemStack itemInHand = packetIn.getHand() == null ? ItemStack.EMPTY : this.player.getItemInHand(packetIn.getHand());
final InteractEntityEvent.Secondary event = SpongeCommonEventFactory
.callInteractEntityEventSecondary(this.player, itemInHand, entity, packetIn.getHand(), null);
if (event.isCancelled()) {
ci.cancel();
}
}
@Inject(method = "handleInteract", cancellable = true,
at = @At(value = "INVOKE",
target = "Lnet/minecraft/entity/player/ServerPlayerEntity;attack(Lnet/minecraft/entity/Entity;)V"),
locals = LocalCapture.CAPTURE_FAILHARD
)
public void impl$onLeftClickEntity(final CUseEntityPacket packetIn, final CallbackInfo ci, final ServerWorld serverworld, final Entity entity) {
final InteractEntityEvent.Primary event = SpongeCommonEventFactory.callInteractEntityEventPrimary(this.player,
this.player.getItemInHand(this.player.getUsedItemHand()), entity, this.player.getUsedItemHand(), null);
if (event.isCancelled()) {
ci.cancel();
}
}
/**
* In production, the ServerWorld is lost.
*/
@SuppressWarnings("Duplicates")
@Surrogate
public void impl$onLeftClickEntity(final CUseEntityPacket packetIn, final CallbackInfo ci, final Entity entity) {
final InteractEntityEvent.Primary event = SpongeCommonEventFactory.callInteractEntityEventPrimary(this.player,
this.player.getItemInHand(this.player.getUsedItemHand()), entity, this.player.getUsedItemHand(), null);
if (event.isCancelled()) {
ci.cancel();
}
}
@SuppressWarnings("ConstantConditions")
@Inject(method = "handleAnimate",
at = @At(value = "INVOKE",
target = "Lnet/minecraft/entity/player/ServerPlayerEntity;resetLastActionTime()V"),
cancellable = true)
private void impl$throwAnimationEvent(final CAnimateHandPacket packetIn, final CallbackInfo ci) {
if (PhaseTracker.getInstance().getPhaseContext().isEmpty()) {
return;
}
SpongeCommonEventFactory.lastAnimationPacketTick = SpongeCommon.getServer().getTickCount();
SpongeCommonEventFactory.lastAnimationPlayer = new WeakReference<>(this.player);
if (ShouldFire.ANIMATE_HAND_EVENT) {
final HandType handType = (HandType) (Object) packetIn.getHand();
final ItemStack heldItem = this.player.getItemInHand(packetIn.getHand());
try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) {
frame.addContext(EventContextKeys.USED_ITEM.get(), ItemStackUtil.snapshotOf(heldItem));
frame.addContext(EventContextKeys.USED_HAND.get(), handType);
final AnimateHandEvent event =
SpongeEventFactory.createAnimateHandEvent(frame.getCurrentCause(), handType, (Humanoid) this.player);
if (SpongeCommon.postEvent(event)) {
ci.cancel();
}
}
}
}
@Redirect(
method = "handleClientCommand",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/server/management/PlayerList;respawn(Lnet/minecraft/entity/player/ServerPlayerEntity;Z)Lnet/minecraft/entity/player/ServerPlayerEntity;"
)
)
private ServerPlayerEntity impl$usePlayerDimensionForRespawn(final PlayerList playerList, final ServerPlayerEntity player,
final boolean keepAllPlayerData) {
// A few changes to Vanilla logic here that, by default, still preserve game mechanics:
// - If we have conquered The End then keep the dimension type we're headed to (which is Overworld as of 1.15)
// - Otherwise, check the platform hooks for which dimension to respawn to. In Sponge, this is the Player's dimension they
// are already in if we can respawn there which is only true for Overworld dimensions
final RegistryKey<World> respawnDimension = player.getRespawnDimension();
final @Nullable ServerWorld destinationWorld = this.server.getLevel(respawnDimension);
final ServerWorld overworld = this.server.getLevel(World.OVERWORLD);
if (overworld == null) {
throw new IllegalStateException("Somehow the Overworld is not retrievable while trying to respawn player " + player.getGameProfile().getName());
}
final ServerWorld destination = destinationWorld == null ? overworld : destinationWorld;
final RespawnPlayerEvent.SelectWorld event =
SpongeEventFactory.createRespawnPlayerEventSelectWorld(PhaseTracker.getCauseStackManager().getCurrentCause(),
(org.spongepowered.api.world.server.ServerWorld) destination,
(org.spongepowered.api.world.server.ServerWorld) player.getLevel(),
(org.spongepowered.api.world.server.ServerWorld) overworld,
(ServerPlayer) player);
SpongeCommon.postEvent(event);
((PlayerListBridge) this.server.getPlayerList()).bridge$setNewDestinationDimensionKey(((ServerWorld) event.getDestinationWorld()).dimension());
// The key is reset to null in the overwrite
return playerList.respawn(player, keepAllPlayerData);
}
@SuppressWarnings("deprecation")
@Redirect(method = "handleSignUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/play/client/CUpdateSignPacket;getLines()[Ljava/lang/String;"))
private String[] impl$callChangeSignEvent(final CUpdateSignPacket packet) {
final @Nullable ServerWorld world = this.server.getLevel(this.player.getLevel().dimension());
if (world == null) {
return new String[] {};
}
final BlockPos position = packet.getPos();
if (!world.hasChunkAt(position)) {
return new String[] {};
}
final @Nullable SignTileEntity sign = (SignTileEntity) world.getBlockEntity(position);
if (sign == null) {
return new String[] {};
}
final ListValue<Component> originalLinesValue = ((Sign) sign).getValue(Keys.SIGN_LINES)
.orElseGet(() -> new ImmutableSpongeListValue<>(Keys.SIGN_LINES.get(), ImmutableList.of()));
final List<Component> newLines = new ArrayList<>();
for (final String line : packet.getLines()) {
newLines.add(Component.text(SharedConstants.filterText(line)));
}
final ListValue.Mutable<Component> newLinesValue = ListValue.mutableOf(Keys.SIGN_LINES.get(), newLines);
final ChangeSignEvent event = SpongeEventFactory.createChangeSignEvent(PhaseTracker.getCauseStackManager().getCurrentCause(),
originalLinesValue.asImmutable(), newLinesValue,
(Sign) sign);
final ListValue<Component> toApply = SpongeCommon.postEvent(event) ? originalLinesValue : newLinesValue;
((Sign) sign).offer(toApply);
return ServerPlayNetHandlerMixin.IMPL$ZERO_LENGTH_STRING_ARRAY;
}
private String[] impl$extractCommandString(final String commandString) {
if (commandString.isEmpty()) {
return ServerPlayNetHandlerMixin.IMPL$EMPTY_COMMAND_ARRAY;
}
if (commandString.startsWith("/")) {
return commandString.substring(1).split(" ", 2);
}
return commandString.split(" ", 2);
}
} |
package org.helioviewer.jhv.plugins.swek.config;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.ImageIcon;
import org.helioviewer.base.logging.Log;
import org.helioviewer.jhv.Settings;
import org.helioviewer.jhv.plugins.swek.settings.SWEKProperties;
import org.helioviewer.jhv.plugins.swek.settings.SWEKSettings;
import org.helioviewer.jhv.plugins.swek.view.SWEKIconBank;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author Bram.Bourgognie@oma.be
*
*/
public class SWEKConfigurationManager {
/** Singleton instance */
private static SWEKConfigurationManager singletonInstance;
/** Config loaded */
private boolean configLoaded;
/** Config file URL */
private URL configFileURL;
/** The loaded configuration */
private SWEKConfiguration configuration;
/** Map containing the sources */
private final Map<String, SWEKSource> sources;
/** Map containing the parameters */
private final Map<String, SWEKParameter> parameters;
/** Map containing the event types */
private final Map<String, SWEKEventType> eventTypes;
/** The properties of the swek plugin */
private final Properties swekProperties;
/**
* private constructor
*/
private SWEKConfigurationManager() {
configLoaded = false;
sources = new HashMap<String, SWEKSource>();
parameters = new HashMap<String, SWEKParameter>();
eventTypes = new HashMap<String, SWEKEventType>();
swekProperties = SWEKProperties.getSingletonInstance().getSWEKProperties();
}
/**
* Gives access to the singleton instance
*
* @return the singleton instance
*/
public static SWEKConfigurationManager getSingletonInstance() {
if (singletonInstance == null) {
singletonInstance = new SWEKConfigurationManager();
}
return singletonInstance;
}
/**
* Loads the configuration.
*
* If no configuration file is set by the user, the program downloads the
* configuration file online and saves it the
* JHelioviewer/Plugins/swek-plugin folder.
*
*/
public void loadConfiguration() {
if (!configLoaded) {
Log.debug("search and open the configuration file");
boolean isConfigParsed;
if (checkAndOpenUserSetFile()) {
isConfigParsed = parseConfigFile();
} else if (checkAndOpenHomeDirectoryFile()) {
boolean manuallyChanged = isManuallyChanged();
if (!manuallyChanged) {
// check if the file is manually changed if not we download
// the latest version anyway.
if (checkAndOpenOnlineFile()) {
isConfigParsed = parseConfigFile();
} else {
isConfigParsed = false;
}
} else {
isConfigParsed = parseConfigFile();
}
} else if (checkAndOpenOnlineFile()) {
isConfigParsed = parseConfigFile();
} else {
isConfigParsed = false;
}
if (!isConfigParsed) {
// TODO set on the panel the config file could not be parsed.
configLoaded = false;
} else {
configLoaded = true;
}
}
}
/**
* Checks if the configuration file was manually changed.
*
* @return true if the configuration file was initially changed, false if
* not
*/
private boolean isManuallyChanged() {
try {
InputStream configIs = configFileURL.openStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(configIs));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject configJSON = new JSONObject(sb.toString());
return parseManuallyChanged(configJSON);
} catch (JSONException e) {
Log.error("Could not parse the json : " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.error("Could not load the file : " + e.getMessage());
e.printStackTrace();
}
return false;
}
/**
* Gives a map with all the event types. The event type name is the key and
* the event type is the value.
*
* @return map containing the event types found in the configuration file
*/
public Map<String, SWEKEventType> getEventTypes() {
loadConfiguration();
return eventTypes;
}
/**
* Gives a map with all the event sources. The source name is the key and
* the source is the value.
*
* @return map containing the sources found in the configuration file
*/
public Map<String, SWEKSource> getSources() {
loadConfiguration();
return sources;
}
/**
* Gets the related event rules.
*
* @return the related event rules.
*/
public List<SWEKRelatedEvents> getSWEKRelatedEvents() {
loadConfiguration();
return configuration.getRelatedEvents();
}
/**
* Downloads the SWEK configuration from the Internet and saves it in the
* plugin home directory.
*
* @return true if the the file was found and copied to the home directory,
* false if the file could not be found, copied or something else
* went wrong.
*/
private boolean checkAndOpenOnlineFile() {
Log.debug("Download the configuration file from the net and copy it to the plugin home directory");
try {
URL url = new URL(swekProperties.getProperty("plugin.swek.onlineconfigfile"));
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
String saveFile = SWEKSettings.SWEK_HOME + swekProperties.getProperty("plugin.swek.configfilename");
Log.debug("saveFile : " + saveFile);
FileOutputStream fos = new FileOutputStream(saveFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
configFileURL = new URL("file://" + saveFile);
return true;
} catch (MalformedURLException e) {
Log.debug("Could not create a URL from the value found in the properties file: "
+ swekProperties.getProperty("plugin.swek.onlineconfigfile") + " : " + e);
} catch (IOException e) {
Log.debug("Something went wrong downloading the configuration file from the server or saving it to the local machine : " + e);
}
return false;
}
/**
* Checks the home directory of the plugin (normally
* ~/JHelioviewer/Plugins/swek-plugin/) for the existence of the
* SWEKSettings.json file.
*
* @return true if the file was found and useful, false if the file was not
* found.
*/
private boolean checkAndOpenHomeDirectoryFile() {
String configFile = SWEKSettings.SWEK_HOME + swekProperties.getProperty("plugin.swek.configfilename");
try {
File f = new File(configFile);
if (f.exists()) {
configFileURL = new URL("file://" + configFile);
return true;
} else {
Log.debug("File created from the settings : " + configFile + " does not exists on this system.");
}
} catch (MalformedURLException e) {
Log.debug("File at possition " + configFile + " could not be parsed into an URL");
}
return false;
}
/**
* Checks the jhelioviewer settings file for a swek configuration file.
*
* @return true if the file as found and useful, false if the file was not
* found.
*/
private boolean checkAndOpenUserSetFile() {
Log.debug("Search for a user defined configuration file in the JHelioviewer setting file.");
Settings jhvSettings = Settings.getSingletonInstance();
String fileName = jhvSettings.getProperty("plugin.swek.configfile");
if (fileName == null) {
Log.debug("No configured filename found.");
return false;
} else {
try {
URI fileLocation = new URI(fileName);
configFileURL = fileLocation.toURL();
Log.debug("Config file : " + configFileURL.toString());
return true;
} catch (URISyntaxException e) {
Log.debug("Wrong URI syntax for the found file name : " + fileName);
} catch (MalformedURLException e) {
Log.debug("Could not convert the URI in a correct URL. The found file name : " + fileName);
}
return false;
}
}
/**
* Parses the SWEK settings.
*/
private boolean parseConfigFile() {
try {
InputStream configIs = configFileURL.openStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(configIs));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject configJSON = new JSONObject(sb.toString());
return parseJSONConfig(configJSON);
} catch (IOException e) {
Log.debug("The configuration file could not be parsed : " + e);
} catch (JSONException e) {
Log.debug("Could not parse the given JSON : " + e);
}
return false;
}
/**
* Parses the JSON from start
*
* @param configJSON
* The JSON to parse
* @return true if the JSON configuration could be parsed, false if not.
*/
private boolean parseJSONConfig(JSONObject configJSON) {
configuration = new SWEKConfiguration();
try {
configuration.setManuallyChanged(parseManuallyChanged(configJSON));
configuration.setConfigurationVersion(parseVersion(configJSON));
configuration.setSources(parseSources(configJSON));
configuration.setEventTypes(parseEventTypes(configJSON));
configuration.setRelatedEvents(parseRelatedEvents(configJSON));
return true;
} catch (JSONException e) {
Log.error("Could not parse config json");
e.printStackTrace();
return false;
}
}
/**
* Parses a if the configuration was manually changed from a json.
*
* @param jsonObject
* the json from which to parse the manually changed indication
* @return the parsed manually changed indication
* @throws JSONException
* if the manually changed indication could not be parsed
*/
private boolean parseManuallyChanged(JSONObject configJSON) throws JSONException {
return configJSON.getBoolean("manually_changed");
}
/**
* Parses the configuration version from the big json.
*
* @param configJSON
* The JSON from which to parse
* @return The parsed configuration version
* @throws JSONException
* If the configuration version could not be parsed.
*/
private String parseVersion(JSONObject configJSON) throws JSONException {
return configJSON.getString("config_version");
}
/**
* Parses the list of sources from a json and adds the sources to a map
* indexed on the name of the source.
*
* @param configJSON
* the JSON from which to parse the sources
* @return a list of sources parsed from the JSON
* @throws JSONException
* if the sources could not be parsed
*/
private List<SWEKSource> parseSources(JSONObject configJSON) throws JSONException {
ArrayList<SWEKSource> swekSources = new ArrayList<SWEKSource>();
JSONArray sourcesArray = configJSON.getJSONArray("sources");
for (int i = 0; i < sourcesArray.length(); i++) {
SWEKSource source = parseSource(sourcesArray.getJSONObject(i));
sources.put(source.getSourceName(), source);
swekSources.add(source);
}
return swekSources;
}
/**
* Parses a source from a json.
*
* @param jsonObject
* the json from which to parse the source
* @return the parsed source
* @throws JSONException
* if the source could not be parsed
*/
private SWEKSource parseSource(JSONObject jsonObject) throws JSONException {
SWEKSource source = new SWEKSource();
source.setSourceName(parseSourceName(jsonObject));
source.setProviderName(parseProviderName(jsonObject));
source.setDownloaderClass(parseDownloader(jsonObject));
source.setEventParserClass(parseEventParser(jsonObject));
source.setJarLocation(parseJarLocation(jsonObject));
source.setBaseURL(parseBaseURL(jsonObject));
source.setGeneralParameters(parseGeneralParameters(jsonObject));
return source;
}
/**
* Parses the source from a json.
*
* @param jsonObject
* the json from which to parse the source
* @return the parsed source
* @throws JSONException
* if the source could not be parsed
*/
private String parseSourceName(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("name");
}
/**
* Parses the provider name from a json.
*
* @param jsonObject
* the json from which to parse the provider name
* @return the parsed provider name
* @throws JSONException
* if the provider name could not be parsed
*/
private String parseProviderName(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("provider_name");
}
/**
* Parses the downloader description from a json.
*
* @param jsonObject
* the json from which to parse the downloader description
* @return the parsed downloader description
* @throws JSONException
* if the downloader description could not be parsed
*/
private String parseDownloader(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("downloader");
}
/**
* Parses the event parser from a json.
*
* @param jsonObject
* the json from which to parse the event parser
* @return the parsed event parser
* @throws JSONException
* if the event parser could not be parsed
*/
private String parseEventParser(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("event_parser");
}
/**
* Parses the jar location from a json.
*
* @param jsonObject
* the json from which to parse the jar location
* @return the parsed jar location
* @throws JSONException
* if the event parser could not be parsed
*/
private String parseJarLocation(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("jar_location");
}
/**
* Parses the base url from a json.
*
* @param jsonObject
* the json from which to parse the base url
* @return the parsed base url
* @throws JSONException
* if the base url could not be parsed
*/
private String parseBaseURL(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("base_url");
}
/**
* Parses the general parameters from a json.
*
* @param jsonObject
* the json from which to parse the general parameters
* @return the parsed general parameters
* @throws JSONException
* if the general parameters could not be parsed
*/
private List<SWEKParameter> parseGeneralParameters(JSONObject jsonObject) throws JSONException {
List<SWEKParameter> parameterList = new ArrayList<SWEKParameter>();
JSONArray parameterArray = jsonObject.getJSONArray("general_parameters");
for (int i = 0; i < parameterArray.length(); i++) {
SWEKParameter parameter = parseParameter(parameterArray.getJSONObject(i));
parameterList.add(parameter);
parameters.put(parameter.getParameterName(), parameter);
}
return parameterList;
}
/**
* Parses the list of event types from a json.
*
* @param configJSON
* the JSON from which to parse the event types
* @return a list of event types parsed from the JSON
* @throws JSONException
* if the event types could not be parsed
*/
private List<SWEKEventType> parseEventTypes(JSONObject configJSON) throws JSONException {
List<SWEKEventType> result = new ArrayList<SWEKEventType>();
JSONArray eventJSONArray = configJSON.getJSONArray("events_types");
for (int i = 0; i < eventJSONArray.length(); i++) {
SWEKEventType eventType = parseEventType(eventJSONArray.getJSONObject(i));
result.add(eventType);
eventTypes.put(eventType.getEventName(), eventType);
}
return result;
}
/**
* Parses an event type from a json.
*
* @param object
* The event type to parse
* @return The parsed event type
* @throws JSONException
*/
private SWEKEventType parseEventType(JSONObject object) throws JSONException {
SWEKEventType eventType = new SWEKEventType();
eventType.setEventName(parseEventName(object));
eventType.setSuppliers(parseSuppliers(object));
eventType.setParameterList(parseParameterList(object));
eventType.setRequestIntervalExtension(parseRequestIntervalExtension(object));
eventType.setStandardSelected(parseStandardSelected(object));
eventType.setGroupOn(parseGroupOn(object));
eventType.setCoordinateSystem(parseCoordinateSystem(object));
eventType.setSpatialRegion(parseSpatialRegion(object));
eventType.setEventIcon(parseEventIcon(object));
eventType.setColor(parseColor(object));
return eventType;
}
/**
* Parses the color from the json.
*
* @param object
* the json to parse from
* @return the color of the event type or black if something went wrong.
* @throws JSONException
* If the parsing went wrong
*/
private Color parseColor(JSONObject object) throws JSONException {
String color = object.getString("color");
if (color != null) {
try {
URI colorURI = new URI(color);
if (colorURI.getScheme().toLowerCase().equals("colorname")) {
return parseColorName(colorURI.getHost());
} else if (colorURI.getScheme().toLowerCase().equals("colorcode")) {
return parseColorCode(colorURI.getHost());
} else {
Log.info("Could not understand : " + color + " returned black color");
return Color.black;
}
} catch (URISyntaxException e) {
Log.info("Could not parse the URI " + color + " black color is returned.");
}
}
return Color.black;
}
/**
* Parses a hexadecimal or octal string to a color.
*
* @param colorCode
* the code to parse into a color
* @return the color represented by the hex st ring or black if something
* went wrong
*/
private Color parseColorCode(String colorCode) {
try {
return Color.decode(colorCode);
} catch (NumberFormatException ex) {
Log.info("Could not parse the color code " + colorCode + " black color is returned.");
return Color.black;
}
}
/**
* Parses a color name into a color.
*
* @param colorName
* the name to parse into a color
* @return the color represented by the color name or black if something
* went wrong
*/
private Color parseColorName(String colorName) {
try {
Field field = Class.forName("java.awt.Color").getField(colorName);
return (Color) field.get(null);
} catch (Exception e) {
Log.info("Could not parse the color name " + colorName + " black color is returned.");
return Color.black; // Not defined
}
}
/**
* Parses the event icon settings.
*
* @param object
* the JSON object from where to parse the icon object.
* @return the icon defined in the configuration
* @throws JSONException
* if the JSON object could not be parsed
*/
private ImageIcon parseEventIcon(JSONObject object) throws JSONException {
String eventIconValue = object.getString("icon");
if (eventIconValue != null) {
try {
URI eventIconURI = new URI(eventIconValue);
if (eventIconURI.getScheme().toLowerCase().equals("iconbank")) {
return SWEKIconBank.getSingletonInstance().getIcon(eventIconURI.getHost());
} else {
return SWEKIconBank.getSingletonInstance().getIcon("Other");
}
// TODO Bram : Add other ways to add icons (file,url,...)
} catch (URISyntaxException e) {
Log.info("Could not parse the URI " + eventIconValue + " null icon is returned.");
return null;
}
}
return null;
}
/**
* Parses the event name from a json.
*
* @param object
* the json from which the event name is parsed
* @return the event name
* @throws JSONException
* if the supplier name could not be parsed
*/
private String parseEventName(JSONObject object) throws JSONException {
return object.getString("event_name");
}
/**
* Parses the suppliers from a json.
*
* @param jsonObject
* the json from which the suppliers are parsed
* @return the suppliers list
* @throws JSONException
* if the suppliers could not be parsed
*/
private List<SWEKSupplier> parseSuppliers(JSONObject object) throws JSONException {
List<SWEKSupplier> suppliers = new ArrayList<SWEKSupplier>();
JSONArray suppliersArray = object.getJSONArray("suppliers");
for (int i = 0; i < suppliersArray.length(); i++) {
suppliers.add(parseSupplier(suppliersArray.getJSONObject(i)));
}
return suppliers;
}
/**
* Parses a supplier from a json.
*
* @param object
* the json from which the supplier is parsed
* @return the supplier
* @throws JSONException
* if the supplier could not be parsed
*/
private SWEKSupplier parseSupplier(JSONObject object) throws JSONException {
SWEKSupplier supplier = new SWEKSupplier();
supplier.setSupplierName(parseSupplierName(object));
supplier.setSupplierDisplayName(parseSupplierDisplayName(object));
supplier.setSource(parseSupplierSource(object));
return supplier;
}
/**
* Parses the supplier name from a json.
*
* @param object
* the json from which the supplier name is parsed
* @return the supplier name
* @throws JSONException
* if the supplier name could not be parsed
*/
private String parseSupplierName(JSONObject object) throws JSONException {
return object.getString("supplier_name");
}
/**
* Parses the supplier display name from a json
*
* @param object
* the JSON from which to parse the supplier display name
* @return the supplier display name
* @throws JSONException
* if the supplier display name could not be parsed
*/
private String parseSupplierDisplayName(JSONObject object) throws JSONException {
return object.getString("supplier_display_name");
}
/**
* Parses a supplier source from a json.
*
* @param object
* the json from which the supplier source is parsed
* @return the supplier source
* @throws JSONException
* if the supplier source could not be parsed
*/
private SWEKSource parseSupplierSource(JSONObject object) throws JSONException {
return sources.get(object.getString("source"));
}
/**
* Parses the parameter list from the given JSON.
*
* @param object
* the json from which to parse the parameter list
* @return the parameter list
* @throws JSONException
* if the parameter list could not be parsed.
*/
private List<SWEKParameter> parseParameterList(JSONObject object) throws JSONException {
List<SWEKParameter> parameterList = new ArrayList<SWEKParameter>();
JSONArray parameterListArray = object.getJSONArray("parameter_list");
for (int i = 0; i < parameterListArray.length(); i++) {
SWEKParameter parameter = parseParameter((JSONObject) parameterListArray.get(i));
parameterList.add(parameter);
parameters.put(parameter.getParameterName(), parameter);
}
return parameterList;
}
/**
* Parses a parameter from json.
*
* @param jsonObject
* the json from which to parse
* @return the parsed parameter
* @throws JSONException
* if the parameter could not be parsed
*/
private SWEKParameter parseParameter(JSONObject jsonObject) throws JSONException {
SWEKParameter parameter = new SWEKParameter();
parameter.setSource(parseSourceInParameter(jsonObject));
parameter.setParameterName(parseParameterName(jsonObject));
parameter.setParameterDisplayName(parseParameterDisplayName(jsonObject));
parameter.setParameterFilter(parseParameterFilter(jsonObject));
parameter.setDefaultVisible(parseDefaultVisible(jsonObject));
return parameter;
}
/**
* Parses the source from a json.
*
* @param jsonObject
* the json from which the source is parsed
* @return the source
* @throws JSONException
* if the source could not be parsed
*/
private String parseSourceInParameter(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("source");
}
/**
* Parses the parameter name from a json.
*
* @param jsonObject
* the json from which the parameter name is parsed
* @return the parameter name
* @throws JSONException
* if the parameter name could not be parsed
*/
private String parseParameterName(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("parameter_name");
}
/**
* Parses the parameter display name from a json.
*
* @param jsonObject
* the json from which the parameter display name is parsed
* @return the parameter display name
* @throws JSONException
* if the parameter display name could not be parsed
*/
private String parseParameterDisplayName(JSONObject jsonObject) throws JSONException {
return jsonObject.getString("parameter_display_name");
}
/**
* Parses the parameter filter from a given json.
*
* @param jsonObject
* the json to parse from
* @return the parsed filter
* @throws JSONException
* if the filter could not be parsed
*/
private SWEKParameterFilter parseParameterFilter(JSONObject jsonObject) throws JSONException {
SWEKParameterFilter filter = new SWEKParameterFilter();
JSONObject filterobject = jsonObject.optJSONObject("filter");
if (filterobject != null) {
filter.setFilterType(parseFilterType(filterobject));
filter.setMin(parseMin(filterobject));
filter.setMax(parseMax(filterobject));
filter.setStartValue(parseStartValue(filterobject));
filter.setStepSize(parseStepSize(filterobject));
return filter;
} else {
return null;
}
}
/**
* Parses the filter type from a json.
*
* @param object
* the json from which the filter type is parsed
* @return the filter type
* @throws JSONException
* if the filter type could not be parsed
*/
private String parseFilterType(JSONObject object) throws JSONException {
return object.getString("filter_type");
}
/**
* parses the minimum filter value from a json.
*
* @param object
* the json from which to filter the minimum value
* @return the minimum filter value
* @throws JSONException
* if the minimum filter value could not be parsed
*/
private double parseMin(JSONObject object) throws JSONException {
return object.getDouble("min");
}
/**
* Parses the maximum filter value from the json.
*
* @param object
* the json from which to parse the maximum filter value
* @return the maximum filter value
* @throws JSONException
* if the maximum filter value could not be parsed
*/
private double parseMax(JSONObject object) throws JSONException {
return object.getDouble("max");
}
/**
* Parses the step size from the json.
*
* @param object
* the json from which to parse the step size
* @return the step size
* @throws JSONException
* if the step size could not be parsed
*/
private double parseStepSize(JSONObject object) throws JSONException {
return object.getDouble("step_size");
}
/**
* Parses the start value from the json.
*
* @param object
* the json from which to parse the start value
* @return the start value
* @throws JSONException
* is the start value could not be parsed
*/
private Double parseStartValue(JSONObject object) throws JSONException {
return object.getDouble("start_value");
}
/**
* Parses the default visible from the given json.
*
* @param jsonObject
* the json from which to parse
* @return the parsed default visible
* @throws JSONException
* if the default visible could not be parsed
*/
private boolean parseDefaultVisible(JSONObject jsonObject) throws JSONException {
return jsonObject.getBoolean("default_visible");
}
/**
* Parses the request interval extension from the json.
*
* @param object
* the json from which to parse the request interval extension
* @return the parsed request interval extension
* @throws JSONException
* if the request interval extension could not be parsed
*/
private Long parseRequestIntervalExtension(JSONObject object) throws JSONException {
return object.getLong("request_interval_extension");
}
/**
* Parses the standard selected from the json.
*
* @param object
* the json from which to parse the standard selected
* @return true if standard selected is true in json, false if standard
* selected is false in json
* @throws JSONException
* if the standard selected could not be parsed from json.
*/
private boolean parseStandardSelected(JSONObject object) throws JSONException {
return object.getBoolean("standard_selected");
}
/**
* Parses the "group on" from the json.
*
* @param object
* the json from which to parse the "group on"
* @return the group on parameter
* @throws JSONException
* if the "group on" could not be parsed from the json.
*/
private SWEKParameter parseGroupOn(JSONObject object) throws JSONException {
return parameters.get(object.getString("group_on"));
}
/**
* Parses the "coordinate_system" from the json.
*
* @param object
* the json from which to parse the "coordinate_system"
* @return the coordinate system
* @throws JSONException
* if the "coordinate_system" could not be parsed from the json
*/
private String parseCoordinateSystem(JSONObject object) throws JSONException {
return object.getString("coordinate_system");
}
/**
* Parses the "spacial_region" from the json.
*
* @param object
* the object from which to parse the "spatial_region"
* @return the spatial region
* @throws JSONException
* if the "spatial_region" could not be parsed from the json
*/
private SWEKSpatialRegion parseSpatialRegion(JSONObject object) throws JSONException {
SWEKSpatialRegion spacialRegion = new SWEKSpatialRegion();
spacialRegion.setX1(parseX1(object.getJSONObject("spatial_region")));
spacialRegion.setY1(parseY1(object.getJSONObject("spatial_region")));
spacialRegion.setX2(parseX2(object.getJSONObject("spatial_region")));
spacialRegion.setY2(parseY2(object.getJSONObject("spatial_region")));
return spacialRegion;
}
/**
* Parses the x1 coordinate of the spatial region from the json.
*
* @param jsonObject
* the object from which to parse the x1-coordinate
* @return the x1 coordinate
* @throws JSONException
* if the x1 coordinate could not be parsed from the json
*/
private int parseX1(JSONObject jsonObject) throws JSONException {
return jsonObject.getInt("x1");
}
/**
* Parses the y1 coordinate of the spatial region from the json.
*
* @param jsonObject
* the object from which to parse the y1-coordinate
* @return the y1 coordinate
* @throws JSONException
* if the y1 coordinate could not be parsed from the json
*/
private int parseY1(JSONObject jsonObject) throws JSONException {
return jsonObject.getInt("y1");
}
/**
* Parses the x2 coordinate of the spatial region from the json.
*
* @param jsonObject
* the object from which to parse the x2-coordinate
* @return the x2 coordinate
* @throws JSONException
* if the x2 coordinate could not be parsed
*/
private int parseX2(JSONObject jsonObject) throws JSONException {
return jsonObject.getInt("x2");
}
/**
* Parses the y2 coordinate of the spatial region from the json.
*
* @param jsonObject
* the object from which to parse the y2 coordinate
* @return the y2 coordinate
* @throws JSONException
* if the y2 coordinate could not be parsed
*/
private int parseY2(JSONObject jsonObject) throws JSONException {
return jsonObject.getInt("y2");
}
/**
* Parses the list of related events from a json.
*
* @param jsonObject
* the json from which to parse the list of related events
* @return the parsed list of related events
* @throws JSONException
* if the list of related events could not be parsed
*/
private List<SWEKRelatedEvents> parseRelatedEvents(JSONObject configJSON) throws JSONException {
List<SWEKRelatedEvents> relatedEventsList = new ArrayList<SWEKRelatedEvents>();
JSONArray relatedEventsArray = configJSON.getJSONArray("related_events");
for (int i = 0; i < relatedEventsArray.length(); i++) {
relatedEventsList.add(parseRelatedEvent(relatedEventsArray.getJSONObject(i)));
}
return relatedEventsList;
}
/**
* Parses related events from a json.
*
* @param jsonObject
* the json from which to parse related events
* @return the parsed related events
* @throws JSONException
* if the related events could not be parsed
*/
private SWEKRelatedEvents parseRelatedEvent(JSONObject jsonObject) throws JSONException {
SWEKRelatedEvents relatedEvents = new SWEKRelatedEvents();
relatedEvents.setEvent(parseRelatedEventName(jsonObject));
relatedEvents.setRelatedWith(parseRelatedWith(jsonObject));
relatedEvents.setRelatedOnList(parseRelatedOnList(jsonObject));
return relatedEvents;
}
/**
* Parses a related event name from a json.
*
* @param jsonObject
* the json from which to parse the related event name
* @return the parsed related event type
* @throws JSONException
* if the related event name could not be parsed
*/
private SWEKEventType parseRelatedEventName(JSONObject jsonObject) throws JSONException {
return eventTypes.get(jsonObject.getString("event_name"));
}
/**
* Parses a "related with" from a json.
*
* @param jsonObject
* the json from which to parse the "related with"
* @return the parsed "related with" event type
* @throws JSONException
* if the "related with" could not be parsed
*/
private SWEKEventType parseRelatedWith(JSONObject jsonObject) throws JSONException {
return eventTypes.get(jsonObject.getString("related_with"));
}
/**
* Parses a list of "related on" from a json.
*
* @param jsonObject
* the json from which to parse the "related on" list
* @return the parsed "related on" list
* @throws JSONException
* if the "related on" list could not be parsed
*/
private List<SWEKRelatedOn> parseRelatedOnList(JSONObject jsonObject) throws JSONException {
List<SWEKRelatedOn> relatedOnList = new ArrayList<SWEKRelatedOn>();
JSONArray relatedOnArray = jsonObject.getJSONArray("related_on");
for (int i = 0; i < relatedOnArray.length(); i++) {
relatedOnList.add(parseRelatedOn(relatedOnArray.getJSONObject(i)));
}
return relatedOnList;
}
/**
* Parses a "related on" from a json.
*
* @param jsonObject
* the json from which to parse the "related on"
* @return the parsed "related on"
* @throws JSONException
* if the "related on" could not be parsed
*/
private SWEKRelatedOn parseRelatedOn(JSONObject jsonObject) throws JSONException {
SWEKRelatedOn relatedOn = new SWEKRelatedOn();
relatedOn.setParameterFrom(parseParameterFrom(jsonObject));
relatedOn.setParameterWith(parseParameterWith(jsonObject));
return relatedOn;
}
/**
* Parses a "parameter from" from a json.
*
* @param jsonObject
* the json from which to parse the "parameter from"
* @return the parsed "parameter from"
* @throws JSONException
* if the "parameter from" could not be parsed
*/
private SWEKParameter parseParameterFrom(JSONObject jsonObject) throws JSONException {
String parameterName = jsonObject.getString("parameter_from");
return new SWEKParameter("", parameterName, parameterName, null, false);
}
/**
* Parses a "parameter with" from a json.
*
* @param jsonObject
* the json from which to parse the "parameter with"
* @return the parsed "parameter with"
* @throws JSONException
* if the "parameter with" could not be parsed
*/
private SWEKParameter parseParameterWith(JSONObject jsonObject) throws JSONException {
String parameterName = jsonObject.getString("parameter_with");
return new SWEKParameter("", parameterName, parameterName, null, false);
}
} |
package com.giannoules.proxstor.connection;
import com.giannoules.proxstor.api.Device;
import com.giannoules.proxstor.api.Location;
import com.giannoules.proxstor.api.Sensor;
import com.giannoules.proxstor.api.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.moxy.xml.MoxyXmlFeature;
import org.glassfish.jersey.server.ResourceConfig;
public class ProxStorConnector {
WebTarget target;
Gson gson;
public ProxStorConnector(String path) {
final Map<String, Object> properties = new HashMap<>();
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final ResourceConfig config = new ResourceConfig()
.register(new MoxyXmlFeature(
properties,
classLoader,
true,
User.class));
target = ClientBuilder.newClient().target(path);
gson = new Gson();
}
public User addUser(User u) {
return target.path("/users")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(u, MediaType.APPLICATION_JSON_TYPE), User.class);
}
public User getUser(Integer userId) {
return target.path("users/" + userId)
.request(MediaType.APPLICATION_JSON_TYPE)
.get(User.class);
}
public boolean updateUser(User u) {
Response response = target.path("users/" + u.getUserId())
.request()
.put(Entity.entity(u, MediaType.APPLICATION_JSON_TYPE));
return response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL;
}
public boolean deleteUser(User u) {
Response response = target.path("users/" + u.getUserId())
.request()
.delete();
return response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL;
}
public Collection<User> getKnows(Integer userId, Integer strength) {
String json = target.path("users/" + userId + "/knows" + "/" + strength)
.request(MediaType.APPLICATION_JSON)
.get(String.class);
Type collectionType = new TypeToken<Collection<User>>() {
}.getType();
Collection<User> users = gson.fromJson(json, collectionType);
return users;
}
public void addUserKnows(User u, User v, int strength) {
String path = "users/" + u.getUserId() + "/knows/" + strength + "/" + v.getUserId();
target.path(path)
.request(MediaType.TEXT_PLAIN)
.post(null);
}
public void updateUserKnows(User u, User v, int strength) {
String path = "users/" + u.getUserId() + "/knows/" + strength + "/" + v.getUserId();
target.path(path)
.request(MediaType.TEXT_PLAIN)
.post(null);
}
public Collection<User> searchUsers(User search) {
String json = target.path("search/users")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(search, MediaType.APPLICATION_JSON_TYPE), String.class);
Type collectionType = new TypeToken<Collection<User>>() {
}.getType();
Collection<User> users = gson.fromJson(json, collectionType);
return users;
}
public Location putLocation(Location l) {
return target.path("/locations")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(l, MediaType.APPLICATION_JSON_TYPE), Location.class);
}
public Location getLocation(Integer locId) {
return target.path("locations/" + locId)
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Location.class);
}
public Device getDevice(Integer userId, Integer devId) {
return target.path("/users/" + userId + "/devices/" + devId)
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Device.class);
}
public Collection<Device> getDevices(Integer userId) {
String json = target.path("/users/" + userId + "/devices")
.request(MediaType.APPLICATION_JSON_TYPE)
.get(String.class);
Type collectionType = new TypeToken<Collection<Device>>() {
}.getType();
Collection<Device> devices = gson.fromJson(json, collectionType);
return devices;
}
public Device putDevice(Integer userId, Device dev) throws Exception {
try {
return target.path("/users/" + userId + "/devices/")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(dev, MediaType.APPLICATION_JSON_TYPE), Device.class);
} catch (javax.ws.rs.InternalServerErrorException ex) {
throw new Exception("Cannot add " + dev + " to " + userId);
}
}
public Sensor putSensor(Integer locId, Sensor s) throws Exception {
try {
return target.path("/locations/" + locId + "/sensors/")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(s, MediaType.APPLICATION_JSON_TYPE), Sensor.class);
} catch (javax.ws.rs.InternalServerErrorException ex) {
throw new Exception("Cannot add " + s + " to " + locId);
}
}
public Collection<Sensor> getSensors(Integer locId) {
String json = target.path("/locations/" + locId + "/sensors")
.request(MediaType.APPLICATION_JSON_TYPE)
.get(String.class);
Type collectionType = new TypeToken<Collection<Sensor>>() {
}.getType();
Collection<Sensor> sensors = gson.fromJson(json, collectionType);
return sensors;
}
public Collection<Location> getNearby(Integer locId, long distance) {
String json = target.path("/locations/" + locId + "/nearby/" + distance)
.request(MediaType.APPLICATION_JSON_TYPE)
.get(String.class);
Type collectionType = new TypeToken<Collection<Location>>() {
}.getType();
Collection<Location> locations = gson.fromJson(json, collectionType);
return locations;
}
public Collection<Location> getWithin(Integer locId) {
String json = target.path("/locations/" + locId + "/within")
.request(MediaType.APPLICATION_JSON_TYPE)
.get(String.class);
Type collectionType = new TypeToken<Collection<Location>>() {
}.getType();
Collection<Location> locations = gson.fromJson(json, collectionType);
return locations;
}
public Collection<Location> getWithinReverse(Integer locId) {
String json = target.path("/locations/" + locId + "/within/reverse")
.request(MediaType.APPLICATION_JSON_TYPE)
.get(String.class);
Type collectionType = new TypeToken<Collection<Location>>() {
}.getType();
Collection<Location> locations = gson.fromJson(json, collectionType);
return locations;
}
public void locationWithin(Location locA, Location locB) {
String path = "locations/" + locA.getLocId() + "/within/" + locB.getLocId();
target.path(path)
.request(MediaType.TEXT_PLAIN)
.post(null);
}
public boolean isWithin(Integer locId, Integer locId2) {
String path = "/locations/" + locId + "/within/" + locId2;
Response response = target.path(path).request().get();
return response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL;
}
public void locationNearby(Location locA, Location locB, int d) {
String path = "locations/" + locA.getLocId() + "/nearby/" + d + "/" + locB.getLocId();
target.path(path)
.request(MediaType.TEXT_PLAIN)
.post(null);
}
public boolean isNearby(Integer locId, Integer locId2, Integer distance) {
String path = "/locations/" + locId + "/nearby/" + distance + "/" + locId2;
Response response = target.path(path).request().get();
return response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL;
}
} |
package dk.statsbiblioteket.medieplatform.newspaper.statistics;
import java.io.File;
import java.io.FileInputStream;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Properties;
import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.TreeIterator;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class StatisticsComponentIT {
private final static String TEST_BATCH_ID = "400022028241";
private File genericPropertyFile;
private Properties properties;
private Logger log = LoggerFactory.getLogger(getClass());
@BeforeMethod(groups = "testDataTest")
public void loadGeneralConfiguration() throws Exception {
String pathToProperties = System.getProperty("integration.test.newspaper.properties");
properties = new Properties();
log.info("Loading general config from: " + pathToProperties);
genericPropertyFile = new File(pathToProperties);
properties.load(new FileInputStream(genericPropertyFile));
loadSpecificProperties(genericPropertyFile.getParentFile() + "/newspaper-statistics-config/config.properties");
}
/**
* Test that a reasonable batch can be run against the flagger component without generating any
* errors or flags when the batch and configuration agree on the setup..
* @throws Exception
*/
@Test(groups = "testDataTest")
public void testSmallBatch() throws Exception {
processBatch("small-test-batch");
}
/**
* Test that a the default batch with a configuration inconsistent with the metadata in the batch. This should
* generate a lot of flags.
* @throws Exception
*/
@Test(groups = "testDataTest")
public void testBadBatch() throws Exception {
processBatch("bad-bad-batch");
}
private void loadSpecificProperties(String path) throws Exception {
log.info("Loading specific config from: " + path);
File specificProperties = new File(path);
properties.load(new FileInputStream(specificProperties));
properties.setProperty(StatisticGenerator.STATISTICS_FILE_LOCATION_PROPERTY, "target/statistics/Integration");
}
private void processBatch(String batchFolder) throws Exception {
TreeIterator iterator = getIterator(batchFolder);
Batch batch = new Batch();
batch.setBatchID(TEST_BATCH_ID);
batch.setRoundTripNumber(1);
EventRunner runner = new EventRunner(iterator, Arrays.asList(new TreeEventHandler[]
{new StatisticGenerator(batch, properties)}), new ResultCollector(getClass().getSimpleName(), "1", 10));
runner.run( );
}
/**
* Creates and returns a iteration based on the test batch file structure found in the test/ressources folder.
*
* @return A iterator the the test batch
* @throws URISyntaxException
*/
public TreeIterator getIterator(String batchFolder) throws URISyntaxException {
File file = getBatchFolder(batchFolder);
return new TransformingIteratorForFileSystems(file, "\\.", ".*\\.jp2$", ".md5");
}
private File getBatchFolder(String batch) {
String pathToTestBatch = System.getProperty("integration.test.newspaper.testdata");
String pathToBatch = pathToTestBatch + '/'+ batch + "/B" + TEST_BATCH_ID + "-RT1";
log.info("Loading batch from: " + pathToBatch);
return new File(pathToBatch);
}
} |
package org.sagebionetworks.web.unitclient.presenter;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.repo.model.ACTAccessRequirement;
import org.sagebionetworks.repo.model.AccessRequirement;
import org.sagebionetworks.repo.model.RestrictableObjectDescriptor;
import org.sagebionetworks.repo.model.RestrictableObjectType;
import org.sagebionetworks.repo.model.TermsOfUseAccessRequirement;
import org.sagebionetworks.web.client.DataAccessClientAsync;
import org.sagebionetworks.web.client.PortalGinInjector;
import org.sagebionetworks.web.client.place.AccessRequirementsPlace;
import org.sagebionetworks.web.client.presenter.AccessRequirementsPresenter;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.view.DivView;
import org.sagebionetworks.web.client.view.PlaceView;
import org.sagebionetworks.web.client.widget.LoadMoreWidgetContainer;
import org.sagebionetworks.web.client.widget.accessrequirements.ACTAccessRequirementWidget;
import org.sagebionetworks.web.client.widget.accessrequirements.CreateAccessRequirementButton;
import org.sagebionetworks.web.client.widget.accessrequirements.TermsOfUseAccessRequirementWidget;
import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert;
import org.sagebionetworks.web.client.widget.table.v2.results.cell.EntityIdCellRendererImpl;
import org.sagebionetworks.web.client.widget.team.TeamBadge;
import org.sagebionetworks.web.test.helper.AsyncMockStubber;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
public class AccessRequirementsPresenterTest {
AccessRequirementsPresenter presenter;
@Mock
PlaceView mockView;
@Mock
AccessRequirementsPlace place;
@Mock
SynapseAlert mockSynAlert;
@Mock
PortalGinInjector mockGinInjector;
@Mock
LoadMoreWidgetContainer mockLoadMoreContainer;
@Mock
EntityIdCellRendererImpl mockEntityIdCellRenderer;
@Mock
TeamBadge mockTeamBadge;
@Mock
ACTAccessRequirement mockACTAccessRequirement;
@Mock
TermsOfUseAccessRequirement mockTermsOfUseAccessRequirement;
@Mock
AccessRequirementsPlace mockPlace;
List<AccessRequirement> accessRequirements;
@Captor
ArgumentCaptor<RestrictableObjectDescriptor> subjectCaptor;
@Mock
ACTAccessRequirementWidget mockACTAccessRequirementWidget;
@Mock
TermsOfUseAccessRequirementWidget mockTermsOfUseAccessRequirementWidget;
@Mock
CreateAccessRequirementButton mockCreateARButton;
@Mock
DataAccessClientAsync mockDataAccessClient;
@Mock
DivView mockEmptyResultsDiv;
public static final String ENTITY_ID = "syn239834";
public static final String TEAM_ID = "45678";
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
presenter = new AccessRequirementsPresenter(mockView, mockDataAccessClient, mockSynAlert, mockGinInjector, mockLoadMoreContainer, mockEntityIdCellRenderer, mockTeamBadge, mockCreateARButton, mockEmptyResultsDiv);
accessRequirements = new ArrayList<AccessRequirement>();
accessRequirements.add(mockACTAccessRequirement);
accessRequirements.add(mockTermsOfUseAccessRequirement);
AsyncMockStubber.callSuccessWith(accessRequirements).when(mockDataAccessClient).getAccessRequirements(any(RestrictableObjectDescriptor.class), anyLong(), anyLong(), any(AsyncCallback.class));
when(mockGinInjector.getACTAccessRequirementWidget()).thenReturn(mockACTAccessRequirementWidget);
when(mockGinInjector.getTermsOfUseAccessRequirementWidget()).thenReturn(mockTermsOfUseAccessRequirementWidget);
}
@Test
public void testConstruction() {
verify(mockView, atLeastOnce()).add(any(Widget.class));
verify(mockView, atLeastOnce()).addTitle(any(Widget.class));
verify(mockView, atLeastOnce()).addAboveBody(any(Widget.class));
verify(mockLoadMoreContainer).configure(any(Callback.class));
}
@Test
public void testLoadDataEntity() {
when(mockPlace.getParam(AccessRequirementsPlace.ENTITY_ID_PARAM)).thenReturn(ENTITY_ID);
presenter.setPlace(mockPlace);
verify(mockDataAccessClient).getAccessRequirements(subjectCaptor.capture(), eq(AccessRequirementsPresenter.LIMIT), eq(0L), any(AsyncCallback.class));
RestrictableObjectDescriptor subject = subjectCaptor.getValue();
assertEquals(ENTITY_ID, subject.getId());
assertEquals(RestrictableObjectType.ENTITY, subject.getType());
verify(mockEntityIdCellRenderer).setValue(ENTITY_ID);
verify(mockACTAccessRequirementWidget).setRequirement(mockACTAccessRequirement);
verify(mockTermsOfUseAccessRequirementWidget).setRequirement(mockTermsOfUseAccessRequirement);
verify(mockLoadMoreContainer).setIsMore(true);
verify(mockEmptyResultsDiv, never()).setVisible(true);
presenter.loadMore();
//load the next page
verify(mockDataAccessClient).getAccessRequirements(any(RestrictableObjectDescriptor.class), eq(AccessRequirementsPresenter.LIMIT), eq(AccessRequirementsPresenter.LIMIT), any(AsyncCallback.class));
verify(mockLoadMoreContainer).setIsMore(false);
}
@Test
public void testLoadDataEntityEmptyResults() {
accessRequirements.clear();
when(mockPlace.getParam(AccessRequirementsPlace.ENTITY_ID_PARAM)).thenReturn(ENTITY_ID);
presenter.setPlace(mockPlace);
verify(mockDataAccessClient).getAccessRequirements(subjectCaptor.capture(), eq(AccessRequirementsPresenter.LIMIT), eq(0L), any(AsyncCallback.class));
verify(mockLoadMoreContainer).setIsMore(false);
verify(mockEmptyResultsDiv).setVisible(true);
}
@Test
public void testLoadDataEntityFailure() {
Exception ex = new Exception("failed");
AsyncMockStubber.callFailureWith(ex).when(mockDataAccessClient).getAccessRequirements(any(RestrictableObjectDescriptor.class), anyLong(), anyLong(), any(AsyncCallback.class));
when(mockPlace.getParam(AccessRequirementsPlace.ENTITY_ID_PARAM)).thenReturn(ENTITY_ID);
presenter.setPlace(mockPlace);
verify(mockSynAlert).handleException(ex);
verify(mockLoadMoreContainer).setIsMore(false);
}
@Test
public void testLoadDataTeam() {
when(mockPlace.getParam(AccessRequirementsPlace.TEAM_ID_PARAM)).thenReturn(TEAM_ID);
presenter.setPlace(mockPlace);
verify(mockDataAccessClient).getAccessRequirements(subjectCaptor.capture(), eq(AccessRequirementsPresenter.LIMIT), eq(0L), any(AsyncCallback.class));
RestrictableObjectDescriptor subject = subjectCaptor.getValue();
assertEquals(TEAM_ID, subject.getId());
assertEquals(RestrictableObjectType.TEAM, subject.getType());
verify(mockTeamBadge).configure(TEAM_ID);
}
} |
package org.motechproject.nms.testing.it.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.mtraining.service.BookmarkService;
import org.motechproject.nms.api.web.BaseController;
import org.motechproject.nms.api.web.contract.BadRequest;
import org.motechproject.nms.api.web.contract.mobileAcademy.CourseResponse;
import org.motechproject.nms.api.web.contract.mobileAcademy.SaveBookmarkRequest;
import org.motechproject.nms.api.web.contract.mobileAcademy.SmsStatusRequest;
import org.motechproject.nms.api.web.contract.mobileAcademy.sms.RequestData;
import org.motechproject.nms.mobileacademy.domain.NmsCourse;
import org.motechproject.nms.mobileacademy.dto.MaCourse;
import org.motechproject.nms.mobileacademy.repository.NmsCourseDataService;
import org.motechproject.nms.mobileacademy.service.MobileAcademyService;
import org.motechproject.nms.testing.it.api.utils.RequestBuilder;
import org.motechproject.nms.testing.service.TestingService;
import org.motechproject.testing.osgi.BasePaxIT;
import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory;
import org.motechproject.testing.osgi.http.SimpleHttpClient;
import org.motechproject.testing.utils.TestContext;
import org.ops4j.pax.exam.ExamFactory;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerSuite;
/**
* Integration tests for mobile academy controller
*/
@RunWith(PaxExam.class)
@ExamReactorStrategy(PerSuite.class)
@ExamFactory(MotechNativeTestContainerFactory.class)
public class MobileAcademyControllerBundleIT extends BasePaxIT {
@Inject
MobileAcademyService mobileAcademyService;
@Inject
TestingService testingService;
@Inject
private BookmarkService bookmarkService;
@Inject
private NmsCourseDataService nmsCourseDataService;
private static final String COURSE_NAME = "MobileAcademyCourse";
public static final int MILLISECONDS_PER_SECOND = 1000;
@Before
public void setupTestData() {
testingService.clearDatabase();
nmsCourseDataService.deleteAll();
}
@Test
public void testBookmarkBadCallingNumber() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
HttpPost request = RequestBuilder.createPostRequest(endpoint, new SaveBookmarkRequest());
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
}
@Test
public void testBookmarkBadCallIdSmallest() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallId(BaseController.SMALLEST_15_DIGIT_NUMBER - 1);
HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
}
@Test
public void testBookmarkBadCallIdLargest() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallId(BaseController.LARGEST_15_DIGIT_NUMBER + 1);
HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
}
@Test
public void testBookmarkNullCallId() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmark = new SaveBookmarkRequest();
bookmark.setCallingNumber(BaseController.SMALLEST_10_DIGIT_NUMBER);
HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmark);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
}
@Test
public void testGetBookmarkEmpty() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore?callingNumber=1234567890&callId=123456789012345",
TestContext.getJettyPort());
HttpGet request = RequestBuilder.createGetRequest(endpoint);
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD);
assertNotNull(response);
assertEquals(200, response.getStatusLine().getStatusCode());
}
@Test
public void testSetValidBookmark() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmark = new SaveBookmarkRequest();
bookmark.setCallingNumber(BaseController.SMALLEST_10_DIGIT_NUMBER);
bookmark.setCallId(BaseController.SMALLEST_15_DIGIT_NUMBER);
HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmark);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
}
@Test
public void testTriggerNotification() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmark = new SaveBookmarkRequest();
bookmark.setCallingNumber(BaseController.SMALLEST_10_DIGIT_NUMBER);
bookmark.setCallId(BaseController.SMALLEST_15_DIGIT_NUMBER);
Map<String, Integer> scores = new HashMap<>();
for (int i = 1; i < 12; i++) {
scores.put(String.valueOf(i), 4);
}
bookmark.setScoresByChapter(scores);
bookmark.setBookmark("Chapter11_Quiz");
HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmark);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
long callingNumber = BaseController.SMALLEST_10_DIGIT_NUMBER;
endpoint = String.format("http://localhost:%d/api/mobileacademy/notify",
TestContext.getJettyPort());
request = RequestBuilder.createPostRequest(endpoint, callingNumber);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
// removed the negative testing since there's not reliable way to clean the data for it to fail
// after the first time. Debugged and verified that the negative works too and we have negative ITs
// at the service layer.
}
@Test
public void testSetValidExistingBookmark() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmark = new SaveBookmarkRequest();
bookmark.setCallingNumber(BaseController.SMALLEST_10_DIGIT_NUMBER);
bookmark.setCallId(BaseController.SMALLEST_15_DIGIT_NUMBER);
HttpPost request = RequestBuilder.createPostRequest(endpoint, bookmark);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
// Now, update the previous bookmark successfully
bookmark.setBookmark("Chapter3_Lesson2");
request = RequestBuilder.createPostRequest(endpoint, bookmark);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
}
@Test
public void testGetCourseValid() throws IOException, InterruptedException {
setupMaCourse();
String endpoint = String.format("http://localhost:%d/api/mobileacademy/course",
TestContext.getJettyPort());
HttpGet request = RequestBuilder.createGetRequest(endpoint);
HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse(request, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD);
assertEquals(200, httpResponse.getStatusLine().getStatusCode());
String body = IOUtils.toString(httpResponse.getEntity().getContent());
assertNotNull(body);
//TODO: figure out a way to automate the body comparison from the course json resource file
}
@Test
@Ignore
public void testSmsStatusInvalidFormat() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/smsdeliverystatus",
TestContext.getJettyPort());
SmsStatusRequest smsStatusRequest = new SmsStatusRequest();
smsStatusRequest.setRequestData(new RequestData());
HttpPost request = RequestBuilder.createPostRequest(endpoint, smsStatusRequest);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_BAD_REQUEST, RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
}
/**
* setup MA course structure from nmsCourse.json file.
*/
private JSONObject setupMaCourse() throws IOException {
MaCourse course = new MaCourse();
String jsonText = IOUtils.toString(new InputStreamReader(getClass().getClassLoader().
getResourceAsStream("nmsCourse.json")));
JSONObject jo = new JSONObject(jsonText);
course.setName(jo.get("name").toString());
course.setContent(jo.get("chapters").toString());
nmsCourseDataService.create(new NmsCourse(course.getName(), course.getContent()));
return jo;
}
/**
* To verify Get MA Course Version API is not returning course version when
* MA course structure doesn't exist.
*/
@Test
public void verifyFT400() throws IOException, InterruptedException {
String endpoint = String.format("http://localhost:%d/api/mobileacademy/courseVersion", TestContext
.getJettyPort());
HttpGet request = RequestBuilder.createGetRequest(endpoint);
HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse(request, RequestBuilder
.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, httpResponse.getStatusLine().getStatusCode());
}
/**
* To verify Get MA Course Version API is returning correct course version
* when MA course structure exist .
*/
@Test
public void verifyFT401() throws IOException, InterruptedException {
setupMaCourse();
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/courseVersion",
TestContext.getJettyPort());
HttpGet request = RequestBuilder.createGetRequest(endpoint);
HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
NmsCourse course = nmsCourseDataService.getCourseByName(COURSE_NAME);
String expectedJsonResponse = "{\"courseVersion\":"
+ course.getModificationDate().getMillis()
/ MILLISECONDS_PER_SECOND + "}";
assertEquals(HttpStatus.SC_OK, httpResponse.getStatusLine()
.getStatusCode());
assertEquals(expectedJsonResponse,
EntityUtils.toString(httpResponse.getEntity()));
}
/**
* To verify Get MA Course API is not returning course structure when MA
* course structure doesn't exist.
*/
@Test
public void verifyFT402() throws IOException, InterruptedException {
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/course",
TestContext.getJettyPort());
HttpGet request = RequestBuilder.createGetRequest(endpoint);
HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, httpResponse
.getStatusLine().getStatusCode());
}
/**
* To verify Get MA Course API is returning correct course structure when MA
* course structure exist.
*/
@Test
public void verifyFT403() throws IOException, InterruptedException {
JSONObject jo = setupMaCourse();
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/course",
TestContext.getJettyPort());
HttpGet request = RequestBuilder.createGetRequest(endpoint);
HttpResponse httpResponse = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
NmsCourse course = nmsCourseDataService.getCourseByName(COURSE_NAME);
CourseResponse courseResponseDTO = new CourseResponse();
courseResponseDTO.setName(jo.get("name").toString());
courseResponseDTO.setCourseVersion(course.getModificationDate()
.getMillis() / MILLISECONDS_PER_SECOND);
courseResponseDTO.setChapters(jo.get("chapters").toString());
ObjectMapper mapper = new ObjectMapper();
String expectedJsonResponse = mapper
.writeValueAsString(courseResponseDTO);
assertEquals(HttpStatus.SC_OK, httpResponse.getStatusLine()
.getStatusCode());
assertEquals(expectedJsonResponse,
EntityUtils.toString(httpResponse.getEntity()));
}
HttpGet createHttpGetBookmarkWithScore(String callingNo, String callId) {
StringBuilder sb = new StringBuilder();
sb.append(String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort()));
String seperator = "?";
if (callingNo != null) {
sb.append(seperator);
sb.append("callingNumber=");
sb.append(callingNo);
seperator = "";
}
if (callId != null) {
if (seperator.equals("")) {
sb.append("&");
} else {
sb.append(seperator);
}
sb.append("callId=");
sb.append(callId);
}
// System.out.println("Request url:" + sb.toString());
return RequestBuilder.createGetRequest(sb.toString());
}
private String createFailureResponseJson(String failureReason)
throws IOException {
BadRequest badRequest = new BadRequest(failureReason);
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(badRequest);
}
/**
* To verify Get Bookmark with Score API is returning correct bookmark and
* score details.
*/
@Ignore
@Test
public void verifyFT404() throws IOException, InterruptedException {
bookmarkService.deleteAllBookmarksForUser("1234567890");
// Blank bookmark should come as request response, As there is no any
// bookmark in the system for the user
HttpGet getRequest = createHttpGetBookmarkWithScore("1234567890",
"123456789012345");
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(
getRequest, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_OK, response.getStatusLine()
.getStatusCode());
String responseJson = EntityUtils.toString(response.getEntity());
assertNotNull(responseJson);
assertTrue("{\"bookmark\":null,\"scoresByChapter\":null}".equals(responseJson));
}
/**
* To verify Get Bookmark with Score API is returning correct bookmark and
* score details.
*/
@Ignore
@Test
public void verifyFT532() throws IOException, InterruptedException {
// create bookmark for the user
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallId(123456789012345l);
bookmarkRequest.setCallingNumber(1234567890l);
bookmarkRequest.setBookmark("Chapter01_Lesson01");
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
scoreMap.put("1", 2);
bookmarkRequest.setScoresByChapter(scoreMap);
HttpPost postRequest = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
SimpleHttpClient.httpRequestAndResponse(postRequest,
RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD);
// fetch bookmark for the same user
HttpGet getRequest = createHttpGetBookmarkWithScore("1234567890",
"123456789012345");
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(
getRequest, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_OK, response.getStatusLine()
.getStatusCode());
assertTrue("{\"bookmark\":\"Chapter01_Lesson01\",\"scoresByChapter\":{\"1\":2}}"
.equals(EntityUtils.toString(response
.getEntity())));
}
/**
* To verify that bookmark with score are saved correctly using Save
* bookmark with score API.
*/
@Test
public void verifyFT409() throws IOException, InterruptedException {
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallId(123456789012345l);
bookmarkRequest.setCallingNumber(1234567890l);
bookmarkRequest.setBookmark("Chapter01_Lesson01");
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
scoreMap.put("1", 2);
scoreMap.put("2", 0);
scoreMap.put("3", 3);
bookmarkRequest.setScoresByChapter(scoreMap);
HttpPost request = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK,
RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD));
}
/**
* To verify that bookmark with score are saved correctly using Save
* bookmark with score API when optional parameter are missing.
*/
@Test
public void verifyFT410() throws IOException, InterruptedException {
// Request without callingNumber and Bookmark
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallId(123456789012345l);
bookmarkRequest.setCallingNumber(1234567890l);
HttpPost request = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
assertTrue(SimpleHttpClient.execHttpRequest(request, HttpStatus.SC_OK,
RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD));
}
/**
* To verify Save bookmark with score API is rejected when mandatory
* parameter "callingNumber" is missing.
*/
@Test
@Ignore
public void verifyFT411() throws IOException, InterruptedException {
// callingNumber missing in the request body
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallId(123456789012345l);
bookmarkRequest.setBookmark("Chapter01_Lesson01");
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
scoreMap.put("1", 2);
scoreMap.put("2", 0);
scoreMap.put("3", 3);
bookmarkRequest.setScoresByChapter(scoreMap);
HttpPost request = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine()
.getStatusCode());
String expectedJsonResponse = createFailureResponseJson("<callingNumber: Not Present>");
assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response
.getEntity())));
}
/**
* To verify Save bookmark with score API is rejected when mandatory
* parameter "callId" is missing.
*/
@Test
@Ignore
public void verifyFT412() throws IOException, InterruptedException {
// callId missing in the request body
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallingNumber(1234567890l);
bookmarkRequest.setBookmark("Chapter01_Lesson01");
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
scoreMap.put("1", 2);
scoreMap.put("2", 0);
scoreMap.put("3", 3);
bookmarkRequest.setScoresByChapter(scoreMap);
HttpPost request = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine()
.getStatusCode());
String expectedJsonResponse = createFailureResponseJson("<callId: Not Present>");
assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response
.getEntity())));
}
/**
* To verify Save bookmark with score API is rejected when mandatory
* parameter "callId" is having invalid value.
*/
@Test
@Ignore
public void verifyFT413() throws IOException, InterruptedException {
// callId more than 15 digit
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallId(1234567890123456l);
bookmarkRequest.setCallingNumber(1234567890l);
bookmarkRequest.setBookmark("Chapter01_Lesson01");
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
scoreMap.put("1", 2);
scoreMap.put("2", 0);
scoreMap.put("3", 3);
bookmarkRequest.setScoresByChapter(scoreMap);
HttpPost request = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine()
.getStatusCode());
String expectedJsonResponse = createFailureResponseJson("<callId: Invalid>");
assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response
.getEntity())));
}
/**
* To verify Save bookmark with score API is rejected when mandatory
* parameter "callingNumber" is having invalid value.
*/
@Test
public void verifyFT414() throws IOException, InterruptedException {
// callingNumber less than 10 digit
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallingNumber(123456789l);
bookmarkRequest.setCallId(123456789012345l);
bookmarkRequest.setBookmark("Chapter01_Lesson01");
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
scoreMap.put("1", 2);
scoreMap.put("2", 0);
scoreMap.put("3", 3);
bookmarkRequest.setScoresByChapter(scoreMap);
HttpPost request = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine()
.getStatusCode());
String expectedJsonResponse = createFailureResponseJson("<callingNumber: Invalid>");
assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response
.getEntity())));
// callingNumber more than 10 digit
bookmarkRequest.setCallingNumber(12345678901l);
request = RequestBuilder.createPostRequest(endpoint, bookmarkRequest);
response = SimpleHttpClient.httpRequestAndResponse(request,
RequestBuilder.ADMIN_USERNAME, RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine()
.getStatusCode());
assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response
.getEntity())));
}
/**
* To verify Save bookmark with score API is rejected when parameter
* scoresByChapter is having value greater than 4.
*/
@Test
@Ignore
public void verifyFT415() throws IOException, InterruptedException {
// Invalid scores should not be accepted
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallingNumber(123456789l);
bookmarkRequest.setCallId(123456789012345l);
bookmarkRequest.setBookmark("Chapter01_Lesson01");
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
scoreMap.put("1", 2);
scoreMap.put("2", 6); // Invalid score greater than 4
scoreMap.put("3", 3);
bookmarkRequest.setScoresByChapter(scoreMap);
HttpPost request = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine()
.getStatusCode());
String expectedJsonResponse = createFailureResponseJson("<scoresByChapter: Invalid>");
assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response
.getEntity())));
}
/**
* To verify Save bookmark with score API is rejected when parameter
* "bookmark" is having invalid value.
*/
@Test
@Ignore
public void verifyFT416() throws IOException, InterruptedException {
// Requets with invalid bookmark value
String endpoint = String.format(
"http://localhost:%d/api/mobileacademy/bookmarkWithScore",
TestContext.getJettyPort());
SaveBookmarkRequest bookmarkRequest = new SaveBookmarkRequest();
bookmarkRequest.setCallingNumber(123456789l);
bookmarkRequest.setCallId(123456789012345l);
bookmarkRequest.setBookmark("Abc_Abc"); // Invalid bookmark
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
scoreMap.put("1", 2);
scoreMap.put("2", 3);
scoreMap.put("3", 3);
bookmarkRequest.setScoresByChapter(scoreMap);
HttpPost request = RequestBuilder.createPostRequest(endpoint,
bookmarkRequest);
HttpResponse response = SimpleHttpClient.httpRequestAndResponse(
request, RequestBuilder.ADMIN_USERNAME,
RequestBuilder.ADMIN_PASSWORD);
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine()
.getStatusCode());
String expectedJsonResponse = createFailureResponseJson("<bookmark: Invalid>");
assertTrue(expectedJsonResponse.equals(EntityUtils.toString(response
.getEntity())));
}
} |
package org.jboss.as.test.integration.json;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.integration.common.HttpRequest;
import org.jboss.as.test.shared.util.AssumeTestGroupUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
/**
* JSON-B 1.0 smoke test
*
* @author Rostislav Svoboda
*/
@RunWith(Arquillian.class)
@RunAsClient
public class JSONBTestCase {
@ArquillianResource
private URL url;
@Deployment(testable = false)
public static Archive<?> deploy() {
return ShrinkWrap.create(WebArchive.class, "jsonb10-test.war").addClasses(JSONBServlet.class);
}
@BeforeClass
public static void skipSecurityManager() {
AssumeTestGroupUtil.assumeSecurityManagerDisabled();
}
@Test
public void testJsonbServlet() throws Exception {
final String result = HttpRequest.get(url + "jsonb", 5, TimeUnit.SECONDS);
assertEquals("{\"name\":\"foo\",\"surname\":\"bar\"}", result);
}
} |
package com.oculusinfo.tile.rest.translation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;
import javax.net.ssl.HttpsURLConnection;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.oculusinfo.tile.rest.config.ConfigException;
import com.oculusinfo.tile.rest.config.ConfigPropertiesService;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A service that will translate given text to a target language based on the parameters
* passed in. Currently only supports the Google Translate Service.
*
*/
@Singleton
public class TileTranslationServiceImpl implements TileTranslationService {
private static final Logger LOGGER = LoggerFactory.getLogger(TileTranslationServiceImpl.class);
public static final String TRANSLATE_API_KEY = "translation.api.key";
public static final String TRANSLATE_API_ENDPOINT = "translation.api.endpoint";
private ConfigPropertiesService _service;
@Inject
public TileTranslationServiceImpl( ConfigPropertiesService service ) {
this._service = service;
}
/* (non-Javadoc)
* @see TileUtilsServiceImpl#getTranslationGoogle(JSONObject query)
*/
public JSONObject getTranslation( JSONObject query ) {
JSONObject result = null;
try {
// get the translation arguments from the query
String service = query.getString("service");
String text = query.getString("text");
String target = query.getString("target");
// as we integrate more translation service we can add a more sophisticated selection mechanism
if ( StringUtils.equalsIgnoreCase( service, "google" ) ) {
Properties properties = _service.getConfigProperties();
if ( properties != null ) {
String translationApiKey = properties.getProperty(TRANSLATE_API_KEY);
String translationApiEndpoint = properties.getProperty(TRANSLATE_API_ENDPOINT);
if ( translationApiKey != null && translationApiEndpoint != null ) {
result = translateGoogle( text, target, translationApiKey, translationApiEndpoint );
}
}
}
if ( result == null ){
JSONObject resultErr = new JSONObject();
resultErr.put("message", "Incorrect Translation Service Configuration");
result = new JSONObject();
result.put("error", resultErr);
}
} catch ( JSONException e ) {
LOGGER.error( "Incorrect Configuration for Translation API", e );
} catch ( ConfigException e ) {
LOGGER.error( "Error with internal configuration properties", e );
}
return result;
}
/*
* Translates the given text using the Google Translate API
*/
private JSONObject translateGoogle( String text, String target, String key, String endpoint ) {
JSONObject result = null;
try {
// assumes that the text has already been uri encoded
String urlStr = endpoint + "?key=" + key + "&q=" + text + "&target=" + target;
URL url = new URL( urlStr );
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
StringBuilder reply = new StringBuilder();
InputStream stream;
if ( connection.getResponseCode() == 200 ) //success
{
stream = connection.getInputStream();
} else {
stream = connection.getErrorStream();
}
BufferedReader reader = new BufferedReader( new InputStreamReader( stream ) );
String line;
while (( line = reader.readLine() ) != null ) {
reply.append(line);
}
result = new JSONObject( reply.toString() );
} catch ( IOException e ) {
LOGGER.error( "Error reading response from Google Translation Service", e );
} catch (JSONException e) {
LOGGER.error( "Error creating JSON Objects from Google Translation Service response", e );
}
return result;
}
} |
// AbstractSwingImageDisplay.java
package imagej.ui.swing.display;
import imagej.ImageJ;
import imagej.data.Dataset;
import imagej.data.Position;
import imagej.data.display.AbstractImageDisplay;
import imagej.data.display.DataView;
import imagej.data.overlay.Overlay;
import imagej.event.EventHandler;
import imagej.ext.display.DisplayService;
import imagej.ext.display.DisplayWindow;
import imagej.options.OptionsService;
import imagej.options.event.OptionsEvent;
import imagej.options.plugins.OptionsAppearance;
import imagej.ui.common.awt.AWTKeyEventDispatcher;
import imagej.ui.common.awt.AWTMouseEventDispatcher;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
/**
* A Swing image display plugin, which displays 2D planes in grayscale or
* composite color. Intended to be subclassed by a concrete implementation that
* provides a {@link DisplayWindow} in which the display should be housed.
*
* @author Curtis Rueden
* @author Grant Harris
* @author Barry DeZonia
*/
public abstract class AbstractSwingImageDisplay extends AbstractImageDisplay {
protected final DisplayWindow window;
private final JHotDrawImageCanvas imgCanvas;
private final SwingDisplayPanel imgPanel;
private ScaleConverter scaleConverter;
public AbstractSwingImageDisplay(final DisplayWindow window) {
super();
this.window = window;
imgCanvas = new JHotDrawImageCanvas(this);
imgCanvas.addEventDispatcher(
new AWTKeyEventDispatcher(this, eventService));
imgCanvas.addEventDispatcher(
new AWTMouseEventDispatcher(this, eventService, false));
setCanvas(imgCanvas);
imgPanel = new SwingDisplayPanel(this, window);
setPanel(imgPanel);
scaleConverter = getScaleConverter();
}
// -- ImageDisplay methods --
@Override
public void display(final Dataset dataset) {
// GBH: Regarding naming/id of the display...
// For now, we will use the original (first) dataset name
final String datasetName = dataset.getName();
createName(datasetName);
window.setTitle(this.getName());
add(new SwingDatasetView(this, dataset));
update();
initActiveAxis();
}
@Override
public void display(final Overlay overlay) {
add(new SwingOverlayView(this, overlay));
update();
initActiveAxis();
}
@Override
public JHotDrawImageCanvas getCanvas() {
return imgCanvas;
}
@Override
public String makeLabel() {
// CTR TODO - Fix window label to show beyond just the active view.
final DataView view = getActiveView();
final Dataset dataset = getDataset(view);
final int xIndex = dataset.getAxisIndex(Axes.X);
final int yIndex = dataset.getAxisIndex(Axes.Y);
final long[] dims = dataset.getDims();
final AxisType[] axes = dataset.getAxes();
final Position pos = view.getPlanePosition();
final StringBuilder sb = new StringBuilder();
for (int i = 0, p = -1; i < dims.length; i++) {
if (Axes.isXY(axes[i])) continue;
p++;
if (dims[i] == 1) continue;
sb.append(axes[i]);
sb.append(": ");
sb.append(pos.getLongPosition(p) + 1);
sb.append("/");
sb.append(dims[i]);
sb.append("; ");
}
sb.append(dims[xIndex]);
sb.append("x");
sb.append(dims[yIndex]);
sb.append("; ");
sb.append(dataset.getTypeLabelLong());
sb.append("; ");
sb.append(bytesOfInfo(dataset));
sb.append("; ");
final double zoomFactor = getCanvas().getZoomFactor();
if (zoomFactor != 1) {
sb.append("(");
sb.append(scaleConverter.getString(zoomFactor));
sb.append(")");
}
return sb.toString();
}
// -- Display methods --
@Override
public SwingDisplayPanel getPanel() {
return imgPanel;
}
@SuppressWarnings("unused")
@EventHandler
public void onEvent(final OptionsEvent e) {
scaleConverter = getScaleConverter();
}
// -- Helper methods --
/** Name this display with unique id. */
private void createName(final String baseName) {
final DisplayService displayService = ImageJ.get(DisplayService.class);
String theName = baseName;
int n = 0;
while (!displayService.isUniqueName(theName)) {
n++;
theName = baseName + "-" + n;
}
this.setName(theName);
}
private String bytesOfInfo(Dataset ds) {
double bitsPerPix = ds.getType().getBitsPerPixel();
long[] dims = ds.getDims();
long pixCount = 1;
for (long dimSize : dims)
pixCount *= dimSize;
double totBits = bitsPerPix * pixCount;
double totBytes = totBits / 8;
return labeledCount(totBytes);
}
private String labeledCount(double totBytes) {
String[] labels = {"KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
for (int i = 0; i < labels.length; i++) {
int pow = i + 2;
if (totBytes < Math.pow(1024.0, pow))
return String.format("%.1f%s",
(totBytes / Math.pow(1024.0,pow-1)), labels[i]);
}
return String.format("%.1f%s",
(totBytes / Math.pow(1024.0,labels.length)), labels[labels.length-1]);
}
@SuppressWarnings("synthetic-access")
private ScaleConverter getScaleConverter() {
final OptionsService service = ImageJ.get(OptionsService.class);
final OptionsAppearance options =
service.getOptions(OptionsAppearance.class);
if (options.isDisplayFractionalScales())
return new FractionalScaleConverter();
return new PercentScaleConverter();
}
// -- Helper classes --
private interface ScaleConverter {
String getString(double realScale);
}
private class PercentScaleConverter implements ScaleConverter {
@Override
public String getString(final double realScale) {
return String.format("%.2f%%", realScale * 100);
}
}
private class FractionalScaleConverter implements ScaleConverter {
@Override
public String getString(final double realScale) {
final FractionalScale scale = new FractionalScale(realScale);
// is fractional scale invalid?
if (scale.getDenom() == 0) {
if (realScale >= 1) return String.format("%.2fX", realScale);
// else scale < 1
return String.format("1/%.2fX", (1 / realScale));
}
// or do we have a whole number scale?
else if (scale.getDenom() == 1)
return String.format("%dX", scale.getNumer());
// else have valid fraction
return String.format("%d/%dX", scale.getNumer(), scale.getDenom());
}
}
private class FractionalScale {
private int numer, denom;
FractionalScale(final double realScale) {
numer = 0;
denom = 0;
if (realScale >= 1) {
final double floor = Math.floor(realScale);
if ((realScale - floor) < 0.0001) {
numer = (int) floor;
denom = 1;
}
}
else { // factor < 1
final double recip = 1.0 / realScale;
final double floor = Math.floor(recip);
if ((recip - floor) < 0.0001) {
numer = 1;
denom = (int) floor;
}
}
if (denom == 0)
lookForBestFraction(realScale);
}
int getNumer() {
return numer;
}
int getDenom() {
return denom;
}
// This method attempts to find a simple fraction that describes the
// specified scale. It searches a small set of numbers to minimize
// time spent. If it fails to find scale it leaves fraction unchanged.
private void lookForBestFraction(final double scale) {
final int quickRange = 32;
for (int n = 1; n <= quickRange; n++) {
for (int d = 1; d <= quickRange; d++) {
final double frac = 1.0 * n / d;
if (Math.abs(scale - frac) < 0.0001) {
numer = n;
denom = d;
return;
}
}
}
}
}
} |
package br.com.caelum.vraptor.core;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import br.com.caelum.vraptor.cache.VRaptorCache;
import br.com.caelum.vraptor.cache.VRaptorDefaultCache;
import br.com.caelum.vraptor.factory.Factories;
import br.com.caelum.vraptor.interceptor.AspectStyleInterceptorHandler;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.interceptor.InterceptorMethodParametersResolver;
import br.com.caelum.vraptor.interceptor.StepInvoker;
import br.com.caelum.vraptor.ioc.Container;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
public class DefaultInterceptorHandlerFactoryTest {
private Container container;
private DefaultInterceptorHandlerFactory factory;
private StepInvoker stepInvoker = Factories.createStepInvoker();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
InterceptorMethodParametersResolver parametersResolver = new InterceptorMethodParametersResolver(container);
VRaptorCache<Class<?>, InterceptorHandler> cachedHandlers = new VRaptorDefaultCache<>();
factory = new DefaultInterceptorHandlerFactory(container, stepInvoker, parametersResolver, cachedHandlers);
}
static interface RegularInterceptor extends Interceptor {}
@Test
public void handlerForRegularInterceptorsShouldBeDynamic() throws Exception {
assertThat(factory.handlerFor(RegularInterceptor.class), is(instanceOf(ToInstantiateInterceptorHandler.class)));
}
@Test
public void handlerForAspectStyleInterceptorsShouldBeDynamic() throws Exception {
assertThat(factory.handlerFor(AspectStyleInterceptor.class), is(instanceOf(AspectStyleInterceptorHandler.class)));
}
@Test
public void aspectStyleHandlersShouldBeCached() throws Exception {
InterceptorHandler handler = factory.handlerFor(AspectStyleInterceptor.class);
assertThat(factory.handlerFor(AspectStyleInterceptor.class), is(sameInstance(handler)));
}
} |
package info.bitrich.xchangestream.kraken;
import com.fasterxml.jackson.databind.JsonNode;
import info.bitrich.xchangestream.core.StreamingTradeService;
import info.bitrich.xchangestream.kraken.dto.KrakenOpenOrder;
import info.bitrich.xchangestream.kraken.dto.KrakenOwnTrade;
import info.bitrich.xchangestream.kraken.dto.enums.KrakenSubscriptionName;
import info.bitrich.xchangestream.service.netty.StreamingObjectMapperHelper;
import io.reactivex.Observable;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.dto.trade.StopOrder;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.kraken.KrakenAdapters;
import org.knowm.xchange.kraken.dto.account.KrakenWebsocketToken;
import org.knowm.xchange.kraken.dto.trade.KrakenOrderFlags;
import org.knowm.xchange.kraken.dto.trade.KrakenOrderStatus;
import org.knowm.xchange.kraken.dto.trade.KrakenType;
import org.knowm.xchange.kraken.service.KrakenAccountServiceRaw;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
public class KrakenStreamingTradeService implements StreamingTradeService {
private static final Logger LOG = LoggerFactory.getLogger(KrakenStreamingTradeService.class);
private KrakenAccountServiceRaw rawKrakenAcctService;
private KrakenStreamingService streamingService;
private KrakenWebsocketToken token;
private long tokenExpires = 0L;
KrakenStreamingTradeService(KrakenStreamingService streamingService, KrakenAccountServiceRaw rawKrakenAcctService) {
this.streamingService = streamingService;
this.rawKrakenAcctService = rawKrakenAcctService;
}
private String getChannelName(KrakenSubscriptionName subscriptionName) {
return subscriptionName.toString();
}
private static class KrakenDtoOrderHolder extends HashMap<String, KrakenOpenOrder> {}
private static class KrakenDtoUserTradeHolder extends HashMap<String, KrakenOwnTrade> {}
private KrakenWebsocketToken renewToken() throws IOException {
if (System.currentTimeMillis() >= tokenExpires) {
token = rawKrakenAcctService.getKrakenWebsocketToken();
tokenExpires = System.currentTimeMillis() + (token.getExpiresInSeconds() * 900L); // 900L instead of a 1000L for 90%
}
return token;
}
@Override
public Observable<Order> getOrderChanges(CurrencyPair currencyPair, Object... args) {
String channelName = getChannelName(KrakenSubscriptionName.openOrders);
try {
return streamingService.subscribeChannel(channelName, renewToken().getToken())
.filter(JsonNode::isArray)
.filter(Objects::nonNull)
.map(jsonNode -> jsonNode.get(0))
.map( jsonNode ->
StreamingObjectMapperHelper.getObjectMapper().treeToValue(jsonNode, KrakenDtoOrderHolder[].class))
.flatMapIterable(this::adaptKrakenOrders)
.filter(order -> currencyPair == null || order.getCurrencyPair() == null || order.getCurrencyPair().compareTo(currencyPair) == 0);
} catch (IOException e) {
return Observable.error(e);
}
}
private Iterable<Order> adaptKrakenOrders(KrakenDtoOrderHolder[] dtoList) {
List<Order> result = new ArrayList<>();
for(KrakenDtoOrderHolder dtoHolder : dtoList) {
for (Map.Entry<String, KrakenOpenOrder> dtoOrderEntry : dtoHolder.entrySet()) {
String orderId = dtoOrderEntry.getKey();
KrakenOpenOrder dto = dtoOrderEntry.getValue();
KrakenOpenOrder.KrakenDtoDescr descr = dto.descr;
CurrencyPair pair = descr == null ? null : new CurrencyPair(descr.pair);
Order.OrderType side = descr == null ? null : KrakenAdapters.adaptOrderType(KrakenType.fromString(descr.type));
String orderType = (descr == null || descr.ordertype == null) ? null : descr.ordertype;
Order.Builder builder;
if ("limit".equals(orderType))
builder = new LimitOrder.Builder(side,pair)
.limitPrice(descr.price);
else if ("stop".equals(orderType))
builder = new StopOrder.Builder(side,pair)
.limitPrice(descr.price)
.stopPrice(descr.price2);
else if ("market".equals(orderType))
builder = new MarketOrder.Builder(side, pair);
else // this is an order update (not the full order, it may only update one field)
builder = new MarketOrder.Builder(side, pair);
result.add(
builder
.id(orderId)
.originalAmount(dto.vol)
.cumulativeAmount(dto.vol_exec)
.orderStatus(dto.status == null ? null : KrakenAdapters.adaptOrderStatus(KrakenOrderStatus.fromString(dto.status)))
.timestamp(dto.opentm == null ? null : new Date((long) (dto.opentm * 1000L)))
.fee(dto.fee)
.flags(adaptFlags(dto.oflags))
.userReference(dto.refid)
.build()
);
}
}
return result;
}
/**
* Comma delimited list of order flags (optional). viqc = volume in quote currency (not available for leveraged orders),
* fcib = prefer fee in base currency, fciq = prefer fee in quote currency,
* nompp = no market price protection, post = post only order (available when ordertype = limit)
*/
private Set<Order.IOrderFlags> adaptFlags(String oflags) {
if (oflags == null)
return new HashSet<>(0);
String[] arr = oflags.split(",");
Set<Order.IOrderFlags> flags = new HashSet<>(arr.length);
for (String flag : arr) {
flags.add(KrakenOrderFlags.fromString(flag));
}
return flags;
}
@Override
public Observable<UserTrade> getUserTrades(CurrencyPair currencyPair, Object... args) {
try {
String channelName = getChannelName(KrakenSubscriptionName.ownTrades);
return streamingService.subscribeChannel(channelName, renewToken().getToken())
.filter(JsonNode::isArray)
.filter(Objects::nonNull)
.map(jsonNode ->
jsonNode.get(0))
.map(jsonNode ->
StreamingObjectMapperHelper.getObjectMapper().treeToValue(jsonNode, KrakenDtoUserTradeHolder[].class))
.flatMapIterable(this::adaptKrakenUserTrade)
.filter(userTrade -> currencyPair == null || userTrade.getCurrencyPair() == null || userTrade.getCurrencyPair().compareTo(currencyPair) == 0);
} catch (IOException e) {
return Observable.error(e);
}
}
private List<UserTrade> adaptKrakenUserTrade(KrakenDtoUserTradeHolder[] ownTrades) {
List<UserTrade> result = new ArrayList<>();
for(KrakenDtoUserTradeHolder holder : ownTrades) {
for (Map.Entry<String, KrakenOwnTrade> entry : holder.entrySet()) {
String orderId = entry.getKey();
KrakenOwnTrade dto = entry.getValue();
CurrencyPair currencyPair = new CurrencyPair(dto.pair);
result.add( new UserTrade.Builder()
.id(dto.postxid)
.orderId(orderId)
.currencyPair(currencyPair)
.timestamp(dto.time == null ? null : new Date((long)(dto.time*1000L)))
.type(KrakenAdapters.adaptOrderType(KrakenType.fromString(dto.type)))
.price(dto.price)
.feeAmount(dto.fee)
.feeCurrency(currencyPair.base)
.originalAmount(dto.vol)
.build());
}
}
return result;
}
} |
package org.voltdb.planner;
import java.io.File;
import java.io.PrintStream;
import java.util.List;
import org.hsqldb_voltpatches.HSQLInterface;
import org.hsqldb_voltpatches.HSQLInterface.HSQLParseException;
import org.hsqldb_voltpatches.VoltXMLElement;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Database;
import org.voltdb.compiler.DatabaseEstimates;
import org.voltdb.compiler.ScalarValueHints;
import org.voltdb.planner.microoptimizations.MicroOptimizationRunner;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.plannodes.PlanNodeList;
import org.voltdb.utils.BuildDirectoryUtils;
/**
* The query planner accepts catalog data, SQL statements from the catalog, then
* outputs the plan with the lowest cost according to the cost model.
*
*/
public class QueryPlanner {
PlanAssembler m_assembler;
HSQLInterface m_HSQL;
DatabaseEstimates m_estimates;
Cluster m_cluster;
Database m_db;
String m_recentErrorMsg;
boolean m_useGlobalIds;
boolean m_quietPlanner;
final boolean m_fullDebug;
/**
* Initialize planner with physical schema info and a reference to HSQLDB parser.
*
* @param catalogCluster Catalog info about the physical layout of the cluster.
* @param catalogDb Catalog info about schema, metadata and procedures.
* @param HSQL HSQLInterface pointer used for parsing SQL into XML.
* @param useGlobalIds
*/
public QueryPlanner(Cluster catalogCluster, Database catalogDb, boolean singlePartition,
HSQLInterface HSQL, DatabaseEstimates estimates,
boolean useGlobalIds, boolean suppressDebugOutput) {
assert(HSQL != null);
assert(catalogCluster != null);
assert(catalogDb != null);
m_HSQL = HSQL;
m_assembler = new PlanAssembler(catalogCluster, catalogDb, singlePartition);
m_db = catalogDb;
m_cluster = catalogCluster;
m_estimates = estimates;
m_useGlobalIds = useGlobalIds;
m_quietPlanner = suppressDebugOutput;
m_fullDebug = System.getProperties().contains("compilerdebug");
}
/**
* Get the best plan for the SQL statement given, assuming the given costModel.
*
* @param costModel The current cost model to evaluate plans with.
* @param sql SQL stmt text to be planned.
* @param sql Suggested join order to be used for the query
* @param stmtName The name of the sql statement to be planned.
* @param procName The name of the procedure containing the sql statement to be planned.
* @param singlePartition Is the stmt single-partition?
* @param paramHints
* @return The best plan found for the SQL statement or null if none can be found.
*/
public CompiledPlan compilePlan(
AbstractCostModel costModel,
String sql,
String joinOrder,
String stmtName,
String procName,
int maxTablesPerJoin,
ScalarValueHints[] paramHints) {
assert(costModel != null);
assert(sql != null);
assert(stmtName != null);
assert(procName != null);
// reset any error message
m_recentErrorMsg = null;
// set the usage of global ids in the plan assembler
AbstractPlanNode.setUseGlobalIds(m_useGlobalIds);
// use HSQLDB to get XML that describes the semantics of the statement
// this is much easier to parse than SQL and is checked against the catalog
VoltXMLElement xmlSQL = null;
try {
xmlSQL = m_HSQL.getXMLCompiledStatement(sql);
} catch (HSQLParseException e) {
// XXXLOG probably want a real log message here
m_recentErrorMsg = e.getMessage();
return null;
}
if (!m_quietPlanner && m_fullDebug) {
outputCompiledStatement(stmtName, procName, xmlSQL);
}
// Get a parsed statement from the xml
// The callers of compilePlan are ready to catch any exceptions thrown here.
AbstractParsedStmt parsedStmt = AbstractParsedStmt.parse(sql, xmlSQL, m_db, joinOrder);
if (parsedStmt == null)
{
m_recentErrorMsg = "Failed to parse SQL statement: " + sql;
return null;
}
if ((parsedStmt.tableList.size() > maxTablesPerJoin) && (parsedStmt.joinOrder == null)) {
m_recentErrorMsg = "Failed to parse SQL statement: " + sql + " because a join of > 5 tables was requested"
+ " without specifying a join order. See documentation for instructions on manually" +
" specifying a join order";
return null;
}
if (!m_quietPlanner && m_fullDebug) {
outputParsedStatement(stmtName, procName, parsedStmt);
}
// get ready to find the plan with minimal cost
CompiledPlan rawplan = null;
CompiledPlan bestPlan = null;
String bestFilename = null;
double minCost = Double.MAX_VALUE;
// index of the plan currently being "costed"
int planCounter = 0;
PlanStatistics stats = null;
{ // XXX: remove this brace and reformat the code when ready to open a whole new can of whitespace diffs.
// set up the plan assembler for this statement
m_assembler.setupForNewPlans(parsedStmt);
// loop over all possible plans
while (true) {
try {
rawplan = m_assembler.getNextPlan();
}
// on exception, set the error message and bail...
catch (PlanningErrorException e) {
m_recentErrorMsg = e.getMessage();
return null;
}
// stop this while loop when no more plans are generated
if (rawplan == null)
break;
// run the set of microptimizations, which may return many plans (or not)
List<CompiledPlan> optimizedPlans = MicroOptimizationRunner.applyAll(rawplan);
// iterate through the subset of plans
for (CompiledPlan plan : optimizedPlans) {
// add in the sql to the plan
plan.sql = sql;
// this plan is final, resolve all the column index references
plan.fragments.get(0).planGraph.resolveColumnIndexes();
// compute resource usage using the single stats collector
stats = new PlanStatistics();
AbstractPlanNode planGraph = plan.fragments.get(0).planGraph;
// compute statistics about a plan
boolean result = planGraph.computeEstimatesRecursively(stats, m_cluster, m_db, m_estimates, paramHints);
assert(result);
// compute the cost based on the resources using the current cost model
plan.cost = costModel.getPlanCost(stats);
// filename for debug output
String filename = String.valueOf(planCounter++);
// find the minimum cost plan
if (plan.cost < minCost) {
minCost = plan.cost;
// free the PlanColumns held by the previous best plan
bestPlan = plan;
bestFilename = filename;
}
if (!m_quietPlanner) {
if (m_fullDebug) {
outputPlanFullDebug(plan, planGraph, stmtName, procName, filename);
}
// get the explained plan for the node
plan.explainedPlan = planGraph.toExplainPlanString();
outputExplainedPlan(stmtName, procName, plan, filename);
}
}
}
} // XXX: remove this brace and reformat the code when ready to open a whole new can of whitespace diffs.
// make sure we got a winner
if (bestPlan == null) {
m_recentErrorMsg = "Unable to plan for statement. Error unknown.";
return null;
}
// reset all the plan node ids for a given plan
// this makes the ids deterministic
bestPlan.resetPlanNodeIds();
if (!m_quietPlanner)
{
finalizeOutput(stmtName, procName, bestFilename, stats);
}
// split up the plan everywhere we see send/recieve into multiple plan fragments
bestPlan = Fragmentizer.fragmentize(bestPlan, m_db);
// DTXN/EE can't handle plans that have more than 2 fragments yet.
if (bestPlan.fragments.size() > 2) {
m_recentErrorMsg = "Unable to plan for statement. Possibly " +
"joining partitioned tables in a multi-partition procedure " +
"using a column that is not the partitioning attribute " +
"or a non-equality operator. " +
"This is statement not supported at this time.";
return null;
}
return bestPlan;
}
/**
* @param stmtName
* @param procName
* @param plan
* @param filename
*/
private void outputExplainedPlan(String stmtName, String procName, CompiledPlan plan, String filename) {
PrintStream candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + ".txt");
candidatePlanOut.println(plan.explainedPlan);
candidatePlanOut.close();
}
/**
* @param stmtName
* @param procName
* @param parsedStmt
*/
private void outputParsedStatement(String stmtName, String procName, AbstractParsedStmt parsedStmt) {
// output a description of the parsed stmt
PrintStream parsedDebugOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-parsed", procName + "_" + stmtName + ".txt");
parsedDebugOut.println(parsedStmt.toString());
parsedDebugOut.close();
}
/**
* @param stmtName
* @param procName
* @param xmlSQL
*/
private void outputCompiledStatement(String stmtName, String procName, VoltXMLElement xmlSQL) {
// output the xml from hsql to disk for debugging
PrintStream xmlDebugOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-hsql-xml", procName + "_" + stmtName + ".xml");
xmlDebugOut.println(xmlSQL.toString());
xmlDebugOut.close();
}
/**
* @param plan
* @param planGraph
* @param stmtName
* @param procName
* @param filename
*/
private void outputPlanFullDebug(CompiledPlan plan, AbstractPlanNode planGraph, String stmtName, String procName, String filename) {
// GENERATE JSON DEBUGGING OUTPUT BEFORE WE CLEAN UP THE
// PlanColumns
// convert a tree into an execution list
PlanNodeList nodeList = new PlanNodeList(planGraph);
// get the json serialized version of the plan
String json = null;
try {
String crunchJson = nodeList.toJSONString();
//System.out.println(crunchJson);
//System.out.flush();
JSONObject jobj = new JSONObject(crunchJson);
json = jobj.toString(4);
} catch (JSONException e2) {
// Any plan that can't be serialized to JSON to
// write to debugging output is also going to fail
// to get written to the catalog, to sysprocs, etc.
// Just bail.
m_recentErrorMsg = "Plan for sql: '" + plan.sql +
"' can't be serialized to JSON";
// This case used to exit the planner
// -- a strange behavior for something that only gets called when full debug output is enabled.
// For now, just skip the output and go on to the next plan.
return;
}
// output a description of the parsed stmt
json = "PLAN:\n" + json;
json = "COST: " + String.valueOf(plan.cost) + "\n" + json;
assert (plan.sql != null);
json = "SQL: " + plan.sql + "\n" + json;
// write json to disk
PrintStream candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + "-json.txt");
candidatePlanOut.println(json);
candidatePlanOut.close();
// create a graph friendly version
candidatePlanOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-all-plans/" + procName + "_" + stmtName,
filename + ".dot");
candidatePlanOut.println(nodeList.toDOTString("name"));
candidatePlanOut.close();
}
/**
* @param filename
* @param filenameRenamed
*/
private void renameFile(String filename, String filenameRenamed) {
File file;
File fileRenamed;
file = new File(filename);
fileRenamed = new File(filenameRenamed);
file.renameTo(fileRenamed);
}
/**
* @param stmtName
* @param procName
* @param bestFilename
* @param stats
*/
private void finalizeOutput(String stmtName, String procName, String bestFilename, PlanStatistics stats) {
// find out where debugging is going
String prefix = BuildDirectoryUtils.getBuildDirectoryPath() +
"/" + BuildDirectoryUtils.rootPath + "statement-all-plans/" +
procName + "_" + stmtName + "/";
String winnerFilename, winnerFilenameRenamed;
// if outputting full stuff
if (m_fullDebug) {
// rename the winner json plan
winnerFilename = prefix + bestFilename + "-json.txt";
winnerFilenameRenamed = prefix + "WINNER-" + bestFilename + "-json.txt";
renameFile(winnerFilename, winnerFilenameRenamed);
// rename the winner dot plan
winnerFilename = prefix + bestFilename + ".dot";
winnerFilenameRenamed = prefix + "WINNER-" + bestFilename + ".dot";
renameFile(winnerFilename, winnerFilenameRenamed);
}
// rename the winner explain plan
winnerFilename = prefix + bestFilename + ".txt";
winnerFilenameRenamed = prefix + "WINNER-" + bestFilename + ".txt";
renameFile(winnerFilename, winnerFilenameRenamed);
if (m_fullDebug) {
// output the plan statistics to disk for debugging
PrintStream plansOut =
BuildDirectoryUtils.getDebugOutputPrintStream("statement-stats", procName + "_" + stmtName + ".txt");
plansOut.println(stats.toString());
plansOut.close();
}
}
public String getErrorMessage() {
return m_recentErrorMsg;
}
} |
package org.voltdb.sysprocs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.StringUtils;
import org.voltcore.logging.VoltLogger;
import org.voltdb.BackendTarget;
import org.voltdb.CatalogContext;
import org.voltdb.ClientInterface.ExplainMode;
import org.voltdb.ClientResponseImpl;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.VoltTypeException;
import org.voltdb.catalog.Database;
import org.voltdb.client.ClientResponse;
import org.voltdb.compiler.AdHocPlannedStatement;
import org.voltdb.compiler.AdHocPlannedStmtBatch;
import org.voltdb.compiler.PlannerTool;
import org.voltdb.parser.SQLLexer;
import org.voltdb.planner.StatementPartitioning;
import org.voltdb.utils.MiscUtils;
import org.voltdb.utils.VoltTrace;
import com.google_voltpatches.common.base.Charsets;
/**
* Base class for non-transactional sysprocs AdHoc, AdHocSPForTest and SwapTables
*
*
*/
public abstract class AdHocNTBase extends UpdateApplicationBase {
protected static final VoltLogger adhocLog = new VoltLogger("ADHOC");
public static final String AdHocErrorResponseMessage =
"The @AdHoc stored procedure when called with more than one parameter "
+ "must be passed a single parameterized SQL statement as its first parameter. "
+ "Pass each parameterized SQL statement to a separate callProcedure invocation.";
// When DEBUG_MODE is true this (valid) DDL string triggers an exception.
// Public visibility allows it to be used from a unit test.
public final static String DEBUG_EXCEPTION_DDL =
"create table DEBUG_MODE_ENG_7653_crash_me_now (die varchar(7654) not null)";
// Enable debug hooks when the "asynccompilerdebug" sys prop is set to "true" or "yes".
protected final static MiscUtils.BooleanSystemProperty DEBUG_MODE =
new MiscUtils.BooleanSystemProperty("asynccompilerdebug");
BackendTarget m_backendTargetType = VoltDB.instance().getBackendTargetType();
boolean m_isConfiguredForNonVoltDBBackend = (m_backendTargetType == BackendTarget.HSQLDB_BACKEND ||
m_backendTargetType == BackendTarget.POSTGRESQL_BACKEND ||
m_backendTargetType == BackendTarget.POSTGIS_BACKEND);
/**
* Log ad hoc batch info
* @param batch planned statement batch
*/
private void logBatch(final CatalogContext context,
final AdHocPlannedStmtBatch batch,
final Object[] userParams)
{
final int numStmts = batch.getPlannedStatementCount();
final int numParams = userParams == null ? 0 : userParams.length;
final String readOnly = batch.readOnly ? "yes" : "no";
final String singlePartition = batch.isSinglePartitionCompatible() ? "yes" : "no";
final String user = getUsername();
final String[] groupNames = context.authSystem.getGroupNamesForUser(user);
final String groupList = StringUtils.join(groupNames, ',');
//String[] stmtArray = batch.stmts.stream().map(s -> new String(s.sql, Charsets.UTF_8)).toArray(String[]::new);
adhocLog.debug(String.format(
"=== statements=%d parameters=%d read-only=%s single-partition=%s user=%s groups=[%s]",
numStmts, numParams, readOnly, singlePartition, user, groupList));
for (int i = 0; i < batch.getPlannedStatementCount(); i++) {
AdHocPlannedStatement stmt = batch.getPlannedStatement(i);
String sql = stmt.sql == null ? "SQL_UNKNOWN" : new String(stmt.sql, Charsets.UTF_8);
adhocLog.debug(String.format("Statement #%d: %s", i + 1, sql));
}
if (userParams != null) {
for (int i = 0; i < userParams.length; ++i) {
Object value = userParams[i];
final String valueString = (value != null ? value.toString() : "NULL");
adhocLog.debug(String.format("Parameter #%d: %s", i + 1, valueString));
}
}
}
public enum AdHocSQLMix {
EMPTY,
ALL_DML_OR_DQL,
ALL_DDL,
MIXED;
}
/**
* Split a set of one or more semi-colon delimited sql statements into a list.
* Store the list in validatedHomogeonousSQL.
* Return whether the SQL is empty, all dml or dql, all ddl, or an invalid mix (AdHocSQLMix)
*
* Used by the NT adhoc procs, but also by the experimental in-proc adhoc.
*/
public static AdHocSQLMix processAdHocSQLStmtTypes(String sql, List<String> validatedHomogeonousSQL) {
assert(validatedHomogeonousSQL != null);
assert(validatedHomogeonousSQL.size() == 0);
List<String> sqlStatements = SQLLexer.splitStatements(sql);
// do initial naive scan of statements for DDL, forbid mixed DDL and (DML|DQL)
Boolean hasDDL = null;
for (String stmt : sqlStatements) {
// Simulate an unhandled exception? (ENG-7653)
if (DEBUG_MODE.isTrue() && stmt.equals(DEBUG_EXCEPTION_DDL)) {
throw new IndexOutOfBoundsException(DEBUG_EXCEPTION_DDL);
}
if (SQLLexer.isComment(stmt) || stmt.trim().isEmpty()) {
continue;
}
String ddlToken = SQLLexer.extractDDLToken(stmt);
if (hasDDL == null) {
hasDDL = (ddlToken != null) ? true : false;
}
else if ((hasDDL && ddlToken == null) || (!hasDDL && ddlToken != null)) {
return AdHocSQLMix.MIXED;
}
validatedHomogeonousSQL.add(stmt);
}
if (validatedHomogeonousSQL.isEmpty()) {
return AdHocSQLMix.EMPTY;
}
assert(hasDDL != null);
return hasDDL ? AdHocSQLMix.ALL_DDL : AdHocSQLMix.ALL_DML_OR_DQL;
}
public static class AdHocPlanningException extends Exception {
private static final long serialVersionUID = 1L;
public AdHocPlanningException(String message) {
super(message);
}
public AdHocPlanningException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Compile a batch of one or more SQL statements into a set of plans.
* Parameters are valid iff there is exactly one DML/DQL statement.
*/
public static AdHocPlannedStatement compileAdHocSQL(CatalogContext context,
String sqlStatement,
boolean inferPartitioning,
Object userPartitionKey,
ExplainMode explainMode,
boolean isSwapTables,
Object[] userParamSet)
throws AdHocPlanningException
{
assert(context != null);
assert(sqlStatement != null);
final PlannerTool ptool = context.m_ptool;
// Take advantage of the planner optimization for inferring single partition work
// when the batch has one statement.
StatementPartitioning partitioning = null;
if (inferPartitioning) {
partitioning = StatementPartitioning.inferPartitioning();
}
else if (userPartitionKey == null) {
partitioning = StatementPartitioning.forceMP();
}
else {
partitioning = StatementPartitioning.forceSP();
}
try {
// I have no clue if this is threadsafe?
synchronized(PlannerTool.class) {
return ptool.planSql(sqlStatement,
partitioning,
explainMode != ExplainMode.NONE,
userParamSet,
isSwapTables);
}
}
catch (Exception e) {
throw new AdHocPlanningException("Unexpected Ad Hoc Planning Error: " + e);
}
catch (StackOverflowError error) {
// Overly long predicate expressions can cause a
// StackOverflowError in various code paths that may be
// covered by different StackOverflowError/Error/Throwable
// catch blocks. The factors that determine which code path
// and catch block get activated appears to be platform
// sensitive for reasons we do not entirely understand.
// To generate a deterministic error message regardless of
// these factors, purposely defer StackOverflowError handling
// for as long as possible, so that it can be handled
// consistently by a minimum number of high level callers like
// this one.
// This eliminates the need to synchronize error message text
// in multiple catch blocks, which becomes a problem when some
// catch blocks lead to re-wrapping of exceptions which tends
// to adorn the final error text in ways that are hard to track
// and replicate.
// Deferring StackOverflowError handling MAY mean ADDING
// explicit StackOverflowError catch blocks that re-throw
// the error to bypass more generic catch blocks
// for Error or Throwable on the same try block.
throw new AdHocPlanningException("Encountered stack overflow error. " +
"Try reducing the number of predicate expressions in the query.");
}
catch (AssertionError ae) {
throw new AdHocPlanningException("Assertion Error in Ad Hoc Planning: " + ae);
}
}
/**
* Plan and execute a batch of DML/DQL sql. Any DDL has been filtered out at this point.
*/
protected CompletableFuture<ClientResponse> runNonDDLAdHoc(CatalogContext context,
List<String> sqlStatements,
boolean inferPartitioning,
Object userPartitionKey,
ExplainMode explainMode,
boolean isSwapTables,
Object[] userParamSet)
{
// record the catalog version the query is planned against to
// catch races vs. updateApplicationCatalog.
if (context == null) {
context = VoltDB.instance().getCatalogContext();
}
List<String> errorMsgs = new ArrayList<>();
List<AdHocPlannedStatement> stmts = new ArrayList<>();
int partitionParamIndex = -1;
VoltType partitionParamType = null;
Object partitionParamValue = null;
assert(sqlStatements != null);
boolean inferSP = (sqlStatements.size() == 1) && inferPartitioning;
if (userParamSet != null && userParamSet.length > 0) {
if (sqlStatements.size() != 1) {
return makeQuickResponse(ClientResponse.GRACEFUL_FAILURE,
AdHocErrorResponseMessage);
}
}
for (final String sqlStatement : sqlStatements) {
try {
AdHocPlannedStatement result = compileAdHocSQL(context,
sqlStatement,
inferSP,
userPartitionKey,
explainMode,
isSwapTables,
userParamSet);
// The planning tool may have optimized for the single partition case
// and generated a partition parameter.
if (inferSP) {
partitionParamIndex = result.getPartitioningParameterIndex();
partitionParamType = result.getPartitioningParameterType();
partitionParamValue = result.getPartitioningParameterValue();
}
stmts.add(result);
}
catch (AdHocPlanningException e) {
errorMsgs.add(e.getMessage());
}
}
if (!errorMsgs.isEmpty()) {
String errorSummary = StringUtils.join(errorMsgs, "\n");
return makeQuickResponse(ClientResponse.GRACEFUL_FAILURE, errorSummary);
}
AdHocPlannedStmtBatch plannedStmtBatch =
new AdHocPlannedStmtBatch(userParamSet,
stmts,
partitionParamIndex,
partitionParamType,
partitionParamValue,
userPartitionKey == null ? null : new Object[] { userPartitionKey });
if (adhocLog.isDebugEnabled()) {
logBatch(context, plannedStmtBatch, userParamSet);
}
final VoltTrace.TraceEventBatch traceLog = VoltTrace.log(VoltTrace.Category.CI);
if (traceLog != null) {
traceLog.add(() -> VoltTrace.endAsync("planadhoc", getClientHandle()));
}
if (explainMode == ExplainMode.EXPLAIN_ADHOC) {
return processExplainPlannedStmtBatch(plannedStmtBatch);
}
else if (explainMode == ExplainMode.EXPLAIN_DEFAULT_PROC) {
return processExplainDefaultProc(plannedStmtBatch);
}
else {
try {
return createAdHocTransaction(plannedStmtBatch, isSwapTables);
}
catch (VoltTypeException vte) {
String msg = "Unable to execute adhoc sql statement(s): " + vte.getMessage();
return makeQuickResponse(ClientResponse.GRACEFUL_FAILURE, msg);
}
}
}
static CompletableFuture<ClientResponse> processExplainPlannedStmtBatch(AdHocPlannedStmtBatch planBatch) {
/**
* Take the response from the async ad hoc planning process and put the explain
* plan in a table with the right format.
*/
Database db = VoltDB.instance().getCatalogContext().database;
int size = planBatch.getPlannedStatementCount();
VoltTable[] vt = new VoltTable[ size ];
for (int i = 0; i < size; ++i) {
vt[i] = new VoltTable(new VoltTable.ColumnInfo("EXECUTION_PLAN", VoltType.STRING));
String str = planBatch.explainStatement(i, db);
vt[i].addRow(str);
}
ClientResponseImpl response =
new ClientResponseImpl(
ClientResponseImpl.SUCCESS,
ClientResponse.UNINITIALIZED_APP_STATUS_CODE,
null,
vt,
null);
CompletableFuture<ClientResponse> fut = new CompletableFuture<>();
fut.complete(response);
return fut;
}
/**
* Explain Proc for a default proc is routed through the regular Explain
* path using ad hoc planning and all. Take the result from that async
* process and format it like other explains for procedures.
*/
static CompletableFuture<ClientResponse> processExplainDefaultProc(AdHocPlannedStmtBatch planBatch) {
Database db = VoltDB.instance().getCatalogContext().database;
// there better be one statement if this is really sql
// from a default procedure
assert(planBatch.getPlannedStatementCount() == 1);
AdHocPlannedStatement ahps = planBatch.getPlannedStatement(0);
String sql = new String(ahps.sql, StandardCharsets.UTF_8);
String explain = planBatch.explainStatement(0, db);
VoltTable vt = new VoltTable(new VoltTable.ColumnInfo( "SQL_STATEMENT", VoltType.STRING),
new VoltTable.ColumnInfo( "EXECUTION_PLAN", VoltType.STRING));
vt.addRow(sql, explain);
ClientResponseImpl response =
new ClientResponseImpl(
ClientResponseImpl.SUCCESS,
ClientResponse.UNINITIALIZED_APP_STATUS_CODE,
null,
new VoltTable[] { vt },
null);
CompletableFuture<ClientResponse> fut = new CompletableFuture<>();
fut.complete(response);
return fut;
}
/**
* Take a set of adhoc plans and pass them off to the right transactional
* adhoc variant.
*/
private final CompletableFuture<ClientResponse> createAdHocTransaction(
final AdHocPlannedStmtBatch plannedStmtBatch,
final boolean isSwapTables)
throws VoltTypeException
{
ByteBuffer buf = null;
try {
buf = plannedStmtBatch.flattenPlanArrayToBuffer();
}
catch (IOException e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
assert(buf.hasArray());
// create the execution site task
String procedureName = null;
Object[] params = null;
// pick the sysproc based on the presence of partition info
// HSQL (or PostgreSQL) does not specifically implement AdHoc SP
// -- instead, use its always-SP implementation of AdHoc
boolean isSinglePartition = plannedStmtBatch.isSinglePartitionCompatible() || m_isConfiguredForNonVoltDBBackend;
if (isSwapTables) {
procedureName = "@SwapTablesCore";
params = new Object[] { buf.array() };
}
else if (isSinglePartition) {
if (plannedStmtBatch.isReadOnly()) {
procedureName = "@AdHoc_RO_SP";
}
else {
procedureName = "@AdHoc_RW_SP";
}
int type = VoltType.NULL.getValue();
// replicated table read is single-part without a partitioning param
// I copied this from below, but I'm not convinced that the above statement is correct
// or that the null behavior here either (a) ever actually happens or (b) has the
// desired intent.
Object partitionParam = plannedStmtBatch.partitionParam();
byte[] param = null;
if (partitionParam != null) {
type = VoltType.typeFromClass(partitionParam.getClass()).getValue();
param = VoltType.valueToBytes(partitionParam);
}
// Send the partitioning parameter and its type along so that the site can check if
// it's mis-partitioned. Type is needed to re-hashinate for command log re-init.
params = new Object[] { param, (byte)type, buf.array() };
}
else {
if (plannedStmtBatch.isReadOnly()) {
procedureName = "@AdHoc_RO_MP";
}
else {
procedureName = "@AdHoc_RW_MP";
}
params = new Object[] { buf.array() };
}
return callProcedure(procedureName, params);
}
} |
package crazypants.enderio.conduit.liquid;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatMessageComponent;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import buildcraft.api.transport.IPipeTile;
import buildcraft.api.transport.IPipeTile.PipeType;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import crazypants.enderio.ModObject;
import crazypants.enderio.conduit.AbstractConduit;
import crazypants.enderio.conduit.AbstractConduitNetwork;
import crazypants.enderio.conduit.ConduitPacketHandler;
import crazypants.enderio.conduit.ConduitUtil;
import crazypants.enderio.conduit.ConnectionMode;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.conduit.RaytraceResult;
import crazypants.enderio.conduit.geom.CollidableComponent;
import crazypants.enderio.machine.RedstoneControlMode;
import crazypants.enderio.machine.reservoir.TileReservoir;
import crazypants.render.IconUtil;
import crazypants.util.BlockCoord;
import crazypants.util.DyeColor;
public class LiquidConduit extends AbstractConduit implements ILiquidConduit {
static final Map<String, Icon> ICONS = new HashMap<String, Icon>();
@SideOnly(Side.CLIENT)
public static void initIcons() {
IconUtil.addIconProvider(new IconUtil.IIconProvider() {
@Override
public void registerIcons(IconRegister register) {
ICONS.put(ICON_KEY, register.registerIcon(ICON_KEY));
ICONS.put(ICON_EMPTY_KEY, register.registerIcon(ICON_EMPTY_KEY));
ICONS.put(ICON_CORE_KEY, register.registerIcon(ICON_CORE_KEY));
ICONS.put(ICON_EXTRACT_KEY, register.registerIcon(ICON_EXTRACT_KEY));
ICONS.put(ICON_EMPTY_EXTRACT_KEY, register.registerIcon(ICON_EMPTY_EXTRACT_KEY));
ICONS.put(ICON_EMPTY_INSERT_KEY, register.registerIcon(ICON_EMPTY_INSERT_KEY));
ICONS.put(ICON_INSERT_KEY, register.registerIcon(ICON_INSERT_KEY));
}
@Override
public int getTextureType() {
return 0;
}
});
}
private LiquidConduitNetwork network;
private ConduitTank tank = new ConduitTank(0);
private float lastSyncRatio = -99;
private int currentPushToken;
private long lastEmptyTick = 0;
private int numEmptyEvents = 0;
private boolean stateDirty = false;
private int maxDrainPerTick = 100;
private ForgeDirection startPushDir = ForgeDirection.DOWN;
private final Set<BlockCoord> filledFromThisTick = new HashSet<BlockCoord>();
protected final EnumMap<ForgeDirection, RedstoneControlMode> extractionModes = new EnumMap<ForgeDirection, RedstoneControlMode>(ForgeDirection.class);
protected final EnumMap<ForgeDirection, DyeColor> extractionColors = new EnumMap<ForgeDirection, DyeColor>(ForgeDirection.class);
private final Map<ForgeDirection, Integer> externalRedstoneSignals = new HashMap<ForgeDirection, Integer>();
private boolean redstoneStateDirty = true;
private long ticksSinceFailedExtract = 0;
@Override
public boolean onBlockActivated(EntityPlayer player, RaytraceResult res, List<RaytraceResult> all) {
if(player.getCurrentEquippedItem() == null) {
return false;
}
if(ConduitUtil.isToolEquipped(player)) {
if(!getBundle().getEntity().worldObj.isRemote) {
if(res != null && res.component != null) {
ForgeDirection connDir = res.component.dir;
ForgeDirection faceHit = ForgeDirection.getOrientation(res.movingObjectPosition.sideHit);
if(connDir == ForgeDirection.UNKNOWN || connDir == faceHit) {
BlockCoord loc = getLocation().getLocation(faceHit);
ILiquidConduit neighbour = ConduitUtil.getConduit(getBundle().getEntity().worldObj, loc.x, loc.y, loc.z, ILiquidConduit.class);
if(neighbour == null) {
return false;
}
if(neighbour.getFluidType() == null || getFluidType() == null) {
FluidStack type = getFluidType();
type = type != null ? type : neighbour.getFluidType();
neighbour.setFluidType(type);
setFluidType(type);
}
return ConduitUtil.joinConduits(this, faceHit);
} else if(containsExternalConnection(connDir)) {
// Toggle extraction mode
setConnectionMode(connDir, getNextConnectionMode(connDir));
} else if(containsConduitConnection(connDir)) {
FluidStack curFluidType = null;
if(network != null) {
curFluidType = network.getFluidType();
}
ConduitUtil.disconectConduits(this, connDir);
setFluidType(curFluidType);
}
}
}
return true;
} else if(player.getCurrentEquippedItem().itemID == Item.bucketEmpty.itemID) {
if(!getBundle().getEntity().worldObj.isRemote) {
long curTick = getBundle().getEntity().worldObj.getWorldTime();
if(curTick - lastEmptyTick < 20) {
numEmptyEvents++;
} else {
numEmptyEvents = 1;
}
lastEmptyTick = curTick;
if(numEmptyEvents < 2) {
tank.setAmount(0);
} else if(network != null) {
network.setFluidType(null);
numEmptyEvents = 0;
}
}
return true;
} else {
FluidStack fluid = FluidContainerRegistry.getFluidForFilledItem(player.getCurrentEquippedItem());
if(fluid != null) {
if(!getBundle().getEntity().worldObj.isRemote) {
if(network != null && (network.getFluidType() == null || network.getTotalVolume() < 500)) {
network.setFluidType(fluid);
ChatMessageComponent c = ChatMessageComponent.func_111066_d("Fluid type set to " + FluidRegistry.getFluidName(fluid));
player.sendChatToPlayer(c);
}
}
return true;
}
}
return false;
}
@Override
public void updateEntity(World world) {
super.updateEntity(world);
if(world.isRemote) {
return;
}
filledFromThisTick.clear();
updateStartPushDir();
doExtract();
if(stateDirty) {
getBundle().dirty();
stateDirty = false;
lastSyncRatio = tank.getFilledRatio();
} else if((lastSyncRatio != tank.getFilledRatio() && world.getTotalWorldTime() % 2 == 0)) {
//need to send a custom packet as we don't want want to trigger a full chunk update, just
//need to get the required values to the entity renderer
BlockCoord loc = getLocation();
Packet packet = ConduitPacketHandler.createFluidConduitLevelPacket(this);
PacketDispatcher.sendPacketToAllAround(loc.x, loc.y, loc.z, 64, world.provider.dimensionId, packet);
lastSyncRatio = tank.getFilledRatio();
}
}
@Override
public boolean onNeighborBlockChange(int blockId) {
redstoneStateDirty = true;
return super.onNeighborBlockChange(blockId);
}
@Override
public void setExtractionRedstoneMode(RedstoneControlMode mode, ForgeDirection dir) {
extractionModes.put(dir, mode);
redstoneStateDirty = true;
}
@Override
public RedstoneControlMode getExtractioRedstoneMode(ForgeDirection dir) {
RedstoneControlMode res = extractionModes.get(dir);
if(res == null) {
res = RedstoneControlMode.ON;
}
return res;
}
@Override
public void setExtractionSignalColor(ForgeDirection dir, DyeColor col) {
extractionColors.put(dir, col);
}
@Override
public DyeColor getExtractionSignalColor(ForgeDirection dir) {
DyeColor result = extractionColors.get(dir);
if(result == null) {
return DyeColor.RED;
}
return result;
}
private void doExtract() {
BlockCoord loc = getLocation();
if(!hasConnectionMode(ConnectionMode.INPUT)) {
return;
}
// assume failure, reset to 0 if we do extract
ticksSinceFailedExtract++;
if(ticksSinceFailedExtract > 9 && ticksSinceFailedExtract % 10 != 0) {
// after 10 ticks of failing, only check every 10 ticks
return;
}
Fluid f = tank.getFluid() == null ? null : tank.getFluid().getFluid();
int token = network == null ? -1 : network.getNextPushToken();
for (ForgeDirection dir : externalConnections) {
if(autoExtractForDir(dir)) {
IFluidHandler extTank = getTankContainer(getLocation().getLocation(dir));
if(extTank != null) {
FluidStack couldDrain = extTank.drain(dir.getOpposite(), maxDrainPerTick, false);
if(couldDrain != null && couldDrain.amount > 0 && canFill(dir, couldDrain.getFluid())) {
int used = pushLiquid(dir, couldDrain, true, network == null ? -1 : network.getNextPushToken());
extTank.drain(dir.getOpposite(), used, true);
if(used > 0 && network != null && network.getFluidType() == null) {
network.setFluidType(couldDrain);
}
if(used > 0) {
ticksSinceFailedExtract = 0;
}
}
}
}
}
}
private boolean autoExtractForDir(ForgeDirection dir) {
if(!isExtractingFromDir(dir)) {
return false;
}
RedstoneControlMode mode = getExtractioRedstoneMode(dir);
if(mode == RedstoneControlMode.IGNORE) {
return true;
}
if(mode == RedstoneControlMode.NEVER) {
return false;
}
if(redstoneStateDirty) {
externalRedstoneSignals.clear();
redstoneStateDirty = false;
}
DyeColor col = getExtractionSignalColor(dir);
int signal = ConduitUtil.getInternalSignalForColor(getBundle(), col);
if(mode.isConditionMet(mode, signal)) {
return true;
}
int externalSignal = 0;
if(col == DyeColor.RED) {
Integer val = externalRedstoneSignals.get(dir);
if(val == null) {
TileEntity te = getBundle().getEntity();
externalSignal = te.worldObj.getStrongestIndirectPower(te.xCoord, te.yCoord, te.zCoord);
externalRedstoneSignals.put(dir, externalSignal);
} else {
externalSignal = val;
}
}
return mode.isConditionMet(mode, externalSignal);
}
@Override
public boolean canOutputToDir(ForgeDirection dir) {
if(isExtractingFromDir(dir) || getConectionMode(dir) == ConnectionMode.DISABLED) {
return false;
}
if(conduitConnections.contains(dir)) {
return true;
}
if(!externalConnections.contains(dir)) {
return false;
}
IFluidHandler ext = getExternalHandler(dir);
if(ext instanceof TileReservoir) { // dont push to an auto ejecting
// resevoir or we loop
TileReservoir tr = (TileReservoir) ext;
return !tr.isMultiblock() || !tr.isAutoEject();
}
return true;
}
@Override
public boolean isExtractingFromDir(ForgeDirection dir) {
return getConectionMode(dir) == ConnectionMode.INPUT;
}
@Override
public void setFluidType(FluidStack liquidType) {
if(tank.getFluid() != null && tank.getFluid().isFluidEqual(liquidType)) {
return;
}
if(liquidType != null) {
liquidType = liquidType.copy();
}
tank.setLiquid(liquidType);
stateDirty = true;
}
@Override
public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
if(network == null || resource == null) {
return 0;
}
if(!canFill(from, resource.getFluid())) {
return 0;
}
// Note: This is just a guard against mekansims pipes that will continuously
// call
// fill on us if we push liquid to them.
if(filledFromThisTick.contains(getLocation().getLocation(from))) {
return 0;
}
if(network.lockNetworkForFill()) {
if(doFill) {
filledFromThisTick.add(getLocation().getLocation(from));
}
try {
int res = fill(from, resource, doFill, true, network == null ? -1 : network.getNextPushToken());
if(doFill && externalConnections.contains(from) && network != null) {
network.addedFromExternal(res);
}
return res;
} finally {
network.unlockNetworkFromFill();
}
} else {
return 0;
}
}
@Override
public int fill(ForgeDirection from, FluidStack resource, boolean doFill, boolean doPush, int pushToken) {
if(resource == null || resource.amount <= 0) {
return 0;
}
if(!canFill(from, resource.getFluid())) {
return 0;
}
if(network == null) {
return 0;
}
if(network.canAcceptLiquid(resource)) {
network.setFluidType(resource);
} else {
return 0;
}
int recieveAmount = resource.amount;
if(doPush) {
return pushLiquid(from, resource, doFill, pushToken);
} else {
return tank.fill(resource, doFill);
}
}
private void updateStartPushDir() {
ForgeDirection newVal = getNextDir(startPushDir);
boolean foundNewStart = false;
while (newVal != startPushDir && !foundNewStart) {
foundNewStart = getConduitConnections().contains(newVal) || getExternalConnections().contains(newVal);
newVal = getNextDir(newVal);
}
startPushDir = newVal;
}
private ForgeDirection getNextDir(ForgeDirection dir) {
if(dir.ordinal() >= ForgeDirection.UNKNOWN.ordinal() - 1) {
return ForgeDirection.VALID_DIRECTIONS[0];
}
return ForgeDirection.VALID_DIRECTIONS[dir.ordinal() + 1];
}
private int pushLiquid(ForgeDirection from, FluidStack pushStack, boolean doPush, int token) {
if(token == currentPushToken || pushStack == null || pushStack.amount <= 0 || network == null) {
return 0;
}
currentPushToken = token;
int pushed = 0;
int total = pushStack.amount;
ForgeDirection dir = startPushDir;
FluidStack toPush = pushStack.copy();
int filledLocal = tank.fill(toPush, doPush);
toPush.amount -= filledLocal;
pushed += filledLocal;
do {
if(dir != from && canOutputToDir(dir)) {
if(getConduitConnections().contains(dir)) {
ILiquidConduit conduitCon = getFluidConduit(dir);
if(conduitCon != null) {
int toCon = ((LiquidConduit) conduitCon).pushLiquid(dir.getOpposite(), toPush, doPush, token);
toPush.amount -= toCon;
pushed += toCon;
}
} else if(getExternalConnections().contains(dir)) {
IFluidHandler con = getTankContainer(getLocation().getLocation(dir));
if(con != null) {
int toExt = con.fill(dir.getOpposite(), toPush, doPush);
toPush.amount -= toExt;
pushed += toExt;
if(doPush) {
network.outputedToExternal(toExt);
}
}
}
}
dir = getNextDir(dir);
} while (dir != startPushDir && pushed < total);
return pushed;
}
private ILiquidConduit getFluidConduit(ForgeDirection dir) {
TileEntity ent = getBundle().getEntity();
return ConduitUtil.getConduit(ent.worldObj, ent, dir, ILiquidConduit.class);
}
@Override
public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
if(getConectionMode(from) == ConnectionMode.INPUT || getConectionMode(from) == ConnectionMode.DISABLED) {
return null;
}
return tank.drain(maxDrain, doDrain);
}
@Override
public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
if(resource != null && !resource.isFluidEqual(tank.getFluid())) {
return null;
}
return drain(from, resource.amount, doDrain);
}
@Override
public boolean canFill(ForgeDirection from, Fluid fluid) {
if(getConectionMode(from) == ConnectionMode.OUTPUT || getConectionMode(from) == ConnectionMode.DISABLED) {
return false;
}
if(tank.getFluid() == null) {
return true;
}
if(fluid != null && fluid.getID() == tank.getFluid().fluidID) {
return true;
}
return false;
}
@Override
public boolean canDrain(ForgeDirection from, Fluid fluid) {
if(getConectionMode(from) == ConnectionMode.INPUT || getConectionMode(from) == ConnectionMode.DISABLED
|| tank.getFluid() == null || fluid == null) {
return false;
}
return tank.getFluid().getFluid().getID() == fluid.getID();
}
@Override
public FluidTankInfo[] getTankInfo(ForgeDirection from) {
return new FluidTankInfo[] { tank.getInfo() };
}
@Override
public void writeToNBT(NBTTagCompound nbtRoot) {
super.writeToNBT(nbtRoot);
if(tank.containsValidLiquid()) {
nbtRoot.setTag("tank", tank.getFluid().writeToNBT(new NBTTagCompound()));
} else {
FluidStack ft = getFluidType();
if(ConduitUtil.isFluidValid(ft)) {
ft = getFluidType().copy();
ft.amount = 0;
nbtRoot.setTag("tank", ft.writeToNBT(new NBTTagCompound()));
}
}
for (Entry<ForgeDirection, RedstoneControlMode> entry : extractionModes.entrySet()) {
if(entry.getValue() != null) {
short ord = (short) entry.getValue().ordinal();
nbtRoot.setShort("extRM." + entry.getKey().name(), ord);
}
}
for (Entry<ForgeDirection, DyeColor> entry : extractionColors.entrySet()) {
if(entry.getValue() != null) {
short ord = (short) entry.getValue().ordinal();
nbtRoot.setShort("extSC." + entry.getKey().name(), ord);
}
}
}
@Override
public void readFromNBT(NBTTagCompound nbtRoot) {
super.readFromNBT(nbtRoot);
updateTanksCapacity();
FluidStack liquid = FluidStack.loadFluidStackFromNBT(nbtRoot.getCompoundTag("tank"));
tank.setLiquid(liquid);
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) {
String key = "extRM." + dir.name();
if(nbtRoot.hasKey(key)) {
short ord = nbtRoot.getShort(key);
if(ord >= 0 && ord < RedstoneControlMode.values().length) {
extractionModes.put(dir, RedstoneControlMode.values()[ord]);
}
}
key = "extSC." + dir.name();
if(nbtRoot.hasKey(key)) {
short ord = nbtRoot.getShort(key);
if(ord >= 0 && ord < DyeColor.values().length) {
extractionColors.put(dir, DyeColor.values()[ord]);
}
}
}
}
@Override
protected void connectionsChanged() {
super.connectionsChanged();
updateTanksCapacity();
}
@Override
public ConduitTank getTank() {
return tank;
}
@Override
public Class<? extends IConduit> getBaseConduitType() {
return ILiquidConduit.class;
}
@Override
public ItemStack createItem() {
return new ItemStack(ModObject.itemLiquidConduit.actualId, 1, 0);
}
@Override
public AbstractConduitNetwork<?> getNetwork() {
return network;
}
@Override
public boolean setNetwork(AbstractConduitNetwork<?> network) {
if(network == null) {
this.network = null;
return true;
}
LiquidConduitNetwork n = (LiquidConduitNetwork) network;
if(tank.getFluid() == null) {
tank.setLiquid(n.getFluidType() == null ? null : n.getFluidType().copy());
} else if(n.getFluidType() == null) {
n.setFluidType(tank.getFluid());
} else if(!tank.getFluid().isFluidEqual(n.getFluidType())) {
return false;
}
this.network = (LiquidConduitNetwork) network;
return true;
}
@Override
public boolean canConnectToExternal(ForgeDirection direction, boolean ignoreDisabled) {
return getExternalHandler(direction) != null;
}
@Override
public IFluidHandler getExternalHandler(ForgeDirection direction) {
IFluidHandler con = getTankContainer(getLocation().getLocation(direction));
return (con != null && !(con instanceof IConduitBundle)) ? con : null;
}
@Override
public boolean canConnectToConduit(ForgeDirection direction, IConduit con) {
if(!super.canConnectToConduit(direction, con)) {
return false;
}
if(!(con instanceof ILiquidConduit)) {
return false;
}
if(getFluidType() != null && ((ILiquidConduit) con).getFluidType() == null) {
return false;
}
return LiquidConduitNetwork.areFluidsCompatable(getFluidType(), ((ILiquidConduit) con).getFluidType());
}
@Override
public FluidStack getFluidType() {
FluidStack result = null;
if(network != null) {
result = network.getFluidType();
}
if(result == null) {
result = tank.getFluid();
}
return result;
}
@Override
public Icon getTextureForState(CollidableComponent component) {
if(component.dir == ForgeDirection.UNKNOWN) {
return ICONS.get(ICON_CORE_KEY);
}
if(isExtractingFromDir(component.dir)) {
return ICONS.get(getFluidType() == null ? ICON_EMPTY_EXTRACT_KEY : ICON_EXTRACT_KEY);
}
if(getConectionMode(component.dir) == ConnectionMode.OUTPUT) {
return ICONS.get(getFluidType() == null ? ICON_EMPTY_INSERT_KEY : ICON_INSERT_KEY);
}
if(getFluidType() == null) {
return ICONS.get(ICON_EMPTY_KEY);
}
return ICONS.get(ICON_KEY);
}
@Override
public Icon getTransmitionTextureForState(CollidableComponent component) {
if(tank.getFluid() != null && tank.getFluid().getFluid() != null) {
return tank.getFluid().getFluid().getStillIcon();
}
return null;
}
@Override
public float getTransmitionGeometryScale() {
return tank.getFilledRatio();
}
private IFluidHandler getTankContainer(BlockCoord bc) {
return getTankContainer(bc.x, bc.y, bc.z);
}
private IFluidHandler getTankContainer(int x, int y, int z) {
TileEntity te = getBundle().getEntity().worldObj.getBlockTileEntity(x, y, z);
if(te instanceof IFluidHandler) {
if(te instanceof IPipeTile) {
if(((IPipeTile) te).getPipeType() != PipeType.FLUID) {
return null;
}
}
return (IFluidHandler) te;
}
return null;
}
private void updateTanksCapacity() {
int totalConnections = getConduitConnections().size() + getExternalConnections().size();
tank.setCapacity(totalConnections * VOLUME_PER_CONNECTION);
}
} |
package vg.civcraft.mc.bettershards.listeners;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.Collection;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.material.Bed;
import org.bukkit.util.Vector;
import vg.civcraft.mc.bettershards.BetterShardsAPI;
import vg.civcraft.mc.bettershards.BetterShardsPlugin;
import vg.civcraft.mc.bettershards.database.DatabaseManager;
import vg.civcraft.mc.bettershards.events.PlayerArrivedChangeServerEvent;
import vg.civcraft.mc.bettershards.events.PlayerChangeServerReason;
import vg.civcraft.mc.bettershards.external.MercuryManager;
import vg.civcraft.mc.bettershards.manager.PortalsManager;
import vg.civcraft.mc.bettershards.manager.RandomSpawnManager;
import vg.civcraft.mc.bettershards.misc.BedLocation;
import vg.civcraft.mc.bettershards.misc.CustomWorldNBTStorage;
import vg.civcraft.mc.bettershards.misc.Grid;
import vg.civcraft.mc.bettershards.misc.InventoryIdentifier;
import vg.civcraft.mc.bettershards.misc.PlayerStillDeadException;
import vg.civcraft.mc.bettershards.misc.TeleportInfo;
import vg.civcraft.mc.bettershards.portal.Portal;
import vg.civcraft.mc.civmodcore.Config;
import vg.civcraft.mc.civmodcore.annotations.CivConfig;
import vg.civcraft.mc.civmodcore.annotations.CivConfigType;
import vg.civcraft.mc.mercury.MercuryAPI;
public class BetterShardsListener implements Listener{
private BetterShardsPlugin plugin;
private DatabaseManager db;
private Config config;
private PortalsManager pm;
private CustomWorldNBTStorage st;
private RandomSpawnManager rs;
public BetterShardsListener(){
plugin = BetterShardsPlugin.getInstance();
db = BetterShardsPlugin.getDatabaseManager();
pm = BetterShardsPlugin.getPortalManager();
config = plugin.GetConfig();
rs = BetterShardsPlugin.getRandomSpawn();
Bukkit.getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
st = CustomWorldNBTStorage.getWorldNBTStorage();
}
});
}
@EventHandler(priority = EventPriority.MONITOR)
public void playerPreLoginCacheInv(AsyncPlayerPreLoginEvent event) {
UUID uuid = event.getUniqueId();
if (uuid != null) {
plugin.getLogger().log(Level.FINER, "Preparing to pre-load player data: {0}", uuid);
} else {
return;
}
if (st == null){ // Small race condition if someone logs on as soon as the server starts.
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "Please try to log in again in a moment, server is not ready to accept log-ins.");
plugin.getLogger().log(Level.INFO, "Player {0} logged on before async process was ready, skipping.", uuid);
return;
}
Future<ByteArrayInputStream> soondata = db.loadPlayerDataAsync(uuid, st.getInvIdentifier(uuid)); // wedon't use the data, but know that it caches behind the scenes.
try {
ByteArrayInputStream after = soondata.get(); // I want to _INTENTIONALLY_ delay accepting the user's login until I know for sure I've got the data loaded asynchronously.
if (after == null) {
plugin.getLogger().log(Level.INFO, "Pre-load for player data {0} came back empty. New player? Error?", uuid);
} else {
plugin.getLogger().log(Level.FINER, "Pre-load for player data {0} complete.", uuid);
}
} catch (InterruptedException | ExecutionException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to pre-load player data: {0}", uuid);
e.printStackTrace();
}
// We do this so it fetches the cache, then when called for real
// by our CustomWorldNBTStorage class it doesn't have to wait and server won't lock.
}
@CivConfig(name = "lobby", def = "false", type = CivConfigType.Bool)
@EventHandler(priority = EventPriority.HIGHEST)
public void playerJoinEvent(PlayerJoinEvent event){
// Defer to next tick so join is fully complete before we unlock
final UUID player = event.getPlayer().getUniqueId();
Bukkit.getScheduler().runTask(plugin, new Runnable() {
public void run() {
//tell other server to remove player from transit
MercuryManager.notifyOfArrival(player);
BetterShardsPlugin.getTransitManager().notifySuccessfullArrival(player);
}
});
if (config.get("lobby").getBool()) {
World w = BetterShardsPlugin.getRandomSpawn().getWorld();
event.getPlayer().teleport(w.getSpawnLocation());
return;
}
if (!event.getPlayer().hasPlayedBefore()) {
rs.handleFirstJoin(event.getPlayer());
return;
}
Location loc = MercuryListener.getTeleportLocation(event.getPlayer().getUniqueId());
if (loc == null)
return;
loc.setDirection(new Vector(loc.getBlockX() * -1, 0, loc.getBlockZ() * -1));
PlayerArrivedChangeServerEvent e = new PlayerArrivedChangeServerEvent(event.getPlayer(), loc);
Bukkit.getPluginManager().callEvent(e);
loc = e.getLocation();
pm.addArrivedPlayer(event.getPlayer());
event.getPlayer().teleport(loc);
}
@EventHandler(priority = EventPriority.LOWEST)
public void playerJoinedLobbyServer(AsyncPlayerPreLoginEvent event) {
if (!config.get("lobby").getBool())
return;
UUID uuid = event.getUniqueId();
if (st == null){ // Small race condition if someone logs on as soon as the server starts.
plugin.getLogger().log(Level.INFO, "Player logged on before async process was ready, skipping.");
return;
}
st.setInventoryIdentifier(uuid, InventoryIdentifier.IGNORE_INV);
}
@EventHandler(priority = EventPriority.LOWEST)
public void playerQuitEvent(PlayerQuitEvent event) {
Player p = event.getPlayer();
UUID uuid = p.getUniqueId();
db.playerQuitServer(uuid);
if (!BetterShardsPlugin.getTransitManager().isPlayerInTransit(uuid)) {
st.save(p, st.getInvIdentifier(uuid), true);
}
}
//without this method players are able to detect who is in their shard as
//the default behavior for tab completion is trying to complete the name of a player on the server
@EventHandler(priority = EventPriority.LOWEST)
public void playerTabComplete(PlayerChatTabCompleteEvent event) {
Collection <String> res = event.getTabCompletions();
res.clear();
String lower = event.getLastToken() != null ? event.getLastToken() : "";
for(String player : MercuryAPI.getAllPlayers()) {
if (player.toLowerCase().startsWith(lower)) {
res.add(player);
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void consoleStopEvent(ServerCommandEvent event) {
if (event.getCommand().equals("stop") || event.getCommand().equals("/stop")) {
forcePlayerSave();
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void opStopEvent(PlayerCommandPreprocessEvent event) {
if (event.getPlayer() != null && event.getPlayer().isOp() && (event.getMessage().equals("stop") || event.getMessage().equals("/stop") ) ) {
forcePlayerSave();
}
}
/**
* Forces all player save. Should be tied to low-priority event listeners (so they get called first) surrounding /stop.
**/
private void forcePlayerSave() {
plugin.getLogger().log(Level.INFO, "Forcing online Player save to DB.");
Collection<Player> online = (Collection<Player>) Bukkit.getOnlinePlayers();
for (Player p : online) {
st.save(p, st.getInvIdentifier(p.getUniqueId()),false);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void playerMoveEvent(PlayerMoveEvent event) {
Location from = event.getFrom();
Location to = event.getTo();
if (from.getBlockX() == to.getBlockX()
&& from.getBlockY() == to.getBlockY()
&& from.getBlockZ() == to.getBlockZ()
&& from.getWorld().equals(to.getWorld())) {
// Player didn't move by at least one block.
return;
}
Player player = event.getPlayer();
Portal p = pm.getPortal(to);
if (p == null || p.getPartnerPortal() == null) {
return;
}
// We need this check incase the player just teleported inside the field.
// We know he does not need to teleport back.
if (pm.canTransferPlayer(player)) {
p.teleport(player);
}
}
@CivConfig(name = "allow_portals_build", def = "false", type = CivConfigType.Bool)
@EventHandler(priority = EventPriority.HIGHEST)
public void portalCreateEvent(PlayerInteractEvent event){
if (!config.get("allow_portals_build").getBool())
return;
Player p = event.getPlayer();
Action a = event.getAction();
if ((a != Action.RIGHT_CLICK_BLOCK ||
a != Action.LEFT_CLICK_BLOCK) &&
(p.getInventory().getItemInMainHand().getType() != Material.WATER_LILY) ||
!(p.hasPermission("bettershards.build") || p.isOp()))
return;
Block block = event.getClickedBlock();
if (block == null)
return;
Location loc = block.getLocation();
Grid g = Grid.getPlayerGrid(p);
String message = ChatColor.YELLOW + "";
if (a == Action.LEFT_CLICK_BLOCK) {
g.setLeftClickLocation(loc);
message += "Your primary block selection has been set.";
}
else {
g.setRightClickLocation(loc);
message += "Your secondary block selection has been set.";
}
p.sendMessage(message);
// Send fake block update.
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.NORMAL)
public void playerRespawnEvent(PlayerRespawnEvent event) {
if (config.get("lobby").getBool())
return;
final Player p = event.getPlayer();
UUID uuid = p.getUniqueId();
final BedLocation bed = BetterShardsPlugin.getBedManager().getBed(uuid);
//if the player has no bed or an invalid bed location, we just want to randomspawn
//him. This needs to be delayed by 1 tick, because the respawn event has to complete first
if (bed == null || (bed.getServer() != null && bed.getServer().equals(MercuryAPI.serverName())
&& Bukkit.getWorld(bed.getTeleportInfo().getWorld()) == null)) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
rs.handleDeath(p);
}
});
return;
}
final TeleportInfo teleportInfo = bed.getTeleportInfo();
if(bed.getServer() != null && bed.getServer().equals(MercuryAPI.serverName())){ //Player's bed is on the current server
event.setRespawnLocation(new Location(Bukkit.getWorld(teleportInfo.getWorld()), teleportInfo.getX(), teleportInfo.getY(), teleportInfo.getZ()));
return;
}
//bed is on a different server, so we send the player there and send the according mercury message
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
//just a badly named method, this only sends a mercury message
MercuryManager.teleportPlayer(bed.getServer(), bed.getUUID(), teleportInfo);
try {
BetterShardsAPI.connectPlayer(p, bed.getServer(), PlayerChangeServerReason.BED);
} catch (PlayerStillDeadException e) {
e.printStackTrace();
}
}
});
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void bedBreak(BlockBreakEvent event) {
if (config.get("lobby").getBool())
return;
bedBreak(event.getBlock());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void bedBreakExplosion(BlockExplodeEvent event) {
if (config.get("lobby").getBool())
return;
for (Block b : event.blockList())
bedBreak(b);
}
private void bedBreak(Block b) {
if (b.getType() != Material.BED_BLOCK)
return;
Block real = getRealFace(b);
List<BedLocation> toBeRemoved = new ArrayList<BedLocation>();
for (BedLocation bed: BetterShardsPlugin.getBedManager().getAllBeds()) {
if (!bed.getServer().equals(MercuryAPI.serverName()))
continue;
TeleportInfo loc = new TeleportInfo(real.getWorld().getName(), bed.getServer(), real.getX(), real.getY(), real.getZ());
if (bed.getTeleportInfo().equals(loc)) {
toBeRemoved.add(bed);
}
}
if (toBeRemoved.size() == 0) {
BetterShardsPlugin.getInstance().warning("Bed was broken at " + b.getLocation() + " but no bed was found in storage?");
}
for (BedLocation bed: toBeRemoved) {
BetterShardsAPI.removeBedLocation(bed);
}
}
private Block getRealFace(Block block) {
if (((Bed) block.getState().getData()).isHeadOfBed())
block = block.getRelative(((Bed) block.getState().getData()).getFacing().getOppositeFace());
return block;
}
/**
* Sets the player bed location by right-clicking on a bed.
* This allows players to set their bed at any time of the day.
* Highest event priority so it ignores events canceled by citadel
* @param event The event args
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void playerSleepInBed(PlayerInteractEvent event) {
if (config.get("lobby").getBool())
return;
if (!event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || !event.getClickedBlock().getType().equals(Material.BED_BLOCK)) {
return;
}
UUID uuid = event.getPlayer().getUniqueId();
String server = MercuryAPI.serverName();
Location loc = getRealFace(event.getClickedBlock()).getLocation();
TeleportInfo info = new TeleportInfo(loc.getWorld().getName(), server, loc.getBlockX(),
loc.getBlockY(), loc.getBlockZ());
plugin.getLogger().log(Level.INFO, "Player {0} bed location set to {1}",
new Object[] { uuid, info });
BedLocation bed = new BedLocation(uuid, info);
BetterShardsAPI.addBedLocation(uuid, bed);
event.getPlayer().sendMessage(ChatColor.GREEN + "You set your bed location.");
}
// Start of methods to try and stop interaction when transferring.
@EventHandler(priority = EventPriority.LOWEST)
public void playerDropItem(PlayerDropItemEvent event) {
Player player = event.getPlayer();
if(BetterShardsPlugin.getTransitManager().isPlayerInTransit(player.getUniqueId())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void playerDamageEvent(EntityDamageEvent event) {
if (!(event.getEntity() instanceof Player)) {
return;
}
Player p = (Player) event.getEntity();
if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void playerMoveEventWhenInTransit(PlayerMoveEvent event) {
Location from = event.getFrom();
Location to = event.getTo();
if (from.getBlockX() == to.getBlockX()
&& from.getBlockY() == to.getBlockY()
&& from.getBlockZ() == to.getBlockZ()
&& from.getWorld().equals(to.getWorld())) {
// Player didn't move by at least one block.
return;
}
Player p = event.getPlayer();
if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) {
event.setCancelled(true);
}
}
@EventHandler
public void inventoryClick(InventoryClickEvent event) {
Player p = (Player) event.getWhoClicked();
if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void playerPickupEvent(PlayerPickupItemEvent event) {
Player p = event.getPlayer();
if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void playerInteractEvent(PlayerInteractEvent event) {
Player p = (Player) event.getPlayer();
if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void blockBreakEvent(BlockBreakEvent event) {
Player p = event.getPlayer();
if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void blockPlaceEvent(BlockPlaceEvent event) {
Player p = event.getPlayer();
if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) {
event.setCancelled(true);
}
}
} |
package il.ac.technion.ie.experiments.service;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import il.ac.technion.ie.experiments.model.BlockWithData;
import il.ac.technion.ie.experiments.model.ConvexBPContext;
import il.ac.technion.ie.experiments.model.UaiVariableContext;
import il.ac.technion.ie.model.Record;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.math3.distribution.UniformRealDistribution;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class ExprimentsService {
static final Logger logger = Logger.getLogger(ExprimentsService.class);
public static final String PARAMETER_NAME = "parameter=";
public static final String CLOSE = ".";
public static final int WAIT_INTERVAL_IN_SECONDS = 5;
/**
* The method filters the blocks whose chosen representative is not the True Representative of the block.
* It doesn't modify the input collection.
*
* @param blocks - A {@link java.util.Collection} of blocks
* @return {@link java.util.Collection} of blocks. This collection shouldn't be modified
*/
public final List<BlockWithData> filterBlocksWhoseTrueRepIsNotFirst(final Collection<BlockWithData> blocks) {
List<BlockWithData> filteredBlocks = new ArrayList<>();
for (BlockWithData block : blocks) {
if (block.getTrueRepresentativePosition() != 1) {
filteredBlocks.add(block);
}
}
return filteredBlocks;
}
/**
* The method return a MAP with the split probability of each block.
* The split probability is sampled from Uniform Real Distribution {@link UniformRealDistribution} Uniform distribution~[0,1]
*
* @param blocks - a Collection of blocks
* @return Map<Integer, Double>
*/
public final Map<Integer, Double> sampleSplitProbabilityForBlocks(final Collection<BlockWithData> blocks) {
UniformRealDistribution uniformRealDistribution = new UniformRealDistribution();
Map<Integer, Double> splitProbMap = new HashMap<>();
for (BlockWithData block : blocks) {
splitProbMap.put(block.getId(), uniformRealDistribution.sample());
}
return splitProbMap;
}
public List<Double> getThresholdSorted(Collection<Double> values) {
List<Double> thresholds = new ArrayList<>(values);
Collections.sort(thresholds);
thresholds.remove(0);
return thresholds;
}
public ConvexBPContext createConvexBPContext(UaiVariableContext context) throws IOException {
final String DCBP_DIR = "C:\\Users\\i062070\\Downloads\\dcBP\\x64\\Debug";
File uaiVariableContextFile = context.getUaiFile();
if (uaiVariableContextFile == null || !uaiVariableContextFile.exists()) {
throw new FileNotFoundException("uaiVariableContextFile doesn't exist in given UaiVariableContext");
}
try {
FileUtils.copyFileToDirectory(uaiVariableContextFile, new File(DCBP_DIR));
} catch (IOException e) {
logger.error("Failed to copy uaiVariableContextFile to " + DCBP_DIR, e);
throw e;
}
String uaiFileName = uaiVariableContextFile.getName();
logger.trace("uaiFileName is: " + uaiFileName);
String outputFileName = "Out_" + System.nanoTime() + ".txt";
logger.trace("outputFileName for binary file is: " + outputFileName);
logger.debug("Create ConvexBPContext with waitIntervalInSeconds of " + WAIT_INTERVAL_IN_SECONDS);
return new ConvexBPContext(DCBP_DIR, uaiFileName, outputFileName, WAIT_INTERVAL_IN_SECONDS);
}
public Collection<File> findDatasets(String pathToDir, boolean recursiveSearch) {
Collection<File> files = null;
File sourceDir = new File(pathToDir);
if (sourceDir.isDirectory()) {
files = FileUtils.listFiles(sourceDir, new String[]{"csv"}, recursiveSearch);
}
return files;
}
public Integer getParameterValue(File dataset) {
Integer numericParamValue = null;
String fileName = dataset.getName().toLowerCase();
String paramValue = StringUtils.substringBetween(fileName, PARAMETER_NAME, CLOSE);
try {
numericParamValue = Integer.valueOf(paramValue);
} catch (NumberFormatException e) {
logger.error("Didn't find Febrl parameter value in file name");
}
return numericParamValue;
}
public double calcAvgBlockSize(List<BlockWithData> blocks) {
double sum = 0;
for (BlockWithData block : blocks) {
sum += block.size();
}
return sum / blocks.size();
}
public Multimap<Record, BlockWithData> fetchRepresentatives(List<BlockWithData> blocks) {
Multimap<Record, BlockWithData> multimap = ArrayListMultimap.create();
for (BlockWithData block : blocks) {
Map<Record, Float> blockRepresentatives = block.reFindBlockRepresentatives();
for (Record record : blockRepresentatives.keySet()) {
multimap.put(record, block);
}
}
return multimap;
}
} |
package org.eclipse.birt.report.designer.ui;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.preference.IPreferences;
import org.eclipse.birt.report.designer.core.CorePlugin;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.dnd.DNDService;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.border.BaseBorder;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.border.SelectionBorder;
import org.eclipse.birt.report.designer.internal.ui.extension.ExtendedElementUIPoint;
import org.eclipse.birt.report.designer.internal.ui.extension.ExtensionPointManager;
import org.eclipse.birt.report.designer.internal.ui.extension.experimental.EditpartExtensionManager;
import org.eclipse.birt.report.designer.internal.ui.extension.experimental.PaletteEntryExtension;
import org.eclipse.birt.report.designer.internal.ui.resourcelocator.ResourceFilter;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.views.ReportResourceSynchronizer;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.extensions.IExtensionConstants;
import org.eclipse.birt.report.designer.ui.preferences.PreferenceFactory;
import org.eclipse.birt.report.designer.ui.views.IReportResourceSynchronizer;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.metadata.IElementDefn;
import org.eclipse.birt.report.model.api.metadata.MetaDataConstants;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.content.IContentTypeManager;
import org.eclipse.core.variables.IStringVariableManager;
import org.eclipse.core.variables.VariablesPlugin;
import org.eclipse.gef.ui.views.palette.PaletteView;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import com.ibm.icu.util.StringTokenizer;
/**
* The main plugin class to be used in the desktop.
*
*/
public class ReportPlugin extends AbstractUIPlugin
{
protected static final Logger logger = Logger.getLogger( ReportPlugin.class.getName( ) );
public static final String LTR_BIDI_DIRECTION = "report.designer.ui.preferences.bidiproperties.ltrdirection"; //$NON-NLS-1$
// Add the static String list, remeber thr ignore view for the selection
private List<String> ignore = new ArrayList<String>( );
/**
* The Report UI plugin ID.
*/
public static final String REPORT_UI = "org.eclipse.birt.report.designer.ui"; //$NON-NLS-1$
/**
* The shared instance.
*/
private static ReportPlugin plugin;
/**
* The bundle context
*/
private BundleContext bundleContext;
/**
* Resource synchronizer service
*/
private ServiceRegistration syncService;
/**
* The cursor for selecting cells
*/
private Cursor cellLeftCursor, cellRightCursor;
public static final String NATURE_ID = "org.eclipse.birt.report.designer.ui.reportprojectnature"; //$NON-NLS-1$
// The entry delimiter
public static final String PREFERENCE_DELIMITER = ";"; //$NON-NLS-1$
public static final String SPACE = " "; //$NON-NLS-1$
public static final String ENABLE_GRADIENT_SELECTION_PREFERENCE = "designer.general.preference.selection.enable.gradient.preferencestore"; //$NON-NLS-1$
public static final String ENABLE_ANIMATION_SELECTION_PREFERENCE = "designer.general.preference.selection.enable.animation.preferencestore"; //$NON-NLS-1$
public static final String DEFAULT_NAME_PREFERENCE = "designer.preview.preference.elementname.defaultname.preferencestore"; //$NON-NLS-1$
public static final String CUSTOM_NAME_PREFERENCE = "designer.preview.preference.elementname.customname.preferencestore"; //$NON-NLS-1$
public static final String DESCRIPTION_PREFERENCE = "designer.preview.preference.elementname.description.preferencestore"; //$NON-NLS-1$
public static final String LIBRARY_PREFERENCE = "designer.library.preference.libraries.description.preferencestore"; //$NON-NLS-1$
public static final String LIBRARY_WARNING_PREFERENCE = "designer.library.preference.libraries.warning.preferencestore"; //$NON-NLS-1$
public static final String TEMPLATE_PREFERENCE = "designer.preview.preference.template.description.preferencestore"; //$NON-NLS-1$
public static final String RESOURCE_PREFERENCE = "org.eclipse.birt.report.designer.ui.preferences.resourcestore"; //$NON-NLS-1$
public static final String COMMENT_PREFERENCE = "org.eclipse.birt.report.designer.ui.preference.comment.description.preferencestore"; //$NON-NLS-1$
public static final String ENABLE_COMMENT_PREFERENCE = "org.eclipse.birt.report.designer.ui.preference.enable.comment.description.preferencestore"; //$NON-NLS-1$
public static final String BIRT_RESOURCE = "resources"; //$NON-NLS-1$
private static final List<String> elementToFilter = Arrays.asList( new String[]{
ReportDesignConstants.AUTOTEXT_ITEM,
ReportDesignConstants.DATA_SET_ELEMENT,
ReportDesignConstants.DATA_SOURCE_ELEMENT,
ReportDesignConstants.EXTENDED_ITEM,
ReportDesignConstants.FREE_FORM_ITEM,
ReportDesignConstants.GRAPHIC_MASTER_PAGE_ELEMENT,
ReportDesignConstants.JOINT_DATA_SET,
ReportDesignConstants.LINE_ITEM,
ReportDesignConstants.MASTER_PAGE_ELEMENT,
ReportDesignConstants.ODA_DATA_SET,
ReportDesignConstants.ODA_DATA_SOURCE,
"Parameter", //$NON-NLS-1$
ReportDesignConstants.RECTANGLE_ITEM,
ReportDesignConstants.REPORT_ITEM,
ReportDesignConstants.SCRIPT_DATA_SET,
ReportDesignConstants.SCRIPT_DATA_SOURCE,
ReportDesignConstants.SIMPLE_DATA_SET_ELEMENT,
ReportDesignConstants.TEMPLATE_DATA_SET,
ReportDesignConstants.TEMPLATE_ELEMENT,
ReportDesignConstants.TEMPLATE_PARAMETER_DEFINITION,
// fix bug 192781
ReportDesignConstants.ODA_HIERARCHY_ELEMENT,
ReportDesignConstants.TABULAR_HIERARCHY_ELEMENT,
ReportDesignConstants.DIMENSION_ELEMENT,
ReportDesignConstants.ODA_CUBE_ELEMENT,
ReportDesignConstants.TABULAR_LEVEL_ELEMENT,
ReportDesignConstants.HIERARCHY_ELEMENT,
ReportDesignConstants.TABULAR_MEASURE_GROUP_ELEMENT,
ReportDesignConstants.ODA_DIMENSION_ELEMENT,
ReportDesignConstants.MEASURE_GROUP_ELEMENT,
ReportDesignConstants.MEASURE_ELEMENT,
ReportDesignConstants.TABULAR_CUBE_ELEMENT,
ReportDesignConstants.CUBE_ELEMENT,
ReportDesignConstants.ODA_MEASURE_ELEMENT,
ReportDesignConstants.ODA_LEVEL_ELEMENT,
ReportDesignConstants.ODA_MEASURE_GROUP_ELEMENT,
ReportDesignConstants.TABULAR_MEASURE_ELEMENT,
ReportDesignConstants.LEVEL_ELEMENT,
ReportDesignConstants.TABULAR_DIMENSION_ELEMENT,
// filter some extension items;
"CrosstabView", //$NON-NLS-1$
"DimensionView", //$NON-NLS-1$
"LevelView", //$NON-NLS-1$
"MeasureView", //$NON-NLS-1$
"ComputedMeasureView" //$NON-NLS-1$
} );
private List<String> reportExtensionNames;
/**
* The constructor.
*/
public ReportPlugin( )
{
super( );
plugin = this;
}
/**
* @return Returns the resource synchronizer service
*/
public IReportResourceSynchronizer getResourceSynchronizerService( )
{
if ( bundleContext != null )
{
ServiceReference serviceRef = bundleContext.getServiceReference( IReportResourceSynchronizer.class.getName( ) );
if ( serviceRef != null )
{
return (IReportResourceSynchronizer) bundleContext.getService( serviceRef );
}
}
return null;
}
/**
* Called upon plug-in activation
*
* @param context
* the context
*/
public void start( BundleContext context ) throws Exception
{
super.start( context );
bundleContext = context;
// set preference default value
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( IPreferenceConstants.PALETTE_DOCK_LOCATION,
IPreferenceConstants.DEFAULT_PALETTE_SIZE );
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( IPreferenceConstants.PALETTE_STATE,
IPreferenceConstants.DEFAULT_PALETTE_STATE );
initCellCursor( );
setDefaultBiDiSettings( );
// set default Element names
setDefaultElementNamePreference( PreferenceFactory.getInstance( )
.getPreferences( this ) );
// set default library
setDefaultLibraryPreference( );
// set default Template
setDefaultTemplatePreference( );
// set default Resource
setDefaultResourcePreference( );
// set default Preference
setDefaultCommentPreference( );
// set default enable comment preference
setDefaultEnableCommentPreference( );
// Biding default short cut services
// Using 3.0 compatible api
PlatformUI.getWorkbench( )
.getContextSupport( )
.setKeyFilterEnabled( true );
// register default synchronizer service
syncService = context.registerService( IReportResourceSynchronizer.class.getName( ),
new ReportResourceSynchronizer( ),
null );
addIgnoreViewID( "org.eclipse.birt.report.designer.ui.editors.ReportEditor" ); //$NON-NLS-1$
addIgnoreViewID( "org.eclipse.birt.report.designer.ui.editors.TemplateEditor" ); //$NON-NLS-1$
addIgnoreViewID( IPageLayout.ID_OUTLINE );
// addIgnoreViewID( AttributeView.ID );
addIgnoreViewID( PaletteView.ID );
// addIgnoreViewID( DataView.ID );
setDefaultSelectionPreference( );
SelectionBorder.enableGradient( getEnableGradientSelectionPreference( ) );
SelectionBorder.enableAnimation( getEnableAnimatedSelectionPreference( ) );
// set resource folder in DesignerConstants for use in Core plugin
CorePlugin.RESOURCE_FOLDER = getResourcePreference( );
SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.setBirtResourcePath( getResourcePreference( ) );
SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.setResourceFolder( getResourcePreference( ) );
Platform.getExtensionRegistry( )
.addRegistryChangeListener( DNDService.getInstance( ) );
}
/**
* Returns the version info for this plugin.
*
* @return Version string.
*/
public static String getVersion( )
{
return (String) getDefault( ).getBundle( )
.getHeaders( )
.get( org.osgi.framework.Constants.BUNDLE_VERSION );
}
/**
* Returns the infomation about the Build
*
*/
public static String getBuildInfo( )
{
return getResourceString( "Build" ); //$NON-NLS-1$
}
/**
* Returns the string from the plugin's resource bundle, or 'key' if not
* found.
*/
public static String getResourceString( String key )
{
ResourceBundle bundle = Platform.getResourceBundle( getDefault( ).getBundle( ) );
try
{
return ( bundle != null ) ? bundle.getString( key ) : key;
}
catch ( MissingResourceException e )
{
return key;
}
}
/**
* Initialize the cell Cursor instance
*/
private void initCellCursor( )
{
ImageData source = ReportPlugin.getImageDescriptor( "icons/point/cellcursor.bmp" ) //$NON-NLS-1$
.getImageData( );
ImageData mask = ReportPlugin.getImageDescriptor( "icons/point/cellcursormask.bmp" ) //$NON-NLS-1$
.getImageData( );
cellLeftCursor = new Cursor( null, source, mask, 16, 16 );
source = ReportPlugin.getImageDescriptor( "icons/point/cellrightcursor.bmp" ) //$NON-NLS-1$
.getImageData( );
mask = ReportPlugin.getImageDescriptor( "icons/point/cellrightcursormask.bmp" ) //$NON-NLS-1$
.getImageData( );
cellRightCursor = new Cursor( null, source, mask, 16, 16 );
}
/**
*
* @return the cursor used to select cells in the table
*/
public Cursor getLeftCellCursor( )
{
return cellLeftCursor;
}
/**
*
* @return the cursor used to select cells in the table
*/
public Cursor getRightCellCursor( )
{
return cellRightCursor;
}
/**
* This method is called when the plug-in is stopped
*/
public void stop( BundleContext context ) throws Exception
{
bundleContext = null;
if ( syncService != null )
{
syncService.unregister( );
syncService = null;
}
ignore.clear( );
if ( cellLeftCursor != null )
{
cellLeftCursor.dispose( );
}
if ( cellRightCursor != null )
{
cellRightCursor.dispose( );
}
Platform.getExtensionRegistry( )
.removeRegistryChangeListener( DNDService.getInstance( ) );
// clean up border width cache to free resource
BaseBorder.cleanWidthCache( );
super.stop( context );
}
/**
* Returns the shared instance.
*/
public static ReportPlugin getDefault( )
{
return plugin;
}
/**
* Relative to UI plugin directory, example: "icons/usertableicon.gif".
*
* @param key
* @return an Image descriptor, this is useful to preserve the original
* color depth for instance.
*/
public static ImageDescriptor getImageDescriptor( String key )
{
ImageRegistry imageRegistry = ReportPlugin.getDefault( )
.getImageRegistry( );
ImageDescriptor imageDescriptor = imageRegistry.getDescriptor( key );
if ( imageDescriptor == null )
{
URL url = ReportPlugin.getDefault( ).find( new Path( key ) );
if ( null != url )
{
imageDescriptor = ImageDescriptor.createFromURL( url );
}
if ( imageDescriptor == null )
{
imageDescriptor = ImageDescriptor.getMissingImageDescriptor( );
}
imageRegistry.put( key, imageDescriptor );
}
return imageDescriptor;
}
/**
* Relative to UI plugin directory, example: "icons/usertableicon.gif".
*
* @param key
* @return an Image, do not dispose
*/
public static Image getImage( String key )
{
ImageRegistry imageRegistry = ReportPlugin.getDefault( )
.getImageRegistry( );
Image image = imageRegistry.get( key );
if ( image == null )
{
URL url = ReportPlugin.getDefault( ).find( new Path( key ) );
if ( url == null )
{
try
{
url = new URL( "file:///" + key ); //$NON-NLS-1$
}
catch ( MalformedURLException e )
{
}
}
if ( null != url )
{
image = ImageDescriptor.createFromURL( url ).createImage( );
}
if ( image == null )
{
image = ImageDescriptor.getMissingImageDescriptor( )
.createImage( );
}
imageRegistry.put( key, image );
}
return image;
}
/**
* @return the cheat sheet property preference, stored in the workbench root
*/
public static boolean readCheatSheetPreference( )
{
IWorkspace workspace = ResourcesPlugin.getWorkspace( );
try
{
String property = workspace.getRoot( )
.getPersistentProperty( new QualifiedName( "org.eclipse.birt.property", //$NON-NLS-1$
"showCheatSheet" ) ); //$NON-NLS-1$
if ( property != null )
return Boolean.valueOf( property ).booleanValue( );
}
catch ( CoreException e )
{
logger.log( Level.SEVERE, e.getMessage( ), e );
}
return true;
}
/**
* Set the show cheatsheet preference in workspace root. Used by wizards
*/
public static void writeCheatSheetPreference( boolean value )
{
IWorkspace workspace = ResourcesPlugin.getWorkspace( );
try
{
workspace.getRoot( )
.setPersistentProperty( new QualifiedName( "org.eclipse.birt.property", //$NON-NLS-1$
"showCheatSheet" ), //$NON-NLS-1$
String.valueOf( value ) );
}
catch ( CoreException e )
{
logger.log( Level.SEVERE, e.getMessage( ), e );
}
}
/**
* Returns the workspace instance.
*/
public static IWorkspace getWorkspace( )
{
return ResourcesPlugin.getWorkspace( );
}
/**
* Set default element names for preference
*
* @param store
* The preference for store
*/
private void setDefaultElementNamePreference( IPreferences store )
{
List tmpList = DEUtil.getMetaDataDictionary( ).getElements( );
List tmpList2 = DEUtil.getMetaDataDictionary( ).getExtensions( );
tmpList.addAll( tmpList2 );
int i;
StringBuffer bufferDefaultName = new StringBuffer( );
StringBuffer bufferCustomName = new StringBuffer( );
StringBuffer bufferPreference = new StringBuffer( );
int nameOption;
IElementDefn elementDefn;
for ( i = 0; i < tmpList.size( ); i++ )
{
elementDefn = (IElementDefn) ( tmpList.get( i ) );
nameOption = elementDefn.getNameOption( );
// only set names for the elements when the element can have a name
if ( nameOption == MetaDataConstants.NO_NAME
|| filterName( elementDefn ) )
{
continue;
}
bufferDefaultName.append( elementDefn.getName( ) );
bufferDefaultName.append( PREFERENCE_DELIMITER );
bufferCustomName.append( "" ); //$NON-NLS-1$
bufferCustomName.append( PREFERENCE_DELIMITER );
appendDefaultPreference( elementDefn.getName( ), bufferPreference );
}
store.setDefault( DEFAULT_NAME_PREFERENCE, bufferDefaultName.toString( ) );
store.setDefault( CUSTOM_NAME_PREFERENCE, bufferCustomName.toString( ) );
store.setDefault( DESCRIPTION_PREFERENCE, bufferPreference.toString( ) );
initFilterMap( store, ResourceFilter.generateCVSFilter( ) );
initFilterMap( store, ResourceFilter.generateDotResourceFilter( ) );
initFilterMap( store, ResourceFilter.generateEmptyFolderFilter( ) );
// initFilterMap( store,
// ResourceFilter.generateNoResourceInFolderFilter( ) );
}
private boolean filterName( IElementDefn elementDefn )
{
return elementToFilter.indexOf( elementDefn.getName( ) ) != -1;
}
/**
* Append default description to the Stringbuffer according to each
* defaultName
*
* @param defaultName
* The default Name preference The Stringbuffer which string
* added to
*/
private void appendDefaultPreference( String defaultName,
StringBuffer preference )
{
if ( defaultName.equals( ReportDesignConstants.DATA_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.dataReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.GRID_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.gridReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.IMAGE_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.imageReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.LABEL_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.labelReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.LIST_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.listReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.TABLE_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.tableReportItem" ) ); //$NON-NLS-1$
}
else if ( defaultName.equals( ReportDesignConstants.TEXT_ITEM ) )
{
preference.append( Messages.getString( "DesignerPaletteFactory.toolTip.textReportItem" ) ); //$NON-NLS-1$
}
else
{
preference.append( getExtendedPaletteEntryDescription( defaultName ) );
}
preference.append( PREFERENCE_DELIMITER );
}
/**
* Get default element name preference
*
* @return String[] the array of Strings of default element name preference
*/
public String[] getDefaultDefaultNamePreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( DEFAULT_NAME_PREFERENCE ) );
}
/**
* Get default custom name preference
*
* @return String[] the array of Strings of custom element name preference
*/
public String[] getDefaultCustomNamePreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( CUSTOM_NAME_PREFERENCE ) );
}
/**
* Get default description preference
*
* @return String[] the array of Strings of default description preference
*/
public String[] getDefaultDescriptionPreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( DESCRIPTION_PREFERENCE ) );
}
/**
* Get element name preference
*
* @return String[] the array of Strings of element name preference
*/
public String[] getDefaultNamePreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.getString( DEFAULT_NAME_PREFERENCE ) );
}
/**
* Get custom element preference
*
* @return String[] the array of Strings of custom name preference
*/
public String[] getCustomNamePreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.getString( CUSTOM_NAME_PREFERENCE ) );
}
/**
* Get description preference
*
* @return String[] the array of Strings of description preference
*/
public String[] getDescriptionPreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.getString( DESCRIPTION_PREFERENCE ) );
}
/**
* Get the custom name preference of specified element name
*
* @param defaultName
* The specified element name
* @return String The custom name gotten
*/
public String getCustomName( String defaultName )
{
int i;
String[] defaultNameArray = getDefaultNamePreference( );
String[] customNameArray = getCustomNamePreference( );
// if the length of elememnts is not equal,it means error
if ( defaultNameArray.length != customNameArray.length )
{
return null;
}
for ( i = 0; i < defaultNameArray.length; i++ )
{
if ( defaultNameArray[i].trim( ).equals( defaultName ) )
{
if ( customNameArray[i].equals( "" ) ) //$NON-NLS-1$
{
return null;
}
return customNameArray[i];
}
}
return null;
}
/**
* Convert the single string of preference into string array
*
* @param preferenceValue
* The specified element name
* @return String[] The array of strings
*/
public static String[] convert( String preferenceValue )
{
String preferenceValueCopy = PREFERENCE_DELIMITER + preferenceValue;
String replaceString = PREFERENCE_DELIMITER + PREFERENCE_DELIMITER;
String regrex = PREFERENCE_DELIMITER + SPACE + PREFERENCE_DELIMITER;
while ( preferenceValueCopy.indexOf( replaceString ) != -1 )
{
preferenceValueCopy = preferenceValueCopy.replaceFirst( replaceString,
regrex );
}
StringTokenizer tokenizer = new StringTokenizer( preferenceValueCopy,
PREFERENCE_DELIMITER );
int tokenCount = tokenizer.countTokens( );
String[] elements = new String[tokenCount];
int i;
for ( i = 0; i < tokenCount; i++ )
{
elements[i] = tokenizer.nextToken( ).trim( );
}
return elements;
}
/**
* Convert Sting[] to String
*
* @param elements
* [] elements - the Strings to be converted to the preference
* value
*/
public String convertStrArray2Str( String[] elements )
{
StringBuffer buffer = new StringBuffer( );
for ( int i = 0; i < elements.length; i++ )
{
buffer.append( elements[i] );
buffer.append( PREFERENCE_DELIMITER );
}
return buffer.toString( );
}
/**
* Set element names from string[]
*
* @param elements
* the array of element names
*/
public void setDefaultNamePreference( String[] elements )
{
PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.setValue( DEFAULT_NAME_PREFERENCE,
convertStrArray2Str( elements ) );
}
/**
* Set element names from string
*
* @param element
* the string of element names
*/
public void setDefaultNamePreference( String element )
{
PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.setValue( DEFAULT_NAME_PREFERENCE, element );
}
/**
* Set default names for the element names from String[]
*
* @param elements
* the array of default names
*/
public void setCustomNamePreference( String[] elements )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( CUSTOM_NAME_PREFERENCE,
convertStrArray2Str( elements ) );
}
/**
* Set default names for the element names from String
*
* @param element
* the string of default names
*/
public void setCustomNamePreference( String element )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( CUSTOM_NAME_PREFERENCE,
element );
}
/**
* Set descriptions for the element names from String[]
*
* @param elements
* the array of descriptions
*/
public void setDescriptionPreference( String[] elements )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( DESCRIPTION_PREFERENCE,
convertStrArray2Str( elements ) );
}
/**
* Set descriptions for the element names from String
*
* @param element
* the string of descriptions
*/
public void setDescriptionPreference( String element )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( DESCRIPTION_PREFERENCE,
element );
}
/**
* Set the bad words preference
*
* @param elements
* [] elements - the Strings to be converted to the preference
* value
*/
public void setLibraryPreference( String[] elements )
{
StringBuffer buffer = new StringBuffer( );
for ( int i = 0; i < elements.length; i++ )
{
buffer.append( elements[i] );
buffer.append( PREFERENCE_DELIMITER );
}
PreferenceFactory.getInstance( )
.getPreferences( this )
.setValue( LIBRARY_PREFERENCE, buffer.toString( ) );
}
/**
* Return the library preference as an array of Strings.
*
* @return String[] The array of strings of library preference
*/
public String[] getLibraryPreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getString( LIBRARY_PREFERENCE ) );
}
/**
* Set default library preference
*/
public void setDefaultLibraryPreference( )
{
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( LIBRARY_PREFERENCE, "" ); //$NON-NLS-1$
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( LIBRARY_WARNING_PREFERENCE,
MessageDialogWithToggle.PROMPT );
}
/**
* Return default library preference as an array of Strings.
*
* @return String[] The array of strings of default library preference
*/
public String[] getDefaultLibraryPreference( )
{
return convert( PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( LIBRARY_PREFERENCE ) );
}
/**
* Return default template preference
*
* @return String The String of default template preference
*/
public String getDefaultTemplatePreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( TEMPLATE_PREFERENCE );
}
/**
* set default template preference
*
*/
public void setDefaultTemplatePreference( )
{
String defaultRootDir = UIUtil.getFragmentDirectory( );
File templateFolder = new File(defaultRootDir, "/custom-templates/"); //$NON-NLS-1$
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( TEMPLATE_PREFERENCE, templateFolder.getAbsolutePath( ) );
}
/**
* Return default template preference
*
* @return String The string of default template preference
*/
public String getTemplatePreference( )
{
return PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).getString( TEMPLATE_PREFERENCE );
}
/**
* set default template preference
*
*/
public void setTemplatePreference( String preference )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( TEMPLATE_PREFERENCE,
preference );
}
/**
* set default resource preference
*
*/
public void setDefaultResourcePreference( )
{
// String metaPath = Platform.getStateLocation( ReportPlugin.getDefault(
// .getBundle( ) ).toOSString( );
// if ( !metaPath.endsWith( File.separator ) )
// metaPath = metaPath + File.separator;
// metaPath = metaPath + BIRT_RESOURCE;
// File targetFolder = new File( metaPath );
// if ( !targetFolder.exists( ) )
// targetFolder.mkdirs( );
// PreferenceFactory.getInstance( ).getPreferences( this ).setDefault(
// RESOURCE_PREFERENCE, metaPath );
// //$NON-NLS-1$
// String defaultDir = new String( UIUtil.getHomeDirectory( ) );
// defaultDir = defaultDir.replace( '\\', '/' ); //$NON-NLS-1$
// //$NON-NLS-2$
// if ( !defaultDir.endsWith( "/" ) ) //$NON-NLS-1$
// defaultDir = defaultDir + "/"; //$NON-NLS-1$
// defaultDir = defaultDir + BIRT_RESOURCE;
// if ( !defaultDir.endsWith( "/" ) ) //$NON-NLS-1$
// defaultDir = defaultDir + "/"; //$NON-NLS-1$
// File targetFolder = new File( defaultDir );
// if ( !targetFolder.exists( ) )
// targetFolder.mkdirs( );
// bug 151361, set default resource folder empty
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( RESOURCE_PREFERENCE, "" ); //$NON-NLS-1$
}
/**
* Return default resouce preference
*
* @return String The String of default resource preference
*/
public String getDefaultResourcePreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( RESOURCE_PREFERENCE );
}
/**
* Return resource preference
*
* @return String The string of resource preference
*/
public String getResourcePreference( )
{
return PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).getString( RESOURCE_PREFERENCE );
}
/**
* Return specified project's resource preference
*
* @param project
*
* @return String The string of resource preference
*/
public String getResourcePreference( IProject project )
{
return PreferenceFactory.getInstance( )
.getPreferences( this, project )
.getString( RESOURCE_PREFERENCE );
}
/**
* set resource preference
*
*/
public void setResourcePreference( String preference )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( RESOURCE_PREFERENCE,
preference );
CorePlugin.RESOURCE_FOLDER = preference;
}
/**
* Add View ID into ignore view list.
*
* @param str
*/
public void addIgnoreViewID( String str )
{
ignore.add( str );
}
/**
* Remove View ID from ignore view list.
*
* @param str
*/
public void removeIgnoreViewID( String str )
{
ignore.remove( str );
}
/**
* Test whether the View ID is in the ignore view list.
*
* @param str
* @return
*/
public boolean containIgnoreViewID( String str )
{
return ignore.contains( str );
}
/**
* set default comment preference
*
*/
public void setDefaultCommentPreference( )
{
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( COMMENT_PREFERENCE,
Messages.getString( "org.eclipse.birt.report.designer.ui.preference.commenttemplates.defaultcomment" ) ); //$NON-NLS-1$
}
/**
* Return default comment preference
*
* @return String The string of default comment preference
*/
public String getDefaultCommentPreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultString( COMMENT_PREFERENCE );
}
/**
* Return comment preference
*
* @return String The string of comment preference
*/
public String getCommentPreference( )
{
return PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).getString( COMMENT_PREFERENCE );
}
/**
* set comment preference
*
*/
public void setCommentPreference( String preference )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( COMMENT_PREFERENCE,
preference );
}
/**
* set enable default comment preference
*
*/
public void setDefaultEnableCommentPreference( )
{
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( ENABLE_COMMENT_PREFERENCE, false );
}
/**
* Return default enable comment preference
*
* @return boolean The bool value of default enable comment preference
*/
public boolean getDefaultEnabelCommentPreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getDefaultBoolean( ENABLE_COMMENT_PREFERENCE );
}
/**
* Return enable comment preference
*
* @return boolean The bool value of enable comment preference
*/
public boolean getEnableCommentPreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.getBoolean( ENABLE_COMMENT_PREFERENCE );
}
private void setDefaultSelectionPreference( )
{
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( ENABLE_GRADIENT_SELECTION_PREFERENCE, true );
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( ENABLE_ANIMATION_SELECTION_PREFERENCE, false );
}
public boolean getEnableGradientSelectionPreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getBoolean( ENABLE_GRADIENT_SELECTION_PREFERENCE );
}
public boolean getEnableAnimatedSelectionPreference( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getBoolean( ENABLE_ANIMATION_SELECTION_PREFERENCE );
}
/**
* set enable comment preference
*
*/
public void setEnableCommentPreference( boolean preference )
{
PreferenceFactory.getInstance( )
.getPreferences( this, UIUtil.getCurrentProject( ) )
.setValue( ENABLE_COMMENT_PREFERENCE, preference );
}
/**
* Returns all available extension names for report design files.
*
* @return the extension name lisr
*/
public List<String> getReportExtensionNameList( )
{
if ( reportExtensionNames == null )
{
reportExtensionNames = new ArrayList<String>( );
IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry( );
IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor( "org.eclipse.ui.editors" ); //$NON-NLS-1$
for ( int i = 0; i < elements.length; i++ )
{
String id = elements[i].getAttribute( "id" ); //$NON-NLS-1$
if ( "org.eclipse.birt.report.designer.ui.editors.ReportEditor".equals( id ) ) //$NON-NLS-1$
{
if ( elements[i].getAttribute( "extensions" ) != null ) //$NON-NLS-1$
{
String[] extensionNames = elements[i].getAttribute( "extensions" ) //$NON-NLS-1$
//$NON-NLS-1$
.split( "," ); //$NON-NLS-1$
for ( int j = 0; j < extensionNames.length; j++ )
{
extensionNames[j] = extensionNames[j].trim( );
if ( !reportExtensionNames.contains( extensionNames[j] ) )
{
reportExtensionNames.add( extensionNames[j] );
}
}
}
}
}
IContentTypeManager contentTypeManager = Platform.getContentTypeManager( );
IContentType contentType = contentTypeManager.getContentType( "org.eclipse.birt.report.designer.ui.editors.reportdesign" ); //$NON-NLS-1$
String[] fileSpecs = contentType.getFileSpecs( IContentType.FILE_EXTENSION_SPEC );
for ( int i = 0; i < fileSpecs.length; i++ )
{
reportExtensionNames.add( fileSpecs[i] );
}
}
return reportExtensionNames;
}
/**
* Checks if the file is a report design file by its file name
*
* @return true if the extension name of the file can be recognized as a
* report design file, or false otherwise.
*/
public boolean isReportDesignFile( String filename )
{
if ( filename != null )
{
for ( Iterator<String> iter = ReportPlugin.getDefault( )
.getReportExtensionNameList( )
.iterator( ); iter.hasNext( ); )
{
if ( filename.endsWith( "." + iter.next( ) ) ) //$NON-NLS-1$
{
return true;
}
}
}
return false;
}
/**
* @param project
* @return
*/
public String getResourceFolder( IProject project )
{
return getResourceFolder( project, SessionHandleAdapter.getInstance( )
.getReportDesignHandle( ) );
}
/**
* @param project
* @param module
* @return
*/
public String getResourceFolder( IProject project, ModuleHandle module )
{
return getResourceFolder( project, module == null ? "" //$NON-NLS-1$
: module.getResourceFolder( ) );
}
/**
* @param project
* @param parentPath
* @return
*/
public String getResourceFolder( IProject project, String parentPath )
{
String resourceFolder = ReportPlugin.getDefault( )
.getResourcePreference( project );
if ( resourceFolder == null || resourceFolder.equals( "" ) ) //$NON-NLS-1$
{
resourceFolder = parentPath;
}
if ( resourceFolder == null )
{
resourceFolder = "";//$NON-NLS-1$
}
String str = resourceFolder;
try
{
IStringVariableManager mgr = VariablesPlugin.getDefault( )
.getStringVariableManager( );
str = mgr.performStringSubstitution( resourceFolder );
}
catch ( CoreException e )
{
str = resourceFolder;
}
resourceFolder = str;
File file = new File( resourceFolder );
if ( !file.isAbsolute( ) )
{
if ( project != null )
{
resourceFolder = project.getLocation( )
.append( resourceFolder )
.toOSString( );
}
else
{
if ( !resourceFolder.startsWith( File.separator ) )
{
resourceFolder = File.separator + resourceFolder;
}
resourceFolder = parentPath + resourceFolder;
}
}
return resourceFolder;
}
public String getResourceFolder( )
{
return getResourceFolder( UIUtil.getCurrentProject( ) );
}
private static LinkedHashMap<String, ResourceFilter> filterMap = new LinkedHashMap<String, ResourceFilter>( );
private static void initFilterMap( IPreferences store, ResourceFilter filter )
{
if ( store.contains( filter.getType( ) ) )
filter.setEnabled( store.getBoolean( filter.getType( ) ) );
filterMap.put( filter.getType( ), filter );
}
public static LinkedHashMap<String, ResourceFilter> getFilterMap( )
{
return filterMap;
}
/**
* Sets default settings for BiDi properties
*
*/
public void setDefaultBiDiSettings( )
{
PreferenceFactory.getInstance( )
.getPreferences( this )
.setDefault( LTR_BIDI_DIRECTION, true );
}
/**
* Retrieves if BiDi orientation is Left To Right
*
* @return true if BiDi orientation is Left To Right false if BiDi
* orientation is Right To Left
*/
public boolean getLTRReportDirection( IProject project )
{
return PreferenceFactory.getInstance( )
.getPreferences( this, project )
.getBoolean( LTR_BIDI_DIRECTION );
}
public boolean getLTRReportDirection( )
{
return PreferenceFactory.getInstance( )
.getPreferences( this )
.getBoolean( LTR_BIDI_DIRECTION );
}
/**
* Sets value for 'Left To Right BIDi direction' flag
*
* @param true if BiDi direction should be set to Left To Right false if
* BiDi direction should be set to Right To Left
*/
public void setLTRReportDirection( boolean ltrDirection )
{
PreferenceFactory.getInstance( ).getPreferences( this,
UIUtil.getCurrentProject( ) ).setValue( LTR_BIDI_DIRECTION,
ltrDirection );
}
/**
* Gets the description text of the extended palette entry elements.
*
* @return the description text, or "" if not found.
*/
private String getExtendedPaletteEntryDescription( String defaultName )
{
PaletteEntryExtension[] entries = EditpartExtensionManager.getPaletteEntries( );
if ( entries != null )
{
for ( int i = 0; i < entries.length; i++ )
{
if ( entries[i].getItemName( ).equals( defaultName ) )
{
return entries[i].getDescription( ) != null ? entries[i].getDescription( )
: ""; //$NON-NLS-1$
}
}
}
List points = ExtensionPointManager.getInstance( )
.getExtendedElementPoints( );
if ( points != null )
{
for ( Iterator itor = points.iterator( ); itor.hasNext( ); )
{
ExtendedElementUIPoint point = (ExtendedElementUIPoint) itor.next( );
if ( point.getExtensionName( ).equals( defaultName ) )
{
return point.getAttribute( IExtensionConstants.ATTRIBUTE_KEY_DESCRIPTION ) != null ?
(String) point.getAttribute( IExtensionConstants.ATTRIBUTE_KEY_DESCRIPTION )
: ""; //$NON-NLS-1$
}
}
}
return ""; //$NON-NLS-1$
}
} |
package net.yadaframework.security.persistence.entity;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrePersist;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unbescape.html.HtmlEscape;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import net.yadaframework.core.YadaLocalEnum;
import net.yadaframework.exceptions.YadaInternalException;
import net.yadaframework.persistence.entity.YadaAttachedFile;
import net.yadaframework.persistence.entity.YadaPersistentEnum;
import net.yadaframework.web.YadaJsonDateTimeShortSerializer;
import net.yadaframework.web.YadaJsonView;
/**
* A message sent to some user by another user or by the system.
* Identical consecutive messages can be "stacked" on a single row by incrementing the "stackSize" and adding a new "created" date
*
* @param <E> a localized enum for the message type
*/
@Entity
// Use a joined table for inheritance so that the subclasses can independently add any attributes without interference
@Inheritance(strategy = InheritanceType.JOINED)
public class YadaUserMessage<E extends Enum<E>> implements Serializable {
private static final long serialVersionUID = 7008892353441772768L;
private final transient Logger log = LoggerFactory.getLogger(getClass());
@Version
protected long version; // For optimistic locking
@JsonView(YadaJsonView.WithEagerAttributes.class)
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
protected Long id;
@JsonView(YadaJsonView.WithEagerAttributes.class)
protected int priority; // Priority or severity, 0 is lowest
@JsonView(YadaJsonView.WithEagerAttributes.class)
protected boolean readByRecipient = false; // Read by recipient
@JsonView(YadaJsonView.WithEagerAttributes.class)
protected boolean emailed = false; // Emailed to recipient
@ElementCollection
@Temporal(TemporalType.TIMESTAMP)
//@JsonView(YadaJsonView.WithEagerAttributes.class)
//@JsonView(YadaJsonView.WithLazyAttributes.class)
protected List<Date> created; // Creation date of the message, a new date is added for each stacked message
@JsonView(YadaJsonView.WithEagerAttributes.class)
@Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP")
@Temporal(TemporalType.TIMESTAMP)
protected Date modified = new Date();
@JsonView(YadaJsonView.WithEagerAttributes.class)
protected int stackSize = 0; // Counter for identical messages (stacked)
@OneToOne(fetch = FetchType.EAGER, optional=true)
@JsonView(YadaJsonView.WithEagerAttributes.class)
protected YadaPersistentEnum<E> type;
@Column(length=80)
@JsonView(YadaJsonView.WithEagerAttributes.class)
protected String title;
@Column(length=12000) // Should it be Lob?
@JsonView(YadaJsonView.WithEagerAttributes.class)
protected String message;
@ManyToOne(optional = true)
@JsonView(YadaJsonView.WithLazyAttributes.class)
protected YadaUserProfile sender;
@ManyToOne(optional = true)
@JsonView(YadaJsonView.WithLazyAttributes.class)
protected YadaUserProfile recipient;
//@JsonView(YadaJsonView.WithLazyAttributes.class)
@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true) // It was REMOVE - why?
protected List<YadaAttachedFile> attachment = new ArrayList<>();
@Column(length=1024)
@JsonView(YadaJsonView.WithEagerAttributes.class)
protected String data; // Can store a url here, or the identity of a non-user sender
protected int contentHash; // To check message equality for stackability
@Transient
protected boolean stackable; // true if same-content messages should be counted not added
@JsonView(YadaJsonView.WithEagerAttributes.class)
@JsonProperty("DT_RowClass")
public String getDT_RowClass() {
// We set the class according to the read state of the message
return this.readByRecipient?"yadaUserMessage-read":"yadaUserMessage-unread";
}
/**
* Computes the content hash before persisting.
* The hash does not consider attachments, sender, receiver or status flags.
* Override this method if your subclass add more fields that should be checked when computing stackability of messages
*/
@PrePersist
public void init() {
computeHash();
setInitialDate();
}
/**
* Escape all markup-significant characters
* @param message
* @return
* @return the current instance
*/
@Transient
public YadaUserMessage<E> setMessageEscaped(String message) {
this.message = HtmlEscape.escapeHtml5Xml(message);
return this;
}
public void computeHash() {
if (type==null) {
Type missingEnum = null;
try {
missingEnum = ((java.lang.reflect.ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
} catch (Exception e) {
// Ignored
}
String enumName = missingEnum!=null?missingEnum.toString():"all YadaLocalEnum classes";
throw new YadaInternalException("YadaUserMessage type is null - did you remember to add " + enumName + " to yadaPersistentEnumDao.initDatabase() during application setup?");
}
this.contentHash = Objects.hash(type.getEnum(), title, message, data);
}
public void setInitialDate() {
if (created==null) {
created = new ArrayList<Date>();
created.add(new Date());
}
}
public void incrementStack() {
this.stackSize++;
this.created.add(new Date());
}
public void setType(YadaLocalEnum<E> localEnum) {
this.type = localEnum.toYadaPersistentEnum();
}
/* DataTables */
@Transient
@JsonView(YadaJsonView.WithEagerAttributes.class)
@JsonProperty("DT_RowId")
@Deprecated // can be removed now that it is added automatically by YadaDataTableDao
public String getDT_RowId() {
return this.getClass().getSimpleName()+"#"+this.id; // YadaUserMessage#142
}
@Transient
@JsonProperty
@JsonView(YadaJsonView.WithEagerAttributes.class)
public String getSenderName() {
if (sender!=null) {
return sender.getUserCredentials().getUsername();
}
return null;
}
@Transient
@JsonProperty
@JsonView(YadaJsonView.WithEagerAttributes.class)
public String getReceiverName() {
return recipient!=null?recipient.getUserCredentials().getUsername():"-";
}
/** Adds a new attachment to this message
*
*/
public void addAttachment(YadaAttachedFile newAttachment) {
attachment.add(newAttachment);
}
/* Plain getter / setter */
@JsonSerialize(using=YadaJsonDateTimeShortSerializer.class)
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public boolean isEmailed() {
return emailed;
}
public void setEmailed(boolean emailed) {
this.emailed = emailed;
}
public int getStackSize() {
return stackSize;
}
public void setStackSize(int count) {
this.stackSize = count;
}
public YadaPersistentEnum<E> getType() {
return type;
}
public void setType(YadaPersistentEnum<E> type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public YadaUserProfile getSender() {
return sender;
}
public void setSender(YadaUserProfile senderUser) {
this.sender = senderUser;
}
public YadaUserProfile getRecipient() {
return recipient;
}
public void setRecipient(YadaUserProfile recipient) {
this.recipient = recipient;
}
public List<YadaAttachedFile> getAttachment() {
return attachment;
}
public void setAttachment(List<YadaAttachedFile> attachment) {
this.attachment = attachment;
}
public int getContentHash() {
return contentHash;
}
public void setContentHash(int hash) {
this.contentHash = hash;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public boolean isStackable() {
return stackable;
}
public void setStackable(boolean stackable) {
this.stackable = stackable;
}
public List<Date> getCreated() {
return created;
}
public void setCreated(List<Date> created) {
this.created = created;
}
public boolean isReadByRecipient() {
return readByRecipient;
}
public void setReadByRecipient(boolean readByRecipient) {
this.readByRecipient = readByRecipient;
}
} |
package info.hiergiltdiestfu.waste.extractor;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.*;
import javax.ws.rs.QueryParam;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.netflix.util.Pair;
import info.hiergiltdiestfu.waste.extractor.model.DisposalRun;
import info.hiergiltdiestfu.waste.extractor.model.Health;
import info.hiergiltdiestfu.waste.extractor.model.NextDisposalRuns;
import info.hiergiltdiestfu.waste.extractor.model.WasteType;
@Controller
public class ExtractorController {
private final Map<String, Pair<Long, NextDisposalRuns>> CACHE = new HashMap<>(MAX_CACHE_ENTRIES / 4);
private static final long MAX_CACHE_AGE_MILLIS = 1000*60*60;
private static final int MAX_CACHE_ENTRIES = 64*4;
private static final String SR_API_HEAD_URI_WITH_PARAMS = "http://stadtplan.dresden.de/project/cardo3Apps/IDU_DDStadtplan/abfall/detailpage.aspx?POS-ADR=%s|%s";
@ResponseBody
@RequestMapping(path="/health-description")
public Health health() {
return new Health(100, "Looking good");
//TODO test availability of SR API and report on that
//TODO change context path to /health for eureka compat
}
@ResponseBody
@RequestMapping(path="/next-disposal")
public NextDisposalRuns nextDisposal(@QueryParam("street") String street, @QueryParam("number") String number) throws Throwable {
if (CACHE.size()>=MAX_CACHE_ENTRIES) {
System.err.println("CACHE: Expunging entries that are too old");
Collection<Pair<Long, NextDisposalRuns>> values = CACHE.values();
List<Pair<Long, ?>> tooOld = values.stream().filter(p->p.first()<=System.currentTimeMillis()-MAX_CACHE_AGE_MILLIS).collect(Collectors.toList());
values.removeAll(tooOld);
System.err.println(String.format("CACHE: That freed up %d entries", tooOld.size()));
if (CACHE.size()>=MAX_CACHE_ENTRIES) {
System.err.println("CACHE: But that wasn't enough. Now I'm gonna choose at random, sorry.");
values = CACHE.values();
List<?> random = values.stream().filter(p->Math.random()>0.75f).collect(Collectors.toList());
values.removeAll(random);
System.err.println(String.format("CACHE: That freed up %d entries", random.size()));
}
}
if (CACHE.containsKey(street+number)) {
final Pair<Long, NextDisposalRuns> cached = CACHE.get(street+number);
if (System.currentTimeMillis()-cached.first() > MAX_CACHE_AGE_MILLIS) {
System.out.println("CACHE: Hit, but too old :(");
CACHE.remove(street+number);
} else {
System.out.println("CACHE: Hit! :)");
return cached.second();
}
}
final NextDisposalRuns result = new NextDisposalRuns(String.format("%s %s", street, number));
final Map<String, Pair<String, String>> rawResult = getRawDisposalRunsFromStadtreinigung(street, number);
rawResult.forEach((type, data) -> {
try {
result.getNextRunPerDisposalType().add(DisposalRunAdapter.build(type, data.first(), data.second()));
} catch (Throwable e) {
throw new RuntimeException(e);
}
});
CACHE.put(street+number, new Pair<Long, NextDisposalRuns>(System.currentTimeMillis(), result));
return result;
}
private Map<String, Pair<String, String>> getRawDisposalRunsFromStadtreinigung(String street, String number) throws IOException {
final Map<String, Pair<String, String>> result = new HashMap<>(8, 0.75f);
final String targetURI = String.format(SR_API_HEAD_URI_WITH_PARAMS, URLEncoder.encode(street, "UTF-8"), URLEncoder.encode(number, "UTF-8"));
Document doc = Jsoup.connect(targetURI).get();
Elements detailsTable = doc.select("td#ux_standort_details tr.fett, td#ux_standort_details tr.fett + tr, td#ux_standort_details tr.fett + tr + tr");
// System.out.println(detailsTable.text());
if (detailsTable.size() % 3 != 0) throw new IllegalStateException("Size of select from SR API is not a multiple of 3! This is suspicious - check your Selector!");
int step = 0;
String wasteType = null, interval = null, nextRun = null;
for (Element e: detailsTable) {
switch (step) {
case 0:
//clean up (new round!)
wasteType = interval = nextRun = null;
//assume waste type
wasteType = e.child(0).text();
break;
case 1:
//assume interval
if (!"Ihr Abfuhrtag:".equals(e.child(0).text())) throw new IllegalStateException("Unexpected element in SR API response: "+e.outerHtml());
interval = e.child(1).text();
break;
case 2:
//assume next run
if (!"nächste Abfuhr:".equals(e.child(0).text())) throw new IllegalStateException("Unexpected element in SR API response: "+e.outerHtml());
nextRun = e.child(1).text();
break;
default: throw new IllegalStateException("Should've wrapped around the state machine Oo");
}
step = ++step % 3;
if (0 == step) {
if (result.containsKey(wasteType)) throw new IllegalStateException("Duplicate entries in SR API response for waste type "+wasteType);
result.put(wasteType, new Pair<>(nextRun, interval));
}
}
return result;
}
} |
package org.ccnx.android.examples.startup;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.impl.security.keys.BasicKeyManager;
import org.ccnx.ccn.profiles.ccnd.CCNDaemonException;
import org.ccnx.ccn.profiles.ccnd.SimpleFaceControl;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ScrollView;
import android.widget.TextView;
public abstract class StartupBase extends Activity {
protected String TAG="StartupBase";
protected final static String LOG_LEVEL="WARNING";
// Process control Methods
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starter);
tv = (TextView) findViewById(R.id.tvOutput);
sv = (ScrollView) findViewById(R.id.svOutput);
ScreenOutput("Starting the CCNx thread\n");
}
@Override
public void onStart() {
super.onStart();
tv.setText("");
tv.invalidate();
_lastScreenOutput = System.currentTimeMillis();
_firstScreenOutput = _lastScreenOutput;
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
if( _handle != null ) {
// close the default handle, which was used by SimpleFaceControl
_handle.close();
KeyManager.closeDefaultKeyManager();
_handle = null;
}
super.onDestroy();
}
// UI Methods
private final static int EXIT_MENU = 1;
private final static int SHUTDOWN_MENU = 2;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_MENU, 1, "Exit");
menu.add(0, SHUTDOWN_MENU, 1, "Exit & Shutdown");
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EXIT_MENU:
doExit();
closeCcn();
finish();
return true;
case SHUTDOWN_MENU:
doShutdown();
closeCcn();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
abstract void doExit();
abstract void doShutdown();
// Internal implementation
protected TextView tv = null;
protected ScrollView sv = null;
protected SimpleDateFormat _dateformat = new SimpleDateFormat("HH:mm:ss.S");
protected long _lastScreenOutput = -1;
protected long _firstScreenOutput = -1;
protected Object _outputLock = new Object();
protected CCNHandle _handle = null;
protected KeyManager _km = null;
protected void openCcn() throws ConfigurationException, IOException, InvalidKeyException {
org.ccnx.ccn.impl.support.Log.setLevel(org.ccnx.ccn.impl.support.Log.FAC_ALL, Level.parse(LOG_LEVEL));
_km = new BasicKeyManager();
_km.initialize();
KeyManager.setDefaultKeyManager(_km);
_handle = CCNHandle.open(_km);
}
protected void closeCcn() {
if( _handle != null ) {
_handle.close();
_handle = null;
}
if( _km != null ) {
KeyManager.closeDefaultKeyManager();
_km = null;
}
}
protected void setupFace() throws CCNDaemonException {
postToUI("Calling SimpleFaceControl");
SimpleFaceControl.getInstance(_handle).openMulicastInterface();
postToUI("Finished SimpleFaceControl");
}
/**
* In the UI thread, post a message to the screen
*/
protected void ScreenOutput(String s) {
synchronized(_outputLock) {
if( _lastScreenOutput < 0 )
_lastScreenOutput = System.currentTimeMillis();
if( _firstScreenOutput < 0 )
_firstScreenOutput = _lastScreenOutput;
Date now = new Date();
long delta = now.getTime() - _lastScreenOutput;
double sec = delta / 1000.0;
delta = now.getTime() - _firstScreenOutput;
double totalsec = delta / 1000.0;
_lastScreenOutput = now.getTime();
String text = String.format("%s (delta %.3f, total %.3f sec)\n%s\n\n",
_dateformat.format(now),
sec,
totalsec,
s);
tv.append(text);
tv.invalidate();
Log.d(TAG,"ScreenOutput: " + text);
// Now scroll to the bottom
sv.post(new Runnable() {
public void run() {
sv.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
}
/**
* this will be called when we receive a chat line.
* It is executed in the UI thread.
*/
private Handler _handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String text = (String) msg.obj;
ScreenOutput(text);
msg.obj = null;
msg = null;
}
};
/**
* From ChatCallback, when we get a message from CCN
*/
public void postToUI(String message) {
Message msg = Message.obtain();
msg.obj = message;
_handler.sendMessage(msg);
}
} |
package com.facebook.fresco.animation.bitmap;
import javax.annotation.Nullable;
import java.lang.annotation.Retention;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntDef;
import android.support.annotation.IntRange;
import com.facebook.common.references.CloseableReference;
import com.facebook.fresco.animation.backend.AnimationBackend;
import com.facebook.fresco.animation.backend.AnimationBackendDelegateWithInactivityCheck;
import com.facebook.fresco.animation.backend.AnimationInformation;
import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory;
import static java.lang.annotation.RetentionPolicy.SOURCE;
/**
* Bitmap animation backend that renders bitmap frames.
*
* The given {@link BitmapFrameCache} is used to cache frames and create new bitmaps. {@link
* AnimationInformation} defines the main animation parameters, like frame and loop count. {@link
* BitmapFrameRenderer} is used to render frames to the bitmaps aquired from the {@link
* BitmapFrameCache}.
*/
public class BitmapAnimationBackend implements AnimationBackend,
AnimationBackendDelegateWithInactivityCheck.InactivityListener {
public interface FrameListener {
/**
* Called when the backend started drawing the given frame.
*
* @param backend the backend
* @param frameNumber the frame number to be drawn
*/
void onDrawFrameStart(BitmapAnimationBackend backend, int frameNumber);
/**
* Called when the given frame has been drawn.
*
* @param backend the backend
* @param frameNumber the frame number that has been drawn
* @param frameType the {@link FrameType} that has been drawn
*/
void onFrameDrawn(BitmapAnimationBackend backend, int frameNumber, @FrameType int frameType);
/**
* Called when no bitmap could be drawn by the backend for the given frame number.
*
* @param backend the backend
* @param frameNumber the frame number that could not be drawn
*/
void onFrameDropped(BitmapAnimationBackend backend, int frameNumber);
}
/**
* Frame type that has been drawn. Can be used for logging.
*/
@Retention(SOURCE)
@IntDef({
FRAME_TYPE_CACHED,
FRAME_TYPE_REUSED,
FRAME_TYPE_CREATED,
FRAME_TYPE_FALLBACK,
})
public @interface FrameType {
}
public static final int FRAME_TYPE_CACHED = 0;
public static final int FRAME_TYPE_REUSED = 1;
public static final int FRAME_TYPE_CREATED = 2;
public static final int FRAME_TYPE_FALLBACK = 3;
private final PlatformBitmapFactory mPlatformBitmapFactory;
private final BitmapFrameCache mBitmapFrameCache;
private final AnimationInformation mAnimationInformation;
private final BitmapFrameRenderer mBitmapFrameRenderer;
private final Paint mPaint;
@Nullable
private Rect mBounds;
private int mBitmapWidth;
private int mBitmapHeight;
private Bitmap.Config mBitmapConfig = Bitmap.Config.ARGB_8888;
@Nullable
private FrameListener mFrameListener;
public BitmapAnimationBackend(
PlatformBitmapFactory platformBitmapFactory,
BitmapFrameCache bitmapFrameCache,
AnimationInformation animationInformation,
BitmapFrameRenderer bitmapFrameRenderer) {
mPlatformBitmapFactory = platformBitmapFactory;
mBitmapFrameCache = bitmapFrameCache;
mAnimationInformation = animationInformation;
mBitmapFrameRenderer = bitmapFrameRenderer;
mPaint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
updateBitmapDimensions();
}
/**
* Set the bitmap config to be used to create new bitmaps.
*
* @param bitmapConfig the bitmap config to be used
*/
public void setBitmapConfig(Bitmap.Config bitmapConfig) {
mBitmapConfig = bitmapConfig;
}
public void setFrameListener(@Nullable FrameListener frameListener) {
mFrameListener = frameListener;
}
@Override
public int getFrameCount() {
return mAnimationInformation.getFrameCount();
}
@Override
public int getFrameDurationMs(int frameNumber) {
return mAnimationInformation.getFrameDurationMs(frameNumber);
}
@Override
public int getLoopCount() {
return mAnimationInformation.getLoopCount();
}
@Override
public boolean drawFrame(
Drawable parent,
Canvas canvas,
int frameNumber) {
if (mFrameListener != null) {
mFrameListener.onDrawFrameStart(this, frameNumber);
}
boolean drawn = drawFrameOrFallback(canvas, frameNumber, FRAME_TYPE_CACHED);
// We could not draw anything
if (!drawn && mFrameListener != null) {
mFrameListener.onFrameDropped(this, frameNumber);
}
return drawn;
}
private boolean drawFrameOrFallback(Canvas canvas, int frameNumber, @FrameType int frameType) {
CloseableReference<Bitmap> bitmapReference = null;
boolean drawn = false;
int nextFrameType = -1;
try {
switch (frameType) {
case FRAME_TYPE_CACHED:
bitmapReference = mBitmapFrameCache.getCachedFrame(frameNumber);
drawn = drawBitmapAndCache(frameNumber, bitmapReference, canvas, FRAME_TYPE_CACHED);
nextFrameType = FRAME_TYPE_REUSED;
break;
case FRAME_TYPE_REUSED:
bitmapReference =
mBitmapFrameCache.getBitmapToReuseForFrame(frameNumber, mBitmapWidth, mBitmapHeight);
// Try to render the frame and draw on the canvas immediately after
drawn = renderFrameInBitmap(frameNumber, bitmapReference) &&
drawBitmapAndCache(frameNumber, bitmapReference, canvas, FRAME_TYPE_REUSED);
nextFrameType = FRAME_TYPE_CREATED;
break;
case FRAME_TYPE_CREATED:
bitmapReference =
mPlatformBitmapFactory.createBitmap(mBitmapWidth, mBitmapHeight, mBitmapConfig);
// Try to render the frame and draw on the canvas immediately after
drawn = renderFrameInBitmap(frameNumber, bitmapReference) &&
drawBitmapAndCache(frameNumber, bitmapReference, canvas, FRAME_TYPE_CREATED);
nextFrameType = FRAME_TYPE_FALLBACK;
break;
case FRAME_TYPE_FALLBACK:
bitmapReference = mBitmapFrameCache.getFallbackFrame(frameNumber);
drawn = drawBitmapAndCache(frameNumber, bitmapReference, canvas, FRAME_TYPE_FALLBACK);
break;
default:
return false;
}
} finally {
CloseableReference.closeSafely(bitmapReference);
}
if (drawn || nextFrameType == -1) {
return drawn;
} else {
return drawFrameOrFallback(canvas, frameNumber, nextFrameType);
}
}
@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
}
@Override
public void setBounds(@Nullable Rect bounds) {
mBounds = bounds;
mBitmapFrameRenderer.setBounds(bounds);
updateBitmapDimensions();
}
@Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
@Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
@Override
public int getSizeInBytes() {
return mBitmapFrameCache.getSizeInBytes();
}
@Override
public void clear() {
mBitmapFrameCache.clear();
}
@Override
public void onInactive() {
clear();
}
private void updateBitmapDimensions() {
// Calculate the correct bitmap dimensions
mBitmapWidth = mBitmapFrameRenderer.getIntrinsicWidth();
if (mBitmapWidth == INTRINSIC_DIMENSION_UNSET) {
mBitmapWidth = mBounds == null ? INTRINSIC_DIMENSION_UNSET : mBounds.width();
}
mBitmapHeight = mBitmapFrameRenderer.getIntrinsicHeight();
if (mBitmapHeight == INTRINSIC_DIMENSION_UNSET) {
mBitmapHeight = mBounds == null ? INTRINSIC_DIMENSION_UNSET : mBounds.height();
}
}
/**
* Try to render the frame to the given target bitmap. If the rendering fails, the target bitmap
* reference will be closed and false is returned. If rendering succeeds, the target bitmap
* reference can be drawn and has to be manually closed after drawing has been completed.
*
* @param frameNumber the frame number to render
* @param targetBitmap the target bitmap
* @return true if rendering successful
*/
private boolean renderFrameInBitmap(
int frameNumber,
@Nullable CloseableReference<Bitmap> targetBitmap) {
if (!CloseableReference.isValid(targetBitmap)) {
return false;
}
// Render the image
boolean frameRendered =
mBitmapFrameRenderer.renderFrame(frameNumber, targetBitmap.get());
if (!frameRendered) {
CloseableReference.closeSafely(targetBitmap);
}
return frameRendered;
}
/**
* Helper method that draws the given bitmap on the canvas respecting the bounds (if set).
*
* If rendering was successful, it notifies the cache that the frame has been rendered with the
* given bitmap. In addition, it will notify the {@link FrameListener} if set.
*
* @param frameNumber the current frame number passed to the cache
* @param bitmapReference the bitmap to draw
* @param canvas the canvas to draw an
* @param frameType the {@link FrameType} to be rendered
* @return true if the bitmap has been drawn
*/
private boolean drawBitmapAndCache(
int frameNumber,
@Nullable CloseableReference<Bitmap> bitmapReference,
Canvas canvas,
@FrameType int frameType) {
if (!CloseableReference.isValid(bitmapReference)) {
return false;
}
if (mBounds == null) {
canvas.drawBitmap(bitmapReference.get(), 0f, 0f, mPaint);
} else {
canvas.drawBitmap(bitmapReference.get(), null, mBounds, mPaint);
}
// The callee has to clone the reference if it needs to hold on to the bitmap
mBitmapFrameCache.onFrameRendered(
frameNumber,
bitmapReference,
frameType);
if (mFrameListener != null) {
mFrameListener.onFrameDrawn(this, frameNumber, frameType);
}
return true;
}
} |
package com.continuuity.internal.app.scheduler;
import com.continuuity.app.Id;
import com.continuuity.app.services.AppFabricService;
import com.continuuity.app.services.AuthToken;
import com.continuuity.app.services.EntityType;
import com.continuuity.app.services.ProgramId;
import com.continuuity.app.services.ProgramRunRecord;
import com.continuuity.app.services.ScheduleId;
import com.continuuity.app.store.Store;
import com.continuuity.internal.app.services.AppFabricServer;
import com.continuuity.internal.app.store.MDTBasedStore;
import com.continuuity.test.internal.TestHelper;
import com.continuuity.weave.filesystem.LocalLocationFactory;
import com.google.common.collect.Maps;
import junit.framework.Assert;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Test schedule run, pause and resume.
*/
public class ScheduleRunPauseResumeTests {
@Test
public void testRunner() throws Exception {
AppFabricServer appFabricServer = TestHelper.getInjector().getInstance(AppFabricServer.class);
AuthToken token = new AuthToken("token");
try {
appFabricServer.startAndWait();
AppFabricService.Iface appFabricService = appFabricServer.getService();
appFabricService.reset(TestHelper.DUMMY_AUTH_TOKEN, "developer");
TestHelper.deployApplication(appFabricService, new LocalLocationFactory(),
Id.Account.from("developer"), token, "SampleApplication",
"SampleApp", SampleApplication.class);
ProgramId id = new ProgramId("developer", "SampleApp", "SampleWorkflow");
id.setType(EntityType.WORKFLOW);
int count = 0;
int workflowRunCount = 0;
//Wait for 10 seconds or until there is one run of the workflow
while (count <= 10 && workflowRunCount == 0) {
count++;
List<ProgramRunRecord> result = appFabricService.getHistory(id, 0,
Long.MAX_VALUE, Integer.MAX_VALUE);
workflowRunCount = result.size();
TimeUnit.SECONDS.sleep(1L);
}
Assert.assertTrue(workflowRunCount >= 1);
List<ScheduleId> scheduleIds = appFabricService.getSchedules(token, id);
Assert.assertEquals(1, scheduleIds.size());
ScheduleId scheduleId = scheduleIds.get(0);
String scheduleState = appFabricService.getScheduleState(new ScheduleId(scheduleId));
Assert.assertEquals("SCHEDULED", scheduleState);
appFabricService.suspendSchedule(token, scheduleId);
TimeUnit.SECONDS.sleep(2L);
//Get the schedule state
scheduleState = appFabricService.getScheduleState(new ScheduleId(scheduleId));
Assert.assertEquals("SUSPENDED", scheduleState);
//get the current number runs and check if after a period of time there are no new runs.
int numWorkFlowRuns = appFabricService.getHistory(id, Long.MIN_VALUE,
Long.MAX_VALUE, Integer.MAX_VALUE).size();
TimeUnit.SECONDS.sleep(10L);
int numWorkFlowRunsAfterWait = appFabricService.getHistory(id, Long.MIN_VALUE,
Long.MAX_VALUE, Integer.MAX_VALUE).size();
Assert.assertEquals(numWorkFlowRuns, numWorkFlowRunsAfterWait);
appFabricService.resumeSchedule(token, scheduleId);
int numWorkflowRunAfterResume = 0;
scheduleState = appFabricService.getScheduleState(new ScheduleId(scheduleId));
Assert.assertEquals("SCHEDULED", scheduleState);
count = 0;
while (count <= 10 && numWorkflowRunAfterResume == 0){
count++;
numWorkflowRunAfterResume = appFabricService.getHistory(id, Long.MIN_VALUE,
Long.MAX_VALUE, Integer.MAX_VALUE).size();
TimeUnit.SECONDS.sleep(1L);
}
Assert.assertTrue(numWorkflowRunAfterResume >= 1);
Map<String, String> args = Maps.newHashMap();
args.put("Key1", "val1");
args.put("Key2", "val2");
appFabricService.storeRuntimeArguments(token, id, args);
Store store = TestHelper.getInjector().getInstance(MDTBasedStore.class);
Map<String, String> argsRead = store.getRunArguments(Id.Program.from("developer", "SampleApp",
"SampleWorkflow"));
Assert.assertEquals(2, argsRead.size());
Assert.assertEquals("val1", argsRead.get("Key1"));
Assert.assertEquals("val2", argsRead.get("Key2"));
Map<String, String> emptyArgs = store.getRunArguments(Id.Program.from("Br", "Ba", "d"));
Assert.assertEquals(0, emptyArgs.size());
//Test a non existing schedule
scheduleState = appFabricService.getScheduleState(new ScheduleId("notfound"));
Assert.assertEquals("NOT_FOUND", scheduleState);
} finally {
appFabricServer.stopAndWait();
}
}
} |
package org.csstudio.logbook.ui;
import java.io.IOException;
import org.csstudio.logbook.LogEntry;
import org.csstudio.logbook.LogEntryBuilder;
import org.csstudio.logbook.LogbookBuilder;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* @author shroffk
*
*/
public class LogEntryWidgetTest extends ApplicationWindow {
public LogEntryWidgetTest() {
super(null);
addToolBar(SWT.FLAT | SWT.WRAP);
addMenuBar();
addStatusLine();
}
/**
* Create contents of the application window.
*
* @param parent
*/
@Override
protected Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout(5, false));
final LogEntryWidget logEntryWidget = new LogEntryWidget(container,
SWT.WRAP, true, false);
logEntryWidget.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
true, 5, 1));
Button btnNewButton = new Button(container, SWT.NONE);
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
LogEntry logEntry;
try {
logEntry = LogEntryBuilder
.withText("SomeText\nsome more text")
.owner("shroffk")
.addLogbook(LogbookBuilder.logbook("test"))
.addLogbook(LogbookBuilder.logbook("test2"))
.addLogbook(LogbookBuilder.logbook("test3"))
.addLogbook(LogbookBuilder.logbook("test4"))
.addLogbook(LogbookBuilder.logbook("test5"))
.build();
logEntryWidget.setLogEntry(logEntry);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setText("test logEntry");
Button btnNewButton_1 = new Button(container, SWT.NONE);
btnNewButton_1.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
LogEntry logEntry;
try {
logEntry = LogEntryBuilder.withText("SomeText")
.owner("shroffk")
.addLogbook(LogbookBuilder.logbook("test"))
.addLogbook(LogbookBuilder.logbook("test2"))
.build();
logEntryWidget.setLogEntry(logEntry);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton_1.setText("simple Entry");
return container;
}
/**
* Launch the application.
*
* @param args
*/
public static void main(String args[]) {
try {
LogEntryWidgetTest window = new LogEntryWidgetTest();
window.setBlockOnOpen(true);
window.open();
Display.getCurrent().dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Configure the shell.
*
* @param newShell
*/
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("New Application");
}
/**
* Return the initial size of the window.
*/
@Override
protected Point getInitialSize() {
return new Point(473, 541);
}
} |
package org.jnosql.artemis.configuration;
import org.jnosql.artemis.ConfigurationUnit;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import javax.json.JsonException;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.logging.Logger;
import static java.util.Objects.nonNull;
/**
* The {@link ConfigurableReader} to JSON
*/
@Named("json")
@ApplicationScoped
class ConfigurableReaderJSON implements ConfigurableReader {
private static final Jsonb JSONB = JsonbBuilder.create();
private static final Logger LOGGER = Logger.getLogger(ConfigurableJSON.class.getName());
private final Map<String, List<Configurable>> cache = new ConcurrentHashMap<>();
private static final Type TYPE = new ArrayList<ConfigurableJSON>() {}.getClass().getGenericSuperclass();
@Override
public List<Configurable> read(Supplier<InputStream> stream, ConfigurationUnit annotation) throws NullPointerException, ConfigurationException {
List<Configurable> configurations = cache.get(annotation.fileName());
if (nonNull(configurations)) {
LOGGER.info("Loading the configuration file from the cache file: " + annotation.fileName());
return configurations;
}
try {
configurations = JSONB.fromJson(stream.get(), TYPE);
cache.put(annotation.fileName(), configurations);
return configurations;
} catch (JsonException exception) {
throw new ConfigurationException("An error when read the JSON file: " + annotation.fileName()
, exception);
}
}
} |
package org.ovirt.engine.core.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import org.ovirt.engine.core.common.interfaces.ErrorTranslator;
public class ErrorTranslatorTest {
private static final String TEST_KEY_NO_REPLACEMENT = "TEST_KEY_NO_REPLACEMENT";
private static final String TEST_KEY_WITH_REPLACEMENT = "TEST_KEY_WITH_REPLACEMENT";
private static final String FILENAME = "TestAppErrors";
private static final String FILENAME_WITH_SUFFIX = FILENAME + ".properties";
@Test
public void testNoStringSubstitutionWithoutSuffix() {
doTestNoStringSubstitution(FILENAME);
}
@Test
public void testNoStringSubstitutionWithSuffix() {
doTestNoStringSubstitution(FILENAME_WITH_SUFFIX);
}
private static void doTestNoStringSubstitution(String name) {
ErrorTranslator et = new ErrorTranslatorImpl(name);
String error = et.TranslateErrorTextSingle(TEST_KEY_NO_REPLACEMENT);
assertEquals("String should equal", "VM not found", error);
}
@Test
public void testNoStringSubstitutionWithList() {
ErrorTranslator et = new ErrorTranslatorImpl(FILENAME);
List<String> error = et.TranslateErrorText(Arrays.asList(TEST_KEY_NO_REPLACEMENT));
assertTrue("Size", error.size() == 1);
assertEquals("String should equal", "VM not found", error.get(0));
}
@Test
public void testStringSubstitutionWithList() {
ErrorTranslator et = new ErrorTranslatorImpl(FILENAME);
List<String> error = et.TranslateErrorText(Arrays.asList(TEST_KEY_WITH_REPLACEMENT,
"$action SOMEACTION", "$type SOME Type"));
String result = "Cannot SOMEACTION SOME Type. VM's Image doesn't exist.";
assertTrue("Size", error.size() == 1);
assertEquals("String should equal", result, error.get(0));
}
@Test
public void testLocaleSpecificWithoutSuffix() {
doTestLocaleSpecific(FILENAME);
}
@Test
public void testLocaleSpecificWithSuffix() {
doTestLocaleSpecific(FILENAME_WITH_SUFFIX);
}
private static void doTestLocaleSpecific(String name) {
Locale locale = Locale.getDefault();
try {
Locale.setDefault(Locale.GERMAN);
ErrorTranslator et = new ErrorTranslatorImpl(name);
List<String> errors = et.TranslateErrorText(Arrays.asList(TEST_KEY_NO_REPLACEMENT));
assertEquals("Unexpected Size", 1, errors.size());
assertEquals("String should equal", "Desktop nicht gefunden", errors.get(0));
String error = et.TranslateErrorTextSingle(TEST_KEY_NO_REPLACEMENT, Locale.GERMAN);
assertEquals("String should equal", "Desktop nicht gefunden", error);
} finally {
Locale.setDefault(locale);
}
}
@Test
public void testLocaleOverrideWithoutSuffix() {
doTestLocaleOverride(FILENAME);
}
@Test
public void testLocaleOverrideWithSuffix() {
doTestLocaleOverride(FILENAME_WITH_SUFFIX);
}
private static void doTestLocaleOverride(String name) {
ErrorTranslator et = new ErrorTranslatorImpl(name);
List<String> errors = et.TranslateErrorText(Arrays.asList(TEST_KEY_NO_REPLACEMENT), Locale.ITALIAN);
assertEquals("Unexpected Size", 1, errors.size());
assertEquals("String should equal", "Impossibile trovare il desktop", errors.get(0));
String error = et.TranslateErrorTextSingle(TEST_KEY_NO_REPLACEMENT, Locale.ITALIAN);
assertEquals("String should equal", "Impossibile trovare il desktop", error);
}
} |
package org.openhab.core.library.types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class TimeType extends CalendarType {
private final static SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("EEE, hh:mm:ss", Locale.US);
public TimeType(Calendar calendar) {
super(calendar);
}
public TimeType(String calendarValue) {
super(calendarValue);
}
@Override
protected DateFormat getFormatter() {
return TIME_FORMATTER;
}
public static TimeType valueOf(String value) {
return new TimeType(value);
}
} |
package gov.nih.nci.cabig.caaers.api.impl;
import gov.nih.nci.cabig.caaers.CaaersSystemException;
import gov.nih.nci.cabig.caaers.api.AbstractImportService;
import gov.nih.nci.cabig.caaers.dao.OrganizationDao;
import gov.nih.nci.cabig.caaers.dao.ParticipantDao;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.dao.query.ParticipantQuery;
import gov.nih.nci.cabig.caaers.domain.Identifier;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier;
import gov.nih.nci.cabig.caaers.domain.Participant;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyParticipantAssignment;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.domain.ajax.StudySearchableAjaxableDomainObject;
import gov.nih.nci.cabig.caaers.event.EventFactory;
import gov.nih.nci.cabig.caaers.integration.schema.common.CaaersServiceResponse;
import gov.nih.nci.cabig.caaers.integration.schema.common.OrganizationType;
import gov.nih.nci.cabig.caaers.integration.schema.common.ResponseDataType;
import gov.nih.nci.cabig.caaers.integration.schema.common.Status;
import gov.nih.nci.cabig.caaers.integration.schema.common.WsError;
import gov.nih.nci.cabig.caaers.integration.schema.participant.AssignmentType;
import gov.nih.nci.cabig.caaers.integration.schema.participant.ParticipantRef;
import gov.nih.nci.cabig.caaers.integration.schema.participant.ParticipantType;
import gov.nih.nci.cabig.caaers.integration.schema.participant.ParticipantType.Assignments;
import gov.nih.nci.cabig.caaers.integration.schema.participant.Participants;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Message;
import gov.nih.nci.cabig.caaers.service.ParticipantImportServiceImpl;
import gov.nih.nci.cabig.caaers.service.migrator.ParticipantConverter;
import gov.nih.nci.cabig.caaers.service.synchronizer.ParticipantSynchronizer;
import gov.nih.nci.cabig.caaers.validation.ValidationErrors;
import gov.nih.nci.security.util.StringUtilities;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.transaction.annotation.Transactional;
public class ParticipantServiceImpl extends AbstractImportService implements ApplicationContextAware {
private static Log logger = LogFactory.getLog(ParticipantServiceImpl.class);
private ApplicationContext applicationContext;
private MessageSource messageSource;
private ParticipantDao participantDao;
private StudyDao studyDao;
private OrganizationDao organizationDao;
public void setOrganizationDao(OrganizationDao organizationDao) {
this.organizationDao = organizationDao;
}
private ParticipantImportServiceImpl participantImportServiceImpl;
private ParticipantConverter participantConverter;
private ParticipantSynchronizer participantSynchronizer;
//private DomainObjectValidator domainObjectValidator;
private Validator validator;
private EventFactory eventFactory;
/**
* Method exisits only to be called from ImportController
*/
public DomainObjectImportOutcome<Participant> processParticipant(ParticipantType xmlParticipant){
logger.info("Entering processParticipant() in ParticipantServiceImpl");
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
DomainObjectImportOutcome<Participant> participantImportOutcome = null;
Participant participant = new Participant();
try{
participantConverter.convertParticipantDtoToParticipantDomain(xmlParticipant, participant);
}catch(CaaersSystemException caEX){
participantImportOutcome = new DomainObjectImportOutcome<Participant>();
logger.error("ParticipantDto to ParticipantDomain Conversion Failed " , caEX);
participantImportOutcome.addErrorMessage("ParticipantDto to ParticipantDomain Conversion Failed " , DomainObjectImportOutcome.Severity.ERROR);
}
if(participantImportOutcome == null){
participantImportOutcome = participantImportServiceImpl.importParticipant(participant);
if(participantImportOutcome.isSavable()){
Participant dbParticipant = fetchParticipantByAssignment(participantImportOutcome.getImportedDomainObject(), caaersServiceResponse);
if(dbParticipant != null){
logger.info("Participant Exists in caAERS trying to Update");
participantSynchronizer.migrate(dbParticipant, participantImportOutcome.getImportedDomainObject(), participantImportOutcome);
participantImportOutcome.setImportedDomainObject(dbParticipant);
logger.info("Participant in caAERS Updated");
}else if (caaersServiceResponse.getServiceResponse().getStatus() == Status.FAILED_TO_PROCESS) {
participantImportOutcome.addErrorMessage(caaersServiceResponse.getServiceResponse().getMessage(), DomainObjectImportOutcome.Severity.ERROR);
}else{
logger.info("New Participant to be Created");
}
}
}
logger.info("Leaving processParticipant() in ParticipantServiceImpl");
return participantImportOutcome;
}
public String getStudySubjectIdentifierFromInXML(ParticipantType xmlParticipant) {
String identifier = null;
Assignments assignments = xmlParticipant.getAssignments();
for(AssignmentType assignmentType : assignments.getAssignment()){
identifier = assignmentType.getStudySubjectIdentifier();
if(StringUtils.isNotEmpty(identifier) ){
return identifier;
}
}
return null;
}
public Identifier getStudyIdentifierFromInXML(ParticipantType xmlParticipant) {
Identifier identifier = null;
Assignments assignments = xmlParticipant.getAssignments();
for(AssignmentType assignmentType : assignments.getAssignment()){
identifier = new Identifier();
identifier.setType(assignmentType.getStudySite().getStudy().getIdentifiers().getIdentifier().getType().value());
identifier.setValue(assignmentType.getStudySite().getStudy().getIdentifiers().getIdentifier().getValue());
return identifier;
}
return identifier;
}
public List<StudySearchableAjaxableDomainObject> getAuthorizedStudies(Identifier identifier) {
List<StudySearchableAjaxableDomainObject> authorizedStudies = new ArrayList<StudySearchableAjaxableDomainObject>();
authorizedStudies = getAuthorizedStudies(identifier.getValue());
return authorizedStudies;
}
private String checkAuthorizedOrganizations (ParticipantType xmlParticipant) {
Assignments assignments = xmlParticipant.getAssignments();
for(AssignmentType assignmentType : assignments.getAssignment()){
String organizationName = assignmentType.getStudySite().getOrganization().getName();
String organizationNciInstituteCode = assignmentType.getStudySite().getOrganization().getNciInstituteCode();
List<Organization> organizations = new ArrayList<Organization>();
if (StringUtilities.isBlank(organizationNciInstituteCode)) {
//System.out.println("looking by name");
organizations = getAuthorizedOrganizationsByNameOrNciId(organizationName,null);
} else {
//System.out.println("looking by id");
organizations = getAuthorizedOrganizationsByNameOrNciId(null,organizationNciInstituteCode);
}
if (organizations.size() == 0 ) {
return organizationNciInstituteCode + " : " + organizationName;
}
}
return "ALL_ORGS_AUTH";
}
/**
* validates xml input and fetches participant based on study identifier and study subject identifier
* @param studySubjectIdentifier - string
* @param studyIdentifier - String
* @param xmlParticipant - xml participant object
* @param caaersServiceResponse - response
* @return Participant - returns retrieve participant, if not returns null, with response filled with appropriate messages
*/
private Participant validateInputsAndFetchParticipant(String studySubjectIdentifier, Identifier studyIdentifier, ParticipantType xmlParticipant,
CaaersServiceResponse caaersServiceResponse) {
if (studyIdentifier != null ) {
Study study = fetchStudy(studyIdentifier);
if(study == null){
createNoStudyFoundResponse(caaersServiceResponse,studyIdentifier);
return null;
}
List<StudySearchableAjaxableDomainObject> authorizedStudies = getAuthorizedStudies(studyIdentifier);
if(authorizedStudies.size() == 0) {
createNoStudyAuthorizationResponse(caaersServiceResponse, studyIdentifier);
return null;
}
}
String errorMsg = checkAuthorizedOrganizations(xmlParticipant);
if(!errorMsg.equals("ALL_ORGS_AUTH")) {
createNoOrganizationAuthorizationResponse(caaersServiceResponse, errorMsg);
return null;
}
String subjectId = xmlParticipant.getIdentifiers().getOrganizationAssignedIdentifier().get(0).getValue();
OrganizationType regSite = xmlParticipant.getAssignments().getAssignment().get(0).getStudySite().getOrganization();
// Get the participant if exists
Participant dbParticipant = fetchParticipantBySubjectIdAndSite(subjectId,regSite.getNciInstituteCode());
if(dbParticipant != null && dbParticipant.getAssignments().size() > 0){
logger.debug("Participant with subject id "+subjectId+" exists, checking for exisint registration on study "+studyIdentifier.getValue());
// Check if there are registrations on this study already
StudyParticipantAssignment studyAssignment = dbParticipant.getAssignments().get(0);
if (checkStudyId(studyAssignment.getStudySite().getStudy(),studyIdentifier) &&
!studySubjectIdentifier.equals(studyAssignment.getStudySubjectIdentifier())){
logger.error("Subject subject identifier "+ studyAssignment.getStudySubjectIdentifier()+" already exists on study "+ studyIdentifier.getValue()+" returning error WS_PMS_019");
populateError(caaersServiceResponse, "WS_PMS_019", messageSource.getMessage("WS_PMS_019", new String[]{subjectId,studyIdentifier.getValue(),studyAssignment.getStudySubjectIdentifier()},"",Locale.getDefault()));
return null;
}
}
return fetchParticipantByAssignment(studySubjectIdentifier, studyIdentifier, caaersServiceResponse);
}
/**
* Check whether the study has the given identifier
* @param study to check
* @param id
* @return
*/
private boolean checkStudyId(Study study, Identifier id){
List<Identifier> identifiers = study.getIdentifiers();
for (Iterator<Identifier> iterator = identifiers.iterator(); iterator.hasNext();) {
Identifier identifier = (Identifier) iterator.next();
if(id.getType().equals(identifier.getType()) && id.getValue().equals(identifier.getValue())){
return true;
}
}
return false;
}
/**
* converts xml participant to the DomainImportOutcome<Participant>
* @param xmlParticipant - xml participant object
* @param studySubjectIdentifier - string
* @param caaersServiceResponse - response
* @param processStr - should be created/updated/deleted to be used in response message
* @return converted and imported domain object
*/
private DomainObjectImportOutcome<Participant> convertToImportedDomainObject(ParticipantType xmlParticipant, String studySubjectIdentifier,
CaaersServiceResponse caaersServiceResponse, String processStr) {
Participant participant = new Participant();
try{
participantConverter.convertParticipantDtoToParticipantDomain(xmlParticipant, participant);
}catch(CaaersSystemException caEX){
String message = messageSource.getMessage("WS_PMS_005", new String[] { caEX.getMessage() }, "", Locale
.getDefault());
logger.error(message, caEX);
populateError(caaersServiceResponse, "WS_PMS_005", message);
return null;
}
DomainObjectImportOutcome<Participant> participantImportOutcome =
participantImportServiceImpl.importParticipant(participant);
Participant importedDomainObject = participantImportOutcome.getImportedDomainObject();
//List<String> errors = domainObjectValidator.validate(importedDomainObject);
Set<ConstraintViolation<Participant>> constraintViolations = validator.validate(importedDomainObject, Default.class);
if( !participantImportOutcome.isSavable() || constraintViolations.size() > 0) {
String errMessage = messageSource.getMessage("WS_PMS_007",
new String[] { importedDomainObject.getFirstName(), importedDomainObject.getLastName(), importedDomainObject.getPrimaryIdentifier().getValue(),
studySubjectIdentifier, processStr },
"", Locale.getDefault());
populateError(caaersServiceResponse, "WS_PMS_007", errMessage);
logger.info(errMessage);
List<String> messages = new ArrayList<String>();
for(Message message : participantImportOutcome.getMessages()){
messages.add(message.getMessage());
}
String valErrmsg = null;
for (ConstraintViolation<Participant> violation : constraintViolations) {
valErrmsg = violation.getMessage()
+ " (" + violation.getPropertyPath()
+ ") in " + participant.getClass().getSimpleName()
+ "(" + participant.getFullName() + ")";
messages.add(valErrmsg);
}
Helper.populateErrorOutcome(caaersServiceResponse, null, null, null, messages);
return null;
}
return participantImportOutcome;
}
@Transactional(readOnly=false)
public CaaersServiceResponse createParticipant(
Participants xmlParticipants) {
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
ParticipantType xmlParticipant = xmlParticipants.getParticipant().get(0);
Identifier studyIdentifier = getStudyIdentifierFromInXML(xmlParticipant);
String studySubjectIdentifier = getStudySubjectIdentifierFromInXML(xmlParticipant);
Participant dbParticipant = validateInputsAndFetchParticipant(studySubjectIdentifier, studyIdentifier, xmlParticipant, caaersServiceResponse);
if( dbParticipant != null) {
String message = messageSource.getMessage("WS_PMS_004", new String[] { studySubjectIdentifier, studyIdentifier.getValue() }, "", Locale
.getDefault());
logger.error(message);
populateError(caaersServiceResponse, "WS_PMS_004", message);
return caaersServiceResponse;
} else {
//remove the error message for participant not found, as this is create flow
List<WsError> wsErrors = caaersServiceResponse.getServiceResponse().getWsError();
if(wsErrors != null && wsErrors.size() == 1 && "WS_PMS_003".equals(wsErrors.get(0).getErrorCode()) ) {
wsErrors.remove(0);
Helper.populateMessage(caaersServiceResponse, "");
}
}
validateAssignmentSite(caaersServiceResponse, xmlParticipant, null);
if(caaersServiceResponse.getServiceResponse().getStatus() == Status.FAILED_TO_PROCESS ) {
return caaersServiceResponse;
}
//resetting the response object
caaersServiceResponse = Helper.createResponse();
DomainObjectImportOutcome<Participant> participantImportOutcome =
convertToImportedDomainObject(xmlParticipant, studySubjectIdentifier, caaersServiceResponse, "created");
if(participantImportOutcome != null) {
Participant importedDomainObject = participantImportOutcome.getImportedDomainObject();
participantDao.save(importedDomainObject);
String message = messageSource.getMessage("WS_PMS_006",
new String[] { importedDomainObject.getFirstName(), importedDomainObject.getLastName(),importedDomainObject.getPrimaryIdentifier().getValue(), studySubjectIdentifier },
"", Locale.getDefault());
Helper.populateMessage(caaersServiceResponse, message);
logger.info(message);
if(eventFactory != null) {
eventFactory.publishEntityModifiedEvent(importedDomainObject, false);
}
}
return caaersServiceResponse;
}
@Transactional(readOnly=false)
public CaaersServiceResponse updateParticipant(
Participants xmlParticipants) {
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
ParticipantType xmlParticipant = xmlParticipants.getParticipant().get(0);
Identifier studyIdentifier = getStudyIdentifierFromInXML(xmlParticipant);
String studySubjectIdentifier = getStudySubjectIdentifierFromInXML(xmlParticipant);
Participant dbParticipant = validateInputsAndFetchParticipant(studySubjectIdentifier, studyIdentifier, xmlParticipant, caaersServiceResponse);
if( dbParticipant == null) {
return caaersServiceResponse;
}
validateAssignmentSite(caaersServiceResponse, xmlParticipant, dbParticipant);
if(caaersServiceResponse.getServiceResponse().getStatus() == Status.FAILED_TO_PROCESS) {
return caaersServiceResponse;
}
//resetting the response object
caaersServiceResponse = Helper.createResponse();
DomainObjectImportOutcome<Participant> participantImportOutcome =
convertToImportedDomainObject(xmlParticipant, studySubjectIdentifier, caaersServiceResponse, "updated");
if(participantImportOutcome != null){
Participant importedDomainObject = participantImportOutcome.getImportedDomainObject();
participantSynchronizer.migrate(dbParticipant, participantImportOutcome.getImportedDomainObject(), participantImportOutcome);
participantImportOutcome.setImportedDomainObject(dbParticipant);
participantDao.save(participantImportOutcome.getImportedDomainObject());
String message = messageSource.getMessage("WS_PMS_008",
new String[] { importedDomainObject.getFirstName(), importedDomainObject.getLastName(), studySubjectIdentifier },
"", Locale.getDefault());
Helper.populateMessage(caaersServiceResponse, message);
logger.info(message);
if(eventFactory != null) {
eventFactory.publishEntityModifiedEvent(importedDomainObject, false);
}
}
return caaersServiceResponse;
}
private void validateAssignmentSite(CaaersServiceResponse caaersServiceResponse, ParticipantType xmlParticipant,
Participant dbParticipant) {
OrganizationType xmlOrg = xmlParticipant.getAssignments().getAssignment().get(0).getStudySite().getOrganization();
if (StringUtils.isEmpty(xmlOrg.getName()) || StringUtils.isEmpty(xmlOrg.getNciInstituteCode())
|| ":".equals(xmlOrg.getNciInstituteCode().trim())) {
String message = messageSource.getMessage("WS_PMS_017", new String[] {}, "", Locale
.getDefault());
logger.error(message);
populateError(caaersServiceResponse, "WS_PMS_017", message);
}
if (dbParticipant == null) { //for create flow
return;
}
Organization dbOrg = dbParticipant.getAssignments().get(0).getStudySite().getOrganization();
if ( (dbOrg.getName() != null && !dbOrg.getName().equals(xmlOrg.getName()) )
|| (dbOrg.getNciInstituteCode() != null && !dbOrg.getNciInstituteCode().equals(xmlOrg.getNciInstituteCode()) )
) {
String message = messageSource.getMessage("WS_PMS_018", new String[] {}, "", Locale
.getDefault());
logger.error(message);
populateError(caaersServiceResponse, "WS_PMS_018", message);
}
}
@Transactional(readOnly=false)
public CaaersServiceResponse deleteParticipant(Participants xmlParticipants) {
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
ParticipantType xmlParticipant = xmlParticipants.getParticipant().get(0);
Identifier studyIdentifier = getStudyIdentifierFromInXML(xmlParticipant);
String studySubjectIdentifier = getStudySubjectIdentifierFromInXML(xmlParticipant);
Participant dbParticipant = validateInputsAndFetchParticipant(studySubjectIdentifier, studyIdentifier, xmlParticipant, caaersServiceResponse);
if( dbParticipant == null) {
return caaersServiceResponse;
} else if(dbParticipant.getHasReportingPeriods()) {
String message = messageSource.getMessage("WS_PMS_009", new String[] { studySubjectIdentifier, studyIdentifier.getValue() }, "", Locale
.getDefault());
logger.error(message);
populateError(caaersServiceResponse, "WS_PMS_009", message);
}
if(caaersServiceResponse.getServiceResponse().getStatus() == Status.FAILED_TO_PROCESS) {
return caaersServiceResponse;
}
//resetting the response object
caaersServiceResponse = Helper.createResponse();
DomainObjectImportOutcome<Participant> participantImportOutcome =
convertToImportedDomainObject(xmlParticipant, studySubjectIdentifier, caaersServiceResponse, "deleted");
if(participantImportOutcome != null){
Participant importedDomainObject = participantImportOutcome.getImportedDomainObject();
participantDao.delete(dbParticipant);
String message = messageSource.getMessage("WS_PMS_010",
new String[] { importedDomainObject.getFirstName(), importedDomainObject.getLastName(), studySubjectIdentifier },
"", Locale.getDefault());
Helper.populateMessage(caaersServiceResponse, message);
logger.info(message);
if(eventFactory != null) {
eventFactory.publishEntityModifiedEvent(importedDomainObject, false);
}
}
return caaersServiceResponse;
}
// returns the domain participant after converting to jaxb participant based on the input identifiers
public CaaersServiceResponse getParticipant(ParticipantRef xmlParticipantRefType) {
CaaersServiceResponse caaersServiceResponse = Helper.createResponse();
Participant dbParticipant = null;
//TODO : Only fetch By Assignment works..Need to add fetch by Identifier(mostly not required)
ParticipantRef.ParticipantAssignment assignment = xmlParticipantRefType.getParticipantAssignment();
if(assignment == null || assignment.getStudyIdentifier() == null || assignment.getStudyIdentifier().getType() == null) {
populateError(caaersServiceResponse, "WS_PMS_013", messageSource.getMessage("WS_PMS_013",
new String[]{},"",Locale.getDefault()));
return caaersServiceResponse;
}
Identifier studyId = new Identifier();
studyId.setType(assignment.getStudyIdentifier().getType().value());
studyId.setValue(assignment.getStudyIdentifier().getValue());
dbParticipant = fetchParticipantByAssignment(assignment.getStudySubjectIdentifier(), studyId, caaersServiceResponse);
if(dbParticipant != null ){
caaersServiceResponse.getServiceResponse().setResponsecode("0");
ParticipantType dbParticipantType = new ParticipantType();
participantConverter.convertDomainParticipantToParticipantDto(dbParticipant, dbParticipantType);
caaersServiceResponse.getServiceResponse().setResponseData(new ResponseDataType());
Participants participants = new Participants();
participants.getParticipant().add(dbParticipantType);
caaersServiceResponse.getServiceResponse().getResponseData().setAny(participants);
}
return caaersServiceResponse;
}
private CaaersServiceResponse createNoStudyAuthorizationResponse(CaaersServiceResponse caaersServiceResponse, Identifier identifier){
populateError(caaersServiceResponse, "WS_GEN_003", messageSource.getMessage("WS_GEN_003", new String[]{identifier.getValue()},"",Locale.getDefault()));
return caaersServiceResponse;
}
private CaaersServiceResponse createNoStudyFoundResponse(CaaersServiceResponse caaersServiceResponse, Identifier identifier){
populateError(caaersServiceResponse, "WS_PMS_002", messageSource.getMessage("WS_PMS_002", new String[]{identifier.getValue()},"",Locale.getDefault()));
return caaersServiceResponse;
}
private CaaersServiceResponse createNoOrganizationAuthorizationResponse(CaaersServiceResponse caaersServiceResponse, String errorMsg){
populateError(caaersServiceResponse, "WS_GEN_005", messageSource.getMessage("WS_GEN_005", new String[]{errorMsg},"",Locale.getDefault()));
return caaersServiceResponse;
}
private Participant fetchParticipant(Participant participant){
Participant dbParticipant = null;
for(Identifier identifier : participant.getIdentifiers()){
dbParticipant = participantDao.getParticipantDesignByIdentifier(identifier);
if(dbParticipant != null){
break;
}
participantDao.evict(dbParticipant);
}
return dbParticipant;
}
/**
* Fetch a participant from DB by subject id and registration site
* @param subjectId
* @param regSite
*/
private Participant fetchParticipantBySubjectIdAndSite(String subjectId, String regSiteCode){
ParticipantQuery pq = new ParticipantQuery();
pq.joinOnIdentifiers();
pq.joinAssignment();
pq.joinStudySite();
pq.filterByIdentifierValueExactMatch(subjectId);
pq.filterByStudySiteNciCode(regSiteCode);
List<Participant> dbParticipants = participantDao.searchParticipant(pq);
if (dbParticipants != null && dbParticipants.size() > 0) {
logger.debug("Found "+dbParticipants.size()+" participant with the give id and site, returning the first one");
return dbParticipants.get(0);
}
return null;
}
private Participant fetchParticipantByAssignment(Participant participant,
CaaersServiceResponse caaersServiceResponse) {
Participant dbParticipant = null;
for(StudyParticipantAssignment assignment : participant.getAssignments()){
for(Identifier identifier : assignment.getStudySite().getStudy().getIdentifiers()) {
dbParticipant = fetchParticipantByAssignment(assignment.getStudySubjectIdentifier(),
identifier, caaersServiceResponse);
if(dbParticipant != null){
participantDao.evict(dbParticipant);
return dbParticipant;
}
}
}
return dbParticipant;
}
private Participant fetchParticipantByAssignment(String studySubjectIdentifier,
Identifier studyIdentifier, CaaersServiceResponse caaersServiceResponse) {
Participant dbParticipant = null;
if (StringUtils.isEmpty(studySubjectIdentifier)) {
String message = messageSource.getMessage("WS_PMS_014", new String[] { studySubjectIdentifier }, "", Locale
.getDefault());
logger.error(message);
populateError(caaersServiceResponse, "WS_PMS_014", message);
return null;
}
if (studyIdentifier == null || StringUtils.isEmpty(studyIdentifier.getValue())) {
String message = messageSource.getMessage("WS_PMS_015", new String[] { studyIdentifier.getValue() }, "", Locale
.getDefault());
logger.error(message);
populateError(caaersServiceResponse, "WS_PMS_015", message);
return null;
}
try {
Study study = fetchStudy(studyIdentifier);
if(study == null) {
String message = messageSource.getMessage("WS_PMS_002", new String[] { studyIdentifier.getValue() }, "", Locale
.getDefault());
logger.error(message);
populateError(caaersServiceResponse, "WS_PMS_002", message);
return dbParticipant;
}
ParticipantQuery pq = new ParticipantQuery();
pq.joinStudy();
pq.filterByStudySubjectIdentifier(studySubjectIdentifier, "=");
pq.filterByStudyId(study.getId(), "=");
List<Participant> dbParticipants = participantDao.searchParticipant(pq);
if (dbParticipants != null && dbParticipants.size() == 1) {
logger.info("Participant registered to this study in caAERS");
dbParticipant = dbParticipants.get(0);
} else {
String message = messageSource.getMessage("WS_PMS_003", new String[] { studySubjectIdentifier, studyIdentifier.getValue() }, "", Locale
.getDefault());
logger.error(message);
populateError(caaersServiceResponse, "WS_PMS_003", message);
}
} catch (Exception e) {
String message = messageSource.getMessage("WS_PMS_016", new String[] { e.getMessage() }, "", Locale
.getDefault());
logger.error("Error retrieving participant", e);
populateError(caaersServiceResponse, "WS_PMS_016", message);
dbParticipant = null;
}
return dbParticipant;
}
public ValidationErrors transferParticipant(Participant dbParticipant, StudySite siteTransferredFrom, Organization organizationTransferredTo, ValidationErrors errors){
Organization dbOrgToBeTransferredTo = organizationDao.getByNCIcode(organizationTransferredTo.getNciInstituteCode());
if(dbOrgToBeTransferredTo == null){
errors.addValidationError( "ORG-NF-1", "Cannot find organization with NCI code :" + organizationTransferredTo.getNciInstituteCode());
return errors;
}
if(!dbParticipant.isAssignedToStudySite(siteTransferredFrom)){
errors.addValidationError( "PT-NF-1", "Cannot transfer patient from the site :" + siteTransferredFrom.getOrganization().getName()
+ " as the patient is not registered on this site.");
return errors;
}
migrateSiteIdentifierToNewSite(dbParticipant, siteTransferredFrom.getOrganization(), dbOrgToBeTransferredTo, errors);
if(errors.hasErrors()) return errors;
List<StudyParticipantAssignment> assignments = dbParticipant.getStudyParticipantAssignments(siteTransferredFrom.getOrganization());
for(StudyParticipantAssignment assignment : assignments){
Study study = assignment.getStudySite().getStudy();
StudySite studySiteToBeTransferredTo = study.getStudySite(dbOrgToBeTransferredTo);
if(studySiteToBeTransferredTo == null){
studySiteToBeTransferredTo = new StudySite();
studySiteToBeTransferredTo.setOrganization(dbOrgToBeTransferredTo);
study.addStudySite(studySiteToBeTransferredTo);
studyDao.save(study);
}
assignment.setStudySite(studySiteToBeTransferredTo);
}
participantDao.save(dbParticipant);
return errors;
}
public ValidationErrors migrateSiteIdentifierToNewSite(Participant participant, Organization orgTransferredFrom, Organization orgTransferredTo, ValidationErrors errors){
List<Identifier> identifiers = participantDao.getSiteIdentifiers(orgTransferredTo.getId());
for(OrganizationAssignedIdentifier oai : participant.getOrganizationIdentifiers()){
//check if another patient has been assigned this MRN by the new site.
for(Identifier id : identifiers){
if(oai.getOrganization().equals(((OrganizationAssignedIdentifier)id).getOrganization()) && oai.getValue().equalsIgnoreCase(id.getValue())){
errors.addValidationError( "PT-ID-DUP-1", "Cannot transfer patient from the site :" + orgTransferredFrom.getName() + " to " + orgTransferredTo.getName()
+ " as the identifier " + id.getValue() + " is already assigned by the site ");
return errors;
}
}
if(oai.getOrganization().equals(orgTransferredFrom)){
oai.setOrganization(orgTransferredTo);
}
}
return errors;
}
private void populateError(CaaersServiceResponse caaersServiceResponse, String errorCode, String message) {
Helper.populateError(caaersServiceResponse, errorCode, message);
caaersServiceResponse.getServiceResponse().setMessage(message);
}
private Study fetchStudy(Identifier identifier) {
Study dbStudy = null;
dbStudy = studyDao.getByIdentifier(identifier);
if(dbStudy != null){
return dbStudy;
}
studyDao.evict(dbStudy);
return dbStudy;
}
public ParticipantDao getParticipantDao() {
return participantDao;
}
public void setParticipantDao(ParticipantDao participantDao) {
this.participantDao = participantDao;
}
public ParticipantImportServiceImpl getParticipantImportServiceImpl() {
return participantImportServiceImpl;
}
public void setParticipantImportServiceImpl(
ParticipantImportServiceImpl participantImportServiceImpl) {
this.participantImportServiceImpl = participantImportServiceImpl;
}
public ParticipantConverter getParticipantConverter() {
return participantConverter;
}
public void setParticipantConverter(ParticipantConverter participantConverter) {
this.participantConverter = participantConverter;
}
public ParticipantSynchronizer getParticipantSynchronizer() {
return participantSynchronizer;
}
public void setParticipantSynchronizer(
ParticipantSynchronizer participantSynchronizer) {
this.participantSynchronizer = participantSynchronizer;
}
/*public void setDomainObjectValidator(DomainObjectValidator domainObjectValidator) {
this.domainObjectValidator = domainObjectValidator;
}*/
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
public Validator getValidator() {
return validator;
}
public void setValidator(Validator validator) {
this.validator = validator;
}
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
public EventFactory getEventFactory() {
return eventFactory;
}
public void setEventFactory(EventFactory eventFactory) {
this.eventFactory = eventFactory;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
} |
package edu.duke.cabig.catrip.gui.querysharing;
import edu.duke.cabig.catrip.gui.common.AttributeBean;
import edu.duke.cabig.catrip.gui.common.CDEComboboxBeanComparator;
import edu.duke.cabig.catrip.gui.common.ClassBean;
import edu.duke.cabig.catrip.gui.components.PreferredHeightMarginBorderBoxLayout;
import edu.duke.cabig.catrip.gui.simplegui.CDEComboboxBean;
import edu.duke.cabig.catrip.gui.simplegui.SimpleGuiRegistry;
import edu.duke.cabig.catrip.gui.simplegui.objectgraph.GraphObject;
import edu.duke.cabig.catrip.gui.wizard.MainFrame;
import gov.nih.nci.cagrid.dcql.DCQLQuery;
import gov.nih.nci.catrip.cagrid.catripquery.client.QueryServiceClient;
import gov.nih.nci.catrip.cagrid.catripquery.server.ClassDb;
import gov.nih.nci.catrip.cagrid.catripquery.server.QueryDb;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import java.awt.event.KeyEvent;
import java.io.CharArrayReader;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.SwingConstants;
import org.globus.wsrf.encoding.ObjectDeserializer;
import org.xml.sax.InputSource;
public class QueryServiceUI extends JPanel {
private static final long serialVersionUID = 1L;
private JButton btnSearch = null;
private JLabel lblFirstName = null;
private JTextField txtFirstName = null;
private JScrollPane resultsScrollPane = null;
private JTable resultTable = null;
private JTextField txtLastName = null;
private JLabel lblLastName = null;
private JPanel metaDataPanel = null;
private JLabel lblDescriptionl = null;
private JLabel lblQueryName = null;
private JTextField txtQueryName = null;
private JTextField txtDescription = null;
private JLabel lblFilter = null;
private JLabel lblConceptl = null;
private JButton btnAddFilter = null;
private JLabel lblQueryResult = null;
Collection<QueryFilterRowPanel> filterCollection = new Vector<QueryFilterRowPanel>(); // @jve:decl-index=0:
//Collection<ClassDb> classCollection = null;
// private DefaultTableModel conceptCodeTableModel = new DefaultTableModel();
private QueryDb queryData = new QueryDb(); // @jve:decl-index=0:
private DefaultTableModel tableModel = null ;
private JPanel filterPanel = null;
private JScrollPane jScrollPane1 = null;
public MainFrame mainFrame;
private ArrayList<CDEComboboxBean> filterList = new ArrayList<CDEComboboxBean>(500);
/**
* This method initializes
*
*/
public QueryServiceUI() {
super();
initialize();
init();
}
public void setMainFrame(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public MainFrame getMainFrame() {
return mainFrame;
}
private void init(){
ArrayList<GraphObject> objs = SimpleGuiRegistry.getAllSimpleGuiXMLObjectList();
for (int i=0;i<objs.size();i++) {
GraphObject gObj = objs.get(i);
if (gObj.isDisplayable()){
ClassBean cBean = gObj.getClassBean();
ArrayList attributes = cBean.getAttributes();
for (int j = 0; j < attributes.size(); j++) {
AttributeBean aBean = (AttributeBean)attributes.get(j);
CDEComboboxBean cdeBean = new CDEComboboxBean();
cdeBean.setGraphObject(gObj);
cdeBean.setAttributeBean(aBean);
filterList.add(cdeBean);
}
// add the class only entry..
CDEComboboxBean cdeBean = new CDEComboboxBean();
cdeBean.setGraphObject(gObj);
cdeBean.setAttributeBean(new AttributeBean()); // add a null bean..
filterList.add(cdeBean);
}
}
// sanjeev: add them in sorted order.. add all the filters in an array list than use collections to sort than add tham to combo.
Collections.sort(filterList, new CDEComboboxBeanComparator());
// for (int i = 0; i < attributeList.size(); i++) {
// getCdeCombo().addItem(attributeList.get(i));
}
/**
* This method initializes this
*
*/
private void initialize() {
lblQueryResult = new JLabel();
lblQueryResult.setBounds(new Rectangle(592, 8, 127, 16));
lblQueryResult.setText("Queries Results :");
lblConceptl = new JLabel();
lblConceptl.setText("Concept");
lblConceptl.setBounds(new Rectangle(116, 197, 47, 16));
lblFilter = new JLabel();
lblFilter.setText("Filter");
lblFilter.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
lblFilter.setHorizontalAlignment(SwingConstants.CENTER);
lblFilter.setBounds(new Rectangle(19, 178, 92, 26));
lblLastName = new JLabel();
lblLastName.setText("Last Name :");
lblLastName.setBounds(new Rectangle(288, 93, 83, 20));
lblFirstName = new JLabel();
lblFirstName.setText("First Name : ");
lblFirstName.setBounds(new Rectangle(34, 92, 74, 20));
this.setLayout(null);
this.setSize(new Dimension(1256, 752));
this.add(getBtnSearch(), null);
this.add(getResultsScrollPane(), null);
this.add(getMetaDataPanel(), null);
this.add(getBtnAddFilter(), null);
this.add(lblQueryResult, null);
this.add(lblFilter, null);
this.add(lblConceptl, null);
this.add(getJScrollPane1(), null);
}
/**
* This method initializes btnSearch
*
* @return javax.swing.JButton
*/
private JButton getBtnSearch() {
if (btnSearch == null) {
btnSearch = new JButton();
btnSearch.setBounds(new Rectangle(356, 185, 85, 23));
btnSearch.setText("Search");
btnSearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
// fill query data with the Concepts selected
Collection<ClassDb> classCollection = new Vector<ClassDb>();
//filterCollection.add(getFilterRowPanel());
for (Iterator iter = filterCollection.iterator(); iter.hasNext();) {
QueryFilterRowPanel element = (QueryFilterRowPanel) iter.next();
classCollection.add(element.getSelectedClass());
}
queryData.setClassCollection(classCollection);
populateTable(QueryServiceClient.search(queryData));
} catch (Exception qe) {
qe.printStackTrace();
}
}
}
);
}
return btnSearch;
}
private QueryFilterRowPanel getFilterRowPanel(){
// QueryFilterRowPanel filterRow = new QueryFilterRowPanel(this);
QueryFilterRowPanel filterRow = new QueryFilterRowPanel(this, filterList);
filterRow.setPreferredSize(new Dimension(538, 30));
return filterRow;
}
@SuppressWarnings("unchecked")
private void populateTable(Vector collection) {
tableModel = new DefaultTableModel();
tableModel.setColumnCount(5);
Vector<String> columnHeaders = new Vector<String>(5);
columnHeaders.add("Query Name");
columnHeaders.add("User Name");
columnHeaders.add("Description");
columnHeaders.add("");
columnHeaders.add("");
tableModel.setColumnIdentifiers(columnHeaders);
// loop over the vector, getting out the entry object
for (Iterator iter = collection.iterator(); iter.hasNext();) {
QueryDb e = (QueryDb) iter.next();
// create another vector, this one will be used as a row in the table
Vector<Serializable> rowData = new Vector<Serializable> () ;
// populate this row with the data out of the objects, using wrapper classes where primitive
// data types are used.
rowData.add(e.getName()) ;
rowData.add(e.getFirstName()+ " " + e.getLastName()) ;
rowData.add(e.getDescription()) ;
rowData.add("View/Modify") ;
rowData.add("Run") ;
// add row to model
tableModel.addRow(rowData) ;
}
resultTable.getColumnModel();
resultTable.setModel(tableModel);
new ButtonColumn(resultTable, 3, collection, true);
new ButtonColumn(resultTable, 4, collection, true);
}
/**
* This method initializes txtUserName
*
* @return javax.swing.JTextField
*/
private JTextField getTxtFirstName() {
if (txtFirstName == null) {
txtFirstName = new JTextField();
txtFirstName.setBounds(new Rectangle(110, 92, 157, 20));
txtFirstName.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent e) {
queryData.setFirstName(txtFirstName.getText()); }
});
}
return txtFirstName;
}
/**
* This method initializes resultsScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getResultsScrollPane() {
if (resultsScrollPane == null) {
resultsScrollPane = new JScrollPane();
resultsScrollPane.setBounds(new Rectangle(594, 30, 575, 356));
resultsScrollPane.setViewportView(getResultTable());
}
return resultsScrollPane;
}
/**
* This method initializes resultTable
*
* @return javax.swing.JTable
*/
private JTable getResultTable() {
if (resultTable == null) {
resultTable = new ButtonTable();
}
return resultTable;
}
/**
* This method initializes txtLastName
*
* @return javax.swing.JTextField
*/
private JTextField getTxtLastName() {
if (txtLastName == null) {
txtLastName = new JTextField();
txtLastName.setBounds(new Rectangle(379, 93, 157, 20));
txtLastName.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent e) {
queryData.setLastName(txtLastName.getText());
}
});
}
return txtLastName;
}
/**
* This method initializes metaDataPanel
*
* @return javax.swing.JPanel
*/
private JPanel getMetaDataPanel() {
if (metaDataPanel == null) {
lblQueryName = new JLabel();
lblQueryName.setBounds(new Rectangle(26, 15, 82, 20));
lblQueryName.setText("Query Name : ");
lblDescriptionl = new JLabel();
lblDescriptionl.setBounds(new Rectangle(28, 52, 80, 20));
lblDescriptionl.setText("Description :");
metaDataPanel = new JPanel();
metaDataPanel.setLayout(null);
metaDataPanel.setBounds(new Rectangle(16, 30, 564, 134));
metaDataPanel.add(lblFirstName, null);
metaDataPanel.add(getTxtFirstName(), null);
metaDataPanel.add(lblLastName, null);
metaDataPanel.add(getTxtLastName(), null);
metaDataPanel.add(lblDescriptionl, null);
metaDataPanel.add(lblQueryName, null);
metaDataPanel.add(getTxtQueryName(), null);
metaDataPanel.add(getTxtDescription(), null);
metaDataPanel.setBorder(BorderFactory.createLineBorder(Color.black));
}
return metaDataPanel;
}
/**
* This method initializes txtQueryName
*
* @return javax.swing.JTextField
*/
private JTextField getTxtQueryName() {
if (txtQueryName == null) {
txtQueryName = new JTextField();
txtQueryName.setBounds(new Rectangle(110, 16, 426, 20));
// txtQueryName.setText("not");
txtQueryName.setName("");
txtQueryName.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent e) {
System.out.println(">" + txtQueryName.getText() +"<");
queryData.setName(txtQueryName.getText());
}
});
}
return txtQueryName;
}
/**
* This method initializes txtDescription
*
* @return javax.swing.JTextField
*/
private JTextField getTxtDescription() {
if (txtDescription == null) {
txtDescription = new JTextField();
txtDescription.setBounds(new Rectangle(110, 52, 426, 20));
// txtDescription.setText("query");
txtDescription.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent e) {
queryData.setDescription(txtDescription.getText());
}
});
}
return txtDescription;
}
/**
* This method initializes btnAddFilter
*
* @return javax.swing.JButton
*/
private JButton getBtnAddFilter() {
if (btnAddFilter == null) {
btnAddFilter = new JButton();
btnAddFilter.setBounds(new Rectangle(470, 185, 99, 24));
btnAddFilter.setText("Add Filter");
btnAddFilter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
addFilterRow();
}
});
}
return btnAddFilter;
}
private void addFilterRow(){
QueryFilterRowPanel filterRow = getFilterRowPanel();
filterCollection.add(filterRow);
// for (Iterator iter = filterCollection.iterator(); iter.hasNext();) {
// FilterRowPanel element = (FilterRowPanel) iter.next();
// //System.out.println("adding " + element.getSelectedClass().getName());
getFilterPanel().add(filterRow,null);
getFilterPanel().revalidate();
getFilterPanel().repaint();
}
/**
* This method initializes filterPanel
*
* @return javax.swing.JPanel
*/
public JPanel getFilterPanel() {
if (filterPanel == null) {
filterPanel = new JPanel();
PreferredHeightMarginBorderBoxLayout layout = new PreferredHeightMarginBorderBoxLayout(getFilterPanel(), PreferredHeightMarginBorderBoxLayout.Y_AXIS);
filterPanel.setLayout(layout);
//filterPanel.setLayout(new BoxLayout(getFilterPanel(), BoxLayout.Y_AXIS));
}
return filterPanel;
}
/**
* This method initializes jScrollPane1
*
* @return javax.swing.JScrollPane
*/
public JScrollPane getJScrollPane1() {
if (jScrollPane1 == null) {
jScrollPane1 = new JScrollPane();
jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane1.setViewportView(getFilterPanel());
jScrollPane1.setBounds(new Rectangle(16, 215, 564, 159));
}
return jScrollPane1;
}
/**
* @param args
*/
public static void main(String[] args) {
QueryServiceUI s = new QueryServiceUI();
//s.setOpaque(true);
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(s,BorderLayout.CENTER);
// frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
// convert the dcql string into object
private void executeDcql(String dcql){
// StringBuffer buf = new StringBuffer(dcql);
// char[] chars = new char[buf.length()];
// buf.getChars(0, chars.length, chars, 0);
// CharArrayReader car = new CharArrayReader(chars);
java.io.Reader reader = new java.io.StringReader(dcql);
InputSource source = new InputSource(reader);//source.setEncoding();
DCQLQuery dcqlObj = null;
try {
dcqlObj = (DCQLQuery) ObjectDeserializer.deserialize(source,DCQLQuery.class);
} catch (Exception e){e.printStackTrace();}
executeDcql(dcqlObj);
}
// execute DCQL in the outPut Pane of the SimpleGUI..
private void executeDcql(DCQLQuery dcql){
getMainFrame().getCommandPanel().runExternalDcql(dcql);
}
public void removeFilter(QueryFilterRowPanel filterRowPanel){
getFilterPanel().remove(filterRowPanel);
getFilterPanel().revalidate();
getFilterPanel().repaint();
if (filterCollection != null){
// remove from array
boolean wasRemoved = false;
//System.out.println("before : " + classCollection.size());
for (Iterator iter = filterCollection.iterator(); iter.hasNext();) {
QueryFilterRowPanel element = (QueryFilterRowPanel) iter.next();
if (element.getSelectedClass().getId() == filterRowPanel.getSelectedClass().getId())
wasRemoved = filterCollection.remove(element);
}
System.out.println("after : " + filterCollection.size() + " was removed ? " + wasRemoved);
}
}
class ButtonColumn extends AbstractCellEditor implements TableCellRenderer, TableCellEditor, ActionListener{
private static final long serialVersionUID = 1L;
JTable table;
JButton renderButton;
JButton editButton;
String text;
Vector<QueryDb> data;
public ButtonColumn(JTable table, int column, Vector<QueryDb> data, boolean enable){
super();
this.table = table;
renderButton = new JButton();
this.data = data;
editButton = new JButton();
editButton.setFocusPainted( false );
editButton.setEnabled(enable);
renderButton.setEnabled(enable);
editButton.addActionListener( this );
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(column).setCellRenderer( this );
columnModel.getColumn(column).setCellEditor( this );
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
if (hasFocus){
renderButton.setForeground(table.getForeground());
renderButton.setBackground(UIManager.getColor("Button.background"));
} else if (isSelected){
renderButton.setForeground(table.getSelectionForeground());
renderButton.setBackground(table.getSelectionBackground());
} else{
renderButton.setForeground(table.getForeground());
renderButton.setBackground(UIManager.getColor("Button.background"));
}
renderButton.setText( (value == null) ? "" : value.toString() );
return renderButton;
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column){
text = (value == null) ? "" : value.toString();
editButton.setText( text );
return editButton;
}
public Object getCellEditorValue(){
return text;
}
public void actionPerformed(ActionEvent e){
fireEditingStopped();
if (e.getActionCommand().equalsIgnoreCase("run")){
String dcql = (String)table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn());
executeDcql(dcql); // execute the dcql...
// System.out.println( e.getActionCommand() + " : " + table.getSelectedRow());
// System.out.println("dcql = " + table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
} else if(e.getActionCommand().equalsIgnoreCase("x")){
DefaultTableModel t = (DefaultTableModel) table.getModel();
t.removeRow(table.getSelectedRow());
} else{
System.out.println(e.getActionCommand() + " : " + table.getSelectedRow() + " \n" + table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()));
}
}
}
class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MyComboBoxRenderer(String[] items) {
super(items);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
// Select the current value
setSelectedItem(value);
return this;
}
}
class MyComboBoxEditor extends DefaultCellEditor {
private static final long serialVersionUID = 1L;
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}
} // @jve:decl-index=0:visual-constraint="-7,7" |
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.document.FixedBucketSpaces;
import com.yahoo.exception.ExceptionUtils;
import com.yahoo.jrt.ListenFailedException;
import com.yahoo.vdslib.distribution.ConfiguredNode;
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabaseFactory;
import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
import com.yahoo.vespa.clustercontroller.core.listeners.SlobrokListener;
import com.yahoo.vespa.clustercontroller.core.listeners.SystemStateListener;
import com.yahoo.vespa.clustercontroller.core.rpc.RPCCommunicator;
import com.yahoo.vespa.clustercontroller.core.rpc.RpcServer;
import com.yahoo.vespa.clustercontroller.core.rpc.SlobrokClient;
import com.yahoo.vespa.clustercontroller.core.status.ClusterStateRequestHandler;
import com.yahoo.vespa.clustercontroller.core.status.LegacyIndexPageRequestHandler;
import com.yahoo.vespa.clustercontroller.core.status.LegacyNodePageRequestHandler;
import com.yahoo.vespa.clustercontroller.core.status.NodeHealthRequestHandler;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageResponse;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageServer;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.StatusPageServerInterface;
import com.yahoo.vespa.clustercontroller.utils.util.MetricReporter;
import java.io.FileNotFoundException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class FleetController implements NodeListener, SlobrokListener, SystemStateListener,
Runnable, RemoteClusterControllerTaskScheduler {
private static final Logger logger = Logger.getLogger(FleetController.class.getName());
private final FleetControllerContext context;
private final Timer timer;
private final Object monitor;
private final EventLog eventLog;
private final NodeLookup nodeLookup;
private final ContentCluster cluster;
private final Communicator communicator;
private final NodeStateGatherer stateGatherer;
private final StateChangeHandler stateChangeHandler;
private final SystemStateBroadcaster systemStateBroadcaster;
private final StateVersionTracker stateVersionTracker;
private final StatusPageServerInterface statusPageServer;
private final RpcServer rpcServer;
private final DatabaseHandler database;
private final MasterElectionHandler masterElectionHandler;
private Thread runner = null;
private final AtomicBoolean running = new AtomicBoolean(true);
private FleetControllerOptions options;
private FleetControllerOptions nextOptions;
private final List<SystemStateListener> systemStateListeners = new CopyOnWriteArrayList<>();
private boolean processingCycle = false;
private boolean wantedStateChanged = false;
private long cycleCount = 0;
private long lastMetricUpdateCycleCount = 0;
private long nextStateSendTime = 0;
private Long controllerThreadId = null;
private boolean waitingForCycle = false;
private final StatusPageServer.PatternRequestRouter statusRequestRouter = new StatusPageServer.PatternRequestRouter();
private final List<ClusterStateBundle> newStates = new ArrayList<>();
private final List<ClusterStateBundle> convergedStates = new ArrayList<>();
private final Queue<RemoteClusterControllerTask> remoteTasks = new LinkedList<>();
private final MetricUpdater metricUpdater;
private boolean isMaster = false;
private boolean inMasterMoratorium = false;
private boolean isStateGatherer = false;
private long firstAllowedStateBroadcast = Long.MAX_VALUE;
private long tickStartTime = Long.MAX_VALUE;
private final List<RemoteClusterControllerTask> tasksPendingStateRecompute = new ArrayList<>();
// Invariant: queued task versions are monotonically increasing with queue position
private final Queue<VersionDependentTaskCompletion> taskCompletionQueue = new ArrayDeque<>();
// Legacy behavior is an empty set of explicitly configured bucket spaces, which means that
// only a baseline cluster state will be sent from the controller and no per-space state
// deriving is done.
private Set<String> configuredBucketSpaces = Collections.emptySet();
public FleetController(FleetControllerContext context,
Timer timer,
EventLog eventLog,
ContentCluster cluster,
NodeStateGatherer nodeStateGatherer,
Communicator communicator,
StatusPageServerInterface statusPage,
RpcServer server,
NodeLookup nodeLookup,
DatabaseHandler database,
StateChangeHandler stateChangeHandler,
SystemStateBroadcaster systemStateBroadcaster,
MasterElectionHandler masterElectionHandler,
MetricUpdater metricUpdater,
FleetControllerOptions options) {
context.log(logger, Level.INFO, "Created");
this.context = context;
this.timer = timer;
this.monitor = timer;
this.eventLog = eventLog;
this.options = options;
this.nodeLookup = nodeLookup;
this.cluster = cluster;
this.communicator = communicator;
this.database = database;
this.stateGatherer = nodeStateGatherer;
this.stateChangeHandler = stateChangeHandler;
this.systemStateBroadcaster = systemStateBroadcaster;
this.stateVersionTracker = new StateVersionTracker(options.minMergeCompletionRatio);
this.metricUpdater = metricUpdater;
this.statusPageServer = Objects.requireNonNull(statusPage, "statusPage cannot be null");
this.rpcServer = server;
this.masterElectionHandler = masterElectionHandler;
this.statusRequestRouter.addHandler(
"^/node=([a-z]+)\\.(\\d+)$",
new LegacyNodePageRequestHandler(timer, eventLog, cluster));
this.statusRequestRouter.addHandler(
"^/state.*",
new NodeHealthRequestHandler());
this.statusRequestRouter.addHandler(
"^/clusterstate",
new ClusterStateRequestHandler(stateVersionTracker));
this.statusRequestRouter.addHandler(
"^/$",
new LegacyIndexPageRequestHandler(timer, cluster, masterElectionHandler, stateVersionTracker, eventLog, options));
propagateOptions();
}
public static FleetController create(FleetControllerOptions options,
StatusPageServerInterface statusPageServer,
MetricReporter metricReporter) throws Exception {
var context = new FleetControllerContextImpl(options);
var timer = new RealTimer();
var metricUpdater = new MetricUpdater(metricReporter, options.fleetControllerIndex, options.clusterName);
var log = new EventLog(timer, metricUpdater);
var cluster = new ContentCluster(
options.clusterName,
options.nodes,
options.storageDistribution);
var stateGatherer = new NodeStateGatherer(timer, timer, log);
var communicator = new RPCCommunicator(
RPCCommunicator.createRealSupervisor(),
timer,
options.fleetControllerIndex,
options.nodeStateRequestTimeoutMS,
options.nodeStateRequestTimeoutEarliestPercentage,
options.nodeStateRequestTimeoutLatestPercentage,
options.nodeStateRequestRoundTripTimeMaxSeconds);
var database = new DatabaseHandler(context, new ZooKeeperDatabaseFactory(context), timer, options.zooKeeperServerAddress, timer);
var lookUp = new SlobrokClient(context, timer);
var stateGenerator = new StateChangeHandler(context, timer, log);
var stateBroadcaster = new SystemStateBroadcaster(context, timer, timer);
var masterElectionHandler = new MasterElectionHandler(context, options.fleetControllerIndex, options.fleetControllerCount, timer, timer);
var controller = new FleetController(context, timer, log, cluster, stateGatherer, communicator,
statusPageServer, null, lookUp, database, stateGenerator,
stateBroadcaster, masterElectionHandler, metricUpdater, options);
controller.start();
return controller;
}
public void start() {
runner = new Thread(this);
runner.start();
}
public Object getMonitor() { return monitor; }
public boolean isRunning() {
return running.get();
}
public boolean isMaster() {
synchronized (monitor) {
return isMaster;
}
}
public ClusterState getClusterState() {
synchronized (monitor) {
return systemStateBroadcaster.getClusterState();
}
}
public ClusterStateBundle getClusterStateBundle() {
synchronized (monitor) {
return systemStateBroadcaster.getClusterStateBundle();
}
}
public void schedule(RemoteClusterControllerTask task) {
synchronized (monitor) {
context.log(logger, Level.FINE, "Scheduled remote task " + task.getClass().getName() + " for execution");
remoteTasks.add(task);
}
}
/** Used for unit testing. */
public void addSystemStateListener(SystemStateListener listener) {
systemStateListeners.add(listener);
// Always give cluster state listeners the current state, in case acceptable state has come before listener is registered.
com.yahoo.vdslib.state.ClusterState state = getSystemState();
if (state == null) {
throw new NullPointerException("Cluster state should never be null at this point");
}
listener.handleNewPublishedState(ClusterStateBundle.ofBaselineOnly(AnnotatedClusterState.withoutAnnotations(state)));
ClusterStateBundle convergedState = systemStateBroadcaster.getLastClusterStateBundleConverged();
if (convergedState != null) {
listener.handleStateConvergedInCluster(convergedState);
}
}
public FleetControllerOptions getOptions() {
synchronized(monitor) {
return options.clone();
}
}
public NodeState getReportedNodeState(Node n) {
synchronized(monitor) {
NodeInfo node = cluster.getNodeInfo(n);
if (node == null) {
throw new IllegalStateException("Did not find node " + n + " in cluster " + cluster);
}
return node.getReportedState();
}
}
// Only used in tests
public NodeState getWantedNodeState(Node n) {
synchronized(monitor) {
return cluster.getNodeInfo(n).getWantedState();
}
}
public com.yahoo.vdslib.state.ClusterState getSystemState() {
synchronized(monitor) {
return stateVersionTracker.getVersionedClusterState();
}
}
public int getRpcPort() { return rpcServer.getPort(); }
public void shutdown() throws InterruptedException, java.io.IOException {
if (runner != null && isRunning()) {
context.log(logger, Level.INFO, "Joining event thread.");
running.set(false);
synchronized(monitor) { monitor.notifyAll(); }
runner.join();
}
context.log(logger, Level.INFO, "FleetController done shutting down event thread.");
controllerThreadId = Thread.currentThread().getId();
database.shutdown(databaseContext);
statusPageServer.shutdown();
if (rpcServer != null) {
rpcServer.shutdown();
}
communicator.shutdown();
nodeLookup.shutdown();
}
public void updateOptions(FleetControllerOptions options) {
var newId = FleetControllerId.fromOptions(options);
synchronized(monitor) {
assert newId.equals(context.id());
context.log(logger, Level.INFO, "FleetController has new options");
nextOptions = options.clone();
monitor.notifyAll();
}
}
private void verifyInControllerThread() {
if (controllerThreadId != null && controllerThreadId != Thread.currentThread().getId()) {
throw new IllegalStateException("Function called from non-controller thread. Shouldn't happen.");
}
}
private ClusterState latestCandidateClusterState() {
return stateVersionTracker.getLatestCandidateState().getClusterState();
}
@Override
public void handleNewNodeState(NodeInfo node, NodeState newState) {
verifyInControllerThread();
stateChangeHandler.handleNewReportedNodeState(latestCandidateClusterState(), node, newState, this);
}
@Override
public void handleNewWantedNodeState(NodeInfo node, NodeState newState) {
verifyInControllerThread();
wantedStateChanged = true;
stateChangeHandler.proposeNewNodeState(stateVersionTracker.getVersionedClusterState(), node, newState);
}
@Override
public void handleRemovedNode(Node node) {
verifyInControllerThread();
// Prune orphaned wanted states
wantedStateChanged = true;
}
@Override
public void handleUpdatedHostInfo(NodeInfo nodeInfo, HostInfo newHostInfo) {
verifyInControllerThread();
triggerBundleRecomputationIfResourceExhaustionStateChanged(nodeInfo, newHostInfo);
stateVersionTracker.handleUpdatedHostInfo(nodeInfo, newHostInfo);
}
private void triggerBundleRecomputationIfResourceExhaustionStateChanged(NodeInfo nodeInfo, HostInfo newHostInfo) {
if (!options.clusterFeedBlockEnabled) {
return;
}
var calc = createResourceExhaustionCalculator();
// Important: nodeInfo contains the _current_ host info _prior_ to newHostInfo being applied.
var previouslyExhausted = calc.enumerateNodeResourceExhaustions(nodeInfo);
var nowExhausted = calc.resourceExhaustionsFromHostInfo(nodeInfo, newHostInfo);
if (!previouslyExhausted.equals(nowExhausted)) {
context.log(logger, Level.FINE, () -> String.format("Triggering state recomputation due to change in cluster feed block: %s -> %s",
previouslyExhausted, nowExhausted));
stateChangeHandler.setStateChangedFlag();
}
}
@Override
public void handleNewNode(NodeInfo node) {
verifyInControllerThread();
stateChangeHandler.handleNewNode(node);
}
@Override
public void handleMissingNode(NodeInfo node) {
verifyInControllerThread();
stateChangeHandler.handleMissingNode(stateVersionTracker.getVersionedClusterState(), node, this);
}
@Override
public void handleNewRpcAddress(NodeInfo node) {
verifyInControllerThread();
stateChangeHandler.handleNewRpcAddress(node);
}
@Override
public void handleReturnedRpcAddress(NodeInfo node) {
verifyInControllerThread();
stateChangeHandler.handleReturnedRpcAddress(node);
}
@Override
public void handleNewPublishedState(ClusterStateBundle stateBundle) {
verifyInControllerThread();
ClusterState baselineState = stateBundle.getBaselineClusterState();
newStates.add(stateBundle);
metricUpdater.updateClusterStateMetrics(cluster, baselineState,
ResourceUsageStats.calculateFrom(cluster.getNodeInfos(), options.clusterFeedBlockLimit, stateBundle.getFeedBlock()));
lastMetricUpdateCycleCount = cycleCount;
systemStateBroadcaster.handleNewClusterStates(stateBundle);
// Iff master, always store new version in ZooKeeper _before_ publishing to any
// nodes so that a cluster controller crash after publishing but before a successful
// ZK store will not risk reusing the same version number.
// Use isMaster instead of election handler state, as isMaster is set _after_ we have
// completed a leadership event edge, so we know we have read from ZooKeeper.
if (isMaster) {
storeClusterStateMetaDataToZooKeeper(stateBundle);
}
}
private boolean maybePublishOldMetrics() {
verifyInControllerThread();
if (isMaster() && cycleCount > 300 + lastMetricUpdateCycleCount) {
ClusterStateBundle stateBundle = stateVersionTracker.getVersionedClusterStateBundle();
ClusterState baselineState = stateBundle.getBaselineClusterState();
metricUpdater.updateClusterStateMetrics(cluster, baselineState,
ResourceUsageStats.calculateFrom(cluster.getNodeInfos(), options.clusterFeedBlockLimit, stateBundle.getFeedBlock()));
lastMetricUpdateCycleCount = cycleCount;
return true;
} else {
return false;
}
}
private void storeClusterStateMetaDataToZooKeeper(ClusterStateBundle stateBundle) {
try {
database.saveLatestSystemStateVersion(databaseContext, stateBundle.getVersion());
database.saveLatestClusterStateBundle(databaseContext, stateBundle);
} catch (InterruptedException e) {
// Rethrow as RuntimeException to propagate exception up to main thread method.
// Don't want to hide failures to write cluster state version.
throw new RuntimeException("ZooKeeper write interrupted", e);
}
}
/**
* This function gives data of the current state in master election.
* The keys in the given map are indices of fleet controllers.
* The values are what fleetcontroller that fleetcontroller wants to
* become master.
*
* If more than half the fleetcontrollers want a node to be master and
* that node also wants itself as master, that node is the single master.
* If this condition is not met, there is currently no master.
*/
public void handleFleetData(Map<Integer, Integer> data) {
verifyInControllerThread();
context.log(logger, Level.FINEST, "Sending fleet data event on to master election handler");
metricUpdater.updateMasterElectionMetrics(data);
masterElectionHandler.handleFleetData(data);
}
/**
* Called when we can no longer contact database.
*/
public void lostDatabaseConnection() {
verifyInControllerThread();
boolean wasMaster = isMaster;
masterElectionHandler.lostDatabaseConnection();
if (wasMaster) {
// Enforce that we re-fetch all state information from ZooKeeper upon the next tick if we're still master.
dropLeadershipState();
metricUpdater.updateMasterState(false);
}
}
private void failAllVersionDependentTasks() {
tasksPendingStateRecompute.forEach(task -> {
task.handleFailure(RemoteClusterControllerTask.Failure.of(
RemoteClusterControllerTask.FailureCondition.LEADERSHIP_LOST));
task.notifyCompleted();
});
tasksPendingStateRecompute.clear();
taskCompletionQueue.forEach(task -> {
task.getTask().handleFailure(RemoteClusterControllerTask.Failure.of(
RemoteClusterControllerTask.FailureCondition.LEADERSHIP_LOST));
task.getTask().notifyCompleted();
});
taskCompletionQueue.clear();
}
/** Called when all distributors have acked newest cluster state version. */
public void handleAllDistributorsInSync(DatabaseHandler database, DatabaseHandler.DatabaseContext dbContext) throws InterruptedException {
Set<ConfiguredNode> nodes = new HashSet<>(cluster.clusterInfo().getConfiguredNodes().values());
// TODO wouldn't it be better to always get bundle information from the state broadcaster?
var currentBundle = stateVersionTracker.getVersionedClusterStateBundle();
context.log(logger, Level.FINE, () -> String.format("All distributors have ACKed cluster state version %d", currentBundle.getVersion()));
stateChangeHandler.handleAllDistributorsInSync(currentBundle.getBaselineClusterState(), nodes, database, dbContext);
convergedStates.add(currentBundle);
}
private boolean changesConfiguredNodeSet(Collection<ConfiguredNode> newNodes) {
if (newNodes.size() != cluster.getConfiguredNodes().size()) return true;
if (! cluster.getConfiguredNodes().values().containsAll(newNodes)) return true;
// Check retirement changes
for (ConfiguredNode node : newNodes) {
if (node.retired() != cluster.getConfiguredNodes().get(node.index()).retired()) {
return true;
}
}
return false;
}
/** This is called when the options field has been set to a new set of options */
private void propagateOptions() {
verifyInControllerThread();
selfTerminateIfConfiguredNodeIndexHasChanged();
if (changesConfiguredNodeSet(options.nodes)) {
// Force slobrok node re-fetch in case of changes to the set of configured nodes
cluster.setSlobrokGenerationCount(0);
}
configuredBucketSpaces = Set.of(FixedBucketSpaces.defaultSpace(), FixedBucketSpaces.globalSpace());
stateVersionTracker.setMinMergeCompletionRatio(options.minMergeCompletionRatio);
communicator.propagateOptions(options);
if (nodeLookup instanceof SlobrokClient) {
((SlobrokClient) nodeLookup).setSlobrokConnectionSpecs(options.slobrokConnectionSpecs);
}
eventLog.setMaxSize(options.eventLogMaxSize, options.eventNodeLogMaxSize);
cluster.setPollingFrequency(options.statePollingFrequency);
cluster.setDistribution(options.storageDistribution);
cluster.setNodes(options.nodes, databaseContext.getNodeStateUpdateListener());
database.setZooKeeperAddress(options.zooKeeperServerAddress, databaseContext);
database.setZooKeeperSessionTimeout(options.zooKeeperSessionTimeout, databaseContext);
stateGatherer.setMaxSlobrokDisconnectGracePeriod(options.maxSlobrokDisconnectGracePeriod);
stateGatherer.setNodeStateRequestTimeout(options.nodeStateRequestTimeoutMS);
// TODO: remove as many temporal parameter dependencies as possible here. Currently duplication of state.
stateChangeHandler.reconfigureFromOptions(options);
stateChangeHandler.setStateChangedFlag(); // Always trigger state recomputation after reconfig
masterElectionHandler.setFleetControllerCount(options.fleetControllerCount);
masterElectionHandler.setMasterZooKeeperCooldownPeriod(options.masterZooKeeperCooldownPeriod);
masterElectionHandler.setUsingZooKeeper(options.zooKeeperServerAddress != null && !options.zooKeeperServerAddress.isEmpty());
if (rpcServer != null) {
rpcServer.setMasterElectionHandler(masterElectionHandler);
try{
rpcServer.setSlobrokConnectionSpecs(options.slobrokConnectionSpecs, options.rpcPort);
} catch (ListenFailedException e) {
context.log(logger, Level.WARNING, "Failed to bind RPC server to port " + options.rpcPort + ". This may be natural if cluster has altered the services running on this node: " + e.getMessage());
} catch (Exception e) {
context.log(logger, Level.WARNING, "Failed to initialize RPC server socket: " + e.getMessage());
}
}
try {
statusPageServer.setPort(options.httpPort);
} catch (Exception e) {
context.log(logger, Level.WARNING, "Failed to initialize status server socket. This may be natural if cluster has altered the services running on this node: " + e.getMessage());
}
long currentTime = timer.getCurrentTimeInMillis();
nextStateSendTime = Math.min(currentTime + options.minTimeBetweenNewSystemStates, nextStateSendTime);
}
private void selfTerminateIfConfiguredNodeIndexHasChanged() {
var newId = new FleetControllerId(options.clusterName, options.fleetControllerIndex);
if (!newId.equals(context.id())) {
context.log(logger, Level.WARNING, context.id() + " got new configuration for " + newId + ". We do not support doing this live; " +
"immediately exiting now to force new configuration");
prepareShutdownEdge();
System.exit(1);
}
}
public StatusPageResponse fetchStatusPage(StatusPageServer.HttpRequest httpRequest) {
verifyInControllerThread();
StatusPageResponse.ResponseCode responseCode;
String message;
final String hiddenMessage;
try {
StatusPageServer.RequestHandler handler = statusRequestRouter.resolveHandler(httpRequest);
if (handler == null) {
throw new FileNotFoundException("No handler found for request: " + httpRequest.getPath());
}
return handler.handle(httpRequest);
} catch (FileNotFoundException e) {
responseCode = StatusPageResponse.ResponseCode.NOT_FOUND;
message = e.getMessage();
hiddenMessage = "";
} catch (Exception e) {
responseCode = StatusPageResponse.ResponseCode.INTERNAL_SERVER_ERROR;
message = "Internal Server Error";
hiddenMessage = ExceptionUtils.getStackTraceAsString(e);
context.log(logger, Level.FINE, () -> "Unknown exception thrown for request " + httpRequest.getRequest() + ": " + hiddenMessage);
}
TimeZone tz = TimeZone.getTimeZone("UTC");
long currentTime = timer.getCurrentTimeInMillis();
StatusPageResponse response = new StatusPageResponse();
StringBuilder content = new StringBuilder();
response.setContentType("text/html");
response.setResponseCode(responseCode);
content.append("<!-- Answer to request " + httpRequest.getRequest() + " -->\n");
content.append("<p>UTC time when creating this page: ").append(RealTimer.printDateNoMilliSeconds(currentTime, tz)).append("</p>");
response.writeHtmlHeader(content, message);
response.writeHtmlFooter(content, hiddenMessage);
response.writeContent(content.toString());
return response;
}
public void tick() throws Exception {
synchronized (monitor) {
boolean didWork;
didWork = metricUpdater.forWork("doNextZooKeeperTask", () -> database.doNextZooKeeperTask(databaseContext));
didWork |= metricUpdater.forWork("updateMasterElectionState", this::updateMasterElectionState);
didWork |= metricUpdater.forWork("handleLeadershipEdgeTransitions", this::handleLeadershipEdgeTransitions);
stateChangeHandler.setMaster(isMaster);
if ( ! isRunning()) { return; }
// Process zero or more getNodeState responses that we have received.
didWork |= metricUpdater.forWork("stateGatherer-processResponses", () -> stateGatherer.processResponses(this));
if ( ! isRunning()) { return; }
if (masterElectionHandler.isAmongNthFirst(options.stateGatherCount)) {
didWork |= resyncLocallyCachedState(); // Calls to metricUpdate.forWork inside method
} else {
stepDownAsStateGatherer();
}
if ( ! isRunning()) { return; }
didWork |= metricUpdater.forWork("systemStateBroadcaster-processResponses", systemStateBroadcaster::processResponses);
if ( ! isRunning()) { return; }
if (isMaster) {
didWork |= metricUpdater.forWork("broadcastClusterStateToEligibleNodes", this::broadcastClusterStateToEligibleNodes);
systemStateBroadcaster.checkIfClusterStateIsAckedByAllDistributors(database, databaseContext, this);
}
if ( ! isRunning()) { return; }
didWork |= metricUpdater.forWork("processAnyPendingStatusPageRequest", this::processAnyPendingStatusPageRequest);
if ( ! isRunning()) { return; }
if (rpcServer != null) {
didWork |= metricUpdater.forWork("handleRpcRequests", () -> rpcServer.handleRpcRequests(cluster, consolidatedClusterState(), this));
}
if ( ! isRunning()) { return; }
didWork |= metricUpdater.forWork("processNextQueuedRemoteTask", this::processNextQueuedRemoteTask);
didWork |= metricUpdater.forWork("completeSatisfiedVersionDependentTasks", this::completeSatisfiedVersionDependentTasks);
didWork |= metricUpdater.forWork("maybePublishOldMetrics", this::maybePublishOldMetrics);
processingCycle = false;
++cycleCount;
long tickStopTime = timer.getCurrentTimeInMillis();
if (tickStopTime >= tickStartTime) {
metricUpdater.addTickTime(tickStopTime - tickStartTime, didWork);
}
// Always sleep some to use avoid using too much CPU and avoid starving waiting threads
monitor.wait(didWork || waitingForCycle ? 1 : options.cycleWaitTime);
if ( ! isRunning()) { return; }
tickStartTime = timer.getCurrentTimeInMillis();
processingCycle = true;
if (nextOptions != null) { // if reconfiguration has given us new options, propagate them
switchToNewConfig();
}
}
if (isRunning()) {
propagateNewStatesToListeners();
}
}
private boolean updateMasterElectionState() {
try {
return masterElectionHandler.watchMasterElection(database, databaseContext);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (Exception e) {
context.log(logger, Level.WARNING, "Failed to watch master election: " + e);
}
return false;
}
private void stepDownAsStateGatherer() {
if (isStateGatherer) {
cluster.clearStates(); // Remove old states that we are no longer certain of as we stop gathering information
eventLog.add(new ClusterEvent(ClusterEvent.Type.MASTER_ELECTION, "This node is no longer a node state gatherer.", timer.getCurrentTimeInMillis()));
}
isStateGatherer = false;
}
private void switchToNewConfig() {
options = nextOptions;
nextOptions = null;
try {
propagateOptions();
} catch (Exception e) {
context.log(logger, Level.SEVERE, "Failed to handle new fleet controller config", e);
}
}
private boolean processAnyPendingStatusPageRequest() {
StatusPageServer.HttpRequest statusRequest = statusPageServer.getCurrentHttpRequest();
if (statusRequest != null) {
statusPageServer.answerCurrentStatusRequest(fetchStatusPage(statusRequest));
return true;
}
return false;
}
private boolean broadcastClusterStateToEligibleNodes() {
// If there's a pending DB store we have not yet been able to store the
// current state bundle to ZK and must therefore _not_ allow it to be published.
if (database.hasPendingClusterStateMetaDataStore()) {
context.log(logger, Level.FINE, "Can't publish current cluster state as it has one or more pending ZooKeeper stores");
return false;
}
boolean sentAny = false;
// Give nodes a fair chance to respond first time to state gathering requests, so we don't
// disturb system when we take over. Allow anyways if we have states from all nodes.
long currentTime = timer.getCurrentTimeInMillis();
if ((currentTime >= firstAllowedStateBroadcast || cluster.allStatesReported())
&& currentTime >= nextStateSendTime)
{
if (inMasterMoratorium) {
context.log(logger, Level.INFO, currentTime < firstAllowedStateBroadcast ?
"Master moratorium complete: all nodes have reported in" :
"Master moratorium complete: timed out waiting for all nodes to report in");
// Reset firstAllowedStateBroadcast to make sure all future times are after firstAllowedStateBroadcast
firstAllowedStateBroadcast = currentTime;
inMasterMoratorium = false;
}
sentAny = systemStateBroadcaster.broadcastNewStateBundleIfRequired(
databaseContext, communicator, database.getLastKnownStateBundleVersionWrittenBySelf());
if (sentAny) {
// FIXME won't this inhibit resending to unresponsive nodes?
nextStateSendTime = currentTime + options.minTimeBetweenNewSystemStates;
}
}
// Always allow activations if we've already broadcasted a state
sentAny |= systemStateBroadcaster.broadcastStateActivationsIfRequired(databaseContext, communicator);
return sentAny;
}
private void propagateNewStatesToListeners() {
if ( ! newStates.isEmpty()) {
synchronized (systemStateListeners) {
for (ClusterStateBundle stateBundle : newStates) {
for (SystemStateListener listener : systemStateListeners) {
listener.handleNewPublishedState(stateBundle);
}
}
newStates.clear();
}
}
if ( ! convergedStates.isEmpty()) {
synchronized (systemStateListeners) {
for (ClusterStateBundle stateBundle : convergedStates) {
for (SystemStateListener listener : systemStateListeners) {
listener.handleStateConvergedInCluster(stateBundle);
}
}
convergedStates.clear();
}
}
}
private boolean processNextQueuedRemoteTask() {
metricUpdater.updateRemoteTaskQueueSize(remoteTasks.size());
RemoteClusterControllerTask task = remoteTasks.poll();
if (task == null) {
return false;
}
final RemoteClusterControllerTask.Context taskContext = createRemoteTaskProcessingContext();
context.log(logger, Level.FINEST, () -> String.format("Processing remote task of type '%s'", task.getClass().getName()));
task.doRemoteFleetControllerTask(taskContext);
if (taskMayBeCompletedImmediately(task)) {
context.log(logger, Level.FINEST, () -> String.format("Done processing remote task of type '%s'", task.getClass().getName()));
task.notifyCompleted();
} else {
context.log(logger, Level.FINEST, () -> String.format("Remote task of type '%s' queued until state recomputation", task.getClass().getName()));
tasksPendingStateRecompute.add(task);
}
return true;
}
private boolean taskMayBeCompletedImmediately(RemoteClusterControllerTask task) {
// We cannot introduce a version barrier for tasks when we're not the master (and therefore will not publish new versions).
return (!task.hasVersionAckDependency() || task.isFailed() || !isMaster);
}
private RemoteClusterControllerTask.Context createRemoteTaskProcessingContext() {
final RemoteClusterControllerTask.Context context = new RemoteClusterControllerTask.Context();
context.cluster = cluster;
context.currentConsolidatedState = consolidatedClusterState();
context.publishedClusterStateBundle = stateVersionTracker.getVersionedClusterStateBundle();
context.masterInfo = new MasterInterface() {
@Override public boolean isMaster() { return isMaster; }
@Override public Integer getMaster() { return masterElectionHandler.getMaster(); }
@Override public boolean inMasterMoratorium() { return inMasterMoratorium; }
};
context.nodeListener = this;
context.slobrokListener = this;
return context;
}
private static long effectiveActivatedStateVersion(NodeInfo nodeInfo, ClusterStateBundle bundle) {
return bundle.deferredActivation()
? nodeInfo.getClusterStateVersionActivationAcked()
: nodeInfo.getClusterStateVersionBundleAcknowledged();
}
private List<Node> enumerateNodesNotYetAckedAtLeastVersion(long version) {
var bundle = systemStateBroadcaster.getClusterStateBundle();
if (bundle == null) {
return List.of();
}
return cluster.getNodeInfos().stream().
filter(n -> effectiveActivatedStateVersion(n, bundle) < version).
map(NodeInfo::getNode).
collect(Collectors.toList());
}
private static <E> String stringifyListWithLimits(List<E> list, int limit) {
if (list.size() > limit) {
var sub = list.subList(0, limit);
return String.format("%s (... and %d more)",
sub.stream().map(E::toString).collect(Collectors.joining(", ")),
list.size() - limit);
} else {
return list.stream().map(E::toString).collect(Collectors.joining(", "));
}
}
private String buildNodesNotYetConvergedMessage(long taskConvergeVersion) {
var nodes = enumerateNodesNotYetAckedAtLeastVersion(taskConvergeVersion);
if (nodes.isEmpty()) {
return "";
}
return String.format("the following nodes have not converged to at least version %d: %s",
taskConvergeVersion, stringifyListWithLimits(nodes, options.maxDivergentNodesPrintedInTaskErrorMessages));
}
private boolean completeSatisfiedVersionDependentTasks() {
int publishedVersion = systemStateBroadcaster.lastClusterStateVersionInSync();
long queueSizeBefore = taskCompletionQueue.size();
// Note: although version monotonicity of tasks in queue always should hold,
// deadline monotonicity is not guaranteed to do so due to reconfigs of task
// timeout durations. Means that tasks enqueued with shorter deadline duration
// might be observed as having at least the same timeout as tasks enqueued during
// a previous configuration. Current clock implementation is also susceptible to
// skewing.
final long now = timer.getCurrentTimeInMillis();
while (!taskCompletionQueue.isEmpty()) {
VersionDependentTaskCompletion taskCompletion = taskCompletionQueue.peek();
// TODO expose and use monotonic clock instead of system clock
if (publishedVersion >= taskCompletion.getMinimumVersion()) {
context.log(logger, Level.FINE, () -> String.format("Deferred task of type '%s' has minimum version %d, published is %d; completing",
taskCompletion.getTask().getClass().getName(), taskCompletion.getMinimumVersion(), publishedVersion));
taskCompletion.getTask().notifyCompleted();
taskCompletionQueue.remove();
} else if (taskCompletion.getDeadlineTimePointMs() <= now) {
var details = buildNodesNotYetConvergedMessage(taskCompletion.getMinimumVersion());
context.log(logger, Level.WARNING, () -> String.format("Deferred task of type '%s' has exceeded wait deadline; completing with failure (details: %s)",
taskCompletion.getTask().getClass().getName(), details));
taskCompletion.getTask().handleFailure(RemoteClusterControllerTask.Failure.of(
RemoteClusterControllerTask.FailureCondition.DEADLINE_EXCEEDED, details));
taskCompletion.getTask().notifyCompleted();
taskCompletionQueue.remove();
} else {
break;
}
}
return (taskCompletionQueue.size() != queueSizeBefore);
}
/**
* A "consolidated" cluster state is guaranteed to have up-to-date information on which nodes are
* up or down even when the whole cluster is down. The regular, published cluster state is not
* normally updated to reflect node events when the cluster is down.
*/
ClusterState consolidatedClusterState() {
final ClusterState publishedState = stateVersionTracker.getVersionedClusterState();
if (publishedState.getClusterState() == State.UP) {
return publishedState; // Short-circuit; already represents latest node state
}
// Latest candidate state contains the most up to date state information, even if it may not
// have been published yet.
final ClusterState current = stateVersionTracker.getLatestCandidateState().getClusterState().clone();
current.setVersion(publishedState.getVersion());
return current;
}
/*
System test observations:
- a node that stops normally (U -> S) then goes down erroneously triggers premature crash handling
- long time before content node state convergence (though this seems to be the case for legacy impl as well)
*/
private boolean resyncLocallyCachedState() {
boolean didWork = false;
// Let non-master state gatherers update wanted states once in a while, so states generated and shown are close to valid.
if ( ! isMaster && cycleCount % 100 == 0) {
didWork = metricUpdater.forWork("loadWantedStates", () -> database.loadWantedStates(databaseContext));
didWork |= metricUpdater.forWork("loadStartTimestamps", () -> database.loadStartTimestamps(cluster));
}
// If we have new slobrok information, update our cluster.
didWork |= metricUpdater.forWork("updateCluster", () -> nodeLookup.updateCluster(cluster, this));
// Send getNodeState requests to zero or more nodes.
didWork |= metricUpdater.forWork("sendMessages", () -> stateGatherer.sendMessages(cluster, communicator, this));
// Important: timer events must use a state with pending changes visible, or they might
// trigger edge events multiple times.
didWork |= metricUpdater.forWork(
"watchTimers",
() -> stateChangeHandler.watchTimers(cluster, stateVersionTracker.getLatestCandidateState().getClusterState(), this));
didWork |= metricUpdater.forWork("recomputeClusterStateIfRequired", this::recomputeClusterStateIfRequired);
if ( ! isStateGatherer) {
if ( ! isMaster) {
eventLog.add(new ClusterEvent(ClusterEvent.Type.MASTER_ELECTION, "This node just became node state gatherer as we are fleetcontroller master candidate.", timer.getCurrentTimeInMillis()));
// Update versions to use so what is shown is closer to what is reality on the master
stateVersionTracker.setVersionRetrievedFromZooKeeper(database.getLatestSystemStateVersion());
stateChangeHandler.setStateChangedFlag();
}
}
isStateGatherer = true;
return didWork;
}
private void invokeCandidateStateListeners(ClusterStateBundle candidateBundle) {
systemStateListeners.forEach(listener -> listener.handleNewCandidateState(candidateBundle));
}
private boolean hasPassedFirstStateBroadcastTimePoint(long timeNowMs) {
return timeNowMs >= firstAllowedStateBroadcast || cluster.allStatesReported();
}
private boolean recomputeClusterStateIfRequired() {
boolean stateWasChanged = false;
if (mustRecomputeCandidateClusterState()) {
stateChangeHandler.unsetStateChangedFlag();
final AnnotatedClusterState candidate = computeCurrentAnnotatedState();
// TODO test multiple bucket spaces configured
// TODO what interaction do we want between generated and derived states wrt. auto group take-downs?
final ClusterStateBundle candidateBundle = ClusterStateBundle.builder(candidate)
.bucketSpaces(configuredBucketSpaces)
.stateDeriver(createBucketSpaceStateDeriver())
.deferredActivation(options.enableTwoPhaseClusterStateActivation)
.feedBlock(createResourceExhaustionCalculator()
.inferContentClusterFeedBlockOrNull(cluster.getNodeInfos()))
.deriveAndBuild();
stateVersionTracker.updateLatestCandidateStateBundle(candidateBundle);
invokeCandidateStateListeners(candidateBundle);
final long timeNowMs = timer.getCurrentTimeInMillis();
if (hasPassedFirstStateBroadcastTimePoint(timeNowMs)
&& (stateVersionTracker.candidateChangedEnoughFromCurrentToWarrantPublish()
|| stateVersionTracker.hasReceivedNewVersionFromZooKeeper()))
{
final ClusterStateBundle before = stateVersionTracker.getVersionedClusterStateBundle();
stateVersionTracker.promoteCandidateToVersionedState(timeNowMs);
emitEventsForAlteredStateEdges(before, stateVersionTracker.getVersionedClusterStateBundle(), timeNowMs);
handleNewPublishedState(stateVersionTracker.getVersionedClusterStateBundle());
stateWasChanged = true;
}
}
/*
* This works transparently for tasks that end up changing the current cluster state (i.e.
* requiring a new state to be published) and for those whose changes are no-ops (because
* the changes they request are already part of the current state). In the former case the
* tasks will depend on the version that was generated based upon them. In the latter case
* the tasks will depend on the version that is already published (or in the process of
* being published).
*/
scheduleVersionDependentTasksForFutureCompletion(stateVersionTracker.getCurrentVersion());
return stateWasChanged;
}
private ClusterStateDeriver createBucketSpaceStateDeriver() {
if (options.clusterHasGlobalDocumentTypes) {
return new MaintenanceWhenPendingGlobalMerges(stateVersionTracker.createMergePendingChecker(),
createDefaultSpaceMaintenanceTransitionConstraint());
} else {
return createIdentityClonedBucketSpaceStateDeriver();
}
}
private ResourceExhaustionCalculator createResourceExhaustionCalculator() {
return new ResourceExhaustionCalculator(
options.clusterFeedBlockEnabled, options.clusterFeedBlockLimit,
stateVersionTracker.getLatestCandidateStateBundle().getFeedBlockOrNull(),
options.clusterFeedBlockNoiseLevel);
}
private static ClusterStateDeriver createIdentityClonedBucketSpaceStateDeriver() {
return (state, space) -> state.clone();
}
private MaintenanceTransitionConstraint createDefaultSpaceMaintenanceTransitionConstraint() {
AnnotatedClusterState currentDefaultSpaceState = stateVersionTracker.getVersionedClusterStateBundle()
.getDerivedBucketSpaceStates().getOrDefault(FixedBucketSpaces.defaultSpace(), AnnotatedClusterState.emptyState());
return UpEdgeMaintenanceTransitionConstraint.forPreviouslyPublishedState(currentDefaultSpaceState.getClusterState());
}
/**
* Move tasks that are dependent on the most recently generated state being published into
* a completion queue with a dependency on the provided version argument. Once that version
* has been ACKed by all distributors in the system, those tasks will be marked as completed.
*/
private void scheduleVersionDependentTasksForFutureCompletion(int completeAtVersion) {
// TODO expose and use monotonic clock instead of system clock
final long maxDeadlineTimePointMs = timer.getCurrentTimeInMillis() + options.getMaxDeferredTaskVersionWaitTime().toMillis();
for (RemoteClusterControllerTask task : tasksPendingStateRecompute) {
context.log(logger, Level.INFO, task + " will be completed at version " + completeAtVersion);
taskCompletionQueue.add(new VersionDependentTaskCompletion(completeAtVersion, task, maxDeadlineTimePointMs));
}
tasksPendingStateRecompute.clear();
}
private AnnotatedClusterState computeCurrentAnnotatedState() {
ClusterStateGenerator.Params params = ClusterStateGenerator.Params.fromOptions(options);
params.currentTimeInMillis(timer.getCurrentTimeInMillis())
.cluster(cluster)
.lowestObservedDistributionBitCount(stateVersionTracker.getLowestObservedDistributionBits());
return ClusterStateGenerator.generatedStateFrom(params);
}
private void emitEventsForAlteredStateEdges(final ClusterStateBundle fromState,
final ClusterStateBundle toState,
final long timeNowMs) {
final List<Event> deltaEvents = EventDiffCalculator.computeEventDiff(
EventDiffCalculator.params()
.cluster(cluster)
.fromState(fromState)
.toState(toState)
.currentTimeMs(timeNowMs)
.maxMaintenanceGracePeriodTimeMs(options.storageNodeMaxTransitionTimeMs()));
for (Event event : deltaEvents) {
eventLog.add(event, isMaster);
}
emitStateAppliedEvents(timeNowMs, fromState.getBaselineClusterState(), toState.getBaselineClusterState());
}
private void emitStateAppliedEvents(long timeNowMs, ClusterState fromClusterState, ClusterState toClusterState) {
eventLog.add(new ClusterEvent(
ClusterEvent.Type.SYSTEMSTATE,
"New cluster state version " + toClusterState.getVersion() + ". Change from last: " +
fromClusterState.getTextualDifference(toClusterState),
timeNowMs), isMaster);
if (toClusterState.getDistributionBitCount() != fromClusterState.getDistributionBitCount()) {
eventLog.add(new ClusterEvent(
ClusterEvent.Type.SYSTEMSTATE,
"Altering distribution bits in system from "
+ fromClusterState.getDistributionBitCount() + " to " +
toClusterState.getDistributionBitCount(),
timeNowMs), isMaster);
}
}
private boolean atFirstClusterStateSendTimeEdge() {
// We only care about triggering a state recomputation for the master, which is the only
// one allowed to actually broadcast any states.
if (!isMaster || systemStateBroadcaster.hasBroadcastedClusterStateBundle()) {
return false;
}
return hasPassedFirstStateBroadcastTimePoint(timer.getCurrentTimeInMillis());
}
private boolean mustRecomputeCandidateClusterState() {
return stateChangeHandler.stateMayHaveChanged()
|| stateVersionTracker.bucketSpaceMergeCompletionStateHasChanged()
|| atFirstClusterStateSendTimeEdge();
}
private boolean handleLeadershipEdgeTransitions() {
boolean didWork = false;
if (masterElectionHandler.isMaster()) {
if ( ! isMaster) {
// If we just became master, restore state from ZooKeeper
stateChangeHandler.setStateChangedFlag();
systemStateBroadcaster.resetBroadcastedClusterStateBundle();
stateVersionTracker.setVersionRetrievedFromZooKeeper(database.getLatestSystemStateVersion());
ClusterStateBundle previousBundle = database.getLatestClusterStateBundle();
database.loadStartTimestamps(cluster);
database.loadWantedStates(databaseContext);
// TODO determine if we need any specialized handling here if feed block is set in the loaded bundle
context.log(logger, Level.INFO, () -> String.format("Loaded previous cluster state bundle from ZooKeeper: %s", previousBundle));
stateVersionTracker.setClusterStateBundleRetrievedFromZooKeeper(previousBundle);
eventLog.add(new ClusterEvent(ClusterEvent.Type.MASTER_ELECTION, "This node just became fleetcontroller master. Bumped version to "
+ stateVersionTracker.getCurrentVersion() + " to be in line.", timer.getCurrentTimeInMillis()));
long currentTime = timer.getCurrentTimeInMillis();
firstAllowedStateBroadcast = currentTime + options.minTimeBeforeFirstSystemStateBroadcast;
isMaster = true;
inMasterMoratorium = true;
context.log(logger, Level.FINE, () -> "At time " + currentTime + " we set first system state broadcast time to be "
+ options.minTimeBeforeFirstSystemStateBroadcast + " ms after at time " + firstAllowedStateBroadcast + ".");
didWork = true;
}
if (wantedStateChanged) {
didWork |= database.saveWantedStates(databaseContext);
wantedStateChanged = false;
}
} else {
dropLeadershipState();
}
metricUpdater.updateMasterState(isMaster);
return didWork;
}
private void dropLeadershipState() {
if (isMaster) {
eventLog.add(new ClusterEvent(ClusterEvent.Type.MASTER_ELECTION, "This node is no longer fleetcontroller master.", timer.getCurrentTimeInMillis()));
firstAllowedStateBroadcast = Long.MAX_VALUE;
failAllVersionDependentTasks();
}
wantedStateChanged = false;
isMaster = false;
inMasterMoratorium = false;
}
@Override
public void run() {
controllerThreadId = Thread.currentThread().getId();
context.log(logger, Level.INFO, "Starting tick loop");
try {
processingCycle = true;
while (isRunning()) {
tick();
}
context.log(logger, Level.INFO, "Tick loop stopped");
} catch (InterruptedException e) {
context.log(logger, Level.INFO, "Event thread stopped by interrupt exception: ", e);
} catch (Throwable t) {
t.printStackTrace();
context.log(logger, Level.SEVERE, "Fatal error killed fleet controller", t);
synchronized (monitor) { running.set(false); }
System.exit(1);
} finally {
prepareShutdownEdge();
}
}
private void prepareShutdownEdge() {
running.set(false);
failAllVersionDependentTasks();
synchronized (monitor) { monitor.notifyAll(); }
}
public DatabaseHandler.DatabaseContext databaseContext = new DatabaseHandler.DatabaseContext() {
@Override
public ContentCluster getCluster() { return cluster; }
@Override
public FleetController getFleetController() { return FleetController.this; }
@Override
public NodeListener getNodeStateUpdateListener() { return FleetController.this; }
};
// For testing only
public void waitForCompleteCycle(Duration timeout) {
Instant endTime = Instant.now().plus(timeout);
synchronized (monitor) {
// To wait at least one complete cycle, if a cycle is already running we need to wait for the next one beyond.
long wantedCycle = cycleCount + (processingCycle ? 2 : 1);
waitingForCycle = true;
try{
while (cycleCount < wantedCycle) {
if (Instant.now().isAfter(endTime))
throw new IllegalStateException("Timed out waiting for cycle to complete. Not completed after " + timeout);
if ( !isRunning() )
throw new IllegalStateException("Fleetcontroller not running. Will never complete cycles");
try {
monitor.wait(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
} finally {
waitingForCycle = false;
}
}
}
/**
* This function might not be 100% threadsafe, as in theory cluster can be changing while accessed.
* But it is only used in unit tests that should not trigger any thread issues. Don't want to add locks that reduce
* live performance to remove a non-problem.
*/
public void waitForNodesHavingSystemStateVersionEqualToOrAbove(int version, int nodeCount, Duration timeout) throws InterruptedException {
Instant endTime = Instant.now().plus(timeout);
synchronized (monitor) {
while (true) {
int ackedNodes = 0;
for (NodeInfo node : cluster.getNodeInfos()) {
if (node.getClusterStateVersionBundleAcknowledged() >= version) {
++ackedNodes;
}
}
if (ackedNodes >= nodeCount) {
context.log(logger, Level.INFO, ackedNodes + " nodes now have acked system state " + version + " or higher.");
return;
}
if (Instant.now().isAfter(endTime)) {
throw new IllegalStateException("Did not get " + nodeCount + " nodes to system state " + version + " within timeout of " + timeout);
}
monitor.wait(10);
}
}
}
public void waitForNodesInSlobrok(int distNodeCount, int storNodeCount, Duration timeout) throws InterruptedException {
Instant endTime = Instant.now().plus(timeout);
synchronized (monitor) {
while (true) {
int distCount = 0, storCount = 0;
for (NodeInfo info : cluster.getNodeInfos()) {
if (info.isInSlobrok()) {
if (info.isDistributor()) ++distCount;
else ++storCount;
}
}
if (distCount == distNodeCount && storCount == storNodeCount) return;
if (Instant.now().isAfter(endTime)) {
throw new IllegalStateException("Did not get all " + distNodeCount + " distributors and " + storNodeCount
+ " storage nodes registered in slobrok within timeout of " + timeout + ". (Got "
+ distCount + " distributors and " + storCount + " storage nodes)");
}
monitor.wait(10);
}
}
}
public boolean hasZookeeperConnection() { return !database.isClosed(); }
// Used by unit tests.
public int getSlobrokMirrorUpdates() { return ((SlobrokClient)nodeLookup).getMirror().updates(); }
public ContentCluster getCluster() { return cluster; }
public EventLog getEventLog() {
return eventLog;
}
} |
package org.opendaylight.netvirt.coe.listeners;
import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.genius.datastoreutils.listeners.DataTreeEventCallbackRegistrar;
import org.opendaylight.genius.infra.Datastore;
import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
import org.opendaylight.genius.infra.TypedReadWriteTransaction;
import org.opendaylight.genius.mdsalutil.MDSALUtil;
import org.opendaylight.genius.mdsalutil.NwConstants;
import org.opendaylight.genius.utils.ServiceIndex;
import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
import org.opendaylight.netvirt.coe.api.SouthboundInterfaceInfo;
import org.opendaylight.netvirt.coe.caches.PodsCache;
import org.opendaylight.netvirt.coe.utils.CoeUtils;
import org.opendaylight.serviceutils.tools.mdsal.listener.AbstractSyncDataTreeChangeListener;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.coe.northbound.pod.rev170611.coe.Pods;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class TerminationPointStateListener extends
AbstractSyncDataTreeChangeListener<OvsdbTerminationPointAugmentation> {
private static final Logger LOG = LoggerFactory.getLogger(TerminationPointStateListener.class);
private final PodsCache podsCache;
private final DataTreeEventCallbackRegistrar eventCallbacks;
private final ManagedNewTransactionRunner txRunner;
@Inject
public TerminationPointStateListener(DataBroker dataBroker,
PodsCache podsCache, DataTreeEventCallbackRegistrar eventCallbacks) {
super(dataBroker, LogicalDatastoreType.OPERATIONAL,
InstanceIdentifier.builder(NetworkTopology.class).child(Topology.class).child(Node.class)
.child(TerminationPoint.class).augmentation(OvsdbTerminationPointAugmentation.class).build());
this.podsCache = podsCache;
this.eventCallbacks = eventCallbacks;
this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
}
@Override
public void remove(OvsdbTerminationPointAugmentation tpOld) {
// DO nothing
}
@Override
public void update(@Nullable OvsdbTerminationPointAugmentation tpOld, OvsdbTerminationPointAugmentation tpNew) {
LOG.debug("Received Update DataChange Notification for ovsdb termination point {}", tpNew.getName());
SouthboundInterfaceInfo tpNewDetails = CoeUtils.getSouthboundInterfaceDetails(tpNew);
SouthboundInterfaceInfo tpOldDetails = CoeUtils.getSouthboundInterfaceDetails(tpOld);
if (!Objects.equals(tpNewDetails, tpOldDetails)) {
Optional<String> interfaceNameOptional = tpNewDetails.getInterfaceName();
Optional<String> macAddressOptional = tpNewDetails.getMacAddress();
if (interfaceNameOptional.isPresent() && macAddressOptional.isPresent()) {
String interfaceName = interfaceNameOptional.get();
String macAddress = macAddressOptional.get();
boolean isServiceGateway = tpNewDetails.isServiceGateway().orElse(false);
LOG.debug("Detected external interface-id {} and attached mac address {} for {}", interfaceName,
macAddress, tpNew.getName());
eventCallbacks.onAddOrUpdate(LogicalDatastoreType.OPERATIONAL,
CoeUtils.getPodMetaInstanceId(interfaceName), (unused, alsoUnused) -> {
LOG.info("Pod configuration {} detected for termination-point {},"
+ "proceeding with l2 and l3 configurations", interfaceName, tpNew.getName());
ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(
CONFIGURATION, tx -> {
InstanceIdentifier<Pods> instanceIdentifier = CoeUtils.getPodUUIDforPodName(
interfaceName, getDataBroker());
Pods pods = podsCache.get(instanceIdentifier).get();
if (pods != null) {
IpAddress podIpAddress = pods.getInterface().get(0).getIpAddress();
CoeUtils.updateElanInterfaceWithStaticMac(macAddress, podIpAddress,
interfaceName, tx);
if (!isServiceGateway) {
CoeUtils.createVpnInterface(pods.getClusterId().getValue(), pods, interfaceName,
macAddress,false, tx);
LOG.debug("Bind Kube Proxy Service for {}", interfaceName);
bindKubeProxyService(tx, interfaceName);
}
}
}), LOG, "Error handling pod configuration for termination-point");
return DataTreeEventCallbackRegistrar.NextAction.UNREGISTER;
});
}
}
}
@Override
public void add(OvsdbTerminationPointAugmentation tpNew) {
update(null, tpNew);
}
private static void bindKubeProxyService(TypedReadWriteTransaction<Datastore.Configuration> tx,
String interfaceName) {
int priority = ServiceIndex.getIndex(NwConstants.COE_KUBE_PROXY_SERVICE_NAME,
NwConstants.COE_KUBE_PROXY_SERVICE_INDEX);
int instructionKey = 0;
List<Instruction> instructions = new ArrayList<>();
instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(
NwConstants.COE_KUBE_PROXY_TABLE, ++instructionKey));
BoundServices serviceInfo =
getBoundServices(String.format("%s.%s", NwConstants.COE_KUBE_PROXY_SERVICE_NAME, interfaceName),
ServiceIndex.getIndex(NwConstants.COE_KUBE_PROXY_SERVICE_NAME,
NwConstants.COE_KUBE_PROXY_SERVICE_INDEX),
priority, NwConstants.COOKIE_COE_KUBE_PROXY_TABLE, instructions);
InstanceIdentifier<BoundServices> boundServicesInstanceIdentifier =
CoeUtils.buildKubeProxyServicesIId(interfaceName);
tx.put(boundServicesInstanceIdentifier, serviceInfo,true);
}
private static BoundServices getBoundServices(String serviceName, short servicePriority, int flowPriority,
BigInteger cookie, List<Instruction> instructions) {
StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookie).setFlowPriority(flowPriority)
.setInstruction(instructions);
return new BoundServicesBuilder().withKey(new BoundServicesKey(servicePriority)).setServiceName(serviceName)
.setServicePriority(servicePriority).setServiceType(ServiceTypeFlowBased.class)
.addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
}
} |
package com.google.maps.android.heatmaps;
import android.graphics.Bitmap;
import android.graphics.Color;
import com.google.maps.android.geometry.Bounds;
import java.util.Collection;
import java.util.Iterator;
/**
* Utility functions for heatmaps.
* Based off the javascript heatmaps code
*/
public class HeatmapUtil {
/**
* Default size of a color map for the heatmap
*/
private static final int COLOR_MAP_SIZE = 1001;
/**
* Helper function for quadtree creation
*
* @param points Collection of LatLngWrapper to calculate bounds for
* @return Bounds that enclose the listed LatLngWrapper points
*/
public static Bounds getBounds(Collection<LatLngWrapper> points) {
// Sigma is used to ensure search is inclusive of upper bounds (eg if a point
// is on exactly the upper bound, it should be returned)
double sigma = 0.0000001;
// Use an iterator, need to access any one point of the collection for starting bounds
Iterator<LatLngWrapper> iter = points.iterator();
LatLngWrapper first = iter.next();
double minX = first.getPoint().x;
double maxX = first.getPoint().x + sigma;
double minY = first.getPoint().y;
double maxY = first.getPoint().y + sigma;
while (iter.hasNext()) {
LatLngWrapper l = iter.next();
double x = l.getPoint().x;
double y = l.getPoint().y;
// Extend bounds if necessary
if (x < minX) minX = x;
if (x + sigma > maxX) maxX = x + sigma;
if (y < minY) minY = y;
if (y + sigma > maxY) maxY = y + sigma;
}
return new Bounds(minX, maxX, minY, maxY);
}
/**
* Generates 1D Gaussian kernel density function, as a double array of size radius * 2 + 1
* Normalised with central value of 1.
*
* @param radius radius of the kernel
* @param sigma standard deviation of the Gaussian function
* @return generated Gaussian kernel
*/
public static double[] generateKernel(int radius, double sigma) {
double[] kernel = new double[radius * 2 + 1];
for (int i = -radius; i <= radius; i++) {
kernel[i + radius] = (Math.exp(-i * i / (2 * sigma * sigma)));
}
return kernel;
}
/**
* Applies a 2D Gaussian convolution to the input grid, returning a 2D grid cropped of padding.
*
* @param grid Raw input grid to convolve: dimension dim+2*radius x dim + 2*radius
* ie dim * dim with padding of size radius
* @param kernel Pre-computed Gaussian kernel of size radius*2+1
* @return the smoothened grid
*/
public static double[][] convolve(double[][] grid, double[] kernel) {
// Calculate radius size
int radius = (int) Math.floor((double) kernel.length / 2.0);
// Padded dimension
int dimOld = grid.length;
// Calculate final (non padded) dimension
int dim = dimOld - 2 * radius;
// Upper and lower limits of non padded (inclusive)
int lowerLimit = radius;
int upperLimit = radius + dim - 1;
// Convolve horizontally
double[][] intermediate = new double[dimOld][dimOld];
// Need to convolve every point (including those outside of non-padded area)
// but only need to add to points within non-padded area
int x, y, x2;
double val;
for (x = 0; x < dimOld; x++) {
for (y = 0; y < dimOld; y++) {
// for each point (x, y)
val = grid[x][y];
// only bother if something there
if (val != 0) {
// need to "apply" convolution from that point to every point in
// (max(lowerLimit, x - radius), y) to (min(upperLimit, x + radius), y)
for (x2 = Math.max(lowerLimit, x - radius);
x2 < Math.min(upperLimit, x + radius) + 1; x2++) {
// multiplier for x2 = x - radius is kernel[0]
// x2 = x + radius is kernel[radius * 2]
// so multiplier for x2 in general is kernel[x2 - (x - radius)]
intermediate[x2][y] += val * kernel[x2 - (x - radius)];
}
}
}
}
// Convolve vertically
double[][] outputGrid = new double[dim][dim];
// Similarly, need to convolve every point, but only add to points within non-padded area
// However, we are adding to a smaller grid here (previously, was to a grid of same size)
int y2;
// Don't care about convolving parts in horizontal padding - wont impact inner
for (x = lowerLimit; x < upperLimit + 1; x++) {
for (y = 0; y < dimOld; y++) {
// for each point (x, y)
val = intermediate[x][y];
// only bother if something there
if (val != 0) {
// need to "apply" convolution from that point to every point in
// (x, max(lowerLimit, y - radius) to (x, min(upperLimit, y + radius))
// Dont care about
for (y2 = Math.max(lowerLimit, y - radius);
y2 < Math.min(upperLimit, y + radius) + 1; y2++) {
// Similar logic to above
// subtract, as adding to a smaller grid
outputGrid[x - radius][y2 - radius] += val * kernel[y2 - (y - radius)];
}
}
}
}
return outputGrid;
}
public static Bitmap colorize(double[][] grid, int[] colorMap, double max) {
// Maximum color value
int maxColor = colorMap[colorMap.length - 1];
// Multiplier to "scale" intensity values with, to map to appropriate color
// TODO: is this change (-1 to length) ok? Reasoning: otherwise max will break it
double colorMapScaling = (colorMap.length - 1) / max;
// Dimension of the input grid (and dimension of output bitmap)
int dim = grid.length;
int i, j, index, col;
double val;
// Array of colours
int colors[] = new int[dim * dim];
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
// need to enter each row of x coordinates sequentally (x first)
val = grid[j][i];
index = i * dim + j;
col = (int) (val * colorMapScaling);
if ((int) val != 0) {
// Make it more resilient: cant go outside colorMap
if (col < colorMap.length) colors[index] = colorMap[col];
else colors[index] = maxColor;
} else {
colors[index] = Color.TRANSPARENT;
}
}
}
// Now turn these colors into a bitmap
Bitmap tile = Bitmap.createBitmap(dim, dim, Bitmap.Config.ARGB_8888);
// (int[] pixels, int offset, int stride, int x, int y, int width, int height)
tile.setPixels(colors, 0, dim, 0, 0, dim, dim);
return tile;
}
/**
* Calculate a reasonable maximum intensity value to map to maximum color intensity
*
* @param points Collection of LatLngs to put into buckets
* @param bounds Bucket boundaries
* @param radius radius of convolution
* @param screenDim larger dimension of screen in pixels (for scale)
* @return Approximate max value
*/
public static double getMaxValue(Collection<LatLngWrapper> points, Bounds bounds, int radius,
int screenDim) {
// Approximate scale as if entire heatmap is on the screen
// ie scale dimensions to larger of width or height (screenDim)
double minX = bounds.minX;
double maxX = bounds.maxX;
double minY = bounds.minY;
double maxY = bounds.maxY;
double boundsDim = (maxX - minX > maxY - minY) ? maxX - minX : maxY - minY;
// Number of buckets: have diameter sized buckets
int nBuckets = (int) (screenDim / (2 * radius) + 0.5);
// Scaling factor to convert width in terms of point distance, to which bucket
double scale = nBuckets / boundsDim;
// Make buckets
double[][] buckets = new double[nBuckets][nBuckets];
// Assign into buckets + find max value as we go along
double x, y;
double max = 0;
for (LatLngWrapper l : points) {
x = l.getPoint().x;
y = l.getPoint().y;
int xBucket = (int) ((x - minX) * scale);
int yBucket = (int) ((y - minY) * scale);
buckets[xBucket][yBucket] += l.getIntensity();
if (buckets[xBucket][yBucket] > max) max = buckets[xBucket][yBucket];
}
return max;
}
/**
* Generates the color map to use with a provided gradient.
*
* @param gradient Array of colors (int format)
* @param opacity Overall opacity of entire image: every individual alpha value will be
* multiplied by this opacity.
* @return the generated color map based on the gradient
*/
public static int[] generateColorMap(int[] gradient, double opacity) {
// Convert gradient into parallel arrays
int[] values = new int[gradient.length];
int[] colors = new int[gradient.length];
// Evenly space out gradient colors with a constant interval (interval = "space" between
// colors given in the gradient)
// With defaults, this is 1000/10 = 100
int interval = (COLOR_MAP_SIZE - 1) / (gradient.length - 1);
// Go through gradient and insert into values/colors
for (int i = 0; i < gradient.length; i++) {
values[i] = i * interval;
colors[i] = gradient[i];
}
int[] colorMap = new int[COLOR_MAP_SIZE];
// lowColorStop = closest color stop (value from gradient) below current position
int lowColorStop = 0;
for (int i = 0; i < COLOR_MAP_SIZE; i++) {
// if i is larger than next color stop value, increment to next color stop
// Check that it is safe to access lowColorStop + 1 first!
// TODO: This fixes previous problem of breaking upon no even divide, but isnt nice
if (lowColorStop + 1 < values.length) {
if (i > values[lowColorStop + 1]) lowColorStop++;
}
// In between two color stops: interpolate
if (lowColorStop < values.length - 1) {
// Check that it is safe to access lowColorStop + 1
if (i > values[lowColorStop + 1]) lowColorStop++;
float ratio = (i - interval * lowColorStop) / ((float) interval);
colorMap[i] = interpolateColor(colors[lowColorStop], colors[lowColorStop + 1],
ratio);
}
// above highest color stop: use that
else {
colorMap[i] = colors[colors.length - 1];
}
// Deal with changing the opacity if required
if (opacity != 1) {
int c = colorMap[i];
// TODO: make this better later?
colorMap[i] = Color.argb((int) (Color.alpha(c) * opacity),
Color.red(c), Color.green(c), Color.blue(c));
}
}
return colorMap;
}
/**
* Helper function for creation of color map - interpolates between given colors
* @param color1 First color
* @param color2 Second color
* @param ratio Between 0 to 1. Fraction of the distance between color1 and color2
* @return Color associated with x2
*/
private static int interpolateColor(int color1, int color2, float ratio) {
int alpha = (int) ((Color.alpha(color2) - Color.alpha(color1)) * ratio + Color.alpha(color1));
float[] hsv1 = new float[3];
Color.RGBToHSV(Color.red(color1), Color.green(color1), Color.blue(color1), hsv1);
float[] hsv2 = new float[3];
Color.RGBToHSV(Color.red(color2), Color.green(color2), Color.blue(color2), hsv2);
// adjust so that the shortest path on the color wheel will be taken
if (hsv1[0] - hsv2[0] > 180) {
hsv2[0] += 360;
} else if (hsv2[0] - hsv1[0] > 180) {
hsv1[0] += 360;
}
// Interpolate using calculated ratio
float[] result = new float[3];
for (int i = 0; i < 3; i++) {
result[i] = (hsv2[i] - hsv1[i]) * (ratio) + hsv1[i];
}
return Color.HSVToColor(alpha, result);
}
} |
package com.qiniu.android.http;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.qiniu.android.common.Constants;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Random;
import static java.lang.String.format;
/**
* HTTP
*/
public final class HttpManager {
private static final String userAgent = getUserAgent();
private AsyncHttpClient client;
private IReport reporter;
private String backUpIp;
public HttpManager(Proxy proxy) {
this(proxy, null);
}
public HttpManager(Proxy proxy, IReport reporter) {
this(proxy, reporter, null, 10, 60);
}
public HttpManager(Proxy proxy, IReport reporter, String backUpIp,
int connectTimeout, int responseTimeout) {
this.backUpIp = backUpIp;
client = new AsyncHttpClient();
client.setConnectTimeout(connectTimeout);
client.setResponseTimeout(responseTimeout);
client.setUserAgent(userAgent);
client.setEnableRedirects(false);
AsyncHttpClient.blockRetryExceptionClass(CancellationHandler.CancellationException.class);
if (proxy != null) {
client.setProxy(proxy.hostAddress, proxy.port, proxy.user, proxy.password);
}
this.reporter = reporter;
if (reporter == null) {
this.reporter = new IReport() {
@Override
public Header[] appendStatHeaders(Header[] headers) {
return headers;
}
@Override
public void updateErrorInfo(ResponseInfo info) {
}
@Override
public void updateSpeedInfo(ResponseInfo info) {
}
};
}
}
public HttpManager() {
this(null);
}
private static String genId() {
Random r = new Random();
return System.currentTimeMillis() + "" + r.nextInt(999);
}
private static String getUserAgent() {
return format("QiniuAndroid/%s (%s; %s; %s)", Constants.VERSION,
android.os.Build.VERSION.RELEASE, android.os.Build.MODEL, genId());
}
/**
* POST
*
* @param url URL
* @param data
* @param offset
* @param size
* @param headers
* @param progressHandler
* @param completionHandler
*/
public void postData(String url, byte[] data, int offset, int size, Header[] headers,
ProgressHandler progressHandler, final CompletionHandler completionHandler, CancellationHandler c) {
ByteArrayEntity entity = new ByteArrayEntity(data, offset, size, progressHandler, c);
postEntity(url, entity, headers, progressHandler, completionHandler);
}
public void postData(String url, byte[] data, Header[] headers, ProgressHandler progressHandler,
CompletionHandler completionHandler, CancellationHandler c) {
postData(url, data, 0, data.length, headers, progressHandler, completionHandler, c);
}
private void postEntity(final String url, final HttpEntity entity, Header[] headers,
ProgressHandler progressHandler, CompletionHandler completionHandler) {
final CompletionHandler wrapper = wrap(completionHandler);
final Header[] h = reporter.appendStatHeaders(headers);
final AsyncHttpResponseHandler originHandler = new ResponseHandler(url, wrapper, progressHandler);
if(backUpIp == null){
client.post(null, url, h, entity, null, originHandler);
return;
}
client.post(null, url, h, entity, null, new ResponseHandler(url, new CompletionHandler() {
@Override
public void complete(ResponseInfo info, JSONObject response) {
if (info.statusCode != ResponseInfo.UnknownHost){
wrapper.complete(info, response);
return;
}
Header[] h2 = new Header[h.length + 1];
System.arraycopy(h, 0, h2, 0, h.length);
URI uri = URI.create(url);
String newUrl = null;
try {
newUrl = new URI(uri.getScheme(), null, backUpIp, uri.getPort(), uri.getPath(), uri.getQuery(), null).toString();
} catch (URISyntaxException e) {
throw new AssertionError(e);
}
h2[h.length] = new BasicHeader("Host", uri.getHost());
client.post(null, newUrl, h2, entity, null, originHandler);
}
}, progressHandler));
}
/**
* POSTmultipart/form-data
*
* @param url URL
* @param args
* @param progressHandler
* @param completionHandler
*/
public void multipartPost(String url, PostArgs args, ProgressHandler progressHandler,
final CompletionHandler completionHandler, CancellationHandler c) {
MultipartBuilder mbuilder = new MultipartBuilder();
for (Map.Entry<String, String> entry : args.params.entrySet()) {
mbuilder.addPart(entry.getKey(), entry.getValue());
}
if (args.data != null) {
ByteArrayInputStream buff = new ByteArrayInputStream(args.data);
try {
mbuilder.addPart("file", args.fileName, buff, args.mimeType);
} catch (IOException e) {
completionHandler.complete(ResponseInfo.fileError(e), null);
return;
}
} else {
try {
mbuilder.addPart("file", args.file, args.mimeType, "filename");
} catch (IOException e) {
completionHandler.complete(ResponseInfo.fileError(e), null);
return;
}
}
ByteArrayEntity entity = mbuilder.build(progressHandler, c);
Header[] h = reporter.appendStatHeaders(new Header[0]);
postEntity(url, entity, h, progressHandler, completionHandler);
}
private CompletionHandler wrap(final CompletionHandler completionHandler) {
return new CompletionHandler() {
@Override
public void complete(ResponseInfo info, JSONObject response) {
completionHandler.complete(info, response);
if (info.isOK()) {
reporter.updateSpeedInfo(info);
} else {
reporter.updateErrorInfo(info);
}
}
};
}
/**
* fixed key escape for async http client
* Appends a quoted-string to a StringBuilder.
* <p/>
* <p>RFC 2388 is rather vague about how one should escape special characters
* in form-data parameters, and as it turns out Firefox and Chrome actually
* do rather different things, and both say in their comments that they're
* not really sure what the right approach is. We go with Chrome's behavior
* (which also experimentally seems to match what IE does), but if you
* actually want to have a good chance of things working, please avoid
* double-quotes, newlines, percent signs, and the like in your field names.
*/
private static String escapeMultipartString(String key) {
StringBuilder target = new StringBuilder();
for (int i = 0, len = key.length(); i < len; i++) {
char ch = key.charAt(i);
switch (ch) {
case '\n':
target.append("%0A");
break;
case '\r':
target.append("%0D");
break;
case '"':
target.append("%22");
break;
default:
target.append(ch);
break;
}
}
return target.toString();
}
} |
package com.WazaBe.HoloDemo;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupWindow;
import com.WazaBe.HoloDemo.fragments.AboutFragment;
import com.WazaBe.HoloDemo.fragments.CalendarFragment;
import com.WazaBe.HoloDemo.fragments.MainFragment;
import com.WazaBe.HoloDemo.fragments.PreferenceFragment;
import com.WazaBe.HoloEverywhere.ArrayAdapter;
import com.WazaBe.HoloEverywhere.LayoutInflater;
import com.WazaBe.HoloEverywhere.ThemeManager;
import com.WazaBe.HoloEverywhere.app.AlertDialog;
import com.WazaBe.HoloEverywhere.app.DatePickerDialog;
import com.WazaBe.HoloEverywhere.app.Fragment;
import com.WazaBe.HoloEverywhere.app.ProgressDialog;
import com.WazaBe.HoloEverywhere.app.TimePickerDialog;
import com.WazaBe.HoloEverywhere.sherlock.SActivity;
import com.WazaBe.HoloEverywhere.widget.ListPopupWindow;
import com.WazaBe.HoloEverywhere.widget.NumberPicker;
import com.WazaBe.HoloEverywhere.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
public class DemoActivity extends SActivity {
private final class FragmentListener implements TabListener {
private final Class<? extends Fragment> clazz;
private Fragment fragment;
public FragmentListener(Class<? extends Fragment> clazz) {
this.clazz = clazz;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (fragment == null) {
try {
fragment = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
ft.replace(android.R.id.content, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
private void addTab(Class<? extends Fragment> clazz, String title) {
Tab tab = getSupportActionBar().newTab();
tab.setText(title);
tab.setTabListener(new FragmentListener(clazz));
getSupportActionBar().addTab(tab);
}
public void closeCalendar(View v) {
replaceFragment(android.R.id.content, MainFragment.getInstance());
}
@Override
public void onCreate(Bundle savedInstanceState) {
setForceThemeApply(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
if (isABSSupport()) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setNavigationMode(
ActionBar.NAVIGATION_MODE_TABS);
addTab(MainFragment.class, "Holo Demo");
addTab(PreferenceFragment.class, "Settings");
addTab(AboutFragment.class, "About");
} else {
replaceFragment(android.R.id.content, MainFragment.getInstance());
}
}
public void replaceFragment(int resId, Fragment fragment) {
replaceFragment(resId, fragment, null);
}
public void replaceFragment(int resId, Fragment fragment,
String backStackName) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(resId, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
if (backStackName != null) {
ft.addToBackStack(backStackName);
}
ft.commit();
}
public void setDarkTheme(View v) {
ThemeManager.restartWithTheme(this, ThemeManager.DARK
| ThemeManager.FULLSCREEN);
}
public void setLightTheme(View v) {
ThemeManager.restartWithTheme(this, ThemeManager.LIGHT
| ThemeManager.FULLSCREEN);
}
public void showAbout(View v) {
replaceFragment(android.R.id.content, new AboutFragment(), "about");
}
public void showAlertDialog(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("AlertDialog");
builder.setIcon(R.drawable.icon);
builder.setMessage("Is fully-working port of AlertDialog from Android Jelly Bean\n"
+ "Yes, I know it's a long text. At the same time check that part.");
builder.setPositiveButton("Positive", null);
builder.setNegativeButton("Negative", null);
builder.setNeutralButton("Neutral", null);
builder.show();
}
public void showCalendar(View v) {
replaceFragment(android.R.id.content, CalendarFragment.getInstance(),
isABSSupport() ? null : "calendar");
}
public void showDatePicker(View v) {
new DatePickerDialog(this, null, 2012, 11, 21).show();
}
@SuppressLint("NewApi")
public void showListPopupWindow(View v) {
final ListPopupWindow w = new ListPopupWindow(this);
w.setAnchorView(v);
w.setAdapter(ArrayAdapter.createFromResource(this, R.array.countries,
R.layout.list_popup_window_row));
w.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
w.dismiss();
}
});
w.show();
}
public void showNumberPicker(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select number");
View view = LayoutInflater.inflate(this, R.layout.number_picker_demo);
NumberPicker picker = (NumberPicker) view
.findViewById(R.id.numberPicker);
picker.setMinValue(1);
picker.setMaxValue(15);
picker.setValue(3);
builder.setView(view);
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
}
public void showPopupWindow(View v) {
View content = LayoutInflater.inflate(this, R.layout.popup_window);
final PopupWindow w = new PopupWindow(content,
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
content.findViewById(R.id.imageButton).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
w.dismiss();
}
});
w.setFocusable(true);
w.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
}
public void showPreferences(View v) {
replaceFragment(android.R.id.content, new PreferenceFragment(), "prefs");
}
public void showProgressDialog(View v) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setIndeterminate(true);
dialog.setMessage("I can close!");
dialog.show();
}
public void showTimePicker(View v) {
new TimePickerDialog(this, null, 12, 34, false).show();
}
public void showToast(View v) {
Toast.makeText(this, "Toast example", Toast.LENGTH_LONG).show();
}
} |
package es.sandwatch.trim;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class containing all report information.
*
* @author Ismael Alonso
* @version 1.0.0
*/
public class Report{
private List<EndpointReport> endpointReports;
/**
* Constructor.
*/
Report(){
endpointReports = new ArrayList<>();
}
/**
* Creates an instance of EndpointReport and adds it to the list.
*
* @param model the model associated to the report.
* @param requestResult the result of the request to the above model.
* @return the report object.
*/
@NotNull
EndpointReport addEndpointReport(@NotNull Class<?> model, @NotNull Fetcher.RequestResult requestResult){
EndpointReport report = new EndpointReport(model, requestResult);
endpointReports.add(report);
return report;
}
@Override
public String toString(){
StringBuilder report = new StringBuilder();
if (endpointReports.isEmpty()){
report.append("Nothing to report.");
}
else{
report.append("Trim report, ").append(endpointReports.size()).append(" endpoints:");
for (EndpointReport endpointReport:endpointReports){
report.append("\n\n").append(endpointReport);
}
}
return report.toString();
}
/**
* Report for a single model.
*
* @author Ismael Alonso
* @version 1.0.0
*/
class EndpointReport{
private Class<?> model;
private Fetcher.RequestResult requestResult;
private boolean responseFormatError;
private Map<String, Boolean> attributeReports;
/**
* Constructor.
*
* @param model the model associated to the report.
* @param requestResult the result of the request to the above model.
*/
private EndpointReport(@NotNull Class<?> model, @NotNull Fetcher.RequestResult requestResult){
this.model = model;
this.requestResult = requestResult;
this.responseFormatError = false;
this.attributeReports = new HashMap<>();
}
/**
* Lets the report know that the format of the response couldn't be understood.
*/
void setResponseFormatError(){
responseFormatError = true;
}
/**
* Adds information about attribute usage to the report.
*
* @param attribute the relevant attribute.
* @param used whether the model uses it.
*/
void addAttributeReport(@NotNull String attribute, boolean used){
attributeReports.put(attribute, used);
}
@Override
public String toString(){
StringBuilder report = new StringBuilder().append(model.toString());
if (requestResult.requestFailed()){
report.append("\n The request could not be performed.");
}
else{
report.append("\n Request time: ").append(requestResult.getRequestTime()).append("s");
report.append("\n Request status code: ").append(requestResult.getStatusCode());
if (requestResult.is4xx()){
report.append("\n Server response: ").append(requestResult.getResponse());
}
else if (responseFormatError){
report.append("\n The format of the response was unknown.");
}
else{
for (Map.Entry<String, Boolean> entry:attributeReports.entrySet()){
report.append("\n ").append(entry.getKey()).append(": ")
.append(entry.getValue() ? "used" : "not used");
}
}
}
return report.toString();
}
}
/**
* Report for a single attribute.
*
* @author Ismael Alonso
* @version 1.0.0
*/
class AttributeReport{
private String name;
private boolean used;
private JsonType apiType;
private JsonType modelType;
/**
* Constructor.
*
* @param name the name of the attribute.
*/
AttributeReport(String name){
this.name = name;
}
/**
* Sets attribute usage information.
*
* @param used true if it is used, false otherwise.
* @return this object.
*/
AttributeReport setUsed(boolean used){
this.used = used;
return this;
}
/**
* Sets type information.
*
* @param apiType the type found in the API endpoint result.
* @param modelType the type found in the model.
* @return this object
*/
AttributeReport setTypes(JsonType apiType, JsonType modelType){
this.apiType = apiType;
this.modelType = modelType;
return this;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder().append(name).append(": ").append(used ? "used" : "unused");
if (used){
result.append(", ");
if (apiType == modelType){
result.append("types match");
}
else{
result.append("types mismatch (")
.append(apiType).append(" in endpoint, ")
.append(modelType).append(" in model)");
}
}
return result.toString();
}
}
} |
package gov.nih.nci.ncicb.cadsr.loader;
import java.util.Iterator;
import org.omg.uml.foundation.core.*;
import org.omg.uml.foundation.extensionmechanisms.*;
import uml.MdrModelManager;
import uml.MdrModelManagerFactory;
import uml.MdrModelManagerFactoryImpl;
import org.omg.uml.modelmanagement.Model;
import org.omg.uml.modelmanagement.UmlPackage;
import java.io.*;
import gov.nih.nci.ncicb.cadsr.loader.event.*;
import gov.nih.nci.ncicb.cadsr.loader.parser.*;
import gov.nih.nci.ncicb.cadsr.loader.persister.*;
import gov.nih.nci.ncicb.cadsr.loader.validator.*;
import java.security.*;
import javax.security.auth.*;
import javax.security.auth.login.*;
import javax.security.auth.callback.CallbackHandler;
import org.apache.log4j.Logger;
import gov.nih.nci.ncicb.cadsr.loader.jaas.ConsoleCallbackHandler;
public class UMLLoader {
private static Logger logger = Logger.getLogger(UMLLoader.class.getName());
public static void main(String[] args) throws Exception {
new UMLLoader().run(args);
}
private void run(String[] args) throws Exception {
InitClass initClass = new InitClass(this);
Thread t = new Thread(initClass);
t.start();
String[] filenames = new File(args[0]).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xmi");
}
});
LoginContext lc = new LoginContext("UML_Loader", new ConsoleCallbackHandler());
String username = null;
try {
lc.login();
boolean loginSuccess = true;
Subject subject = lc.getSubject();
Iterator it = subject.getPrincipals().iterator();
while (it.hasNext()) {
username = it.next().toString();
logger.debug("Authenticated username: " + username);
}
} catch (Exception ex) {
logger.error("Failed to login: " + ex.getMessage());
System.exit(1);
}
String projectName = args[1];
logger.info(filenames.length + " files to process");
ElementsLists elements = new ElementsLists();
Validator validator = new UMLValidator(elements);
UMLListener listener = new XMIUMLListener(elements);
for(int i=0; i<filenames.length; i++) {
logger.info("Starting file: " + filenames[i]);
UMLDefaults defaults = UMLDefaults.getInstance();
defaults.initParams(projectName, username);
defaults.initClassifications();
XMIParser parser = new XMIParser();
parser.setListener(listener);
parser.parse(args[0] + "/" + filenames[i]);
synchronized(initClass) {
if(!initClass.isDone())
try {
wait();
} catch (Exception e){
} // end of try-catch
}
}
validator.validate();
// Persister persister = new UMLPersister(elements);
// persister.setParameter("projectName", projectName);
// persister.setParameter("username", username);
// persister.persist();
}
class InitClass implements Runnable {
Object parent;
boolean done = false;
InitClass(Object parent) {
this.parent = parent;
}
public void run() {
UMLPersister p = new UMLPersister(null);
synchronized (this) {
done = true;
notifyAll();
}
}
public boolean isDone() {
return done;
}
}
} |
/*
* $Id$
* $URL$
*/
package org.subethamail.common.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataSource;
import org.subethamail.common.MailUtils;
/**
* I can't believe this class didn't already exist. JAF is an overarchitected,
* underthought, irritating pile of rubbish.
*
* @author Jeff Schnitzer
* @author Scott Hernandez
*/
public class TrivialDataSource implements DataSource
{
InputStream input;
String contentType;
public TrivialDataSource(InputStream input, String contentType)
{
this.input = input;
this.contentType = contentType;
}
/* (non-Javadoc)
* @see javax.activation.DataSource#getContentType()
*/
public String getContentType()
{
return this.contentType;
}
/* (non-Javadoc)
* @see javax.activation.DataSource#getInputStream()
*/
public InputStream getInputStream() throws IOException
{
this.input.reset();
return this.input;
}
/* (non-Javadoc)
* @see javax.activation.DataSource#getName()
*/
public String getName()
{
return MailUtils.getNameFromContentType(getContentType());
}
/* (non-Javadoc)
* @see javax.activation.DataSource#getOutputStream()
*/
public OutputStream getOutputStream() throws IOException
{
throw new UnsupportedOperationException();
}
} |
package com.graphhopper.routing.util;
import com.graphhopper.coll.GHBitSetImpl;
import com.graphhopper.storage.GraphHopperStorage;
import com.graphhopper.util.EdgeIterator;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.stack.array.TIntArrayStack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class TarjansStronglyConnectedComponentsAlgorithm
{
private final GraphHopperStorage graph;
private final TIntArrayStack nodeStack;
private final GHBitSetImpl onStack;
private final int[] nodeIndex;
private final int[] nodeLowLink;
private final ArrayList<TIntArrayList> components = new ArrayList<TIntArrayList>();
private int index = 1;
private final EdgeFilter edgeFilter;
public TarjansStronglyConnectedComponentsAlgorithm( GraphHopperStorage graph, final EdgeFilter edgeFilter )
{
this.graph = graph;
this.nodeStack = new TIntArrayStack();
this.onStack = new GHBitSetImpl(graph.getNodes());
this.nodeIndex = new int[graph.getNodes()];
this.nodeLowLink = new int[graph.getNodes()];
this.edgeFilter = edgeFilter;
}
/**
* Find and return list of all strongly connected components in g.
*/
public List<TIntArrayList> findComponents()
{
int nodes = graph.getNodes();
for (int start = 0; start < nodes; start++)
{
if (nodeIndex[start] == 0 && !graph.isNodeRemoved(start))
{
strongConnect(start);
}
}
return components;
}
// Find all components reachable from firstNode, add them to 'components'
private void strongConnect( int firstNode )
{
final Stack<TarjanState> stateStack = new Stack<TarjanState>();
stateStack.push(TarjanState.startState(firstNode));
// nextState label is equivalent to the function entry point in the recursive Tarjan's algorithm.
nextState:
while (!stateStack.empty())
{
TarjanState state = stateStack.pop();
final int start = state.start;
final EdgeIterator iter;
if (state.isStart())
{
// We're traversing a new node 'start'. Set the depth index for this node to the smallest unused index.
nodeIndex[start] = index;
nodeLowLink[start] = index;
index++;
nodeStack.push(start);
onStack.set(start);
iter = graph.createEdgeExplorer(edgeFilter).setBaseNode(start);
} else
{ // if (state.isResume()) {
// We're resuming iteration over the next child of 'start', set lowLink as appropriate.
iter = state.iter;
int prevConnectedId = iter.getAdjNode();
nodeLowLink[start] = Math.min(nodeLowLink[start], nodeLowLink[prevConnectedId]);
}
// Each element (excluding the first) in the current component should be able to find
// a successor with a lower nodeLowLink.
while (iter.next())
{
int connectedId = iter.getAdjNode();
if (nodeIndex[connectedId] == 0)
{
// Push resume and start states onto state stack to continue our DFS through the graph after the jump.
// Ideally we'd just call strongConnectIterative(connectedId);
stateStack.push(TarjanState.resumeState(start, iter));
stateStack.push(TarjanState.startState(connectedId));
continue nextState;
} else if (onStack.contains(connectedId))
{
nodeLowLink[start] = Math.min(nodeLowLink[start], nodeIndex[connectedId]);
}
}
// If nodeLowLink == nodeIndex, then we are the first element in a component.
// Add all nodes higher up on nodeStack to this component.
if (nodeIndex[start] == nodeLowLink[start])
{
TIntArrayList component = new TIntArrayList();
int node;
while ((node = nodeStack.pop()) != start)
{
component.add(node);
onStack.clear(node);
}
component.add(start);
component.trimToSize();
onStack.clear(start);
components.add(component);
}
}
}
// Internal stack state of algorithm, used to avoid recursive function calls and hitting stack overflow exceptions.
// State is either 'start' for new nodes or 'resume' for partially traversed nodes.
private static class TarjanState
{
final int start;
final EdgeIterator iter;
// Iterator only present in 'resume' state.
boolean isStart()
{
return iter == null;
}
private TarjanState( final int start, final EdgeIterator iter )
{
this.start = start;
this.iter = iter;
}
public static TarjanState startState( int start )
{
return new TarjanState(start, null);
}
public static TarjanState resumeState( int start, EdgeIterator iter )
{
return new TarjanState(start, iter);
}
}
} |
package org.postgresql;
import java.io.*;
import java.lang.*;
import java.net.*;
import java.util.*;
import java.sql.*;
import org.postgresql.*;
import org.postgresql.core.*;
import org.postgresql.util.*;
/**
* @version 1.0 15-APR-1997
*
* This class is used by Connection & PGlobj for communicating with the
* backend.
*
* @see java.sql.Connection
*/
// This class handles all the Streamed I/O for a org.postgresql connection
public class PG_Stream
{
private Socket connection;
private InputStream pg_input;
private BufferedOutputStream pg_output;
BytePoolDim1 bytePoolDim1 = new BytePoolDim1();
BytePoolDim2 bytePoolDim2 = new BytePoolDim2();
/**
* Constructor: Connect to the PostgreSQL back end and return
* a stream connection.
*
* @param host the hostname to connect to
* @param port the port number that the postmaster is sitting on
* @exception IOException if an IOException occurs below it.
*/
public PG_Stream(String host, int port) throws IOException
{
connection = new Socket(host, port);
// Submitted by Jason Venner <jason@idiom.com> adds a 10x speed
// improvement on FreeBSD machines (caused by a bug in their TCP Stack)
connection.setTcpNoDelay(true);
// Buffer sizes submitted by Sverre H Huseby <sverrehu@online.no>
pg_input = new BufferedInputStream(connection.getInputStream(), 8192);
pg_output = new BufferedOutputStream(connection.getOutputStream(), 8192);
}
/**
* Sends a single character to the back end
*
* @param val the character to be sent
* @exception IOException if an I/O error occurs
*/
public void SendChar(int val) throws IOException
{
pg_output.write((byte)val);
}
/**
* Sends an integer to the back end
*
* @param val the integer to be sent
* @param siz the length of the integer in bytes (size of structure)
* @exception IOException if an I/O error occurs
*/
public void SendInteger(int val, int siz) throws IOException
{
byte[] buf = bytePoolDim1.allocByte(siz);
while (siz
{
buf[siz] = (byte)(val & 0xff);
val >>= 8;
}
Send(buf);
}
/**
* Send an array of bytes to the backend
*
* @param buf The array of bytes to be sent
* @exception IOException if an I/O error occurs
*/
public void Send(byte buf[]) throws IOException
{
pg_output.write(buf);
}
/**
* Send an exact array of bytes to the backend - if the length
* has not been reached, send nulls until it has.
*
* @param buf the array of bytes to be sent
* @param siz the number of bytes to be sent
* @exception IOException if an I/O error occurs
*/
public void Send(byte buf[], int siz) throws IOException
{
Send(buf,0,siz);
}
/**
* Send an exact array of bytes to the backend - if the length
* has not been reached, send nulls until it has.
*
* @param buf the array of bytes to be sent
* @param off offset in the array to start sending from
* @param siz the number of bytes to be sent
* @exception IOException if an I/O error occurs
*/
public void Send(byte buf[], int off, int siz) throws IOException
{
int i;
pg_output.write(buf, off, ((buf.length-off) < siz ? (buf.length-off) : siz));
if((buf.length-off) < siz)
{
for (i = buf.length-off ; i < siz ; ++i)
{
pg_output.write(0);
}
}
}
/**
* Receives a single character from the backend
*
* @return the character received
* @exception SQLException if an I/O Error returns
*/
public int ReceiveChar() throws SQLException
{
int c = 0;
try
{
c = pg_input.read();
if (c < 0) throw new PSQLException("postgresql.stream.eof");
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
return c;
}
/**
* Receives an integer from the backend
*
* @param siz length of the integer in bytes
* @return the integer received from the backend
* @exception SQLException if an I/O error occurs
*/
public int ReceiveInteger(int siz) throws SQLException
{
int n = 0;
try
{
for (int i = 0 ; i < siz ; i++)
{
int b = pg_input.read();
if (b < 0)
throw new PSQLException("postgresql.stream.eof");
n = n | (b << (8 * i)) ;
}
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
return n;
}
/**
* Receives an integer from the backend
*
* @param siz length of the integer in bytes
* @return the integer received from the backend
* @exception SQLException if an I/O error occurs
*/
public int ReceiveIntegerR(int siz) throws SQLException
{
int n = 0;
try
{
for (int i = 0 ; i < siz ; i++)
{
int b = pg_input.read();
if (b < 0)
throw new PSQLException("postgresql.stream.eof");
n = b | (n << 8);
}
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
return n;
}
/**
* Receives a null-terminated string from the backend. Maximum of
* maxsiz bytes - if we don't see a null, then we assume something
* has gone wrong.
*
* @param maxsiz maximum length of string
* @return string from back end
* @exception SQLException if an I/O error occurs
*/
public String ReceiveString(int maxsiz) throws SQLException
{
byte[] rst = bytePoolDim1.allocByte(maxsiz);
return ReceiveString(rst, maxsiz, null);
}
/**
* Receives a null-terminated string from the backend. Maximum of
* maxsiz bytes - if we don't see a null, then we assume something
* has gone wrong.
*
* @param maxsiz maximum length of string
* @param encoding the charset encoding to use.
* @param maxsiz maximum length of string in bytes
* @return string from back end
* @exception SQLException if an I/O error occurs
*/
public String ReceiveString(int maxsiz, String encoding) throws SQLException
{
byte[] rst = bytePoolDim1.allocByte(maxsiz);
return ReceiveString(rst, maxsiz, encoding);
}
/**
* Receives a null-terminated string from the backend. Maximum of
* maxsiz bytes - if we don't see a null, then we assume something
* has gone wrong.
*
* @param rst byte array to read the String into. rst.length must
* equal to or greater than maxsize.
* @param maxsiz maximum length of string in bytes
* @param encoding the charset encoding to use.
* @return string from back end
* @exception SQLException if an I/O error occurs
*/
public String ReceiveString(byte rst[], int maxsiz, String encoding)
throws SQLException
{
int s = 0;
try
{
while (s < maxsiz)
{
int c = pg_input.read();
if (c < 0)
throw new PSQLException("postgresql.stream.eof");
else if (c == 0) {
rst[s] = 0;
break;
} else
rst[s++] = (byte)c;
}
if (s >= maxsiz)
throw new PSQLException("postgresql.stream.toomuch");
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
String v = null;
if (encoding == null)
v = new String(rst, 0, s);
else {
try {
v = new String(rst, 0, s, encoding);
} catch (UnsupportedEncodingException unse) {
throw new PSQLException("postgresql.stream.encoding", unse);
}
}
return v;
}
/**
* Read a tuple from the back end. A tuple is a two dimensional
* array of bytes
*
* @param nf the number of fields expected
* @param bin true if the tuple is a binary tuple
* @return null if the current response has no more tuples, otherwise
* an array of strings
* @exception SQLException if a data I/O error occurs
*/
public byte[][] ReceiveTuple(int nf, boolean bin) throws SQLException
{
int i, bim = (nf + 7)/8;
byte[] bitmask = Receive(bim);
byte[][] answer = bytePoolDim2.allocByte(nf);
int whichbit = 0x80;
int whichbyte = 0;
for (i = 0 ; i < nf ; ++i)
{
boolean isNull = ((bitmask[whichbyte] & whichbit) == 0);
whichbit >>= 1;
if (whichbit == 0)
{
++whichbyte;
whichbit = 0x80;
}
if (isNull)
answer[i] = null;
else
{
int len = ReceiveIntegerR(4);
if (!bin)
len -= 4;
if (len < 0)
len = 0;
answer[i] = Receive(len);
}
}
return answer;
}
/**
* Reads in a given number of bytes from the backend
*
* @param siz number of bytes to read
* @return array of bytes received
* @exception SQLException if a data I/O error occurs
*/
private byte[] Receive(int siz) throws SQLException
{
byte[] answer = bytePoolDim1.allocByte(siz);
Receive(answer,0,siz);
return answer;
}
/**
* Reads in a given number of bytes from the backend
*
* @param buf buffer to store result
* @param off offset in buffer
* @param siz number of bytes to read
* @exception SQLException if a data I/O error occurs
*/
public void Receive(byte[] b,int off,int siz) throws SQLException
{
int s = 0;
try
{
while (s < siz)
{
int w = pg_input.read(b, off+s, siz - s);
if (w < 0)
throw new PSQLException("postgresql.stream.eof");
s += w;
}
} catch (IOException e) {
throw new PSQLException("postgresql.stream.ioerror",e);
}
}
/**
* This flushes any pending output to the backend. It is used primarily
* by the Fastpath code.
* @exception SQLException if an I/O error occurs
*/
public void flush() throws SQLException
{
try {
pg_output.flush();
} catch (IOException e) {
throw new PSQLException("postgresql.stream.flush",e);
}
}
/**
* Closes the connection
*
* @exception IOException if a IO Error occurs
*/
public void close() throws IOException
{
pg_output.write("X".getBytes());
pg_output.flush();
pg_output.close();
pg_input.close();
connection.close();
}
} |
package io.cloudchaser.murmur.types;
import static io.cloudchaser.murmur.types.MurmurType.STRING;
/**
*
* @author Mihail K
* @since 0.1
**/
public class MurmurString extends MurmurObject {
/**
* Singleton empty Murmur string.
**/
public static final MurmurString EMPTY = MurmurString.create("");
/**
* The internal Java string value.
**/
private final String value;
private MurmurString(String value) {
super(STRING);
this.value = value;
}
public static MurmurString create(String value) {
if(value.isEmpty()) return EMPTY;
return new MurmurString(value);
}
public String getValue() {
return value;
}
@Override
public Object toJavaObject() {
return value;
}
@Override
public boolean isCompatible(Class<?> type) {
return type.isAssignableFrom(String.class) ||
type.isAssignableFrom(CharSequence.class);
}
@Override
public Object getAsJavaType(Class<?> type) {
// Java string type.
if(type.isAssignableFrom(String.class) ||
type.isAssignableFrom(CharSequence.class)) {
return value;
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurString asString() {
return this;
}
@Override
public MurmurObject opEquals(MurmurObject other) {
// Check for supported operation.
if(other.getType() == STRING) {
return MurmurBoolean.create(
value.equals(((MurmurString)other).value));
}
// Not equal.
return MurmurBoolean.FALSE;
}
@Override
public MurmurObject opNotEquals(MurmurObject other) {
// Check for supported operation.
if(other.getType() == STRING) {
return MurmurBoolean.create(!
value.equals(((MurmurString)other).value));
}
// Not equal.
return MurmurBoolean.TRUE;
}
@Override
public MurmurObject opIndex(MurmurObject other) {
// Check for a numeric type.
if(other.getType().numeric) {
// Get and validate the index.
int index = (int)other.asInteger().getValue();
if(index >= value.length() ||
index < -value.length()) {
throw new IndexOutOfBoundsException();
}
// Compute negative index.
if(index < 0) {
index = value.length() + index;
}
// Fetch and return the character.
char ch = value.charAt(index);
return new MurmurCharacter(ch);
}
// Unsupported index type.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opConcat(MurmurObject other) {
// Convert to string and do concat.
MurmurString string = other.asString();
return MurmurString.create(value + string.value);
}
@Override
public String toString() {
return "MurmurString{value=" + value + '}';
}
} |
package org.hisp.dhis.startup;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.jdbc.StatementBuilder;
import org.hisp.dhis.system.startup.AbstractStartupRoutine;
import org.hisp.quick.StatementManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Lars Helge Overland
*/
public class InitTableAlteror
extends AbstractStartupRoutine
{
private static final Log log = LogFactory.getLog( InitTableAlteror.class );
@Autowired
private StatementManager statementManager;
@Autowired
private StatementBuilder statementBuilder;
// Execute
@Override
@Transactional
public void execute()
{
executeSql( "update dataelement set domaintype='AGGREGATE' where domaintype='aggregate' or domaintype is null;" );
executeSql( "update dataelement set domaintype='TRACKER' where domaintype='patient';" );
executeSql( "update users set invitation = false where invitation is null" );
executeSql( "update users set selfregistered = false where selfregistered is null" );
executeSql( "update users set externalauth = false where externalauth is null" );
executeSql( "update users set disabled = false where disabled is null" );
executeSql( "alter table dataelement alter column domaintype set not null;" );
executeSql( "alter table programstageinstance alter column status type varchar(25);" );
executeSql( "UPDATE programstageinstance SET status='ACTIVE' WHERE status='0';" );
executeSql( "UPDATE programstageinstance SET status='COMPLETED' WHERE status='1';" );
executeSql( "UPDATE programstageinstance SET status='SKIPPED' WHERE status='5';" );
executeSql( "ALTER TABLE program DROP COLUMN displayonallorgunit" );
upgradeProgramStageDataElements();
updateValueTypes();
updateAggregationTypes();
updateFeatureTypes();
updateValidationRuleEnums();
updateProgramStatus();
removeDeprecatedConfigurationColumns();
updateTimestamps();
updateCompletedBy();
updateRelativePeriods();
executeSql( "ALTER TABLE program ALTER COLUMN \"type\" TYPE varchar(255);" );
executeSql( "update program set \"type\"='WITH_REGISTRATION' where type='1' or type='2'" );
executeSql( "update program set \"type\"='WITHOUT_REGISTRATION' where type='3'" );
// Update userkeyjsonvalue and keyjsonvalue to set new encrypted column to false.
executeSql( "UPDATE keyjsonvalue SET encrypted = false WHERE encrypted IS NULL" );
executeSql( "UPDATE userkeyjsonvalue SET encrypted = false WHERE encrypted IS NULL" );
// Set messages "ticket" properties to non-null values
executeSql( "UPDATE message SET internal = FALSE WHERE internal IS NULL" );
executeSql( "UPDATE messageconversation SET priority = 'NONE' WHERE priority IS NULL" );
executeSql( "UPDATE messageconversation SET status = 'NONE' WHERE status IS NULL" );
updateMessageConversationMessageCount();
// Set OrganisationUnitGroupSet includeSubhierarchyInAnalytics to false where IS NULL
executeSql( "UPDATE orgunitgroupset SET includesubhierarchyinanalytics = FALSE WHERE includesubhierarchyinanalytics IS NULL" );
// Update programstageinstance set deleted = false where deleted = null
executeSql( "UPDATE programstageinstance SET deleted = false WHERE deleted IS NULL" );
executeSql( "alter table programstageinstance alter column deleted set not null" );
executeSql( "create index in_programstageinstance_deleted on programstageinstace(deleted)" );
// Update trackedentityinstance set deleted = false where deleted = null
executeSql( "UPDATE trackedentityinstance SET deleted = false WHERE deleted IS NULL" );
executeSql( "alter table trackedentityinstance alter column deleted set not null" );
executeSql( "create index in_trackedentityinstance_deleted on trackedentityinstance(deleted)" );
// Update programinstance set deleted = false where deleted = null
executeSql( "UPDATE programinstance SET deleted = false WHERE deleted IS NULL" );
executeSql( "alter table programinstance alter column deleted set not null" );
executeSql( "create index in_programinstance_deleted on programinstance(deleted)" );
// Remove DataSet start and end date - replaced by DataInputPeriods
executeSql( "ALTER TABLE dataset drop column startdate" );
executeSql( "ALTER TABLE dataset drop column enddate" );
updateLegendSetAssociationAndDeleteOldAssociation();
// Message Conversation Message Type
updateMessageConversationMessageTypes();
executeSql( "UPDATE expression SET slidingWindow = FALSE WHERE slidingWindow IS NULL" );
executeSql( "UPDATE validationResult set notificationsent = false WHERE notificationsent is null" );
executeSql( "UPDATE trackedentityinstance SET featuretype = 'NONE' WHERE featuretype IS NULL " );
updateTrackedEntityAttributePatternAndTextPattern();
// 2FA fixes for 2.30
executeSql( "UPDATE users set twofa = false where twofa is null" );
executeSql( "ALTER TABLE users alter column twofa set not null" );
// Update trackedentityattribute set skipsynchronization = false where skipsynchronization = null
executeSql( "UPDATE trackedentityattribute SET skipsynchronization = false WHERE skipsynchronization IS NULL" );
executeSql( "ALTER TABLE trackedentityattribute ALTER COLUMN skipsynchronization SET NOT NULL" );
// alter/update lastsynchronized column in trackedentityinstance to: NOT NULL, DEFAULT to_timestamp(0)
executeSql( "UPDATE trackedentityinstance SET lastsynchronized = to_timestamp(0) WHERE lastsynchronized IS NULL;" ); //Do not remove this line if some cleanup will ever happen
executeSql( "ALTER TABLE trackedentityinstance ALTER COLUMN lastsynchronized SET NOT NULL" );
executeSql( "ALTER TABLE trackedentityinstance ALTER COLUMN lastsynchronized SET DEFAULT to_timestamp(0)" );
// alter/update lastsynchronized column in programstageinstance to: NOT NULL, DEFAULT to_timestamp(0)
executeSql( "UPDATE programstageinstance SET lastsynchronized = to_timestamp(0) WHERE lastsynchronized IS NULL" ); //Do not remove this line if some cleanup will ever happen
executeSql( "ALTER TABLE programstageinstance ALTER COLUMN lastsynchronized SET NOT NULL" );
executeSql( "ALTER TABLE programstageinstance ALTER COLUMN lastsynchronized SET DEFAULT to_timestamp(0)" );
// Update trackedentityattribute set skipsynchronization = false where skipsynchronization = null
executeSql( "UPDATE programstagedataelement SET skipsynchronization = false WHERE skipsynchronization IS NULL" );
executeSql( "ALTER TABLE programstagedataelement ALTER COLUMN skipsynchronization SET NOT NULL" );
executeSql( "UPDATE programstage SET featuretype = 'POINT' WHERE capturecoordinates = true AND featuretype IS NULL" );
executeSql( "UPDATE programstage SET featuretype = 'NONE' WHERE capturecoordinates = false AND featuretype IS NULL" );
updateAndRemoveOldProgramStageInstanceCoordinates();
//Remove createddate column from trackedentitycomment table
executeSql( "UPDATE trackedentitycomment SET created = createddate WHERE created IS NOT NULL;" );
executeSql( "ALTER TABLE trackedentitycomment DROP COLUMN createddate;" );
addGenerateUidFunction();
}
private void addGenerateUidFunction()
{
executeSql(
"create or replace function generate_uid()\n" +
" returns text as\n" +
"$$\n" +
"declare\n" +
" chars text [] := '{0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z}';\n" +
" result text := chars [11 + random() * (array_length(chars, 1) - 11)];\n" +
"begin\n" +
" for i in 1..10 loop\n" +
" result := result || chars [1 + random() * (array_length(chars, 1) - 1)];\n" +
" end loop;\n" +
" return result;\n" +
"end;\n" +
"$$\n" +
"language plpgsql;"
);
}
private void updateAndRemoveOldProgramStageInstanceCoordinates()
{
executeSql( "UPDATE programstageinstance " +
"SET geometry = ST_GeomFromText('POINT(' || longitude || ' ' || latitude || ')', 4326) " +
"WHERE longitude IS NOT NULL " +
"AND latitude IS NOT NULL" +
"AND geometry IS NULL" );
executeSql( "ALTER TABLE programstageinstance DROP COLUMN latitude " );
executeSql( "ALTER TABLE programstageinstance DROP COLUMN longitude " );
}
private void updateTrackedEntityAttributePatternAndTextPattern()
{
// Create textpattern jsonb
executeSql( "UPDATE trackedentityattribute SET textpattern = concat('{\"ownerUid\": \"', uid, '\",\"segments\": [{\"parameter\": \"', pattern, '\",\"method\": \"RANDOM\"}],\"ownerObject\": \"TRACKEDENTITYATTRIBUTE\"}')::jsonb WHERE pattern SIMILAR TO '#+' AND generated = true AND textpattern IS NULL" );
// Update pattern to match new syntax
executeSql( "UPDATE trackedentityattribute SET pattern = concat('RANDOM(', pattern, ')') WHERE pattern SIMILAR TO '#+' AND generated = true AND textpattern IS NOT NULL" );
// Move all reserved values into the new table
executeSql( "INSERT INTO reservedvalue(owneruid, key, value, expires, ownerobject, reservedvalueid) " +
"SELECT TEA.uid, TEA.pattern, TEARV.value, TEARV.expirydate, 'TRACKEDENTITYATTRIBUTE', nextval('hibernate_sequence') " +
"FROM trackedentityattributereservedvalue TEARV, trackedentityattribute TEA " +
"WHERE TEARV.trackedentityattributeid = TEA.trackedentityattributeid " +
"AND TEARV.expirydate > NOW() " +
"AND TEARV.trackedentityinstanceid IS NULL" );
// Drop the old table
executeSql( "DROP TABLE trackedentityattributereservedvalue" );
}
private void updateMessageConversationMessageTypes()
{
// Tickets has status != NONE
executeSql( "UPDATE messageconversation SET messagetype = 'TICKET' WHERE messagetype IS NULL AND status != 'NONE'" );
// Validation results existing ValidationResults always start with "Alerts as of%"
executeSql( "UPDATE messageconversation SET messagetype = 'VALIDATION_RESULT' WHERE messagetype IS NULL AND ( subject LIKE 'Alerts as of%' OR subject LIKE 'DHIS alerts as of%' )" );
// System Always have no user "owner"
executeSql( "UPDATE messageconversation SET messagetype = 'SYSTEM' WHERE messagetype IS NULL AND userid IS NULL" );
// Direct messages is what is left
executeSql( "UPDATE messageconversation SET messagetype = 'PRIVATE' WHERE messagetype IS NULL" );
executeSql( "ALTER TABLE messageconversation ALTER COLUMN messagetype set not null" );
}
private void updateLegendSetAssociationAndDeleteOldAssociation()
{
// Transfer all existing references from dataelement to legendset to new many-to-many table
// Then delete old reference
executeSql( "INSERT INTO dataelementlegendsets (dataelementid, sort_order, legendsetid) SELECT dataelementid, 0, legendsetid FROM dataelement WHERE legendsetid IS NOT NULL" );
executeSql( "ALTER TABLE dataelement DROP COLUMN legendsetid " );
// Transfer all existing references from dataset to legendset to new many-to-many table
// Then delete old reference
executeSql( "INSERT INTO datasetlegendsets (datasetid, sort_order, legendsetid) SELECT datasetid, 0, legendsetid FROM dataset WHERE legendsetid IS NOT NULL" );
executeSql( "ALTER TABLE dataset DROP COLUMN legendsetid " );
// Transfer all existing references from dataset to legendset to new many-to-many table
// Then delete old reference
executeSql( "INSERT INTO indicatorlegendsets (indicatorid, sort_order, legendsetid) SELECT indicatorid, 0, legendsetid FROM indicator WHERE legendsetid IS NOT NULL" );
executeSql( "ALTER TABLE indicator DROP COLUMN legendsetid " );
// Transfer all existing references from dataset to legendset to new many-to-many table
// Then delete old reference
executeSql( "INSERT INTO programindicatorlegendsets (programindicatorid, sort_order, legendsetid) SELECT programindicatorid, 0, legendsetid FROM programindicator WHERE legendsetid IS NOT NULL" );
executeSql( "ALTER TABLE programindicator DROP COLUMN legendsetid " );
// Transfer all existing references from dataset to legendset to new many-to-many table
// Then delete old reference
executeSql( "INSERT INTO programindicatorlegendsets (programindicatorid, sort_order, legendsetid) SELECT programindicatorid, 0, legendsetid FROM programindicator WHERE legendsetid IS NOT NULL" );
executeSql( "ALTER TABLE programindicator DROP COLUMN legendsetid " );
// Transfer all existing references from dataset to legendset to new many-to-many table
// Then delete old reference
executeSql( "INSERT INTO trackedentityattributelegendsets (trackedentityattributeid, sort_order, legendsetid) SELECT trackedentityattributeid, 0, legendsetid FROM trackedentityattribute WHERE legendsetid IS NOT NULL" );
executeSql( "ALTER TABLE trackedentityattribute DROP COLUMN legendsetid " );
}
private void updateMessageConversationMessageCount()
{
Integer nullCounts = statementManager.getHolder().queryForInteger( "SELECT count(*) from messageconversation WHERE messagecount IS NULL" );
if ( nullCounts > 0 )
{
executeSql( "update messageconversation MC SET messagecount = (SELECT count(MCM.messageconversationid) FROM messageconversation_messages MCM WHERE messageconversationid=MC.messageconversationid)" );
}
}
private void updateCompletedBy()
{
executeSql( "update programinstance set completedby=completeduser where completedby is null" );
executeSql( "update programstageinstance set completedby=completeduser where completedby is null" );
executeSql( "alter table programinstance drop column completeduser" );
executeSql( "alter table programstageinstance drop column completeduser" );
}
// Supportive methods
private void removeDeprecatedConfigurationColumns()
{
try
{
executeSql( "ALTER TABLE configuration DROP COLUMN smptpassword" );
executeSql( "ALTER TABLE configuration DROP COLUMN smtppassword" );
executeSql( "ALTER TABLE configuration DROP COLUMN remoteserverurl" );
executeSql( "ALTER TABLE configuration DROP COLUMN remoteserverusername" );
executeSql( "ALTER TABLE configuration DROP COLUMN remotepassword" );
executeSql( "ALTER TABLE configuration DROP COLUMN remoteserverpassword" );
}
catch ( Exception ex )
{
log.debug( ex );
}
}
private void updateTimestamps()
{
executeSql( "update datavalueaudit set created=timestamp where created is null" );
executeSql( "update datavalueaudit set created=now() where created is null" );
executeSql( "alter table datavalueaudit drop column timestamp" );
executeSql( "update trackedentitydatavalue set created=timestamp where created is null" );
executeSql( "update trackedentitydatavalue set lastupdated=timestamp where lastupdated is null" );
executeSql( "update trackedentityattributevalue set created=now() where created is null" );
executeSql( "update trackedentityattributevalue set lastupdated=now() where lastupdated is null" );
executeSql( "alter table trackedentitydatavalue drop column timestamp" );
}
private void updateProgramStatus()
{
executeSql( "alter table programinstance alter column status type varchar(50)" );
executeSql( "update programinstance set status='ACTIVE' where status='0'" );
executeSql( "update programinstance set status='COMPLETED' where status='1'" );
executeSql( "update programinstance set status='CANCELLED' where status='2'" );
executeSql( "update programinstance set status='ACTIVE' where status is null" );
}
private void updateValidationRuleEnums()
{
executeSql( "alter table validationrule alter column ruletype type varchar(50)" );
executeSql( "alter table validationrule alter column importance type varchar(50)" );
executeSql( "update validationrule set ruletype='VALIDATION' where ruletype='validation'" );
executeSql( "update validationrule set ruletype='SURVEILLANCE' where ruletype='surveillance'" );
executeSql( "update validationrule set ruletype='VALIDATION' where ruletype='' or ruletype is null" );
executeSql( "update validationrule set importance='HIGH' where importance='high'" );
executeSql( "update validationrule set importance='MEDIUM' where importance='medium'" );
executeSql( "update validationrule set importance='LOW' where importance='low'" );
executeSql( "update validationrule set importance='MEDIUM' where importance='' or importance is null" );
}
private void updateFeatureTypes()
{
executeSql( "update organisationunit set featuretype='NONE' where featuretype='None'" );
executeSql( "update organisationunit set featuretype='MULTI_POLYGON' where featuretype='MultiPolygon'" );
executeSql( "update organisationunit set featuretype='POLYGON' where featuretype='Polygon'" );
executeSql( "update organisationunit set featuretype='POINT' where featuretype='Point'" );
executeSql( "update organisationunit set featuretype='SYMBOL' where featuretype='Symbol'" );
executeSql( "update organisationunit set featuretype='NONE' where featuretype is null" );
}
private void updateAggregationTypes()
{
executeSql( "alter table dataelement alter column aggregationtype type varchar(50)" );
executeSql( "update dataelement set aggregationtype='SUM' where aggregationtype='sum'" );
executeSql( "update dataelement set aggregationtype='AVERAGE' where aggregationtype='avg'" );
executeSql( "update dataelement set aggregationtype='AVERAGE_SUM_ORG_UNIT' where aggregationtype='avg_sum_org_unit'" );
executeSql( "update dataelement set aggregationtype='AVERAGE_SUM_ORG_UNIT' where aggregationtype='average'" );
executeSql( "update dataelement set aggregationtype='COUNT' where aggregationtype='count'" );
executeSql( "update dataelement set aggregationtype='STDDEV' where aggregationtype='stddev'" );
executeSql( "update dataelement set aggregationtype='VARIANCE' where aggregationtype='variance'" );
executeSql( "update dataelement set aggregationtype='MIN' where aggregationtype='min'" );
executeSql( "update dataelement set aggregationtype='MAX' where aggregationtype='max'" );
executeSql( "update dataelement set aggregationtype='NONE' where aggregationtype='none'" );
executeSql( "update dataelement set aggregationtype='DEFAULT' where aggregationtype='default'" );
executeSql( "update dataelement set aggregationtype='CUSTOM' where aggregationtype='custom'" );
executeSql( "update dataelement set aggregationtype='SUM' where aggregationtype is null" );
}
private void updateValueTypes()
{
executeSql( "alter table dataelement alter column valuetype type varchar(50)" );
executeSql( "update dataelement set valuetype='NUMBER' where valuetype='int' and numbertype='number'" );
executeSql( "update dataelement set valuetype='INTEGER' where valuetype='int' and numbertype='int'" );
executeSql( "update dataelement set valuetype='INTEGER_POSITIVE' where valuetype='int' and numbertype='posInt'" );
executeSql( "update dataelement set valuetype='INTEGER_POSITIVE' where valuetype='int' and numbertype='positiveNumber'" );
executeSql( "update dataelement set valuetype='INTEGER_NEGATIVE' where valuetype='int' and numbertype='negInt'" );
executeSql( "update dataelement set valuetype='INTEGER_NEGATIVE' where valuetype='int' and numbertype='negativeNumber'" );
executeSql( "update dataelement set valuetype='INTEGER_ZERO_OR_POSITIVE' where valuetype='int' and numbertype='zeroPositiveInt'" );
executeSql( "update dataelement set valuetype='PERCENTAGE' where valuetype='int' and numbertype='percentage'" );
executeSql( "update dataelement set valuetype='UNIT_INTERVAL' where valuetype='int' and numbertype='unitInterval'" );
executeSql( "update dataelement set valuetype='NUMBER' where valuetype='int' and numbertype is null" );
executeSql( "alter table dataelement drop column numbertype" );
executeSql( "update dataelement set valuetype='TEXT' where valuetype='string' and texttype='text'" );
executeSql( "update dataelement set valuetype='LONG_TEXT' where valuetype='string' and texttype='longText'" );
executeSql( "update dataelement set valuetype='TEXT' where valuetype='string' and texttype is null" );
executeSql( "alter table dataelement drop column texttype" );
executeSql( "update dataelement set valuetype='DATE' where valuetype='date'" );
executeSql( "update dataelement set valuetype='DATETIME' where valuetype='datetime'" );
executeSql( "update dataelement set valuetype='BOOLEAN' where valuetype='bool'" );
executeSql( "update dataelement set valuetype='TRUE_ONLY' where valuetype='trueOnly'" );
executeSql( "update dataelement set valuetype='USERNAME' where valuetype='username'" );
executeSql( "update dataelement set valuetype='NUMBER' where valuetype is null" );
executeSql( "update trackedentityattribute set valuetype='TEXT' where valuetype='string'" );
executeSql( "update trackedentityattribute set valuetype='PHONE_NUMBER' where valuetype='phoneNumber'" );
executeSql( "update trackedentityattribute set valuetype='EMAIL' where valuetype='email'" );
executeSql( "update trackedentityattribute set valuetype='NUMBER' where valuetype='number'" );
executeSql( "update trackedentityattribute set valuetype='NUMBER' where valuetype='int'" );
executeSql( "update trackedentityattribute set valuetype='LETTER' where valuetype='letter'" );
executeSql( "update trackedentityattribute set valuetype='BOOLEAN' where valuetype='bool'" );
executeSql( "update trackedentityattribute set valuetype='TRUE_ONLY' where valuetype='trueOnly'" );
executeSql( "update trackedentityattribute set valuetype='DATE' where valuetype='date'" );
executeSql( "update trackedentityattribute set valuetype='TEXT' where valuetype='optionSet'" );
executeSql( "update trackedentityattribute set valuetype='TEXT' where valuetype='OPTION_SET'" );
executeSql( "update trackedentityattribute set valuetype='TRACKER_ASSOCIATE' where valuetype='trackerAssociate'" );
executeSql( "update trackedentityattribute set valuetype='USERNAME' where valuetype='users'" );
executeSql( "update trackedentityattribute set valuetype='TEXT' where valuetype is null" );
executeSql( "update optionset set valuetype='TEXT' where valuetype is null" );
executeSql( "update attribute set valuetype='TEXT' where valuetype='string'" );
executeSql( "update attribute set valuetype='LONG_TEXT' where valuetype='text'" );
executeSql( "update attribute set valuetype='BOOLEAN' where valuetype='bool'" );
executeSql( "update attribute set valuetype='DATE' where valuetype='date'" );
executeSql( "update attribute set valuetype='NUMBER' where valuetype='number'" );
executeSql( "update attribute set valuetype='INTEGER' where valuetype='integer'" );
executeSql( "update attribute set valuetype='INTEGER_POSITIVE' where valuetype='positive_integer'" );
executeSql( "update attribute set valuetype='INTEGER_NEGATIVE' where valuetype='negative_integer'" );
executeSql( "update attribute set valuetype='TEXT' where valuetype='option_set'" );
executeSql( "update attribute set valuetype='TEXT' where valuetype is null" );
}
private void upgradeProgramStageDataElements()
{
if ( tableExists( "programstage_dataelements" ) )
{
String autoIncr = statementBuilder.getAutoIncrementValue();
String insertSql =
"insert into programstagedataelement(programstagedataelementid,programstageid,dataelementid,compulsory,allowprovidedelsewhere," +
"sort_order,displayinreports,programstagesectionid,allowfuturedate,section_sort_order) " + "select " + autoIncr +
",programstageid,dataelementid,compulsory,allowprovidedelsewhere,sort_order,displayinreports,programstagesectionid,allowfuturedate,section_sort_order from programstage_dataelements";
executeSql( insertSql );
String dropSql = "drop table programstage_dataelements";
executeSql( dropSql );
log.info( "Upgraded program stage data elements" );
}
}
private void updateRelativePeriods()
{
if ( tableExists( "relativeperiods" ) )
{
executeSql( "UPDATE relativeperiods SET thisbiweek='f' WHERE thisbiweek IS NULL" );
executeSql( "UPDATE relativeperiods SET lastbiweek='f' WHERE lastbiweek IS NULL" );
executeSql( "UPDATE relativeperiods SET last4biweeks='f' WHERE last4biweeks IS NULL" );
}
}
private int executeSql( String sql )
{
try
{
return statementManager.getHolder().executeUpdate( sql );
}
catch ( Exception ex )
{
log.debug( ex );
return -1;
}
}
private boolean tableExists( String table )
{
try
{
statementManager.getHolder().queryForInteger( "select 1 from " + table );
return true;
}
catch ( Exception ex )
{
return false;
}
}
} |
package io.flutter.logging;
import com.intellij.ui.treeStructure.treetable.TreeTable;
import org.jetbrains.annotations.NotNull;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
class FlutterTreeTableModel implements TableModel {
@NotNull
private final TableModel model;
FlutterTreeTableModel(@NotNull TreeTable treeTable) {
model = treeTable.getModel();
}
@Override
public int getRowCount() {
return model.getRowCount();
}
@Override
public int getColumnCount() {
return ColumnIndex.values().length;
}
@Override
public String getColumnName(int columnIndex) {
return model.getColumnName(columnIndex);
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return model.getColumnClass(columnIndex);
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return model.isCellEditable(rowIndex, columnIndex);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
final Object obj = model.getValueAt(rowIndex, columnIndex);
final ColumnIndex index = ColumnIndex.forIndex(columnIndex);
if (index != ColumnIndex.INVALID && obj instanceof FlutterLogEntry) {
return index.toLogString((FlutterLogEntry)obj);
}
return obj;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
model.setValueAt(aValue, rowIndex, columnIndex);
}
@Override
public void addTableModelListener(TableModelListener l) {
model.addTableModelListener(l);
}
@Override
public void removeTableModelListener(TableModelListener l) {
model.removeTableModelListener(l);
}
public enum ColumnIndex {
INVALID(-1) {
@Override
public String toLogString(@NotNull FlutterLogEntry entry) {
throw new IllegalStateException("Can't get log string for `INVALID`");
}
},
MESSAGE(0) {
@Override
public String toLogString(@NotNull FlutterLogEntry entry) {
return entry.getMessage();
}
},
CATEGORY(1) {
@Override
public String toLogString(@NotNull FlutterLogEntry entry) {
return entry.getCategory();
}
},
LOG_LEVEL(2) {
@Override
public String toLogString(@NotNull FlutterLogEntry entry) {
return FlutterLog.Level.forValue(entry.getLevel()).name();
}
};
public final int index;
ColumnIndex(int index) {
this.index = index;
}
public abstract String toLogString(@NotNull FlutterLogEntry entry);
@NotNull
public static ColumnIndex forIndex(int index) {
for (ColumnIndex columnIndex : values()) {
if (columnIndex.index == index) {
return columnIndex;
}
}
return INVALID;
}
}
} |
package io.flutter.run.daemon;
import com.google.common.base.Stopwatch;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import io.flutter.FlutterInitializer;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* Listens for events while running or debugging an app.
*/
class FlutterAppListener implements DaemonEvent.Listener {
private final @NotNull FlutterApp app;
private final @NotNull ProgressHelper progress;
private final AtomicReference<Stopwatch> stopwatch = new AtomicReference<>();
FlutterAppListener(@NotNull FlutterApp app, @NotNull Project project) {
this.app = app;
this.progress = new ProgressHelper(project);
}
// process lifecycle
@Override
public void processWillTerminate() {
progress.cancel();
// Shutdown must be sync so that we prevent the processTerminated() event from being delivered
// until a graceful shutdown has been tried.
try {
app.shutdownAsync().get();
}
catch (Exception e) {
LOG.warn("exception while shutting down Flutter App", e);
}
}
@Override
public void processTerminated() {
progress.cancel();
app.changeState(FlutterApp.State.TERMINATED);
}
// daemon domain
@Override
public void onDaemonLogMessage(@NotNull DaemonEvent.LogMessage message) {
LOG.info("flutter app: " + message.message);
}
// app domain
@Override
public void onAppStarting(DaemonEvent.AppStarting event) {
app.setAppId(event.appId);
}
@Override
public void onAppDebugPort(@NotNull DaemonEvent.AppDebugPort port) {
app.setWsUrl(port.wsUri);
String uri = port.baseUri;
if (uri == null) return;
if (uri.startsWith("file:")) {
// Convert the file: url to a path.
try {
uri = new URL(uri).getPath();
if (uri.endsWith(File.separator)) {
uri = uri.substring(0, uri.length() - 1);
}
}
catch (MalformedURLException e) {
// ignore
}
}
app.setBaseUri(uri);
}
@Override
public void onAppStarted(DaemonEvent.AppStarted started) {
app.changeState(FlutterApp.State.STARTED);
}
@Override
public void onAppLog(@NotNull DaemonEvent.AppLog message) {
final ConsoleView console = app.getConsole();
if (console == null) return;
console.print(message.log + "\n", ConsoleViewContentType.NORMAL_OUTPUT);
}
@Override
public void onAppProgressStarting(@NotNull DaemonEvent.AppProgress event) {
progress.start(event.message);
if (event.getType().startsWith("hot.")) {
stopwatch.set(Stopwatch.createStarted());
}
}
@Override
public void onAppProgressFinished(@NotNull DaemonEvent.AppProgress event) {
progress.done();
final Stopwatch watch = stopwatch.getAndSet(null);
if (watch != null) {
watch.stop();
switch (event.getType()) {
case "hot.reload":
reportElapsed(watch, "Reloaded", "reload");
break;
case "hot.restart":
reportElapsed(watch, "Restarted", "restart");
break;
}
}
}
private void reportElapsed(@NotNull Stopwatch watch, String verb, String analyticsName) {
final long elapsedMs = watch.elapsed(TimeUnit.MILLISECONDS);
FlutterInitializer.getAnalytics().sendTiming("run", analyticsName, elapsedMs);
}
@Override
public void onAppStopped(@NotNull DaemonEvent.AppStopped stopped) {
progress.cancel();
app.getProcessHandler().destroyProcess();
}
private static final Logger LOG = Logger.getInstance(FlutterAppListener.class.getName());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.