answer
stringlengths
17
10.2M
package sg.edu.cs2103aug2015_w13_2j; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import javafx.util.Pair; import sg.edu.cs2103aug2015_w13_2j.Parser.Token; import sg.edu.cs2103aug2015_w13_2j.TaskInterface.InvalidTaskException; import sg.edu.cs2103aug2015_w13_2j.TaskInterface.TaskNotFoundException; import sg.edu.cs2103aug2015_w13_2j.TextUI.Message; public class Logic implements LogicInterface { private FunDUE mAppInstance; private ArrayList<Task> mTasks = new ArrayList<Task>(); public Logic(FunDUE appInstance) { mAppInstance = appInstance; } public void executeCommand(ArrayList<Pair<Token, String>> tokens) { for (Pair<Token, String> pair : tokens) { if (pair.getKey() == Token.RESERVED) { try { switch (pair.getValue()) { case "add": addTask(tokens); mAppInstance.getTextUIInstance().feedback(Message.LOGIC_ADDED); break; case "edit": editTask(tokens); mAppInstance.getTextUIInstance().feedback(Message.LOGIC_EDITED); break; case "list": mAppInstance.getTextUIInstance().feedback(Message.CLEAR); break; case "delete": deleteTask(tokens); mAppInstance.getTextUIInstance().feedback(Message.LOGIC_DELETED); break; default: System.err.println("[Logic] Unimplemented command: " + pair.getValue()); mAppInstance.getTextUIInstance().feedback(Message.ERROR_COMMAND_NOT_IMPLEMENTED); break; } } catch (InvalidTaskException e) { System.err.println("[Logic] Invalid Task"); mAppInstance.getTextUIInstance().feedback(Message.ERROR_INVALID_TASK); } catch (TaskNotFoundException e) { System.err.println("[Logic] Task not found"); mAppInstance.getTextUIInstance().feedback(Message.ERROR_TASK_NOT_FOUND); } mAppInstance.getTextUIInstance().display(mTasks); return; } } mAppInstance.getTextUIInstance().feedback(Message.ERROR_COMMAND_NOT_RECOGNIZED); } public void echo(String s) { //mAppInstance.getTextUIInstance().print(s); } /** * Updates the passed in Task object based on the parsed tokens * * @param tokens * The tokens parsed from the command <b>including</b> the * command token itself but <b>excluding</b> any previously used * identifiers * @throws InvalidTaskException * Thrown when the Task constructed from the parsed tokens is * invalid */ private Task updateTask(ArrayList<Pair<Token, String>> tokens, Task task) throws InvalidTaskException { Iterator<Pair<Token, String>> iter = tokens.iterator(); while (iter.hasNext()) { Pair<Token, String> pair = iter.next(); switch (pair.getKey()) { case FLAG: String flag = pair.getValue(); switch (flag) { // Flags which expect the next token to be a date case Parser.FLAG_END: case Parser.FLAG_START: if (iter.hasNext()) { Pair<Token, String> nextPair = iter.next(); assert(nextPair.getKey() == Token.DATE || nextPair.getKey() == Token.DATE_INVALID); // Only set valid dates if (nextPair.getKey() == Token.DATE) { if (flag == Parser.FLAG_END) { task.setEnd(nextPair.getValue()); } else if (flag == Parser.FLAG_START) { task.setStart(nextPair.getValue()); } } } break; } break; case NAME: task.setName(pair.getValue()); break; case ALPHA_NUM: case DATE: case DATE_INVALID: case FLAG_INVALID: case ID: case ID_INVALID: case RESERVED: case WHITESPACE: // Do nothing break; } } // Check if the constructed Task is valid if (task.isValid()) { return task; } else { return null; } } private Task addTask(ArrayList<Pair<Token, String>> tokens) throws InvalidTaskException { Task task = updateTask(tokens, new Task()); mTasks.add(task); determineType(task); sortByDeadline(); System.out.println("[Logic] Added task"); System.out.print(task); return task; } private void editTask(ArrayList<Pair<Token, String>> tokens) throws TaskNotFoundException, InvalidTaskException { Iterator<Pair<Token, String>> iter = tokens.iterator(); Task task = null; // First iteration to retrieve the corresponding Task object while (iter.hasNext() && task == null) { Pair<Token, String> pair = iter.next(); switch (pair.getKey()) { case NAME: case ID: int index = pair.getKey() == Token.ID ? Integer.parseInt(pair.getValue()) : getTaskIndexByName(pair.getValue()); task = getTask(index); // Remove the first identifying name or ID such that future ones // will update the Task's name iter.remove(); break; default: break; } } System.out.println("[Logic] Editing task"); System.out.println("[Logic] Before"); System.out.print(task); updateTask(tokens, task); System.out.println("[Logic] After"); System.out.print(task); sortByDeadline(); } /** * Deletes the task with the specified ID or name (ID has greater precedence * over name) from the master task list * * @param tokens * The tokens parsed from the command <b>including</b> the * command token itself * @throws TaskNotFoundException * Thrown when the provided task name could not be found or ID * is out of bounds */ private void deleteTask(ArrayList<Pair<Token, String>> tokens) throws TaskNotFoundException { Iterator<Pair<Token, String>> iter = tokens.iterator(); while (iter.hasNext()) { Pair<Token, String> pair = iter.next(); switch (pair.getKey()) { case ALPHA_NUM: case DATE: case DATE_INVALID: case FLAG: case FLAG_INVALID: // Do nothing break; case ID_INVALID: // Do nothing break; case ID: case NAME: int index = pair.getKey() == Token.ID ? Integer.parseInt(pair.getValue()) : getTaskIndexByName(pair.getValue()); System.out.println("[Logic] Removing task"); Task task = removeTask(index); System.out.print(task); return; case RESERVED: case WHITESPACE: // Do nothing break; } } } /** * This method updates the tasks list upon a new session It reads the file * from the storage and fills up the internal ArrayList * */ /* // Why is this public? private void readFile() { try { String path = mAppInstance.getStorageInstance().readRawFile("DATA_FILE_PATH"); tasks = (ArrayList) mAppInstance.getStorageInstance().readFile(path); } catch (Exception e) { e.printStackTrace(); } } */ /** * Retrieves the index of the first occurrence of a Task object with the * name provided * * @param name * The name of the Task object to find * @return The index of the Task object or -1 if none is found */ private int getTaskIndexByName(String name) { for (int i = 0; i < mTasks.size(); i++) { if (mTasks.get(i).getName().compareTo(name) == 0) { return i; } } return -1; } /** * Convenience method to retrieve a task with an index specified by * non-sanitized user input or to be chained with the return value of * {@link Logic#getTaskIndexByName(String)}. Throws an exception if the * index is out of bounds * * @param index * The index of the Task object to retrieve * @return The Task object with the specified index * @throws TaskNotFoundException * Thrown when the index specified is out of bounds */ private Task getTask(int index) throws TaskNotFoundException { if (index >= 0 && index < mTasks.size()) { return mTasks.get(index); } else { throw new TaskNotFoundException(); } } /** * Convenience method to remove a task with an index specified by * non-sanitized user input or to be chained with the return value of * {@link Logic#getTaskIndexByName(String)}. Throws an exception if the * index is out of bounds * * @param index * The index of the Task object to be removed * @return The Task object that was removed * @throws TaskNotFoundException * Thrown when the index specified is out of bounds */ private Task removeTask(int index) throws TaskNotFoundException { if (index >= 0 && index < mTasks.size()) { Task toRemove = mTasks.remove(index); sortByDeadline(); return toRemove; } else { throw new TaskNotFoundException(); } } private Task archiveTask(int index) throws TaskNotFoundException { Task archivedTask = new Task(); if (index >= 0 && index < mTasks.size()) { archivedTask = mTasks.get(index); archivedTask.setArchived("TRUE"); return archivedTask; } else { throw new TaskNotFoundException(); } } private Task retrieveTask(int index) throws TaskNotFoundException { Task retrievedTask = new Task(); if (index >= 0 && index < mTasks.size()) { retrievedTask = mTasks.get(index); retrievedTask.setArchived("FALSE"); return retrievedTask; } else { throw new TaskNotFoundException(); } } /** * This method sorts a list of tasks according to their deadlines(if any) * The tasks with deadlines takes priority, followed by events sorted * according to start time and floats to be added last, sorted by their * names * */ private ArrayList<Task> sortByDeadline() { Collections.sort(mTasks, new Comparator<Task>() { public int compare(Task task1, Task task2) { if (task1.getType().equals(task2.getType())) { if (task1.getType().equals("DEADLINE")) { return task1.getEnd().compareTo(task2.getEnd()); } else if (task1.getType().equals("EVENT")) { return task1.getStart().compareTo(task2.getStart()); } else { return task1.getName().compareTo(task2.getName()); } } else { return task1.getType().compareTo(task2.getType()); } } }); return mTasks; } /** * Determine the type of a task based on its start (if any) and end (if any) * times * * @param task * the new task to be categorized */ private void determineType(Task task) { if (task.getEnd() == null) { // if end == null, float task.setType("FLOAT"); } else { if (task.getStart() != null) { // if end != null and start != null, event task.setType("EVENT"); } else { // if end != null but start == null, deadline task.setType("DEADLINE"); } } } }
package org.appwork.utils.net; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map.Entry; import java.util.logging.Level; import java.util.zip.GZIPInputStream; import org.appwork.utils.Application; import org.appwork.utils.IO; import org.appwork.utils.locale.Loc; import org.appwork.utils.logging.Log; public class SimpleHTTP { private static final Object CALL_LOCK = new Object(); private final HashMap<String, String> requestHeader; private HttpURLConnection connection; private int connectTimeout = 15000; private int readTimeout = 30000; private boolean followRedirects = true; public SimpleHTTP() { requestHeader = new HashMap<String, String>(); } public void clearRequestHeader() { requestHeader.clear(); } /** * @param url * @param progress * @param file * @throws InterruptedException * @throws IOException */ public void download(final URL url, final DownloadProgress progress, final File file) throws IOException, InterruptedException { BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); try { this.download(url, progress, 0, out); } catch (final IOException e) { try { out.close(); } catch (final Throwable t) { } if (file.length() > 0) { final IOException ex = new HTTPException(connection, IO.readFileToString(file), e); file.delete(); throw ex; } } } finally { try { out.close(); } catch (final Throwable t) { } } } public byte[] download(final URL url, final DownloadProgress progress, final long maxSize) throws IOException, InterruptedException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { this.download(url, progress, maxSize, baos); } catch (final IOException e) { if (baos.size() > 0) { throw new HTTPException(connection, new String(baos.toByteArray()), e); } } try { baos.close(); } catch (final Throwable t) { } return baos.toByteArray(); } /** * * Please do not forget to close the output stream. * * @param url * @param progress * @param maxSize * @param baos * @throws IOException * @throws InterruptedException */ public void download(final URL url, final DownloadProgress progress, final long maxSize, final OutputStream baos) throws IOException, InterruptedException { BufferedInputStream input = null; GZIPInputStream gzi = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(followRedirects); connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); try { final String loc = Loc.getLocale().split("_")[0]; connection.setRequestProperty("Accept-Language", loc); } catch (final Throwable e) { // Log.exception(Level.WARNING, e); } connection.setRequestProperty("User-Agent", "AppWork " + Application.getApplication()); connection.setRequestProperty("Connection", "Close"); for (final Entry<String, String> next : requestHeader.entrySet()) { connection.setRequestProperty(next.getKey(), next.getValue()); } connection.connect(); IOException exception = null; try { if (connection.getHeaderField("Content-Encoding") != null && connection.getHeaderField("Content-Encoding").equalsIgnoreCase("gzip")) { input = new BufferedInputStream(gzi = new GZIPInputStream(connection.getInputStream())); } else { input = new BufferedInputStream(connection.getInputStream()); } } catch (final IOException e) { exception = e; if (connection.getHeaderField("Content-Encoding") != null && connection.getHeaderField("Content-Encoding").equalsIgnoreCase("gzip")) { input = new BufferedInputStream(gzi = new GZIPInputStream(connection.getErrorStream())); } else { input = new BufferedInputStream(connection.getErrorStream()); } } if (maxSize > 0 && connection.getContentLength() > maxSize) { throw new IOException("Max size exeeded!"); } if (progress != null) { progress.setTotal(connection.getContentLength()); } final byte[] b = new byte[32767]; int len; long loaded = 0; while ((len = input.read(b)) != -1) { if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } if (len > 0) { baos.write(b, 0, len); loaded += len; if (maxSize > 0 && loaded > maxSize) { throw new IOException("Max size exeeded!"); } } if (progress != null) { progress.increaseLoaded(len); } } if (exception != null) { throw exception; } } finally { try { input.close(); } catch (final Exception e) { } try { gzi.close(); } catch (final Exception e) { } try { connection.disconnect(); } catch (final Throwable e) { } } } public HttpURLConnection getConnection() { return connection; } public int getConnectTimeout() { return connectTimeout; } public String getPage(final URL url) throws IOException, InterruptedException { synchronized (SimpleHTTP.CALL_LOCK) { BufferedReader in = null; InputStreamReader isr = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(followRedirects); connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); try { final String loc = Loc.getLocale().split("_")[0]; connection.setRequestProperty("Accept-Language", loc); } catch (final Throwable e) { } connection.setRequestProperty("User-Agent", "AppWork " + Application.getApplication()); connection.setRequestProperty("Connection", "Close"); connection.setRequestProperty("Accept-Charset", "UTF-8"); for (final Entry<String, String> next : requestHeader.entrySet()) { connection.setRequestProperty(next.getKey(), next.getValue()); } int lookupTry = 0; while (true) { try { connection.connect(); break; } catch (final UnknownHostException e) { if (++lookupTry > 3) { throw e; } /* dns lookup failed, short wait and try again */ Thread.sleep(200); } } in = new BufferedReader(isr = new InputStreamReader(connection.getInputStream(), "UTF-8")); String str; final StringBuilder sb = new StringBuilder(); while ((str = in.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(str); } return sb.toString(); } finally { try { in.close(); } catch (final Throwable e) { } try { isr.close(); } catch (final Throwable e) { } try { connection.disconnect(); } catch (final Throwable e) { } } } } public int getReadTimeout() { return readTimeout; } /** * @return */ public HashMap<String, String> getRequestHeader() { return requestHeader; } public String getRequestHeader(final String key) { return requestHeader.get(key); } public String getResponseHeader(final String string) { synchronized (SimpleHTTP.CALL_LOCK) { if (connection == null) { return null; } return connection.getHeaderField(string); } } public boolean isFollowRedirects() { return followRedirects; } public HttpURLConnection openGetConnection(final URL url) throws IOException, InterruptedException { return this.openGetConnection(url, readTimeout); } public HttpURLConnection openGetConnection(final URL url, final int readTimeout) throws IOException, InterruptedException { synchronized (SimpleHTTP.CALL_LOCK) { try { connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(connectTimeout); connection.setInstanceFollowRedirects(followRedirects); connection.setReadTimeout(readTimeout < 0 ? readTimeout : readTimeout); try { final String loc = Loc.getLocale().split("_")[0]; connection.setRequestProperty("Accept-Language", loc); } catch (final Throwable e) { // Log.exception(Level.WARNING, e); } connection.setRequestProperty("User-Agent", "AppWork " + Application.getApplication()); connection.setRequestProperty("Connection", "Close"); connection.setRequestProperty("Accept-Charset", "UTF-8"); for (final Entry<String, String> next : requestHeader.entrySet()) { connection.setRequestProperty(next.getKey(), next.getValue()); } int lookupTry = 0; while (true) { try { connection.connect(); break; } catch (final UnknownHostException e) { if (++lookupTry > 3) { throw e; } /* dns lookup failed, short wait and try again */ Thread.sleep(200); } } return connection; } finally { try { connection.disconnect(); } catch (final Throwable e2) { } } } } public HttpURLConnection openPostConnection(final URL url, final String postData, final HashMap<String, String> header) throws IOException, InterruptedException { synchronized (SimpleHTTP.CALL_LOCK) { OutputStreamWriter writer = null; OutputStream outputStream = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(followRedirects); connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setUseCaches(false); connection.setDoOutput(true); try { final String loc = Loc.getLocale().split("_")[0]; connection.setRequestProperty("Accept-Language", loc); } catch (final Throwable e) { Log.exception(Level.WARNING, e); } connection.setRequestProperty("User-Agent", "AppWork " + Application.getApplication()); connection.setRequestProperty("Connection", "Close"); /* connection specific headers */ if (header != null) { for (final Entry<String, String> next : header.entrySet()) { connection.setRequestProperty(next.getKey(), next.getValue()); } } for (final Entry<String, String> next : requestHeader.entrySet()) { connection.setRequestProperty(next.getKey(), next.getValue()); } int lookupTry = 0; while (true) { try { connection.connect(); break; } catch (final UnknownHostException e) { if (++lookupTry > 3) { throw e; } /* dns lookup failed, short wait and try again */ Thread.sleep(200); } } outputStream = connection.getOutputStream(); writer = new OutputStreamWriter(outputStream); writer.write(postData); writer.flush(); return connection; } finally { try { connection.disconnect(); } catch (final Throwable e2) { } try { writer.close(); } catch (final Throwable e) { } try { outputStream.close(); } catch (final Throwable e) { } } } } public String postPage(final URL url, final String data) throws IOException, InterruptedException { synchronized (SimpleHTTP.CALL_LOCK) { OutputStreamWriter writer = null; BufferedReader reader = null; OutputStream outputStream = null; InputStreamReader isr = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(followRedirects); connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setUseCaches(false); connection.setDoOutput(true); try { final String loc = Loc.getLocale().split("_")[0]; connection.setRequestProperty("Accept-Language", loc); } catch (final Throwable e) { } connection.setRequestProperty("User-Agent", "AppWork " + Application.getApplication()); connection.setRequestProperty("Connection", "Close"); for (final Entry<String, String> next : requestHeader.entrySet()) { connection.setRequestProperty(next.getKey(), next.getValue()); } int lookupTry = 0; while (true) { try { connection.connect(); break; } catch (final UnknownHostException e) { if (++lookupTry > 3) { throw e; } /* dns lookup failed, short wait and try again */ Thread.sleep(200); } } outputStream = connection.getOutputStream(); writer = new OutputStreamWriter(outputStream); writer.write(data); writer.flush(); reader = new BufferedReader(isr = new InputStreamReader(connection.getInputStream(), "UTF-8")); final StringBuilder sb = new StringBuilder(); String str; while ((str = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(str); } return sb.toString(); } finally { try { reader.close(); } catch (final Throwable e) { } try { isr.close(); } catch (final Throwable e) { } try { writer.close(); } catch (final Throwable e) { } try { outputStream.close(); } catch (final Throwable e) { } try { connection.disconnect(); } catch (final Throwable e) { } } } } public void putRequestHeader(final String key, final String value) { requestHeader.put(key, value); } public void setConnectTimeout(final int connectTimeout) { this.connectTimeout = connectTimeout; } public void setFollowRedirects(final boolean followRedirects) { this.followRedirects = followRedirects; } public void setReadTimeout(final int readTimeout) { this.readTimeout = readTimeout; } }
package org.appwork.utils.os; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.logging.Level; import javax.swing.filechooser.FileFilter; import net.miginfocom.swing.MigLayout; import org.appwork.exceptions.WTFException; import org.appwork.shutdown.ShutdownController; import org.appwork.shutdown.ShutdownEvent; import org.appwork.storage.JSonStorage; import org.appwork.storage.StorageException; import org.appwork.utils.Application; import org.appwork.utils.Regex; import org.appwork.utils.StringUtils; import org.appwork.utils.locale._AWU; import org.appwork.utils.logging.Log; import org.appwork.utils.os.mime.Mime; import org.appwork.utils.os.mime.MimeDefault; import org.appwork.utils.os.mime.MimeLinux; import org.appwork.utils.os.mime.MimeWindows; import org.appwork.utils.swing.dialog.Dialog; import org.appwork.utils.swing.dialog.DialogCanceledException; import org.appwork.utils.swing.dialog.DialogClosedException; import org.appwork.utils.swing.dialog.DialogNoAnswerException; public class CrossSystem { public static final byte OS_LINUX_OTHER = 6; public static final byte OS_MAC_OTHER = 5; public static final byte OS_WINDOWS_OTHER = 4; public static final byte OS_WINDOWS_NT = 3; public static final byte OS_WINDOWS_2000 = 2; public static final byte OS_WINDOWS_XP = 0; public static final byte OS_WINDOWS_2003 = 7; public static final byte OS_WINDOWS_VISTA = 1; public static final byte OS_WINDOWS_7 = 8; public static final byte OS_WINDOWS_SERVER_2008 = 9; public static final byte OS_WINDOWS_8 = 10; private static String JAVAINT = null; private static DesktopSupport desktopSupport = null; /** * Cache to store the OS string in */ private final static String OS_STRING; /** * Cache to store the OS ID in */ private final static byte OS_ID; /** * Cache to store the Mime Class in */ private static final Mime MIME; private static String[] BROWSER_COMMANDLINE = null; private static String[] FILE_COMMANDLINE = null; static { } static { /* Init OS_ID */ OS_STRING = System.getProperty("os.name"); OS_ID = CrossSystem.getOSID(CrossSystem.OS_STRING); /* Init MIME */ if (CrossSystem.isWindows()) { MIME = new MimeWindows(); CrossSystem.desktopSupport = new DesktopSupportWindows(); } else if (CrossSystem.isLinux()) { CrossSystem.desktopSupport = new DesktopSupportLinux(); MIME = new MimeLinux(); } else { CrossSystem.desktopSupport = new DesktopSupportJavaDesktop(); MIME = new MimeDefault(); } } /** * internal function to open a file/folder * * @param file * @throws IOException */ private static void _openFILE(final File file) throws IOException { if (!CrossSystem.openCustom(CrossSystem.FILE_COMMANDLINE, file.getAbsolutePath())) { CrossSystem.desktopSupport.openFile(file); } } /** * internal function to open an URL in a browser * * @param _url * @throws IOException * @throws URISyntaxException */ private static void _openURL(final String _url) throws IOException, URISyntaxException { if (!CrossSystem.openCustom(CrossSystem.BROWSER_COMMANDLINE, _url)) { CrossSystem.desktopSupport.browseURL(new URL(_url)); } } /** * use this method to make pathPart safe to use in a full absoluePath. * * it will remove driveletters/path seperators and all known chars that are * forbidden in a path * * @param pathPart * @return */ public static String alleviatePathParts(String pathPart) { if (StringUtils.isEmpty(pathPart)) { if (pathPart != null) { return pathPart; } return null; } /* remove invalid chars */ pathPart = pathPart.replaceAll("([\\\\|<|>|\\||\"|:|\\*|\\?|/|\\x00])+", "_"); /* * remove ending points, not allowed under windows and others os maybe * too */ pathPart = pathPart.replaceFirst("\\.+$", ""); if (CrossSystem.isWindows()) { if (new Regex(pathPart, "^(CON|PRN|AUX|NUL|COM\\d+|LPT\\d+|CLOCK\\$)$").matches()) { pathPart = "_" + pathPart; } } return pathPart.trim(); } public static String[] getBrowserCommandLine() { return CrossSystem.BROWSER_COMMANDLINE; } public static String[] getEditor(final String extension) throws DialogCanceledException, DialogClosedException, StorageException { final File[] ret = Dialog.getInstance().showFileChooser("FILE_EDIT_CONTROLLER_" + extension, _AWU.T.fileditcontroller_geteditor_for(extension), Dialog.FileChooserSelectionMode.FILES_ONLY, new FileFilter() { @Override public boolean accept(final File f) { if (f.isDirectory()) { return true; } if (CrossSystem.isWindows()) { return f.getName().endsWith(".exe"); } else { return f.canExecute(); } } @Override public String getDescription() { return _AWU.T.fileeditcontroller_exechooser_description(extension); } }, false, Dialog.FileChooserType.OPEN_DIALOG_WITH_PRESELECTION, new File(JSonStorage.getPlainStorage("EDITORS").get(extension, ""))); if (ret != null && ret.length > 0) { JSonStorage.getPlainStorage("EDITORS").put(extension, ret[0].toString()); return new String[] { ret[0].toString() }; } else { return null; } } public static String[] getFileCommandLine() { return CrossSystem.FILE_COMMANDLINE; } public static String getFileExtension(final String str) { if (StringUtils.isEmpty(str)) { return null; } final int lastPoint = str.lastIndexOf("."); if (lastPoint > 0 && lastPoint != str.length()) { return str.substring(lastPoint + 1); } return null; } public static byte getID() { return CrossSystem.OS_ID; } public static String getJavaBinary() { if (CrossSystem.JAVAINT != null) { return CrossSystem.JAVAINT; } String javaBinary = "java"; if (CrossSystem.isWindows()) { javaBinary = "javaw.exe"; } final String javaHome = System.getProperty("java.home"); if (javaHome != null) { /* get path from system property */ final File java = new File(new File(javaHome), "/bin/" + javaBinary); if (java.exists() && java.isFile()) { CrossSystem.JAVAINT = java.getAbsolutePath(); } } else { CrossSystem.JAVAINT = javaBinary; } return CrossSystem.JAVAINT; } /** * Returns the Mime Class for the current OS * * @return * @see Mime */ public static Mime getMime() { return CrossSystem.MIME; } /** * @param osString * @return */ public static byte getOSID(final String osString) { if (osString == null) { /* fallback to latest Windows */ return CrossSystem.OS_WINDOWS_7; } final String OS = osString.toLowerCase(); if (OS.contains("windows 8")) { return CrossSystem.OS_WINDOWS_8; } else if (OS.contains("windows 7")) { return CrossSystem.OS_WINDOWS_7; } else if (OS.contains("windows xp")) { return CrossSystem.OS_WINDOWS_XP; } else if (OS.contains("windows vista")) { return CrossSystem.OS_WINDOWS_VISTA; } else if (OS.contains("windows 2000")) { return CrossSystem.OS_WINDOWS_2000; } else if (OS.contains("windows 2003")) { return CrossSystem.OS_WINDOWS_2003; } else if (OS.contains("windows server 2008")) { return CrossSystem.OS_WINDOWS_SERVER_2008; } else if (OS.contains("nt")) { return CrossSystem.OS_WINDOWS_NT; } else if (OS.contains("windows")) { return CrossSystem.OS_WINDOWS_OTHER; } else if (OS.contains("mac")) { return CrossSystem.OS_MAC_OTHER; } else { return CrossSystem.OS_LINUX_OTHER; } } public static String getOSString() { return CrossSystem.OS_STRING; } /** * checks if given path is absolute or relative * * @param path * @return */ public static boolean isAbsolutePath(final String path) { if (StringUtils.isEmpty(path)) { return false; } if (CrossSystem.isWindows() && path.matches("\\\\\\\\.+\\\\.+")) { return true; } if (CrossSystem.isWindows() && path.matches(".:/.*")) { return true; } if (CrossSystem.isWindows() && path.matches(".:\\\\.*")) { return true; } if (!CrossSystem.isWindows() && path.startsWith("/")) { return true; } return false; } /** * Returns true if the OS is a linux system * * @return */ public static boolean isLinux() { return CrossSystem.isLinux(CrossSystem.OS_ID); } public static boolean isLinux(final byte osID) { return osID == CrossSystem.OS_LINUX_OTHER; } /** * Returns true if the OS is a MAC System * * @return */ public static boolean isMac() { return CrossSystem.isMac(CrossSystem.OS_ID); } public static boolean isMac(final byte osID) { return osID == CrossSystem.OS_MAC_OTHER; } /** * returns true in case of "open an URL in a browser" is supported * * @return */ public static boolean isOpenBrowserSupported() { return CrossSystem.desktopSupport.isBrowseURLSupported(); } /** * returns true in case of "open a File" is supported * * @return */ public static boolean isOpenFileSupported() { return CrossSystem.desktopSupport.isOpenFileSupported(); } /** * Returns true if the OS is a Windows System * * @return */ public static boolean isWindows() { return CrossSystem.isWindows(CrossSystem.OS_ID); } /** * @param osId * @return */ public static boolean isWindows(final byte osId) { switch (osId) { case OS_WINDOWS_8: case OS_WINDOWS_XP: case OS_WINDOWS_VISTA: case OS_WINDOWS_2000: case OS_WINDOWS_2003: case OS_WINDOWS_NT: case OS_WINDOWS_OTHER: case OS_WINDOWS_7: case OS_WINDOWS_SERVER_2008: return true; } return false; } public static void main(final String[] args) { CrossSystem.restartApplication(MigLayout.class); } private static boolean openCustom(final String[] custom, final String what) throws IOException { if (custom == null || custom.length < 1) { return false; } boolean added = false; final ArrayList<String> commands = new ArrayList<String>(); for (final String s : custom) { final String add = s.replace("%s", what); if (!add.equals(s)) { added = true; } commands.add(add); } if (added == false) { commands.add(what); } Runtime.getRuntime().exec(commands.toArray(new String[] {})); return true; } /** * Opens a file or directory * * @see java.awt.Desktop#open(File) * @param file * @throws IOException */ public static void openFile(final File file) { try { CrossSystem._openFILE(file); } catch (final IOException e) { Log.exception(e); } } /** * Open an url in the systems default browser * * @param url */ public static void openURL(final String url) { try { CrossSystem._openURL(url); } catch (final Throwable e) { Log.exception(Level.WARNING, e); } } public static void openURL(final URL url) { CrossSystem.openURL(url.toString()); } /** * @param update_dialog_news_button_url */ public static void openURLOrShowMessage(final String urlString) { try { CrossSystem._openURL(urlString); } catch (final Throwable e) { Log.exception(Level.WARNING, e); try { Dialog.getInstance().showInputDialog(Dialog.BUTTONS_HIDE_CANCEL, _AWU.T.crossSystem_open_url_failed_msg(), urlString); } catch (final DialogNoAnswerException donothing) { } } } /** * @param class1 */ public static void restartApplication(final Class<?> class1, final String... parameters) { try { final ArrayList<String> nativeParameters = new ArrayList<String>(); File runin = null; if (CrossSystem.isMac()) { // find .app File rootpath = Application.getRootByClass(class1, null); final HashSet<File> loopMap = new HashSet<File>(); while (rootpath != null && loopMap.add(rootpath)) { if (rootpath.getName().endsWith(".app")) { break; } rootpath = rootpath.getParentFile(); } if (rootpath.getName().endsWith(".app")) { // found app.- restart it. nativeParameters.add("open"); nativeParameters.add("-n"); nativeParameters.add(rootpath.getAbsolutePath()); runin = rootpath.getParentFile(); } } if (nativeParameters.isEmpty()) { final URL root = class1.getClassLoader().getResource(class1.getName().replace(".", "/") + ".class"); // Filenames may contain ! !! final int index = root.getPath().indexOf("!"); if (index <= 0 || !"jar".equalsIgnoreCase(root.getProtocol())) { throw new WTFException("REstart works only in Jared mode"); } else { final File jarFile = new File(new URI(root.getPath().substring(0, index))); runin = jarFile.getParentFile(); if (CrossSystem.isWindows()) { final File exeFile = new File(jarFile.getParentFile(), jarFile.getName().substring(0, jarFile.getName().length() - 4) + ".exe"); if (exeFile.exists()) { nativeParameters.add(exeFile.getAbsolutePath()); } else { nativeParameters.add(CrossSystem.getJavaBinary()); nativeParameters.add("-jar"); nativeParameters.add(jarFile.getAbsolutePath()); } } else { nativeParameters.add(CrossSystem.getJavaBinary()); nativeParameters.add("-jar"); nativeParameters.add(jarFile.getAbsolutePath()); } } } if (parameters != null) { for (final String s : parameters) { nativeParameters.add(s); } } final ProcessBuilder pb = new ProcessBuilder(nativeParameters.toArray(new String[] {})); /* * needed because the root is different for jre/class version */ System.out.println("Root: " + runin); if (runin != null) { pb.directory(runin); } ShutdownController.getInstance().addShutdownEvent(new ShutdownEvent() { { this.setHookPriority(Integer.MIN_VALUE); } @Override public void run() { try { pb.start(); } catch (final IOException e) { Log.exception(e); } } }); ShutdownController.getInstance().requestShutdown(); } catch (final Throwable e) { throw new WTFException(e); } } /** * Set commandline to open the browser use %s as wildcard for the url * * @param commands */ public static void setBrowserCommandLine(final String[] commands) { CrossSystem.BROWSER_COMMANDLINE = commands; } public static void setFileCommandLine(final String[] fILE_COMMANDLINE) { CrossSystem.FILE_COMMANDLINE = fILE_COMMANDLINE; } /** * splits filename into name,extension * * @param filename * @return */ public static String[] splitFileName(final String filename) { final String extension = new Regex(filename, "\\.+([^\\.]*$)").getMatch(0); final String name = new Regex(filename, "(.*?)(\\.+[^\\.]*$|$)").getMatch(0); return new String[] { name, extension }; } }
package org.jgroups; import org.jgroups.annotations.ManagedOperation; import org.jgroups.blocks.MethodCall; import org.jgroups.jmx.AdditionalJmxObjects; import org.jgroups.jmx.ResourceDMBean; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.stack.DiagnosticsHandler; import org.jgroups.stack.Protocol; import org.jgroups.util.Util; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Stream; /** * @author Bela Ban * @since 4.0 */ public class JChannelProbeHandler implements DiagnosticsHandler.ProbeHandler { protected final JChannel ch; protected final Log log; public JChannelProbeHandler(JChannel ch) { this.ch=ch; log=LogFactory.getLog(ch.getClass()); } public Map<String, String> handleProbe(String... keys) { Map<String,String> map=new TreeMap<>(); for(String key : keys) { if(key.startsWith("jmx")) { handleJmx(map, key); continue; } if(key.startsWith("reset-stats")) { resetAllStats(); continue; } if(key.startsWith("ops")) { listOperations(map, key); continue; } if(key.startsWith("invoke") || key.startsWith("op")) { int index=key.indexOf('='); if(index != -1) { try { handleOperation(map, key.substring(index + 1)); } catch(Throwable throwable) { log.error(Util.getMessage("OperationInvocationFailure"), key.substring(index + 1), throwable); } } continue; } if(key.startsWith("threads")) { ThreadMXBean bean=ManagementFactory.getThreadMXBean(); boolean cpu_supported=bean.isThreadCpuTimeSupported(); boolean contention_supported=bean.isThreadContentionMonitoringSupported(); int max_name=0; long[] ids=bean.getAllThreadIds(); List<ThreadEntry> entries=new ArrayList<>(ids.length); for(long id : ids) { ThreadInfo info=bean.getThreadInfo(id); if(info == null) continue; String thread_name=info.getThreadName(); max_name=Math.max(max_name, thread_name.length()); Thread.State state=info.getThreadState(); long blocked=info.getBlockedCount(); long blocked_time=contention_supported? info.getBlockedTime() : -1; long waited=info.getWaitedCount(); long waited_time=contention_supported? info.getWaitedTime() : -1; double cpu_time=cpu_supported? bean.getThreadCpuTime(id) : -1; if(cpu_time > 0) cpu_time/=1_000_000; double user_time=cpu_supported? bean.getThreadUserTime(id) : -1; if(user_time > 0) user_time/=1_000_000; ThreadEntry entry=new ThreadEntry(state, thread_name, blocked, waited, blocked_time, waited_time, cpu_time, user_time); entries.add(entry); } int index=key.indexOf('='); if(index >= 0) { Comparator<ThreadEntry> comp=Comparator.comparing(e -> e.thread_name); String val=key.substring(index+1); if(val.startsWith("state")) comp=Comparator.comparing(e -> e.state); else if(val.startsWith("cpu")) comp=Comparator.comparing((ThreadEntry e) -> e.cpu_time).reversed(); else if(val.startsWith("user")) comp=Comparator.comparing((ThreadEntry e) -> e.user_time).reversed(); else if(val.startsWith("block")) comp=Comparator.comparing((ThreadEntry e) -> e.blocks).reversed(); else if(val.startsWith("btime")) comp=Comparator.comparing((ThreadEntry e) -> e.block_time).reversed(); else if(val.startsWith("wait")) comp=Comparator.comparing((ThreadEntry e) -> e.waits).reversed(); else if(val.startsWith("wtime")) comp=Comparator.comparing((ThreadEntry e) -> e.wait_time).reversed(); entries.sort(comp); } // see if we need to limit the displayed data index=key.indexOf('=', index+1); int limit=0; if(index >= 0) { String val=key.substring(index+1); limit=Integer.parseInt(val); } max_name=Math.min(max_name, 50)+1; String title="\n[%s] \t%-" + max_name+"s: %10s %10s %6s %9s %10s %10s\n"; String line="[%s]\t%-"+max_name+"s: %,8.0f %,8.0f %,10d %,9.0f %,10d %,10.0f\n"; StringBuilder sb=new StringBuilder(String.format(title, "state", "thread-name", "cpu (ms)", "user (ms)", "block", "btime (ms)", "wait", "wtime (ms)")); Stream<ThreadEntry> stream=entries.stream(); if(limit > 0) stream=stream.limit(limit); stream.forEach(e -> sb.append(e.print(line))); map.put(key, sb.toString()); continue; } if(key.equals("enable-cpu")) { map.put(key, enable(1, true)); continue; } if(key.startsWith("enable-cont")) { map.put(key, enable(2, true)); continue; } if(key.equals("disable-cpu")) { map.put(key, enable(1, false)); continue; } if(key.startsWith("disable-cont")) { map.put(key, enable(2, false)); } // everything else could be an attribute query (without prefix "jmx=") or an operation (without "op=") String protocol; int index=key.indexOf('.'); if(index == -1) protocol=key; else protocol=key.substring(0, index); Protocol prot=ch.getProtocolStack().findProtocol(protocol); if(prot != null) { String tmp=key.substring(index+1); int left=tmp.indexOf('['), right=left != -1? tmp.indexOf(']', left) : -1; if(left != -1 && right != -1) { // it is most likely an operation try { return handleProbe("op=" + key); } catch(Throwable throwable) { log.error(Util.getMessage("OperationInvocationFailure"), key.substring(index + 1), throwable); } } else // try JMX return handleProbe("jmx=" + key); } } return map; } public String[] supportedKeys() { return new String[]{"reset-stats", "jmx", "op=<operation>[<args>]", "ops", "threads[=<filter>[=<limit>]]", "enable-cpu", "enable-contention", "disable-cpu", "disable-contention"}; } protected static String enable(int type, boolean flag) { ThreadMXBean bean=ManagementFactory.getThreadMXBean(); boolean supported=false; if(type == 1) { // cpu supported=bean.isThreadCpuTimeSupported(); if(supported) bean.setThreadCpuTimeEnabled(flag); } else if(type == 2) { supported=bean.isThreadContentionMonitoringSupported(); if(supported) bean.setThreadContentionMonitoringEnabled(flag); } String tmp=type == 1? "CPU" : "contention"; return String.format("%s monitoring supported: %b, %s monitoring enabled: %b", tmp, supported, tmp, supported && flag); } protected JChannel resetAllStats() { List<Protocol> prots=ch.getProtocolStack().getProtocols(); prots.forEach(Protocol::resetStatistics); return ch; } /** * Dumps the attributes and their values of _all_ protocols in a stack * @return A map of protocol names as keys and maps (of attribute names and values) as values */ protected Map<String,Map<String,Object>> dumpAttrsAllProtocols() { return ch.dumpStats(); } /** * Dumps attributes and their values of a given protocol. * @param protocol_name The name of the protocol * @param attrs A list of attributes that need to be returned. If null, all attributes of the given protocol will * be returned * @return A map of protocol names as keys and maps (of attribute names and values) as values */ protected Map<String,Map<String,Object>> dumpAttrsSelectedProtocol(String protocol_name, List<String> attrs) { return ch.dumpStats(protocol_name, attrs); } protected void handleJmx(Map<String,String> map, String input) { int index=input.indexOf('='); if(index == -1) { Map<String,Map<String,Object>> tmp_stats=dumpAttrsAllProtocols(); convert(tmp_stats, map); // inserts into map return; } String protocol_name=input.substring(index +1); index=protocol_name.indexOf('.'); if(index == -1) { Map<String,Map<String,Object>> tmp_stats=dumpAttrsSelectedProtocol(protocol_name, null); convert(tmp_stats, map); return; } String rest=protocol_name; protocol_name=protocol_name.substring(0, index); String attrs=rest.substring(index +1); // e.g. "num_sent,msgs,num_received_msgs" List<String> list=Util.parseStringList(attrs, ","); // check if there are any attribute-sets in the list for(Iterator<String> it=list.iterator(); it.hasNext();) { String tmp=it.next(); index=tmp.indexOf('='); if(index > -1) { // an attribute write it.remove(); String attrname=tmp.substring(0, index); String attrvalue=tmp.substring(index+1); handleAttrWrite(protocol_name, attrname, attrvalue); } } if(!list.isEmpty()) { Map<String,Map<String,Object>> tmp_stats=dumpAttrsSelectedProtocol(protocol_name, list); convert(tmp_stats, map); } } protected void listOperations(Map<String, String> map, String key) { if(!key.contains("=")) { map.put("ops", listAllOperations()); return; } String p=key.substring(key.indexOf("=")+1).trim(); try { Class<? extends Protocol> cl=Util.loadProtocolClass(p, getClass()); StringBuilder sb=new StringBuilder(); listAllOperations(sb, cl); map.put("ops", sb.toString()); } catch(Exception e) { log.warn("%s: protocol %s not found", ch.getAddress(), p); } } protected String listAllOperations() { StringBuilder sb=new StringBuilder(); for(Protocol p: ch.getProtocolStack().getProtocols()) { listAllOperations(sb, p.getClass()); } return sb.toString(); } protected static void listAllOperations(StringBuilder sb, Class<? extends Protocol> cl) { sb.append(cl.getSimpleName()).append(":\n"); Method[] methods=Util.getAllDeclaredMethodsWithAnnotations(cl, ManagedOperation.class); for(Method m: methods) sb.append(" ").append(methodToString(m)).append("\n"); } protected static String methodToString(Method m) { StringBuilder sb=new StringBuilder(m.getName()); sb.append('('); StringJoiner sj = new StringJoiner(","); for (Class<?> parameterType : m.getParameterTypes()) { sj.add(parameterType.getTypeName()); } sb.append(sj); sb.append(')'); return sb.toString(); } /** * Invokes an operation and puts the return value into map * @param map * @param operation Protocol.OperationName[args], e.g. STABLE.foo[arg1 arg2 arg3] */ protected void handleOperation(Map<String, String> map, String operation) throws Exception { int index=operation.indexOf('.'); if(index == -1) throw new IllegalArgumentException("operation " + operation + " is missing the protocol name"); String prot_name=operation.substring(0, index); Protocol prot=null; try { Class<? extends Protocol> cl=Util.loadProtocolClass(prot_name, this.getClass()); prot=ch.getProtocolStack().findProtocol(cl); } catch(Exception e) { } if(prot == null) prot=ch.getProtocolStack().findProtocol(prot_name); if(prot == null) { log.error("protocol %s not found", prot_name); return; // less drastic than throwing an exception... } int args_index=operation.indexOf('['); String method_name; if(args_index != -1) method_name=operation.substring(index +1, args_index).trim(); else method_name=operation.substring(index+1).trim(); String[] args=null; if(args_index != -1) { int end_index=operation.indexOf(']'); if(end_index == -1) throw new IllegalArgumentException("] not found"); List<String> str_args=Util.parseCommaDelimitedStrings(operation.substring(args_index + 1, end_index)); Object[] strings=str_args.toArray(); args=new String[strings.length]; for(int i=0; i < strings.length; i++) args[i]=(String)strings[i]; } Method method=findMethod(prot, method_name, args); if(method == null) throw new IllegalArgumentException(String.format("method %s not found in %s", method_name, prot.getName())); MethodCall call=new MethodCall(method); Object[] converted_args=null; if(args != null) { converted_args=new Object[args.length]; Class<?>[] types=method.getParameterTypes(); for(int i=0; i < args.length; i++) converted_args[i]=Util.convert(args[i], types[i]); } Object retval=call.invoke(prot, converted_args); if(retval != null) map.put(prot.getName() + "." + method_name, retval.toString()); } protected Method findMethod(Protocol prot, String method_name, String[] args) throws Exception { Object target=prot; Method method=Util.findMethod(target.getClass(), method_name, args); if(method == null) { if(prot instanceof AdditionalJmxObjects) { for(Object obj: ((AdditionalJmxObjects)prot).getJmxObjects()) { method=Util.findMethod(obj.getClass(), method_name, args); if(method != null) { target=obj; break; } } } if(method == null) { log.warn(Util.getMessage("MethodNotFound"), ch.getAddress(), target.getClass().getSimpleName(), method_name); return null; } } return method; } protected void handleAttrWrite(String protocol_name, String attr_name, String attr_value) { Object target=ch.getProtocolStack().findProtocol(protocol_name); Field field=target != null? Util.getField(target.getClass(), attr_name) : null; if(field == null && target instanceof AdditionalJmxObjects) { Object[] objs=((AdditionalJmxObjects)target).getJmxObjects(); if(objs != null && objs.length > 0) { for(Object o: objs) { field=o != null? Util.getField(o.getClass(), attr_name) : null; if(field != null) { target=o; break; } } } } if(field != null) { Object value=Util.convert(attr_value, field.getType()); if(value != null) { if(target instanceof Protocol) ((Protocol)target).setValue(attr_name, value); else Util.setField(field, target, value); } } else { // try to find a setter for X, e.g. x(type-of-x) or setX(type-of-x) ResourceDMBean.Accessor setter=ResourceDMBean.findSetter(target, attr_name); if(setter == null && target instanceof AdditionalJmxObjects) { Object[] objs=((AdditionalJmxObjects)target).getJmxObjects(); if(objs != null && objs.length > 0) { for(Object o: objs) { setter=o != null? ResourceDMBean.findSetter(o, attr_name) : null; if(setter!= null) break; } } } if(setter != null) { try { Class<?> type=setter instanceof ResourceDMBean.FieldAccessor? ((ResourceDMBean.FieldAccessor)setter).getField().getType() : setter instanceof ResourceDMBean.MethodAccessor? ((ResourceDMBean.MethodAccessor)setter).getMethod().getParameterTypes()[0] : null; Object converted_value=Util.convert(attr_value, type); setter.invoke(converted_value); } catch(Exception e) { log.error("unable to invoke %s() on %s: %s", setter, protocol_name, e); } } else { log.warn(Util.getMessage("FieldNotFound"), attr_name, protocol_name); setter=new ResourceDMBean.NoopAccessor(); } } } protected static void convert(Map<String,Map<String,Object>> in, Map<String,String> out) { if(in != null) in.entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> out.put(e.getKey(), e.getValue().toString())); } protected static class ThreadEntry { protected final Thread.State state; protected final String thread_name; protected final long blocks, waits; protected final double block_time, wait_time; protected final double cpu_time, user_time; public ThreadEntry(Thread.State state, String thread_name, long blocks, long waits, double block_time, double wait_time, double cpu_time, double user_time) { this.state=state; this.thread_name=thread_name; this.blocks=blocks; this.waits=waits; this.block_time=block_time; this.wait_time=wait_time; this.cpu_time=cpu_time; this.user_time=user_time; } public String toString() { return String.format("[%s] %s: blocks=%d (%.2f ms) waits=%d (%.2f ms) sys=%.2f ms user=%.2f ms\n", state, thread_name, blocks, block_time, waits, wait_time, cpu_time, user_time); } protected String print(String format) { return String.format(format, state, thread_name, cpu_time, user_time, blocks, block_time, waits, wait_time); } } }
// $Id: ProtocolTester.java,v 1.7 2006/01/28 10:51:19 belaban Exp $ package org.jgroups.debug; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.stack.Configurator; import org.jgroups.stack.Protocol; import org.jgroups.stack.ProtocolStack; import org.jgroups.util.Util; /** * Generic class to test one or more protocol layers directly. Sets up a protocol stack consisting of * the top layer (which is essentially given by the user and is the test harness), the specified protocol(s) and * a bottom layer (which is automatically added), which sends all received messages immediately back up the * stack (swapping sender and receiver address of the message). * * @author Bela Ban * @author March 23 2001 */ public class ProtocolTester { Protocol harness=null, top, bottom; String props=null; Configurator config=null; protected final Log log=LogFactory.getLog(this.getClass()); public ProtocolTester(String prot_spec, Protocol harness) throws Exception { if(prot_spec == null || harness == null) throw new Exception("ProtocolTester(): prot_spec or harness is null"); props=prot_spec; this.harness=harness; props="LOOPBACK:" + props; // add a loopback layer at the bottom of the stack config=new Configurator(); ProtocolStack stack=new ProtocolStack(); top=config.setupProtocolStack(props, stack); harness.setDownProtocol(top); top.setUpProtocol(harness); bottom=getBottomProtocol(top); config.startProtocolStack(bottom); // has to be set after StartProtocolStack, otherwise the up and down handler threads in the harness // will be started as well (we don't want that) ! // top.setUpProtocol(harness); } public String getProtocolSpec() { return props; } public void start() throws Exception { Protocol p; if(harness != null) { p=harness; while(p != null) { p.start(); p=p.getDownProtocol(); } config.startProtocolStack(harness); } else if(top != null) { p=top; while(p != null) { p.start(); p=p.getDownProtocol(); } config.startProtocolStack(top); } } public void stop() { Protocol p; if(harness != null) { p=harness; while(p != null) { p.stop(); p=p.getDownProtocol(); } config.stopProtocolStack(harness); } else if(top != null) { p=top; while(p != null) { p.stop(); p=p.getDownProtocol(); } config.stopProtocolStack(top); } } private final Protocol getBottomProtocol(Protocol top) { Protocol tmp; if(top == null) return null; tmp=top; while(tmp.getDownProtocol() != null) tmp=tmp.getDownProtocol(); return tmp; } public static void main(String[] args) { String props; ProtocolTester t; Harness h; if(args.length < 1 || args.length > 2) { System.out.println("ProtocolTester <protocol stack spec> [-trace]"); return; } props=args[0]; try { h=new Harness(); t=new ProtocolTester(props, h); System.out.println("protocol specification is " + t.getProtocolSpec()); h.down(new Event(Event.BECOME_SERVER)); for(int i=0; i < 5; i++) { System.out.println("Sending msg h.down(new Event(Event.MSG, new Message(null, null, "Hello world } Util.sleep(500); t.stop(); } catch(Exception ex) { System.err.println(ex); } } private static class Harness extends Protocol { public String getName() { return "Harness"; } public void up(Event evt) { System.out.println("Harness.up(): " + evt); } } }
package org.jgroups.protocols.pbcast; import org.apache.commons.logging.Log; import org.jgroups.*; import org.jgroups.stack.Protocol; import org.jgroups.util.*; import org.jgroups.util.Queue; import java.io.*; import java.util.*; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Group membership protocol. Handles joins/leaves/crashes (suspicions) and emits new views * accordingly. Use VIEW_ENFORCER on top of this layer to make sure new members don't receive * any messages until they are members * @author Bela Ban * @version $Id: GMS.java,v 1.101 2007/04/26 14:32:52 belaban Exp $ */ public class GMS extends Protocol { private GmsImpl impl=null; Address local_addr=null; final Membership members=new Membership(); // real membership private final Membership tmp_members=new Membership(); // base for computing next view /** Members joined but for which no view has been received yet */ private final Vector<Address> joining=new Vector<Address>(7); /** Members excluded from group, but for which no view has been received yet */ private final Vector<Address> leaving=new Vector<Address>(7); View view=null; ViewId view_id=null; private long ltime=0; long join_timeout=5000; long join_retry_timeout=2000; long leave_timeout=5000; long merge_timeout=10000; // time to wait for all MERGE_RSPS private final Object impl_mutex=new Object(); // synchronizes event entry into impl private final Hashtable<String,GmsImpl> impls=new Hashtable<String,GmsImpl>(3); private boolean shun=false; boolean merge_leader=false; // can I initiate a merge ? private boolean print_local_addr=true; boolean disable_initial_coord=false; // can the member become a coord on startup or not ? /** Setting this to false disables concurrent startups. This is only used by unit testing code * for testing merging. To everybody else: don't change it to false ! */ boolean handle_concurrent_startup=true; private boolean view_bundling=true; private long max_bundling_time=50; // 50ms max to wait for other JOIN, LEAVE or SUSPECT requests static final String CLIENT="Client"; static final String COORD="Coordinator"; static final String PART="Participant"; TimeScheduler timer=null; /** Max number of old members to keep in history */ protected int num_prev_mbrs=50; /** Keeps track of old members (up to num_prev_mbrs) */ BoundedList prev_members=null; int num_views=0; /** Stores the last 20 views */ BoundedList prev_views=new BoundedList(20); /** Class to process JOIN, LEAVE and MERGE requests */ private final ViewHandler view_handler=new ViewHandler(); /** To collect VIEW_ACKs from all members */ final AckCollector ack_collector=new AckCollector(); /** Time in ms to wait for all VIEW acks (0 == wait forever) */ long view_ack_collection_timeout=2000; /** How long should a Resumer wait until resuming the ViewHandler */ long resume_task_timeout=20000; boolean flushProtocolInStack=false; public static final String name="GMS"; public GMS() { initState(); } public String getName() { return name; } public String getView() {return view_id != null? view_id.toString() : "null";} public int getNumberOfViews() {return num_views;} public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";} public String getMembers() {return members != null? members.toString() : "[]";} public int getNumMembers() {return members != null? members.size() : 0;} public long getJoinTimeout() {return join_timeout;} public void setJoinTimeout(long t) {join_timeout=t;} public long getJoinRetryTimeout() {return join_retry_timeout;} public void setJoinRetryTimeout(long t) {join_retry_timeout=t;} public boolean isShun() {return shun;} public void setShun(boolean s) {shun=s;} public String printPreviousMembers() { StringBuilder sb=new StringBuilder(); if(prev_members != null) { for(Enumeration en=prev_members.elements(); en.hasMoreElements();) { sb.append(en.nextElement()).append("\n"); } } return sb.toString(); } public int viewHandlerSize() {return view_handler.size();} public boolean isViewHandlerSuspended() {return view_handler.suspended();} public String dumpViewHandlerQueue() { return view_handler.dumpQueue(); } public String dumpViewHandlerHistory() { return view_handler.dumpHistory(); } public void suspendViewHandler() { view_handler.suspend(null); } public void resumeViewHandler() { view_handler.resumeForce(); } Log getLog() {return log;} ViewHandler getViewHandler() {return view_handler;} public String printPreviousViews() { StringBuilder sb=new StringBuilder(); for(Enumeration en=prev_views.elements(); en.hasMoreElements();) { sb.append(en.nextElement()).append("\n"); } return sb.toString(); } public boolean isCoordinator() { Address coord=determineCoordinator(); return coord != null && local_addr != null && local_addr.equals(coord); } public void resetStats() { super.resetStats(); num_views=0; prev_views.removeAll(); } public Vector<Integer> requiredDownServices() { Vector<Integer> retval=new Vector<Integer>(3); retval.addElement(new Integer(Event.GET_DIGEST)); retval.addElement(new Integer(Event.SET_DIGEST)); retval.addElement(new Integer(Event.FIND_INITIAL_MBRS)); return retval; } public void setImpl(GmsImpl new_impl) { synchronized(impl_mutex) { if(impl == new_impl) // superfluous return; impl=new_impl; if(log.isDebugEnabled()) { String msg=(local_addr != null? local_addr.toString()+" " : "") + "changed role to " + new_impl.getClass().getName(); log.debug(msg); } } } public GmsImpl getImpl() { return impl; } public void init() throws Exception { prev_members=new BoundedList(num_prev_mbrs); timer=stack != null? stack.timer : null; if(timer == null) throw new Exception("GMS.init(): timer is null"); if(impl != null) impl.init(); } public void start() throws Exception { if(impl != null) impl.start(); } public void stop() { view_handler.stop(true); if(impl != null) impl.stop(); if(prev_members != null) prev_members.removeAll(); } public void becomeCoordinator() { CoordGmsImpl tmp=(CoordGmsImpl)impls.get(COORD); if(tmp == null) { tmp=new CoordGmsImpl(this); impls.put(COORD, tmp); } try { tmp.init(); } catch(Exception e) { log.error("exception switching to coordinator role", e); } setImpl(tmp); } public void becomeParticipant() { ParticipantGmsImpl tmp=(ParticipantGmsImpl)impls.get(PART); if(tmp == null) { tmp=new ParticipantGmsImpl(this); impls.put(PART, tmp); } try { tmp.init(); } catch(Exception e) { log.error("exception switching to participant", e); } setImpl(tmp); } public void becomeClient() { ClientGmsImpl tmp=(ClientGmsImpl)impls.get(CLIENT); if(tmp == null) { tmp=new ClientGmsImpl(this); impls.put(CLIENT, tmp); } try { tmp.init(); } catch(Exception e) { log.error("exception switching to client role", e); } setImpl(tmp); } boolean haveCoordinatorRole() { return impl != null && impl instanceof CoordGmsImpl; } /** * Computes the next view. Returns a copy that has <code>old_mbrs</code> and * <code>suspected_mbrs</code> removed and <code>new_mbrs</code> added. */ public View getNextView(Collection new_mbrs, Collection old_mbrs, Collection suspected_mbrs) { Vector<Address> mbrs; long vid; View v; Membership tmp_mbrs; Address tmp_mbr; synchronized(members) { if(view_id == null) { log.error("view_id is null"); return null; // this should *never* happen ! } vid=Math.max(view_id.getId(), ltime) + 1; ltime=vid; tmp_mbrs=tmp_members.copy(); // always operate on the temporary membership tmp_mbrs.remove(suspected_mbrs); tmp_mbrs.remove(old_mbrs); tmp_mbrs.add(new_mbrs); mbrs=tmp_mbrs.getMembers(); v=new View(local_addr, vid, mbrs); // Update membership (see DESIGN for explanation): tmp_members.set(mbrs); // Update joining list (see DESIGN for explanation) if(new_mbrs != null) { for(Iterator it=new_mbrs.iterator(); it.hasNext();) { tmp_mbr=(Address)it.next(); if(!joining.contains(tmp_mbr)) joining.addElement(tmp_mbr); } } // Update leaving list (see DESIGN for explanations) if(old_mbrs != null) { for(Iterator it=old_mbrs.iterator(); it.hasNext();) { Address addr=(Address)it.next(); if(!leaving.contains(addr)) leaving.add(addr); } } if(suspected_mbrs != null) { for(Iterator it=suspected_mbrs.iterator(); it.hasNext();) { Address addr=(Address)it.next(); if(!leaving.contains(addr)) leaving.add(addr); } } return v; } } /** Compute a new view, given the current view, the new members and the suspected/left members. Then simply mcast the view to all members. This is different to the VS GMS protocol, in which we run a FLUSH protocol which tries to achive consensus on the set of messages mcast in the current view before proceeding to install the next view. The members for the new view are computed as follows: <pre> existing leaving suspected joining 1. new_view y n n y 2. tmp_view y y n y (view_dest) </pre> <ol> <li> The new view to be installed includes the existing members plus the joining ones and excludes the leaving and suspected members. <li> A temporary view is sent down the stack as an <em>event</em>. This allows the bottom layer (e.g. UDP or TCP) to determine the members to which to send a multicast message. Compared to the new view, leaving members are <em>included</em> since they have are waiting for a view in which they are not members any longer before they leave. So, if we did not set a temporary view, joining members would not receive the view (signalling that they have been joined successfully). The temporary view is essentially the current view plus the joining members (old members are still part of the current view). </ol> */ public void castViewChange(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) { View new_view; // next view: current mbrs + new_mbrs - old_mbrs - suspected_mbrs new_view=getNextView(new_mbrs, old_mbrs, suspected_mbrs); castViewChange(new_view, null); } public void castViewChange(View new_view, Digest digest) { castViewChangeWithDest(new_view, digest, null); } /** * Broadcasts the new view and digest, and waits for acks from all members in the list given as argument. * If the list is null, we take the members who are part of new_view * @param new_view * @param digest * @param members */ public void castViewChangeWithDest(View new_view, Digest digest, java.util.List members) { Message view_change_msg; GmsHeader hdr; long start, stop; ViewId vid=new_view.getVid(); int size=-1; if(members == null || members.isEmpty()) members=new_view.getMembers(); if(log.isTraceEnabled()) log.trace("mcasting view {" + new_view + "} (" + new_view.size() + " mbrs)\n"); start=System.currentTimeMillis(); view_change_msg=new Message(); // bcast to all members hdr=new GmsHeader(GmsHeader.VIEW, new_view); hdr.my_digest=digest; view_change_msg.putHeader(name, hdr); ack_collector.reset(vid, members); size=ack_collector.size(); // Send down a local TMP_VIEW event. This is needed by certain layers (e.g. NAKACK) to compute correct digest // in case client's next request (e.g. getState()) reaches us *before* our own view change multicast. // Check NAKACK's TMP_VIEW handling for details down_prot.up(new Event(Event.TMP_VIEW, new_view)); down_prot.down(new Event(Event.TMP_VIEW, new_view)); down_prot.down(new Event(Event.MSG, view_change_msg)); try { ack_collector.waitForAllAcks(view_ack_collection_timeout); stop=System.currentTimeMillis(); if(trace) log.trace("received all ACKs (" + size + ") for " + vid + " in " + (stop-start) + "ms"); } catch(TimeoutException e) { log.warn("failed to collect all ACKs (" + size + ") for view " + new_view + " after " + view_ack_collection_timeout + "ms, missing ACKs from " + ack_collector.printMissing() + " (received=" + ack_collector.printReceived() + "), local_addr=" + local_addr); } } /** * Sets the new view and sends a VIEW_CHANGE event up and down the stack. If the view is a MergeView (subclass * of View), then digest will be non-null and has to be set before installing the view. */ public void installView(View new_view, Digest digest) { if(digest != null) mergeDigest(digest); installView(new_view); } /** * Sets the new view and sends a VIEW_CHANGE event up and down the stack. */ public void installView(View new_view) { Address coord; int rc; ViewId vid=new_view.getVid(); Vector mbrs=new_view.getMembers(); if(log.isDebugEnabled()) log.debug("[local_addr=" + local_addr + "] view is " + new_view); if(stats) { num_views++; prev_views.add(new_view); } ack_collector.handleView(new_view); // Discards view with id lower than our own. Will be installed without check if first view if(view_id != null) { rc=vid.compareTo(view_id); if(rc <= 0) { if(log.isTraceEnabled() && rc < 0) // only scream if view is smaller, silently discard same views log.trace("[" + local_addr + "] received view < current view;" + " discarding it (current vid: " + view_id + ", new vid: " + vid + ')'); return; } } ltime=Math.max(vid.getId(), ltime); // compute Lamport logical time /* Check for self-inclusion: if I'm not part of the new membership, I just discard it. This ensures that messages sent in view V1 are only received by members of V1 */ if(checkSelfInclusion(mbrs) == false) { // only shun if this member was previously part of the group. avoids problem where multiple // members (e.g. X,Y,Z) join {A,B} concurrently, X is joined first, and Y and Z get view // {A,B,X}, which would cause Y and Z to be shunned as they are not part of the membership // bela Nov 20 2003 if(shun && local_addr != null && prev_members.contains(local_addr)) { if(warn) log.warn("I (" + local_addr + ") am not a member of view " + new_view + ", shunning myself and leaving the group (prev_members are " + prev_members + ", current view is " + view + ")"); if(impl != null) impl.handleExit(); up_prot.up(new Event(Event.EXIT)); } else { if(warn) log.warn("I (" + local_addr + ") am not a member of view " + new_view + "; discarding view"); } return; } synchronized(members) { // serialize access to views // assign new_view to view_id if(new_view instanceof MergeView) view=new View(new_view.getVid(), new_view.getMembers()); else view=new_view; view_id=vid.copy(); // Set the membership. Take into account joining members if(mbrs != null && !mbrs.isEmpty()) { members.set(mbrs); tmp_members.set(members); joining.removeAll(mbrs); // remove all members in mbrs from joining // remove all elements from 'leaving' that are not in 'mbrs' leaving.retainAll(mbrs); tmp_members.add(joining); // add members that haven't yet shown up in the membership tmp_members.remove(leaving); // remove members that haven't yet been removed from the membership // add to prev_members for(Iterator it=mbrs.iterator(); it.hasNext();) { Address addr=(Address)it.next(); if(!prev_members.contains(addr)) prev_members.add(addr); } } // Send VIEW_CHANGE event up and down the stack: Event view_event=new Event(Event.VIEW_CHANGE, new_view.clone()); up_prot.up(view_event); down_prot.down(view_event); // needed e.g. by failure detector or UDP coord=determineCoordinator(); // if(coord != null && coord.equals(local_addr) && !(coord.equals(vid.getCoordAddress()))) { // changed on suggestion by yaronr and Nicolas Piedeloupe if(coord != null && coord.equals(local_addr) && !haveCoordinatorRole()) { becomeCoordinator(); } else { if(haveCoordinatorRole() && !local_addr.equals(coord)) becomeParticipant(); } } } protected Address determineCoordinator() { synchronized(members) { return members != null && members.size() > 0? (Address)members.elementAt(0) : null; } } /** Checks whether the potential_new_coord would be the new coordinator (2nd in line) */ protected boolean wouldBeNewCoordinator(Address potential_new_coord) { Address new_coord; if(potential_new_coord == null) return false; synchronized(members) { if(members.size() < 2) return false; new_coord=(Address)members.elementAt(1); // member at 2nd place return new_coord != null && new_coord.equals(potential_new_coord); } } /** Returns true if local_addr is member of mbrs, else false */ protected boolean checkSelfInclusion(Vector mbrs) { Object mbr; if(mbrs == null) return false; for(int i=0; i < mbrs.size(); i++) { mbr=mbrs.elementAt(i); if(mbr != null && local_addr.equals(mbr)) return true; } return false; } public View makeView(Vector<Address> mbrs) { Address coord=null; long id=0; if(view_id != null) { coord=view_id.getCoordAddress(); id=view_id.getId(); } return new View(coord, id, mbrs); } public View makeView(Vector<Address> mbrs, ViewId vid) { Address coord=null; long id=0; if(vid != null) { coord=vid.getCoordAddress(); id=vid.getId(); } return new View(coord, id, mbrs); } /** Send down a SET_DIGEST event */ public void setDigest(Digest d) { down_prot.down(new Event(Event.SET_DIGEST, d)); } /** Send down a MERGE_DIGEST event */ public void mergeDigest(Digest d) { down_prot.down(new Event(Event.MERGE_DIGEST, d)); } /** Sends down a GET_DIGEST event and waits for the GET_DIGEST_OK response, or timeout, whichever occurs first */ public Digest getDigest() { return (Digest)down_prot.down(Event.GET_DIGEST_EVT); } boolean startFlush(View new_view){ return (Boolean) up_prot.up(new Event(Event.SUSPEND, new_view)); } void stopFlush(View view) { //since we did not call startFlush on //empty view do not call RESUME either if(view != null && view.getMembers().isEmpty()) return; if (log.isDebugEnabled()) { log.debug("sending RESUME event"); } up_prot.up(new Event(Event.RESUME)); } public Object up(Event evt) { switch(evt.getType()) { case Event.MSG: Message msg=(Message)evt.getArg(); GmsHeader hdr=(GmsHeader)msg.getHeader(name); if(hdr == null) break; switch(hdr.type) { case GmsHeader.JOIN_REQ: view_handler.add(new Request(Request.JOIN, hdr.mbr, false, null)); break; case GmsHeader.JOIN_RSP: impl.handleJoinResponse(hdr.join_rsp); break; case GmsHeader.LEAVE_REQ: if(log.isDebugEnabled()) log.debug("received LEAVE_REQ for " + hdr.mbr + " from " + msg.getSrc()); if(hdr.mbr == null) { if(log.isErrorEnabled()) log.error("LEAVE_REQ's mbr field is null"); return null; } view_handler.add(new Request(Request.LEAVE, hdr.mbr, false, null)); break; case GmsHeader.LEAVE_RSP: impl.handleLeaveResponse(); break; case GmsHeader.VIEW: View new_view=hdr.view; if(new_view == null) { if(log.isErrorEnabled()) log.error("[VIEW]: view == null"); return null; } Address coord=msg.getSrc(); if(!new_view.containsMember(coord)) { sendViewAck(coord); // we need to send the ack first, otherwise the connection is removed impl.handleViewChange(new_view, hdr.my_digest); } else { impl.handleViewChange(new_view, hdr.my_digest); sendViewAck(coord); // send VIEW_ACK to sender of view } break; case GmsHeader.VIEW_ACK: Object sender=msg.getSrc(); ack_collector.ack(sender); return null; // don't pass further up case GmsHeader.MERGE_REQ: impl.handleMergeRequest(msg.getSrc(), hdr.merge_id); break; case GmsHeader.MERGE_RSP: MergeData merge_data=new MergeData(msg.getSrc(), hdr.view, hdr.my_digest); merge_data.merge_rejected=hdr.merge_rejected; impl.handleMergeResponse(merge_data, hdr.merge_id); break; case GmsHeader.INSTALL_MERGE_VIEW: impl.handleMergeView(new MergeData(msg.getSrc(), hdr.view, hdr.my_digest), hdr.merge_id); break; case GmsHeader.CANCEL_MERGE: impl.handleMergeCancelled(hdr.merge_id); break; default: if(log.isErrorEnabled()) log.error("GmsHeader with type=" + hdr.type + " not known"); } return null; // don't pass up case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); if(print_local_addr) { System.out.println("\n "GMS: address is " + local_addr + "\n } break; // pass up case Event.SUSPECT: Address suspected=(Address)evt.getArg(); view_handler.add(new Request(Request.SUSPECT, suspected, true, null)); ack_collector.suspect(suspected); break; // pass up case Event.UNSUSPECT: impl.unsuspect((Address)evt.getArg()); return null; // discard case Event.MERGE: view_handler.add(new Request(Request.MERGE, null, false, (Vector)evt.getArg())); return null; // don't pass up } if(impl.handleUpEvent(evt)) return up_prot.up(evt); return null; } /** This method is overridden to avoid hanging on getDigest(): when a JOIN is received, the coordinator needs to retrieve the digest from the NAKACK layer. It therefore sends down a GET_DIGEST event, to which the NAKACK layer responds with a GET_DIGEST_OK event.<p> However, the GET_DIGEST_OK event will not be processed because the thread handling the JOIN request won't process the GET_DIGEST_OK event until the JOIN event returns. The receiveUpEvent() method is executed by the up-handler thread of the lower protocol and therefore can handle the event. All we do here is unblock the mutex on which JOIN is waiting, allowing JOIN to return with a valid digest. The GET_DIGEST_OK event is then discarded, because it won't be processed twice. */ // public void receiveUpEvent(Event evt) { // switch(evt.getType()) { // case Event.GET_DIGEST_OK: // digest_promise.setResult(evt.getArg()); // return; // don't pass further up // super.receiveUpEvent(evt); public Object down(Event evt) { switch(evt.getType()) { case Event.CONNECT: Object arg=null; down_prot.down(evt); if(local_addr == null) if(log.isFatalEnabled()) log.fatal("[CONNECT] local_addr is null"); try { impl.join(local_addr); } catch(Throwable e) { arg=e; } return arg; // don't pass down: was already passed down case Event.DISCONNECT: impl.leave((Address)evt.getArg()); if(!(impl instanceof CoordGmsImpl)) { initState(); // in case connect() is called again } down_prot.down(evt); // notify the other protocols, but ignore the result return null; case Event.CONFIG : Map config = (Map) evt.getArg(); if((config != null && config.containsKey("flush_supported"))){ flushProtocolInStack = true; } break; } return down_prot.down(evt); } /** Setup the Protocol instance according to the configuration string */ public boolean setProperties(Properties props) { String str; super.setProperties(props); str=props.getProperty("shun"); if(str != null) { shun=Boolean.valueOf(str).booleanValue(); props.remove("shun"); } str=props.getProperty("merge_leader"); if(str != null) { merge_leader=Boolean.valueOf(str).booleanValue(); props.remove("merge_leader"); } str=props.getProperty("print_local_addr"); if(str != null) { print_local_addr=Boolean.valueOf(str).booleanValue(); props.remove("print_local_addr"); } str=props.getProperty("join_timeout"); // time to wait for JOIN if(str != null) { join_timeout=Long.parseLong(str); props.remove("join_timeout"); } str=props.getProperty("join_retry_timeout"); // time to wait between JOINs if(str != null) { join_retry_timeout=Long.parseLong(str); props.remove("join_retry_timeout"); } str=props.getProperty("leave_timeout"); // time to wait until coord responds to LEAVE req. if(str != null) { leave_timeout=Long.parseLong(str); props.remove("leave_timeout"); } str=props.getProperty("merge_timeout"); // time to wait for MERGE_RSPS from subgroup coordinators if(str != null) { merge_timeout=Long.parseLong(str); props.remove("merge_timeout"); } str=props.getProperty("digest_timeout"); // time to wait for GET_DIGEST_OK from PBCAST if(str != null) { log.warn("digest_timeout has been deprecated and its value will be ignored"); props.remove("digest_timeout"); } str=props.getProperty("view_ack_collection_timeout"); if(str != null) { view_ack_collection_timeout=Long.parseLong(str); props.remove("view_ack_collection_timeout"); } str=props.getProperty("resume_task_timeout"); if(str != null) { resume_task_timeout=Long.parseLong(str); props.remove("resume_task_timeout"); } str=props.getProperty("disable_initial_coord"); if(str != null) { disable_initial_coord=Boolean.valueOf(str).booleanValue(); props.remove("disable_initial_coord"); } str=props.getProperty("handle_concurrent_startup"); if(str != null) { handle_concurrent_startup=Boolean.valueOf(str).booleanValue(); props.remove("handle_concurrent_startup"); } str=props.getProperty("num_prev_mbrs"); if(str != null) { num_prev_mbrs=Integer.parseInt(str); props.remove("num_prev_mbrs"); } str=props.getProperty("use_flush"); if(str != null) { log.warn("use_flush has been deprecated and its value will be ignored"); props.remove("use_flush"); } str=props.getProperty("flush_timeout"); if(str != null) { log.warn("flush_timeout has been deprecated and its value will be ignored"); props.remove("flush_timeout"); } str=props.getProperty("view_bundling"); if(str != null) { view_bundling=Boolean.valueOf(str).booleanValue(); props.remove("view_bundling"); } str=props.getProperty("max_bundling_time"); if(str != null) { max_bundling_time=Long.parseLong(str); props.remove("max_bundling_time"); } if(!props.isEmpty()) { log.error("the following properties are not recognized: " + props); return false; } return true; } final void initState() { becomeClient(); view_id=null; view=null; } private void sendViewAck(Address dest) { Message view_ack=new Message(dest, null, null); view_ack.setFlag(Message.OOB); GmsHeader tmphdr=new GmsHeader(GmsHeader.VIEW_ACK); view_ack.putHeader(name, tmphdr); if(trace) log.trace("sending VIEW_ACK to " + dest); down_prot.down(new Event(Event.MSG, view_ack)); } public static class GmsHeader extends Header implements Streamable { public static final byte JOIN_REQ=1; public static final byte JOIN_RSP=2; public static final byte LEAVE_REQ=3; public static final byte LEAVE_RSP=4; public static final byte VIEW=5; public static final byte MERGE_REQ=6; public static final byte MERGE_RSP=7; public static final byte INSTALL_MERGE_VIEW=8; public static final byte CANCEL_MERGE=9; public static final byte VIEW_ACK=10; byte type=0; View view=null; // used when type=VIEW or MERGE_RSP or INSTALL_MERGE_VIEW Address mbr=null; // used when type=JOIN_REQ or LEAVE_REQ JoinRsp join_rsp=null; // used when type=JOIN_RSP Digest my_digest=null; // used when type=MERGE_RSP or INSTALL_MERGE_VIEW ViewId merge_id=null; // used when type=MERGE_REQ or MERGE_RSP or INSTALL_MERGE_VIEW or CANCEL_MERGE boolean merge_rejected=false; // used when type=MERGE_RSP public GmsHeader() { } // used for Externalization public GmsHeader(byte type) { this.type=type; } /** Used for VIEW header */ public GmsHeader(byte type, View view) { this.type=type; this.view=view; } /** Used for JOIN_REQ or LEAVE_REQ header */ public GmsHeader(byte type, Address mbr) { this.type=type; this.mbr=mbr; } /** Used for JOIN_RSP header */ public GmsHeader(byte type, JoinRsp join_rsp) { this.type=type; this.join_rsp=join_rsp; } public byte getType() { return type; } public Address getMemeber() { return mbr; } public String toString() { StringBuilder sb=new StringBuilder("GmsHeader"); sb.append('[' + type2String(type) + ']'); switch(type) { case JOIN_REQ: sb.append(": mbr=" + mbr); break; case JOIN_RSP: sb.append(": join_rsp=" + join_rsp); break; case LEAVE_REQ: sb.append(": mbr=" + mbr); break; case LEAVE_RSP: break; case VIEW: case VIEW_ACK: sb.append(": view=" + view); break; case MERGE_REQ: sb.append(": merge_id=" + merge_id); break; case MERGE_RSP: sb.append(": view=" + view + ", digest=" + my_digest + ", merge_rejected=" + merge_rejected + ", merge_id=" + merge_id); break; case INSTALL_MERGE_VIEW: sb.append(": view=" + view + ", digest=" + my_digest); break; case CANCEL_MERGE: sb.append(", <merge cancelled>, merge_id=" + merge_id); break; } return sb.toString(); } public static String type2String(int type) { switch(type) { case JOIN_REQ: return "JOIN_REQ"; case JOIN_RSP: return "JOIN_RSP"; case LEAVE_REQ: return "LEAVE_REQ"; case LEAVE_RSP: return "LEAVE_RSP"; case VIEW: return "VIEW"; case MERGE_REQ: return "MERGE_REQ"; case MERGE_RSP: return "MERGE_RSP"; case INSTALL_MERGE_VIEW: return "INSTALL_MERGE_VIEW"; case CANCEL_MERGE: return "CANCEL_MERGE"; case VIEW_ACK: return "VIEW_ACK"; default: return "<unknown>"; } } public void writeExternal(ObjectOutput out) throws IOException { out.writeByte(type); out.writeObject(view); out.writeObject(mbr); out.writeObject(join_rsp); out.writeObject(my_digest); out.writeObject(merge_id); out.writeBoolean(merge_rejected); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { type=in.readByte(); view=(View)in.readObject(); mbr=(Address)in.readObject(); join_rsp=(JoinRsp)in.readObject(); my_digest=(Digest)in.readObject(); merge_id=(ViewId)in.readObject(); merge_rejected=in.readBoolean(); } public void writeTo(DataOutputStream out) throws IOException { out.writeByte(type); boolean isMergeView=view != null && view instanceof MergeView; out.writeBoolean(isMergeView); Util.writeStreamable(view, out); Util.writeAddress(mbr, out); Util.writeStreamable(join_rsp, out); Util.writeStreamable(my_digest, out); Util.writeStreamable(merge_id, out); // kludge: we know merge_id is a ViewId out.writeBoolean(merge_rejected); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readByte(); boolean isMergeView=in.readBoolean(); if(isMergeView) view=(View)Util.readStreamable(MergeView.class, in); else view=(View)Util.readStreamable(View.class, in); mbr=Util.readAddress(in); join_rsp=(JoinRsp)Util.readStreamable(JoinRsp.class, in); my_digest=(Digest)Util.readStreamable(Digest.class, in); merge_id=(ViewId)Util.readStreamable(ViewId.class, in); merge_rejected=in.readBoolean(); } public long size() { long retval=Global.BYTE_SIZE *2; // type + merge_rejected retval+=Global.BYTE_SIZE; // presence view retval+=Global.BYTE_SIZE; // MergeView or View if(view != null) retval+=view.serializedSize(); retval+=Util.size(mbr); retval+=Global.BYTE_SIZE; // presence of join_rsp if(join_rsp != null) retval+=join_rsp.serializedSize(); retval+=Global.BYTE_SIZE; // presence for my_digest if(my_digest != null) retval+=my_digest.serializedSize(); retval+=Global.BYTE_SIZE; // presence for merge_id if(merge_id != null) retval+=merge_id.serializedSize(); return retval; } } public static class Request { static final int JOIN = 1; static final int LEAVE = 2; static final int SUSPECT = 3; static final int MERGE = 4; static final int VIEW = 5; int type=-1; Address mbr; boolean suspected; Vector coordinators; View view; Digest digest; List target_members; Request(int type) { this.type=type; } Request(int type, Address mbr, boolean suspected, Vector coordinators) { this.type=type; this.mbr=mbr; this.suspected=suspected; this.coordinators=coordinators; } public int getType() { return type; } public String toString() { switch(type) { case JOIN: return "JOIN(" + mbr + ")"; case LEAVE: return "LEAVE(" + mbr + ", " + suspected + ")"; case SUSPECT: return "SUSPECT(" + mbr + ")"; case MERGE: return "MERGE(" + coordinators + ")"; case VIEW: return "VIEW (" + view.getVid() + ")"; } return "<invalid (type=" + type + ")"; } /** * Specifies whether this request can be processed with other request simultaneously */ public boolean canBeProcessedTogether(Request other) { if(other == null) return false; int other_type=other.getType(); return (type == JOIN || type == LEAVE || type == SUSPECT) && (other_type == JOIN || other_type == LEAVE || other_type == SUSPECT); } } /** * Class which processes JOIN, LEAVE and MERGE requests. Requests are queued and processed in FIFO order * @author Bela Ban * @version $Id: GMS.java,v 1.101 2007/04/26 14:32:52 belaban Exp $ */ class ViewHandler implements Runnable { volatile Thread thread; Queue q=new Queue(); // Queue<Request> boolean suspended=false; final static long INTERVAL=5000; private static final long MAX_COMPLETION_TIME=10000; /** Maintains a list of the last 20 requests */ private final BoundedList history=new BoundedList(20); /** Map<Object,Future>. Keeps track of Resumer tasks which have not fired yet */ private final Map<Object, Future> resume_tasks=new HashMap<Object,Future>(); private Object merge_id=null; void add(Request req) { add(req, false, false); } synchronized void add(Request req, boolean at_head, boolean unsuspend) { if(suspended && !unsuspend) { log.warn("queue is suspended; request " + req + " is discarded"); return; } start(unsuspend); try { if(at_head) q.addAtHead(req); else q.add(req); history.add(new Date() + ": " + req.toString()); } catch(QueueClosedException e) { if(trace) log.trace("queue is closed; request " + req + " is discarded"); } } void waitUntilCompleted(long timeout) { waitUntilCompleted(timeout, false); } synchronized void waitUntilCompleted(long timeout, boolean resume) { if(thread != null) { try { thread.join(timeout); } catch(InterruptedException e) { Thread.currentThread().interrupt(); // set interrupt flag again } } if(resume) resumeForce(); } /** * Waits until the current request has been processes, then clears the queue and discards new * requests from now on */ public synchronized void suspend(Object merge_id) { if(suspended) return; suspended=true; this.merge_id=merge_id; q.clear(); waitUntilCompleted(MAX_COMPLETION_TIME); q.close(true); if(trace) log.trace("suspended ViewHandler"); Resumer resumer=new Resumer(merge_id, resume_tasks, this); Future future=timer.schedule(resumer, resume_task_timeout, TimeUnit.MILLISECONDS); Future old_future=resume_tasks.put(merge_id, future); if(old_future != null) old_future.cancel(true); } public synchronized void resume(Object merge_id) { if(!suspended) return; boolean same_merge_id=this.merge_id != null && merge_id != null && this.merge_id.equals(merge_id); same_merge_id=same_merge_id || (this.merge_id == null && merge_id == null); if(!same_merge_id) { if(warn) log.warn("resume(" +merge_id+ ") does not match " + this.merge_id + ", ignoring resume()"); return; } synchronized(resume_tasks) { Future future=resume_tasks.get(merge_id); if(future != null) { future.cancel(false); resume_tasks.remove(merge_id); } } resumeForce(); } public synchronized void resumeForce() { if(q.closed()) q.reset(); suspended=false; if(trace) log.trace("resumed ViewHandler"); } public void run() { long start, stop, wait_time; List<Request> requests=new LinkedList<Request>(); while(Thread.currentThread().equals(thread)) { requests.clear(); try { boolean keepGoing=false; start=System.currentTimeMillis(); do { Request firstRequest=(Request)q.remove(INTERVAL); // throws a TimeoutException if it runs into timeout requests.add(firstRequest); if(q.size() > 0) { Request nextReq=(Request)q.peek(); keepGoing=view_bundling && firstRequest.canBeProcessedTogether(nextReq); } else { stop=System.currentTimeMillis(); wait_time=max_bundling_time - (stop-start); if(wait_time > 0) Util.sleep(wait_time); keepGoing=q.size() > 0; } } while(keepGoing); process(requests); } catch(QueueClosedException e) { break; } catch(TimeoutException e) { break; } catch(Throwable catchall) { Util.sleep(50); } } } public int size() {return q.size();} public boolean suspended() {return suspended;} public String dumpQueue() { StringBuilder sb=new StringBuilder(); List v=q.values(); for(Iterator it=v.iterator(); it.hasNext();) { sb.append(it.next() + "\n"); } return sb.toString(); } public String dumpHistory() { StringBuilder sb=new StringBuilder(); for(Enumeration en=history.elements(); en.hasMoreElements();) { sb.append(en.nextElement() + "\n"); } return sb.toString(); } private void process(List requests) { if(requests.isEmpty()) return; if(trace) log.trace("processing " + requests); Request firstReq=(Request)requests.get(0); switch(firstReq.type) { case Request.JOIN: case Request.LEAVE: case Request.SUSPECT: Collection<Address> newMembers=new LinkedHashSet<Address>(requests.size()); Collection<Address> suspectedMembers=new LinkedHashSet<Address>(requests.size()); Collection<Address> oldMembers=new LinkedHashSet<Address>(requests.size()); for(Iterator i=requests.iterator(); i.hasNext();) { Request req=(Request)i.next(); switch(req.type) { case Request.JOIN: newMembers.add(req.mbr); break; case Request.LEAVE: if(req.suspected) suspectedMembers.add(req.mbr); else oldMembers.add(req.mbr); break; case Request.SUSPECT: suspectedMembers.add(req.mbr); break; } } impl.handleMembershipChange(newMembers, oldMembers, suspectedMembers); break; case Request.MERGE: if(requests.size() > 1) log.error("more than one MERGE request to process, ignoring the others"); impl.merge(firstReq.coordinators); break; case Request.VIEW: if(requests.size() > 1) log.error("more than one VIEW request to process, ignoring the others"); try { if (flushProtocolInStack){ boolean successfulFlush = startFlush(firstReq.view); if (successfulFlush){ log.info("Successful GMS flush by coordinator at " + getLocalAddress()); } else { log.warn("GMS flush by coordinator at " + getLocalAddress() + " failed"); } } castViewChangeWithDest(firstReq.view, firstReq.digest, firstReq.target_members); } finally { if(flushProtocolInStack) stopFlush(firstReq.view); } break; default: log.error("request " + firstReq.type + " is unknown; discarded"); } } synchronized void start(boolean unsuspend) { if(q.closed()) q.reset(); if(unsuspend) { suspended=false; Future future; synchronized(resume_tasks) { future=resume_tasks.remove(merge_id); } if(future != null) future.cancel(true); } merge_id=null; if(thread == null || !thread.isAlive()) { thread=new Thread(Util.getGlobalThreadGroup(), this, "ViewHandler"); thread.setDaemon(false); // thread cannot terminate if we have tasks left, e.g. when we as coord leave thread.start(); if(trace) log.trace("ViewHandler started"); } } synchronized void stop(boolean flush) { q.close(flush); synchronized(resume_tasks) { for(Future future: resume_tasks.values()) { future.cancel(true); } resume_tasks.clear(); } merge_id=null; // resumeForce(); } } /** * Resumer is a second line of defense: when the ViewHandler is suspended, it will be resumed when the current * merge is cancelled, or when the merge completes. However, in a case where this never happens (this * shouldn't be the case !), the Resumer will nevertheless resume the ViewHandler. * We chose this strategy because ViewHandler is critical: if it is suspended indefinitely, we would * not be able to process new JOIN requests ! So, this is for peace of mind, although it most likely * will never be used... */ static class Resumer implements Runnable { final Object token; final Map<Object,Future> tasks; final ViewHandler handler; public Resumer(final Object token, final Map<Object,Future> t, final ViewHandler handler) { this.token=token; this.tasks=t; this.handler=handler; } public void run() { boolean execute=true; synchronized(tasks) { Future future=tasks.get(token); if(future != null) { future.cancel(false); execute=true; } else { execute=false; } tasks.remove(token); } if(execute) { handler.resume(token); } } } }
// $Id: GMS.java,v 1.52 2006/01/13 21:27:09 belaban Exp $ package org.jgroups.protocols.pbcast; import org.jgroups.*; import org.jgroups.stack.Protocol; import org.jgroups.util.*; import org.jgroups.util.Queue; import org.apache.commons.logging.Log; import java.io.*; import java.util.*; import java.util.List; /** * Group membership protocol. Handles joins/leaves/crashes (suspicions) and emits new views * accordingly. Use VIEW_ENFORCER on top of this layer to make sure new members don't receive * any messages until they are members. */ public class GMS extends Protocol { private GmsImpl impl=null; Address local_addr=null; final Membership members=new Membership(); // real membership private final Membership tmp_members=new Membership(); // base for computing next view /** Members joined but for which no view has been received yet */ private final Vector joining=new Vector(7); /** Members excluded from group, but for which no view has been received yet */ private final Vector leaving=new Vector(7); View view=null; ViewId view_id=null; private long ltime=0; long join_timeout=5000; long join_retry_timeout=2000; long leave_timeout=5000; private long digest_timeout=0; // time to wait for a digest (from PBCAST). should be fast long merge_timeout=10000; // time to wait for all MERGE_RSPS private final Object impl_mutex=new Object(); // synchronizes event entry into impl private final Object digest_mutex=new Object(); private final Promise digest_promise=new Promise(); // holds result of GET_DIGEST event private final Hashtable impls=new Hashtable(3); private boolean shun=true; boolean merge_leader=false; // can I initiate a merge ? private boolean print_local_addr=true; boolean disable_initial_coord=false; // can the member become a coord on startup or not ? /** Setting this to false disables concurrent startups. This is only used by unit testing code * for testing merging. To everybody else: don't change it to false ! */ boolean handle_concurrent_startup=true; static final String CLIENT="Client"; static final String COORD="Coordinator"; static final String PART="Participant"; TimeScheduler timer=null; /** Max number of old members to keep in history */ protected int num_prev_mbrs=50; /** Keeps track of old members (up to num_prev_mbrs) */ BoundedList prev_members=null; int num_views=0; /** Stores the last 20 views */ BoundedList prev_views=new BoundedList(20); /** Class to process JOIN, LEAVE and MERGE requests */ public final ViewHandler view_handler=new ViewHandler(); /** To collect VIEW_ACKs from all members */ final AckCollector ack_collector=new AckCollector(); /** Time in ms to wait for all VIEW acks (0 == wait forever) */ long view_ack_collection_timeout=20000; /** How long should a Resumer wait until resuming the ViewHandler */ long resume_task_timeout=20000; public static final String name="GMS"; public GMS() { initState(); } public String getName() { return name; } public String getView() {return view_id != null? view_id.toString() : "null";} public int getNumberOfViews() {return num_views;} public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";} public String getMembers() {return members != null? members.toString() : "[]";} public int getNumMembers() {return members != null? members.size() : 0;} public long getJoinTimeout() {return join_timeout;} public void setJoinTimeout(long t) {join_timeout=t;} public long getJoinRetryTimeout() {return join_retry_timeout;} public void setJoinRetryTimeout(long t) {join_retry_timeout=t;} public boolean isShun() {return shun;} public void setShun(boolean s) {shun=s;} public String printPreviousMembers() { StringBuffer sb=new StringBuffer(); if(prev_members != null) { for(Enumeration en=prev_members.elements(); en.hasMoreElements();) { sb.append(en.nextElement()).append("\n"); } } return sb.toString(); } public int viewHandlerSize() {return view_handler.size();} public boolean isViewHandlerSuspended() {return view_handler.suspended();} public String dumpViewHandlerQueue() { return view_handler.dumpQueue(); } public String dumpViewHandlerHistory() { return view_handler.dumpHistory(); } public void suspendViewHandler() { view_handler.suspend(null); } public void resumeViewHandler() { view_handler.resumeForce(); } Log getLog() {return log;} public String printPreviousViews() { StringBuffer sb=new StringBuffer(); for(Enumeration en=prev_views.elements(); en.hasMoreElements();) { sb.append(en.nextElement()).append("\n"); } return sb.toString(); } public boolean isCoordinator() { Address coord=determineCoordinator(); return coord != null && local_addr != null && local_addr.equals(coord); } public void resetStats() { super.resetStats(); num_views=0; prev_views.removeAll(); } public Vector requiredDownServices() { Vector retval=new Vector(3); retval.addElement(new Integer(Event.GET_DIGEST)); retval.addElement(new Integer(Event.SET_DIGEST)); retval.addElement(new Integer(Event.FIND_INITIAL_MBRS)); return retval; } public void setImpl(GmsImpl new_impl) { synchronized(impl_mutex) { if(impl == new_impl) // superfluous return; impl=new_impl; if(log.isDebugEnabled()) { String msg=(local_addr != null? local_addr.toString()+" " : "") + "changed role to " + new_impl.getClass().getName(); log.debug(msg); } } } public GmsImpl getImpl() { return impl; } public void init() throws Exception { prev_members=new BoundedList(num_prev_mbrs); timer=stack != null? stack.timer : null; if(timer == null) throw new Exception("GMS.init(): timer is null"); if(impl != null) impl.init(); } public void start() throws Exception { if(impl != null) impl.start(); } public void stop() { view_handler.stop(true); if(impl != null) impl.stop(); if(prev_members != null) prev_members.removeAll(); } public void becomeCoordinator() { CoordGmsImpl tmp=(CoordGmsImpl)impls.get(COORD); if(tmp == null) { tmp=new CoordGmsImpl(this); impls.put(COORD, tmp); } try { tmp.init(); } catch(Exception e) { log.error("exception switching to coordinator role", e); } setImpl(tmp); } public void becomeParticipant() { ParticipantGmsImpl tmp=(ParticipantGmsImpl)impls.get(PART); if(tmp == null) { tmp=new ParticipantGmsImpl(this); impls.put(PART, tmp); } try { tmp.init(); } catch(Exception e) { log.error("exception switching to participant", e); } setImpl(tmp); } public void becomeClient() { ClientGmsImpl tmp=(ClientGmsImpl)impls.get(CLIENT); if(tmp == null) { tmp=new ClientGmsImpl(this); impls.put(CLIENT, tmp); } try { tmp.init(); } catch(Exception e) { log.error("exception switching to client role", e); } setImpl(tmp); } boolean haveCoordinatorRole() { return impl != null && impl instanceof CoordGmsImpl; } /** * Computes the next view. Returns a copy that has <code>old_mbrs</code> and * <code>suspected_mbrs</code> removed and <code>new_mbrs</code> added. */ public View getNextView(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) { Vector mbrs; long vid; View v; Membership tmp_mbrs; Address tmp_mbr; synchronized(members) { if(view_id == null) { log.error("view_id is null"); return null; // this should *never* happen ! } vid=Math.max(view_id.getId(), ltime) + 1; ltime=vid; tmp_mbrs=tmp_members.copy(); // always operate on the temporary membership tmp_mbrs.remove(suspected_mbrs); tmp_mbrs.remove(old_mbrs); tmp_mbrs.add(new_mbrs); mbrs=tmp_mbrs.getMembers(); v=new View(local_addr, vid, mbrs); // Update membership (see DESIGN for explanation): tmp_members.set(mbrs); // Update joining list (see DESIGN for explanation) if(new_mbrs != null) { for(int i=0; i < new_mbrs.size(); i++) { tmp_mbr=(Address)new_mbrs.elementAt(i); if(!joining.contains(tmp_mbr)) joining.addElement(tmp_mbr); } } // Update leaving list (see DESIGN for explanations) if(old_mbrs != null) { for(Iterator it=old_mbrs.iterator(); it.hasNext();) { Address addr=(Address)it.next(); if(!leaving.contains(addr)) leaving.add(addr); } } if(suspected_mbrs != null) { for(Iterator it=suspected_mbrs.iterator(); it.hasNext();) { Address addr=(Address)it.next(); if(!leaving.contains(addr)) leaving.add(addr); } } if(log.isDebugEnabled()) log.debug("new view is " + v); return v; } } /** Compute a new view, given the current view, the new members and the suspected/left members. Then simply mcast the view to all members. This is different to the VS GMS protocol, in which we run a FLUSH protocol which tries to achive consensus on the set of messages mcast in the current view before proceeding to install the next view. The members for the new view are computed as follows: <pre> existing leaving suspected joining 1. new_view y n n y 2. tmp_view y y n y (view_dest) </pre> <ol> <li> The new view to be installed includes the existing members plus the joining ones and excludes the leaving and suspected members. <li> A temporary view is sent down the stack as an <em>event</em>. This allows the bottom layer (e.g. UDP or TCP) to determine the members to which to send a multicast message. Compared to the new view, leaving members are <em>included</em> since they have are waiting for a view in which they are not members any longer before they leave. So, if we did not set a temporary view, joining members would not receive the view (signalling that they have been joined successfully). The temporary view is essentially the current view plus the joining members (old members are still part of the current view). </ol> @return View The new view */ public void castViewChange(Vector new_mbrs, Vector old_mbrs, Vector suspected_mbrs) { View new_view; // next view: current mbrs + new_mbrs - old_mbrs - suspected_mbrs new_view=getNextView(new_mbrs, old_mbrs, suspected_mbrs); castViewChange(new_view, null); } public void castViewChange(View new_view, Digest digest) { castViewChangeWithDest(new_view, digest, null); } /** * Broadcasts the new view and digest, and waits for acks from all members in the list given as argument. * If the list is null, we take the members who are part of new_view * @param new_view * @param digest * @param members */ public void castViewChangeWithDest(View new_view, Digest digest, java.util.List members) { Message view_change_msg; GmsHeader hdr; long start, stop; ViewId vid=new_view.getVid(); int size=-1; if(members == null || members.size() == 0) members=new_view.getMembers(); if(log.isTraceEnabled()) log.trace("mcasting view {" + new_view + "} (" + new_view.size() + " mbrs)\n"); start=System.currentTimeMillis(); view_change_msg=new Message(); // bcast to all members hdr=new GmsHeader(GmsHeader.VIEW, new_view); hdr.my_digest=digest; view_change_msg.putHeader(name, hdr); ack_collector.reset(vid, members); size=ack_collector.size(); passDown(new Event(Event.MSG, view_change_msg)); try { ack_collector.waitForAllAcks(view_ack_collection_timeout); stop=System.currentTimeMillis(); if(trace) log.trace("received all ACKs (" + size + ") for " + vid + " in " + (stop-start) + "ms"); } catch(TimeoutException e) { log.warn("failed to collect all ACKs (" + size + ") for view " + vid + " after " + view_ack_collection_timeout + "ms, missing ACKs from " + ack_collector.getMissing() + " (received=" + ack_collector.getReceived() + "), local_addr=" + local_addr); } } /** * Sets the new view and sends a VIEW_CHANGE event up and down the stack. If the view is a MergeView (subclass * of View), then digest will be non-null and has to be set before installing the view. */ public void installView(View new_view, Digest digest) { if(digest != null) mergeDigest(digest); installView(new_view); } /** * Sets the new view and sends a VIEW_CHANGE event up and down the stack. */ public void installView(View new_view) { Address coord; int rc; ViewId vid=new_view.getVid(); Vector mbrs=new_view.getMembers(); if(log.isDebugEnabled()) log.debug("[local_addr=" + local_addr + "] view is " + new_view); if(stats) { num_views++; prev_views.add(new_view); } // Discards view with id lower than our own. Will be installed without check if first view if(view_id != null) { rc=vid.compareTo(view_id); if(rc <= 0) { if(log.isTraceEnabled() && rc < 0) // only scream if view is smaller, silently discard same views log.trace("[" + local_addr + "] received view < current view;" + " discarding it (current vid: " + view_id + ", new vid: " + vid + ')'); return; } } ltime=Math.max(vid.getId(), ltime); // compute Lamport logical time /* Check for self-inclusion: if I'm not part of the new membership, I just discard it. This ensures that messages sent in view V1 are only received by members of V1 */ if(checkSelfInclusion(mbrs) == false) { // only shun if this member was previously part of the group. avoids problem where multiple // members (e.g. X,Y,Z) join {A,B} concurrently, X is joined first, and Y and Z get view // {A,B,X}, which would cause Y and Z to be shunned as they are not part of the membership // bela Nov 20 2003 if(shun && local_addr != null && prev_members.contains(local_addr)) { if(warn) log.warn("I (" + local_addr + ") am not a member of view " + new_view + ", shunning myself and leaving the group (prev_members are " + prev_members + ", current view is " + view + ")"); if(impl != null) impl.handleExit(); passUp(new Event(Event.EXIT)); } else { if(warn) log.warn("I (" + local_addr + ") am not a member of view " + new_view + "; discarding view"); } return; } synchronized(members) { // serialize access to views // assign new_view to view_id if(new_view instanceof MergeView) view=new View(new_view.getVid(), new_view.getMembers()); else view=new_view; view_id=vid.copy(); // Set the membership. Take into account joining members if(mbrs != null && mbrs.size() > 0) { members.set(mbrs); tmp_members.set(members); joining.removeAll(mbrs); // remove all members in mbrs from joining // remove all elements from 'leaving' that are not in 'mbrs' leaving.retainAll(mbrs); tmp_members.add(joining); // add members that haven't yet shown up in the membership tmp_members.remove(leaving); // remove members that haven't yet been removed from the membership // add to prev_members for(Iterator it=mbrs.iterator(); it.hasNext();) { Address addr=(Address)it.next(); if(!prev_members.contains(addr)) prev_members.add(addr); } } // Send VIEW_CHANGE event up and down the stack: Event view_event=new Event(Event.VIEW_CHANGE, new_view.clone()); passDown(view_event); // needed e.g. by failure detector or UDP passUp(view_event); coord=determineCoordinator(); // if(coord != null && coord.equals(local_addr) && !(coord.equals(vid.getCoordAddress()))) { // changed on suggestion by yaronr and Nicolas Piedeloupe if(coord != null && coord.equals(local_addr) && !haveCoordinatorRole()) { becomeCoordinator(); } else { if(haveCoordinatorRole() && !local_addr.equals(coord)) becomeParticipant(); } } } protected Address determineCoordinator() { synchronized(members) { return members != null && members.size() > 0? (Address)members.elementAt(0) : null; } } /** Checks whether the potential_new_coord would be the new coordinator (2nd in line) */ protected boolean wouldBeNewCoordinator(Address potential_new_coord) { Address new_coord; if(potential_new_coord == null) return false; synchronized(members) { if(members.size() < 2) return false; new_coord=(Address)members.elementAt(1); // member at 2nd place return new_coord != null && new_coord.equals(potential_new_coord); } } /** Returns true if local_addr is member of mbrs, else false */ protected boolean checkSelfInclusion(Vector mbrs) { Object mbr; if(mbrs == null) return false; for(int i=0; i < mbrs.size(); i++) { mbr=mbrs.elementAt(i); if(mbr != null && local_addr.equals(mbr)) return true; } return false; } public View makeView(Vector mbrs) { Address coord=null; long id=0; if(view_id != null) { coord=view_id.getCoordAddress(); id=view_id.getId(); } return new View(coord, id, mbrs); } public View makeView(Vector mbrs, ViewId vid) { Address coord=null; long id=0; if(vid != null) { coord=vid.getCoordAddress(); id=vid.getId(); } return new View(coord, id, mbrs); } /** Send down a SET_DIGEST event */ public void setDigest(Digest d) { passDown(new Event(Event.SET_DIGEST, d)); } /** Send down a MERGE_DIGEST event */ public void mergeDigest(Digest d) { passDown(new Event(Event.MERGE_DIGEST, d)); } /** Sends down a GET_DIGEST event and waits for the GET_DIGEST_OK response, or timeout, whichever occurs first */ public Digest getDigest() { Digest ret=null; synchronized(digest_mutex) { digest_promise.reset(); passDown(Event.GET_DIGEST_EVT); try { ret=(Digest)digest_promise.getResultWithTimeout(digest_timeout); } catch(TimeoutException e) { if(log.isErrorEnabled()) log.error("digest could not be fetched from below"); } return ret; } } public void up(Event evt) { Object obj; Message msg; GmsHeader hdr; MergeData merge_data; switch(evt.getType()) { case Event.MSG: msg=(Message)evt.getArg(); obj=msg.getHeader(name); if(obj == null || !(obj instanceof GmsHeader)) break; hdr=(GmsHeader)msg.removeHeader(name); switch(hdr.type) { case GmsHeader.JOIN_REQ: view_handler.add(new Request(Request.JOIN, hdr.mbr, false, null)); break; case GmsHeader.JOIN_RSP: impl.handleJoinResponse(hdr.join_rsp); break; case GmsHeader.LEAVE_REQ: if(log.isDebugEnabled()) log.debug("received LEAVE_REQ for " + hdr.mbr + " from " + msg.getSrc()); if(hdr.mbr == null) { if(log.isErrorEnabled()) log.error("LEAVE_REQ's mbr field is null"); return; } view_handler.add(new Request(Request.LEAVE, hdr.mbr, false, null)); break; case GmsHeader.LEAVE_RSP: impl.handleLeaveResponse(); break; case GmsHeader.VIEW: if(hdr.view == null) { if(log.isErrorEnabled()) log.error("[VIEW]: view == null"); return; } // send VIEW_ACK to sender of view Address coord=msg.getSrc(); Message view_ack=new Message(coord, null, null); GmsHeader tmphdr=new GmsHeader(GmsHeader.VIEW_ACK, hdr.view); view_ack.putHeader(name, tmphdr); passDown(new Event(Event.MSG, view_ack)); impl.handleViewChange(hdr.view, hdr.my_digest); break; case GmsHeader.VIEW_ACK: Object sender=msg.getSrc(); ack_collector.ack(sender); return; // don't pass further up case GmsHeader.MERGE_REQ: impl.handleMergeRequest(msg.getSrc(), hdr.merge_id); break; case GmsHeader.MERGE_RSP: merge_data=new MergeData(msg.getSrc(), hdr.view, hdr.my_digest); merge_data.merge_rejected=hdr.merge_rejected; impl.handleMergeResponse(merge_data, hdr.merge_id); break; case GmsHeader.INSTALL_MERGE_VIEW: impl.handleMergeView(new MergeData(msg.getSrc(), hdr.view, hdr.my_digest), hdr.merge_id); break; case GmsHeader.CANCEL_MERGE: impl.handleMergeCancelled(hdr.merge_id); break; default: if(log.isErrorEnabled()) log.error("GmsHeader with type=" + hdr.type + " not known"); } return; // don't pass up case Event.CONNECT_OK: // sent by someone else, but WE are responsible for sending this ! case Event.DISCONNECT_OK: // dito (e.g. sent by TP layer). Don't send up the stack return; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); if(print_local_addr) { System.out.println("\n "GMS: address is " + local_addr + "\n } break; // pass up case Event.SUSPECT: Address suspected=(Address)evt.getArg(); view_handler.add(new Request(Request.LEAVE, suspected, true, null)); ack_collector.suspect(suspected); break; // pass up case Event.UNSUSPECT: impl.unsuspect((Address)evt.getArg()); return; // discard case Event.MERGE: view_handler.add(new Request(Request.MERGE, null, false, (Vector)evt.getArg())); return; // don't pass up } if(impl.handleUpEvent(evt)) passUp(evt); } /** This method is overridden to avoid hanging on getDigest(): when a JOIN is received, the coordinator needs to retrieve the digest from the NAKACK layer. It therefore sends down a GET_DIGEST event, to which the NAKACK layer responds with a GET_DIGEST_OK event.<p> However, the GET_DIGEST_OK event will not be processed because the thread handling the JOIN request won't process the GET_DIGEST_OK event until the JOIN event returns. The receiveUpEvent() method is executed by the up-handler thread of the lower protocol and therefore can handle the event. All we do here is unblock the mutex on which JOIN is waiting, allowing JOIN to return with a valid digest. The GET_DIGEST_OK event is then discarded, because it won't be processed twice. */ public void receiveUpEvent(Event evt) { switch(evt.getType()) { case Event.GET_DIGEST_OK: digest_promise.setResult(evt.getArg()); return; // don't pass further up } super.receiveUpEvent(evt); } public void down(Event evt) { switch(evt.getType()) { case Event.CONNECT: Object arg=null; passDown(evt); if(local_addr == null) if(log.isFatalEnabled()) log.fatal("[CONNECT] local_addr is null"); try { impl.join(local_addr); } catch(SecurityException e) { arg=e; } passUp(new Event(Event.CONNECT_OK, arg)); return; // don't pass down: was already passed down case Event.DISCONNECT: impl.leave((Address)evt.getArg()); passUp(new Event(Event.DISCONNECT_OK)); initState(); // in case connect() is called again break; // pass down } if(impl.handleDownEvent(evt)) passDown(evt); } /** Setup the Protocol instance according to the configuration string */ public boolean setProperties(Properties props) { String str; super.setProperties(props); str=props.getProperty("shun"); if(str != null) { shun=Boolean.valueOf(str).booleanValue(); props.remove("shun"); } str=props.getProperty("merge_leader"); if(str != null) { merge_leader=Boolean.valueOf(str).booleanValue(); props.remove("merge_leader"); } str=props.getProperty("print_local_addr"); if(str != null) { print_local_addr=Boolean.valueOf(str).booleanValue(); props.remove("print_local_addr"); } str=props.getProperty("join_timeout"); // time to wait for JOIN if(str != null) { join_timeout=Long.parseLong(str); props.remove("join_timeout"); } str=props.getProperty("join_retry_timeout"); // time to wait between JOINs if(str != null) { join_retry_timeout=Long.parseLong(str); props.remove("join_retry_timeout"); } str=props.getProperty("leave_timeout"); // time to wait until coord responds to LEAVE req. if(str != null) { leave_timeout=Long.parseLong(str); props.remove("leave_timeout"); } str=props.getProperty("merge_timeout"); // time to wait for MERGE_RSPS from subgroup coordinators if(str != null) { merge_timeout=Long.parseLong(str); props.remove("merge_timeout"); } str=props.getProperty("digest_timeout"); // time to wait for GET_DIGEST_OK from PBCAST if(str != null) { digest_timeout=Long.parseLong(str); props.remove("digest_timeout"); } str=props.getProperty("view_ack_collection_timeout"); if(str != null) { view_ack_collection_timeout=Long.parseLong(str); props.remove("view_ack_collection_timeout"); } str=props.getProperty("resume_task_timeout"); if(str != null) { resume_task_timeout=Long.parseLong(str); props.remove("resume_task_timeout"); } str=props.getProperty("disable_initial_coord"); if(str != null) { disable_initial_coord=Boolean.valueOf(str).booleanValue(); props.remove("disable_initial_coord"); } str=props.getProperty("handle_concurrent_startup"); if(str != null) { handle_concurrent_startup=Boolean.valueOf(str).booleanValue(); props.remove("handle_concurrent_startup"); } str=props.getProperty("num_prev_mbrs"); if(str != null) { num_prev_mbrs=Integer.parseInt(str); props.remove("num_prev_mbrs"); } if(props.size() > 0) { log.error("GMS.setProperties(): the following properties are not recognized: " + props); return false; } return true; } void initState() { becomeClient(); view_id=null; view=null; } public static class GmsHeader extends Header implements Streamable { public static final byte JOIN_REQ=1; public static final byte JOIN_RSP=2; public static final byte LEAVE_REQ=3; public static final byte LEAVE_RSP=4; public static final byte VIEW=5; public static final byte MERGE_REQ=6; public static final byte MERGE_RSP=7; public static final byte INSTALL_MERGE_VIEW=8; public static final byte CANCEL_MERGE=9; public static final byte VIEW_ACK=10; byte type=0; View view=null; // used when type=VIEW or MERGE_RSP or INSTALL_MERGE_VIEW Address mbr=null; // used when type=JOIN_REQ or LEAVE_REQ JoinRsp join_rsp=null; // used when type=JOIN_RSP Digest my_digest=null; // used when type=MERGE_RSP or INSTALL_MERGE_VIEW ViewId merge_id=null; // used when type=MERGE_REQ or MERGE_RSP or INSTALL_MERGE_VIEW or CANCEL_MERGE boolean merge_rejected=false; // used when type=MERGE_RSP public GmsHeader() { } // used for Externalization public GmsHeader(byte type) { this.type=type; } /** Used for VIEW header */ public GmsHeader(byte type, View view) { this.type=type; this.view=view; } /** Used for JOIN_REQ or LEAVE_REQ header */ public GmsHeader(byte type, Address mbr) { this.type=type; this.mbr=mbr; } /** Used for JOIN_RSP header */ public GmsHeader(byte type, JoinRsp join_rsp) { this.type=type; this.join_rsp=join_rsp; } public byte getType() { return type; } public Address getMemeber() { return mbr; } public String toString() { StringBuffer sb=new StringBuffer("GmsHeader"); sb.append('[' + type2String(type) + ']'); switch(type) { case JOIN_REQ: sb.append(": mbr=" + mbr); break; case JOIN_RSP: sb.append(": join_rsp=" + join_rsp); break; case LEAVE_REQ: sb.append(": mbr=" + mbr); break; case LEAVE_RSP: break; case VIEW: case VIEW_ACK: sb.append(": view=" + view); break; case MERGE_REQ: sb.append(": merge_id=" + merge_id); break; case MERGE_RSP: sb.append(": view=" + view + ", digest=" + my_digest + ", merge_rejected=" + merge_rejected + ", merge_id=" + merge_id); break; case INSTALL_MERGE_VIEW: sb.append(": view=" + view + ", digest=" + my_digest); break; case CANCEL_MERGE: sb.append(", <merge cancelled>, merge_id=" + merge_id); break; } return sb.toString(); } public static String type2String(int type) { switch(type) { case JOIN_REQ: return "JOIN_REQ"; case JOIN_RSP: return "JOIN_RSP"; case LEAVE_REQ: return "LEAVE_REQ"; case LEAVE_RSP: return "LEAVE_RSP"; case VIEW: return "VIEW"; case MERGE_REQ: return "MERGE_REQ"; case MERGE_RSP: return "MERGE_RSP"; case INSTALL_MERGE_VIEW: return "INSTALL_MERGE_VIEW"; case CANCEL_MERGE: return "CANCEL_MERGE"; case VIEW_ACK: return "VIEW_ACK"; default: return "<unknown>"; } } public void writeExternal(ObjectOutput out) throws IOException { out.writeByte(type); out.writeObject(view); out.writeObject(mbr); out.writeObject(join_rsp); out.writeObject(my_digest); out.writeObject(merge_id); out.writeBoolean(merge_rejected); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { type=in.readByte(); view=(View)in.readObject(); mbr=(Address)in.readObject(); join_rsp=(JoinRsp)in.readObject(); my_digest=(Digest)in.readObject(); merge_id=(ViewId)in.readObject(); merge_rejected=in.readBoolean(); } public void writeTo(DataOutputStream out) throws IOException { out.writeByte(type); boolean isMergeView=view != null && view instanceof MergeView; out.writeBoolean(isMergeView); Util.writeStreamable(view, out); Util.writeAddress(mbr, out); Util.writeStreamable(join_rsp, out); Util.writeStreamable(my_digest, out); Util.writeStreamable(merge_id, out); // kludge: we know merge_id is a ViewId out.writeBoolean(merge_rejected); } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { type=in.readByte(); boolean isMergeView=in.readBoolean(); if(isMergeView) view=(View)Util.readStreamable(MergeView.class, in); else view=(View)Util.readStreamable(View.class, in); mbr=Util.readAddress(in); join_rsp=(JoinRsp)Util.readStreamable(JoinRsp.class, in); my_digest=(Digest)Util.readStreamable(Digest.class, in); merge_id=(ViewId)Util.readStreamable(ViewId.class, in); merge_rejected=in.readBoolean(); } public long size() { long retval=Global.BYTE_SIZE *2; // type + merge_rejected retval+=Global.BYTE_SIZE; // presence view retval+=Global.BYTE_SIZE; // MergeView or View if(view != null) retval+=view.serializedSize(); retval+=Util.size(mbr); retval+=Global.BYTE_SIZE; // presence of join_rsp if(join_rsp != null) retval+=join_rsp.serializedSize(); retval+=Global.BYTE_SIZE; // presence for my_digest if(my_digest != null) retval+=my_digest.serializedSize(); retval+=Global.BYTE_SIZE; // presence for merge_id if(merge_id != null) retval+=merge_id.serializedSize(); return retval; } } public static class Request { static final int JOIN = 1; static final int LEAVE = 2; static final int SUSPECT = 3; static final int MERGE = 4; static final int VIEW = 5; int type=-1; Address mbr=null; boolean suspected; Vector coordinators=null; View view=null; Digest digest=null; List target_members=null; Request(int type) { this.type=type; } Request(int type, Address mbr, boolean suspected, Vector coordinators) { this.type=type; this.mbr=mbr; this.suspected=suspected; this.coordinators=coordinators; } public String toString() { switch(type) { case JOIN: return "JOIN(" + mbr + ")"; case LEAVE: return "LEAVE(" + mbr + ", " + suspected + ")"; case SUSPECT: return "SUSPECT(" + mbr + ")"; case MERGE: return "MERGE(" + coordinators + ")"; case VIEW: return "VIEW (" + view.getVid() + ")"; } return "<invalid (type=" + type + ")"; } } /** * Class which processes JOIN, LEAVE and MERGE requests. Requests are queued and processed in FIFO order * @author Bela Ban * @version $Id: GMS.java,v 1.52 2006/01/13 21:27:09 belaban Exp $ */ class ViewHandler implements Runnable { Thread t; Queue q=new Queue(); // Queue<Request> boolean suspended=false; final static long INTERVAL=5000; private static final long MAX_COMPLETION_TIME=10000; /** Maintains a list of the last 20 requests */ private final BoundedList history=new BoundedList(20); /** Map<Object,TimeScheduler.CancellableTask>. Keeps track of Resumer tasks which have not fired yet */ private final Map resume_tasks=new HashMap(); private Object merge_id=null; void add(Request req) { add(req, false, false); } synchronized void add(Request req, boolean at_head, boolean unsuspend) { if(suspended && !unsuspend) { log.warn("queue is suspended; request " + req + " is discarded"); return; } start(unsuspend); try { if(at_head) q.addAtHead(req); else q.add(req); history.add(new Date() + ": " + req.toString()); } catch(QueueClosedException e) { if(trace) log.trace("queue is closed; request " + req + " is discarded"); } } synchronized void waitUntilCompleted(long timeout) { if(t != null) { try { t.join(timeout); } catch(InterruptedException e) { } } } /** * Waits until the current request has been processes, then clears the queue and discards new * requests from now on */ public synchronized void suspend(Object merge_id) { if(suspended) return; suspended=true; this.merge_id=merge_id; q.clear(); waitUntilCompleted(MAX_COMPLETION_TIME); q.close(true); if(trace) log.trace("suspended ViewHandler"); Resumer r=new Resumer(resume_task_timeout, merge_id, resume_tasks, this); resume_tasks.put(merge_id, r); timer.add(r); } public synchronized void resume(Object merge_id) { if(!suspended) return; boolean same_merge_id=this.merge_id != null && merge_id != null && this.merge_id.equals(merge_id); same_merge_id=same_merge_id || (this.merge_id == null && merge_id == null); if(!same_merge_id) { if(warn) log.warn("resume(" +merge_id+ ") does not match " + this.merge_id + ", ignoring resume()"); return; } synchronized(resume_tasks) { TimeScheduler.CancellableTask task=(TimeScheduler.CancellableTask)resume_tasks.get(merge_id); if(task != null) { task.cancel(); resume_tasks.remove(merge_id); } } resumeForce(); } public synchronized void resumeForce() { if(q.closed()) q.reset(); suspended=false; if(trace) log.trace("resumed ViewHandler"); } public void run() { Request req; while(!q.closed() && Thread.currentThread().equals(t)) { try { req=(Request)q.remove(INTERVAL); // throws a TimeoutException if it runs into timeout process(req); } catch(QueueClosedException e) { break; } catch(TimeoutException e) { break; } catch(Throwable catchall) { Util.sleep(50); } } } public int size() {return q.size();} public boolean suspended() {return suspended;} public String dumpQueue() { StringBuffer sb=new StringBuffer(); List v=q.values(); for(Iterator it=v.iterator(); it.hasNext();) { sb.append(it.next() + "\n"); } return sb.toString(); } public String dumpHistory() { StringBuffer sb=new StringBuffer(); for(Enumeration en=history.elements(); en.hasMoreElements();) { sb.append(en.nextElement() + "\n"); } return sb.toString(); } private void process(Request req) { if(trace) log.trace("processing " + req); switch(req.type) { case Request.JOIN: impl.handleJoin(req.mbr); break; case Request.LEAVE: if(req.suspected) impl.suspect(req.mbr); else impl.handleLeave(req.mbr, req.suspected); break; case Request.SUSPECT: impl.suspect(req.mbr); break; case Request.MERGE: impl.merge(req.coordinators); break; case Request.VIEW: castViewChangeWithDest(req.view, req.digest, req.target_members); break; default: log.error("Request " + req.type + " is unknown; discarded"); } } synchronized void start(boolean unsuspend) { if(q.closed()) q.reset(); if(unsuspend) { suspended=false; synchronized(resume_tasks) { TimeScheduler.CancellableTask task=(TimeScheduler.CancellableTask)resume_tasks.get(merge_id); if(task != null) { task.cancel(); resume_tasks.remove(merge_id); } } } merge_id=null; if(t == null || !t.isAlive()) { t=new Thread(this, "ViewHandler"); t.setDaemon(true); t.start(); if(trace) log.trace("ViewHandler started"); } } synchronized void stop(boolean flush) { q.close(flush); TimeScheduler.CancellableTask task; synchronized(resume_tasks) { for(Iterator it=resume_tasks.values().iterator(); it.hasNext();) { task=(TimeScheduler.CancellableTask)it.next(); task.cancel(); } resume_tasks.clear(); } merge_id=null; resumeForce(); } } /** * Resumer is a second line of defense: when the ViewHandler is suspended, it will be resumed when the current * merge is cancelled, or when the merge completes. However, in a case where this never happens (this * shouldn't be the case !), the Resumer will nevertheless resume the ViewHandler. * We chose this strategy because ViewHandler is critical: if it is suspended indefinitely, we would * not be able to process new JOIN requests ! So, this is for peace of mind, although it most likely * will never be used... */ static class Resumer implements TimeScheduler.CancellableTask { boolean cancelled=false; long interval; final Object token; final Map tasks; final ViewHandler handler; public Resumer(long interval, final Object token, final Map t, final ViewHandler handler) { this.interval=interval; this.token=token; this.tasks=t; this.handler=handler; } public void cancel() { cancelled=true; } public boolean cancelled() { return cancelled; } public long nextInterval() { return interval; } public void run() { TimeScheduler.CancellableTask t; boolean execute=true; synchronized(tasks) { t=(TimeScheduler.CancellableTask)tasks.get(token); if(t != null) { t.cancel(); execute=true; } else { execute=false; } tasks.remove(token); } if(execute) { handler.resume(token); } } } }
package org.joshy.gfx.node.control; import org.joshy.gfx.SkinManager; import org.joshy.gfx.css.BoxPainter; import org.joshy.gfx.css.CSSSkin; import org.joshy.gfx.css.SizeInfo; import org.joshy.gfx.css.StyleInfo; import org.joshy.gfx.draw.Font; import org.joshy.gfx.draw.GFX; import org.joshy.gfx.node.Bounds; import org.joshy.gfx.node.Insets; import java.util.ArrayList; import java.util.List; public class Label extends Control { private String text = "Label"; private StyleInfo styleInfo; private SizeInfo sizeInfo; private BoxPainter boxPainter; private List<String> lines = new ArrayList<String>(); public Label(String text) { this.text = text; } @Override public void doSkins() { cssSkin = SkinManager.getShared().getCSSSkin(); styleInfo = cssSkin.getStyleInfo(this); setLayoutDirty(); } @Override public void doPrefLayout() { sizeInfo = cssSkin.getSizeInfo(this,styleInfo,text); if(prefWidth != CALCULATED) { setWidth(prefWidth); sizeInfo.width = prefWidth; } else { setWidth(sizeInfo.width); } setHeight(sizeInfo.height); layoutText(); setHeight(lines.size()*Font.DEFAULT.calculateHeight("ASDF")); } @Override public void doLayout() { if(sizeInfo != null) { sizeInfo.width = getWidth(); sizeInfo.height = getHeight(); } boxPainter = cssSkin.createBoxPainter(this,styleInfo,sizeInfo,text,CSSSkin.State.None); } //TODO: all of this code is very very dodgy and must be rewritten private void layoutText() { Insets insets = styleInfo.calcContentInsets(); double maxw = sizeInfo.width - insets.getLeft()-insets.getRight(); if(getWidth() <= 10) return; int start = 0; int end = 0; lines.clear(); String[] words = text.split(" "); String line = ""; for(int i =0; i<words.length; i++) { String word = words[i]; String testLine = line + " " + word; //hard coded newlines if(word.contains("\n")) { String[] splitWord = word.split("\n"); if(splitWord.length > 0) { testLine = line + " " + splitWord[0]; lines.add(testLine); if(splitWord.length>1) { line = splitWord[1]; testLine = splitWord[1]; } else { line = ""; testLine = ""; } } } double w = Font.DEFAULT.calculateWidth(testLine); if(w > maxw) { //if last line if(i == words.length-1) { lines.add(testLine); } else { lines.add(line); line = word; } continue; } //last word if(i == words.length-1) { lines.add(testLine); } line = testLine; } } @Override public void draw(GFX g) { if(!isVisible()) return; if(sizeInfo == null) { doPrefLayout(); } boxPainter.draw(g, styleInfo, sizeInfo, this, ""); g.setPaint(boxPainter.color); double y = Font.DEFAULT.calculateHeight("ASDF"); Insets insets = styleInfo.calcContentInsets(); y+=insets.getTop(); double x = insets.getLeft(); for(String line : lines) { g.drawText(line,Font.DEFAULT,x,y); y+= Font.DEFAULT.calculateHeight(line); } //g.setPaint(FlatColor.RED); //g.drawRect(0,0,getWidth(),getHeight()); } public Label setText(String text) { this.text = text; setLayoutDirty(); setDrawingDirty(); return this; } public String getText() { return this.text; } @Override public Bounds getLayoutBounds() { return new Bounds(getTranslateX(), getTranslateY(), getWidth(), getHeight()); } @Override public double getBaseline() { if(sizeInfo == null) { doPrefLayout(); } return styleInfo.margin.getTop() + styleInfo.borderWidth.getTop() + styleInfo.padding.getTop() + styleInfo.contentBaseline; } }
/* * $Id: WarcExporter.java,v 1.6 2011-05-11 03:31:30 tlipkis Exp $ */ package org.lockss.exporter; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.*; import org.archive.io.*; import org.archive.io.warc.*; import org.archive.util.*; import org.archive.util.anvl.*; import static org.archive.io.warc.WARCConstants.*; import org.lockss.app.*; import org.lockss.util.*; import org.lockss.daemon.*; import org.lockss.plugin.*; /** * Export to an ARC file */ public class WarcExporter extends Exporter { private static Logger log = Logger.getLogger("WarcExporter"); protected CIProperties arcProps = null; AtomicInteger serialNo = new AtomicInteger(0); WARCWriter ww; boolean isResponse; public WarcExporter(LockssDaemon daemon, ArchivalUnit au, boolean isResponse) { super(daemon, au); this.isResponse = isResponse; } protected void start() throws IOException { ww = makeWARCWriter(); } protected void finish() throws IOException { ww.close(); } private WARCWriter makeWARCWriter() { Properties props = new Properties(); props.put("software", getSoftwareVersion()); props.put("ip", getHostIp()); props.put("hostname", getHostName()); props.put("format","WARC File Format 0.17"); props.put("conformsTo", "http://crawler.archive.org/warc/0.17/WARC0.17ISO.doc"); props.put("created", ArchiveUtils.getLog14Date(TimeBase.nowMs())); props.put("description", au.getName()); props.put("robots", "ignore"); props.put("http-header-user-agent", daemon.getUserAgent()); List metadata = new ArrayList<String>(); for (Map.Entry ent : props.entrySet()) { String key = (String)ent.getKey(); metadata.add((String)ent.getKey() + ": " + (String)ent.getValue() + "\r\n"); } return new WARCWriter(serialNo, ListUtil.list(dir), prefix, "" /*settings.getSuffix()*/ , compress, maxSize >= 0 ? maxSize : Long.MAX_VALUE, metadata ); } protected void writeCu(CachedUrl cu) throws IOException { String url = cu.getUrl(); long contentSize = cu.getContentSize(); CIProperties props = cu.getProperties(); ANVLRecord headers = new ANVLRecord(5); headers.addLabelValue(HEADER_KEY_IP, getHostIp()); // XXX Temporary for LuKII; replace with ExporterHelper TypedEntryMap auProps = au.getProperties(); if (auProps.containsKey("article_base")) { // Add field to WARC header String pattern = auProps.getString("article_base"); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(url); if (m.find()) { headers.addLabelValue("LOCKSS-Article-Base", m.group(1)); } } long fetchTime = Long.parseLong(props.getProperty(CachedUrl.PROPERTY_FETCH_TIME)); String timestamp = ArchiveUtils.getLog14Date(fetchTime); InputStream contentIn = cu.getUnfilteredInputStream(); try { if (isResponse) { String hdrString = getHttpResponseString(cu); long size = contentSize + hdrString.length(); InputStream headerIn = new ReaderInputStream(new StringReader(hdrString)); InputStream concat = new SequenceInputStream(headerIn, contentIn); try { ww.writeResponseRecord(xlateFilename(url), timestamp, HTTP_RESPONSE_MIMETYPE, WARCWriter.getRecordID(), headers, concat, size); } finally { IOUtil.safeClose(concat); } } else { String mimeType = HeaderUtil.getMimeTypeFromContentType(cu.getContentType()); ww.writeResourceRecord(xlateFilename(url), timestamp, mimeType, headers, contentIn, contentSize); } } finally { IOUtil.safeClose(contentIn); } } }
/* * $Id: LockssServlet.java,v 1.27 2003-08-06 06:27:10 tlipkis Exp $ */ package org.lockss.servlet; import javax.servlet.http.*; import javax.servlet.*; import java.io.*; import java.util.*; import java.net.*; import java.text.*; // import com.mortbay.servlet.*; // import org.mortbay.util.*; import org.mortbay.html.*; import org.mortbay.tools.*; import org.lockss.app.*; import org.lockss.util.*; import org.lockss.daemon.*; /** Abstract base class for LOCKSS servlets */ // SingleThreadModel causes servlet instances to be assigned to only a // single thread (request) at a time. public abstract class LockssServlet extends HttpServlet implements SingleThreadModel { // Constants static final String PARAM_LOCAL_IP = Configuration.PREFIX + "localIPAddress"; // static final String PARAM_IS_CLUSTER_ADMIN = // Configuration.PREFIX + "clusterAdmin"; static final String PARAM_CONTACT_ADDR = Configuration.PREFIX + "admin.contactEmail"; static final String DEFAULT_CONTACT_ADDR = "contactnotset@notset"; static final String PARAM_PLATFORM_VERSION = Configuration.PREFIX + "platform.version"; static final String PARAM_ADMIN_ADDRESS = Configuration.PREFIX + "admin.IPAddress"; public static final String JAVASCRIPT_RESOURCE = "org/lockss/htdocs/admin.js"; /** Format to display date/time in headers */ public static final DateFormat headerDf = new SimpleDateFormat("MM/dd/yy HH:mm:ss"); static final String BACKGROUND_COLOR = "#FFFFFF"; static final Image IMAGE_LOGO_LARGE = image("lockss-logo-large.gif", 160, 160, 0); static final Image IMAGE_LOGO_SMALL = image("lockss-logo-small.gif", 80, 81, 0); static final Image IMAGE_TM = image("tm.gif", 16, 16, 0); static final Image IMAGE_LOCKSS_RED = image("lockss-type-red.gif", 595, 31, 0); protected static final String footAccessDenied = "Clicking on this link will result in an access denied error, unless your browser is configured to proxy through a LOCKSS cache, or your workstation is allowed access by the publisher."; protected static Logger log = Logger.getLogger("LockssServlet"); protected ServletContext context; private LockssDaemon theDaemon = null; // Request-local storage. Convenient, but requires servlet instances // to be single threaded, and must ensure reset them to avoid carrying // over state between requests. protected HttpServletRequest req; protected HttpServletResponse resp; protected URL reqURL; private String adminDir = null; protected String client; // client param protected String clientAddr; // client addr, even if no param protected String adminAddr; protected String adminHost; protected String localAddr; private Vector footnotes; private int footNumber; ServletDescr _myServletDescr = null; private String myName = null; // Servlet descriptor. static class ServletDescr { public Class cls; public String heading; // display name public String name; // url path component to invoke servlet public int flags = 0; // flags public static int ON_CLIENT = 1; // runs on client (else on admin) public static int PER_CLIENT = 2; // per client (takes client arg) public static int NOT_IN_NAV = 4; // no link in nav table public static int LARGE_LOGO = 8; // use large LOCKSS logo public static int DEBUG_ONLY = 0x10; // debug user only public static int STATUS = ON_CLIENT | PER_CLIENT; // shorthand public ServletDescr(Class cls, String heading, String name, int flags) { this.cls = cls; this.heading = heading; this.name = name; this.flags = flags; } public ServletDescr(Class cls, String heading, int flags) { this(cls, heading, cls.getName().substring(cls.getName().lastIndexOf('.') + 1), flags); } public ServletDescr(Class cls, String heading) { this(cls, heading, 0); } public ServletDescr(String className, String heading) { this(classForName(className), heading); } public ServletDescr(String className, String heading, int flags) { this(classForName(className), heading, flags); } static Class classForName(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { return null; } } boolean isPerClient() { return (flags & PER_CLIENT) != 0; } boolean runsOnClient() { return (flags & ON_CLIENT) != 0; } boolean isInNavTable() { return (flags & NOT_IN_NAV) == 0; } boolean isDebugOnly() { return (flags & DEBUG_ONLY) != 0; } boolean isLargeLogo() { return (flags & LARGE_LOGO) != 0; } } // Descriptors for all servlets. protected static ServletDescr SERVLET_AU_CONFIG = new ServletDescr(AuConfig.class, "Journal Configuration"); protected static ServletDescr SERVLET_DAEMON_STATUS = new ServletDescr(DaemonStatus.class, "Daemon Status"); protected static ServletDescr SERVLET_PROXY_INFO = new ServletDescr(ProxyConfig.class, "Proxy Info", "info/ProxyInfo", 0); protected static ServletDescr SERVLET_THREAD_DUMP = new ServletDescr("org.lockss.servlet.ThreadDump", "Thread Dump", ServletDescr.DEBUG_ONLY); protected static ServletDescr LINK_LOGS = new ServletDescr(null, "Logs", "log", ServletDescr.DEBUG_ONLY); protected static ServletDescr SERVLET_ADMIN_ACCESS_CONTROL = new ServletDescr(AdminIpAccess.class, "Admin Access Control"); protected static ServletDescr SERVLET_PROXY_ACCESS_CONTROL = new ServletDescr(ProxyIpAccess.class, "Proxy Access Control"); // protected static ServletDescr SERVLET_ADMIN_HOME = // new ServletDescr(Admin.class, "Admin Home", ServletDescr.LARGE_LOGO); // protected static ServletDescr SERVLET_JOURNAL_STATUS = // new ServletDescr(JournalStatus.class, "Journal Status", // ServletDescr.STATUS); // protected static ServletDescr SERVLET_JOURNAL_SETUP = // new ServletDescr(JournalSettings.class, "Journal Setup", // ServletDescr.PER_CLIENT); // protected static ServletDescr SERVLET_DAEMON_STATUS = // new ServletDescr(DaemonStatus.class, "Daemon Status", // ServletDescr.STATUS + ServletDescr.NOT_IN_NAV); // All servlets must be listed here (even if not in van table). // Order of descrs determines order in nav table. static ServletDescr servletDescrs[] = { SERVLET_AU_CONFIG, SERVLET_ADMIN_ACCESS_CONTROL, SERVLET_PROXY_ACCESS_CONTROL, SERVLET_PROXY_INFO, SERVLET_DAEMON_STATUS, LINK_LOGS, SERVLET_THREAD_DUMP, // SERVLET_ADMIN_HOME, // SERVLET_JOURNAL_STATUS, // SERVLET_JOURNAL_SETUP, // SERVLET_DAEMON_STATUS, // SERVLET_ACCESS_CONTROL, }; // Create mapping from servlet class to ServletDescr private static final Hashtable servletToDescr = new Hashtable(); static { for (int i = 0; i < servletDescrs.length; i++) { ServletDescr d = servletDescrs[i]; if (d.cls != null) { servletToDescr.put(d.cls, d); } } }; private ServletDescr findServletDescr(Object o) { ServletDescr d = (ServletDescr)servletToDescr.get(o.getClass()); if (d != null) return d; // if not in map, o might be an instance of a subclass of a servlet class // that's in the map. for (int i = 0; i < servletDescrs.length; i++) { d = servletDescrs[i]; if (d.cls != null && d.cls.isInstance(o)) { // found a descr that describes a superclass. Add actual class to map servletToDescr.put(o.getClass(), d); return d; } } return null; // shouldn't happen // XXX do something better here } /** Run once when servlet loaded. */ public void init(ServletConfig config) throws ServletException { super.init(config); context = config.getServletContext(); theDaemon = (LockssDaemon)context.getAttribute("LockssDaemon"); } /** Servlets must implement this method. */ protected abstract void lockssHandleRequest() throws ServletException, IOException; /** Common request handling. */ public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { this.req = req; this.resp = resp; if (log.isDebug()) { logParams(); } resp.setContentType("text/html"); footNumber = 0; reqURL = new URL(UrlUtil.getRequestURL(req)); adminAddr = req.getParameter("admin"); if (adminAddr == null) { adminAddr = Configuration.getParam(PARAM_ADMIN_ADDRESS); } adminHost = reqURL.getHost(); client = req.getParameter("client"); clientAddr = client; if (clientAddr == null) { clientAddr = getLocalIPAddr(); } lockssHandleRequest(); } finally { // Don't hold on to stuff forever req = null; resp = null; reqURL = null; adminDir = null; localAddr = null; footnotes = null; _myServletDescr = null; myName = null; } } // Return descriptor of running servlet protected ServletDescr myServletDescr() { if (_myServletDescr == null) { _myServletDescr = findServletDescr(this); } return _myServletDescr; } // By default, servlet heading is in descr. Override method to // compute other heading protected String getHeading(ServletDescr d) { if (d == null) return "Unknown Servlet"; return d.heading; } protected String getHeading() { return getHeading(myServletDescr()); } String getLocalIPAddr() { if (localAddr == null) { try { InetAddress localHost = InetAddress.getLocalHost(); localAddr = localHost.getHostAddress(); } catch (UnknownHostException e) { // shouldn't happen log.error("LockssServlet: getLocalHost: " + e.toString()); return "???"; } } return localAddr; } // Return IP addr used by LCAP. If specified by (misleadingly named) // localIPAddress prop, might not really be our address (if we are // behind NAT). String getLcapIPAddr() { String ip = Configuration.getParam(PARAM_LOCAL_IP); if (ip.length() <= 0) { return getLocalIPAddr(); } return ip; } String getMachineName() { if (myName == null) { // Return the canonical name of the interface the request was aimed // at. (localIPAddress prop isn't necessarily right here, as it // might be the address of a NAT that we're behind.) String host = reqURL.getHost(); try { InetAddress localHost = InetAddress.getByName(host); String ip = localHost.getHostAddress(); myName = getMachineName(ip); } catch (UnknownHostException e) { // shouldn't happen log.error("getMachineName", e); return host; } } return myName; } String getMachineName(String ip) { try { InetAddress inet = InetAddress.getByName(ip); return inet.getHostName(); } catch (UnknownHostException e) { log.warning("getMachineName", e); } return ip; } // return IP given name or IP String getMachineIP(String name) { try { InetAddress inet = InetAddress.getByName(name); return inet.getHostAddress(); } catch (UnknownHostException e) { return null; } } // Servlet predicates boolean isPerClient() { return myServletDescr().isPerClient(); } boolean runsOnClient() { return myServletDescr().runsOnClient(); } boolean isServletLinkInNav(ServletDescr d) { return !isThisServlet(d) || linkMeInNav(); } boolean isThisServlet(ServletDescr d) { return d == myServletDescr(); } /** servlets may override this to determine whether they should be * a link in nav table */ protected boolean linkMeInNav() { return false; } boolean isLargeLogo() { return myServletDescr().isLargeLogo(); } // machine predicates boolean isClusterAdmin() { return false; // return Configuration.getBooleanParam(PARAM_IS_CLUSTER_ADMIN, false); } // user predicates protected boolean isDebugUser() { return req.isUserInRole("debugRole"); } // Called when a servlet doesn't get the parameters it expects/needs protected void paramError() throws IOException { PrintWriter wrtr = resp.getWriter(); Page page = new Page(); // add referer, params, msg to contact lockss unless from old bookmark // or manually entered url page.add("Parameter error"); page.write(wrtr); } // return true iff error protected boolean checkParam(boolean ok, String msg) throws IOException { if (ok) return false; log.error(myServletDescr().name + ": " + msg); paramError(); return true; } /** Construct servlet URL, with params as necessary. Avoid generating a * hostname different from that used in the original request, or * browsers will prompt again for login */ String srvURL(ServletDescr d, String params) { return srvURL(null, d, params); } /** Construct servlet absolute URL, with params as necessary. */ String srvAbsURL(ServletDescr d, String params) { return srvURL(getMachineName(), d, params); } /** Construct servlet URL, with params as necessary. Avoid generating a * hostname different from that used in the original request, or * browsers will prompt again for login */ String srvURL(String host, ServletDescr d, String params) { StringBuffer sb = new StringBuffer(); StringBuffer paramsb = new StringBuffer(); if (!clientAddr.equals(adminAddr)) { if (!d.runsOnClient()) { if (runsOnClient()) { // invoking admin servlet from client host = adminAddr; } } else if (!runsOnClient()) { // invoking client servlet from admin host = clientAddr; paramsb.append("&admin="); paramsb.append(adminHost); } } if (params != null) { paramsb.append('&'); paramsb.append(params); } if (d.isPerClient()) { paramsb.append("&client="); paramsb.append(clientAddr); } if (host != null) { sb.append(reqURL.getProtocol()); sb.append(": sb.append(host); sb.append(':'); sb.append(reqURL.getPort()); } sb.append('/'); sb.append(d.name); if (paramsb.length() != 0) { paramsb.setCharAt(0, '?'); sb.append(paramsb.toString()); } return sb.toString(); } /** Return a link to a servlet */ String srvLink(ServletDescr d, String text) { return srvLink(d, text, null); } /** Return a link to a servlet with params */ String srvLink(ServletDescr d, String text, String params) { return new Link(srvURL(d, params), (text != null ? text : d.heading)).toString(); } /** Return an absolute link to a servlet with params */ String srvAbsLink(ServletDescr d, String text, String params) { return new Link(srvAbsURL(d, params), (text != null ? text : d.heading)).toString(); } /** Return text as a link iff isLink */ String conditionalSrvLink(ServletDescr d, String text, String params, boolean isLink) { if (isLink) { return srvLink(d, text, params); } else { return text; } } /** Return text as a link iff isLink */ String conditionalSrvLink(ServletDescr d, String text, boolean isLink) { return conditionalSrvLink(d, text, null, isLink); } /** Concatenate params for URL string */ String concatParams(String p1, String p2) { if (p1 == null || p1.equals("")) { return p2; } if (p2 == null || p2.equals("")) { return p1; } return p1 + "&" + p2; } protected String urlEncode(String param) { return URLEncoder.encode(param); } protected boolean isServletInNav(ServletDescr d) { if (!isDebugUser() && d.isDebugOnly()) return false; return d.isInNavTable() && (!d.isPerClient() || isPerClient()); } // Build servlet navigation table private Table getNavTable() { Table navTable = new Table(0, " CELLSPACING=2 CELLPADDING=0 "); boolean clientTitle = false; for (int i = 0; i < servletDescrs.length; i++) { ServletDescr d = servletDescrs[i]; if (isServletInNav(d)) { navTable.newRow(); navTable.newCell(); if (d.isPerClient()) { if (!clientTitle) { // Insert client name before first per-client servlet navTable.cell().attribute("WIDTH=\"15\""); navTable.newCell(); navTable.cell().attribute("COLSPAN=\"2\""); navTable.add("<b>" + getMachineName(clientAddr) + "</b>"); navTable.newRow(); navTable.newCell(); clientTitle = true; } navTable.cell().attribute("WIDTH=\"15\""); navTable.newCell(); navTable.cell().attribute("WIDTH=\"15\""); navTable.newCell(); } else { navTable.cell().attribute("COLSPAN=\"3\""); } if (false /*isThisServlet(d)*/) { navTable.add("<font size=-1 color=green>"); } else { navTable.add("<font size=-1>"); } navTable.add(conditionalSrvLink(d, d.heading, isServletLinkInNav(d))); navTable.add("</font>"); } } navTable.newRow(); navTable.newCell(); navTable.cell().attribute("COLSPAN=\"3\""); String contactAddr = Configuration.getParam(PARAM_CONTACT_ADDR, DEFAULT_CONTACT_ADDR); navTable.add("<font size=-1>"); navTable.add(new Link("mailto:" + contactAddr, "Contact Us")); navTable.add("</font>"); return navTable; } protected Table getExplanationBlock(String text) { Table exp = new Table(0, "width=\"85%\""); exp.center(); exp.newCell("align=center"); exp.add(text); return exp; } protected String getRequestKey() { String key = req.getPathInfo(); if (key != null && key.startsWith("/")) { return key.substring(1); } return key; } /** Common page setup. */ protected Page newPage() { Page page = new Page(); String heading = getHeading(); page.add("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">"); page.addHeader("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"); page.addHeader("<meta http-equiv=\"content-type\" content=\"text/html;charset=ISO-8859-1\">"); page.addHeader("<style type=\"text/css\"><!-- sup {font-weight: normal} --> </STYLE>"); if (heading != null) page.title("LOCKSS: " + heading); else page.title("LOCKSS"); page.attribute("BGCOLOR", BACKGROUND_COLOR); page.add(getHeader()); return page; } // Common page header private Composite getHeader() { String heading = getHeading(); if (heading == null) { heading = "Cache Administration"; } Composite comp = new Composite(); Table table = new Table(0, " cellspacing=2 cellpadding=0 width=\"100%\""); comp.add(table); String machineName = getMachineName(); table.newRow(); Image logo = isLargeLogo() ? IMAGE_LOGO_LARGE : IMAGE_LOGO_SMALL; table.newCell("valign=top align=center width=\"20%\""); // table.newCell("valign=top width=\"25%\""); // table.newCell("valign=top align=center width=" + // (logo.width() + IMAGE_TM.width() + 20)); table.add(new Link("/index.html", logo)); table.add(IMAGE_TM); table.newCell("valign=center align=center width=\"60%\""); table.add("<h3>Permanent Publishing On The Web</h3><br>"); table.add("<font size=+2><b>"); table.add(heading); table.add("</b></font>"); table.add("<br>"); Date startDate = getLockssDaemon().getStartDate(); String since = StringUtil.timeIntervalToString(TimeBase.msSince(startDate.getTime())); table.add(getMachineName() + " at " + headerDf.format(new Date()) + ", up " + since + "</center>"); // table.newCell("valign=center align=right width=\"25%\""); table.newCell("valign=center align=center width=\"20%\""); table.add(getNavTable()); // comp.add("<br><center><font size=+2><b>Cache Administration</b></font></center>"); // comp.add("<center><b>" + machineName + "</b></center>"); // comp.add("<br><center><font size=+1><b>"+heading+"</b></font></center>"); // Date startDate = getLockssDaemon().getStartDate(); // String since = // StringUtil.timeIntervalToString(TimeBase.msSince(startDate.getTime())); // comp.add("<center>" + getMachineName() + " at " + // headerDf.format(new Date()) + ", up " + since + "</center>"); // // comp.add("<center>Running since " + headerDf.format(startDate) + "</center>"); comp.add("<br>"); return comp; } // Common page footer public Element getFooter() { Composite comp = new Composite(); String vPlatform = Configuration.getParam(PARAM_PLATFORM_VERSION); String buildTimeStamp = BuildInfo.getBuildProperty(BuildInfo.BUILD_TIMESTAMP); String buildHost = BuildInfo.getBuildProperty(BuildInfo.BUILD_HOST); String releaseName = BuildInfo.getBuildProperty(BuildInfo.BUILD_RELEASENAME); StringBuffer sb = new StringBuffer(); sb.append("Daemon "); if (releaseName != null) { sb.append(releaseName); sb.append(" "); } sb.append("built "); sb.append(buildTimeStamp); if (buildHost != null) { sb.append(" on "); sb.append(buildHost); } if (vPlatform != null) { sb.append(", CD "); sb.append(vPlatform); } String vDaemon = sb.toString(); addNotes(comp); comp.add("<p>"); Table table = new Table(0, " CELLSPACING=0 CELLPADDING=0 ALIGN=CENTER"); table.newRow("VALIGN=TOP"); table.newCell(); table.add(IMAGE_LOCKSS_RED); table.newCell(); table.add(IMAGE_TM); table.newRow(); table.newCell("COLSPAN=2"); table.add("<center><font size=-1>" + vDaemon + "</font></center>"); comp.add(table); // comp.add("<center><font size=-1>" + vDaemon + "</font></center>"); return comp; } // eventually this should calculate w & h static Image image(String file, int w, int h, int border) { return new Image("/images/" + file, w, h, border); } /** Add html tags to grey the text if isGrey is true */ protected String greyText(String txt, boolean isGrey) { if (!isGrey) { return txt; } return "<font color=grey>" + txt + "</font>"; } /** Store a footnote, assign it a number, return html for footnote * reference. If footnote in null or empty, no footnote is added and am * empty string is returned. */ protected String addFootnote(String s) { if (s == null || s.length() == 0) { return ""; } if (footNumber == 0) { if (footnotes == null) { footnotes = new Vector(10, 10); } else { footnotes.removeAllElements(); } } int n = footnotes.indexOf(s); if (n < 0) { n = footNumber++; footnotes.addElement(s); } return "<sup>" + (n+1) + "</sup>"; } /** Add accumulated footnotes to Composite. */ protected void addNotes(Composite elem) { if (footnotes == null || footNumber == 0) { return; } elem.add("<p><b>Notes:</b>"); elem.add("<ol><font size=-1>"); for (int n = 0; n < footNumber; n++) { elem.add("<li value=" + (n+1) + ">" + footnotes.elementAt(n)); } footnotes.removeAllElements(); elem.add("</font></ol>"); } protected void addJavaScript(Composite comp) { Script script = new Script(getJavascript()); comp.add(script); } private static String jstext = null; private static synchronized String getJavascript() { if (jstext == null) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream istr = loader.getResourceAsStream(JAVASCRIPT_RESOURCE); jstext = StringUtil.fromInputStream(istr); istr.close(); } catch (Exception e) { log.error("Can't load javascript", e); } } return jstext; } /** Return the daemon instance. */ protected LockssDaemon getLockssDaemon() { return theDaemon; } protected void logParams() { Enumeration en = req.getParameterNames(); while (en.hasMoreElements()) { String name = (String)en.nextElement(); log.debug(name + " = " + req.getParameter(name)); } } /** Convenience method */ protected String encodeText(String s) { return HtmlUtil.encode(s, HtmlUtil.ENCODE_TEXT); } /** Convenience method */ protected String encodeTextArea(String s) { return HtmlUtil.encode(s, HtmlUtil.ENCODE_TEXTAREA); } /** Convenience method */ protected String encodeAttr(String s) { return HtmlUtil.encode(s, HtmlUtil.ENCODE_ATTR); } }
package org.mozilla.mozstumbler; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import android.content.BroadcastReceiver; class Reporter extends BroadcastReceiver { private static final String LOGTAG = Reporter.class.getName(); private static final String LOCATION_URL = "https://location.services.mozilla.com/v1/submit"; private static final String NICKNAME_HEADER = "X-Nickname"; private static final String USER_AGENT_HEADER = "User-Agent"; private static final int RECORD_BATCH_SIZE = 20; private static final int REPORTER_WINDOW = 3000; private static String MOZSTUMBLER_USER_AGENT_STRING; private final Context mContext; private final Prefs mPrefs; private JSONArray mReports; private volatile long mLastUploadTime; //TODO why volatile private String mWifiData; private long mWifiDataTime; private String mCellData; private long mCellDataTime; private long mGPSDataTime; private String mGPSData; private String mRadioType; private long mReportsSent; Reporter(Context context, Prefs prefs) { mContext = context; mPrefs = prefs; MOZSTUMBLER_USER_AGENT_STRING = NetworkUtils.getUserAgentString(mContext); String storedReports = mPrefs.getReports(); try { mReports = new JSONArray(storedReports); } catch (Exception e) { mReports = new JSONArray(); } resetData(); mContext.registerReceiver(this, new IntentFilter(ScannerService.MESSAGE_TOPIC)); } private void resetData() { mWifiData = ""; mCellData = ""; mRadioType = ""; mGPSData = ""; mWifiDataTime = 0; mCellDataTime = 0; mGPSDataTime = 0; } void shutdown() { Log.d(LOGTAG, "shutdown"); resetData(); // Attempt to write out mReports mPrefs.setReports(mReports.toString()); mContext.unregisterReceiver(this); } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!action.equals(ScannerService.MESSAGE_TOPIC)) { Log.e(LOGTAG, "Received an unknown intent"); return; } long time = intent.getLongExtra("time", 0); String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); String data = intent.getStringExtra("data"); if (data!=null) Log.d(LOGTAG, "" + subject + " : " + data); if (mWifiDataTime - time > REPORTER_WINDOW) { mWifiData = ""; mWifiDataTime = 0; } if (mCellDataTime - time > REPORTER_WINDOW) { mCellData = ""; mCellDataTime = 0; } if (mGPSDataTime - time > REPORTER_WINDOW) { mGPSData = ""; mGPSDataTime = 0; } if (subject.equals("WifiScanner")) { mWifiData = data; mWifiDataTime = time; } else if (subject.equals("CellScanner")) { mCellData = data; mRadioType = intent.getStringExtra("radioType"); mCellDataTime = time; } else if (subject.equals("GPSScanner")) { mGPSData = data; mGPSDataTime = time; } else { Log.d(LOGTAG, "Intent ignored with Subject: " + subject); return; // Intent not aimed at the Reporter (it is possibly for UI instead) } // Record recent Wi-Fi and/or cell scan results for the current GPS position. Log.d(LOGTAG, "Reporter data: GPS: "+mGPSData.length()+", WiFi: "+mWifiData.length()+", Cell: "+mCellData.length()+" ("+mRadioType+")"); if (mGPSData.length() > 0 && (mWifiData.length() > 0 || mCellData.length() > 0)) { reportLocation(mGPSData, mWifiData, mRadioType, mCellData); resetData(); } } void sendReports(boolean force) { Log.d(LOGTAG, "sendReports: force=" + force); int count = mReports.length(); if (count == 0) { Log.d(LOGTAG, "no reports to send"); return; } if (count < RECORD_BATCH_SIZE && !force && mLastUploadTime > 0) { Log.d(LOGTAG, "batch count not reached, and !force"); return; } if (!NetworkUtils.isNetworkAvailable(mContext)) { Log.d(LOGTAG, "Can't send reports without network connection"); return; } JSONArray reports = mReports; mReports = new JSONArray(); String nickname = mPrefs.getNickname(); spawnReporterThread(reports, nickname); } private void spawnReporterThread(final JSONArray reports, final String nickname) { new Thread(new Runnable() { public void run() { try { Log.d(LOGTAG, "sending results..."); URL url = new URL(LOCATION_URL); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { urlConnection.setDoOutput(true); urlConnection.setRequestProperty(USER_AGENT_HEADER, MOZSTUMBLER_USER_AGENT_STRING); if (nickname != null) { urlConnection.setRequestProperty(NICKNAME_HEADER, nickname); } JSONObject wrapper = new JSONObject(); wrapper.put("items", reports); String wrapperData = wrapper.toString(); byte[] bytes = wrapperData.getBytes(); urlConnection.setFixedLengthStreamingMode(bytes.length); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(bytes); out.flush(); Log.d(LOGTAG, "uploaded wrapperData: " + wrapperData + " to " + LOCATION_URL); int code = urlConnection.getResponseCode(); if (code>=200 && code <= 299) { mReportsSent = reports.length(); } Log.e(LOGTAG, "urlConnection returned " + code); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader r = new BufferedReader(new InputStreamReader(in)); StringBuilder total = new StringBuilder(in.available()); String line; while ((line = r.readLine()) != null) { total.append(line); } r.close(); mLastUploadTime = System.currentTimeMillis(); sendUpdateIntent(); Log.d(LOGTAG, "response was: \n" + total + "\n"); } catch (JSONException jsonex) { Log.e(LOGTAG, "error wrapping data as a batch", jsonex); } catch (Exception ex) { Log.e(LOGTAG, "error submitting data", ex); } finally { urlConnection.disconnect(); } } catch (Exception ex) { Log.e(LOGTAG, "error submitting data", ex); } } }).start(); } void reportLocation(String location, String wifiInfo, String radioType, String cellInfo) { Log.d(LOGTAG, "reportLocation called"); JSONObject locInfo = null; JSONArray cellJSON = null ,wifiJSON = null; try { locInfo = new JSONObject( location ); if (cellInfo.length()>0) { cellJSON=new JSONArray(cellInfo); locInfo.put("cell", cellJSON); locInfo.put("radio", radioType); } if (wifiInfo.length()>0) { wifiJSON=new JSONArray(wifiInfo); locInfo.put("wifi", wifiJSON); } // At least one cell or wifi entry is required if (cellJSON==null && wifiJSON==null) { Log.w(LOGTAG, "Invalid report: at least one cell/wifi entry is required"); return; } } catch (JSONException jsonex) { Log.w(LOGTAG, "JSON exception", jsonex); return; } mReports.put(locInfo); sendReports(false); } public long getLastUploadTime() { return mLastUploadTime; } public long getReportsSent() { return mReportsSent; } private void sendUpdateIntent() { Intent i = new Intent(ScannerService.MESSAGE_TOPIC); i.putExtra(Intent.EXTRA_SUBJECT, "Reporter"); mContext.sendBroadcast(i); } }
package org.nescent.informatics; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.obd.model.Node; import org.obd.model.Statement; import org.obd.query.AnnotationLinkQueryTerm; import org.obd.query.QueryTerm; import org.obd.query.Shard; import org.obd.query.impl.OBDSQLShard; import org.phenoscape.bridge.OBDModelBridge; import org.purl.obo.vocab.RelationVocabulary; /** * FIXME Class comment missing. */ public class OBDQuery { private static RelationVocabulary relationVocabulary = new RelationVocabulary(); private final Shard shard; private Connection conn; private Map<String, Integer> relationNodeIds; public Logger log; /* FIXME this file seems like a bad place for these constants - * aren't they used by other classes too? shouldn't there an * OBDRelation or OBDConstants class? */ private final static String IS_A_RELATION_ID = "OBO_REL:is_a"; private final static String INHERES_IN_RELATION_ID = "OBO_REL:inheres_in"; private final static String HAS_ALLELE_RELATION_ID = "PHENOSCAPE:has_allele"; private final static String EXHIBITS_RELATION_ID = "PHENOSCAPE:exhibits"; private final static String VALUE_FOR_RELATION_ID = "PHENOSCAPE:value_for"; private String anatomyQuery; private String taxonQuery; private String geneQuery; /** * FIXME Constructor and parameter documentation missing. */ public OBDQuery(Shard shard, Connection conn, String[] queries){ this(shard, conn); this.anatomyQuery = queries[0]; this.taxonQuery = queries[1]; this.geneQuery = queries[2]; // FIXME the replacement strings should be constants, // should be documented, and should be in a different file. // FIXME this looks repetitive - rewrite this as a loop // FIXME why aren't we using the accessor method // (getRelationNodeIds()) here? anatomyQuery = anatomyQuery.replaceAll("___inheres_in", relationNodeIds.get("inheres_in").toString()); taxonQuery = taxonQuery.replaceAll("___inheres_in", relationNodeIds.get("inheres_in").toString()); geneQuery = geneQuery.replaceAll("___inheres_in", relationNodeIds.get("inheres_in").toString()); anatomyQuery = anatomyQuery.replaceAll("___exhibits", relationNodeIds.get("exhibits").toString()); taxonQuery = taxonQuery.replaceAll("___exhibits", relationNodeIds.get("exhibits").toString()); geneQuery = geneQuery.replaceAll("___exhibits", relationNodeIds.get("exhibits").toString()); anatomyQuery = anatomyQuery.replaceAll("___has_allele", relationNodeIds.get("has_allele").toString()); taxonQuery = taxonQuery.replaceAll("___has_allele", relationNodeIds.get("has_allele").toString()); geneQuery = geneQuery.replaceAll("___has_allele", relationNodeIds.get("has_allele").toString()); anatomyQuery = anatomyQuery.replaceAll("___value_for", relationNodeIds.get("value_for").toString()); taxonQuery = taxonQuery.replaceAll("___value_for", relationNodeIds.get("value_for").toString()); geneQuery = geneQuery.replaceAll("___value_for", relationNodeIds.get("value_for").toString()); anatomyQuery = anatomyQuery.replaceAll("___is_a", relationNodeIds.get("is_a").toString()); taxonQuery = taxonQuery.replaceAll("___is_a", relationNodeIds.get("is_a").toString()); geneQuery = geneQuery.replaceAll("___is_a", relationNodeIds.get("is_a").toString()); // FIXME should print context to it's clear from the // logs what this is. Also, why are taxonQuery and // geneQuery not being debugged here too? log.debug(anatomyQuery); } /** * FIXME Constructor and parameter documentation missing. */ public OBDQuery(Shard shard, Connection conn){ this.shard = shard; // FIXME if the shard instanceof AbstractSQLShard, // could obtain the connection from the shard this.conn = conn; this.log = Logger.getLogger(this.getClass()); relationNodeIds = new HashMap<String, Integer>(); // FIXME why is this not using the relationship // constants defined above? At any rate, the keys need // to be constants or elements of an enumeration. // FIXME why are we assuming that we have an // OBDSQLShard or derived class here? And if that's // what we must have, why is it not the type requested // in the constructor argument declaration? // FIXME why aren't we using the accessor method // (getRelationNodeIds()) here? relationNodeIds.put("is_a", ((OBDSQLShard) this.shard).getNodeInternalId(IS_A_RELATION_ID)); relationNodeIds.put("inheres_in", ((OBDSQLShard) this.shard).getNodeInternalId(INHERES_IN_RELATION_ID)); relationNodeIds.put("has_allele", ((OBDSQLShard) this.shard).getNodeInternalId(HAS_ALLELE_RELATION_ID)); relationNodeIds.put("exhibits", ((OBDSQLShard) this.shard).getNodeInternalId(EXHIBITS_RELATION_ID)); relationNodeIds.put("value_for", ((OBDSQLShard) this.shard).getNodeInternalId(VALUE_FOR_RELATION_ID)); } public Map<String, Integer> getRelationNodeIds(){ return relationNodeIds; } public String getAnatomyQuery(){ return anatomyQuery; } public String getTaxonQuery(){ return taxonQuery; } public String getGeneQuery(){ return geneQuery; } /** * FIXME Method and parameter documentation missing. */ /* FIXME according to the code in filterNode(), the variable * filterOptions parameter isn't actually variable - if there are * not precisely 3 values, the result will be IndexOutOfBounds */ /* FIXME poorly named method - this seems to be more like * fetchNodes(), or fetchPhenotypeNodes(). */ public Collection<Node> executeQuery(String queryStr, String searchTerm, String... filterOptions){ Collection<Node> results = new ArrayList<Node>(); String entityLabel; PreparedStatement pstmt = null; try{ pstmt = conn.prepareStatement(queryStr); pstmt.setString(1, searchTerm); log.trace(pstmt.toString()); long startTime = System.currentTimeMillis(); ResultSet rs = pstmt.executeQuery(); long endTime = System.currentTimeMillis(); log.trace("Query execution took " + (endTime -startTime) + " milliseconds"); while(rs.next()){ // FIXME it's completely obscure what is // going on in this while() loop, and the // method name doesn't provide any clue // either. Please deobfuscate. if(!filterNode(filterOptions, new String[]{rs.getString(2), rs.getString(8), rs.getString(6)})){ if(!rs.getString(2).contains("GENO")){ Node phenotypeNode = new Node(rs.getString(1)); // FIXME why is this not using the relationship // constants defined above? Statement taxonOrGeneSt = new Statement(phenotypeNode.getId(), "exhibitedBy", rs.getString(3)); Statement taxonOrGeneIdSt = new Statement(phenotypeNode.getId(), "exhibitedById", rs.getString(2)); Statement stateSt = new Statement(phenotypeNode.getId(), "hasState", rs.getString(5)); Statement stateIdSt = new Statement(phenotypeNode.getId(), "hasStateId", rs.getString(4)); Statement characterSt = new Statement(phenotypeNode.getId(), "hasCharacter", rs.getString(7)); Statement characterIdSt = new Statement(phenotypeNode.getId(), "hasCharacterId", rs.getString(6)); entityLabel = rs.getString(9); if(entityLabel == null){ entityLabel = resolveLabel(rs.getString(8)); } Statement entitySt = new Statement(phenotypeNode.getId(), "inheresIn", entityLabel); Statement entityIdSt = new Statement(phenotypeNode.getId(), "inheresInId", rs.getString(8)); phenotypeNode.addStatement(taxonOrGeneSt); phenotypeNode.addStatement(taxonOrGeneIdSt); phenotypeNode.addStatement(stateSt); phenotypeNode.addStatement(stateIdSt); phenotypeNode.addStatement(characterSt); phenotypeNode.addStatement(characterIdSt); phenotypeNode.addStatement(entitySt); phenotypeNode.addStatement(entityIdSt); results.add(phenotypeNode); } } } } catch(SQLException sqle){ log.error(sqle); // FIXME we don't really want to chain exceptions // here but ideally just rethrow the SQLException // so that a caller has more information on what // went wrong, but that requires changing the // method signature (it's a checked exception). throw new RuntimeException(sqle); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException ex) { log.error(ex); // let's not worry further about the close() failing } } } return results; } /** * FIXME Method and parameter documentation missing. */ /* * FIXME Poorly method - calling code seems to be doing something * if the method returns false, and skip a row if the method * returns true - should this be isSkipRow() or isFilterOut()? * What if the two arrays are of unequal length? Nothing seems to * protect against that. */ private boolean filterNode(String[] filterOptions, String[] ids) { for(int i = 0 ; i < filterOptions.length; i++){ if(filterOptions[i] != null && !filterOptions[i].equals(ids[i])){ return true; } } return false; } /** * FIXME Method and parameter documentation missing. * * FIXME Poorly named method. Apparently what this is trying * to do is transform the label of post-composed terms to * something consumable by humans. * * FIXME This is probably the wrong way to achieve this. This * should rather be using an API-based approach, presumably * using the CompositionalDescription class(es). */ public String resolveLabel(String cd){ String label = cd.replaceAll("\\^", " "); String oldLabel = label; // FIXME need to document what this pattern does - is // this trying to identify OBO-style term identifiers? Pattern pat = Pattern.compile("[A-Z]+_?[A-Z]*:[0-9a-zA-Z]+_?[0-9a-zA-Z]*"); Matcher m = pat.matcher(oldLabel); while(m.find()){ String s2replace = oldLabel.substring(m.start(), m.end()); String replaceS = shard.getNode(s2replace).getLabel(); if(replaceS == null) replaceS = s2replace.substring(s2replace.indexOf(":") + 1); label = label.replace(s2replace, replaceS); } label = label.replace("_", " "); return label; } /** * FIXME Parameter documentation and what the method does and * how it does it are missing. * * @author cartik * @param term * @return * THis method has been developed for generic term searches */ public Set<Statement> genericTermSearch(String term, String source){ if(term == null){ throw new IllegalArgumentException("ERROR: Input parameter is null"); } Set<Statement> results = new HashSet<Statement>(); // search term first as subject, then as object of triples results.addAll(this.shard.getStatementsWithSearchTerm(term, null, null, source, false, false)); results.addAll(this.shard.getStatementsWithSearchTerm(null, null, term, source, false, false)); return results; } /** * FIXME Parameter documentation and what the method does and * how it does it are missing. * * @author cartik * @param term * @param options * @return * a method for term auto completions * * FIXME a variable list of string options is a bad way of * passing what seems essentially to be 2 boolean parameters. * * FIXME zfinOption seems poorly named - does this mean this * method can only be called for searches against a repository * containing ZFIN data? */ public Map<String, Collection<Node>> getCompletionsForSearchTerm(String term, boolean zfinOption, List<String> ontologyList, String... options){ boolean bySynonymOption = Boolean.parseBoolean(options[0]); boolean byDefinitionOption = Boolean.parseBoolean(options[1]); Map<String, Collection<Node>> results = new HashMap<String, Collection<Node>>(); Collection<Node> nodesByName = this.shard.getNodesForSearchTermByLabel(term, zfinOption, ontologyList); // FIXME the keys should be constants that are visible // to calling classes, or elements of an enumeration results.put("name-matches", nodesByName); if(bySynonymOption){ Collection<Node> nodesBySynonym = this.shard.getNodesForSearchTermBySynonym(term, zfinOption, ontologyList, true); results.put("synonym-matches", nodesBySynonym); } if(byDefinitionOption){ Collection<Node> nodesByDefinition = this.shard.getNodesForSearchTermByDefinition(term, zfinOption, ontologyList); results.put("definition-matches", nodesByDefinition); } return results; } /** * FIXME Parameter documentation and what the method does and * how it does it are missing. * * This method is designed to find statements that contain a * specific relation-target combination * @param term * @return */ public Collection<Statement> getStatementsWithPredicateAndObject(String target, String relation){ if(target == null || relation == null){ throw new IllegalArgumentException("ERROR: Input parameter is null"); } return this.shard.getStatementsWithSearchTerm(null, relation, target, null, false, false); } /** * FIXME Parameter documentation and what the method does and * how it does it are missing. * * This method is designed to find specific targets of a node by traversing a specific relation */ public Collection<Statement> getStatementsWithSubjectAndPredicate(String subj, String pred){ if(subj == null || pred == null){ throw new IllegalArgumentException("ERROR: Input parameter is null"); } return this.shard.getStatementsWithSearchTerm(subj, pred, null, null, false, false); } }
package org.objectweb.asm.commons; import java.util.HashMap; import java.util.Map; import org.objectweb.asm.Type; /** * A named method descriptor. * @author Juozas Baliuka * @author Chris Nokleberg * @author Eric Bruneton */ public class Method { /** * The method name. */ private final String name; /** * The method descriptor. */ private final String desc; /** * Maps primitive Java type names to their descriptors. */ private final static Map DESCRIPTORS; static { DESCRIPTORS = new HashMap(); DESCRIPTORS.put("void", "V"); DESCRIPTORS.put("byte", "B"); DESCRIPTORS.put("char", "C"); DESCRIPTORS.put("double", "D"); DESCRIPTORS.put("float", "F"); DESCRIPTORS.put("int", "I"); DESCRIPTORS.put("long", "J"); DESCRIPTORS.put("short", "S"); DESCRIPTORS.put("boolean", "Z"); } /** * Creates a new {@link Method}. * * @param name the method's name. * @param desc the method's descriptor. */ public Method (final String name, final String desc) { this.name = name; this.desc = desc; } /** * Creates a new {@link Method}. * * @param name the method's name. * @param returnType the method's return type. * @param argumentTypes the method's argument types. */ public Method ( final String name, final Type returnType, final Type[] argumentTypes) { this(name, Type.getMethodDescriptor(returnType, argumentTypes)); } /** * Returns a {@link Method} corresponding to the given Java method * declaration. * * @param method a Java method declaration, without argument names, of the * form "returnType name (argumentType1, ... argumentTypeN)", where the * types are in plain Java (e.g. "int", "float", "java.util.List", ...). * @return a {@link Method} corresponding to the given Java method * declaration. */ public static Method getMethod (final String method) { int space = method.indexOf(' '); int start = method.indexOf('(', space) + 1; int end = method.indexOf(')', start); String returnType = method.substring(0, space); String methodName = method.substring(space + 1, start - 1).trim(); StringBuffer sb = new StringBuffer(); sb.append('('); int p; do { p = method.indexOf(',', start); if (p == -1) { map(method.substring(start, end).trim()); } else { map(method.substring(start, p).trim()); start = p + 1; } } while (p != -1); sb.append(')'); sb.append(map(returnType)); return new Method(methodName, sb.toString()); } private static String map (final String type) { if (type.equals("")) { return type; } String desc = (String)DESCRIPTORS.get(type); if (desc != null) { return desc; } else if (type.indexOf('.') < 0) { return map("java.lang." + type); } else { StringBuffer sb = new StringBuffer(); int index = 0; while ((index = type.indexOf("[]", index) + 1) > 0) { sb.append('['); } String elementType = type.substring(0, type.length() - sb.length() * 2); sb.append('L').append(elementType.replace('.', '/')).append(';'); return sb.toString(); } } /** * Returns the name of the method described by this object. * * @return the name of the method described by this object. */ public String getName () { return name; } /** * Returns the descriptor of the method described by this object. * * @return the descriptor of the method described by this object. */ public String getDescriptor () { return desc; } /** * Returns the return type of the method described by this object. * * @return the return type of the method described by this object. */ public Type getReturnType () { return Type.getReturnType(desc); } /** * Returns the argument types of the method described by this object. * * @return the argument types of the method described by this object. */ public Type[] getArgumentTypes () { return Type.getArgumentTypes(desc); } public String toString () { return name + desc; } public boolean equals (final Object o) { if (!(o instanceof Method)) { return false; } Method other = (Method)o; return name.equals(other.name) && desc.equals(other.desc); } public int hashCode () { return name.hashCode() ^ desc.hashCode(); } }
package org.vitrivr.cineast.api; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import org.apache.commons.codec.binary.Base64; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.vitrivr.cineast.core.data.audio.AudioFrame; import org.vitrivr.cineast.core.util.LogHelper; public class WebUtils { private WebUtils() { } private static final Logger LOGGER = LogManager.getLogger(); /** * Converts a Base64 data URL to a BufferedImage. * * @param dataUrl String containing the data url. * @return BufferedImage or null, if conversion failed. */ public static BufferedImage dataURLtoBufferedImage(String dataUrl) { /* Convert Base64 string into byte array. */ byte[] bytes = dataURLtoByteArray(dataUrl); if (bytes == null) return null; ByteArrayInputStream binstream = new ByteArrayInputStream(bytes); BufferedImage bimg; try { bimg = ImageIO.read(binstream); } catch (IOException e) { LOGGER.error("could not make image, {}", LogHelper.getStackTrace(e)); return null; } return bimg; } /** * Converts a Base64 data URL into a List auf AudioFrames. * * @param dataUrl String containing the data url. * @return List of AudioFrames or empty list, if conversion failed. */ public static List<AudioFrame> dataURLtoAudioFrames(String dataUrl) { ArrayList<AudioFrame> list = new ArrayList<>(); /* Convert Base64 string into byte array. */ byte[] bytes = dataURLtoByteArray(dataUrl); if (bytes == null) return list; try { /* Read data as AudioInputStream and re-sample it. */ ByteArrayInputStream rawByteStream = new ByteArrayInputStream(bytes); AudioInputStream inputAudio = AudioSystem.getAudioInputStream(rawByteStream); AudioFormat targetFormat = new AudioFormat(22050.0f, 16, 1, true, false); AudioInputStream convertedAudio = AudioSystem.getAudioInputStream(targetFormat, inputAudio); /* Constants: * - Length of a single AudioFrame (in bytes) * - Total length of the audio data in the AudioInputStream. */ final int framesize = 2048; final long length = convertedAudio.getFrameLength() * (targetFormat.getSampleSizeInBits()/2) * targetFormat.getChannels(); /* * Read the data into constant length AudioFrames. */ int read = 0; boolean done = false; while (!done) { /* Allocate a byte-array for the audio-data. */ byte[] data = null; if (read + framesize < length) { data = new byte[framesize]; } else { data = new byte[(int)(length-read)]; done = true; } /* Read audio-data and create AudioFrame. */ convertedAudio.read(data, 0, data.length); list.add(new AudioFrame(read/((targetFormat.getSampleSizeInBits()/2) * targetFormat.getChannels()), targetFormat.getSampleRate(), targetFormat.getChannels(), data)); read += framesize; } } catch (UnsupportedAudioFileException e) { LOGGER.error("Could not create audio frames from Base64 input because the file-format is not supported. {}", LogHelper.getStackTrace(e)); } catch (IOException e) { LOGGER.error("Could not create audio frames from Base64 input due to a serious IO error: {}", LogHelper.getStackTrace(e)); } return list; } /** * Converts a base 64 data URL to a byte array and returns it. Only supported types of * data URLs are currently converted (i.e. images and audio). * * @param dataUrl String containing the data url. * @return Byte array of the data. */ public static byte[] dataURLtoByteArray(String dataUrl) { dataUrl = dataUrl.replace(' ', '+'); /* Check if string is actually a valid data URL. */ if (!dataUrl.startsWith("data:")) { LOGGER.warn("This is not a valid data URL."); return null; } /* Check if data URL is of supported type. */ if (dataUrl.substring(5, 11).equals("image/")) { LOGGER.info("Data URL has been identified as image."); } else if (dataUrl.substring(5, 11).equals("audio/")) { LOGGER.info("Data URL has been identified as audio."); } else { LOGGER.warn("Type of data URL is neither image nor audio and therefore not supported."); return null; } /* Convert and return byte array. */ int headerLength = dataUrl.indexOf(','); String base46data = dataUrl.substring(headerLength + 1); return Base64.decodeBase64(base46data); } /** * * @param img * @param format * @return */ public static String BufferedImageToDataURL(BufferedImage img, String format){ ByteArrayOutputStream bouts = new ByteArrayOutputStream(); try { ImageIO.write(img, format, bouts); } catch (IOException e) { LOGGER.error("could not make image, {}", LogHelper.getStackTrace(e)); return null; } String base64 = new String(Base64.encodeBase64(bouts.toByteArray())); return "data:image/" + format + ";base64," + base64; } }
package com.google.sps; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.lang.Math; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.google.sps.data.SmallCityService; import com.google.sps.data.Listing; import com.google.sps.data.MapLocation; import com.google.sps.data.User; import com.google.maps.GeocodingApi; import com.google.maps.model.AddressComponentType; import com.google.maps.model.AddressType; import com.google.maps.model.ComponentFilter; import com.google.maps.model.GeocodingResult; import com.google.maps.GeoApiContext; import com.google.maps.model.LatLng; import com.google.maps.model.LocationType; import java.util.logging.Logger; /** Test class for User Object **/ @RunWith(JUnit4.class) public final class UserTest { // Pittsburgh Google Office Location private final MapLocation TEST_USER_MAP_LOCATION = new MapLocation(40.45717, -79.91669); private final String TEST_USER_ZIPCODE = "15206"; private final String TEST_USER_CITY = "Pittsburgh"; private final String TEST_USER_ADDRESS = "6425 Penn Ave, Pittsburgh, PA 15206"; private User test_userWithMapLocation; private User test_userWithZipCode; private User test_userWithCity; private User test_userWithAddress; private final String KEY = "REDACTED"; private final static Logger LOGGER = Logger.getLogger(UserTest.class.getName()); @Test public void geolocationUserWithMapLocation() { test_userWithMapLocation = new User(TEST_USER_MAP_LOCATION); MapLocation actual = test_userWithMapLocation.getGeolocation(); MapLocation expected = TEST_USER_MAP_LOCATION; Assert.assertEquals(expected, actual); } @Test public void geolocationUserWithZipCode() { test_userWithZipCode = new User(TEST_USER_ZIPCODE); MapLocation actual = test_userWithZipCode.getGeolocation(); String address = reverseGeocode(actual); Assert.assertTrue(address.contains(TEST_USER_ZIPCODE)); } @Test public void geolocationUserWithCity() { test_userWithCity = new User(TEST_USER_CITY); MapLocation actual = test_userWithCity.getGeolocation(); String address = reverseGeocode(actual); Assert.assertTrue(address.contains(TEST_USER_CITY)); } @Test public void geolocationUserWithAddress() { test_userWithAddress = new User(TEST_USER_ADDRESS); MapLocation actual = test_userWithAddress.getGeolocation(); String address = reverseGeocode(actual); Assert.assertTrue(address.contains(TEST_USER_ADDRESS)); } public String reverseGeocode(MapLocation mapLocation) { final GeoApiContext context = new GeoApiContext.Builder() .apiKey(KEY) .build(); final GeocodingResult[] results; final LatLng latLng = new LatLng(mapLocation.lat, mapLocation.lng); try { results = GeocodingApi.reverseGeocode(context, latLng).await(); String address = results[0].formattedAddress; return address; } catch (final Exception e) { LOGGER.warning(e.getMessage()); } return ""; } }
package org.scijava.util; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; /** * A helper class to help with optimizing the performance of a list of * operations. * <p> * For example, when trying to figure out which * {@link org.scijava.service.Service} would be the best candidate to speed up * {@link org.scijava.Context} initialization, this helper comes in real handy: * it accumulates a list of operations with their duration and prints out a * sorted list when asked to. * </p> * <p> * Use this class as following: * </p> * <code> * private static Timing timing = new Timing();<br /> * ...<br /> * private void oneOperation() {<br /> * &nbsp;final long t1 = System.nanoTime();<br /> * &nbsp;...<br /> * &nbsp;timing.add(System.nanoTime() - t1, "Operation #1");<br /> * }<br /> * ...<br /> * private void atEnd() {<br /> * &nbsp;...<br /> * &nbsp;timing.report("Operations");<br /> * } * </code> * * @author Johannes Schindelin */ public class Timing { private long total = 0, start = System.nanoTime(); private List<Entry<Long, String>> list = new ArrayList<Entry<Long, String>>(); public void addTiming(final long duration, final Object message) { final long now = System.nanoTime(); total += duration; list.add(new Entry<Long, String>() { @Override public Long getKey() { return Long.valueOf(duration); } @Override public String getValue() { return message.toString() + ": " + ((now - start - duration) / 1e6) + " - " + ((now - start) / 1e6); } @Override public String setValue(String value) { throw new UnsupportedOperationException(); } }); } public void report(final String description) { System.err.println(description == null ? getCaller() : description); Collections.sort(list, new Comparator<Entry<Long, String>>() { @Override public int compare(Entry<Long, String> o1, Entry<Long, String> o2) { return Double.compare(o1.getKey(), o2.getKey()); } }); for (final Entry<?,?> e: list) { System.err.printf("% 5.3f ms %s\n", ((Long)e.getKey()) / 1e6, e.getValue()); } System.err.println("Total time: " + total + " = " + (total / 1e9) + " sec"); } private static String getCaller() { final StackTraceElement[] trace = Thread.currentThread().getStackTrace(); int i = 1; while (i + 1 < trace.length && Timing.class.getName().equals(trace[i].getClassName())) { i++; } return i >= trace.length ? "?" : trace[i].getClassName() + "." + trace[i].getMethodName() + "(" + trace[i].getFileName() + ":" + trace[i].getLineNumber() + ")"; } }
import static models.QAccess.access; import static models.QAnyText.anyText; import static models.QDocSubject.docSubject; import static models.QDocument.document; import static models.QDocumentSearch.documentSearch; import static models.QMdType.mdType; import static models.QMdTypeLabel.mdTypeLabel; import static models.QSubject.subject; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Statement; import java.sql.Timestamp; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.jackrabbit.webdav.DavConstants; import org.apache.jackrabbit.webdav.MultiStatus; import org.apache.jackrabbit.webdav.MultiStatusResponse; import org.apache.jackrabbit.webdav.client.methods.DavMethod; import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import com.querydsl.sql.Configuration; import com.querydsl.sql.PostgreSQLTemplates; import com.querydsl.sql.SQLQueryFactory; import com.querydsl.sql.SQLTemplates; public class Main { public static void main(String[] args) throws Exception { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(System.getenv("DB_DRIVER")); dataSource.setUrl(System.getenv("DB_URL")); dataSource.setUsername(System.getenv("DB_USER")); dataSource.setPassword(System.getenv("DB_PASSWORD")); PlatformTransactionManager TransactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate tt = new TransactionTemplate(TransactionManager); HostConfiguration hostConfig = new HostConfiguration(); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); connectionManager.setParams(params); HttpClient client = new HttpClient(connectionManager); client.setHostConfiguration(hostConfig); SQLTemplates templates = PostgreSQLTemplates.builder().printSchema().build(); Configuration configuration = new Configuration(templates); SQLQueryFactory qf = new SQLQueryFactory(configuration, () -> DataSourceUtils.getConnection(dataSource)); tt.execute((status) -> { try { // Delete values from previous harvest qf.delete(mdType) .where(mdType.url.eq(System.getenv("DATA_URL"))) .execute(); qf.insert(mdType) .set(mdType.url, System.getenv("DATA_URL")) .set(mdType.name, System.getenv("DATA_NAME")) .execute(); Integer mdTypeId = qf.select(mdType.id) .from(mdType) .where(mdType.url.eq(System.getenv("DATA_URL"))) .fetchOne(); qf.insert(mdTypeLabel) .set(mdTypeLabel.mdTypeId, mdTypeId) .set(mdTypeLabel.language, System.getenv("LANGUAGE")) .set(mdTypeLabel.title, System.getenv("DATA_LABEL")) .execute(); DavMethod pFind = new PropFindMethod(System.getenv("DATA_URL"), DavConstants.PROPFIND_ALL_PROP, DavConstants.DEPTH_1); // Fill database if(System.getenv("DATA_NAME").equals("dataset")) { executeWebDav(qf, client, pFind, System.getenv("DATA_URL"), MetadataType.DATASET); } else if(System.getenv("DATA_NAME").equals("service")) { executeWebDav(qf, client, pFind, System.getenv("DATA_URL"), MetadataType.SERVICE); } else if(System.getenv("DATA_NAME").equals("dc")) { executeWebDav(qf, client, pFind, System.getenv("DATA_URL"), MetadataType.DC); } // Refresh materialized view executeStatement(dataSource, "refresh materialized view concurrently \"" + documentSearch.getSchemaName() + "\".\"" + documentSearch.getTableName() + "\""); return true; } catch(Exception e) { throw new RuntimeException(e); } }); } public static void executeWebDav(SQLQueryFactory qf, HttpClient client, DavMethod pFind, String url, MetadataType metadataType) throws Exception { client.executeMethod(pFind); MultiStatus multiStatus = pFind.getResponseBodyAsMultiStatus(); MultiStatusResponse[] responses = multiStatus.getResponses(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); for (int i = 0; i < responses.length; i++) { String href = responses[i].getHref(); if(href.endsWith(".xml")) { String filename = href.substring(href.lastIndexOf("/") + 1); try(InputStream input = new URL(url + filename).openStream();) { Document doc = db.parse(input); switch(metadataType) { case DATASET: convertDatasetValues(qf, doc); break; case SERVICE: convertServiceValues(qf, doc); break; case DC: convertDcValues(qf, doc); } } } } System.out.println("Harvesting has been completed"); } public static void convertDatasetValues(SQLQueryFactory qf, Document d) throws Exception { // construct namespace context Map<String, String> ns = new HashMap<>(); ns.put("gmd", "http: ns.put("gco", "http: Map<String, String> pf = new HashMap<>(); for(Map.Entry<String, String> e : ns.entrySet()) { pf.put(e.getValue(), e.getKey()); } MetadataDocument metaDoc = parseDocument(d, ns, pf); List<String> listUuid = metaDoc.getStrings(DatasetPath.UUID.path()); List<String> listTitle = metaDoc.getStrings(DatasetPath.TITLE.path()); List<String> listDate = metaDoc.getStrings(DatasetPath.DATE.path()); List<String> listOrganisationCreator = metaDoc.getStrings(DatasetPath.ORGANISATION_CREATOR.path()); List<String> listDescription = metaDoc.getStrings(DatasetPath.ABSTRACT.path()); List<String> listThumbnail = metaDoc.getStrings(DatasetPath.THUMBNAIL.path()); List<String> listSubject = metaDoc.getStrings(DatasetPath.SUBJECT.path()); List<String> listIndividualNameCreator = metaDoc.getStrings(DatasetPath.INDIVIDUAL_NAME_CREATOR.path()); List<String> listAltTitle = metaDoc.getStrings(DatasetPath.ALT_TITLE.path()); List<String> listMdId = metaDoc.getStrings(DatasetPath.MD_ID.path()); List<String> listDataId = metaDoc.getStrings(DatasetPath.DATA_ID.path()); List<String> listKeyword = metaDoc.getStrings(DatasetPath.KEYWORD.path()); List<String> listIndividualNameContact = metaDoc.getStrings(DatasetPath.INDIVIDUAL_NAME_CONTACT.path()); List<String> listOrganisationContact = metaDoc.getStrings(DatasetPath.ORGANISATION_CONTACT.path()); List<String> listIndividualNameDistributor = metaDoc.getStrings(DatasetPath.INDIVIDUAL_NAME_DISTRIBUTOR.path()); List<String> listOrganisationDistributor = metaDoc.getStrings(DatasetPath.ORGSANISATION_DISTRIBUTOR.path()); List<String> listGeoArea = metaDoc.getStrings(DatasetPath.GEO_AREA.path()); List<String> listPurpose = metaDoc.getStrings(DatasetPath.PURPOSE.path()); List<String> listUseLimitation = metaDoc.getStrings(DatasetPath.USE_LIMITATION.path()); List<String> listDescriptionSource = metaDoc.getStrings(DatasetPath.DESCRIPTION_SOURCE.path()); List<String> listPotentialUse = metaDoc.getStrings(DatasetPath.POTENTIAL_USE.path()); List<String> listOtherConstraint = metaDoc.getStrings(DatasetPath.OTHER_CONSTRAINT.path()); List<String> listRelatedDataset = metaDoc.getStrings(DatasetPath.RELATED_DATASET.path()); Integer mdTypeId = qf.select(mdType.id) .from(mdType) .where(mdType.url.eq(System.getenv("DATA_URL"))) .fetchOne(); LocalDate finalLD = null; for(String date : listDate) { if(finalLD == null) { finalLD = LocalDate.parse(date); } else { LocalDate tempLD = LocalDate.parse(date); if(tempLD.isAfter(finalLD)) { finalLD = LocalDate.parse(date); } } } Timestamp ts; if(finalLD != null) { ts = Timestamp.valueOf(finalLD.atStartOfDay()); } else { ts = null; } List<String> listFinalThumbnail = new ArrayList<>(); for(String thumbnail : listThumbnail) { String finalThumbnail = ""; if(thumbnail.trim().startsWith("http")) { finalThumbnail = thumbnail.trim().replaceAll("\\\\", "/"); } listFinalThumbnail.add(finalThumbnail); } Integer accessId; if(Math.random() < 0.5) { accessId = 1; } else { accessId = 2; } try { qf.insert(document) .set(document.uuid, getValueFromList(listUuid)) .set(document.mdTypeId, mdTypeId) .set(document.title, getValueFromList(listTitle)) .set(document.date, ts) .set(document.creator, getValueFromList(listOrganisationCreator)) .set(document.description, getValueFromList(listDescription)) .set(document.thumbnail, getValueFromList(listFinalThumbnail)) .set(document.accessId, accessId) .execute(); } catch(Exception e) { throw new Exception(e.getCause() + " " + getValueFromList(listUuid)); } Integer docId = qf.select(document.id) .from(document) .where(document.uuid.eq(getValueFromList(listUuid))) .fetchOne(); for(String subjectOne : listSubject) { Integer subjectId = qf.select(subject.id) .from(subject) .where(subject.name.eq(subjectOne)) .fetchOne(); qf.insert(docSubject) .set(docSubject.documentId, docId) .set(docSubject.subjectId, subjectId) .execute(); } setAnyText(qf, docId, listIndividualNameCreator); setAnyText(qf, docId, listAltTitle); setAnyText(qf, docId, listMdId); setAnyText(qf, docId, listDataId); setAnyText(qf, docId, listKeyword); setAnyText(qf, docId, listIndividualNameContact); setAnyText(qf, docId, listOrganisationContact); setAnyText(qf, docId, listIndividualNameDistributor); setAnyText(qf, docId, listOrganisationDistributor); setAnyText(qf, docId, listGeoArea); setAnyText(qf, docId, listPurpose); setAnyText(qf, docId, listUseLimitation); setAnyText(qf, docId, listDescriptionSource); setAnyText(qf, docId, listPotentialUse); setAnyText(qf, docId, listOtherConstraint); setAnyText(qf, docId, listRelatedDataset); } public static void convertServiceValues(SQLQueryFactory qf, Document d) throws Exception { // construct namespace context Map<String, String> ns = new HashMap<>(); ns.put("gmd", "http: ns.put("gco", "http: ns.put("srv", "http: Map<String, String> pf = new HashMap<>(); for(Map.Entry<String, String> e : ns.entrySet()) { pf.put(e.getValue(), e.getKey()); } MetadataDocument metaDoc = parseDocument(d, ns, pf); List<String> listUuid = metaDoc.getStrings(ServicePath.UUID.path()); List<String> listTitle = metaDoc.getStrings(ServicePath.TITLE.path()); List<String> listDate = metaDoc.getStrings(ServicePath.DATE.path()); List<String> listOrganisationCreator = metaDoc.getStrings(ServicePath.ORGANISATION_CREATOR.path()); List<String> listDescription = metaDoc.getStrings(ServicePath.ABSTRACT.path()); List<String> listUseLimitation = metaDoc.getStrings(ServicePath.USE_LIMITATION.path()); List<String> listOtherConstraint = metaDoc.getStrings(ServicePath.OTHER_CONSTRAINT.path()); List<String> listIndividualNameCreator = metaDoc.getStrings(ServicePath.INDIVIDUAL_NAME_CREATOR.path()); List<String> listOrganisationContact = metaDoc.getStrings(ServicePath.ORGANISATION_CONTACT.path()); List<String> listIndividualNameContact = metaDoc.getStrings(ServicePath.INDIVIDUAL_NAME_CONTACT.path()); List<String> listGeoArea = metaDoc.getStrings(ServicePath.GEO_AREA.path()); List<String> listLayer = metaDoc.getStrings(ServicePath.LAYER.path()); List<String> listAttachedFile = metaDoc.getStrings(ServicePath.ATTACHED_FILE.path()); List<String> listKeyword = metaDoc.getStrings(ServicePath.KEYWORD.path()); Integer mdTypeId = qf.select(mdType.id) .from(mdType) .where(mdType.url.eq(System.getenv("DATA_URL"))) .fetchOne(); LocalDate finalLD = null; for(String date : listDate) { if(finalLD == null) { finalLD = LocalDate.parse(date); } else { LocalDate tempLD = LocalDate.parse(date); if(tempLD.isAfter(finalLD)) { finalLD = LocalDate.parse(date); } } } Timestamp ts; if(finalLD != null) { ts = Timestamp.valueOf(finalLD.atStartOfDay()); } else { ts = null; } String thumbnail = null; Integer accessId; if(Math.random() < 0.5) { accessId = 1; } else { accessId = 2; } try { qf.insert(document) .set(document.uuid, getValueFromList(listUuid)) .set(document.mdTypeId, mdTypeId) .set(document.title, getValueFromList(listTitle)) .set(document.date, ts) .set(document.creator, getValueFromList(listOrganisationCreator)) .set(document.description, getValueFromList(listDescription)) .set(document.thumbnail, thumbnail) .set(document.accessId, accessId) .execute(); } catch(Exception e) { e.printStackTrace(); throw new Exception(e.getCause() + " " + getValueFromList(listUuid)); } Integer docId = qf.select(document.id) .from(document) .where(document.uuid.eq(getValueFromList(listUuid))) .fetchOne(); setAnyText(qf, docId, listUseLimitation); setAnyText(qf, docId, listOtherConstraint); setAnyText(qf, docId, listIndividualNameCreator); setAnyText(qf, docId, listOrganisationContact); setAnyText(qf, docId, listIndividualNameContact); setAnyText(qf, docId, listGeoArea); setAnyText(qf, docId, listLayer); setAnyText(qf, docId, listAttachedFile); setAnyText(qf, docId, listKeyword); } public static void convertDcValues(SQLQueryFactory qf, Document d) throws Exception { // construct namespace context Map<String, String> ns = new HashMap<>(); ns.put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns ns.put("dc", "http://purl.org/dc/elements/1.1/"); ns.put("dcterms", "http://purl.org/dc/terms/"); Map<String, String> pf = new HashMap<>(); for(Map.Entry<String, String> e : ns.entrySet()) { pf.put(e.getValue(), e.getKey()); } MetadataDocument metaDoc = parseDocument(d, ns, pf); List<String> listUuid = metaDoc.getStrings(DcPath.UUID.path()); List<String> listTitle = metaDoc.getStrings(DcPath.TITLE.path()); List<String> listDate = metaDoc.getStrings(DcPath.DATE.path()); List<String> listOrganisationCreator = metaDoc.getStrings(DcPath.ORGANISATION_CREATOR.path()); List<String> listDescription = metaDoc.getStrings(DcPath.ABSTRACT.path()); List<String> listLocation = metaDoc.getStrings(DcPath.LOCATION.path()); List<String> listNumber = metaDoc.getStrings(DcPath.NUMBER.path()); List<String> listType = metaDoc.getStrings(DcPath.TYPE.path()); List<String> listPublisher = metaDoc.getStrings(DcPath.PUBLISHER.path()); List<String> listContributor = metaDoc.getStrings(DcPath.CONTRIBUTOR.path()); List<String> listRights = metaDoc.getStrings(DcPath.RIGHTS.path()); List<String> listFormat = metaDoc.getStrings(DcPath.FORMAT.path()); List<String> listSource = metaDoc.getStrings(DcPath.SOURCE.path()); List<String> listSubject = metaDoc.getStrings(DcPath.SUBJECT.path()); List<String> listLanguage = metaDoc.getStrings(DcPath.LANGUAGE.path()); Integer mdTypeId = qf.select(mdType.id) .from(mdType) .where(mdType.url.eq(System.getenv("DATA_URL"))) .fetchOne(); LocalDate ld = LocalDate.parse(getValueFromList(listDate)); Timestamp ts; if(ld != null) { ts = Timestamp.valueOf(ld.atStartOfDay()); } else { ts = null; } String thumbnail = null; Integer accessId; if(Math.random() < 0.5) { accessId = 1; } else { accessId = 2; } try { qf.insert(document) .set(document.uuid, getValueFromList(listUuid)) .set(document.mdTypeId, mdTypeId) .set(document.title, getValueFromList(listTitle)) .set(document.date, ts) .set(document.creator, getValueFromList(listOrganisationCreator)) .set(document.description, getValueFromList(listDescription)) .set(document.thumbnail, thumbnail) .set(document.accessId, accessId) .execute(); } catch(Exception e) { e.printStackTrace(); throw new Exception(e.getCause() + " " + getValueFromList(listUuid)); } Integer docId = qf.select(document.id) .from(document) .where(document.uuid.eq(getValueFromList(listUuid))) .fetchOne(); for(String subjectOne : listSubject) { Integer subjectId = qf.select(subject.id) .from(subject) .where(subject.name.eq(subjectOne)) .fetchOne(); qf.insert(docSubject) .set(docSubject.documentId, docId) .set(docSubject.subjectId, subjectId) .execute(); } setAnyText(qf, docId, listLocation); setAnyText(qf, docId, listNumber); setAnyText(qf, docId, listType); setAnyText(qf, docId, listPublisher); setAnyText(qf, docId, listContributor); setAnyText(qf, docId, listRights); setAnyText(qf, docId, listFormat); setAnyText(qf, docId, listSource); setAnyText(qf, docId, listSubject); setAnyText(qf, docId, listLanguage); } private static void setAnyText(SQLQueryFactory qf, Integer docId, List<String> listValues) { for(String value : listValues) { qf.insert(anyText) .set(anyText.documentId, docId) .set(anyText.content, value.trim()) .execute(); } } private static String getValueFromList(List<String> listValues) { if(listValues.size() == 0) { return null; } else { return listValues.get(0).trim(); } } private static MetadataDocument parseDocument(Document d, Map<String, String> ns, Map<String, String> pf) throws Exception { // parse xml to DOM NamespaceContext nc = new NamespaceContext() { @Override public String getNamespaceURI(String pf) { return ns.get(pf); } @Override public String getPrefix(String ns) { return pf.get(ns); } @Override @SuppressWarnings("rawtypes") public Iterator getPrefixes(String ns) { return Arrays.asList(getPrefix(ns)).iterator(); } }; // construct XPath evaluator XPathFactory xf = XPathFactory.newInstance(); XPath xp = xf.newXPath(); xp.setNamespaceContext(nc); return new MetadataDocument(d, xp); } public static void executeStatement(DriverManagerDataSource dataSource, String statement) throws Exception { try(Statement stmt = DataSourceUtils.getConnection(dataSource).createStatement()) { stmt.execute(statement); } } public enum MetadataType { DATASET, SERVICE, DC; } public static class MetadataDocument { private final Document d; private final XPath xp; MetadataDocument(Document d, XPath xp) { this.d = d; this.xp = xp; } List<String> getStrings(String path) throws Exception { if(!path.endsWith("text()") && !path.endsWith("@uuidref")) { throw new RuntimeException("path should end with text() or @uuidref"); } List<String> retval = new ArrayList<>(); NodeList nl = (NodeList) xp.evaluate(path, d, XPathConstants.NODESET); for(int i = 0; i < nl.getLength(); i++) { retval.add(nl.item(i).getNodeValue()); } return retval; } } }
package net.londatiga.android; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.PopupWindow.OnDismissListener; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * QuickAction dialog, shows action list as icon and text like the one in Gallery3D app. Currently supports vertical * and horizontal layout. * * @author Lorensius W. L. T <lorenz@londatiga.net> * * Contributors: * - Kevin Peck <kevinwpeck@gmail.com> */ public class QuickAction extends PopupWindows implements OnDismissListener { private View mRootView; private ImageView mArrowUp; private ImageView mArrowDown; private LayoutInflater mInflater; private ViewGroup mTrack; private ScrollView mScroller; private OnActionItemClickListener mItemClickListener; private OnDismissListener mDismissListener; private List<ActionItem> actionItems = new ArrayList<ActionItem>(); private boolean mDidAction; private int mChildPos; private int mInsertPos; private int mAnimStyle; private int mOrientation; private int rootWidth=0; public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; public static final int ANIM_GROW_FROM_LEFT = 1; public static final int ANIM_GROW_FROM_RIGHT = 2; public static final int ANIM_GROW_FROM_CENTER = 3; public static final int ANIM_REFLECT = 4; public static final int ANIM_AUTO = 5; /** * Constructor for default vertical layout * * @param context Context */ public QuickAction(Context context) { this(context, VERTICAL); } /** * Constructor allowing orientation override * * @param context Context * @param orientation Layout orientation, can be vartical or horizontal */ public QuickAction(Context context, int orientation) { super(context); mOrientation = orientation; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (mOrientation == HORIZONTAL) { setRootViewId(R.layout.popup_horizontal); } else { setRootViewId(R.layout.popup_vertical); } mAnimStyle = ANIM_AUTO; mChildPos = 0; } /** * Get action item at an index * * @param index Index of item (position from callback) * * @return Action Item at the position */ public ActionItem getActionItem(int index) { return actionItems.get(index); } /** * Set root view. * * @param id Layout resource id */ public void setRootViewId(int id) { mRootView = (ViewGroup) mInflater.inflate(id, mTrack, true); mTrack = (ViewGroup) mRootView.findViewById(R.id.tracks); mArrowDown = (ImageView) mRootView.findViewById(R.id.arrow_down); mArrowUp = (ImageView) mRootView.findViewById(R.id.arrow_up); mScroller = (ScrollView) mRootView.findViewById(R.id.scroller); //This was previously defined on show() method, moved here to prevent force close that occured //when tapping fastly on a view to show quickaction dialog. //Thanx to zammbi (github.com/zammbi) mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); setContentView(mRootView); } /** * Set animation style * * @param mAnimStyle animation style, default is set to ANIM_AUTO */ public void setAnimStyle(int mAnimStyle) { this.mAnimStyle = mAnimStyle; } /** * Set listener for action item clicked. * * @param listener Listener */ public void setOnActionItemClickListener(OnActionItemClickListener listener) { mItemClickListener = listener; } /** * Add action item * * @param action {@link ActionItem} */ public void addActionItem(ActionItem action) { actionItems.add(action); String title = action.getTitle(); Drawable icon = action.getIcon(); View container; if (mOrientation == HORIZONTAL) { container = mInflater.inflate(R.layout.action_item_horizontal, null); } else { container = mInflater.inflate(R.layout.action_item_vertical, null); } ImageView img = (ImageView) container.findViewById(R.id.iv_icon); TextView text = (TextView) container.findViewById(R.id.tv_title); if (icon != null) { img.setImageDrawable(icon); } else { img.setVisibility(View.GONE); } if (title != null) { text.setText(title); } else { text.setVisibility(View.GONE); } final int pos = mChildPos; final int actionId = action.getActionId(); container.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mItemClickListener != null) { mItemClickListener.onItemClick(QuickAction.this, pos, actionId); } if (!getActionItem(pos).isSticky()) { mDidAction = true; dismiss(); } } }); container.setFocusable(true); container.setClickable(true); if (mOrientation == HORIZONTAL && mChildPos != 0) { View separator = mInflater.inflate(R.layout.horiz_separator, null); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); separator.setLayoutParams(params); separator.setPadding(5, 0, 5, 0); mTrack.addView(separator, mInsertPos); mInsertPos++; } mTrack.addView(container, mInsertPos); mChildPos++; mInsertPos++; } /** * Show quickaction popup. Popup is automatically positioned, on top or bottom of anchor view. * */ public void show (View anchor) { preShow(); int xPos, yPos, arrowPos; mDidAction = false; int[] location = new int[2]; anchor.getLocationInWindow(location); Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1] + anchor.getHeight()); //mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); int rootHeight = mRootView.getMeasuredHeight(); if (rootWidth == 0) { rootWidth = mRootView.getMeasuredWidth(); } int screenWidth = mWindowManager.getDefaultDisplay().getWidth(); int screenHeight = mWindowManager.getDefaultDisplay().getHeight(); //automatically get X coord of popup (top left) if ((anchorRect.left + rootWidth) > screenWidth) { xPos = anchorRect.left - (rootWidth-anchor.getWidth()); xPos = (xPos < 0) ? 0 : xPos; arrowPos = anchorRect.centerX()-xPos; } else { if (anchor.getWidth() > rootWidth) { xPos = anchorRect.centerX() - (rootWidth/2); } else { xPos = anchorRect.left; } arrowPos = anchorRect.centerX()-xPos; } int dyTop = anchorRect.top; int dyBottom = screenHeight - anchorRect.bottom; boolean onTop = (dyTop > dyBottom) ? true : false; if (onTop) { if (rootHeight > dyTop) { yPos = 15; LayoutParams l = mScroller.getLayoutParams(); l.height = dyTop - anchor.getHeight(); } else { yPos = anchorRect.top - rootHeight; } } else { yPos = anchorRect.bottom; if (rootHeight > dyBottom) { LayoutParams l = mScroller.getLayoutParams(); l.height = dyBottom; } } showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), arrowPos); setAnimationStyle(screenWidth, anchorRect.centerX(), onTop); mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos); } /** * Set animation style * * @param screenWidth screen width * @param requestedX distance from left edge * @param onTop flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor view * and vice versa */ private void setAnimationStyle(int screenWidth, int requestedX, boolean onTop) { int arrowPos = requestedX - mArrowUp.getMeasuredWidth()/2; switch (mAnimStyle) { case ANIM_GROW_FROM_LEFT: mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left); break; case ANIM_GROW_FROM_RIGHT: mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right); break; case ANIM_GROW_FROM_CENTER: mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center); break; case ANIM_REFLECT: mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect : R.style.Animations_PopDownMenu_Reflect); break; case ANIM_AUTO: if (arrowPos <= screenWidth/4) { mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left); } else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) { mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center); } else { mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right); } break; } } /** * Show arrow * * @param whichArrow arrow type resource id * @param requestedX distance from left screen */ private void showArrow(int whichArrow, int requestedX) { final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown; final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp; final int arrowWidth = mArrowUp.getMeasuredWidth(); showArrow.setVisibility(View.VISIBLE); ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.getLayoutParams(); param.leftMargin = requestedX - arrowWidth / 2; hideArrow.setVisibility(View.INVISIBLE); } /** * Set listener for window dismissed. This listener will only be fired if the quicakction dialog is dismissed * by clicking outside the dialog or clicking on sticky item. */ public void setOnDismissListener(QuickAction.OnDismissListener listener) { setOnDismissListener(this); mDismissListener = listener; } @Override public void onDismiss() { if (!mDidAction && mDismissListener != null) { mDismissListener.onDismiss(); } } /** * Listener for item click * */ public interface OnActionItemClickListener { public abstract void onItemClick(QuickAction source, int pos, int actionId); } /** * Listener for window dismiss * */ public interface OnDismissListener { public abstract void onDismiss(); } }
package net.maizegenetics.util; import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SMTPClient { private String host; private String fromAddress; private String toAddress; private static MimeMessage message; public SMTPClient(String host, String[] toAddresses){ Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); message = new MimeMessage(session); for(int i = 0; i < toAddresses.length; i++){ try{ message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddresses[i])); message.setFrom(new InternetAddress(toAddresses[0])); // just use first address as From }catch(javax.mail.internet.AddressException ae){ /* ignore */ } catch(javax.mail.MessagingException me){ /* ignore */ } } } public void sendMessageWithAttachment(String subject, String msg, String fileAttachment) throws javax.mail.MessagingException{ MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(msg); message.setSubject(subject); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileAttachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileAttachment); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); Transport.send(message); } public void sendMessage(String subject, String msg) throws javax.mail.MessagingException{ message.setSubject(subject); message.setText(msg); Transport.send(message); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.eventio; import java.io.Closeable; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.ArrayList; import java.util.logging.Logger; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.aemonitor.EventRaw; /** * An AE input stream that uses a generic InputStream such as a * URL connection to an http server or memory input stream. * * @author tobi */ public class AEInputStream implements Closeable { // TODO needs to be combined with AEFileInputStream so that AEFileInputStream extends AEInputStream /** * Property change event. Listeners should check for events using these static String objects. * <p> * In order to use these events, an EventFilter must register itself either with the AEInputStream or with the owning AEViewer. * But this registration * is only possible after AEViewer is constructed, which is after the * EventFilter is constructed. The registration can occur in the EventFilter * filterPacket() method as in the code snippet below: * <pre><code> * private boolean addedViewerPropertyChangeListener = false; * * synchronized public EventPacket filterPacket(EventPacket in) { // TODO completely rework this code because IMUSamples are part of the packet now! * if (!addedViewerPropertyChangeListener) { * if (chip.getAeViewer() != null) { * chip.getAeViewer().addPropertyChangeListener(this); // AEViewer refires these events for convenience * addedViewerPropertyChangeListener = true; * } * } * } * </code></pre> * <p> * <ul> * <li>EVENT_EOF end of input file or stream * <li>EVENT_WRAPPED_TIME means timestamp has wrapped around 32-bit value * <li>EVENT_POSITION means input stream position has changed (called on * every packet) * <li>EVENT_REWIND means files has just rewound to start * <li>EVENT_MARKSET means the mark has just been set on the stream for * later possible rewind * <li>EVENT_MARKS_CLEARED means the marks were cleared * <li>EVENT_INIT is called after initialization of the input stream, * <li>EVENT_NON_MONOTONIC_TIMESTAMP a non-monotonic timestamp was detected * </ul> */ public static final String EVENT_EOF="eof", EVENT_WRAPPED_TIME="wrappedTime", EVENT_POSITION="position", EVENT_REWIND="rewind", EVENT_MARKSET="markset", EVENT_MARKS_CLEARED="marksCleared",EVENT_MARK_IN_SET="markInSet",EVENT_MARK_OUT_SET="markOutSet", EVENT_INIT="init", EVENT_NON_MONOTONIC_TIMESTAMP="nonMonotonicTimestamp"; private InputStream is; AEPacketRaw packet = new AEPacketRaw(); int lastPacketEndTimestamp = 0; static Logger log = Logger.getLogger("AEInputStream"); protected ArrayList<String> header = new ArrayList<String>(); private Class addressType = Short.TYPE; // default address type, unless file header specifies otherwise DataInputStream dis; boolean readFirstEventFlag = false; PushbackInputStream pbis; /** Constructs new instance of AEInputStream, and attempts skip its header, if any. * * @param is the input stream * @throws IOException on error skipping header. */ public AEInputStream(InputStream is) throws IOException { this.is = is; dis = new DataInputStream(pbis=new PushbackInputStream(is)); // we need to be able to push back bytes after scanning header skipHeader(); } EventRaw tmpEvent = new EventRaw(); private EventRaw readEvent() throws IOException { int addr; int ts; if (getAddressType() == Integer.TYPE) { addr = dis.readInt(); } else { addr = dis.readShort(); } ts = dis.readInt(); tmpEvent.address = addr; tmpEvent.timestamp = ts; return tmpEvent; } /** Reads all available events from the stream * @return available event packet */ public AEPacketRaw readAvailablePacket() throws IOException{ packet.setNumEvents(0); int n=dis.available(); int es=getAddressType()==Integer.TYPE?8:4; int ne=n/es; for (int i = 0; i < n; i++) { packet.addEvent(readEvent()); } return packet; } /** Reads a raw event packet of n events @param n the number of events to read @throws IOException if there is a problem, e.g. end of file */ public AEPacketRaw readPacketByNumber(int n) throws IOException { packet.setNumEvents(0); for (int i = 0; i < n; i++) { packet.addEvent(readEvent()); } return packet; } /** * returns an AEPacketRaw at least dt long up to the max size of the buffer or until end-of-file. * Events are read as long as the timestamp until (and including) the event whose timestamp is greater (for dt>0) than * startTimestamp+dt, where startTimestamp is the last timestamp from the previous call. * * @param dt the timestamp different in units of the timestamp (usually us) @return the packet, always at least one event even if there is no event in the interval dt. @throws IOException if there is any problem */ public AEPacketRaw readPacketByTime(int dt) throws IOException { packet.setNumEvents(0); int ts; if(!readFirstEventFlag) lastPacketEndTimestamp=readEvent().timestamp; do{ EventRaw e=readEvent(); packet.addEvent(e); ts=e.timestamp; }while(ts-lastPacketEndTimestamp<dt); return packet; } /** skips the header lines (if any) */ protected void skipHeader() throws IOException { readHeader(); } /** reads the header comment lines. Assumes we are rewound to position(0). */ protected void readHeader() throws IOException { String s; while ((s = readHeaderLine()) != null) { header.add(s); parseFileFormatVersion(s); } StringBuffer sb = new StringBuffer(); sb.append("File header:"); for (String str : getHeader()) { sb.append(str); sb.append("\n"); } log.info(sb.toString()); } /** parses the file format version @see net.sf.jaer.eventio.AEDataFile */ protected void parseFileFormatVersion(String s) { float version = 1f; if (s.startsWith(AEDataFile.DATA_FILE_FORMAT_HEADER)) { // # stripped off by readHeaderLine try { version = Float.parseFloat(s.substring(AEDataFile.DATA_FILE_FORMAT_HEADER.length())); } catch (NumberFormatException numberFormatException) { log.warning("While parsing header line " + s + " got " + numberFormatException.toString()); } if (version < 2) { setAddressType(Short.TYPE); } else if (version >= 2) { // this is hack to avoid parsing the AEDataFile. format number string... setAddressType(Integer.TYPE); } log.info("Data file version=" + version + " and has addressType=" + getAddressType()); } } /** assumes we are positioned at start of line and that we may either read a comment char '#' or something else leaves us after the line at start of next line or of raw data. Assumes header lines are written using the AEOutputStream.writeHeaderLine(). @return header line */ String readHeaderLine() throws IOException { StringBuffer s = new StringBuffer(); int c = pbis.read(); if (c != AEDataFile.COMMENT_CHAR) { pbis.unread(c); return null; } while (((char) (c = pbis.read())) != '\r') { if (c < 32 || c > 126) { throw new IOException("Non printable character (<32 || >126) detected in header line, aborting header read and resetting to start of file because this file may not have a real header"); } s.append((char) c); } if ((c = pbis.read()) != '\n') { log.warning("header line \"" + s.toString() + "\" doesn't end with LF"); // get LF of CRLF } return s.toString(); } /** Gets the header strings from the file @return list of strings, one per line */ public ArrayList<String> getHeader() { return header; } public void close() throws IOException { if(is!=null) is.close(); } /** * @return the addressType, either Integer.TYPE or Short.TYPE; */ public Class getAddressType (){ return addressType; } /** * @param addressType the addressType to set, either Integer.TYPE or Short.TYPE */ public void setAddressType (Class addressType){ if(addressType!=Integer.TYPE && addressType!=Short.TYPE ){ log.warning("tried to set event type to be "+addressType+" but only Integer.TYPE and Short.TYPE addresses are allowed"); return; } this.addressType = addressType; } }
/** * Clase ventanaPrincipal * @author curso14/7803 * @version 1.0 * @since 19/11/2015 * <br> * <p> * Esta clase corresponde a la pantalla principal del programa y sus mens * </p> */ package ventanaPrincipal; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; //import alumnos.VentanaInteresado; import cursos.VentanaCursos; import cursos.VentanaGrupos; import cursos.ventanaModulo; import matricula.VentanaFormaPago; import matricula.VentanaMatricula; public class VentanaPrincipal extends JFrame implements ActionListener { private JMenuBar barraMenu; private JMenu menuAlumnos, menuCursos, menuCalificacion, menuMatricula, menuAyuda, menuSalir; private JMenuItem matriculado, interesado, cursos, grupos, modulos, calificacion, matricula, formaPago, ayuda, salir; public static String usuario = "root"; public static String pwd = "root"; public static String bd = "nowedb"; public static basedatos.ConexionBaseDatos conexion = null; public VentanaPrincipal () { setLayout(null); Fondo fondo; Toolkit t = Toolkit.getDefaultToolkit(); Dimension tamaoPantalla = Toolkit.getDefaultToolkit().getScreenSize(); this.setLayout(null); Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/logo_nowe.gif")); setIconImage(icon); this.setTitle("ERP Nowe"); setSize(tamaoPantalla.width, tamaoPantalla.height); setResizable(false); fondo = new Fondo(); add(fondo); barraMenu = new JMenuBar(); setJMenuBar(barraMenu); menuAlumnos = new JMenu ("Alumnos"); barraMenu.add(menuAlumnos); matriculado = new JMenuItem("Matriculado"); matriculado.addActionListener(this); menuAlumnos.add(matriculado); interesado = new JMenuItem("Interesado"); interesado.addActionListener(this); menuAlumnos.add(interesado); menuCursos = new JMenu ("Cursos"); barraMenu.add(menuCursos); cursos = new JMenuItem("Cursos"); cursos.addActionListener(this); menuCursos.add(cursos); grupos = new JMenuItem("Grupos"); grupos.addActionListener(this); menuCursos.add(grupos); modulos = new JMenuItem("Mdulos"); modulos.addActionListener(this); menuCursos.add(modulos); menuCalificacion = new JMenu ("Calificacin"); barraMenu.add(menuCalificacion); calificacion = new JMenuItem("Calificacin"); calificacion.addActionListener(this); menuCalificacion.add(calificacion); menuMatricula = new JMenu ("Matrcula"); barraMenu.add(menuMatricula); matricula = new JMenuItem("Matrcula"); matricula.addActionListener(this); menuMatricula.add(matricula); formaPago = new JMenuItem("Forma de Pago"); formaPago.addActionListener(this); menuMatricula.add(formaPago); menuAyuda = new JMenu ("Ayuda"); barraMenu.add(menuAyuda); ayuda = new JMenuItem("?"); ayuda.addActionListener(this); menuAyuda.add(ayuda); menuSalir = new JMenu ("Salir"); barraMenu.add(menuSalir); salir = new JMenuItem("Salir"); salir.addActionListener(this); menuSalir.add(salir);} public void actionPerformed(ActionEvent e) { if (e.getSource()== cursos) { conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaCursos ventana=new VentanaCursos(); ventana.setVisible(true); } if (e.getSource()== modulos){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); ventanaModulo ventana = new ventanaModulo(); ventana.setVisible(true); } /*if (e.getSource()== interesado){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaInteresado ne = new VentanaInteresado(); ne.setVisible(true); }*/ if (e.getSource()== grupos){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaGrupos ne = new VentanaGrupos(); ne.setVisible(true); } if (e.getSource()== matricula){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaMatricula ventana = new VentanaMatricula(); ventana.setVisible(true); } if (e.getSource()== formaPago){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaFormaPago ventana = new VentanaFormaPago(); ventana.setVisible(true); } } }
package polyglot.types.reflect; import polyglot.main.Report; import polyglot.types.*; import polyglot.util.*; import java.io.*; import java.util.*; /** * ClassFile basically represents a Java classfile as it is found on * disk. The classfile is modeled according to the Java Virtual Machine * Specification. Methods are provided to edit the classfile at a very * low level. * * @see polyglot.types.reflect Attribute * @see polyglot.types.reflect Constant * @see polyglot.types.reflect Field * @see polyglot.types.reflect Method * * @author Nate Nystrom * (<a href="mailto:nystrom@cs.purdue.edu">nystrom@cs.purdue.edu</a>) */ public class ClassFile implements LazyClassInitializer { Constant[] constants; // The constant pool int modifiers; // This class's modifer bit field int thisClass; int superClass; int[] interfaces; Field[] fields; Method[] methods; Attribute[] attrs; InnerClasses innerClasses; static Collection verbose = ClassFileLoader.verbose; /** * Constructor. This constructor parses the class file from the input * stream. * * @param file * The file in which the class resides. * @param loader * The class info loader which loaded the class. * @param in * The data stream containing the class. * @exception ClassFormatError * When the class could not be parsed. */ public ClassFile(byte[] code) { try { ByteArrayInputStream bin = new ByteArrayInputStream(code); DataInputStream in = new DataInputStream(bin); read(in); in.close(); bin.close(); } catch (IOException e) { throw new InternalCompilerError("I/O exception on ByteArrayInputStream"); } } public boolean fromClassFile() { return true; } JLCInfo getJLCInfo(String ts) { // Check if already set. JLCInfo jlc = (JLCInfo) jlcInfo.get(ts); if (jlc != null) { return jlc; } jlc = new JLCInfo(); jlcInfo.put(ts, jlc); try { int mask = 0; for (int i = 0; i < fields.length; i++) { if (fields[i].name().equals("jlc$SourceLastModified$" + ts)) { jlc.sourceLastModified = fields[i].getLong(); mask |= 1; } else if (fields[i].name().equals("jlc$CompilerVersion$" + ts)) { jlc.compilerVersion = fields[i].getString(); mask |= 2; } else if (fields[i].name().equals("jlc$ClassType$" + ts)) { jlc.encodedClassType = fields[i].getString(); mask |= 4; } } if (mask != 7) { // Not all the information is there. Reset to default. jlc.sourceLastModified = 0; jlc.compilerVersion = null; jlc.encodedClassType = null; } } catch (SemanticException e) { jlc.sourceLastModified = 0; jlc.compilerVersion = null; jlc.encodedClassType = null; } return jlc; } /** * Get the encoded source modified time. */ public long sourceLastModified(String ts) { JLCInfo jlc = getJLCInfo(ts); return jlc.sourceLastModified; } /** * Get the encoded compiler version used to compile the source. */ public String compilerVersion(String ts) { JLCInfo jlc = getJLCInfo(ts); return jlc.compilerVersion; } /** * Get the encoded class type. */ public String encodedClassType(String ts) { JLCInfo jlc = getJLCInfo(ts); return jlc.encodedClassType; } Map jlcInfo = new HashMap(); /** * Read the class file. */ void read(DataInputStream in) throws IOException { // Read in file contents from stream readHeader(in); readConstantPool(in); readAccessFlags(in); readClassInfo(in); readFields(in); readMethods(in); readAttributes(in); } /** * Extract the class type from the class file. */ public ParsedClassType type(TypeSystem ts) throws SemanticException { ParsedClassType ct = createType(ts); if (ts.equals(ct, ts.Object())) { ct.superType(null); } else { String superName = classNameCP(superClass); if (superName != null) { ct.superType(typeForName(ts, superName)); } else { ct.superType(ts.Object()); } } return ct; } /** * Initialize <code>ct</code>'s member classes. */ public void initMemberClasses(ParsedClassType ct) { if (innerClasses == null) { return; } TypeSystem ts = ct.typeSystem(); for (int i = 0; i < innerClasses.classes.length; i++) { InnerClasses.Info c = innerClasses.classes[i]; if (c.outerClassIndex == thisClass && c.classIndex != 0) { String name = classNameCP(c.classIndex); int index = name.lastIndexOf('$'); // Skip local and anonymous classes. if (index >= 0 && Character.isDigit(name.charAt(index+1))) { continue; } // A member class of this class ClassType t = typeForName(ts, name); if (t.isMember()) { if (Report.should_report(verbose, 3)) Report.report(3, "adding member " + t + " to " + ct); ct.addMemberClass(t); } else { throw new InternalCompilerError(name + " should be a member class."); } } } } /** * Initialize <code>ct</code>'s interfaces. */ public void initInterfaces(ParsedClassType ct) { TypeSystem ts = ct.typeSystem(); for (int i = 0; i < interfaces.length; i++) { String name = classNameCP(interfaces[i]); ct.addInterface(typeForName(ts, name)); } } /** * Initialize <code>ct</code>'s fields. */ public void initFields(ParsedClassType ct) { TypeSystem ts = ct.typeSystem(); // Add the "class" field. LazyClassInitializer init = ts.defaultClassInitializer(); init.initFields(ct); for (int i = 0; i < fields.length; i++) { if (! fields[i].name().startsWith("jlc$")) { FieldInstance fi = fields[i].fieldInstance(ts, ct); if (Report.should_report(verbose, 3)) Report.report(3, "adding " + fi + " to " + ct); ct.addField(fi); } } } /** * Initialize <code>ct</code>'s methods. */ public void initMethods(ParsedClassType ct) { TypeSystem ts = ct.typeSystem(); for (int i = 0; i < methods.length; i++) { if (! methods[i].name().equals("<init>") && ! methods[i].name().equals("<clinit>")) { MethodInstance mi = methods[i].methodInstance(ts, ct); if (Report.should_report(verbose,3)) Report.report(3, "adding " + mi + " to " + ct); ct.addMethod(mi); } } } /** * Initialize <code>ct</code>'s constructors. */ public void initConstructors(ParsedClassType ct) { TypeSystem ts = ct.typeSystem(); for (int i = 0; i < methods.length; i++) { if (methods[i].name().equals("<init>")) { ConstructorInstance ci = methods[i].constructorInstance(ts, ct); if (Report.should_report(verbose,3)) Report.report(3, "adding " + ci + " to " + ct); ct.addConstructor(ci); } } } /** * Create an array of <code>t</code>. */ Type arrayOf(Type t, int dims) { if (dims == 0) { return t; } else { return t.typeSystem().arrayOf(t, dims); } } /** * Convert a descriptor string into a list of types. */ List typeListForString(TypeSystem ts, String str) { List types = new ArrayList(); for (int i = 0; i < str.length(); i++) { int dims = 0; while (str.charAt(i) == '[') { dims++; i++; } switch (str.charAt(i)) { case 'Z': types.add(arrayOf(ts.Boolean(), dims)); break; case 'B': types.add(arrayOf(ts.Byte(), dims)); break; case 'S': types.add(arrayOf(ts.Short(), dims)); break; case 'C': types.add(arrayOf(ts.Char(), dims)); break; case 'I': types.add(arrayOf(ts.Int(), dims)); break; case 'J': types.add(arrayOf(ts.Long(), dims)); break; case 'F': types.add(arrayOf(ts.Float(), dims)); break; case 'D': types.add(arrayOf(ts.Double(), dims)); break; case 'V': types.add(arrayOf(ts.Void(), dims)); break; case 'L': { int start = ++i; while (i < str.length()) { if (str.charAt(i) == ';') { String s = str.substring(start, i); s = s.replace('/', '.'); types.add(arrayOf(typeForName(ts, s), dims)); break; } i++; } } } } if (Report.should_report(verbose, 4)) Report.report(4, "parsed \"" + str + "\" -> " + types); return types; } /** * Convert a descriptor string into a type. */ Type typeForString(TypeSystem ts, String str) { List l = typeListForString(ts, str); if (l.size() == 1) { return (Type) l.get(0); } throw new InternalCompilerError("Bad type string: \"" + str + "\""); } /** * Convert a String into a type. */ ClassType typeForName(TypeSystem ts, String name) { if (Report.should_report(verbose,2)) Report.report(2, "resolving " + name); try { return (ClassType) ts.systemResolver().find(name); } catch (SemanticException e) { throw new InternalCompilerError("could not load " + name); } } /** * Create the type for this class file. */ ParsedClassType createType(TypeSystem ts) { // The name is of the form "p.q.C$I$J". String name = classNameCP(thisClass); if (Report.should_report(verbose, 2)) Report.report(2, "creating ClassType for " + name); // This is the "p.q" part. String packageName = StringUtil.getPackageComponent(name); // This is the "C$I$J" part. String className = StringUtil.getShortNameComponent(name); int dollar = name.lastIndexOf('$'); String outerName; // This will be "p.q.C$I" String innerName; // This will be "J" if (dollar >= 0) { outerName = name.substring(0, dollar); innerName = name.substring(dollar+1); } else { outerName = name; innerName = null; } ClassType.Kind kind = ClassType.TOP_LEVEL; if (dollar >= 0) { // A nested class. Parse the class name to determine what kind. StringTokenizer st = new StringTokenizer(className, "$"); while (st.hasMoreTokens()) { String s = st.nextToken(); if (Character.isDigit(s.charAt(0))) { // Example: C$1 kind = ClassType.ANONYMOUS; } else if (kind == ClassType.ANONYMOUS) { // Example: C$1$D kind = ClassType.LOCAL; } else { // Example: C$D kind = ClassType.MEMBER; } } } if (Report.should_report(verbose, 3)) Report.report(3, name + " is " + kind); ParsedClassType ct = ts.createClassType(this); ct.kind(kind); if (ct.isTopLevel()) { ct.name(className); } else if (ct.isMember() || ct.isLocal()) { ct.name(innerName); } if (! packageName.equals("")) { ct.package_(ts.packageForName(packageName)); } // Add unresolved class into the cache to avoid circular resolving. ((CachingResolver) ts.systemResolver()).install(name, ct); if (ct.isNested()) { ct.outer(typeForName(ts, outerName)); } ct.flags(ts.flagsForBits(modifiers)); ct.position(position()); return ct; } /** * Create a position for the class file. */ public Position position() { return new Position(name() + ".class"); } /** * Get the class name at the given constant pool index. */ String classNameCP(int index) { Constant c = constants[index]; if (c != null && c.tag() == Constant.CLASS) { Integer nameIndex = (Integer) c.value(); if (nameIndex != null) { c = constants[nameIndex.intValue()]; if (c.tag() == Constant.UTF8) { String s = (String) c.value(); return s.replace('/', '.'); } } } return null; } /** * Get the name of the class, including the package name. * * @return * The name of the class. */ public String name() { Constant c = constants[thisClass]; if (c.tag() == Constant.CLASS) { Integer nameIndex = (Integer) c.value(); if (nameIndex != null) { c = constants[nameIndex.intValue()]; if (c.tag() == Constant.UTF8) { return (String) c.value(); } } } throw new ClassFormatError("Couldn't find class name in file"); } /** * Read a constant from the constant pool. * * @param in * The stream from which to read. * @return * The constant. * @exception IOException * If an error occurs while reading. */ Constant readConstant(DataInputStream in) throws IOException { int tag = in.readUnsignedByte(); Object value; switch (tag) { case Constant.CLASS: case Constant.STRING: value = new Integer(in.readUnsignedShort()); break; case Constant.FIELD_REF: case Constant.METHOD_REF: case Constant.INTERFACE_METHOD_REF: case Constant.NAME_AND_TYPE: value = new int[2]; ((int[]) value)[0] = in.readUnsignedShort(); ((int[]) value)[1] = in.readUnsignedShort(); break; case Constant.INTEGER: value = new Integer(in.readInt()); break; case Constant.FLOAT: value = new Float(in.readFloat()); break; case Constant.LONG: // Longs take up 2 constant pool entries. value = new Long(in.readLong()); break; case Constant.DOUBLE: // Doubles take up 2 constant pool entries. value = new Double(in.readDouble()); break; case Constant.UTF8: value = in.readUTF(); break; default: throw new ClassFormatError("Invalid constant tag: " + tag); } return new Constant(tag, value); } /** * Read the class file header. * * @param in * The stream from which to read. * @exception IOException * If an error occurs while reading. */ void readHeader(DataInputStream in) throws IOException { int magic = in.readInt(); if (magic != 0xCAFEBABE) { throw new ClassFormatError("Bad magic number."); } int major = in.readUnsignedShort(); int minor = in.readUnsignedShort(); } /** * Read the class's constant pool. Constants in the constant pool * are modeled by an array of <tt>reflect.Constant</tt>/ * * @param in * The stream from which to read. * @exception IOException * If an error occurs while reading. * * @see Constant * @see #constants */ void readConstantPool(DataInputStream in) throws IOException { int count = in.readUnsignedShort(); constants = new Constant[count]; // The first constant is reserved for internal use by the JVM. constants[0] = null; // Read the constants. for (int i = 1; i < count; i++) { constants[i] = readConstant(in); switch (constants[i].tag()) { case Constant.LONG: case Constant.DOUBLE: // Longs and doubles take up 2 constant pool entries. constants[++i] = null; break; } } } /** * Read the class's access flags. * * @param in * The stream from which to read. * @exception IOException * If an error occurs while reading. */ void readAccessFlags(DataInputStream in) throws IOException { modifiers = in.readUnsignedShort(); } /** * Read the class's name, superclass, and interfaces. * * @param in * The stream from which to read. * @exception IOException * If an error occurs while reading. */ void readClassInfo(DataInputStream in) throws IOException { int index; thisClass = in.readUnsignedShort(); superClass = in.readUnsignedShort(); int numInterfaces = in.readUnsignedShort(); interfaces = new int[numInterfaces]; for (int i = 0; i < numInterfaces; i++) { interfaces[i] = in.readUnsignedShort(); } } /** * Read the class's fields. * * @param in * The stream from which to read. * @exception IOException * If an error occurs while reading. */ void readFields(DataInputStream in) throws IOException { int numFields = in.readUnsignedShort(); fields = new Field[numFields]; for (int i = 0; i < numFields; i++) { fields[i] = new Field(in, this); } } /** * Read the class's methods. * * @param in * The stream from which to read. * @exception IOException * If an error occurs while reading. */ void readMethods(DataInputStream in) throws IOException { int numMethods = in.readUnsignedShort(); methods = new Method[numMethods]; for (int i = 0; i < numMethods; i++) { methods[i] = new Method(in, this); } } /** * Read the class's attributes. Since none of the attributes * are required, just read the length of each attribute and * skip that many bytes. * * @param in * The stream from which to read. * @exception IOException * If an error occurs while reading. */ void readAttributes(DataInputStream in) throws IOException { int numAttributes = in.readUnsignedShort(); attrs = new Attribute[numAttributes]; for (int i = 0; i < numAttributes; i++) { int nameIndex = in.readUnsignedShort(); int length = in.readInt(); if ("InnerClasses".equals(constants[nameIndex].value())) { innerClasses = new InnerClasses(in, nameIndex, length); attrs[i] = innerClasses; } else { in.skip(length); } } } }
package opendap.bes.dap2Responders; import opendap.bes.*; import opendap.coreServlet.RequestCache; import opendap.coreServlet.ResourceInfo; import opendap.coreServlet.Scrub; import opendap.dap4.QueryParameters; import opendap.logging.Timer; import opendap.logging.Procedure; import opendap.ppt.PPTException; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.slf4j.Logger; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * Subclass BesApi to get different BES behaviors. * * You may find that it's usefule to: * * - override one (or even all!) of the BesApi.write*() methods. * * - override BesApi.getRequestDocument() * * - override BesApi.besTransaction(*) */ public class BesApi { public static final String DAP4_DATA = "dap"; public static final String DAP4_DMR = "dmr"; public static final String DDS = "dds"; public static final String DAS = "das"; public static final String DDX = "ddx"; public static final String DataDDX = "dataddx"; public static final String DAP2_DATA = "dods"; public static final String STREAM = "stream"; public static final String ASCII = "ascii"; public static final String CSV = "csv"; public static final String HTML_FORM = "html_form"; public static final String INFO_PAGE = "info_page"; public static final String XML_DATA = "xml_data"; public static final String NETCDF_3 = "netcdf"; public static final String NETCDF_4 = "netcdf-4"; public static final String GEOTIFF = "geotiff"; public static final String GMLJP2 = "jpeg2000"; public static final String JSON = "json"; public static final String IJSON = "ijson"; public static final String W10N = "w10n"; public static final String W10N_META = "w10nMeta"; public static final String W10N_CALLBACK = "w10nCallback"; public static final String W10N_FLATTEN = "w10nFlatten"; public static final String W10N_TRAVERSE = "w10nTraverse"; private static final Namespace BES_NS = opendap.namespaces.BES.BES_NS; public static final String ERRORS_CONTEXT = "errors"; public static final String XML_ERRORS = "xml"; public static final String DAP2_ERRORS = "dap2"; public static final String DAP4_ERRORS = "dap4"; public static final String JSON_ERRORS = "json"; public static final String XMLBASE_CONTEXT = "xml:base"; public static final String STORE_RESULT_CONTEXT = "store_result"; public static final String XDAP_ACCEPT_CONTEXT = "xdap_accept"; public static final String DEFAULT_XDAP_ACCEPT = "2.0"; public static final String EXPLICIT_CONTAINERS_CONTEXT = "dap_explicit_containers"; public static final String MAX_RESPONSE_SIZE_CONTEXT = "max_response_size"; public static final String _regexToMatchLastDotSuffixString = "\\.(?=[^.]*$).*$" ; /** * The name of the BES Exception Element. */ private static String BES_ERROR = "BESError"; private boolean _initialized = false; private Logger log; public BesApi() { super(); init(); log = org.slf4j.LoggerFactory.getLogger(this.getClass()); } /** * Initializes logging for the BesApi class. */ public void init() { if (_initialized) return; _initialized = true; } public boolean isInitialized(){ return _initialized; } public boolean isConfigured() { return BESManager.isConfigured(); } public Document getGroupVersionDocument(String path) throws Exception { return BESManager.getGroupVersionDocument(path); } public Document getCombinedVersionDocument() throws Exception { return BESManager.getCombinedVersionDocument(); } //public static void configure(OLFSConfig olfsConfig) throws Exception { // BESManager.configure(olfsConfig.getBESConfig()); /** * Writes an OPeNDAP DDX for the dataSource to the passed stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param xmlBase The request URL. * @param os The Stream to which to write the response. * @param err The Stream to which to errors returned by * the BES.. * @return False if the BES returns an error, true otherwise. * @throws opendap.bes.BadConfigurationException . * @throws opendap.bes.BESError . * @throws java.io.IOException . * @throws opendap.ppt.PPTException . */ public boolean writeDDX(String dataSource, String constraintExpression, String xdap_accept, String xmlBase, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDDXRequest(dataSource, constraintExpression, xdap_accept, xmlBase), os, err); } /** * Writes an OPeNDAP DAP4 DMR for the dataSource to the passed stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters associated with the request. * @param xmlBase The request URL. * @param os The Stream to which to write the response. * @param err The Stream to which to errors returned by * the BES.. * @return False if the BES returns an error, true otherwise. * @throws opendap.bes.BadConfigurationException . * @throws opendap.bes.BESError . * @throws java.io.IOException . * @throws opendap.ppt.PPTException . */ public boolean writeDMR(String dataSource, QueryParameters qp, String xmlBase, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDMRRequest(dataSource,qp,xmlBase), os, err); } /** * Writes an OPeNDAP DAP4 Data response for the dataSource to the passed stream. * * @param dataSource The requested DataSource * @param qp A DAP4 QueryParameters object generated by processing the request * @param xmlBase The request URL. * @param os The Stream to which to write the response. * @param err The Stream to which to errors returned by * the BES.. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws java.io.IOException . * @throws opendap.ppt.PPTException . */ public boolean writeDap4Data(String dataSource, QueryParameters qp, int maxResponseSize, String xmlBase, String contentID, String mimeBoundary, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4DataRequest(dataSource, qp, maxResponseSize, xmlBase, contentID, mimeBoundary), os, err); } public boolean getDDXDocument(String dataSource, String constraintExpression, String xdap_accept, String xmlBase, Document response) throws PPTException, BadConfigurationException, IOException, JDOMException, BESError { ByteArrayOutputStream ddxString = new ByteArrayOutputStream(); boolean ret = writeDDX(dataSource,constraintExpression,xdap_accept,xmlBase,ddxString,ddxString); SAXBuilder sb = new SAXBuilder(); Document ddx = sb.build(new ByteArrayInputStream(ddxString.toByteArray())); response.detachRootElement(); response.setRootElement(ddx.detachRootElement()); return ret; } public boolean getDMRDocument(String dataSource, QueryParameters qp, String xmlBase, Document response) throws PPTException, BadConfigurationException, IOException, JDOMException, BESError { ByteArrayOutputStream ddxString = new ByteArrayOutputStream(); boolean ret = writeDMR(dataSource,qp,xmlBase,ddxString,ddxString); SAXBuilder sb = new SAXBuilder(); Document ddx = sb.build(new ByteArrayInputStream(ddxString.toByteArray())); response.detachRootElement(); response.setRootElement(ddx.detachRootElement()); return ret; } /** * Writes an OPeNDAP DDS for the dataSource to the passed stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request. * @param xdap_accept The version of the DAP the BES is to use to package the * reponse. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDDS(String dataSource, String constraintExpression, String xdap_accept, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDDSRequest(dataSource, constraintExpression, xdap_accept), os, err); } /** * Writes the source data (it is often a file, thus the method name) to * the passed stream. * * @param dataSource The requested DataSource * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeFile(String dataSource, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getStreamRequest(dataSource), os, err); } /** * Writes an OPeNDAP DAS for the dataSource to the passed stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDAS(String dataSource, String constraintExpression, String xdap_accept, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDASRequest(dataSource,constraintExpression,xdap_accept), os, err); } /** * Writes an OPeNDAP DAP2 data response for the dataSource to the * passed stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2Data(String dataSource, String constraintExpression, String async, String storeResult, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2RequestDocument(DAP2_DATA, dataSource, constraintExpression, async, storeResult, xdap_accept, maxResponseSize, null, null, null, DAP2_ERRORS), os, err); } /** * Writes the NetCDF-3 file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsNetcdf3(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2DataAsNetcdf3Request(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF-3 file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters associated wih the request. ] * @param maxResponseSize * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4DataAsNetcdf3(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4DataAsNetcdf3Request(dataSource, qp, maxResponseSize), os, err); } /** * Writes the NetCDF-4 file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsNetcdf4(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2DataAsNetcdf4Request(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF-4 file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters associated wih the request. * @param maxResponseSize * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4DataAsNetcdf4(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4DataAsNetcdf4Request(dataSource, qp, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsXml(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, String xmlBase, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getXmlDataRequest(dataSource,constraintExpression,xdap_accept,maxResponseSize,xmlBase), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsGmlJpeg2000(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2DataAsGmlJpeg2000Request(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4DataAsGmlJpeg2000(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4DataAsGmlJpeg2000Request(dataSource, qp, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4DataAsJson(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4DataAsJsonRequest(dataSource, qp, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writePathInfoResponse(String dataSource, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getShowPathInfoRequestDocument(dataSource), os, err); } public boolean getPathInfoDocument(String dataSource,Document response) throws PPTException, BadConfigurationException, IOException, JDOMException, BESError { ByteArrayOutputStream pathInfoDocString = new ByteArrayOutputStream(); boolean ret = writePathInfoResponse(dataSource,pathInfoDocString,pathInfoDocString); SAXBuilder sb = new SAXBuilder(); Document pathInfoResponseDoc = sb.build(new ByteArrayInputStream(pathInfoDocString.toByteArray())); response.detachRootElement(); response.setRootElement(pathInfoResponseDoc.detachRootElement()); return ret; } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4DataAsGeoTiff(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4DataAsGeoTiffRequest(dataSource, qp, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4DataAsIjsn(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4IjsnDataRequest(dataSource, qp, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4DataAsXml(String dataSource, QueryParameters qp, int maxResponseSize, String xmlBase, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4RequestDocument(XML_DATA, dataSource, qp, maxResponseSize, xmlBase, null, null, XML_ERRORS), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query parameters submitted with the request. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4MetadataAsJson(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4JsonMetadataRequest(dataSource, qp, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query parameters submitted with the request. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4MetadataAsIjsn(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4IjsnMetadataRequest(dataSource, qp, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsIjsn(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2IjsnDataRequest(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2MetadataAsIjsn(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2IjsnMetadataRequest(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsJson(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2DataAsJsonRequest(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2MetadataAsJson(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2MetadataAsJsonRequest(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsW10nJson(String dataSource, String constraintExpression, String w10nMeta, String w10nCallback, boolean w10nFlatten, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2DataAsW10nJsonRequest(dataSource, constraintExpression, w10nMeta, w10nCallback, w10nFlatten, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2MetadataAsW10nJson(String dataSource, String constraintExpression, String w10nMeta, String w10nCallback, boolean w10nFlatten, boolean w10nTraverse, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2MetadataAsW10nJsonRequest(dataSource, constraintExpression, w10nMeta, w10nCallback, w10nFlatten, w10nTraverse, xdap_accept, maxResponseSize), os, err); } /** * Writes the NetCDF file out response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsGeoTiff(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2DataAsGeoTiffRequest(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the ASCII representation _rawOS the OPeNDAP data response for the * dataSource to the passed stream. * * @param dataSource The requested DataSource * @param constraintExpression The constraintElement expression to be applied to * the request.. * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2DataAsAscii(String dataSource, String constraintExpression, String xdap_accept, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap2DataAsAsciiRequest(dataSource, constraintExpression, xdap_accept, maxResponseSize), os, err); } /** * Writes the ASCII representation _rawOS the OPeNDAP data response for the * dataSource to the passed stream. * * @param dataSource The requested DataSource * @param qp The DAP4 query string parameters associated with the request. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap4DataAsCsv(String dataSource, QueryParameters qp, int maxResponseSize, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getDap4DataAsCsvRequest(dataSource, qp, maxResponseSize), os, err); } /** * Writes the HTML data request form (aka the I.F.H.) for the OPeNDAP the * dataSource to the passed stream. * * @param dataSource The requested DataSource * @param xdap_accept The version of the DAP to use in building the response. * @param url The URL to refernence in the HTML form. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned by the BES. * @return True is everything goes well, false if the BES returns an error. * @throws BadConfigurationException . * @throws PPTException . * @throws IOException . * @throws BESError . */ public boolean writeDap2DataRequestForm(String dataSource, String xdap_accept, String url, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getHtmlFormRequest(dataSource,xdap_accept,url), os, err); } /** * Writes the OPeNDAP INFO response for the dataSource to the passed * stream. * * @param dataSource The requested DataSource * @param xdap_accept The version of the DAP to use in building the response. * @param os The Stream to which to write the response. * @param err The Stream to which to write errors returned * by the BES. * @return False if the BES returns an error, true otherwise. * @throws BadConfigurationException . * @throws BESError . * @throws IOException . * @throws PPTException . */ public boolean writeDap2HtmlInfoPage(String dataSource, String xdap_accept, OutputStream os, OutputStream err) throws BadConfigurationException, BESError, IOException, PPTException { return besTransaction( dataSource, getHtmlInfoPageRequest(dataSource,xdap_accept), os, err); } /** * Returns the BES version document for the BES serving the passed * dataSource. * * @param dataSource The data source whose information is to be retrieved * @param response The document where the response (be it a catalog * document or an error) will be placed. * @return True if successful, false if the BES generated an error in * while servicing the request. * @throws PPTException . * @throws BadConfigurationException . * @throws IOException . * @throws JDOMException . */ public boolean getBesVersion(String dataSource, Document response) throws PPTException, BadConfigurationException, IOException, JDOMException { boolean ret = besTransaction(dataSource, showVersionRequest(),response); return ret; } /** * Returns the BES catalog document for the specified dataSource. * * @param dataSource The data source whose information is to be retrieved * @param response The document where the response (be it a catalog * document or an error) will be placed. * @return True if successful, false if the BES generated an error in * while servicing the request. * @throws PPTException . * @throws BadConfigurationException . * @throws IOException . * @throws JDOMException . */ public boolean getBesCatalog(String dataSource, Document response) throws PPTException, BadConfigurationException, IOException, JDOMException { Procedure timedProc = Timer.start(); try { boolean ret; String responseCacheKey = this.getClass().getName() + ".getCatalog(\"" + dataSource + "\")"; log.info("getCatalog(): Looking for cached copy of BES showCatalog response for responseCacheKey=\"" + responseCacheKey + "\""); Object o = RequestCache.get(responseCacheKey); if (o == null) { Document getCatalogRequest = showCatalogRequest(dataSource); ret = besTransaction(dataSource, getCatalogRequest, response); if (ret) { // Get the root element. Element root = response.getRootElement(); // Find the top level dataset Element Element topDataset = root.getChild("showCatalog", BES_NS).getChild("dataset", BES_NS); topDataset.setAttribute("prefix", getBESprefix(dataSource)); RequestCache.put(responseCacheKey, response.clone()); log.info("getCatalog(): Cached copy of BES showCatalog response for dataSource: \"" + dataSource + "\" (responseCacheKey=\"" + responseCacheKey + "\")"); } else { RequestCache.put(responseCacheKey, new NoSuchDatasource((Document) response.clone())); log.info("getInfo(): BES showInfo response failed, cached a NoSuchDatasource object. responseCacheKey=\"" + responseCacheKey + "\""); } return ret; } else { log.info("getCatalog(): Using cached copy of BES showCatalog. responseCacheKey=\"" + responseCacheKey + "\""); Document result; if (o instanceof NoSuchDatasource) { result = ((NoSuchDatasource) o).getErrDoc(); ret = false; } else { result = (Document) ((Document) o).clone(); ret = true; } Element root = result.getRootElement(); root.detach(); response.setRootElement(root); return ret; } } finally { Timer.stop(timedProc); } } /** * Returns the BES INFO document for the specified dataSource. * * @param dataSource The data source whose information is to be retrieved * @param response The document where the response (be it datasource * information or an error) will be placed. * @return True if successful, false if the BES generated an error in * while servicing the request. * @throws PPTException . * @throws BadConfigurationException . * @throws IOException . * @throws JDOMException . */ public boolean getInfo(String dataSource, Document response) throws PPTException, BadConfigurationException, IOException, JDOMException { Procedure timedProc = Timer.start(); try { boolean ret; String responseCacheKey = this.getClass().getName() + ".showInfo(\"" + dataSource + "\")"; log.info("getInfo(): Looking for cached copy of BES showInfo response for data source: \"" + Scrub.urlContent(dataSource) + "\" (responseCacheKey=\"" + Scrub.urlContent(responseCacheKey) + "\")"); Object o = RequestCache.get(responseCacheKey); if (o == null) { log.info("getInfo(): Copy of BES showInfo for responseCacheKey=\"" + Scrub.urlContent(responseCacheKey) + "\" not found in cache."); Document request = showInfoRequest(dataSource); ret = besTransaction(dataSource, request, response); if (ret) { // Get the root element. Element responseElement = response.getRootElement(); // Find the top level dataset Element Element topDataset = responseElement.getChild("showInfo", BES_NS).getChild("dataset", BES_NS); // Add the prefix attribute for this BES. topDataset.setAttribute("prefix", getBESprefix(dataSource)); RequestCache.put(responseCacheKey, response.clone()); log.info("getInfo(): Cached copy of BES showInfo response. responseCacheKey=\"" + Scrub.urlContent(responseCacheKey) + "\""); } else { RequestCache.put(responseCacheKey, new NoSuchDatasource((Document) response.clone())); log.info("getInfo(): BES showInfo response failed, cached the BES (error) response Document. responseCacheKey=\"" + Scrub.urlContent(responseCacheKey) + "\""); } } else { log.info("getInfo(): Using cached copy of BES showInfo. responseCacheKey=\"" + Scrub.urlContent(responseCacheKey) + "\" returned an object of type " + o.getClass().getName()); Document result; if (o instanceof NoSuchDatasource) { result = ((NoSuchDatasource) o).getErrDoc(); ret = false; } else { result = (Document) ((Document) o).clone(); ret = true; } Element root = result.getRootElement(); root.detach(); response.setRootElement(root); } return ret; } finally { Timer.stop(timedProc); } } public static class NoSuchDatasource { Document err; public NoSuchDatasource(Document besError){ err = besError; } public Document getErrDoc(){ return (Document)err.clone(); } } /** * Executes a command/response transaction with the BES * * @param dataSource The BES datasource that is going to be acccessed. This is used to determine which BES should * be used to fulfill the request (In the event that Hyrax is configured to use multiple BESs this string will * be used to locate the appropriate BES). * @param request The BES request document. * @param response The document into which the BES response will be placed. If the passed Document object contains * conent, then the content will be discarded. * @return true if the request is successful, false if there is a problem fulfilling the request. * @throws IOException * @throws PPTException * @throws BadConfigurationException * @throws JDOMException */ public boolean besTransaction( String dataSource, Document request, Document response ) throws IOException, PPTException, BadConfigurationException, JDOMException { log.debug("besTransaction started."); log.debug("besTransaction() request document: \n BES bes = BESManager.getBES(dataSource); return bes.besTransaction(request,response); } /** * Executes a command/response transaction with the BES * * @param dataSource The BES datasource that is going to be acccessed. This is used to determine which BES should * be used to fulfill the request (In the event that Hyrax is configured to use multiple BESs this string will * be used to locate the appropriate BES). * @param request The BES request document. * @param os The outputstream to write the BES response to. * @param err The output stream to which BES errors should be written * @return true if the request is successful, false if there is a problem fulfilling the request. If false, then * any error information will be written to the OutputStream err. * @throws BadConfigurationException * @throws IOException * @throws PPTException */ public boolean besTransaction(String dataSource, Document request, OutputStream os, OutputStream err) throws BadConfigurationException, IOException, PPTException { log.debug("besTransaction() started."); log.debug("besTransaction() request document: \n BES bes = BESManager.getBES(dataSource); return bes.besTransaction(request, os, err); } public Element setContainerElement(String name, String space, String source, String type) { Element e = new Element("setContainer",BES_NS); e.setAttribute("name",name); e.setAttribute("space",space); if(type.equals(STREAM)) e.setAttribute("type",type); e.setText(source); return e; } public Element defineElement(String name, String space) { Element e = new Element("define",BES_NS); e.setAttribute("name",name); e.setAttribute("space",space); return e; } public Element containerElement(String name) { Element e = new Element("container",BES_NS); e.setAttribute("name",name); return e; } public Element constraintElement(String ce) { Element e = new Element("constraint",BES_NS); e.setText(ce); return e; } public Element dap4ConstraintElement(String ce) { Element e = new Element("dap4constraint",BES_NS); e.setText(ce); return e; } public Element dap4FunctionElement(String dap4_function) { Element e = new Element("dap4function",BES_NS); e.setText(dap4_function); return e; } public Element getElement(String type, String definition, String url, String returnAs ) { return getElement(type,definition,url,returnAs,null,null); } public Element getElement(String type, String definition, String url, String returnAs, String async, String storeResult ) { Element e = new Element("get",BES_NS); e.setAttribute("type",type); e.setAttribute("definition",definition); if(url!=null) e.setAttribute("url",url); if(returnAs!=null) e.setAttribute("returnAs",returnAs); if(async!=null) e.setAttribute("async",async); if(storeResult!=null) e.setAttribute("store_result",storeResult); return e; } public Element setContextElement(String name, String value) { Element e = new Element("setContext",BES_NS); e.setAttribute("name",name); e.setText(value); return e; } /** * Returns the DDX request document for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDX is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the dap that should be used to build the * response. * @param xmlBase The request URL. * @return The DDX request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDDXRequest(String dataSource, String ce, String xdap_accept, String xmlBase) throws BadConfigurationException { return getDap2RequestDocument(DDX, dataSource, ce, xdap_accept, 0, xmlBase, null, null, XML_ERRORS); } /** * Returns the DDX request document for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDX is being requested * @param qp The DAP4 query string parameters associated wih the request.. * response. * @param xmlBase The request URL. * @return The DDX request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDMRRequest(String dataSource, QueryParameters qp, String xmlBase) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DMR, dataSource, qp, 0, xmlBase, null, null, XML_ERRORS); } /** * Returns the DDX request document for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDX is being requested * @param qp The DAP4 QueryParameters ingested from the client request. * response. * @param xmlBase The request URL. * @return The DDX request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap4DataRequest(String dataSource, QueryParameters qp, int maxResponseSize, String xmlBase, String contentID, String mimeBoundary) throws BadConfigurationException { Document reqDoc = getDap4RequestDocument( DAP4_DATA, dataSource, qp, maxResponseSize, xmlBase, null, null, XML_ERRORS); Element req = reqDoc.getRootElement(); Element getReq = req.getChild("get",BES_NS); Element e = new Element("contentStartId",BES_NS); e.setText(contentID); getReq.addContent(e); e = new Element("mimeBoundary",BES_NS); e.setText(mimeBoundary); getReq.addContent(e); return reqDoc; } /** * Returns the DDS request document for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDDSRequest(String dataSource, String ce, String xdap_accept) throws BadConfigurationException { return getDap2RequestDocument(DDS, dataSource, ce, xdap_accept, 0, null, null, null, DAP2_ERRORS); } public Document getDASRequest(String dataSource, String ce, String xdap_accept) throws BadConfigurationException { return getDap2RequestDocument(DAS, dataSource, ce, xdap_accept, 0, null, null, null, DAP2_ERRORS); } public Document getDap2DataAsAsciiRequest(String dataSource, String ce, String xdap_accept, int maxResponseSize) throws BadConfigurationException { // return getDap2RequestDocument(ASCII, dataSource, ce, xdap_accept, maxResponseSize, null, null, null, XML_ERRORS); return getDap2RequestDocument(DAP2_DATA, dataSource, ce, xdap_accept, maxResponseSize, null, null, ASCII, XML_ERRORS); } public Document getDap4DataAsCsvRequest(String dataSource, QueryParameters qp, int maxResponseSize) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DATA, dataSource, qp, maxResponseSize, null, null, CSV, XML_ERRORS); } public Document getHtmlFormRequest(String dataSource, String xdap_accept, String URL) throws BadConfigurationException { return getDap2RequestDocument(HTML_FORM, dataSource, null, xdap_accept, 0, null, URL, null, XML_ERRORS); } public Document getStreamRequest(String dataSource) throws BadConfigurationException{ return getDap2RequestDocument(STREAM, dataSource, null, null, 0, null, null, null, XML_ERRORS); } public Document getHtmlInfoPageRequest(String dataSource, String xdap_accept) throws BadConfigurationException { return getDap2RequestDocument(INFO_PAGE, dataSource, null, xdap_accept, 0, null, null, null, XML_ERRORS); } public Document getDap2DataAsNetcdf3Request(String dataSource, String ce, String xdap_accept, int maxResponseSize) throws BadConfigurationException { return getDap2RequestDocument(DAP2_DATA, dataSource, ce, xdap_accept, maxResponseSize, null, null, NETCDF_3, DAP2_ERRORS); } public Document getDap4DataAsNetcdf3Request(String dataSource, QueryParameters qp, int maxResponseSize) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DATA, dataSource, qp, maxResponseSize, null, null, NETCDF_3, DAP4_ERRORS); } public Document getDap2DataAsNetcdf4Request(String dataSource, String ce, String xdap_accept, int maxResponseSize) throws BadConfigurationException { return getDap2RequestDocument(DAP2_DATA, dataSource, ce, xdap_accept, maxResponseSize, null, null, NETCDF_4, DAP2_ERRORS); } public Document getDap4DataAsNetcdf4Request(String dataSource, QueryParameters qp, int maxResponseSize) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DATA, dataSource, qp, maxResponseSize, null, null, NETCDF_4, DAP4_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getXmlDataRequest(String dataSource, String ce, String xdap_accept, int maxResponseSize, String xmlBase) throws BadConfigurationException { return getDap2RequestDocument(XML_DATA, dataSource, ce, xdap_accept, maxResponseSize, xmlBase, null, null, XML_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap2DataAsGmlJpeg2000Request(String dataSource, String ce, String xdap_accept, int maxResponseSize) throws BadConfigurationException { return getDap2RequestDocument(DAP2_DATA, dataSource, ce, xdap_accept, maxResponseSize, null, null, GMLJP2, XML_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap2DataAsGeoTiffRequest(String dataSource, String ce, String xdap_accept, int maxResponseSize) throws BadConfigurationException { return getDap2RequestDocument(DAP2_DATA, dataSource, ce, xdap_accept, maxResponseSize, null, null, GEOTIFF, DAP2_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param qp The DAP4 query string parameters associated wih the request. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap4DataAsGeoTiffRequest(String dataSource, QueryParameters qp, int maxResponseSize ) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DATA, dataSource, qp, maxResponseSize, null, null, GEOTIFF, DAP4_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param qp The DAP4 query string parameters associated wih the request. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap4DataAsGmlJpeg2000Request(String dataSource, QueryParameters qp, int maxResponseSize ) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DATA, dataSource, qp, maxResponseSize, null, null, GMLJP2, DAP4_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap2DataAsJsonRequest(String dataSource, String ce, String xdap_accept, int maxResponseSize) throws BadConfigurationException { return getDap2RequestDocument(DAP2_DATA, dataSource, ce, xdap_accept, maxResponseSize, null, null, JSON, JSON_ERRORS); } /** * Returns the JSON encoded DAP2 Metadata response (DDX) for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The DAP2 query string parameters associated wih the request. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap2MetadataAsJsonRequest(String dataSource, String ce, String xdap_accept, int maxResponseSize ) throws BadConfigurationException { return getDap2RequestDocument(DDX, dataSource, ce, xdap_accept, maxResponseSize, null, null, JSON, JSON_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap2DataAsW10nJsonRequest(String dataSource, String ce, String w10nMeta, String w10nCallback, boolean w10nFlatten, String xdap_accept, int maxResponseSize) throws BadConfigurationException { Document requestDoc = getDap2RequestDocument(DAP2_DATA, dataSource, ce, xdap_accept, maxResponseSize, null, null, W10N, JSON_ERRORS); if(w10nMeta!=null) requestDoc.getRootElement().addContent(1,setContextElement(W10N_META,w10nMeta)); if(w10nCallback!=null) requestDoc.getRootElement().addContent(1,setContextElement(W10N_CALLBACK,w10nCallback)); if(w10nFlatten) requestDoc.getRootElement().addContent(1,setContextElement(W10N_FLATTEN,"true")); return requestDoc; } /** * Returns the JSON encoded DAP2 Metadata response (DDX) for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The DAP2 query string parameters associated wih the request. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap2MetadataAsW10nJsonRequest(String dataSource, String ce, String w10nMeta, String w10nCallback, boolean w10nFlatten, boolean w10nTraverse, String xdap_accept, int maxResponseSize ) throws BadConfigurationException { Document requestDoc = getDap2RequestDocument(DDX, dataSource, ce, xdap_accept, maxResponseSize, null, null, W10N, JSON_ERRORS); if(w10nMeta!=null) requestDoc.getRootElement().addContent(1,setContextElement(W10N_META,w10nMeta)); if(w10nCallback!=null) requestDoc.getRootElement().addContent(1,setContextElement(W10N_CALLBACK,w10nCallback)); if(w10nFlatten) requestDoc.getRootElement().addContent(1,setContextElement(W10N_FLATTEN,"true")); if(w10nTraverse) requestDoc.getRootElement().addContent(1,setContextElement(W10N_TRAVERSE,"true")); return requestDoc; } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param qp The DAP4 query string parameters associated wih the request. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap4DataAsJsonRequest(String dataSource, QueryParameters qp, int maxResponseSize ) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DATA, dataSource, qp, maxResponseSize, null, null, JSON, JSON_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param qp The DAP4 query string parameters associated wih the request. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap4IjsnDataRequest(String dataSource, QueryParameters qp, int maxResponseSize ) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DATA, dataSource, qp, maxResponseSize, null, null, IJSON, JSON_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param qp The DAP4 query string parameters associated wih the request. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap4JsonMetadataRequest(String dataSource, QueryParameters qp, int maxResponseSize) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DMR, dataSource, qp, maxResponseSize, null, null, JSON, JSON_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param qp The DAP4 query string parameters associated wih the request. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap4IjsnMetadataRequest(String dataSource, QueryParameters qp, int maxResponseSize) throws BadConfigurationException { return getDap4RequestDocument(DAP4_DMR, dataSource, qp, maxResponseSize, null, null, IJSON, JSON_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap2IjsnDataRequest(String dataSource, String ce, String xdap_accept, int maxResponseSize) throws BadConfigurationException { return getDap2RequestDocument(DAP2_DATA, dataSource, ce, xdap_accept, maxResponseSize, null, null, IJSON, JSON_ERRORS); } /** * Returns the XML data response for the passed dataSource * using the passed constraint expression. * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize Maximum allowable response size. * @return The DDS request document. * @throws BadConfigurationException When no BES can be found to * service the request. */ public Document getDap2IjsnMetadataRequest(String dataSource, String ce, String xdap_accept, int maxResponseSize) throws BadConfigurationException { return getDap2RequestDocument(DDX, dataSource, ce, xdap_accept, maxResponseSize, null, null, IJSON, JSON_ERRORS); } /** * Returns a BES Request document. * @param type * @param dataSource The data set whose DDS is being requested * @param ce The constraint expression to apply. * @param xdap_accept The version of the DAP to use in building the response. * @param maxResponseSize Maximum allowable response size. * @param xmlBase * @param formURL * @param returnAs * @param errorContext * @return * @throws BadConfigurationException */ public Document getDap2RequestDocument(String type, String dataSource, String ce, String xdap_accept, int maxResponseSize, String xmlBase, String formURL, String returnAs, String errorContext) throws BadConfigurationException { return getDap2RequestDocument(type, dataSource,ce, null, null, xdap_accept, maxResponseSize, xmlBase, formURL, returnAs, errorContext); } public Document getDap2RequestDocument(String type, String dataSource, String ce, String async, String storeResult, String xdap_accept, int maxResponseSize, String xmlBase, String formURL, String returnAs, String errorContext) throws BadConfigurationException { String besDataSource = getBES(dataSource).trimPrefix(dataSource); Element e, request = new Element("request", BES_NS); String reqID = Thread.currentThread().getName()+":"+ Thread.currentThread().getId(); request.setAttribute("reqID",reqID); if(xdap_accept!=null) request.addContent(setContextElement(XDAP_ACCEPT_CONTEXT,xdap_accept)); else request.addContent(setContextElement(XDAP_ACCEPT_CONTEXT, DEFAULT_XDAP_ACCEPT)); request.addContent(setContextElement(EXPLICIT_CONTAINERS_CONTEXT,"no")); request.addContent(setContextElement(ERRORS_CONTEXT,errorContext)); if(xmlBase!=null) request.addContent(setContextElement(XMLBASE_CONTEXT,xmlBase)); if(maxResponseSize>=0) request.addContent(setContextElement(MAX_RESPONSE_SIZE_CONTEXT,maxResponseSize+"")); request.addContent(setContainerElement("catalogContainer","catalog",besDataSource,type)); Element def = defineElement("d1","default"); e = (containerElement("catalogContainer")); if(ce!=null && !ce.equals("")) e.addContent(constraintElement(ce)); def.addContent(e); request.addContent(def); e = getElement(type,"d1",formURL,returnAs,async,storeResult); request.addContent(e); return new Document(request); } public Document getDap4RequestDocument(String type, String dataSource, QueryParameters qp, int maxResponseSize, String xmlBase, String formURL, String returnAs, String errorContext) throws BadConfigurationException { String besDataSource = getBES(dataSource).trimPrefix(dataSource); Element e, request = new Element("request", BES_NS); String reqID = Thread.currentThread().getName()+":"+ Thread.currentThread().getId(); request.setAttribute("reqID",reqID); request.addContent(setContextElement(EXPLICIT_CONTAINERS_CONTEXT,"no")); request.addContent(setContextElement(ERRORS_CONTEXT,errorContext)); if(xmlBase!=null) request.addContent(setContextElement(XMLBASE_CONTEXT,xmlBase)); if(maxResponseSize>=0) request.addContent(setContextElement(MAX_RESPONSE_SIZE_CONTEXT,maxResponseSize+"")); request.addContent(setContainerElement("catalogContainer","catalog",besDataSource,type)); Element def = defineElement("d1","default"); e = (containerElement("catalogContainer")); if(qp.getCe()!=null && !qp.getCe().equals("")) e.addContent(dap4ConstraintElement(qp.getCe())); if(qp.getFunc()!=null && !qp.getFunc().equals("")) e.addContent(dap4FunctionElement(qp.getFunc())); def.addContent(e); request.addContent(def); e = getElement(type,"d1",formURL,returnAs,qp.getAsync(),qp.getStoreResultRequestServiceUrl()); request.addContent(e); return new Document(request); } public Document getShowPathInfoRequestDocument(String dataSource) throws BadConfigurationException { String besDataSource = getBES(dataSource).trimPrefix(dataSource); Element request = new Element("request", BES_NS); String reqID = "["+Thread.currentThread().getName()+":"+ Thread.currentThread().getId()+":bes_request]"; request.setAttribute("reqID",reqID); request.addContent(setContextElement(EXPLICIT_CONTAINERS_CONTEXT,"no")); request.addContent(setContextElement(ERRORS_CONTEXT,XML_ERRORS)); //request.addContent(w10nRequestElement(besDataSource,queryString,mediaType,maxResponseSize)); request.addContent(showPathInfoRequestElement(besDataSource)); XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); log.debug("getShowPathInfoRequestDocument() - Document\n {}",xmlo.outputString(request)); return new Document(request); } public Element showPathInfoRequestElement(String resource) { Element e; Element spi = new Element("showPathInfo",BES_NS); spi.setAttribute("node", resource); return spi; } public Document showVersionRequest() throws BadConfigurationException { return showRequestDocument("showVersion",null); } public Document showCatalogRequest(String dataSource) throws BadConfigurationException { return showRequestDocument("showCatalog",dataSource); } public Document showInfoRequest(String dataSource) throws BadConfigurationException { return showRequestDocument("showInfo",dataSource); } public Document showRequestDocument(String type, String dataSource) throws BadConfigurationException { Element e, request = new Element("request", BES_NS); String reqID = "["+Thread.currentThread().getName()+":"+ Thread.currentThread().getId()+":bes_request]"; request.setAttribute("reqID",reqID); request.addContent(setContextElement(ERRORS_CONTEXT,XML_ERRORS)); e = new Element(type,BES_NS); if(dataSource!=null){ String besDataSource = getBES(dataSource).trimPrefix(dataSource); e.setAttribute("node",besDataSource); } request.addContent(e); return new Document(request); } public BES getBES(String dataSource) throws BadConfigurationException { BES bes = BESManager.getBES(dataSource); return bes; } public String getBESprefix(String dataSource) throws BadConfigurationException { BES bes = BESManager.getBES(dataSource); return bes.getPrefix(); } void showRequest(Document request, OutputStream os) throws IOException{ XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); xmlo.output(request, os); } String showRequest(Document request) throws IOException{ XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); return xmlo.outputString(request); } public String getBesDataSourceID(String relativeUrl, boolean checkWithBes){ Pattern lastDotSuffixPattern= Pattern.compile(_regexToMatchLastDotSuffixString); return getBesDataSourceID(relativeUrl,lastDotSuffixPattern,checkWithBes); } public String getBesDataSourceID(String relativeUrl, Pattern matchPattern, boolean checkWithBes){ log.debug("getBesDataSourceID() - relativeUrl: " + relativeUrl); Matcher suffixMatcher = matchPattern.matcher(relativeUrl); boolean suffixMatched = false; while(!suffixMatcher.hitEnd()){ suffixMatched = suffixMatcher.find(); //log.debug("{}", Util.checkRegex(suffixMatcher, suffixMatched)); } String besDataSourceId = null; if(suffixMatched){ int start = suffixMatcher.start(); besDataSourceId = relativeUrl.substring(0,start); if(checkWithBes){ log.debug("Asking BES about resource: {}", besDataSourceId); try { ResourceInfo dsi = new BESResource(besDataSourceId, this); if (!dsi.isDataset()) { besDataSourceId = null; } } catch (Exception e) { log.debug("matches() failed with an Exception. Msg: '{}'", e.getMessage()); } } } log.debug("getBesDataSourceID() - besDataSourceId: " + besDataSourceId); return besDataSourceId; } }
package simpleserver.stream; import static simpleserver.lang.Translations.t; import static simpleserver.util.Util.print; import static simpleserver.util.Util.println; import java.io.*; import java.nio.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javassist.bytecode.ByteArray; import simpleserver.*; import simpleserver.Authenticator.AuthRequest; import simpleserver.Coordinate.Dimension; import simpleserver.command.PlayerListCommand; import simpleserver.config.data.Chests.Chest; import simpleserver.config.xml.Config.BlockPermission; import simpleserver.message.Message; import simpleserver.message.MessagePacket; public class StreamTunnel { private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING"); private static final int IDLE_TIME = 30000; private static final int BUFFER_SIZE = 1024; private static final byte BLOCK_DESTROYED_STATUS = 2; private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$"); private static final Pattern COLOR_PATTERN = Pattern.compile("\u00a7[0-9a-z]"); private static final Pattern JOIN_PATTERN = Pattern.compile("\u00a7.((\\d|\\w|\\u00a7)*) (joined|left) the game."); private static final String CONSOLE_CHAT_PATTERN = "\\[Server:.*\\]"; private static final int MESSAGE_SIZE = 360; private static final int MAXIMUM_MESSAGE_SIZE = 119; private static final int STATE_HANDSHAKE = 0; private static final int STATE_STATUS = 1; private static final int STATE_LOGIN = 2; private static final int STATE_PLAY = 3; private final boolean isServerTunnel; private final String streamType; private final Player player; private final Server server; private final byte[] buffer; private final Tunneler tunneler; private DataInput in; private DataOutput out; private InputStream inputStream; private OutputStream outputStream; private StreamDumper inputDumper; private StreamDumper outputDumper; private boolean inGame = false; private volatile long lastRead; private volatile boolean run = true; private Byte lastPacket; private char commandPrefix; private int state = 0; private boolean readyToSend = false; private ByteBuffer incoming = null; private ByteBuffer outgoing = null; public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel, Player player) { this.isServerTunnel = isServerTunnel; if (isServerTunnel) { streamType = "ServerStream"; } else { streamType = "PlayerStream"; } this.player = player; server = player.getServer(); commandPrefix = server.options.getBoolean("useSlashes") ? '/' : '!'; inputStream = in; outputStream = out; DataInputStream dIn = new DataInputStream(in); DataOutputStream dOut = new DataOutputStream(out); if (EXPENSIVE_DEBUG_LOGGING) { try { OutputStream dump = new FileOutputStream(streamType + "Input.debug"); InputStreamDumper dumper = new InputStreamDumper(dIn, dump); inputDumper = dumper; this.in = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open input debug dump!"); throw new RuntimeException(e); } try { OutputStream dump = new FileOutputStream(streamType + "Output.debug"); OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump); outputDumper = dumper; this.out = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open output debug dump!"); throw new RuntimeException(e); } } else { this.in = dIn; this.out = dOut; } buffer = new byte[BUFFER_SIZE]; tunneler = new Tunneler(); tunneler.start(); lastRead = System.currentTimeMillis(); } public void stop() { run = false; } public void setState(int i) { state = i; } public boolean isAlive() { return tunneler.isAlive(); } public boolean isActive() { return System.currentTimeMillis() - lastRead < IDLE_TIME || player.isRobot(); } private void handlePacket() throws IOException { int length = decodeVarInt(); readyToSend = false; // read length into byte[], copy into ByteBuffer byte[] buf = new byte[length]; in.readFully(buf, 0, length); incoming = ByteBuffer.wrap(buf); outgoing = ByteBuffer.allocate(length * 2); Byte packetId = (byte) decodeVarInt(); //System.out.println("state:" + state + (isServerTunnel ? " server " : " client ") + //String.format("%02x", packetId) + " length: " + length); if (state == STATE_HANDSHAKE) { if (!isServerTunnel) { add(packetId); copyVarInt(); add(readUTF8()); copyUnsignedShort(); state = decodeVarInt(); player.setState(state); addVarInt(state); } } else if (state == STATE_STATUS) { switch(packetId) { case 0x00: // JSON Response add(packetId); if (isServerTunnel) { add(readUTF8()); // @todo handle changing of max-player, server name, etc. } break; case 0x01: // Ping add(packetId); add(incoming.getLong()); break; } } else if (state == STATE_LOGIN) { switch(packetId) { case 0x00: // Disconnect / Login Start add(packetId); add(readUTF8()); break; case 0x01: // Encryption Request / Response if (isServerTunnel) { add(packetId); tunneler.setName(streamType + "-" + player.getUuid()); String serverId = readUTF8(); if (!server.authenticator.useCustAuth(player)) { serverId = "-"; } else { serverId = player.getConnectionHash(); } add(serverId); byte[] keyBytes = new byte[incoming.getShort()]; incoming.put(keyBytes); byte[] challengeToken = new byte[incoming.getShort()]; incoming.put(challengeToken); player.serverEncryption.setPublicKey(keyBytes); byte[] key = player.clientEncryption.getPublicKey(); add((short) key.length); add(key); add((short) challengeToken.length); add(challengeToken); player.serverEncryption.setChallengeToken(challengeToken); player.clientEncryption.setChallengeToken(challengeToken); } else { byte[] sharedKey = new byte[incoming.getShort()]; incoming.put(sharedKey); byte[] challengeTokenResponse = new byte[incoming.getShort()]; incoming.put(challengeTokenResponse); if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) { player.kick("Invalid client response"); break; } player.clientEncryption.setEncryptedSharedKey(sharedKey); sharedKey = player.serverEncryption.getEncryptedSharedKey(); if (server.authenticator.useCustAuth(player) && !server.authenticator.onlineAuthenticate(player)) { player.kick(t("%s Failed to login: User not premium", "[CustAuth]")); break; } add(packetId); add((short) sharedKey.length); add(sharedKey); challengeTokenResponse = player.serverEncryption.encryptChallengeToken(); add((short) challengeTokenResponse.length); add(challengeTokenResponse); in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream))); } break; case 0x02: // Login Success add(packetId); String uuid = readUTF8(); String name = readUTF8(); boolean nameSet = false; if (name.contains(";")) { name = name.substring(0, name.indexOf(";")); } if (name.equals("Player") || !server.authenticator.isMinecraftUp) { AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress()); if (req != null) { name = req.playerName; nameSet = server.authenticator.completeLogin(req, player); } if (req == null || !nameSet) { if (!name.equals("Player")) { player.addTMessage(Color.RED, "Login verification failed."); player.addTMessage(Color.RED, "You were logged in as guest."); } name = server.authenticator.getFreeGuestName(); player.setGuest(true); nameSet = player.setName(name); } } else { nameSet = player.setName(name); if (nameSet) { player.updateRealName(name); } } if (player.isGuest() && !server.authenticator.allowGuestJoin()) { player.kick(t("Failed to login: User not authenticated")); nameSet = false; } tunneler.setName(streamType + "-" + player.getName()); player.setUuid(uuid); player.setState(3); add(uuid); add(player.getName()); break; } } else if (state == STATE_PLAY) { int x, z; byte y, dimension; Coordinate coordinate; switch(packetId) { case 0x00: // Keep-Alive add(packetId); add(incoming.getInt()); break; case 0x01: // Join-Game / Chat-Message if (isServerTunnel) { add(packetId); player.setEntityId(add(incoming.getInt())); copyUnsignedByte(); dimension = incoming.get(); add(dimension); copyUnsignedByte(); readUnsignedByte(); addUnsignedByte(server.config.properties.getInt("maxPlayers")); add(readUTF8()); } else { String message = readUTF8(); if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addTMessage(Color.RED, "You are muted! You may not send messages to all players."); break; } if (message.charAt(0) == commandPrefix) { message = player.parseCommand(message, false); if (message == null) { break; } add(message); return; } player.sendMessage(message); } break; case 0x02: // Chat-Message / Use Entity add(packetId); if (isServerTunnel) { String message = readUTF8(); MessagePacket messagePacket = new Message().decodeMessage(message); if (messagePacket == null) { if (server.config.properties.getBoolean("useMsgFormats")) { if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) { break; } Matcher colorMatcher = COLOR_PATTERN.matcher(message); String cleanMessage = colorMatcher.replaceAll(""); Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage); if (messageMatcher.find()) { } else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) { break; } // @todo bring msgWrap back sendMessage(message); add(message); } } else { // we have a json object if (messagePacket.isJoinedPacket()) { String username = messagePacket.getJoinedUsername(); if (server.bots.ninja(username)) { break; } if (message.contains("join")) { player.addTMessage(Color.YELLOW, "%s joined the game.", username); } else { player.addTMessage(Color.YELLOW, "%s left the game.", username); } break; } else { add(message); } } } else { add(incoming.getInt()); add(incoming.get()); } break; case 0x03: // Time-Update / Player add(packetId); if (isServerTunnel) { add(incoming.getLong()); long time = incoming.getLong(); server.setTime(time); add(time); } else { add(incoming.get()); } break; case 0x04: // Entity-Equipment / Player Position add(packetId); if (isServerTunnel) { add(incoming.getInt()); add(incoming.getShort()); copyItem(); } else { copyPlayerPosition(true, true); } break; case 0x05: // Spawn Position / Player Look add(packetId); if (isServerTunnel) { add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); if (server.options.getBoolean("enableEvents")) { server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null); } } else { add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.get()); } break; case 0x06: // Update Health / Player Position & Look add(packetId); if (isServerTunnel) { player.updateHealth(add(incoming.getFloat())); player.getHealth(); add(incoming.getShort()); add(incoming.getFloat()); } else { copyPlayerPosition(false, true); copyPlayerLook(true); } break; case 0x07: // Respawn / Player Digging if (isServerTunnel) { add(packetId); player.setDimension(Dimension.get(add(incoming.getInt()))); copyUnsignedByte(); copyUnsignedByte(); add(readUTF8()); if (server.options.getBoolean("enableEvents") && isServerTunnel) { server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null); } } else { byte status = incoming.get(); x = incoming.getInt(); y = incoming.get(); z = incoming.getInt(); byte face = incoming.get(); coordinate = new Coordinate(x, y, z, player); if (!player.getGroup().ignoreAreas) { BlockPermission perm = server.config.blockPermission(player, coordinate); if (!perm.use && status == 0) { player.addTMessage(Color.RED, "You can not use this block here!"); break; } if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) { player.addTMessage(Color.RED, "You can not destroy this block!"); break; } } boolean locked = server.data.chests.isLocked(coordinate); if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) { if (locked && status == BLOCK_DESTROYED_STATUS) { server.data.chests.releaseLock(coordinate); server.data.save(); } add(packetId); add(status); add(x); add(y); add(z); add(face); if (player.instantDestroyEnabled()) { // @todo fix instant destroy //packetFinished(); //add(packetId); //add(BLOCK_DESTROYED_STATUS); //add(x); //add(y); //add(z); //add(face); } if (status == BLOCK_DESTROYED_STATUS) { player.destroyedBlock(); } } } break; case 0x08: // Player Position & Look / Player Block Placement if (isServerTunnel) { add(packetId); copyPlayerPosition(false, false); copyPlayerLook(true); } else { x = incoming.getInt(); y = (byte) readUnsignedByte(); z = incoming.getInt(); coordinate = new Coordinate(x, y, z, player); final byte direction = incoming.get(); final short dropItem = incoming.getShort(); byte itemCount = 0; short uses = 0; byte[] data = null; if (dropItem != -1) { itemCount = incoming.get(); uses = incoming.getShort(); short dataLength = incoming.getShort(); if (dataLength != -1) { data = new byte[dataLength]; incoming.get(data); } } byte blockX = incoming.get(); byte blockY = incoming.get(); byte blockZ = incoming.get(); boolean writePacket = true; boolean drop = false; BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem); if (server.options.getBoolean("enableEvents")) { player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0))); } if (server.data.chests.isChest(coordinate)) { // continue } else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) { if (!perm.use) { player.addTMessage(Color.RED, "You can not use this block here!"); } else { player.addTMessage(Color.RED, "You can not place this block here!"); } writePacket = false; drop = true; } else if (dropItem == 54) { int xPosition = x; byte yPosition = y; int zPosition = z; switch (direction) { case 0: --yPosition; break; case 1: ++yPosition; break; case 2: --zPosition; break; case 3: ++zPosition; break; case 4: --xPosition; break; case 5: ++xPosition; break; } Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player); Chest adjacentChest = server.data.chests.adjacentChest(targetBlock); if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) { player.addTMessage(Color.RED, "The adjacent chest is locked!"); writePacket = false; drop = true; } else { player.placingChest(targetBlock); } } if (writePacket) { add(packetId); add(x); addUnsignedByte(y); add(z); add(direction); add(dropItem); if (dropItem != -1) { add(itemCount); add(uses); if (data != null) { add((short) data.length); add(data); } else { add((short) -1); } if (dropItem <= 94 && direction >= 0) { player.placedBlock(); } } add(blockX); add(blockY); add(blockZ); player.openingChest(coordinate); } else if (drop) { // Drop the item in hand. This keeps the client state in-sync with the // server. This generally prevents empty-hand clicks by the client // from placing blocks the server thinks the client has in hand. //add((byte) 0x0e); // @todo figure out how to drop items in new protocol //add((byte) 0x04); //add(x); //add(y); //add(z); //add(direction); } } break; case 0x09: // Held Item Change / Held Item Change add(packetId); if (isServerTunnel) { add(incoming.get()); } else { add(incoming.getShort()); } break; case 0x0A: // Animation / Use Bed add(packetId); if (!isServerTunnel) { add(incoming.getInt()); add(incoming.get()); } else { add(incoming.getInt()); add(incoming.getInt()); copyUnsignedByte(); add(incoming.getInt()); } break; case 0x0B: // Entity Action / Animation add(packetId); if (!isServerTunnel) { add(incoming.getInt()); add(incoming.get()); add(incoming.getInt()); } else { copyVarInt(); copyUnsignedByte(); } break; case 0x0C: // Steer Vehicle / Spawn Player add(packetId); if (!isServerTunnel) { add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.get()); add(incoming.get()); } else { copyVarInt(); add(readUTF8()); add(readUTF8()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); add(incoming.get()); add(incoming.getShort()); copyEntityMetadata(); } break; case 0x0D: // Close Window / Collect Item add(packetId); if (!isServerTunnel) { add(incoming.get()); } else { add(incoming.getInt()); add(incoming.getInt()); } break; case 0x0E: // Click Window / Spawn Object if (!isServerTunnel) { add(packetId); add(incoming.get()); add(incoming.getShort()); add(incoming.get()); add(incoming.getShort()); add(incoming.get()); copyItem(); } else { add(packetId); int eid = decodeVarInt(); addVarInt(eid); add(incoming.get()); int objects = 0; add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); add(incoming.get()); objects = add(incoming.getInt()); if (objects > 0) { add(incoming.getShort()); add(incoming.getShort()); add(incoming.getShort()); } } break; case 0x0F: // Confirm Transaction / Spawn Mob add(packetId); if (!isServerTunnel) { add(incoming.get()); add(incoming.getShort()); add(incoming.get()); } else { copyVarInt(); copyUnsignedByte(); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); add(incoming.get()); add(incoming.get()); add(incoming.getShort()); add(incoming.getShort()); add(incoming.getShort()); copyEntityMetadata(); } break; case 0x10: // Creative Inventory Action / Spawn Painting add(packetId); if (!isServerTunnel) { add(incoming.getShort()); copyItem(); } else { copyVarInt(); add(readUTF8()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); } break; case 0x11: // Enchant Item / Spawn Experience Orb add(packetId); if (!isServerTunnel) { add(incoming.get()); add(incoming.get()); } else { copyVarInt(); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getShort()); } break; case 0x12: // Update Sign / Entity Velocity add(packetId); if (!isServerTunnel) { add(incoming.getInt()); add(incoming.getShort()); add(incoming.getInt()); add(readUTF8()); add(readUTF8()); add(readUTF8()); add(readUTF8()); } else { add(incoming.getInt()); add(incoming.getShort()); add(incoming.getShort()); add(incoming.getShort()); } break; case 0x13: // Player Abilities / Destroy Entities add(packetId); if (!isServerTunnel) { add(incoming.get()); add(incoming.getFloat()); add(incoming.getFloat()); } else { byte destroyCount = add(incoming.get()); if (destroyCount > 0) { copyNBytes(destroyCount * 4); } } break; case 0x14: // Tab Complete / Entity add(packetId); if (isServerTunnel) { add(readUTF8()); } else { add(incoming.getInt()); } break; case 0x15: // Client Settings / Entity Relative Move add(packetId); if (!isServerTunnel) { add(readUTF8()); add(incoming.get()); add(incoming.get()); add(incoming.get()); add(incoming.get()); add(incoming.get()); } else { add(incoming.getInt()); add(incoming.get()); add(incoming.get()); add(incoming.get()); } break; case 0x16: // Client Status / Entity Look add(packetId); if (!isServerTunnel) { add(incoming.get()); } else { add(incoming.getInt()); add(incoming.get()); add(incoming.get()); } break; case 0x17: // Plugin Message / Entity Look & Relative Move add(packetId); if (!isServerTunnel) { add(readUTF8()); copyNBytes(add(incoming.getShort())); } else { add(incoming.getInt()); add(incoming.get()); add(incoming.get()); add(incoming.get()); add(incoming.get()); add(incoming.get()); } break; case 0x18: // Entity Teleport add(packetId); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); add(incoming.get()); break; case 0x19: // Entity Head Lock add(packetId); add(incoming.getInt()); add(incoming.get()); break; case 0x1A: // Entity Status add(packetId); add(incoming.getInt()); add(incoming.get()); break; case 0x1B: // Attach Entity add(packetId); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); break; case 0x1C: // Entity Metdata add(packetId); add(incoming.getInt()); copyEntityMetadata(); break; case 0x1D: // Entity Effect add(packetId); add(incoming.getInt()); add(incoming.get()); add(incoming.get()); add(incoming.getShort()); break; case 0x1E: // Remove Entity Effect add(packetId); add(incoming.getInt()); add(incoming.get()); break; case 0x1F: // Set Experience add(packetId); player.updateExperience(add(incoming.getFloat()),add(incoming.getShort()),add(incoming.getShort())); break; case 0x20: // Entity Properties add(packetId); add(incoming.getInt()); int properties_count = incoming.getInt(); short list_length = 0; add(properties_count); // loop for every property key/value pair for (int i = 0; i < properties_count; i++) { add(readUTF8()); add(incoming.getDouble()); // grab list elements list_length = incoming.getShort(); add(list_length); if (list_length > 0) { for (int k = 0; k < list_length; k++) { add(incoming.getLong()); add(incoming.getLong()); add(incoming.getDouble()); add(incoming.get()); } } } break; case 0x21: // Chunk Data add(packetId); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); copyUnsignedShort(); copyUnsignedShort(); copyNBytes(add(incoming.getInt())); break; case 0x22: // Multi Block Change add(packetId); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getShort()); copyNBytes(add(incoming.getInt())); break; case 0x23: // Block Change add(packetId); x = incoming.getInt(); y = (byte) readUnsignedByte(); z = incoming.getInt(); int blockType = decodeVarInt(); byte metadata = (byte) readUnsignedByte(); coordinate = new Coordinate(x, y, z, player); if (blockType == 54 && player.placedChest(coordinate)) { lockChest(coordinate); player.placingChest(null); } add(x); addUnsignedByte(y); add(z); addVarInt(blockType); addUnsignedByte(metadata); break; case 0x24: // Block Action add(packetId); add(incoming.getInt()); add(incoming.getShort()); add(incoming.getInt()); copyUnsignedByte(); copyUnsignedByte(); copyVarInt(); break; case 0x25: // Block Break Animation add(packetId); copyVarInt(); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); break; case 0x26: // Map Chunk Bulk add(packetId); short chunkCount = incoming.getShort(); int dataLength = incoming.getInt(); add(chunkCount); add(dataLength); add(incoming.get()); copyNBytes(dataLength); for (int i = 0; i < chunkCount; i++) { add(incoming.getInt()); add(incoming.getInt()); copyUnsignedShort(); copyUnsignedShort(); } break; case 0x27: // Explosion add(packetId); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getFloat()); int recordCount = incoming.getInt(); add(recordCount); copyNBytes(recordCount * 3); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getFloat()); break; case 0x28: // Effect add(packetId); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.get()); break; case 0x29: // Sound Effect add(packetId); add(readUTF8()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getFloat()); copyUnsignedByte(); break; case 0x2A: // Particle add(packetId); add(readUTF8()); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.getInt()); break; case 0x2B: // Change Game State add(packetId); copyUnsignedByte(); add(incoming.getFloat()); break; case 0x2C: // Spawn Global Entity add(packetId); copyVarInt(); add(incoming.get()); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); break; case 0x2D: // Open Window boolean allow = true; byte id = incoming.get(); byte invtype = incoming.get(); String title = readUTF8(); byte number = incoming.get(); byte provided = incoming.get(); int unknown = 0; if (invtype == 11) { unknown = incoming.getInt(); } if (invtype == 0) { Chest adjacent = server.data.chests.adjacentChest(player.openedChest()); if (!server.data.chests.isChest(player.openedChest())) { if (adjacent == null) { server.data.chests.addOpenChest(player.openedChest()); } else { server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name); } server.data.save(); } if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) { player.addTMessage(Color.RED, "You can't use chests here"); allow = false; } else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) { if (server.data.chests.isLocked(player.openedChest())) { if (player.isAttemptingUnlock()) { server.data.chests.unlock(player.openedChest()); server.data.save(); player.setAttemptedAction(null); player.addTMessage(Color.RED, "This chest is no longer locked!"); title = t("Open Chest"); } else { title = server.data.chests.chestName(player.openedChest()); } } else { title = t("Open Chest"); if (player.isAttemptLock()) { lockChest(player.openedChest()); title = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName(); } } } else { player.addTMessage(Color.RED, "This chest is locked!"); allow = false; } } if (!allow) { // @todo figure out what this does //add((byte) 0x2E); //add(id); } else { add(packetId); add(id); add(invtype); add(title); add(number); add(provided); if (invtype == 11) { add(unknown); } } break; case 0x2E: // Close Window add(packetId); copyUnsignedByte(); break; case 0x2F: // Set Slot add(packetId); copyUnsignedByte(); add(incoming.getShort()); copyItem(); break; case 0x30: // Window Items add(packetId); copyUnsignedByte(); short count = add(incoming.getShort()); for (int c = 0; c < count; ++c) { copyItem(); } break; case 0x31: // Window Property add(packetId); copyUnsignedByte(); add(incoming.getShort()); add(incoming.getShort()); break; case 0x32: // Confirm Transaction add(packetId); copyUnsignedByte(); add(incoming.getShort()); add(incoming.get()); break; case 0x33: // Update Sign add(packetId); add(incoming.getInt()); add(incoming.getShort()); add(incoming.getInt()); add(readUTF8()); add(readUTF8()); add(readUTF8()); add(readUTF8()); break; case 0x34: // Maps add(packetId); copyVarInt(); copyNBytes(add(incoming.getShort())); break; case 0x35: // Update Block Entity add(packetId); add(incoming.getInt()); add(incoming.getShort()); add(incoming.getInt()); copyUnsignedByte(); short len = incoming.getShort(); add(len); if (len > 0) { copyNBytes(len); } break; case 0x36: // Sign Editor Open add(packetId); add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); break; case 0x37: // Statistics add(packetId); int entrys = decodeVarInt(); addVarInt(entrys); if (entrys > 0) { for (int i = 0; i < entrys; i++) { add(readUTF8()); copyVarInt(); } } break; case 0x38: // Player List Item add(packetId); add(readUTF8()); add(incoming.get()); add(incoming.getShort()); break; case 0x39: // Player Abilities add(packetId); add(incoming.get()); add(incoming.getFloat()); add(incoming.getFloat()); break; case 0x3A: // Tab-Complete add(packetId); int s = decodeVarInt(); add(encodeVarInt(s)); if (s > 0) { add(readUTF8()); } break; case 0x3B: // Scoreboard Objective add(packetId); add(readUTF8()); add(readUTF8()); add(incoming.get()); break; case 0x3C: // Update Score add(packetId); add(readUTF8()); add(incoming.get()); add(readUTF8()); add(incoming.get()); break; case 0x3D: // Display Scoreboard add(packetId); add(incoming.get()); add(readUTF8()); break; case 0x3E: // Teams add(packetId); add(readUTF8()); byte mode = incoming.get(); short playerCount = -1; add(mode); if (mode == 0 || mode == 2) { add(readUTF8()); // team display name add(readUTF8()); // team prefix add(readUTF8()); // team suffix add(incoming.get()); // friendly fire } // only ran if 0,3,4 if (mode == 0 || mode == 3 || mode == 4) { playerCount = incoming.getShort(); add(playerCount); if (playerCount != -1) { for (int i = 0; i < playerCount; i++) { add(readUTF8()); } } } break; case 0x3F: // Plugin Message add(packetId); add(readUTF8()); copyNBytes(add(incoming.getShort())); break; case 0x40: // Disconnect add(packetId); String reason = readUTF8(); if (reason.startsWith("\u00a71")) { reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s", Main.protocolVersion, Main.minecraftVersion, server.config.properties.get("serverDescription"), server.playerList.size(), server.config.properties.getInt("maxPlayers")); } add(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { copyNBytes(length); flushAll(); } else { System.out.println("WARNING: Unknown packet 0x" + Integer.toHexString(packetId)); copyNBytes(length); } } } else { throw new ArrayIndexOutOfBoundsException(); } packetFinished(); lastPacket = (packetId == 0x00) ? lastPacket : packetId; } private void copyItem() throws IOException { if (add(incoming.getShort()) > 0) { add(incoming.get()); add(incoming.getShort()); short length; if ((length = add(incoming.getShort())) > 0) { copyNBytes(length); } } } private void skipItem() throws IOException { if (incoming.getShort() > 0) { incoming.get(); incoming.getShort(); short length; if ((length = incoming.getShort()) > 0) { copyNBytes(length); } } } private String readUTF8() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int length = decodeVarInt(); for (int i = 0; i < length; i++) { buffer.write((incoming != null) ? incoming.get() : in.readByte()); } return new String(buffer.toByteArray(), "UTF-8"); } private int readUnsignedShort() { return (incoming.getShort() & 0xFFFF); } private short readUnsignedByte() { return ((short) (incoming.get() & 0xFF)); } private void copyVarInt() throws IOException { outgoing.put(encodeVarInt(decodeVarInt())); } private int copyUnsignedByte() throws IOException { return addUnsignedByte(readUnsignedByte()); } private int copyUnsignedShort() throws IOException { return addUnsignedShort(readUnsignedShort()); } private int addVarInt(int i) throws IOException { outgoing.put(encodeVarInt(i)); return i; } private int addUnsignedShort(int i) { outgoing.putShort((short) (i & 0xFFFF)); return i; } private int addUnsignedByte(int i) { outgoing.put((byte) (i & 0xFF)); return i; } private int add(int i) throws IOException { outgoing.putInt(i); return i; } private String add(String s) throws IOException { addVarInt(s.length()); add(s.getBytes()); return s; } private byte[] add(byte[] b) throws IOException { outgoing.put(b); return b; } private byte add(byte b) throws IOException { outgoing.put(b); return b; } private long add(long l) throws IOException { outgoing.putLong(l); return l; } private short add(short s) throws IOException { outgoing.putShort(s); return s; } private double add(double d) throws IOException { outgoing.putDouble(d); return d; } private float add(float f) throws IOException { outgoing.putFloat(f); return f; } private byte[] encodeVarInt(int value) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); while (true) { if ((value & 0xFFFFFF80) == 0) { buffer.write(value); return buffer.toByteArray(); } buffer.write(value & 0x7F | 0x80); value >>>= 7; } } private int decodeVarInt() throws IOException { int i = 0; int j = 0; while (true) { int k = ((incoming != null) ? incoming.get() : in.readByte()); i |= (k & 0x7F) << j++ * 7; if (j > 5) { throw new IllegalArgumentException("VarInt too big"); } if ((k & 0x80) != 128) break; } return i; } private void lockChest(Coordinate coordinate) { Chest adjacentChest = server.data.chests.adjacentChest(coordinate); if (player.isAttemptLock() || adjacentChest != null && !adjacentChest.isOpen()) { if (adjacentChest != null && !adjacentChest.isOpen()) { server.data.chests.giveLock(adjacentChest.owner, coordinate, adjacentChest.name); } else { if (adjacentChest != null) { adjacentChest.lock(player); adjacentChest.name = player.nextChestName(); } server.data.chests.giveLock(player, coordinate, player.nextChestName()); } player.setAttemptedAction(null); player.addTMessage(Color.GRAY, "This chest is now locked."); } else if (!server.data.chests.isChest(coordinate)) { server.data.chests.addOpenChest(coordinate); } server.data.save(); } /** * copyPlayerPosition * * @param ground_enabled do I read the boolean `On Ground`? * @param stance_enabled do I read the Stance double as part of x,y,z coords? * @throws IOException */ private void copyPlayerPosition(boolean ground_enabled, boolean stance_enabled) throws IOException { double x = incoming.getDouble(); double y = incoming.getDouble(); double stance = 0.0; if (stance_enabled) { stance = incoming.getDouble(); } double z = incoming.getDouble(); if (stance_enabled) { player.position.updatePosition(x, y, z, stance); } else { player.position.updatePositionWithNoStance(x, y, z); } if (server.options.getBoolean("enableEvents")) { player.checkLocationEvents(); } add(x); add(y); if (stance_enabled) { add(stance); } add(z); if (ground_enabled) { add(incoming.get()); // on ground (bool) } } private void copyPlayerLook(boolean on_ground) throws IOException { float yaw = incoming.getFloat(); float pitch = incoming.getFloat(); player.position.updateLook(yaw, pitch); add(yaw); add(pitch); if (on_ground) { add(incoming.get()); } } private void copyEntityMetadata() throws IOException { byte item = incoming.get(); add(item); while (item != 0x7F) { int type = (item & 0xE0) >> 5; switch (type) { case 0: add(incoming.get()); break; case 1: add(incoming.getShort()); break; case 2: add(incoming.getInt()); break; case 3: add(incoming.getFloat()); break; case 4: add(readUTF8()); break; case 5: copyItem(); break; case 6: add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); break; } item = incoming.get(); add(item); } } private void skipEntityMetadata() throws IOException { byte item = incoming.get(); while (item != 0x7F) { int type = (item & 0xE0) >> 5; switch (type) { case 0: incoming.get(); break; case 1: incoming.getShort(); break; case 2: incoming.getInt(); break; case 3: incoming.getFloat(); break; case 4: readUTF8(); break; case 5: skipItem(); break; case 6: incoming.getInt(); incoming.getInt(); incoming.getInt(); break; } item = incoming.get(); } } private byte write(byte b) throws IOException { out.writeByte(b); return b; } private byte[] write(byte[] b) throws IOException { out.write(b); return b; } private short write(short s) throws IOException { out.writeShort(s); return s; } private int write(int i) throws IOException { out.writeInt(i); return i; } private long write(long l) throws IOException { out.writeLong(l); return l; } private float write(float f) throws IOException { out.writeFloat(f); return f; } private double write(double d) throws IOException { out.writeDouble(d); return d; } private String write(String s) throws IOException { write((short) s.length()); out.writeChars(s); return s; } private boolean write(boolean b) throws IOException { out.writeBoolean(b); return b; } private void skipNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { incoming.get(buffer, 0, buffer.length); } incoming.get(buffer, 0, bytes % buffer.length); } private void copyNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { incoming.get(buffer, 0, buffer.length); outgoing.put(buffer, 0, buffer.length); } incoming.get(buffer, 0, bytes % buffer.length); outgoing.put(buffer, 0, bytes % buffer.length); } private void kick(String reason) throws IOException { // @todo start new packet //add((byte) 0x40); //add(reason); //packetFinished(); } private void sendMessage(String message) throws IOException { if (message.length() > 0) { int end = message.length(); if (message.charAt(end - 1) == '\u00a7') { end } sendMessagePacket(message.substring(0, end)); } } private void sendMessagePacket(String message) throws IOException { if (message.length() > 0) { // create new byte array byte[] size = encodeVarInt(message.getBytes().length); byte[] packet = new byte[message.getBytes().length + size.length]; // make byte [size][data] System.arraycopy(size, 0, packet, 0, size.length); System.arraycopy(message.getBytes(), 0, packet, size.length, message.getBytes().length); sendPacketIndependently((byte) 0x02, packet); } } private void sendPacketIndependently(byte id, byte[] data) throws IOException { ByteBuffer tmp = ByteBuffer.allocate(data.length + 1); tmp.put(id); tmp.put(data); write(encodeVarInt(tmp.limit())); tmp.rewind(); outgoing.order(ByteOrder.BIG_ENDIAN); write(tmp.array()); ((OutputStream) out).flush(); } private void packetFinished() throws IOException { // reset our incoming buffer, and write the outgoing one int pre = incoming.position(); int max = incoming.limit(); incoming = null; int size = outgoing.position(); if (pre == max) { outgoing.limit(size); outgoing.rewind(); outgoing.order(ByteOrder.BIG_ENDIAN); byte[] tmp = new byte[size]; outgoing.get(tmp); readyToSend = true; write(encodeVarInt(size)); write(tmp); } else { System.out.println("read " + pre + " bytes. found: " + max); System.out.println("outbound size: " + size); } if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.packetFinished(); outputDumper.packetFinished(); } } private void flushAll() throws IOException { try { if (readyToSend) { ((OutputStream) out).flush(); } } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.flush(); } } } private final class Tunneler extends Thread { @Override public void run() { try { while (run) { lastRead = System.currentTimeMillis(); try { handlePacket(); if (isServerTunnel) { while (player.hasMessages()) { sendMessage(player.getMessage()); } } else { while (player.hasForwardMessages()) { sendMessage(player.getForwardMessage()); } } flushAll(); } catch (IOException e) { if (run && !player.isRobot()) { println(e); print(streamType + " error handling traffic for " + player.getIPAddress()); if (lastPacket != null) { System.out.print(" (" + Integer.toHexString(lastPacket) + ")"); } System.out.println(); } break; } } try { if (player.isKicked()) { kick(player.getKickMsg()); } flushAll(); } catch (IOException e) { } } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.cleanup(); outputDumper.cleanup(); } } } } }
package simpleserver.stream; import static simpleserver.lang.Translations.t; import static simpleserver.util.Util.print; import static simpleserver.util.Util.println; import java.io.*; import java.nio.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import javassist.bytecode.ByteArray; import simpleserver.*; import simpleserver.Authenticator.AuthRequest; import simpleserver.Coordinate.Dimension; import simpleserver.command.PlayerListCommand; import simpleserver.config.data.Chests.Chest; import simpleserver.config.xml.Config.BlockPermission; import simpleserver.message.Message; import simpleserver.message.MessagePacket; public class StreamTunnel { private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING"); private static final int IDLE_TIME = 30000; private static final int BUFFER_SIZE = 1024; private static final byte BLOCK_DESTROYED_STATUS = 2; private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$"); private static final Pattern COLOR_PATTERN = Pattern.compile("\u00a7[0-9a-z]"); private static final Pattern JOIN_PATTERN = Pattern.compile("\u00a7.((\\d|\\w|\\u00a7)*) (joined|left) the game."); private static final String CONSOLE_CHAT_PATTERN = "\\[Server:.*\\]"; private static final int MESSAGE_SIZE = 360; private static final int MAXIMUM_MESSAGE_SIZE = 119; private static final int STATE_HANDSHAKE = 0; private static final int STATE_STATUS = 1; private static final int STATE_LOGIN = 2; private static final int STATE_PLAY = 3; private final boolean isServerTunnel; private final String streamType; private final Player player; private final Server server; private final byte[] buffer; private final Tunneler tunneler; private DataInput in; private DataOutput out; private InputStream inputStream; private OutputStream outputStream; private StreamDumper inputDumper; private StreamDumper outputDumper; private boolean inGame = false; private volatile long lastRead; private volatile boolean run = true; private Byte lastPacket; private char commandPrefix; private int state = 0; private ByteBuffer incoming = null; private ByteBuffer outgoing = null; public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel, Player player) { this.isServerTunnel = isServerTunnel; if (isServerTunnel) { streamType = "ServerStream"; } else { streamType = "PlayerStream"; } this.player = player; server = player.getServer(); commandPrefix = server.options.getBoolean("useSlashes") ? '/' : '!'; inputStream = in; outputStream = out; DataInputStream dIn = new DataInputStream(in); DataOutputStream dOut = new DataOutputStream(out); if (EXPENSIVE_DEBUG_LOGGING) { try { OutputStream dump = new FileOutputStream(streamType + "Input.debug"); InputStreamDumper dumper = new InputStreamDumper(dIn, dump); inputDumper = dumper; this.in = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open input debug dump!"); throw new RuntimeException(e); } try { OutputStream dump = new FileOutputStream(streamType + "Output.debug"); OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump); outputDumper = dumper; this.out = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open output debug dump!"); throw new RuntimeException(e); } } else { this.in = dIn; this.out = dOut; } buffer = new byte[BUFFER_SIZE]; tunneler = new Tunneler(); tunneler.start(); lastRead = System.currentTimeMillis(); } public void stop() { run = false; } public void setState(int i) { state = i; } public boolean isAlive() { return tunneler.isAlive(); } public boolean isActive() { return System.currentTimeMillis() - lastRead < IDLE_TIME || player.isRobot(); } private void handlePacket() throws IOException { int length = decodeVarInt(); // read length into byte[], copy into ByteBuffer byte[] buf = new byte[length]; in.readFully(buf, 0, length); incoming = ByteBuffer.wrap(buf); outgoing = ByteBuffer.allocate(length * 2); Byte packetId = (byte) decodeVarInt(); System.out.println("state:" + state + (isServerTunnel ? " server " : " client ") + String.format("%02x", packetId) + " length: " + length); if (state == STATE_HANDSHAKE) { if (!isServerTunnel) { add(packetId); copyVarInt(); add(readUTF8()); addUnsignedShort(readUnsignedShort()); state = decodeVarInt(); player.setState(state); addVarInt(state); } } else if (state == STATE_STATUS) { switch(packetId) { case 0x00: // JSON Response add(packetId); if (isServerTunnel) { add(readUTF8()); // @todo handle changing of max-player, server name, etc. } break; case 0x01: // Ping add(packetId); add(incoming.getLong()); break; } } else if (state == STATE_LOGIN) { switch(packetId) { case 0x00: // Disconnect / Login Start add(packetId); add(readUTF8()); break; case 0x01: // Encryption Request / Response if (isServerTunnel) { add(packetId); tunneler.setName(streamType + "-" + player.getUuid()); String serverId = readUTF8(); if (!server.authenticator.useCustAuth(player)) { serverId = "-"; } else { serverId = player.getConnectionHash(); } add(serverId); // @todo fixup sizes byte[] keyBytes = new byte[incoming.getShort()]; outgoing.put(keyBytes); byte[] challengeToken = new byte[incoming.getShort()]; outgoing.put(challengeToken); player.serverEncryption.setPublicKey(keyBytes); byte[] key = player.clientEncryption.getPublicKey(); add((short) key.length); add(key); add((short) challengeToken.length); add(challengeToken); player.serverEncryption.setChallengeToken(challengeToken); player.clientEncryption.setChallengeToken(challengeToken); } else { byte[] sharedKey = new byte[incoming.getShort()]; outgoing.put(sharedKey); byte[] challengeTokenResponse = new byte[incoming.getShort()]; outgoing.put(challengeTokenResponse); if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) { player.kick("Invalid client response"); break; } player.clientEncryption.setEncryptedSharedKey(sharedKey); sharedKey = player.serverEncryption.getEncryptedSharedKey(); if (server.authenticator.useCustAuth(player) && !server.authenticator.onlineAuthenticate(player)) { player.kick(t("%s Failed to login: User not premium", "[CustAuth]")); break; } add(packetId); add((short) sharedKey.length); add(sharedKey); challengeTokenResponse = player.serverEncryption.encryptChallengeToken(); add((short) challengeTokenResponse.length); add(challengeTokenResponse); in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream))); } break; case 0x02: // Login Success add(packetId); String uuid = readUTF8(); String name = readUTF8(); boolean nameSet = false; if (name.contains(";")) { name = name.substring(0, name.indexOf(";")); } if (name.equals("Player") || !server.authenticator.isMinecraftUp) { AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress()); if (req != null) { name = req.playerName; nameSet = server.authenticator.completeLogin(req, player); } if (req == null || !nameSet) { if (!name.equals("Player")) { player.addTMessage(Color.RED, "Login verification failed."); player.addTMessage(Color.RED, "You were logged in as guest."); } name = server.authenticator.getFreeGuestName(); player.setGuest(true); nameSet = player.setName(name); } } else { nameSet = player.setName(name); if (nameSet) { player.updateRealName(name); } } if (player.isGuest() && !server.authenticator.allowGuestJoin()) { player.kick(t("Failed to login: User not authenticated")); nameSet = false; } tunneler.setName(streamType + "-" + player.getName()); player.setUuid(uuid); player.setState(3); add(uuid); add(player.getName()); break; } } else if (state == STATE_PLAY) { int x, z; byte y, dimension; Coordinate coordinate; switch(packetId) { case 0x00: // Keep-Alive add(packetId); add(incoming.getInt()); break; case 0x01: // Join-Game / Chat-Message add(packetId); if (isServerTunnel) { player.setEntityId(add(incoming.getInt())); copyUnsignedByte(); dimension = incoming.get(); add(dimension); copyUnsignedByte(); copyUnsignedByte(); //readUnsignedByte(); @todo uncomment once fix 0x00 of status //addUnsignedByte(server.config.properties.getInt("maxPlayers")); add(readUTF8()); } else { add(readUTF8()); // @todo handle chat message } break; case 0x02: // Chat-Message / Use Entity add(packetId); if (isServerTunnel) { add(readUTF8()); } else { add(incoming.getInt()); add(incoming.get()); } break; case 0x03: // Time-Update / Player add(packetId); if (isServerTunnel) { add(incoming.getLong()); long time = incoming.getLong(); server.setTime(time); add(time); } else { add(incoming.get()); } break; case 0x04: // Entity-Equipment / Player Position add(packetId); if (isServerTunnel) { add(incoming.getInt()); add(incoming.getShort()); copyItem(); } else { copyPlayerPosition(true); } break; case 0x05: // Spawn Position / Player Look add(packetId); if (isServerTunnel) { add(incoming.getInt()); add(incoming.getInt()); add(incoming.getInt()); if (server.options.getBoolean("enableEvents")) { server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null); } } else { add(incoming.getFloat()); add(incoming.getFloat()); add(incoming.get()); } break; case 0x06: // Update Health / Player Position & Look add(packetId); if (isServerTunnel) { add(incoming.getFloat()); add(incoming.getShort()); add(incoming.getFloat()); } else { copyPlayerPosition(false); copyPlayerLook(true); } break; case 0x3F: // Plugin Message add(packetId); add(readUTF8()); short size = incoming.getShort(); copyNBytes(size); break; } } else { throw new ArrayIndexOutOfBoundsException(); } packetFinished(); lastPacket = (packetId == 0x00) ? lastPacket : packetId; } private void copyItem() throws IOException { if (add(incoming.getShort()) > 0) { add(incoming.get()); add(incoming.getShort()); short length; if ((length = add(incoming.getShort())) > 0) { copyNBytes(length); } } } // private void skipItem() throws IOException { // if (in.readShort() > 0) { // in.readByte(); // in.readShort(); // short length; // if ((length = in.readShort()) > 0) { // skipNBytes(length); // private long copyVLC() throws IOException { // long value = 0; // int shift = 0; // while (true) { // int i = write(in.readByte()); // value |= (i & 0x7F) << shift; // if ((i & 0x80) == 0) { // break; // shift += 7; // return value; private String readUTF8() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int length = decodeVarInt(); for (int i = 0; i < length; i++) { buffer.write((incoming != null) ? incoming.get() : in.readByte()); } return new String(buffer.toByteArray(), "UTF-8"); } private int readUnsignedShort() { return (incoming.getShort() & 0xFFFF); } private short readUnsignedByte() { return ((short) (incoming.get() & 0xFF)); } private void copyVarInt() throws IOException { outgoing.put(encodeVarInt(decodeVarInt())); } private int copyUnsignedByte() throws IOException { return addUnsignedByte(readUnsignedByte()); } private int copyUnsignedShort() throws IOException { return addUnsignedShort(readUnsignedShort()); } private int addVarInt(int i) throws IOException { outgoing.put(encodeVarInt(i)); return i; } private int addUnsignedShort(int i) { outgoing.putShort((short) (i & 0xFFFF)); return i; } private int addUnsignedByte(int i) { outgoing.put((byte) (i & 0xFF)); return i; } private int add(int i) throws IOException { outgoing.putInt(i); return i; } private String add(String s) throws IOException { addVarInt(s.length()); add(s.getBytes()); return s; } private byte[] add(byte[] b) throws IOException { outgoing.put(b); return b; } private byte add(byte b) throws IOException { outgoing.put(b); return b; } private long add(long l) throws IOException { outgoing.putLong(l); return l; } private short add(short s) throws IOException { outgoing.putShort(s); return s; } private double add(double d) throws IOException { outgoing.putDouble(d); return d; } private float add(float f) throws IOException { outgoing.putFloat(f); return f; } private byte[] encodeVarInt(int value) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); while (true) { if ((value & 0xFFFFFF80) == 0) { buffer.write(value); return buffer.toByteArray(); } buffer.write(value & 0x7F | 0x80); value >>>= 7; } } private int decodeVarInt() throws IOException { int i = 0; int j = 0; while (true) { int k = ((incoming != null) ? incoming.get() : in.readByte()); i |= (k & 0x7F) << j++ * 7; if (j > 5) { throw new IllegalArgumentException("VarInt too big"); } if ((k & 0x80) != 128) break; } return i; } // private void lockChest(Coordinate coordinate) { // Chest adjacentChest = server.data.chests.adjacentChest(coordinate); // if (player.isAttemptLock() || adjacentChest != null && !adjacentChest.isOpen()) { // if (adjacentChest != null && !adjacentChest.isOpen()) { // server.data.chests.giveLock(adjacentChest.owner, coordinate, adjacentChest.name); // } else { // if (adjacentChest != null) { // adjacentChest.lock(player); // adjacentChest.name = player.nextChestName(); // server.data.chests.giveLock(player, coordinate, player.nextChestName()); // player.setAttemptedAction(null); // player.addTMessage(Color.GRAY, "This chest is now locked."); // } else if (!server.data.chests.isChest(coordinate)) { // server.data.chests.addOpenChest(coordinate); // server.data.save(); private void copyPlayerPosition(boolean on_ground) throws IOException { double x = incoming.getDouble(); double y = incoming.getDouble(); double stance = incoming.getDouble(); double z = incoming.getDouble(); player.position.updatePosition(x, y, z, stance); if (server.options.getBoolean("enableEvents")) { player.checkLocationEvents(); } add(x); add(y); add(stance); add(z); if (on_ground) { add(incoming.get()); // on ground (bool) } } private void copyPlayerLook(boolean on_ground) throws IOException { float yaw = incoming.getFloat(); float pitch = incoming.getFloat(); player.position.updateLook(yaw, pitch); add(yaw); add(pitch); if (on_ground) { add(incoming.get()); } } // private void copyUnknownBlob() throws IOException { // byte item = in.readByte(); // write(item); // while (item != 0x7f) { // int type = (item & 0xE0) >> 5; // switch (type) { // case 0: // write(in.readByte()); // break; // case 1: // write(in.readShort()); // break; // case 2: // write(in.readInt()); // break; // case 3: // write(in.readFloat()); // break; // case 4: // write(readUTF8()); // break; // case 5: // copyItem(); // break; // case 6: // write(in.readInt()); // write(in.readInt()); // write(in.readInt()); // item = in.readByte(); // write(item); // private void skipUnknownBlob() throws IOException { // byte item = in.readByte(); // while (item != 0x7f) { // int type = (item & 0xE0) >> 5; // switch (type) { // case 0: // in.readByte(); // break; // case 1: // in.readShort(); // break; // case 2: // in.readInt(); // break; // case 3: // in.readFloat(); // break; // case 4: // readUTF8(); // break; // case 5: // skipItem(); // break; // case 6: // in.readInt(); // in.readInt(); // in.readInt(); // item = in.readByte(); private byte write(byte b) throws IOException { out.writeByte(b); return b; } private byte[] write(byte[] b) throws IOException { out.write(b); return b; } private short write(short s) throws IOException { out.writeShort(s); return s; } private int write(int i) throws IOException { out.writeInt(i); return i; } private long write(long l) throws IOException { out.writeLong(l); return l; } private float write(float f) throws IOException { out.writeFloat(f); return f; } private double write(double d) throws IOException { out.writeDouble(d); return d; } private String write(String s) throws IOException { write((short) s.length()); out.writeChars(s); return s; } private boolean write(boolean b) throws IOException { out.writeBoolean(b); return b; } // private void skipNBytes(int bytes) throws IOException { // int overflow = bytes / buffer.length; // for (int c = 0; c < overflow; ++c) { // in.readFully(buffer, 0, buffer.length); // in.readFully(buffer, 0, bytes % buffer.length); private void copyNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { incoming.get(buffer, 0, buffer.length); outgoing.put(buffer, 0, buffer.length); } incoming.get(buffer, 0, bytes % buffer.length); outgoing.put(buffer, 0, bytes % buffer.length); } private void kick(String reason) throws IOException { write((byte) 0xff); write(reason); packetFinished(); } // private String getLastColorCode(String message) { // String colorCode = ""; // int lastIndex = message.lastIndexOf('\u00a7'); // if (lastIndex != -1 && lastIndex + 1 < message.length()) { // colorCode = message.substring(lastIndex, lastIndex + 2); // return colorCode; private void sendMessage(String message) throws IOException { if (message.length() > 0) { int end = message.length(); if (message.charAt(end - 1) == '\u00a7') { end } sendMessagePacket(message.substring(0, end)); } } private void sendMessagePacket(String message) throws IOException { if (message.length() > 0) { write((byte) 0x03); write(message); packetFinished(); } } private void packetFinished() throws IOException { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.packetFinished(); outputDumper.packetFinished(); } // reset our incoming buffer, and write the outgoing one incoming = null; int size = outgoing.position(); outgoing.limit(size); outgoing.rewind(); outgoing.order(ByteOrder.BIG_ENDIAN); byte[] tmp = new byte[size]; outgoing.get(tmp); System.out.println("outbound size: " + size ); out.write(size); out.write(tmp); } private void flushAll() throws IOException { try { ((OutputStream) out).flush(); } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.flush(); } } } private final class Tunneler extends Thread { @Override public void run() { try { while (run) { lastRead = System.currentTimeMillis(); try { handlePacket(); if (isServerTunnel) { while (player.hasMessages()) { sendMessage(player.getMessage()); } } else { while (player.hasForwardMessages()) { sendMessage(player.getForwardMessage()); } } flushAll(); } catch (IOException e) { if (run && !player.isRobot()) { println(e); print(streamType + " error handling traffic for " + player.getIPAddress()); if (lastPacket != null) { System.out.print(" (" + Integer.toHexString(lastPacket) + ")"); } System.out.println(); } break; } } try { if (player.isKicked()) { kick(player.getKickMsg()); } flushAll(); } catch (IOException e) { } } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.cleanup(); outputDumper.cleanup(); } } } } }
import capsule.DependencyManagerImpl; import capsule.DependencyManager; import capsule.PomReader; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import static java.util.Collections.*; /** * An application capsule. * <p> * This API is to be used by custom capsules to programmatically (rather than declaratively) configure the capsule and possibly provide custom behavior. * <p> * All non-final protected methods may be overridden by custom capsules. These methods will usually be called once, but they must be idempotent, * i.e. if called numerous times they must always return the same value, and produce the same effect as if called once. * <br> * Overridden methods need not be thread-safe, and are guaranteed to be called by a single thread at a time. * <br> * Overridable (non-final) methods <b>must never</b> be called directly by custom capsule code, except by their overrides. * <p> * Final methods implement various utility or accessors, which may be freely used by custom capsules. * <p> * For command line option handling, see {@link #registerOption(String, String, String) registerOption}. * * @author pron */ public class Capsule implements Runnable { protected static final String VERSION = "0.10.0"; /* * This class follows some STRICT RULES: * * 1. IT MUST COMPILE TO A SINGLE CLASS FILE (so it must not contain nested or inner classes). * 2. IT MUST ONLY REFERENCE CLASSES IN THE JDK AND THOSE IN THE capsule PACKAGE. * 3. CAPSULES WITH NO DECLARED DEPENDENCIES MUST LAUNCH WITHOUT REQUIRING ANY CLASSES BUT THIS AND THE JDK. * 4. ALL METHODS MUST BE PURE OR, AT LEAST, IDEMPOTENT (with the exception of the launch method, and, of course, the constructor). * * Rules #1 and #3 ensure that fat capsules will work with only Capsule.class included in the JAR. Rule #2 helps enforcing rules #1 and #3. * Rule #4 ensures methods can be called in any order (after construction completes), and makes maintenance and evolution of Capsule simpler. * * This class contains several strange hacks to compy with rule #1. * * Also, the code is not meant to be the most efficient, but methods should be as independent and stateless as possible. * Other than those few methods called in the constructor, all others are can be called in any order, and don't rely on any state. * * We do a lot of data transformations that could benefited from Java 8's lambdas+streams, but we want Capsule to support Java 7. */ //<editor-fold defaultstate="collapsed" desc="Constants"> /////////// Constants /////////////////////////////////// private static final String PROP_VERSION = "capsule.version"; private static final String PROP_TREE = "capsule.tree"; private static final String PROP_RESOLVE = "capsule.resolve"; private static final String PROP_MODES = "capsule.modes"; private static final String PROP_PRINT_JRES = "capsule.jvms"; private static final String PROP_HELP = "capsule.help"; private static final String PROP_TRAMPOLINE = "capsule.trampoline"; private static final String PROP_MODE = "capsule.mode"; private static final String PROP_RESET = "capsule.reset"; private static final String PROP_LOG_LEVEL = "capsule.log"; private static final String PROP_CAPSULE_JAVA_HOME = "capsule.java.home"; private static final String PROP_CAPSULE_JAVA_CMD = "capsule.java.cmd"; private static final String PROP_USE_LOCAL_REPO = "capsule.local"; private static final String PROP_JVM_ARGS = "capsule.jvm.args"; private static final String PROP_NO_DEP_MANAGER = "capsule.no_dep_manager"; private static final String PROP_PROFILE = "capsule.profile"; private static final String PROP_JAVA_VERSION = "java.version"; private static final String PROP_JAVA_HOME = "java.home"; private static final String PROP_OS_NAME = "os.name"; private static final String PROP_USER_HOME = "user.home"; private static final String PROP_JAVA_LIBRARY_PATH = "java.library.path"; private static final String PROP_FILE_SEPARATOR = "file.separator"; private static final String PROP_PATH_SEPARATOR = "path.separator"; private static final String PROP_JAVA_SECURITY_POLICY = "java.security.policy"; private static final String PROP_JAVA_SECURITY_MANAGER = "java.security.manager"; private static final String PROP_TMP_DIR = "java.io.tmpdir"; private static final String ENV_CACHE_DIR = "CAPSULE_CACHE_DIR"; private static final String ENV_CACHE_NAME = "CAPSULE_CACHE_NAME"; private static final String ENV_CAPSULE_REPOS = "CAPSULE_REPOS"; private static final String ENV_CAPSULE_LOCAL_REPO = "CAPSULE_LOCAL_REPO"; private static final String ATTR_MANIFEST_VERSION = "Manifest-Version"; private static final String ATTR_CLASS_PATH = "Class-Path"; private static final String ATTR_IMPLEMENTATION_VERSION = "Implementation-Version"; private static final String ATTR_IMPLEMENTATION_TITLE = "Implementation-Title"; private static final String ATTR_IMPLEMENTATION_VENDOR = "Implementation-Vendor"; private static final String ATTR_IMPLEMENTATION_URL = "Implementation-URL"; private static final String ATTR_APP_NAME = "Application-Name"; private static final String ATTR_APP_VERSION = "Application-Version"; private static final String ATTR_MODE_DESC = "Description"; private static final String ATTR_APP_CLASS = "Application-Class"; private static final String ATTR_APP_ARTIFACT = "Application"; private static final String ATTR_UNIX_SCRIPT = "Unix-Script"; private static final String ATTR_WINDOWS_SCRIPT = "Windows-Script"; private static final String ATTR_EXTRACT = "Extract-Capsule"; private static final String ATTR_MIN_JAVA_VERSION = "Min-Java-Version"; private static final String ATTR_JAVA_VERSION = "Java-Version"; private static final String ATTR_MIN_UPDATE_VERSION = "Min-Update-Version"; private static final String ATTR_JDK_REQUIRED = "JDK-Required"; private static final String ATTR_JVM_ARGS = "JVM-Args"; private static final String ATTR_ARGS = "Args"; private static final String ATTR_ENV = "Environment-Variables"; private static final String ATTR_SYSTEM_PROPERTIES = "System-Properties"; private static final String ATTR_APP_CLASS_PATH = "App-Class-Path"; private static final String ATTR_CAPSULE_IN_CLASS_PATH = "Capsule-In-Class-Path"; private static final String ATTR_BOOT_CLASS_PATH = "Boot-Class-Path"; private static final String ATTR_BOOT_CLASS_PATH_A = "Boot-Class-Path-A"; private static final String ATTR_BOOT_CLASS_PATH_P = "Boot-Class-Path-P"; private static final String ATTR_LIBRARY_PATH_A = "Library-Path-A"; private static final String ATTR_LIBRARY_PATH_P = "Library-Path-P"; private static final String ATTR_SECURITY_MANAGER = "Security-Manager"; private static final String ATTR_SECURITY_POLICY = "Security-Policy"; private static final String ATTR_SECURITY_POLICY_A = "Security-Policy-A"; private static final String ATTR_JAVA_AGENTS = "Java-Agents"; private static final String ATTR_REPOSITORIES = "Repositories"; private static final String ATTR_ALLOW_SNAPSHOTS = "Allow-Snapshots"; private static final String ATTR_DEPENDENCIES = "Dependencies"; private static final String ATTR_NATIVE_DEPENDENCIES_LINUX = "Native-Dependencies-Linux"; private static final String ATTR_NATIVE_DEPENDENCIES_WIN = "Native-Dependencies-Win"; private static final String ATTR_NATIVE_DEPENDENCIES_MAC = "Native-Dependencies-Mac"; private static final String ATTR_MAIN_CLASS = "Main-Class"; private static final String ATTR_LOG_LEVEL = "Capsule-Log-Level"; private static final Set<String> NON_MODAL_ATTRS = unmodifiableSet(new HashSet<String>(Arrays.asList( ATTR_APP_NAME, ATTR_APP_VERSION ))); // outgoing private static final String VAR_CAPSULE_APP = "CAPSULE_APP"; private static final String VAR_CAPSULE_DIR = "CAPSULE_DIR"; private static final String VAR_CAPSULE_JAR = "CAPSULE_JAR"; private static final String VAR_CLASSPATH = "CLASSPATH"; private static final String VAR_JAVA_HOME = "JAVA_HOME"; private static final String PROP_CAPSULE_JAR = "capsule.jar"; private static final String PROP_CAPSULE_DIR = "capsule.dir"; private static final String PROP_CAPSULE_APP = "capsule.app"; private static final String PROP_CAPSULE_APP_PID = "capsule.app.pid"; // misc private static final String CAPSULE_PROP_PREFIX = "capsule."; private static final String CACHE_DEFAULT_NAME = "capsule"; private static final String DEPS_CACHE_NAME = "deps"; private static final String APP_CACHE_NAME = "apps"; private static final String POM_FILE = "pom.xml"; private static final String SEPARATOR_DOT = "\\."; private static final String LOCK_FILE_NAME = ".lock"; private static final String TIMESTAMP_FILE_NAME = ".extracted"; private static final String FILE_SEPARATOR = System.getProperty(PROP_FILE_SEPARATOR); private static final char FILE_SEPARATOR_CHAR = FILE_SEPARATOR.charAt(0); private static final String PATH_SEPARATOR = System.getProperty(PROP_PATH_SEPARATOR); private static final Path WINDOWS_PROGRAM_FILES_1 = Paths.get("C:", "Program Files"); private static final Path WINDOWS_PROGRAM_FILES_2 = Paths.get("C:", "Program Files (x86)"); private static final int WINDOWS_MAX_CMD = 32500; private static final Object DEFAULT = new Object(); private static final Set<String> COMMON_ATTRIBUTES = unmodifiableSet(new HashSet<String>(Arrays.asList( ATTR_MANIFEST_VERSION, ATTR_MAIN_CLASS, "Created-By", "Signature-Version", "Sealed", "Magic", ATTR_IMPLEMENTATION_TITLE, ATTR_IMPLEMENTATION_VERSION, ATTR_IMPLEMENTATION_VENDOR, "Implementation-Vendor-Id", ATTR_IMPLEMENTATION_URL, "Specification-Title", "Specification-Version", "Specification-Vendor" ))); @SuppressWarnings("FieldMayBeFinal") private static Object DEPENDENCY_MANAGER = DEFAULT; // used only by tests // logging private static final String LOG_PREFIX = "CAPSULE: "; protected static final int LOG_NONE = 0; protected static final int LOG_QUIET = 1; protected static final int LOG_VERBOSE = 2; protected static final int LOG_DEBUG = 3; private static final int PROFILE = propertyDefined(PROP_PROFILE) ? LOG_QUIET : LOG_DEBUG; // options private static final int OPTION_METHOD = 0; private static final int OPTION_DEFAULT = 1; private static final int OPTION_DESC = 2; //</editor-fold> //<editor-fold desc="Main"> /////////// Main /////////////////////////////////// private static Capsule CAPSULE; private static final Map<String, String[]> OPTIONS = new LinkedHashMap<>(); static { registerOption(PROP_VERSION, "printVersion", "false", "Prints the capsule and application versions."); registerOption(PROP_MODES, "printModes", "false", "Prints all available capsule modes."); registerOption(PROP_TREE, "printDependencyTree", "false", "Prints the capsule's dependency tree."); registerOption(PROP_RESOLVE, "resolve", "false", "Downloads all un-cached dependencies."); registerOption(PROP_PRINT_JRES, "printJVMs", "false", "Prints a list of all JVM installations found."); registerOption(PROP_HELP, "printUsage", "false", "Prints this help message."); registerOption(PROP_MODE, null, null, "Picks the capsule mode to run."); registerOption(PROP_RESET, null, "false", "Resets the capsule cache before launching." + " The capsule to be re-extracted (if applicable), and other possibly cached files will be recreated."); registerOption(PROP_LOG_LEVEL, null, "quiet", "Picks a log level. Must be one of none, quiet, verbose, or debug."); registerOption(PROP_CAPSULE_JAVA_HOME, null, null, "Sets the location of the Java home (JVM installation directory) to use."); registerOption(PROP_CAPSULE_JAVA_CMD, null, null, "Sets the path to the Java executable to use."); registerOption(PROP_USE_LOCAL_REPO, null, null, "Sets the path of the local Maven repository to use."); registerOption(PROP_JVM_ARGS, null, null, "Sets additional JVM arguments to use when running the application."); } final static Capsule myCapsule(List<String> args) { if (CAPSULE == null) { final Capsule capsule = newCapsule(findOwnJarFile(), getCacheDir()); clearContext(); if (capsule.isEmptyCapsule() && !args.isEmpty()) { processCmdLineOptions(args); if (!args.isEmpty()) capsule.setTarget(args.remove(0)); } CAPSULE = capsule; } return CAPSULE; } public static final void main(String[] args) { System.exit(main0(args)); } @SuppressWarnings({"BroadCatchBlock", "CallToPrintStackTrace", "UnusedAssignment"}) private static int main0(String[] args0) { List<String> args = new ArrayList<>(Arrays.asList(args0)); // list must be mutable b/c myCapsule() might mutate it Capsule capsule = null; try { processOptions(); capsule = myCapsule(args); args = unmodifiableList(args); if (capsule.isFactoryCapsule() && !capsule.isEmptyCapsule()) // not a custom capsule System.exit(runMain(capsule.getJarFile(), args)); if (runActions(capsule, args)) return 0; return capsule.launch(args); } catch (Throwable t) { System.err.print("CAPSULE EXCEPTION: " + t.getMessage()); if (hasContext() && (t.getMessage() == null || t.getMessage().length() < 50)) System.err.print(" while processing " + reportContext()); if (getLogLevel(System.getProperty(PROP_LOG_LEVEL)) >= LOG_VERBOSE) { System.err.println(); t.printStackTrace(System.err); } else System.err.println(" (for stack trace, run with -D" + PROP_LOG_LEVEL + "=verbose)"); if (t instanceof IllegalArgumentException) printUsage(capsule != null ? capsule.isWrapperCapsule() : true, args); return 1; } } @SuppressWarnings("CallToPrintStackTrace") private static int runMain(Path jar, List<String> args) { try { new URLClassLoader(new URL[]{jar.toUri().toURL()}, null) .loadClass(getMainClass(jar)) .getMethod("main", String[].class).invoke(null, (Object) args.toArray(new String[0])); return 0; } catch (Exception e) { e.printStackTrace(); return 1; } } //<editor-fold defaultstate="collapsed" desc="Command Line"> /////////// Command Line /////////////////////////////////// /** * Registers a capsule command-line option. Must be called in the custom capsule class's static initializer. * <p> * Capsule options are system properties beginning with the prefix ".capsule", normally passed to the capsule as -D flags on the command line. * <p> * Options can be top-level *actions* (like print dependency tree or list JVMs), in which case the {@code methodName} argument must * be the name of a method used to launch the action instead of launching the capsule. * <p> * Options can have a default value, which will be automatically assigned to the system property if undefined. The default values * {@code "true"} and {@code "false"} are treated specially. If one of them is the assigned default value, and the system property * is defined with with a value of the empty string, then it will be re-assigned the value {@code "true"}. * <p> * <b>Simple Command Line Options for Wrapper Capsules</b><br> * When the capsule serves as a wrapper (i.e. it's an empty capsule used to launch an executable artifact or another capsule) * then the options can also be passed to the capsule as simple command line options (arguments starting with a hyphen), * with the "capsule." prefix removed, and every '.' character replaced with a '-'. * <p> * These command line arguments will automatically be converted to system properties, which will take their value from the argument * following the option (i.e. {@code -option value}), <i>unless</i> the option is given one of the special default values * {@code "true"} or {@code "false"}, in which case it is treated as a flag with no arguments (note that an option with the default * value {@code "true"} will therefore not be able to be turned off if simple options are used). * * @param optionName the name of the system property for the option; must begin with {@code "capsule."}. * @param methodName if non-null, then the option is a top-level action (like print dependency tree or list JVMs), * and this is the method which will run the action. * The method must accept a single {@code args} parameter of type {@code List<String>}. * @param defaultValue the option's default value ({@code "true"} and {@code "false"} are specially treated; see above). */ protected static final void registerOption(String optionName, String methodName, String defaultValue, String description) { if (!optionName.startsWith(CAPSULE_PROP_PREFIX)) throw new IllegalArgumentException("Option name must start with " + CAPSULE_PROP_PREFIX + " but was " + optionName); OPTIONS.put(optionName, new String[]{methodName, defaultValue, description}); } private static boolean optionTakesArguments(String propertyName) { final String defaultValue = OPTIONS.get(propertyName)[OPTION_DEFAULT]; return !("false".equals(defaultValue) || "true".equals(defaultValue)); } private static void processOptions() { for (Map.Entry<String, String[]> entry : OPTIONS.entrySet()) { final String option = entry.getKey(); if (System.getProperty(option) == null && entry.getValue()[OPTION_DEFAULT] != null) System.setProperty(option, entry.getValue()[OPTION_DEFAULT]); else if (optionTakesArguments(option) && "".equals(System.getProperty(option))) System.setProperty(option, "true"); } } private static void processCmdLineOptions(List<String> args) { while (!args.isEmpty()) { if (!args.get(0).startsWith("-")) break; final String arg = args.remove(0); final String option = simpleToOption(arg); if (option == null) throw new IllegalArgumentException("Unrecognized option: " + arg); if (System.getProperty(option) != null) { // -D wins over simple flags if (optionTakesArguments(option)) System.setProperty(option, args.remove(0)); else System.setProperty(option, ""); } } processOptions(); } private static boolean runActions(Capsule capsule, List<String> args) { try { boolean found = false; for (Map.Entry<String, String[]> entry : OPTIONS.entrySet()) { if (entry.getValue()[OPTION_METHOD] != null && systemPropertyEmptyOrTrue(entry.getKey())) { getMethod(capsule.getClass(), entry.getValue()[0], List.class).invoke(capsule, args); found = true; } } return found; } catch (InvocationTargetException e) { throw rethrow(e); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } } private static String optionToSimple(String option) { return "-" + camelCaseToDashed(option.substring(CAPSULE_PROP_PREFIX.length())).replace('.', '-'); } private static String simpleToOption(String simple) { if ("-h".equals(simple)) return PROP_HELP; for (String option : OPTIONS.keySet()) { if (simple.equals(optionToSimple(option))) return option; } return null; } private static String camelCaseToDashed(String camel) { return camel.replaceAll("([A-Z][a-z]+)", "-$1").toLowerCase(); } private static boolean isCapsuleOption(String propertyName) { return propertyName.startsWith(CAPSULE_PROP_PREFIX); // OPTIONS.containsKey(propertyName); } //</editor-fold> //</editor-fold> private static Map<String, Path> JAVA_HOMES; // an optimization trick (can be injected by CapsuleLauncher) // fields marked /*final*/ are effectively final after finalizeCapsule private final Path cacheDir; // never null private final boolean wrapper; private final Manifest manifest; // never null private /*final*/ Path jarFile; // never null private /*final*/ String appId; // null iff wrapper capsule wrapping a non-capsule JAR private /*final*/ String appName; // null iff wrapper capsule wrapping a non-capsule JAR private /*final*/ String appVersion; // null iff wrapper capsule wrapping a non-capsule JAR private /*final*/ String mode; private /*final*/ Object pom; // non-null iff jar has pom AND manifest doesn't have ATTR_DEPENDENCIES private /*final*/ Object dependencyManager; private /*final*/ int logLevel; private Path appCache; // non-null iff capsule is extracted private boolean cacheUpToDate; private FileLock appCacheLock; // Some very limited state private List<String> jvmArgs_; private List<String> args_; private Path pathingJar; private Process child; // Error reporting private static String contextType_; private static String contextKey_; private static String contextValue_; //<editor-fold defaultstate="collapsed" desc="Constructors"> /////////// Constructors /////////////////////////////////// /* * The constructors and methods in this section may be reflectively called by CapsuleLauncher */ /** * Constructs a capsule from the given JAR file. * <p> * This constructor or that of a subclass must not make use of any registered capsule options, * as they may not have been properly pre-processed yet. * * @param jarFile the path to the JAR file * @param cacheDir the path to the (shared) Capsule cache directory */ @SuppressWarnings("OverridableMethodCallInConstructor") protected Capsule(Path jarFile, Path cacheDir) { Objects.requireNonNull(jarFile, "jarFile can't be null"); Objects.requireNonNull(cacheDir, "cacheDir can't be null"); this.cacheDir = initCacheDir(cacheDir); this.jarFile = toAbsolutePath(jarFile); final long start = System.nanoTime(); // can't use clock before log level is set try (JarInputStream jis = openJarInputStream(jarFile)) { this.manifest = jis.getManifest(); if (manifest == null) throw new RuntimeException("Capsule " + jarFile + " does not have a manifest"); this.pom = createPomReader(jis); } catch (IOException e) { throw new RuntimeException("Could not read JAR file " + jarFile, e); } this.wrapper = isEmptyCapsule(); this.logLevel = chooseLogLevel(); // temporary, just for the sake of "time". will be overridden in finalizeCapsule time("Read JAR in constructor", start); if (!wrapper) finalizeCapsule(true); clearContext(); } final Capsule setTarget(String capsuleArtifact) { initDependencyManager(); final Path jar = isDependency(capsuleArtifact) ? firstOrNull(resolveDependency(capsuleArtifact, "jar")) : Paths.get(capsuleArtifact); if (jar == null) throw new RuntimeException(capsuleArtifact + " not found."); return setTarget(jar); } final Capsule setTarget(Path jar) { jar = toAbsolutePath(jar); if (appId != null) throw new IllegalStateException("Capsule is finalized"); if (!isEmptyCapsule()) throw new IllegalStateException("Capsule " + jarFile + " isn't empty"); if (jar.equals(jarFile)) // catch simple loops throw new RuntimeException("Capsule wrapping loop detected with capsule " + jarFile); final Manifest man; boolean isCapsule = false; final long start = clock(); try (JarInputStream jis = openJarInputStream(jar)) { man = jis.getManifest(); if (man == null || man.getMainAttributes().getValue(ATTR_MAIN_CLASS) == null) throw new IllegalArgumentException(jar + " is not a capsule or an executable JAR"); for (JarEntry entry; (entry = jis.getNextJarEntry()) != null;) { if (entry.getName().equals(Capsule.class.getName() + ".class")) isCapsule = true; else if (entry.getName().equals(POM_FILE)) this.pom = createPomReader0(jis); } } catch (IOException e) { throw new RuntimeException("Could not read JAR file " + jar, e); } time("Read JAR in setTarget", start); if (!isCapsule) manifest.getMainAttributes().putValue(ATTR_APP_ARTIFACT, jar.toString()); else { log(LOG_VERBOSE, "Wrapping capsule " + jar); this.jarFile = jar; merge(manifest, man); if (dependencyManager != null) setDependencyRepositories(getRepositories()); } finalizeCapsule(isCapsule); return this; } private void finalizeCapsule(boolean setId) { validateManifest(); this.logLevel = chooseLogLevel(); initDependencyManager(); final String[] nameAndVersion = setId ? buildAppId() : null; if (nameAndVersion != null) { this.appName = nameAndVersion[0]; this.appVersion = nameAndVersion[1]; this.appId = appName + (appVersion != null ? "_" + appVersion : ""); } this.mode = chooseMode1(); clearContext(); } private void initDependencyManager() { if (dependencyManager == null) { this.dependencyManager = DEPENDENCY_MANAGER != DEFAULT ? DEPENDENCY_MANAGER : tryCreateDependencyManager(); if (dependencyManager != null) setDependencyRepositories(getRepositories()); } } private boolean isEmptyCapsule() { return !hasAttribute(ATTR_APP_ARTIFACT) && !hasAttribute(ATTR_APP_CLASS) && !hasScript(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Properties"> /////////// Properties /////////////////////////////////// private boolean isWrapperOfNonCapsule() { return appId == null; } private boolean isFactoryCapsule() { if (!getClass().equals(Capsule.class) || !wrapper) return false; for (Object attr : manifest.getMainAttributes().keySet()) { if (!isCommonAttribute(attr.toString())) return false; } for (Attributes atts : manifest.getEntries().values()) { for (Object attr : atts.keySet()) { if (!isCommonAttribute(attr.toString())) return false; } } log(LOG_DEBUG, "Factory (unchanged) capsule"); return true; } /** * Whether or not this is an empty capsule */ protected final boolean isWrapperCapsule() { return wrapper; } /** * This capsule's current mode. */ protected final String getMode() { return mode; } /** * This capsule's cache directory, or {@code null} if capsule has been configured not to extract. */ protected final Path getAppCache() { return appCache; } /** * This capsule's JAR file. */ protected final Path getJarFile() { return jarFile; } /** * The app's name */ protected final String getAppName() { return appName; } /** * The app's version or {@code null} if unversioned. */ protected final String getAppVersion() { return appVersion; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Capsule JAR"> /////////// Capsule JAR /////////////////////////////////// private static Path findOwnJarFile() { final URL url = Capsule.class.getClassLoader().getResource(Capsule.class.getName().replace('.', '/') + ".class"); if (!"jar".equals(url.getProtocol())) throw new IllegalStateException("The Capsule class must be in a JAR file, but was loaded from: " + url); final String path = url.getPath(); if (path == null || !path.startsWith("file:")) throw new IllegalStateException("The Capsule class must be in a local JAR file, but was loaded from: " + url); try { final URI jarUri = new URI(path.substring(0, path.indexOf('!'))); return Paths.get(jarUri); } catch (URISyntaxException e) { throw new AssertionError(e); } } private String toJarUrl(String relPath) { return "jar:file:" + jarFile.toAbsolutePath() + "!/" + relPath; } private InputStream getEntry(ZipInputStream zis, String name) throws IOException { for (ZipEntry entry; (entry = zis.getNextEntry()) != null;) { if (entry.getName().equals(name)) return zis; } return null; } private static boolean isExecutable(Path path) { if (!Files.isExecutable(path)) return false; try (Reader reader = new InputStreamReader(Files.newInputStream(path), "UTF-8")) { int c = reader.read(); if (c < 0 || (char) c != ' return false; c = reader.read(); if (c < 0 || (char) c != '!') return false; return true; } catch (IOException e) { throw new RuntimeException(e); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Main Operations"> /////////// Main Operations /////////////////////////////////// void printVersion(List<String> args) { if (getAppId() != null) { System.out.println(LOG_PREFIX + "Application " + getAppId()); for (String attr : Arrays.asList(ATTR_IMPLEMENTATION_TITLE, ATTR_IMPLEMENTATION_VENDOR, ATTR_IMPLEMENTATION_URL)) { if (hasAttribute(attr)) System.out.println(LOG_PREFIX + getAttribute(attr)); } } System.out.println(LOG_PREFIX + "Capsule Version " + VERSION); } void printModes(List<String> args) { verifyNonEmpty("Cannot print modes of a wrapper capsule."); System.out.println(LOG_PREFIX + "Application " + getAppId()); System.out.println("Available modes:"); final Set<String> modes = getModes(); if (modes.isEmpty()) System.out.println("Default mode only"); else { for (String m : modes) { final String desc = getModeDescription(m); System.out.println("* " + m + (desc != null ? ": " + desc : "")); } } } void printJVMs(List<String> args) { final Map<String, Path> jres = getJavaHomes(); if (jres == null) println("No detected Java installations"); else { System.out.println(LOG_PREFIX + "Detected Java installations:"); for (Map.Entry<String, Path> j : jres.entrySet()) System.out.println(j.getKey() + (j.getKey().length() < 8 ? "\t\t" : "\t") + j.getValue()); } final Path javaHome = chooseJavaHome(); System.out.println(LOG_PREFIX + "selected " + (javaHome != null ? javaHome : (systemProperty(PROP_JAVA_HOME) + " (current)"))); } void printUsage(List<String> args) { printUsage(wrapper, args); } static void printUsage(boolean simple, List<String> args) { final Path myJar = toFriendlyPath(findOwnJarFile()); final boolean executable = isExecutable(myJar); final StringBuilder usage = new StringBuilder(); if (!executable) usage.append("java "); if (simple) { if (!executable) usage.append("-jar "); usage.append(myJar).append(' '); } usage.append("<options> "); if (simple) usage.append("<path or Maven coords of application JAR/capsule>"); else usage.append(myJar); System.err.println("USAGE: " + usage); System.err.println("Options:"); for (Map.Entry<String, String[]> entry : OPTIONS.entrySet()) { if (entry.getValue()[OPTION_DESC] != null) { final String option = entry.getKey(); final String defaultValue = entry.getValue()[OPTION_DEFAULT]; if (simple && !optionTakesArguments(option) && defaultValue.equals("true")) continue; StringBuilder sb = new StringBuilder(); sb.append(simple ? optionToSimple(option) : option); if (optionTakesArguments(option) || defaultValue.equals("true")) { sb.append(simple ? ' ' : '=').append("<value>"); if (defaultValue != null) sb.append(" (default: ").append(defaultValue).append(")"); } sb.append(" - ").append(entry.getValue()[OPTION_DESC]); System.err.println(" " + sb); } } if (!simple && !executable) usage.append("-jar "); } void printDependencyTree(List<String> args) { verifyNonEmpty("Cannot print dependencies of a wrapper capsule."); System.out.println("Dependencies for " + getAppId()); if (dependencyManager == null) System.out.println("No dependencies declared."); else if (hasAttribute(ATTR_APP_ARTIFACT)) { final String appArtifact = getAttribute(ATTR_APP_ARTIFACT); if (appArtifact == null) throw new IllegalStateException("capsule " + jarFile + " has nothing to run"); printDependencyTree(appArtifact, "jar"); } else printDependencyTree(getDependencies(), "jar"); final List<String> nativeDeps = getNativeDependencies(); if (nativeDeps != null) { System.out.println("\nNative Dependencies:"); printDependencyTree(nativeDeps, getNativeLibExtension()); } } void resolve(List<String> args) throws IOException, InterruptedException { verifyNonEmpty("Cannot resolve a wrapper capsule."); ensureExtractedIfNecessary(); resolveDependency(getAttribute(ATTR_APP_ARTIFACT), "jar"); resolveDependencies(getDependencies(), "jar"); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH)); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH_P)); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH_A)); resolveNativeDependencies(); log(LOG_QUIET, "Capsule resolved"); } private int launch(List<String> args) throws IOException, InterruptedException { verifyNonEmpty("Cannot launch a wrapper capsule."); final ProcessBuilder pb; try { final List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); pb = prepareForLaunch(jvmArgs, args); if (pb == null) { // can be null if prelaunch has been overridden by a subclass log(LOG_VERBOSE, "Nothing to run"); return 0; } } catch (Throwable t) { cleanup(); throw t; } clearContext(); log(LOG_VERBOSE, join(pb.command(), " ") + (pb.directory() != null ? " (Running in " + pb.directory() + ")" : "")); if (isTrampoline()) { if (hasAttribute(ATTR_ENV)) throw new RuntimeException("Capsule cannot trampoline because manifest defines the " + ATTR_ENV + " attribute."); pb.command().remove("-D" + PROP_TRAMPOLINE); System.out.println(join(pb.command(), " ")); } else { Runtime.getRuntime().addShutdownHook(new Thread(this)); if (!isInheritIoBug()) pb.inheritIO(); this.child = pb.start(); if (isInheritIoBug()) pipeIoStreams(); final int pid = getPid(child); if (pid > 0) System.setProperty(PROP_CAPSULE_APP_PID, Integer.toString(pid)); child.waitFor(); } return child != null ? child.exitValue() : 0; } private void verifyNonEmpty(String message) { if (isEmptyCapsule()) throw new IllegalArgumentException(message); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Launch"> /////////// Launch /////////////////////////////////// // directly used by CapsuleLauncher final ProcessBuilder prepareForLaunch(List<String> jvmArgs, List<String> args) { final long start = clock(); this.jvmArgs_ = nullToEmpty(jvmArgs); // hack this.args_ = nullToEmpty(jvmArgs); // hack log(LOG_VERBOSE, "Launching app " + appId + (mode != null ? " in mode " + mode : "")); try { final ProcessBuilder pb; try { ensureExtractedIfNecessary(); pb = prelaunch(nullToEmpty(args)); markCache1(); return pb; } finally { unlockAppCache(); time("prepareForLaunch", start); } } catch (IOException e) { throw new RuntimeException(e); } } /** * @deprecated marked deprecated to exclude from javadoc */ @Override public final void run() { if (isInheritIoBug() && pipeIoStream()) return; // shutdown hook cleanup(); } /** * Called when the capsule exits after a successful or failed attempt to launch the application. * If you override this method, you must make sure to call {@code super.cleanup()} even in the event of an abnormal termination * (i.e. when an exception is thrown). This method must not throw any exceptions. All exceptions origination by {@code cleanup} * must be wither ignored completely or printed to STDERR. */ @SuppressWarnings("CallToPrintStackTrace") protected void cleanup() { try { if (child != null) child.destroy(); } catch (Throwable t) { t.printStackTrace(); } try { if (pathingJar != null) Files.delete(pathingJar); } catch (Throwable t) { t.printStackTrace(); } } private String chooseMode1() { String m = chooseMode(); if (m != null && !hasMode(m)) throw new IllegalArgumentException("Capsule " + jarFile + " does not have mode " + m); return m; } /** * Chooses this capsule's mode. * The mode is chosen during the preparations for launch (not at construction time). */ protected String chooseMode() { return emptyToNull(systemProperty(PROP_MODE)); } /** * Returns a configured {@link ProcessBuilder} that is later used to launch the capsule. * The ProcessBuilder's IO redirection is left in its default settings. * Custom capsules may override this method to display a message prior to launch, or to configure the process's IO streams. * For more elaborate manipulation of the Capsule's launched process, consider overriding {@link #buildProcess() buildProcess}. * * @param args the application command-line arguments * @return a configured {@code ProcessBuilder} (if {@code null}, the launch will be aborted). */ protected ProcessBuilder prelaunch(List<String> args) { final ProcessBuilder pb = buildProcess(); buildEnvironmentVariables(pb); pb.command().addAll(buildArgs(args)); return pb; } /** * Constructs a {@link ProcessBuilder} that is later used to launch the capsule. * The returned process builder should contain the command <i>minus</i> the application arguments (which are later constructed by * {@link #buildArgs(List) buildArgs} and appended to the command).<br> * While environment variables may be set at this stage, the environment is later configured by * {@link #buildEnvironmentVariables(Map) buildEnvironmentVariables}. * <p> * This implementation tries to create a process running a startup script, and, if one has not been set, constructs a Java process. * <p> * This method should be overridden to add new types of processes the capsule can launch (like, say, Python scripts). * If all you want is to configure the returned {@link ProcessBuilder}, for example to set IO stream redirection, * you should override {@link #prelaunch(List) prelaunch}. * * @return a {@code ProcessBuilder} (must never be {@code null}). */ protected ProcessBuilder buildProcess() { if (jvmArgs_ == null) throw new IllegalStateException("Capsule has not been prepared for launch!"); final ProcessBuilder pb = new ProcessBuilder(); if (!buildScriptProcess(pb)) buildJavaProcess(pb, jvmArgs_, args_); return pb; } /** * Returns a list of command line arguments to pass to the application. * * @param args The command line arguments passed to the capsule at launch */ protected List<String> buildArgs(List<String> args) { return expandArgs(nullToEmpty(expand(getListAttribute(ATTR_ARGS))), args); } // visible for testing static List<String> expandArgs(List<String> args0, List<String> args) { final List<String> args1 = new ArrayList<String>(); boolean expanded = false; for (String a : args0) { if (a.startsWith("$")) { if (a.equals("$*")) { args1.addAll(args); expanded = true; continue; } else { try { final int i = Integer.parseInt(a.substring(1)); args1.add(args.get(i - 1)); expanded = true; continue; } catch (NumberFormatException e) { } } } args1.add(a); } if (!expanded) args1.addAll(args); return args1; } private void buildEnvironmentVariables(ProcessBuilder pb) { Map<String, String> env = new HashMap<>(pb.environment()); env = buildEnvironmentVariables(env); pb.environment().clear(); pb.environment().putAll(env); } /** * Returns a map of environment variables (property-value pairs). * * @param env the current environment */ protected Map<String, String> buildEnvironmentVariables(Map<String, String> env) { final List<String> jarEnv = getListAttribute(ATTR_ENV); if (jarEnv != null) { for (String e : jarEnv) { String var = getBefore(e, '='); String value = getAfter(e, '='); if (var.isEmpty()) throw new IllegalArgumentException("Malformed env variable definition: " + e); boolean overwrite = false; if (var.endsWith(":")) { overwrite = true; var = var.substring(0, var.length() - 1); } if (overwrite || !env.containsKey(var)) env.put(var, value != null ? value : ""); } } if (appId != null) { if (appCache != null) env.put(VAR_CAPSULE_DIR, processOutgoingPath(appCache)); env.put(VAR_CAPSULE_JAR, processOutgoingPath(jarFile)); env.put(VAR_CAPSULE_APP, appId); } return env; } private static boolean isTrampoline() { return propertyDefined(PROP_TRAMPOLINE); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="App ID"> /////////// App ID /////////////////////////////////// /** * Computes and returns application's ID. * * @return An array of exactly two strings, the first being the application's name, and the second, its version (or {@code null} if no version). */ protected String[] buildAppId() { String name; String version = null; name = getAttribute(ATTR_APP_NAME); if (name == null) { final String appArtifact = getAttribute(ATTR_APP_ARTIFACT); if (appArtifact != null && isDependency(appArtifact)) { if (hasModalAttribute(ATTR_APP_ARTIFACT)) throw new IllegalArgumentException("App ID-related attribute " + ATTR_APP_ARTIFACT + " is defined in a modal section of the manifest. " + " In this case, you must add the " + ATTR_APP_NAME + " attribute to the manifest's main section."); final String[] nameAndVersion = getAppArtifactId(getAppArtifactSpecificVersion(appArtifact)); name = nameAndVersion[0]; version = nameAndVersion[1]; } } if (name == null) { if (pom != null) { final String[] nameAndVersion = getPomAppNameAndVersion(); name = nameAndVersion[0]; version = nameAndVersion[1]; } } if (name == null) { name = getAttribute(ATTR_APP_CLASS); if (name != null && hasModalAttribute(ATTR_APP_CLASS)) throw new IllegalArgumentException("App ID-related attribute " + ATTR_APP_CLASS + " is defined in a modal section of the manifest. " + " In this case, you must add the " + ATTR_APP_NAME + " attribute to the manifest's main section."); } if (name == null) { throw new IllegalArgumentException("Capsule jar " + jarFile + " must either have the " + ATTR_APP_NAME + " manifest attribute, " + "the " + ATTR_APP_CLASS + " attribute, or contain a " + POM_FILE + " file."); } if (version == null) version = hasAttribute(ATTR_APP_VERSION) ? getAttribute(ATTR_APP_VERSION) : getAttribute(ATTR_IMPLEMENTATION_VERSION); return new String[]{name, version}; } /** * Returns the app's ID. */ protected final String getAppId() { return appId; } private static String[] getAppArtifactId(String coords) { if (coords == null) return null; final String[] cs = coords.split(":"); if (cs.length < 3) throw new IllegalArgumentException("Illegal main artifact coordinates: " + coords); String name = cs[0] + "_" + cs[1]; String version = cs[2]; return new String[]{name, version}; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Capsule Cache"> /////////// Capsule Cache /////////////////////////////////// private static Path getCacheDir() { final Path cache; final String cacheDirEnv = System.getenv(ENV_CACHE_DIR); if (cacheDirEnv != null) cache = Paths.get(cacheDirEnv); else { final String cacheNameEnv = System.getenv(ENV_CACHE_NAME); final String cacheName = cacheNameEnv != null ? cacheNameEnv : CACHE_DEFAULT_NAME; cache = getCacheHome().resolve((isWindows() ? "" : ".") + cacheName); } return cache; } private static Path initCacheDir(Path cache) { try { if (!Files.exists(cache)) Files.createDirectory(cache); Files.createDirectories(cache.resolve(APP_CACHE_NAME)); Files.createDirectories(cache.resolve(DEPS_CACHE_NAME)); return cache; } catch (IOException e) { throw new RuntimeException("Error opening cache directory " + cache.toAbsolutePath(), e); } } private static Path getCacheHome() { final Path userHome = Paths.get(systemProperty(PROP_USER_HOME)); if (!isWindows()) return userHome; Path localData; final String localAppData = getenv("LOCALAPPDATA"); if (localAppData != null) { localData = Paths.get(localAppData); if (!Files.isDirectory(localData)) throw new RuntimeException("%LOCALAPPDATA% set to nonexistent directory " + localData); } else { localData = userHome.resolve(Paths.get("AppData", "Local")); if (!Files.isDirectory(localData)) localData = userHome.resolve(Paths.get("Local Settings", "Application Data")); if (!Files.isDirectory(localData)) throw new RuntimeException("%LOCALAPPDATA% is undefined, and neither " + userHome.resolve(Paths.get("AppData", "Local")) + " nor " + userHome.resolve(Paths.get("Local Settings", "Application Data")) + " have been found"); } return localData; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="App Cache"> /////////// App Cache /////////////////////////////////// private Path getAppCacheDir() throws IOException { assert appId != null; Path appDir = toAbsolutePath(cacheDir.resolve(APP_CACHE_NAME).resolve(appId)); try { if (!Files.exists(appDir)) Files.createDirectory(appDir); return appDir; } catch (IOException e) { throw new IOException("Application cache directory " + appDir.toAbsolutePath() + " could not be created."); } } private void ensureAppCacheIfNecessary() throws IOException { if (appCache != null) return; if (appId == null) return; this.appCache = needsAppCache() ? getAppCacheDir() : null; this.cacheUpToDate = appCache != null ? isAppCacheUpToDate1() : false; } private void ensureExtractedIfNecessary() throws IOException { final long start = clock(); ensureAppCacheIfNecessary(); if (appCache != null) { if (!cacheUpToDate) { resetAppCache(); if (shouldExtract()) extractCapsule(); } else log(LOG_VERBOSE, "App cache " + appCache + " is up to date."); } time("ensureExtracted", start); } /** * @return {@code true} if this capsule requires an app cache; {@code false} otherwise. */ protected boolean needsAppCache() { if (hasRenamedNativeDependencies()) return true; // if (hasAttribute(ATTR_APP_ARTIFACT) && isDependency(getAttribute(ATTR_APP_ARTIFACT))) // return false; return shouldExtract(); } private boolean shouldExtract() { return getAttribute(ATTR_EXTRACT, true); } private void resetAppCache() throws IOException { try { log(LOG_DEBUG, "Creating cache for " + jarFile + " in " + appCache.toAbsolutePath()); final Path lockFile = appCache.resolve(LOCK_FILE_NAME); try (DirectoryStream<Path> ds = Files.newDirectoryStream(appCache)) { for (Path f : ds) { if (lockFile.equals(f)) continue; delete(f); } } } catch (IOException e) { throw new IOException("Exception while extracting jar " + jarFile + " to app cache directory " + appCache.toAbsolutePath(), e); } } private boolean isAppCacheUpToDate1() throws IOException { boolean res = testAppCacheUpToDate(); if (!res) { lockAppCache(); res = testAppCacheUpToDate(); if (res) unlockAppCache(); } return res; } /** * Tests if the app cache is up to date. * * The app cache directory is obtained by calling {@link #getAppCache() getAppCache}. * This creates a file in the app cache, whose timestamp is compared with the capsule's JAR timestamp. */ protected boolean testAppCacheUpToDate() throws IOException { if (systemPropertyEmptyOrTrue(PROP_RESET)) return false; Path extractedFile = appCache.resolve(TIMESTAMP_FILE_NAME); if (!Files.exists(extractedFile)) return false; FileTime extractedTime = Files.getLastModifiedTime(extractedFile); FileTime jarTime = Files.getLastModifiedTime(jarFile); return extractedTime.compareTo(jarTime) >= 0; } /** * Whether the app cache is up to date. * This is the result returned from {@link #testAppCacheUpToDate() }. */ protected final boolean isAppCacheUpToDate() { return cacheUpToDate; } /** * Extracts the capsule's contents into the app cache directory. * This method may be overridden to write additional files to the app cache. */ protected void extractCapsule() throws IOException { try { log(LOG_VERBOSE, "Extracting " + jarFile + " to app cache directory " + appCache.toAbsolutePath()); extractJar(openJarInputStream(jarFile), appCache); } catch (IOException e) { throw new IOException("Exception while extracting jar " + jarFile + " to app cache directory " + appCache.toAbsolutePath(), e); } } private void markCache1() throws IOException { if (appCache == null || cacheUpToDate) return; markCache(); } /** * Called after a successful completion of launch preparation if an app cache is used * to write persistent information to the cache denoting the successful preparation. */ protected void markCache() throws IOException { Files.createFile(appCache.resolve(TIMESTAMP_FILE_NAME)); } private void lockAppCache() throws IOException { final Path lockFile = appCache.resolve(LOCK_FILE_NAME); log(LOG_VERBOSE, "Locking " + lockFile); final FileChannel c = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE); this.appCacheLock = c.lock(); } private void unlockAppCache() throws IOException { if (appCacheLock != null) { log(LOG_VERBOSE, "Unocking " + appCache.resolve(LOCK_FILE_NAME)); appCacheLock.release(); appCacheLock.acquiredBy().close(); appCacheLock = null; } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Script Process"> /////////// Script Process /////////////////////////////////// private boolean hasScript() { return hasAttribute(isWindows() ? ATTR_WINDOWS_SCRIPT : ATTR_UNIX_SCRIPT); } private Path getScript() { final String s = getAttribute(isWindows() ? ATTR_WINDOWS_SCRIPT : ATTR_UNIX_SCRIPT); return s != null ? sanitize(appCache.resolve(s.replace('/', FILE_SEPARATOR_CHAR))) : null; } private boolean buildScriptProcess(ProcessBuilder pb) { final Path script = getScript(); if (script == null) return false; if (appCache == null) throw new IllegalStateException("Cannot run the startup script " + script + " when the " + ATTR_EXTRACT + " attribute is set to false"); setJavaHomeEnv(pb, getJavaHome()); final List<Path> classPath = buildClassPath(); resolveNativeDependencies(); pb.environment().put(VAR_CLASSPATH, compileClassPath(classPath)); ensureExecutable(script); pb.command().add(processOutgoingPath(script)); return true; } private Path setJavaHomeEnv(ProcessBuilder pb, Path javaHome) { if (javaHome == null) return null; pb.environment().put(VAR_JAVA_HOME, javaHome.toString()); return javaHome; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Java Process"> /////////// Java Process /////////////////////////////////// private boolean buildJavaProcess(ProcessBuilder pb, List<String> cmdLine, List<String> args) { final List<String> command = pb.command(); command.add(processOutgoingPath(getJavaExecutable())); command.addAll(buildJVMArgs(cmdLine)); command.addAll(compileSystemProperties(buildSystemProperties(cmdLine))); addOption(command, "-Xbootclasspath:", compileClassPath(buildBootClassPath(cmdLine))); addOption(command, "-Xbootclasspath/p:", compileClassPath(buildBootClassPathP())); addOption(command, "-Xbootclasspath/a:", compileClassPath(buildBootClassPathA())); command.addAll(compileJavaAgents(buildJavaAgents())); final List<Path> classPath = buildClassPath(); final String mainClass = getMainClass(classPath); command.add("-classpath"); command.add(compileClassPath(handleLongClasspath(classPath, mainClass.length(), command, args))); command.add(mainClass); return true; } private List<Path> handleLongClasspath(List<Path> cp, int extra, List<?>... args) { if (!isWindows()) return cp; // why work hard if we know the problem only exists on Windows? long len = extra + getStringsLength(cp) + cp.size(); for (List<?> list : args) len += getStringsLength(list) + list.size(); if (len >= getMaxCommandLineLength()) { log(LOG_DEBUG, "Command line length: " + len); if (isTrampoline()) throw new RuntimeException("Command line too long and trampoline requested."); this.pathingJar = createPathingJar(Paths.get(systemProperty(PROP_TMP_DIR)), cp); log(LOG_VERBOSE, "Writing classpath: " + cp + " to pathing JAR: " + pathingJar); return singletonList(pathingJar); } else return cp; } /** * Returns the path to the executable that will be used to launch Java. * The default implementation uses the {@code capsule.java.cmd} property or the {@code JAVACMD} environment variable, * and if not set, returns the value of {@code getJavaExecutable(getJavaHome())}. */ protected Path getJavaExecutable() { String javaCmd = emptyToNull(systemProperty(PROP_CAPSULE_JAVA_CMD)); if (javaCmd != null) return path(javaCmd); return getJavaExecutable(getJavaHome()); } /** * Finds the path to the executable that will be used to launch Java within the given {@code javaHome}. */ protected static final Path getJavaExecutable(Path javaHome) { final Path exec = getJavaExecutable0(javaHome); assert exec.startsWith(javaHome); return exec; } private static List<String> compileSystemProperties(Map<String, String> ps) { final List<String> command = new ArrayList<String>(); for (Map.Entry<String, String> entry : ps.entrySet()) command.add("-D" + entry.getKey() + (entry.getValue() != null && !entry.getValue().isEmpty() ? "=" + entry.getValue() : "")); return command; } private String compileClassPath(List<Path> cp) { return join(processOutgoingPath(cp), PATH_SEPARATOR); } private List<String> compileJavaAgents(Map<Path, String> jagents) { final List<String> command = new ArrayList<>(); for (Map.Entry<Path, String> jagent : nullToEmpty(jagents).entrySet()) command.add("-javaagent:" + processOutgoingPath(jagent.getKey()) + (jagent.getValue().isEmpty() ? "" : ("=" + jagent.getValue()))); return command; } private static void addOption(List<String> cmdLine, String prefix, String value) { if (value == null) return; cmdLine.add(prefix + value); } /** * Compiles and returns the application's classpath as a list of paths. */ protected List<Path> buildClassPath() { final long start = clock(); final List<Path> classPath = new ArrayList<Path>(); // the capsule jar if (!isWrapperOfNonCapsule()) { if (getAttribute(ATTR_CAPSULE_IN_CLASS_PATH, true)) classPath.add(jarFile); else if (appCache == null) throw new IllegalStateException("Cannot set the " + ATTR_CAPSULE_IN_CLASS_PATH + " attribute to false when the " + ATTR_EXTRACT + " attribute is also set to false"); } if (hasAttribute(ATTR_APP_ARTIFACT)) { if (isGlob(getAttribute(ATTR_APP_ARTIFACT))) throw new IllegalArgumentException("Glob pattern not allowed in " + ATTR_APP_ARTIFACT + " attribute."); final List<Path> app = isWrapperOfNonCapsule() ? singletonList(toAbsolutePath(path(getAttribute(ATTR_APP_ARTIFACT)))) : getPath(getAttribute(ATTR_APP_ARTIFACT)); classPath.addAll(app); final Path jar = app.get(0); final Manifest man = getManifest(jar); for (String e : nullToEmpty(parse(man.getMainAttributes().getValue(ATTR_CLASS_PATH)))) { Path p; try { p = path(new URL(e).toURI()); } catch (MalformedURLException | URISyntaxException ex) { p = jar.getParent().resolve(path(e.replace('/', FILE_SEPARATOR_CHAR))); } if (!classPath.contains(p)) classPath.add(isWrapperOfNonCapsule() ? toAbsolutePath(p) : sanitize(p)); } } if (hasAttribute(ATTR_APP_CLASS_PATH)) { for (String sp : getListAttribute(ATTR_APP_CLASS_PATH)) { if (isDependency(sp)) throw new IllegalArgumentException("Dependency " + sp + " is not allowed in the " + ATTR_APP_CLASS_PATH + " attribute"); addAllIfNotContained(classPath, getPath(sp)); } } if (appCache != null) addAllIfNotContained(classPath, nullToEmpty(getDefaultCacheClassPath())); classPath.addAll(nullToEmpty(resolveDependencies(getDependencies(), "jar"))); time("buildClassPath", start); return classPath; } private List<Path> getDefaultCacheClassPath() { final List<Path> cp = new ArrayList<Path>(listDir(appCache, "*.jar", true)); cp.add(0, appCache); return cp; } /** * Returns a list of dependencies, each in the format {@code groupId:artifactId:version[:classifier]} (classifier is optional) */ protected List<String> getDependencies() { List<String> deps = getListAttribute(ATTR_DEPENDENCIES); if ((deps == null || deps.isEmpty()) && pom != null) deps = getPomDependencies(); return (deps != null && !deps.isEmpty()) ? unmodifiableList(deps) : null; } /** * Compiles and returns the application's boot classpath as a list of paths. */ private List<Path> buildBootClassPath(List<String> cmdLine) { String option = null; for (String o : cmdLine) { if (o.startsWith("-Xbootclasspath:")) option = o.substring("-Xbootclasspath:".length()); } if (option != null) return toPath(Arrays.asList(option.split(PATH_SEPARATOR))); return buildBootClassPath(); } /** * Compiles and returns the application's boot classpath as a list of paths. */ protected List<Path> buildBootClassPath() { return getPath(getListAttribute(ATTR_BOOT_CLASS_PATH)); } /** * Compiles and returns the paths to be prepended to the application's boot classpath. */ protected List<Path> buildBootClassPathP() { return buildClassPath(ATTR_BOOT_CLASS_PATH_P); } /** * Compiles and returns the paths to be appended to the application's boot classpath. */ protected List<Path> buildBootClassPathA() { return buildClassPath(ATTR_BOOT_CLASS_PATH_A); } private List<Path> buildClassPath(String attr) { return getPath(getListAttribute(attr)); } private Map<String, String> buildSystemProperties(List<String> cmdLine) { final Map<String, String> systemProperties = buildSystemProperties(); // command line overrides everything for (String option : cmdLine) { if (option.startsWith("-D") && !isCapsuleOption(option.substring(2))) addSystemProperty(option.substring(2), systemProperties); } return systemProperties; } /** * Returns a map of system properties (property-value pairs). */ protected Map<String, String> buildSystemProperties() { final Map<String, String> systemProperties = new HashMap<String, String>(); // attribute for (Map.Entry<String, String> pv : nullToEmpty(getMapAttribute(ATTR_SYSTEM_PROPERTIES, "")).entrySet()) systemProperties.put(pv.getKey(), expand(pv.getValue())); // library path final List<Path> libraryPath = buildNativeLibraryPath(); systemProperties.put(PROP_JAVA_LIBRARY_PATH, compileClassPath(libraryPath)); if (hasAttribute(ATTR_SECURITY_POLICY) || hasAttribute(ATTR_SECURITY_POLICY_A)) { systemProperties.put(PROP_JAVA_SECURITY_MANAGER, ""); if (hasAttribute(ATTR_SECURITY_POLICY_A)) systemProperties.put(PROP_JAVA_SECURITY_POLICY, toJarUrl(getAttribute(ATTR_SECURITY_POLICY_A))); if (hasAttribute(ATTR_SECURITY_POLICY)) systemProperties.put(PROP_JAVA_SECURITY_POLICY, "=" + toJarUrl(getAttribute(ATTR_SECURITY_POLICY))); } if (hasAttribute(ATTR_SECURITY_MANAGER)) systemProperties.put(PROP_JAVA_SECURITY_MANAGER, getAttribute(ATTR_SECURITY_MANAGER)); // Capsule properties if (appId != null) { if (appCache != null) systemProperties.put(PROP_CAPSULE_DIR, processOutgoingPath(appCache)); systemProperties.put(PROP_CAPSULE_JAR, processOutgoingPath(jarFile)); systemProperties.put(PROP_CAPSULE_APP, appId); } return systemProperties; } private static void addSystemProperty(String p, Map<String, String> ps) { try { String name = getBefore(p, '='); String value = getAfter(p, '='); ps.put(name, value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Illegal system property definition: " + p); } } //<editor-fold desc="Native Dependencies"> /////////// Native Dependencies /////////////////////////////////// /** * Compiles and returns the application's native library as a list of paths. */ protected List<Path> buildNativeLibraryPath() { final List<Path> libraryPath = new ArrayList<Path>(getPlatformNativeLibraryPath()); resolveNativeDependencies(); if (appCache != null) { libraryPath.addAll(0, nullToEmpty(sanitize(appCache, getListAttribute(ATTR_LIBRARY_PATH_P)))); libraryPath.addAll(nullToEmpty(sanitize(appCache, getListAttribute(ATTR_LIBRARY_PATH_A)))); libraryPath.add(appCache); } else if (hasAttribute(ATTR_LIBRARY_PATH_P) || hasAttribute(ATTR_LIBRARY_PATH_A)) throw new IllegalStateException("Cannot use the " + ATTR_LIBRARY_PATH_P + " or the " + ATTR_LIBRARY_PATH_A + " attributes when the " + ATTR_EXTRACT + " attribute is set to false"); return libraryPath; } /** * Returns the default native library path for the Java platform the application uses. */ protected List<Path> getPlatformNativeLibraryPath() { // WARNING: this assumes the platform running the app (say a different Java home), has the same // java.library.path. If that's wrong, this could be a bug. return toPath(Arrays.asList(systemProperty(PROP_JAVA_LIBRARY_PATH).split(PATH_SEPARATOR))); } private void resolveNativeDependencies() { final List<String> depsAndRename = getNativeDependencies(); if (depsAndRename == null || depsAndRename.isEmpty()) return; if (appCache == null) throw new IllegalStateException("Cannot have native dependencies when the " + ATTR_EXTRACT + " attribute is set to false"); final List<String> deps = new ArrayList<String>(depsAndRename.size()); final List<String> renames = new ArrayList<String>(depsAndRename.size()); splitDepsAndRename(depsAndRename, deps, renames); log(LOG_VERBOSE, "Resolving native libs " + deps); final List<Path> resolved = resolveDependencies(deps, getNativeLibExtension()); if (resolved.size() != deps.size()) throw new RuntimeException("One of the native artifacts " + deps + " reolved to more than a single file or to none"); assert appCache != null; if (!cacheUpToDate) { if (isLogging(LOG_DEBUG)) System.err.println("Copying native libs to " + appCache); try { for (int i = 0; i < deps.size(); i++) { final Path lib = resolved.get(i); final String rename = renames.get(i); Files.copy(lib, sanitize(appCache.resolve(rename != null ? rename : lib.getFileName().toString()))); } } catch (IOException e) { throw new RuntimeException("Exception while copying native libs", e); } } } private void splitDepsAndRename(List<String> depsAndRename, List<String> deps, List<String> renames) { for (String depAndRename : depsAndRename) { String[] dna = depAndRename.split(","); deps.add(dna[0]); if (renames != null) renames.add(dna.length > 1 ? dna[1] : null); } } /** * Constructs this capsule's native dependency list. * * @return a list of native dependencies, each in the format {@code groupId:artifactId:version[:classifier][,renameTo]} * (classifier and renameTo are optional). */ protected List<String> getNativeDependencies() { if (isWindows()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_WIN); if (isMac()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_MAC); if (isUnix()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_LINUX); return null; } private boolean hasRenamedNativeDependencies() { final List<String> depsAndRename = getNativeDependencies(); if (depsAndRename == null) return false; for (String depAndRename : depsAndRename) { if (depAndRename.contains(",")) return true; } return false; } //</editor-fold> private List<String> buildJVMArgs(List<String> cmdLine) { final Map<String, String> jvmArgs = new LinkedHashMap<String, String>(); for (String option : buildJVMArgs()) addJvmArg(option, jvmArgs); for (String option : nullToEmpty(Capsule.split(systemProperty(PROP_JVM_ARGS), " "))) addJvmArg(option, jvmArgs); // command line overrides everything for (String option : cmdLine) { if (!option.startsWith("-D") && !option.startsWith("-Xbootclasspath:")) addJvmArg(option, jvmArgs); } return new ArrayList<String>(jvmArgs.values()); } /** * Returns a list of JVM arguments. */ protected List<String> buildJVMArgs() { final Map<String, String> jvmArgs = new LinkedHashMap<String, String>(); for (String a : nullToEmpty(getListAttribute(ATTR_JVM_ARGS))) { a = a.trim(); if (!a.isEmpty() && !a.startsWith("-Xbootclasspath:") && !a.startsWith("-javaagent:")) addJvmArg(expand(a), jvmArgs); } return new ArrayList<String>(jvmArgs.values()); } private static void addJvmArg(String a, Map<String, String> args) { args.put(getJvmArgKey(a), a); } private static String getJvmArgKey(String a) { if (a.equals("-client") || a.equals("-server")) return "compiler"; if (a.equals("-enablesystemassertions") || a.equals("-esa") || a.equals("-disablesystemassertions") || a.equals("-dsa")) return "systemassertions"; if (a.equals("-jre-restrict-search") || a.equals("-no-jre-restrict-search")) return "-jre-restrict-search"; if (a.startsWith("-Xloggc:")) return "-Xloggc"; if (a.startsWith("-Xss")) return "-Xss"; if (a.startsWith("-Xmx")) return "-Xmx"; if (a.startsWith("-Xms")) return "-Xms"; if (a.startsWith("-XX:+") || a.startsWith("-XX:-")) return "-XX:" + a.substring("-XX:+".length()); if (a.contains("=")) return a.substring(0, a.indexOf('=')); return a; } /** * Returns all Java agents that will be launched with the application. * * @return A map from the path to each agent to a string containing the agent arguments (or an empty string if none). */ protected Map<Path, String> buildJavaAgents() { final long start = clock(); final Map<String, String> agents0 = getMapAttribute(ATTR_JAVA_AGENTS, ""); if (agents0 == null) return null; final Map<Path, String> agents = new LinkedHashMap<>(agents0.size()); for (Map.Entry<String, String> agent : agents0.entrySet()) { final String agentJar = agent.getKey(); final String agentOptions = agent.getValue(); try { final Path agentPath = first(getPath(agent.getKey())); agents.put(agentPath, ((agentOptions != null && !agentOptions.isEmpty()) ? "=" + agentOptions : "")); } catch (IllegalStateException e) { if (appCache == null) throw new RuntimeException("Cannot run the embedded Java agent " + agentJar + " when the " + ATTR_EXTRACT + " attribute is set to false"); throw e; } } time("buildJavaAgents", start); return agents; } private String getMainClass(List<Path> classPath) { String mainClass = getAttribute(ATTR_APP_CLASS); if (mainClass == null && hasAttribute(ATTR_APP_ARTIFACT)) mainClass = getMainClass(getAppArtifactJarFromClasspath(classPath)); if (mainClass == null) throw new RuntimeException("Jar " + classPath.get(0).toAbsolutePath() + " does not have a main class defined in the manifest."); return mainClass; } private Path getAppArtifactJarFromClasspath(List<Path> classPath) { return classPath.get(0).equals(jarFile) ? classPath.get(1) : classPath.get(0); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Get Java Home"> /////////// Get Java Home /////////////////////////////////// private Path javaHome_; // cached value /** * The path to the Java installation this capsule's app will use. */ protected final Path getJavaHome() { if (javaHome_ == null) { final Path jhome = chooseJavaHome(); this.javaHome_ = jhome != null ? jhome : Paths.get(systemProperty(PROP_JAVA_HOME)); log(LOG_VERBOSE, "Using JVM: " + javaHome_); } return javaHome_; } /** * Chooses which Java installation to use for running the app. * * @return the path of the Java installation to use for launching the app, or {@code null} if the current JVM is to be used. */ protected Path chooseJavaHome() { final long start = clock(); Path jhome = emptyToNull(systemProperty(PROP_CAPSULE_JAVA_HOME)) != null ? Paths.get(systemProperty(PROP_CAPSULE_JAVA_HOME)) : null; if (jhome == null && !isMatchingJavaVersion(systemProperty(PROP_JAVA_VERSION))) { final boolean jdk = getAttribute(ATTR_JDK_REQUIRED, false); jhome = findJavaHome(jdk); if (isLogging(LOG_VERBOSE)) log(LOG_VERBOSE, "Finding JVM: " + ((System.nanoTime() - start) / 1_000_000) + "ms"); if (jhome == null) { throw new RuntimeException("Could not find Java installation for requested version " + '[' + "Min. Java version: " + getAttribute(ATTR_MIN_JAVA_VERSION) + " JavaVersion: " + getAttribute(ATTR_JAVA_VERSION) + " Min. update version: " + getAttribute(ATTR_MIN_UPDATE_VERSION) + ']' + " (JDK required: " + jdk + ")" + ". You can override the used Java version with the -D" + PROP_CAPSULE_JAVA_HOME + " flag."); } } time("chooseJavaHome", start); return jhome != null ? jhome.toAbsolutePath() : jhome; } private Path findJavaHome(boolean jdk) { Map<String, Path> homes = getJavaHomes(); if (jdk) homes = getJDKs(homes); if (homes == null) return null; Path best = null; String bestVersion = null; for (Map.Entry<String, Path> e : homes.entrySet()) { final String v = e.getKey(); log(LOG_DEBUG, "Trying JVM: " + e.getValue() + " (version " + e.getKey() + ")"); if (isMatchingJavaVersion(v)) { log(LOG_DEBUG, "JVM " + e.getValue() + " (version " + e.getKey() + ") matches"); if (bestVersion == null || compareVersions(v, bestVersion) > 0) { log(LOG_DEBUG, "JVM " + e.getValue() + " (version " + e.getKey() + ") is best so far"); bestVersion = v; best = e.getValue(); } } } return best; } private boolean isMatchingJavaVersion(String javaVersion) { try { if (hasAttribute(ATTR_MIN_JAVA_VERSION) && compareVersions(javaVersion, getAttribute(ATTR_MIN_JAVA_VERSION)) < 0) { log(LOG_DEBUG, "Java version " + javaVersion + " fails to match due to " + ATTR_MIN_JAVA_VERSION + ": " + getAttribute(ATTR_MIN_JAVA_VERSION)); return false; } if (hasAttribute(ATTR_JAVA_VERSION) && compareVersions(javaVersion, shortJavaVersion(getAttribute(ATTR_JAVA_VERSION)), 3) > 0) { log(LOG_DEBUG, "Java version " + javaVersion + " fails to match due to " + ATTR_JAVA_VERSION + ": " + getAttribute(ATTR_JAVA_VERSION)); return false; } if (getMinUpdateFor(javaVersion) > parseJavaVersion(javaVersion)[3]) { log(LOG_DEBUG, "Java version " + javaVersion + " fails to match due to " + ATTR_MIN_UPDATE_VERSION + ": " + getAttribute(ATTR_MIN_UPDATE_VERSION) + " (" + getMinUpdateFor(javaVersion) + ")"); return false; } log(LOG_DEBUG, "Java version " + javaVersion + " matches"); return true; } catch (IllegalArgumentException ex) { log(LOG_VERBOSE, "Error parsing Java version " + javaVersion); return false; } } private int getMinUpdateFor(String version) { final Map<String, String> m = getMapAttribute(ATTR_MIN_UPDATE_VERSION, null); if (m == null) return 0; final int[] ver = parseJavaVersion(version); for (Map.Entry<String, String> entry : m.entrySet()) { if (equals(ver, toInt(shortJavaVersion(entry.getKey()).split(SEPARATOR_DOT)), 3)) return Integer.parseInt(entry.getValue()); } return 0; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="POM"> /////////// POM /////////////////////////////////// private Object createPomReader(ZipInputStream zis) throws IOException { try { final InputStream is = getEntry(zis, POM_FILE); if (is == null) return null; return createPomReader0(is); } catch (IOException e) { throw new IOException("Could not read " + POM_FILE, e); } } private static Object createPomReader0(InputStream is) { try { return new PomReader(is); } catch (NoClassDefFoundError e) { throw new RuntimeException("JAR contains a pom.xml file, while the necessary dependency management classes are not found in the capsule"); } } private List<String> getPomRepositories() { return ((PomReader) pom).getRepositories(); } private List<String> getPomDependencies() { return ((PomReader) pom).getDependencies(); } private String[] getPomAppNameAndVersion() { final PomReader pr = (PomReader) pom; return new String[]{pr.getGroupId() + "_" + pr.getArtifactId(), pr.getVersion()}; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Dependency Manager"> /////////// Dependency Manager /////////////////////////////////// private List<String> getRepositories() { final List<String> repos = new ArrayList<String>(); final List<String> envRepos = Capsule.split(getenv(ENV_CAPSULE_REPOS), "[,\\s]\\s*"); final List<String> attrRepos = getListAttribute(ATTR_REPOSITORIES); if (envRepos != null) repos.addAll(envRepos); if (attrRepos != null) repos.addAll(attrRepos); if (pom != null) { for (String repo : nullToEmpty(getPomRepositories())) { if (!repos.contains(repo)) repos.add(repo); } } return !repos.isEmpty() ? unmodifiableList(repos) : null; } private Object tryCreateDependencyManager() { if (systemPropertyEmptyOrTrue(PROP_NO_DEP_MANAGER)) return null; try { final boolean reset = systemPropertyEmptyOrTrue(PROP_RESET); final Path localRepo = getLocalRepo(); return new DependencyManagerImpl(localRepo.toAbsolutePath(), reset, logLevel); } catch (NoClassDefFoundError e) { return null; } } private void verifyDependencyManager() { if (dependencyManager == null) throw new RuntimeException("Capsule " + jarFile + " uses dependencies, while the necessary dependency management classes are not found in the capsule JAR"); } private void setDependencyRepositories(List<String> repositories) { verifyDependencyManager(); ((DependencyManager) dependencyManager).setRepos(repositories, getAttribute(ATTR_ALLOW_SNAPSHOTS, false)); } protected Path getLocalRepo() { Path localRepo = cacheDir.resolve(DEPS_CACHE_NAME); final String local = expandCommandLinePath(propertyOrEnv(PROP_USE_LOCAL_REPO, ENV_CAPSULE_LOCAL_REPO)); if (local != null) localRepo = !local.isEmpty() ? toAbsolutePath(Paths.get(local)) : null; return localRepo; } private void printDependencyTree(String root, String type) { verifyDependencyManager(); ((DependencyManager) dependencyManager).printDependencyTree(root, type, System.out); } private void printDependencyTree(List<String> dependencies, String type) { if (dependencies == null) return; verifyDependencyManager(); ((DependencyManager) dependencyManager).printDependencyTree(dependencies, type, System.out); } private List<Path> resolveDependencies(List<String> dependencies, String type) { if (dependencies == null) return null; verifyDependencyManager(); final long start = clock(); final List<Path> res = ((DependencyManager) dependencyManager).resolveDependencies(dependencies, type); time("resolveDependencies", start); return res; } private List<Path> resolveDependency(String coords, String type) { if (coords == null) return null; verifyDependencyManager(); final long start = clock(); final List<Path> res = ((DependencyManager) dependencyManager).resolveDependency(coords, type); time("resolveDependency " + coords, start); return res; } private String getAppArtifactSpecificVersion(String appArtifact) { return getArtifactLatestVersion(appArtifact, "jar"); } private String getArtifactLatestVersion(String coords, String type) { if (coords == null) return null; verifyDependencyManager(); return ((DependencyManager) dependencyManager).getLatestVersion(coords, type); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Attributes"> /////////// Attributes /////////////////////////////////// /* * The methods in this section are the only ones accessing the manifest. Therefore other means of * setting attributes can be added by changing these methods alone. */ private void validateManifest() { if (manifest.getMainAttributes().getValue(ATTR_CLASS_PATH) != null) throw new IllegalStateException("Capsule manifest contains a " + ATTR_CLASS_PATH + " attribute." + " Use " + ATTR_APP_CLASS_PATH + " and/or " + ATTR_DEPENDENCIES + " instead."); validateNonModalAttributes(); } private void validateNonModalAttributes() { for (Map.Entry<String, Attributes> entry : manifest.getEntries().entrySet()) { for (String attr : NON_MODAL_ATTRS) { if (entry.getValue().containsKey(new Attributes.Name(attr))) throw new IllegalStateException("Manifest section " + entry.getKey() + " contains non-modal attribute " + attr); } } } private boolean hasModalAttribute(String attr) { final Attributes.Name key = new Attributes.Name(attr); for (Map.Entry<String, Attributes> entry : manifest.getEntries().entrySet()) { if (entry.getValue().containsKey(key)) return true; } return false; } private static boolean isCommonAttribute(String attr) { return COMMON_ATTRIBUTES.contains(attr) || attr.toLowerCase().endsWith("-digest"); } private static boolean isLegalModeName(String name) { return !name.contains("/") && !name.endsWith(".class"); } private boolean hasMode(String mode) { if (!isLegalModeName(mode)) throw new IllegalArgumentException(mode + " is an illegal mode name"); return manifest.getAttributes(mode) != null; } /** * Returns the names of all modes defined in this capsule's manifest. */ protected final Set<String> getModes() { final Set<String> modes = new HashSet<>(manifest.getEntries().size()); for (String section : manifest.getEntries().keySet()) { if (isLegalModeName(section)) modes.add(section); } return unmodifiableSet(modes); } /** * Returns the description of the given mode. */ protected final String getModeDescription(String mode) { if (!isLegalModeName(mode)) throw new IllegalArgumentException(mode + " is an illegal mode name"); return manifest.getAttributes(mode).getValue(ATTR_MODE_DESC); } /** * Returns the value of the given manifest attribute with consideration to the capsule's mode. * * @param attr the attribute */ protected final String getAttribute(String attr) { String value = null; if (mode != null && !NON_MODAL_ATTRS.contains(attr)) value = manifest.getAttributes(mode).getValue(attr); if (value == null) value = manifest.getMainAttributes().getValue(attr); setContext("attribute", attr, value); return value; } /** * Tests whether the given attribute is found in the manifest. * * @param attr the attribute */ protected final boolean hasAttribute(String attr) { final Attributes.Name key = new Attributes.Name(attr); if (mode != null && !NON_MODAL_ATTRS.contains(attr)) { if (manifest.getAttributes(mode).containsKey(key)) return true; } return manifest.getMainAttributes().containsKey(key); } private boolean getAttribute(String attr, boolean defaultValue) { final String val = getAttribute(attr); return val != null ? Boolean.parseBoolean(val) : defaultValue; } /** * Returns the value of the given attribute (with consideration to the capsule's mode) as a list. * The items comprising attribute's value must be whitespace-separated. * <p> * Same as {@code parse(getAttribute(attr))}. * * @param attr the attribute */ protected final List<String> getListAttribute(String attr) { return parse(getAttribute(attr)); } /** * Returns the value of the given attribute (with consideration to the capsule's mode) as a map. * The key-value pairs comprising attribute's value must be whitespace-separated, with each pair written as <i>key</i>=<i>value</i>. * <p> * Same as {@code parse(getAttribute(attr), defaultValue)}. * * @param attr the attribute * @param defaultValue a default value to use for keys without a value, or {@code null} if such an event should throw an exception */ protected final Map<String, String> getMapAttribute(String attr, String defaultValue) { return parse(getAttribute(attr), defaultValue); } /** * Parses an attribute's value string into a list. * The items comprising attribute's value must be whitespace-separated. * * @param value the attribute's value */ protected static final List<String> parse(String value) { return split(value, "\\s+"); } /** * Parses an attribute's value string into an ordered map. * The key-value pairs comprising string must be whitespace-separated, with each pair written as <i>key</i>=<i>value</i>. * * @param value the attribute's value * @param defaultValue a default value to use for keys without a value, or {@code null} if such an event should throw an exception */ protected static final Map<String, String> parse(String value, String defaultValue) { return split(value, '=', "\\s+", defaultValue); } /** * Combines collection elements into a string that can be used as the value of an attribute. */ protected static final String toStringValue(Collection<?> list) { return join(list, " "); } /** * Combines map elements into a string that can be used as the value of an attribute. */ protected static final String toStringValue(Map<?, ?> map) { return join(map, '=', " "); } private void merge(Manifest man1, Manifest man2) { if (man2 == null) return; merge(man1.getMainAttributes(), man2.getMainAttributes()); for (Map.Entry<String, Attributes> entry : man2.getEntries().entrySet()) { final Attributes attr = man1.getAttributes(entry.getKey()); if (attr != null) merge(attr, entry.getValue()); else man1.getEntries().put(entry.getKey(), entry.getValue()); } } private void merge(Attributes a1, Attributes a2) { for (Map.Entry<Object, Object> entry : a2.entrySet()) a1.put(entry.getKey(), merge(entry.getKey().toString(), (String) a1.get(entry.getKey()), (String) entry.getValue())); } /** * When using an empty capsule to launch another, this method will be called for each attribute in the wrapped (non-empty) manifest to merge * the wrapped capsule's attribute with the wrapper (empty) capsule's attribute. * When overriding this method, it may be useful to make use of {@link #parse(String) parse}, {@link #parse(String, String) parse map}, * {@link #toStringValue(Collection) toStringValue}, and {@link #toStringValue(Map) map toStringValue}. * <p> * The default implementation simply returns {@code value1}, unless it is {@code null} in which case it will pick {@code value2}; * in other words, it gives preference to the wrapper capsule's attributes. * * @param attribute the attribute's name * @param value1 the attribute's value in the wrapper (empty) capsule * @param value2 the attribute's value in the wrapped capsule * @return the value which will be used when launching the capsule */ protected String merge(String attribute, String value1, String value2) { return (value1 != null) ? value1 : value2; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Dependency Utils"> /////////// Dependency Utils /////////////////////////////////// private static boolean isDependency(String lib) { return lib.contains(":") && !lib.contains(":\\"); } private String dependencyToLocalJar(boolean withGroupId, String p) { String[] coords = p.split(":"); StringBuilder sb = new StringBuilder(); if (withGroupId) sb.append(coords[0]).append('-'); sb.append(coords[1]).append('-'); sb.append(coords[2]); if (coords.length > 3) sb.append('-').append(coords[3]); sb.append(".jar"); return sb.toString(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Paths"> /////////// Paths /////////////////////////////////// /** * Returns the path or paths to the given file descriptor. * The given descriptor can be a dependency, a file name (relative to the app cache) * or a glob pattern (again, relative to the app cache). The returned list can contain more than one element * if a dependency is given and it resolves to more than a single artifact, or if a glob pattern is given, * which matches more than one file. */ private List<Path> getPath(String p) { if (p == null) return null; if (isDependency(p) && dependencyManager != null) { final List<Path> res = resolveDependency(p, "jar"); if (res == null || res.isEmpty()) throw new RuntimeException("Dependency " + p + " was not found."); return res; } if (appCache == null) throw new IllegalStateException((isDependency(p) ? "Dependency manager not found. Cannot resolve" : "Capsule not extracted. Cannot obtain path") + " " + p); if (isDependency(p)) { Path f = appCache.resolve(dependencyToLocalJar(true, p)); if (Files.isRegularFile(f)) return singletonList(f); f = appCache.resolve(dependencyToLocalJar(false, p)); if (Files.isRegularFile(f)) return singletonList(f); throw new IllegalArgumentException("Dependency manager not found, and could not locate artifact " + p + " in capsule"); } else if (isGlob(p)) return listDir(appCache, p, false); else return singletonList(sanitize(appCache.resolve(p))); } /** * Returns a list which is a concatenation of all lists returned by calling * {@link #getPath(String) getPath(String)} on each of the file descriptors in the given list. */ private List<Path> getPath(List<String> ps) { if (ps == null) return null; final List<Path> res = new ArrayList<Path>(ps.size()); for (String p : ps) res.addAll(getPath(p)); return res; } /** * Every path emitted by the capsule to the app's command line, system properties or environment variables is * first passed through this method. Custom capsules that relocate files should override it. * * @param p the path * @return the processed path */ protected String processOutgoingPath(Path p) { if (p == null) return null; return toAbsolutePath(p).toString(); } private List<String> processOutgoingPath(List<Path> ps) { if (ps == null) return null; final List<String> res = new ArrayList<>(ps.size()); for (Path p : ps) res.add(processOutgoingPath(p)); return res; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="JAR Extraction"> /////////// JAR Extraction /////////////////////////////////// private static void extractJar(JarInputStream jar, Path targetDir) throws IOException { for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) { if (entry.isDirectory() || !shouldExtractFile(entry.getName())) continue; writeFile(targetDir, entry.getName(), jar); } } private static boolean shouldExtractFile(String fileName) { if (fileName.equals(Capsule.class.getName().replace('.', '/') + ".class") || (fileName.startsWith(Capsule.class.getName().replace('.', '/') + "$") && fileName.endsWith(".class"))) return false; if (fileName.endsWith(".class")) return false; if (fileName.startsWith("capsule/")) return false; if (fileName.startsWith("META-INF/")) return false; return true; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Path Utils"> /////////// Path Utils /////////////////////////////////// private Path path(String p, String... more) { return cacheDir.getFileSystem().getPath(p, more); } private Path path(URI uri) { return cacheDir.getFileSystem().provider().getPath(uri); } private List<Path> toPath(List<String> ps) { if (ps == null) return null; final List<Path> aps = new ArrayList<Path>(ps.size()); for (String p : ps) aps.add(path(p)); return aps; } private static Path toAbsolutePath(Path p) { return p.normalize().toAbsolutePath(); } private static List<Path> sanitize(Path root, List<String> ps) { if (ps == null) return null; final List<Path> aps = new ArrayList<Path>(ps.size()); for (String p : ps) aps.add(sanitize(root, root.resolve(p))); return aps; } private static Path sanitize(Path dir, Path p) { final Path path = p.normalize().toAbsolutePath(); if (!path.startsWith(dir)) throw new IllegalArgumentException("Path " + p + " is not local to " + dir); return path; } private Path sanitize(Path dir) { return sanitize(appCache, dir); } private static String expandCommandLinePath(String str) { if (str == null) return null; // if (isWindows()) // return str; // else return str.startsWith("~/") ? str.replace("~", System.getProperty(PROP_USER_HOME)) : str; } private static Path toFriendlyPath(Path p) { if (p.isAbsolute()) { Path rel = p.getFileSystem().getPath("").toAbsolutePath().relativize(p); if (rel.normalize().equals(rel)) return rel; } return p; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="OS"> /** * Tests whether the current OS is Windows. */ protected static final boolean isWindows() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("windows"); } /** * Tests whether the current OS is MacOS. */ protected static final boolean isMac() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("mac"); } /** * Tests whether the current OS is UNIX/Linux. */ protected static final boolean isUnix() { return System.getProperty(PROP_OS_NAME).toLowerCase().contains("nux") || System.getProperty(PROP_OS_NAME).toLowerCase().contains("solaris") || System.getProperty(PROP_OS_NAME).toLowerCase().contains("aix"); } private String getNativeLibExtension() { if (isWindows()) return "dll"; if (isMac()) return "dylib"; if (isUnix()) return "so"; throw new RuntimeException("Unsupported operating system: " + System.getProperty(PROP_OS_NAME)); } private static long getMaxCommandLineLength() { if (isWindows()) return WINDOWS_MAX_CMD; return Long.MAX_VALUE; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="JAR Utils"> /////////// JAR Utils /////////////////////////////////// private static JarInputStream openJarInputStream(Path jar) throws IOException { return new JarInputStream(skipToZipStart(Files.newInputStream(jar))); } private static String getMainClass(Path jar) { return getMainClass(getManifest(jar)); } private static String getMainClass(Manifest manifest) { if (manifest == null) return null; return manifest.getMainAttributes().getValue(ATTR_MAIN_CLASS); } private static Manifest getManifest(Path jar) { try (JarInputStream jis = openJarInputStream(jar)) { return jis.getManifest(); } catch (IOException e) { throw new RuntimeException("Error reading manifest from " + jar, e); } } private static final int[] ZIP_HEADER = new int[]{'\n', 'P', 'K', 0x03, 0x04}; private static InputStream skipToZipStart(InputStream is) throws IOException { if (!is.markSupported()) is = new BufferedInputStream(is); int state = 1; for (;;) { if (state == 1) is.mark(ZIP_HEADER.length); final int b = is.read(); if (b < 0) throw new IllegalArgumentException("Not a JAR/ZIP file"); if (b == ZIP_HEADER[state]) { state++; if (state == ZIP_HEADER.length) break; } else { state = 0; if (b == ZIP_HEADER[state]) state++; } } is.reset(); return is; } /** * @deprecated marked deprecated to exclude from javadoc. Visible for testing */ static Path createPathingJar(Path dir, List<Path> cp) { try { dir = dir.toAbsolutePath(); final List<Path> paths = new ArrayList<>(cp.size()); for (Path p : cp) // In order to use the Class-Path attribute, we must either relativize the paths, or specifiy them as file URLs paths.add(dir.relativize(p)); final Path pathingJar = Files.createTempFile(dir, "capsule_pathing_jar", ".jar"); final Manifest man = new Manifest(); man.getMainAttributes().putValue(ATTR_MANIFEST_VERSION, "1.0"); man.getMainAttributes().putValue(ATTR_CLASS_PATH, join(paths, " ")); new JarOutputStream(Files.newOutputStream(pathingJar), man).close(); return pathingJar; } catch (IOException e) { throw new RuntimeException("Pathing JAR creation failed", e); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="File Utils"> /////////// File Utils /////////////////////////////////// private static void writeFile(Path targetDir, String fileName, InputStream is) throws IOException { fileName = toNativePath(fileName); final String dir = getDirectory(fileName); if (dir != null) Files.createDirectories(targetDir.resolve(dir)); final Path targetFile = targetDir.resolve(fileName); Files.copy(is, targetFile); } private static String toNativePath(String filename) { final char ps = (!filename.contains("/") && filename.contains("\\")) ? '\\' : '/'; return ps != FILE_SEPARATOR_CHAR ? filename.replace(ps, FILE_SEPARATOR_CHAR) : filename; } private static String getDirectory(String filename) { final int index = filename.lastIndexOf(FILE_SEPARATOR_CHAR); if (index < 0) return null; return filename.substring(0, index); } /** * Deletes the given file or directory (even if nonempty). */ protected static void delete(Path path) throws IOException { if (Files.isDirectory(path)) { try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) { for (Path f : ds) delete(f); } } Files.delete(path); } /** * Copies the source file or directory (recursively) to the target location. */ protected static void copy(Path source, Path target) throws IOException { Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); if (Files.isDirectory(source)) { try (DirectoryStream<Path> ds = Files.newDirectoryStream(source)) { for (Path f : ds) copy(f, target.resolve(f.getFileName())); } } } private static void ensureExecutable(Path file) { if (!Files.isExecutable(file)) { try { Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file); if (!perms.contains(PosixFilePermission.OWNER_EXECUTE)) { Set<PosixFilePermission> newPerms = EnumSet.copyOf(perms); newPerms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, newPerms); } } catch (UnsupportedOperationException e) { } catch (IOException e) { throw new RuntimeException(e); } } } /** * Returns the contents of a directory. <br> * Passing {@code null} as the glob pattern is the same as passing {@code "*"} * * @param dir the directory * @param glob the glob pattern to use to filter the entries, or {@code null} if all entries are to be returned * @param regular whether only regular files should be returned */ protected static final List<Path> listDir(Path dir, String glob, boolean regular) { return listDir(dir, glob, false, regular, new ArrayList<Path>()); } private static boolean isGlob(String s) { return s.contains("*") || s.contains("?") || s.contains("{") || s.contains("["); } private static List<Path> listDir(Path dir, String glob, boolean recursive, boolean regularFile, List<Path> res) { return listDir(dir, splitGlob(glob), recursive, regularFile, res); } private static List<String> splitGlob(String glob) { // splits glob pattern by directory return glob != null ? Arrays.asList(glob.split(FILE_SEPARATOR_CHAR == '\\' ? "\\\\" : FILE_SEPARATOR)) : null; } @SuppressWarnings("null") private static List<Path> listDir(Path dir, List<String> globs, boolean recursive, boolean regularFile, List<Path> res) { PathMatcher matcher = null; if (globs != null) { while (!globs.isEmpty() && "**".equals(globs.get(0))) { recursive = true; globs = globs.subList(1, globs.size()); } if (!globs.isEmpty()) matcher = dir.getFileSystem().getPathMatcher("glob:" + globs.get(0)); } final List<Path> ms = (matcher != null || recursive) ? new ArrayList<Path>() : res; final List<Path> mds = matcher != null ? new ArrayList<Path>() : null; final List<Path> rds = recursive ? new ArrayList<Path>() : null; try (DirectoryStream<Path> fs = Files.newDirectoryStream(dir)) { for (Path f : fs) { if (recursive && Files.isDirectory(f)) rds.add(f); if (matcher == null) { if (!regularFile || Files.isRegularFile(f)) ms.add(f); } else { if (matcher.matches(f.getFileName())) { if (globs.size() == 1 && (!regularFile || Files.isRegularFile(f))) ms.add(f); else if (Files.isDirectory(f)) mds.add(f); } } } } catch (IOException e) { throw new RuntimeException(e); } sort(ms); // sort to give same reults on all platforms (hopefully) if (res != ms) { res.addAll(ms); recurse: for (List<Path> ds : Arrays.asList(mds, rds)) { if (ds == null) continue; sort(ds); final List<String> gls = (ds == mds ? globs.subList(1, globs.size()) : globs); for (Path d : ds) listDir(d, gls, recursive, regularFile, res); } } return res; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="JRE Installations"> /////////// JRE Installations /////////////////////////////////// private static Map<String, Path> getJDKs(Map<String, Path> homes) { Map<String, Path> jdks = new HashMap<>(); for (Map.Entry<String, Path> entry : homes.entrySet()) { Path home = entry.getValue(); if (isJDK(home)) jdks.put(entry.getKey(), entry.getValue()); } return jdks.isEmpty() ? null : jdks; } private static boolean isJDK(Path javaHome) { final String name = javaHome.toString().toLowerCase(); return name.contains("jdk") && !name.contains("jre"); } /** * Returns all found Java installations. * * @return a map from installations' versions to their respective paths */ protected static Map<String, Path> getJavaHomes() { if (JAVA_HOMES == null) { try { Path homesDir = null; for (Path d = Paths.get(System.getProperty(PROP_JAVA_HOME)); d != null; d = d.getParent()) { if (isJavaDir(d.getFileName().toString()) != null) { homesDir = d.getParent(); break; } } Map<String, Path> homes = getJavaHomes(homesDir); if (homes != null) { if (isWindows()) homes = windowsJavaHomesHeuristics(homesDir, homes); } JAVA_HOMES = homes; } catch (IOException e) { throw new RuntimeException(e); } } return JAVA_HOMES; } private static Map<String, Path> windowsJavaHomesHeuristics(Path dir, Map<String, Path> homes) throws IOException { Path dir2 = null; if (dir.startsWith(WINDOWS_PROGRAM_FILES_1)) dir2 = WINDOWS_PROGRAM_FILES_2.resolve(WINDOWS_PROGRAM_FILES_1.relativize(dir)); else if (dir.startsWith(WINDOWS_PROGRAM_FILES_2)) dir2 = WINDOWS_PROGRAM_FILES_1.resolve(WINDOWS_PROGRAM_FILES_2.relativize(dir)); if (dir2 != null) { Map<String, Path> allHomes = new HashMap<>(homes); allHomes.putAll(getJavaHomes(dir2)); return allHomes; } else return homes; } private static Map<String, Path> getJavaHomes(Path dir) throws IOException { if (dir == null) return null; if (!Files.isDirectory(dir)) return null; final Map<String, Path> dirs = new HashMap<String, Path>(); try (DirectoryStream<Path> fs = Files.newDirectoryStream(dir)) { for (Path f : fs) { if (Files.isDirectory(f)) { String dirName = f.getFileName().toString(); String ver = isJavaDir(dirName); if (ver != null) { Path home = searchJavaHomeInDir(f); if (home != null) { home = home.toAbsolutePath(); if (parseJavaVersion(ver)[3] == 0) ver = getActualJavaVersion(home); dirs.put(ver, home); } } } } } return !dirs.isEmpty() ? dirs : null; } // visible for testing static String isJavaDir(String fileName) { fileName = fileName.toLowerCase(); if (fileName.startsWith("jdk") || fileName.startsWith("jre") || fileName.endsWith(".jdk") || fileName.endsWith(".jre")) { if (fileName.startsWith("jdk") || fileName.startsWith("jre")) fileName = fileName.substring(3); if (fileName.endsWith(".jdk") || fileName.endsWith(".jre")) fileName = fileName.substring(0, fileName.length() - 4); return shortJavaVersion(fileName); } else return null; } private static Path searchJavaHomeInDir(Path dir) throws IOException { try (DirectoryStream<Path> fs = Files.newDirectoryStream(dir)) { for (Path f : fs) { if (Files.isDirectory(f)) { if (isJavaHome(f)) return f; Path home = searchJavaHomeInDir(f); if (home != null) return home; } } } return null; } private static boolean isJavaHome(Path dir) { return Files.isRegularFile(dir.resolve("bin").resolve("java" + (isWindows() ? ".exe" : ""))); } private static Path getJavaExecutable0(Path javaHome) { final String exec = (isWindows() && System.console() == null) ? "javaw" : "java"; return javaHome.resolve("bin").resolve(exec + (isWindows() ? ".exe" : "")); } private static final Pattern PAT_JAVA_VERSION_LINE = Pattern.compile(".*?\"(.+?)\""); private static String getActualJavaVersion(Path javaHome) { try { final String versionLine = exec(1, getJavaExecutable0(javaHome).toString(), "-version").get(0); final Matcher m = PAT_JAVA_VERSION_LINE.matcher(versionLine); if (!m.matches()) throw new IllegalArgumentException("Could not parse version line: " + versionLine); final String version = m.group(1); return version; } catch (Exception e) { throw new RuntimeException(e); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Version Strings"> /////////// Version Strings /////////////////////////////////// // visible for testing static String shortJavaVersion(String v) { try { final String[] vs = v.split(SEPARATOR_DOT); if (vs.length == 1) { if (Integer.parseInt(vs[0]) < 5) throw new RuntimeException("Unrecognized major Java version: " + v); v = "1." + v + ".0"; } if (vs.length == 2) v += ".0"; return v; } catch (NumberFormatException e) { return null; } } /** * Compares two dotted software versions, regarding only the first several version components. * * @param a first version * @param b second version * @param n the number of (most significant) components to consider * @return {@code 0} if {@code a == b}; {@code > 0} if {@code a > b}; {@code < 0} if {@code a < b}; */ protected static final int compareVersions(String a, String b, int n) { return compareVersions(parseJavaVersion(a), parseJavaVersion(b), n); } /** * Compares two dotted software versions. * * @param a first version * @param b second version * @return {@code 0} if {@code a == b}; {@code > 0} if {@code a > b}; {@code < 0} if {@code a < b}; */ protected static final int compareVersions(String a, String b) { return compareVersions(parseJavaVersion(a), parseJavaVersion(b)); } private static int compareVersions(int[] a, int[] b) { return compareVersions(a, b, 5); } private static int compareVersions(int[] a, int[] b, int n) { for (int i = 0; i < n; i++) { if (a[i] != b[i]) return a[i] - b[i]; } return 0; } private static boolean equals(int[] a, int[] b, int n) { for (int i = 0; i < n; i++) { if (a[i] != b[i]) return false; } return true; } private static final Pattern PAT_JAVA_VERSION = Pattern.compile("(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)(_(?<update>\\d+))?(-(?<pre>[^-]+))?(-(?<build>.+))?"); // visible for testing static int[] parseJavaVersion(String v) { final Matcher m = PAT_JAVA_VERSION.matcher(v); if (!m.matches()) throw new IllegalArgumentException("Could not parse version: " + v); final int[] ver = new int[5]; ver[0] = toInt(m.group("major")); ver[1] = toInt(m.group("minor")); ver[2] = toInt(m.group("patch")); ver[3] = toInt(m.group("update")); final String pre = m.group("pre"); if (pre != null) { if (pre.startsWith("rc")) ver[4] = -1; else if (pre.startsWith("beta")) ver[4] = -2; else if (pre.startsWith("ea")) ver[4] = -3; } return ver; } // visible for testing static String toJavaVersionString(int[] version) { final StringBuilder sb = new StringBuilder(); sb.append(version[0]).append('.'); sb.append(version[1]).append('.'); sb.append(version[2]); if (version.length > 3 && version[3] > 0) sb.append('_').append(version[3]); if (version.length > 4 && version[4] != 0) { final String pre; switch (version[4]) { case -1: pre = "rc"; break; case -2: pre = "beta"; break; case -3: pre = "ea"; break; default: pre = "?"; } sb.append('-').append(pre); } return sb.toString(); } private static int toInt(String s) { return s != null ? Integer.parseInt(s) : 0; } private static int[] toInt(String[] ss) { int[] res = new int[ss.length]; for (int i = 0; i < ss.length; i++) res[i] = ss[i] != null ? Integer.parseInt(ss[i]) : 0; return res; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="String Expansion"> /////////// String Expansion /////////////////////////////////// private List<String> expand(List<String> strs) { if (strs == null) return null; final List<String> res = new ArrayList<String>(strs.size()); for (String s : strs) res.add(expand(s)); return res; } /** * Expands occurrences of {@code $VARNAME} in attribute values. * * @param str the original string * @return the expanded string */ protected String expand(String str) { if ("$0".equals(str)) return jarFile.toString(); if (appCache != null) str = str.replaceAll("\\$" + VAR_CAPSULE_DIR, appCache.toAbsolutePath().toString()); else if (str.contains("$" + VAR_CAPSULE_DIR)) throw new IllegalStateException("The $" + VAR_CAPSULE_DIR + " variable cannot be expanded when the capsule is not extracted"); str = expandCommandLinePath(str); if (appId == null && str.contains("\\$" + VAR_CAPSULE_APP)) throw new IllegalStateException("Cannot use $" + VAR_CAPSULE_APP + " variable in an empty capsule. (in: " + str + ")"); str = str.replaceAll("\\$" + VAR_CAPSULE_APP, appId); str = str.replaceAll("\\$" + VAR_CAPSULE_JAR, jarFile.toString()); final String jhome = toString(getJavaHome()); if (jhome != null) str = str.replaceAll("\\$" + VAR_JAVA_HOME, jhome); str = str.replace('/', FILE_SEPARATOR_CHAR); return str; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="String Utils"> /////////// String Utils /////////////////////////////////// private static String toString(Object obj) { return obj != null ? obj.toString() : null; } static List<String> split(String str, String separator) { if (str == null) return null; String[] es = str.split(separator); final List<String> list = new ArrayList<>(es.length); for (String e : es) { e = e.trim(); if (!e.isEmpty()) list.add(e); } return list; } static Map<String, String> split(String map, char kvSeparator, String separator, String defaultValue) { if (map == null) return null; Map<String, String> m = new LinkedHashMap<>(); for (String entry : Capsule.split(map, separator)) { final String key = getBefore(entry, kvSeparator); String value = getAfter(entry, kvSeparator); if (value == null) { if (defaultValue != null) value = defaultValue; else throw new IllegalArgumentException("Element " + entry + " in \"" + map + "\" is not a key-value entry separated with " + kvSeparator + " and no default value provided"); } m.put(key.trim(), value.trim()); } return m; } final static String join(Collection<?> coll, String separator) { if (coll == null) return null; if (coll.isEmpty()) return ""; StringBuilder sb = new StringBuilder(); for (Object e : coll) { if (e != null) sb.append(e).append(separator); } sb.delete(sb.length() - separator.length(), sb.length()); return sb.toString(); } final static String join(Map<?, ?> map, char kvSeparator, String separator) { if (map == null) return null; StringBuilder sb = new StringBuilder(); for (Map.Entry<?, ?> entry : map.entrySet()) sb.append(entry.getKey()).append(kvSeparator).append(entry.getValue()).append(separator); sb.delete(sb.length() - separator.length(), sb.length()); return sb.toString(); } private static String getBefore(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return s; return s.substring(0, i); } private static String getAfter(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return null; return s.substring(i + 1); } private static long getStringsLength(Collection<?> coll) { if (coll == null) return 0; long len = 0; for (Object o : coll) len += o.toString().length(); return len; } private static String emptyToNull(String s) { if (s == null) return null; s = s.trim(); return s.isEmpty() ? null : s; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Collection Utils"> /////////// Collection Utils /////////////////////////////////// private static <T> List<T> nullToEmpty(List<T> list) { if (list == null) return emptyList(); return list; } private static <K, V> Map<K, V> nullToEmpty(Map<K, V> map) { if (map == null) return emptyMap(); return map; } private static <T> T first(List<T> c) { if (c == null || c.isEmpty()) throw new IllegalArgumentException("Not found"); return c.get(0); } private static <T> T firstOrNull(List<T> c) { if (c == null || c.isEmpty()) return null; return c.get(0); } private static <C extends Collection<T>, T> C addAllIfNotContained(C c, Collection<T> c1) { for (T e : c1) { if (!c.contains(e)) c.add(e); } return c; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Reflection Utils"> /////////// Reflection Utils /////////////////////////////////// private static Method getMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws NoSuchMethodException { try { final Method m = clazz.getDeclaredMethod(name, parameterTypes); m.setAccessible(true); return m; } catch (NoSuchMethodException e) { if (clazz.getSuperclass() == null) throw new NoSuchMethodException(name + "(" + Arrays.toString(parameterTypes) + ")"); return getMethod(clazz.getSuperclass(), name, parameterTypes); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Misc Utils"> /////////// Misc Utils /////////////////////////////////// private static boolean propertyDefined(String... props) { for (String prop : props) { if (System.getProperty(prop) != null) return true; } return false; } private static String propertyOrEnv(String propName, String envVar) { String val = systemProperty(propName); if (val == null) val = emptyToNull(getenv(envVar)); return val; } /** * Same as {@link System#getProperty(java.lang.String) System.getProperty(propName)} but sets context for error reporting. */ protected static final String systemProperty(String propName) { final String val = System.getProperty(propName); setContext("system property", propName, val); return val; } /** * Same as {@link System#getenv(java.lang.String) System.getenv(envName)} but sets context for error reporting. */ private static String getenv(String envName) { final String val = System.getenv(envName); setContext("environment variable", envName, val); return val; } private static boolean systemPropertyEmptyOrTrue(String property) { final String value = System.getProperty(property); if (value == null) return false; return value.isEmpty() || Boolean.parseBoolean(value); } /** * Executes a command and returns its output as a list of lines. * The method will wait for the child process to terminate, and throw an exception if the command returns an exit value {@code != 0}. * <br> * Same as calling {@code exec(-1, cmd}}. * * @param cmd the command * @return the lines output by the command */ protected static List<String> exec(String... cmd) throws IOException { return exec(-1, cmd); } /** * Executes a command and returns its output as a list of lines. * If the number of lines read is less than {@code numLines}, or if {@code numLines < 0}, then the method will wait for the child process * to terminate, and throw an exception if the command returns an exit value {@code != 0}. * * @param numLines the maximum number of lines to read, or {@code -1} for an unbounded number * @param cmd the command * @return the lines output by the command */ protected static List<String> exec(int numLines, String... cmd) throws IOException { return exec(numLines, new ProcessBuilder(Arrays.asList(cmd))); } /** * Executes a command and returns its output as a list of lines. * The method will wait for the child process to terminate, and throw an exception if the command returns an exit value {@code != 0}. * <br> * Same as calling {@code exec(-1, pb}}. * * @param pb the {@link ProcessBuilder} that will be used to launch the command * @return the lines output by the command */ protected static List<String> exec(ProcessBuilder pb) throws IOException { return exec(-1, pb); } /** * Executes a command and returns its output as a list of lines. * If the number of lines read is less than {@code numLines}, or if {@code numLines < 0}, then the method will wait for the child process * to terminate, and throw an exception if the command returns an exit value {@code != 0}. * * @param numLines the maximum number of lines to read, or {@code -1} for an unbounded number * @param pb the {@link ProcessBuilder} that will be used to launch the command * @return the lines output by the command */ protected static List<String> exec(int numLines, ProcessBuilder pb) throws IOException { final List<String> lines = new ArrayList<>(); final Process p = pb.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream(), Charset.defaultCharset()))) { for (int i = 0; numLines < 0 || i < numLines; i++) { final String line = reader.readLine(); if (line == null) break; lines.add(line); } } try { if (numLines < 0 || lines.size() < numLines) { final int exitValue = p.waitFor(); if (exitValue != 0) throw new RuntimeException("Command '" + join(pb.command(), " ") + "' has returned " + exitValue); } return lines; } catch (InterruptedException e) { throw new RuntimeException(e); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Logging"> /////////// Logging /////////////////////////////////// /** * Chooses and returns the capsules log level. */ protected int chooseLogLevel() { String level = System.getProperty(PROP_LOG_LEVEL); if (level == null && manifest != null) level = getAttribute(ATTR_LOG_LEVEL); int lvl = getLogLevel(level); if (lvl < 0) throw new IllegalArgumentException("Unrecognized log level: " + level); return lvl; } private static int getLogLevel(String level) { if (level == null || level.isEmpty()) level = "QUIET"; switch (level.toUpperCase()) { case "NONE": return LOG_NONE; case "QUIET": return LOG_QUIET; case "VERBOSE": return LOG_VERBOSE; case "DEBUG": case "ALL": return LOG_DEBUG; default: return -1; } } /** * Tests if the given log level is currently being logged */ protected final boolean isLogging(int level) { return level <= logLevel; } /** * Prints a message to stderr if the given log-level is being logged. */ protected final void log(int level, String str) { if (isLogging(level)) System.err.println(LOG_PREFIX + str); } private void println(String str) { log(LOG_QUIET, str); } private static boolean hasContext() { return contextType_ != null; } private static void clearContext() { setContext(null, null, null); } private static void setContext(String type, String key, String value) { // System.err.println("setContext: " + type + " " + key + " " + value); // Thread.dumpStack(); contextType_ = type; contextKey_ = key; contextValue_ = value; } private static String reportContext() { return contextType_ + " " + contextKey_ + ": " + contextValue_; } private long clock() { return isLogging(PROFILE) ? System.nanoTime() : 0; } private void time(String op, long start) { if (isLogging(PROFILE)) log(PROFILE, "PROFILE " + op + " " + ((System.nanoTime() - start) / 1_000_000) + "ms"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Pipe Streams (workaround for inheritIO bug)"> /////////// Pipe Streams (workaround for inheritIO bug) /////////////////////////////////// private static boolean isInheritIoBug() { return isWindows() && compareVersions(System.getProperty(PROP_JAVA_VERSION), "1.8.0") < 0; } private void pipeIoStreams() { new Thread(this, "pipe-out").start(); new Thread(this, "pipe-err").start(); new Thread(this, "pipe-in").start(); } private boolean pipeIoStream() { switch (Thread.currentThread().getName()) { case "pipe-out": pipe(child.getInputStream(), System.out); return true; case "pipe-err": pipe(child.getErrorStream(), System.err); return true; case "pipe-in": pipe(System.in, child.getOutputStream()); return true; default: return false; } } private void pipe(InputStream in, OutputStream out) { try (OutputStream out1 = out) { final byte[] buf = new byte[1024]; int read; while (-1 != (read = in.read(buf))) { out.write(buf, 0, read); out.flush(); } } catch (Throwable e) { if (isLogging(LOG_VERBOSE)) e.printStackTrace(System.err); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="POSIX"> /////////// POSIX /////////////////////////////////// private static int getPid(Process p) { try { java.lang.reflect.Field pidField = p.getClass().getDeclaredField("pid"); pidField.setAccessible(true); return pidField.getInt(p); } catch (Exception e) { return -1; } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Object Methods"> /////////// Object Methods /////////////////////////////////// /** * Throws a {@link CloneNotSupportedException} */ @SuppressWarnings("CloneDoesntCallSuperClone") @Override protected final Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } @Override public final int hashCode() { int hash = 3; hash = 47 * hash + Objects.hashCode(this.jarFile); hash = 47 * hash + Objects.hashCode(this.mode); return hash; } @Override public final boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Capsule other = (Capsule) obj; if (!Objects.equals(this.jarFile, other.jarFile)) return false; if (!Objects.equals(this.mode, other.mode)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()).append('['); sb.append(jarFile); if (appId != null) { sb.append(", ").append(appId); sb.append(", ").append(getAttribute(ATTR_APP_CLASS) != null ? getAttribute(ATTR_APP_CLASS) : getAttribute(ATTR_APP_ARTIFACT)); } else sb.append(", ").append("empty"); if (mode != null) sb.append(", ").append("mode: ").append(mode); sb.append(']'); return sb.toString(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Capsule Loading and Launching"> /////////// Capsule Loading and Launching /////////////////////////////////// // visible for testing static Capsule newCapsule(Path jarFile, Path cacheDir) { try { final String mainClassName = getMainClass(jarFile); if (mainClassName != null) { final Class<?> clazz = Capsule.class.getClassLoader().loadClass(mainClassName); if (isCapsuleClass(clazz)) { final Constructor<?> ctor = clazz.getDeclaredConstructor(Path.class, Path.class); ctor.setAccessible(true); return (Capsule) ctor.newInstance(jarFile, cacheDir); } } throw new RuntimeException(jarFile + " does not appear to be a valid capsule."); } catch (ClassNotFoundException e) { throw new RuntimeException(jarFile + " does not appear to be a valid capsule.", e); } catch (InvocationTargetException e) { throw rethrow(e.getTargetException()); } catch (ReflectiveOperationException e) { throw new RuntimeException("Could not instantiate capsule.", e); } } private static RuntimeException rethrow(Throwable t) { while (t instanceof InvocationTargetException) t = ((InvocationTargetException) t).getTargetException(); if (t instanceof RuntimeException) throw (RuntimeException) t; if (t instanceof Error) throw (Error) t; throw new RuntimeException(t); } private static boolean isCapsuleClass(Class<?> clazz) { if (clazz == null) return false; return Capsule.class.getName().equals(clazz.getName()) || isCapsuleClass(clazz.getSuperclass()); } //</editor-fold> }
package test.application; import org.lwjgl.Display; import org.lwjgl.opengl.GL; import jme.AbstractGame; import jme.system.DisplaySystem; /** * <code>TestApplication</code> provides a very basic jME OpenGL construct * This code generates a basic OpenGL window with a black background. * You will can use this basic construct to build more complex jME applications * * @author Samuel Wasson * @version $Id: TestApplication.java,v 1.2 2003-08-08 02:16:56 mojomonkey Exp $ */ //Edit: Mark Powell - altered comments slightly. 8/7/03 public class TestApplication extends AbstractGame { /** * This is where we'll do any updating */ protected void update() { } /** * Render is called once per frame to display the data. */ protected void render() { gl.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT); gl.loadIdentity(); } /** * This is where we create and initialize the window. */ protected void initDisplay() { DisplaySystem.createDisplaySystem( "TestApplication", "jme/data/Images/Monkey.jpg", true ); } protected void initGL() { // Here we create the OpenGL bindings. gl = DisplaySystem.getDisplaySystem().getGL(); glu = DisplaySystem.getDisplaySystem().getGLU(); //Define the clear color to be black gl.clearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.matrixMode(GL.PROJECTION); gl.loadIdentity(); // Calculate the aspect ratio glu.perspective( 45.0f, (float)Display.getWidth() / (float)Display.getHeight(), 0.01f, 750.0f); gl.matrixMode(GL.MODELVIEW); gl.hint(GL.PERSPECTIVE_CORRECTION_HINT, GL.NICEST); } /** * Called first to initialize system attributes. */ protected void initSystem() { initDisplay(); initGL(); } /** * Nothing here yet. */ protected void initGame() { } /** * Nothing here yet. */ protected void reinit() { } /** * Clean up the OpenGL resources */ protected void cleanup() { gl.destroy(); } /** * <code>main</code> entry point for application. * @param args comman line arguments, none used. */ public static void main(String[] args) { TestApplication testApp = new TestApplication(); testApp.start(); } }
package mho.qbar; import mho.haskellesque.iterables.ExhaustiveProvider; import mho.haskellesque.iterables.IterableProvider; import mho.haskellesque.iterables.RandomProvider; import mho.haskellesque.structures.Pair; import mho.haskellesque.structures.Triple; import java.math.BigInteger; import java.math.RoundingMode; import java.util.Random; import static mho.haskellesque.iterables.IterableUtils.*; public class RationalDemos { private static final boolean USE_RANDOM = false; private static final IterableProvider P = USE_RANDOM ? new RandomProvider(new Random(7706916639046193098L)) : new ExhaustiveProvider(); private static Iterable<Rational> RATIONALS = USE_RANDOM ? Rational.RATIONALS : Rational.RATIONALS; //todo private static final String NECESSARY_CHARS = "-/0123456789"; private static final int LIMIT = 10000; public static void ofBigIntegerBigIntegerDemo() { Iterable<Pair<BigInteger, BigInteger>> it = filter( p -> !p.b.equals(BigInteger.ZERO), P.pairs(P.bigIntegers()) ); for (Pair<BigInteger, BigInteger> p : take(LIMIT, it)) { System.out.println("of(" + p.a + ", " + p.b + ") = " + Rational.of(p.a, p.b)); } } public static void ofIntIntDemo() { Iterable<Pair<Integer, Integer>> it = filter(p -> p.b != 0, P.pairs(P.integers())); for (Pair<Integer, Integer> p : take(LIMIT, it)) { System.out.println("of(" + p.a + ", " + p.b + ") = " + Rational.of(p.a, p.b)); } } public static void ofBigIntegerDemo() { for (BigInteger bi : take(LIMIT, P.bigIntegers())) { System.out.println("of(" + bi + ") = " + Rational.of(bi)); } } public static void ofIntDemo() { for (int bi : take(LIMIT, P.integers())) { System.out.println("of(" + bi + ") = " + Rational.of(bi)); } } public static void ofFloatDemo() { for (float f : take(LIMIT, P.floats())) { System.out.println("of(" + f + ") = " + Rational.of(f)); } } public static void ofDoubleDemo() { for (double d : take(LIMIT, P.doubles())) { System.out.println("of(" + d + ") = " + Rational.of(d)); } } // public static void ofBigDecimalDemo() { // for (BigDecimal bd : Generators.bigDecimals().iterate(limit)) { // System.out.println("of(" + bd + ") = " + Rational.of(bd)); public static void negateDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("-(" + r + ") = " + r.negate()); } } public static void invertDemo() { for (Rational r : take(LIMIT, filter(s -> s != Rational.ZERO, RATIONALS))) { System.out.println("1/(" + r + ") = " + r.invert()); } } public static void absDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("|" + r + "| = " + r.abs()); } } public static void signumDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("sgn(" + r + ") = " + r.signum()); } } public static void addDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println(p.a + " + " + p.b + " = " + Rational.add(p.a, p.b)); } } public static void subtractDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println(p.a + " - " + p.b + " = " + Rational.subtract(p.a, p.b)); } } public static void multiplyRationalRationalDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println(p.a + " * " + p.b + " = " + Rational.multiply(p.a, p.b)); } } public static void multiplyBigIntegerDemo() { for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(RATIONALS, P.bigIntegers()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } public static void multiplyIntDemo() { for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(RATIONALS, P.integers()))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " * " + p.b + " = " + p.a.multiply(p.b)); } } public static void divideRationalRationalDemo() { Iterable<Pair<Rational, Rational>> it = filter(p -> p.b != Rational.ZERO, P.pairs(RATIONALS)); for (Pair<Rational, Rational> p : take(LIMIT, it)) { System.out.println(p.a + " / " + p.b + " = " + Rational.divide(p.a, p.b)); } } public static void divideBigIntegerDemo() { Iterable<Pair<Rational, BigInteger>> it = P.pairs( RATIONALS, filter(bi -> !bi.equals(BigInteger.ZERO), P.bigIntegers()) ); for (Pair<Rational, BigInteger> p : take(LIMIT, it)) { assert p.a != null; assert p.b != null; System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } public static void divideIntDemo() { for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(RATIONALS, filter(i -> i != 0, P.integers())))) { assert p.a != null; assert p.b != null; System.out.println(p.a + " / " + p.b + " = " + p.a.divide(p.b)); } } public static void powDemo() { Iterable<Pair<Rational, Integer>> it = filter( p -> p.b >= 0 || p.a != Rational.ZERO, P.pairs(RATIONALS, P.integers()) ); for (Pair<Rational, Integer> p : take(LIMIT, it)) { assert p.a != null; assert p.b != null; System.out.println(p.a + " ^ " + p.b + " = " + p.a.pow(p.b)); } } public static void floorDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("floor(" + r + ") = " + r.floor()); } } public static void ceilingDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("ceil(" + r + ") = " + r.ceiling()); } } public static void fractionalPartDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("fractionalPart(" + r + ") = " + r.fractionalPart()); } } public static void roundDemo() { Iterable<Pair<Rational, RoundingMode>> it = filter( p -> p.b != RoundingMode.UNNECESSARY || p.a.getDenominator().equals(BigInteger.ONE), P.pairs(RATIONALS, P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, it)) { System.out.println("round(" + p.a + ", " + p.b + ") = " + p.a.round(p.b)); } } public static void roundToDenominatorDemo() { Iterable<Triple<Rational, BigInteger, RoundingMode>> it = filter( p -> p.c != RoundingMode.UNNECESSARY || p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO), P.triples(RATIONALS, P.positiveBigIntegers(), P.roundingModes()) ); for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, it)) { System.out.println("round(" + t.a + ", " + t.b + ", " + t.c + ") = " + t.a.roundToDenominator(t.b, t.c)); } } public static void shiftLeftDemo() { for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(RATIONALS, P.integers()))) { System.out.println(p.a + " << " + p.b + " = " + p.a.shiftLeft(p.b)); } } public static void shiftRightDemo() { for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(RATIONALS, P.integers()))) { System.out.println(p.a + " >> " + p.b + " = " + p.a.shiftRight(p.b)); } } public static void binaryExponentDemo() { for (Rational r : take(LIMIT, Rational.POSITIVE_RATIONALS)) { System.out.println("binaryExponent(" + r + ") = " + r.binaryExponent()); } } public static void toFloatDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("toFloat(" + r + ") = " + r.toFloat()); } } public static void toFloatRoundingModeDemo() { Iterable<Pair<Rational, RoundingMode>> it = filter( p -> p.b != RoundingMode.UNNECESSARY || Rational.of(p.a.toFloat(RoundingMode.FLOOR)).equals(p.a), P.pairs(RATIONALS, P.roundingModes()) ); for (Pair<Rational, RoundingMode> p : take(LIMIT, it)) { System.out.println("toFloat(" + p.a + ", " + p.b + ") = " + p.a.toFloat(p.b)); } } public static void toDoubleDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("toDouble(" + r + ") = " + r.toDouble()); } } public static void toDoubleRoundingModeDemo() { Iterable<Pair<Rational, RoundingMode>> it = filter( p -> p.b != RoundingMode.UNNECESSARY || Rational.of(p.a.toFloat(RoundingMode.FLOOR)).equals(p.a), P.pairs(RATIONALS, P.roundingModes())); for (Pair<Rational, RoundingMode> p : take(LIMIT, it)) { System.out.println("toDouble(" + p.a + ", " + p.b + ") = " + p.a.toDouble(p.b)); } } public static void hasTerminatingDecimalExpansionDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("hasTerminatingDecimalExpansion(" + r + ") = " + r.hasTerminatingDecimalExpansion()); } } public static void toBigDecimalDemo() { Iterable<Rational> it = filter(Rational::hasTerminatingDecimalExpansion, RATIONALS); for (Rational r : take(LIMIT, it)) { System.out.println("toBigDecimal(" + r + ") = " + r.toBigDecimal()); } } // public static void toBigDecimalPrecisionDemo() { // Iterable<Pair<Rational, Integer>> g = filter( // new SubExponentialPairGenerator<>( // RATIONALS, // Generators.naturalIntegers() // p -> p.b != 0 || p.a.hasTerminatingDecimalExpansion()); // for (Pair<Rational, Integer> p : g.iterate(limit)) { // System.out.println("toBigDecimal(" + p.a + ", " + p.b + ") = " + p.a.toBigDecimal(p.b)); // public static void toBigDecimalPrecisionRoundingMode() { // Generator<Pair<Rational, Integer>> pg = new FilteredGenerator<Pair<Rational, Integer>>( // new SubExponentialPairGenerator<>( // RATIONALS, // Generators.naturalIntegers() // p -> p.b != 0 || p.a.hasTerminatingDecimalExpansion()); // Generator<Pair<Pair<Rational, Integer>, RoundingMode>> g = new FilteredGenerator<Pair<Pair<Rational,Integer>, RoundingMode>>( // pairs(pg, Generators.roundingModes()), // p -> p.b != RoundingMode.UNNECESSARY || // (p.a.a.hasTerminatingDecimalExpansion() && // p.a.b >= p.a.a.numberOfDecimalDigits())); // for (Pair<Pair<Rational, Integer>, RoundingMode> p : g.iterate(limit)) { // System.out.println("toBigDecimal(" + p.a.a + ", " + p.a.b + ", " + p.b + ") = " + // p.a.a.toBigDecimal(p.a.b, p.b)); public static void equalsRationalDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println("equals(" + p.a + ", " + p.b + ") = " + p.a.equals(p.b)); } } public static void equalsNullDemo() { for (Rational r : take(LIMIT, RATIONALS)) { //noinspection ObjectEqualsNull System.out.println("equals(" + r + ", null) = " + r.equals(null)); } } public static void hashCodeDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("hashCode(" + r + ") = " + r.hashCode()); } } public static void compareToDemo() { for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(RATIONALS))) { System.out.println("compareTo(" + p.a + ", " + p.b + ") = " + p.a.compareTo(p.b)); } } public static void continuedFractionDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("continuedFraction(" + r + ") = " + r.continuedFraction()); } } // public static void fromContinuedFractionDemo() { // Iterable<List<BigInteger>> it = pairs( // P.bigIntegers(), // new ListGenerator<BigInteger>(POSITIVE_BIG_INTEGERS) // ).map( // List<BigInteger> bis = new ArrayList<>(); // bis.add(p.a); // bis.addAll(p.b); // return bis; // bis -> { // List<BigInteger> tail = new ArrayList<>(); // for (int i = 1; i < bis.size(); i++) { // tail.add(bis.get(i)); // return Pair.of(bis.get(0), tail); // bis -> { // if (bis.isEmpty()) return false; // for (int i = 1; i < bis.size(); i++) { // if (bis.get(i).signum() != 1) return false; // return true; // for (List<BigInteger> bis : bisg.iterate(limit)) { // String bisString = bis.toString(); // bisString = bisString.substring(1, bisString.length() - 1); // System.out.println("fromContinuedFraction(" + bisString + ") = " + Rational.fromContinuedFraction(bis)); public static void convergentsDemo() { for (Rational r : take(LIMIT, RATIONALS)) { System.out.println("convergents(" + r + ") = " + r.convergents()); } } // public static void positionalNotationDemo() { // Generator<BigInteger> big = new FilteredGenerator<>( // POSITIVE_BIG_INTEGERS, // bi -> bi.compareTo(BigInteger.ONE) > 0 // Generator<Pair<Rational, BigInteger>> g = new SubExponentialPairGenerator<>(Rational.nonnegativeRationals(), big); // for (Pair<Rational, BigInteger> p : g.iterate(limit)) { // System.out.println("positionalNotation(" + p.a + ", " + p.b + " = " + p.a.positionalNotation(p.b)); // public static void fromPositionalNotationDemo() { // Generator<BigInteger> big = new FilteredGenerator<>( // POSITIVE_BIG_INTEGERS, // bi -> bi.compareTo(BigInteger.ONE) > 0 // Generator<Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> tg = new SameTripleGenerator<>(new ListGenerator<>(Generators.naturalBigIntegers())); // Generator<Pair<Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>, BigInteger>> g = new FilteredGenerator<>( // new SubExponentialPairGenerator<Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>, BigInteger>(tg, big), // if (p.a.c.isEmpty()) return false; // for (BigInteger digit : p.a.a) { // if (digit.compareTo(p.b) >= 0) return false; // for (BigInteger digit : p.a.b) { // if (digit.compareTo(p.b) >= 0) return false; // for (BigInteger digit : p.a.c) { // if (digit.compareTo(p.b) >= 0) return false; // return true; // for (Pair<Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>, BigInteger> t : g.iterate(limit)) { // System.out.println("fromPositionalNotation(" + t.b + ", " + t.a.a + ", " + t.a.b + ", " + t.a.c + ") = " + Rational.fromPositionalNotation(t.b, t.a.a, t.a.b, t.a.c)); // public static void digitsDemo() { // Generator<BigInteger> big = new FilteredGenerator<>( // POSITIVE_BIG_INTEGERS, // bi -> bi.compareTo(BigInteger.ONE) > 0 // Generator<Pair<Rational, BigInteger>> g = new SubExponentialPairGenerator<>(Rational.nonnegativeRationals(), big); // for (Pair<Rational, BigInteger> p : g.iterate(limit)) { // Pair<List<BigInteger>, Iterable<BigInteger>> digits = p.a.digits(p.b); // String beforeDecimalString = digits.a.toString(); // List<String> afterDecimalStrings = new ArrayList<>(); // int i = 0; // for (BigInteger digit : digits.b) { // if (i >= 20) { // afterDecimalStrings.add("..."); // break; // afterDecimalStrings.add(digit.toString()); // String resultString = "(" + beforeDecimalString + ", " + afterDecimalStrings + ")"; // System.out.println("digits(" + p.a + ", " + p.b + ") = " + resultString); // public static void readDemo() { // readDemo(limit, false, false); // public static void readDemo(, boolean necessaryChars, boolean skipNullResults) { // Generator<String> g = new FilteredGenerator<>( // (necessaryChars ? Generators.strings(NECESSARY_CHARS) : Generators.strings()), // s -> !s.endsWith("/0")); // for (String s : g.iterate(limit)) { // Rational r = Rational.read(s); // if (!skipNullResults || r != null) System.out.println("read(" + s + ") = " + r); }
import capsule.DependencyManagerImpl; import capsule.DependencyManager; import capsule.PomReader; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import static java.util.Collections.*; /** * An application capsule. * <p> * This API is to be used by custom capsules to programmatically (rather than declaratively) configure the capsule and possibly provide custom behavior. * <p> * All non-final protected methods may be overridden by custom capsules. These methods will usually be called once, but they must be idempotent, * i.e. if called numerous times they must always return the same value, and produce the same effect as if called once. * <br> * Overridden methods need not be thread-safe, and are guaranteed to be called by a single thread at a time. * <br> * Overridable (non-final) methods <b>must never</b> be called directly by custom capsule code, except by their overrides. * <p> * Final methods implement various utility or accessors, which may be freely used by custom capsules. * * @author pron */ public class Capsule implements Runnable { protected static final String VERSION = "0.10.0"; /* * This class follows some STRICT RULES: * * 1. IT MUST COMPILE TO A SINGLE CLASS FILE (so it must not contain nested or inner classes). * 2. IT MUST ONLY REFERENCE CLASSES IN THE JDK AND THOSE IN THE capsule PACKAGE. * 3. CAPSULES WITH NO DECLARED DEPENDENCIES MUST LAUNCH WITHOUT REQUIRING ANY CLASSES BUT THIS AND THE JDK. * 4. ALL METHODS MUST BE PURE OR, AT LEAST, IDEMPOTENT (with the exception of the launch method, and, of course, the constructor). * * Rules #1 and #3 ensure that fat capsules will work with only Capsule.class included in the JAR. Rule #2 helps enforcing rules #1 and #3. * Rule #4 ensures methods can be called in any order (after construction completes), and makes maintenance and evolution of Capsule simpler. * * This class contains several strange hacks to compy with rule #1. * * Also, the code is not meant to be the most efficient, but methods should be as independent and stateless as possible. * Other than those few methods called in the constructor, all others are can be called in any order, and don't rely on any state. * * We do a lot of data transformations that could benefited from Java 8's lambdas+streams, but we want Capsule to support Java 7. */ //<editor-fold defaultstate="collapsed" desc="Constants"> /////////// Constants /////////////////////////////////// private static final String PROP_VERSION = "capsule.version"; private static final String PROP_TREE = "capsule.tree"; private static final String PROP_RESOLVE = "capsule.resolve"; private static final String PROP_MODES = "capsule.modes"; private static final String PROP_TRAMPOLINE = "capsule.trampoline"; private static final String PROP_RESET = "capsule.reset"; private static final String PROP_LOG_LEVEL = "capsule.log"; private static final String PROP_APP_ID = "capsule.app.id"; private static final String PROP_PRINT_JRES = "capsule.jvms"; private static final String PROP_CAPSULE_JAVA_HOME = "capsule.java.home"; private static final String PROP_CAPSULE_JAVA_CMD = "capsule.java.cmd"; private static final String PROP_MODE = "capsule.mode"; private static final String PROP_USE_LOCAL_REPO = "capsule.local"; private static final String PROP_JVM_ARGS = "capsule.jvm.args"; private static final String PROP_NO_DEP_MANAGER = "capsule.no_dep_manager"; private static final String PROP_PROFILE = "capsule.profile"; private static final String PROP_JAVA_VERSION = "java.version"; private static final String PROP_JAVA_HOME = "java.home"; private static final String PROP_OS_NAME = "os.name"; private static final String PROP_USER_HOME = "user.home"; private static final String PROP_JAVA_LIBRARY_PATH = "java.library.path"; private static final String PROP_FILE_SEPARATOR = "file.separator"; private static final String PROP_PATH_SEPARATOR = "path.separator"; private static final String PROP_JAVA_SECURITY_POLICY = "java.security.policy"; private static final String PROP_JAVA_SECURITY_MANAGER = "java.security.manager"; private static final String PROP_TMP_DIR = "java.io.tmpdir"; private static final String ENV_CACHE_DIR = "CAPSULE_CACHE_DIR"; private static final String ENV_CACHE_NAME = "CAPSULE_CACHE_NAME"; private static final String ENV_CAPSULE_REPOS = "CAPSULE_REPOS"; private static final String ENV_CAPSULE_LOCAL_REPO = "CAPSULE_LOCAL_REPO"; private static final String ATTR_MANIFEST_VERSION = "Manifest-Version"; private static final String ATTR_CLASS_PATH = "Class-Path"; private static final String ATTR_IMPLEMENTATION_VERSION = "Implementation-Version"; private static final String ATTR_APP_NAME = "Application-Name"; private static final String ATTR_APP_VERSION = "Application-Version"; private static final String ATTR_MODE_DESC = "Description"; private static final String ATTR_APP_CLASS = "Application-Class"; private static final String ATTR_APP_ARTIFACT = "Application"; private static final String ATTR_UNIX_SCRIPT = "Unix-Script"; private static final String ATTR_WINDOWS_SCRIPT = "Windows-Script"; private static final String ATTR_EXTRACT = "Extract-Capsule"; private static final String ATTR_MIN_JAVA_VERSION = "Min-Java-Version"; private static final String ATTR_JAVA_VERSION = "Java-Version"; private static final String ATTR_MIN_UPDATE_VERSION = "Min-Update-Version"; private static final String ATTR_JDK_REQUIRED = "JDK-Required"; private static final String ATTR_JVM_ARGS = "JVM-Args"; private static final String ATTR_ARGS = "Args"; private static final String ATTR_ENV = "Environment-Variables"; private static final String ATTR_SYSTEM_PROPERTIES = "System-Properties"; private static final String ATTR_APP_CLASS_PATH = "App-Class-Path"; private static final String ATTR_CAPSULE_IN_CLASS_PATH = "Capsule-In-Class-Path"; private static final String ATTR_BOOT_CLASS_PATH = "Boot-Class-Path"; private static final String ATTR_BOOT_CLASS_PATH_A = "Boot-Class-Path-A"; private static final String ATTR_BOOT_CLASS_PATH_P = "Boot-Class-Path-P"; private static final String ATTR_LIBRARY_PATH_A = "Library-Path-A"; private static final String ATTR_LIBRARY_PATH_P = "Library-Path-P"; private static final String ATTR_SECURITY_MANAGER = "Security-Manager"; private static final String ATTR_SECURITY_POLICY = "Security-Policy"; private static final String ATTR_SECURITY_POLICY_A = "Security-Policy-A"; private static final String ATTR_JAVA_AGENTS = "Java-Agents"; private static final String ATTR_REPOSITORIES = "Repositories"; private static final String ATTR_ALLOW_SNAPSHOTS = "Allow-Snapshots"; private static final String ATTR_DEPENDENCIES = "Dependencies"; private static final String ATTR_NATIVE_DEPENDENCIES_LINUX = "Native-Dependencies-Linux"; private static final String ATTR_NATIVE_DEPENDENCIES_WIN = "Native-Dependencies-Win"; private static final String ATTR_NATIVE_DEPENDENCIES_MAC = "Native-Dependencies-Mac"; private static final String ATTR_MAIN_CLASS = "Main-Class"; private static final String ATTR_LOG_LEVEL = "Capsule-Log-Level"; private static final Set<String> NON_MODAL_ATTRS = unmodifiableSet(new HashSet<String>(Arrays.asList( new String[]{ATTR_APP_NAME, ATTR_APP_VERSION} ))); // outgoing private static final String VAR_CAPSULE_APP = "CAPSULE_APP"; private static final String VAR_CAPSULE_DIR = "CAPSULE_DIR"; private static final String VAR_CAPSULE_JAR = "CAPSULE_JAR"; private static final String VAR_CLASSPATH = "CLASSPATH"; private static final String VAR_JAVA_HOME = "JAVA_HOME"; private static final String PROP_CAPSULE_JAR = "capsule.jar"; private static final String PROP_CAPSULE_DIR = "capsule.dir"; private static final String PROP_CAPSULE_APP = "capsule.app"; private static final String PROP_CAPSULE_APP_PID = "capsule.app.pid"; // misc private static final String CACHE_DEFAULT_NAME = "capsule"; private static final String DEPS_CACHE_NAME = "deps"; private static final String APP_CACHE_NAME = "apps"; private static final String POM_FILE = "pom.xml"; private static final String SEPARATOR_DOT = "\\."; private static final String LOCK_FILE_NAME = ".lock"; private static final String TIMESTAMP_FILE_NAME = ".extracted"; private static final String FILE_SEPARATOR = System.getProperty(PROP_FILE_SEPARATOR); private static final char FILE_SEPARATOR_CHAR = FILE_SEPARATOR.charAt(0); private static final String PATH_SEPARATOR = System.getProperty(PROP_PATH_SEPARATOR); private static final Path WINDOWS_PROGRAM_FILES_1 = Paths.get("C:", "Program Files"); private static final Path WINDOWS_PROGRAM_FILES_2 = Paths.get("C:", "Program Files (x86)"); private static final int WINDOWS_MAX_CMD = 32500; private static final Object DEFAULT = new Object(); @SuppressWarnings("FieldMayBeFinal") private static Object DEPENDENCY_MANAGER = DEFAULT; // used only by tests // logging private static final String LOG_PREFIX = "CAPSULE: "; protected static final int LOG_NONE = 0; protected static final int LOG_QUIET = 1; protected static final int LOG_VERBOSE = 2; protected static final int LOG_DEBUG = 3; private static final int PROFILE = propertyDefined(PROP_PROFILE) ? LOG_QUIET : LOG_DEBUG; //</editor-fold> //<editor-fold desc="Main"> /////////// Main /////////////////////////////////// private static Capsule CAPSULE; private static final Map<String, String> ACTIONS = new LinkedHashMap<>(); static { registerAction(PROP_VERSION, "printVersion"); registerAction(PROP_MODES, "printModes"); registerAction(PROP_TREE, "printDependencyTree"); registerAction(PROP_RESOLVE, "resolve"); registerAction(PROP_PRINT_JRES, "printJVMs"); } final static Capsule myCapsule(List<String> args) { if (CAPSULE == null) { final Capsule capsule = newCapsule(findOwnJarFile(), getCacheDir()); if (capsule.isEmptyCapsule() && !args.isEmpty()) capsule.setTargetCapsule(args.remove(0)); CAPSULE = capsule; } return CAPSULE; } @SuppressWarnings({"BroadCatchBlock", "CallToPrintStackTrace"}) public static final void main(String[] args0) { List<String> args = new ArrayList<>(Arrays.asList(args0)); // list must be mutable b/c myCapsule() might mutate it try { final Capsule capsule = myCapsule(args); args = unmodifiableList(args); if (capsule.getClass().equals(Capsule.class) && capsule.wrapper && !capsule.isEmptyCapsule()) // not a custom capsule System.exit(runMain(capsule.jarFile, args)); if (runActions(capsule, args)) return; if (capsule.isEmptyCapsule()) throw new RuntimeException("USAGE: java -jar " + capsule.jarFile + " PATH_OR_MAVEN_COORDINATES\n" + capsule.jarFile + " is an empty capsule."); System.exit(capsule.launch(args)); } catch (Throwable t) { System.err.print("CAPSULE EXCEPTION: " + t.getMessage()); if (hasContext() && (t.getMessage() == null || t.getMessage().length() < 50)) System.err.print(" while processing " + reportContext()); if (getLogLevel(System.getProperty(PROP_LOG_LEVEL)) >= LOG_VERBOSE) { System.err.println(); t.printStackTrace(System.err); } else System.err.println(" (for stack trace, run with -D" + PROP_LOG_LEVEL + "=verbose)"); System.exit(1); } } @SuppressWarnings("CallToPrintStackTrace") private static int runMain(Path jar, List<String> args) { try { new URLClassLoader(new URL[]{jar.toUri().toURL()}, null) .loadClass(getMainClass(jar)) .getMethod("main", String[].class).invoke(null, (Object) args.toArray(new String[0])); return 0; } catch (Exception e) { e.printStackTrace(); return 1; } } /** * Registers a top-level capsule *action* (like print dependency tree or list JVMs). * * @param propertyName the name of the system property that,if defined, will cause the action to be run. * @param methodName the method which will run the action. The method must accept a single {@code args} parameter of type {@code List<String>}. */ protected static final void registerAction(String propertyName, String methodName) { ACTIONS.put(propertyName, methodName); } private static boolean runActions(Capsule capsule, List<String> args) { try { boolean found = false; for (Map.Entry<String, String> entry : ACTIONS.entrySet()) { if (propertyDefined(entry.getKey())) { getMethod(capsule.getClass(), entry.getValue(), List.class).invoke(capsule, args); found = true; } } return found; } catch (InvocationTargetException e) { throw rethrow(e); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } } //</editor-fold> private static Map<String, Path> JAVA_HOMES; // an optimization trick (can be injected by CapsuleLauncher) // fields marked /*final*/ are effectively final after finalizeCapsule private final Path cacheDir; // never null private final Object dependencyManager; private final boolean wrapper; private /*final*/ Path jarFile; // never null private final Manifest manifest; // never null private /*final*/ String appId; // null iff empty capsule private /*final*/ String mode; private /*final*/ Object pom; // non-null iff jar has pom AND manifest doesn't have ATTR_DEPENDENCIES private final int logLevel; private Path appCache; // non-null iff capsule is extracted private boolean cacheUpToDate; private FileLock appCacheLock; // very limited state private List<String> jvmArgs_; private List<String> args_; private Path pathingJar; private Process child; // Error reporting private static String contextType_; private static String contextKey_; private static String contextValue_; //<editor-fold defaultstate="collapsed" desc="Constructors"> /////////// Constructors /////////////////////////////////// /* * The constructors and methods in this section may be reflectively called by CapsuleLauncher */ /** * Constructs a capsule from the given JAR file. * * @param jarFile the path to the JAR file * @param cacheDir the path to the (shared) Capsule cache directory */ @SuppressWarnings("OverridableMethodCallInConstructor") protected Capsule(Path jarFile, Path cacheDir) { Objects.requireNonNull(jarFile, "jarFile can't be null"); Objects.requireNonNull(cacheDir, "cacheDir can't be null"); this.cacheDir = initCacheDir(cacheDir); this.jarFile = jarFile; try (JarInputStream jis = openJarInputStream(jarFile)) { this.manifest = jis.getManifest(); if (manifest == null) throw new RuntimeException("Capsule " + jarFile + " does not have a manifest"); this.pom = !hasAttribute(ATTR_DEPENDENCIES) ? createPomReader(jis) : null; } catch (IOException e) { throw new RuntimeException("Could not read JAR file " + jarFile, e); } this.logLevel = chooseLogLevel(); this.wrapper = isEmptyCapsule(); this.dependencyManager = DEPENDENCY_MANAGER != DEFAULT ? DEPENDENCY_MANAGER : tryCreateDependencyManager(); if (this.dependencyManager != null) setDependencyRepositories(getRepositories()); if (!wrapper) finalizeCapsule(); clearContext(); } private void setTargetCapsule(String capsuleArtifact) { clearContext(); final Path jar = isDependency(capsuleArtifact) ? firstOrNull(resolveDependency(capsuleArtifact, "jar")) : Paths.get(capsuleArtifact); if (jar == null) throw new RuntimeException(capsuleArtifact + " not found."); setTargetCapsule(jar); } private void setTargetCapsule(Path jar) { if (!isEmptyCapsule()) throw new IllegalStateException("Capsule " + jarFile + " isn't empty"); if (jar.equals(jarFile)) // catch simple loops throw new RuntimeException("Capsule wrapping loop detected with capsule " + jarFile); log(LOG_VERBOSE, "Wrapping capsule " + jar); this.jarFile = jar; try (JarInputStream jis = openJarInputStream(jarFile)) { boolean isCapsule = false; for (JarEntry entry; (entry = jis.getNextJarEntry()) != null;) { if (entry.getName().equals(Capsule.class.getName() + ".class")) isCapsule = true; else if (entry.getName().equals(POM_FILE)) this.pom = !hasAttribute(ATTR_DEPENDENCIES) ? createPomReader0(jis) : null; } final Manifest man = jis.getManifest(); if (man == null || !isCapsule) throw new RuntimeException(jarFile + " is not a capsule"); merge(manifest, man); } catch (IOException e) { throw new RuntimeException("Could not read JAR file " + jarFile, e); } if (this.dependencyManager != null) setDependencyRepositories(getRepositories()); finalizeCapsule(); clearContext(); } private void finalizeCapsule() { validateManifest(); this.appId = buildAppId(); this.mode = chooseMode1(); } private boolean isEmptyCapsule() { return !hasAttribute(ATTR_APP_ARTIFACT) && !hasAttribute(ATTR_APP_CLASS) && !hasScript(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Properties"> /////////// Properties /////////////////////////////////// /** * This capsule's current mode. */ protected final String getMode() { return mode; } /** * This capsule's cache directory, or {@code null} if capsule has been configured not to extract. */ protected final Path getAppCache() { return appCache; } /** * This capsule's JAR file. */ protected final Path getJarFile() { return jarFile; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Capsule JAR"> /////////// Capsule JAR /////////////////////////////////// private static Path findOwnJarFile() { final URL url = Capsule.class.getClassLoader().getResource(Capsule.class.getName().replace('.', '/') + ".class"); if (!"jar".equals(url.getProtocol())) throw new IllegalStateException("The Capsule class must be in a JAR file, but was loaded from: " + url); final String path = url.getPath(); if (path == null || !path.startsWith("file:")) throw new IllegalStateException("The Capsule class must be in a local JAR file, but was loaded from: " + url); try { final URI jarUri = new URI(path.substring(0, path.indexOf('!'))); return Paths.get(jarUri); } catch (URISyntaxException e) { throw new AssertionError(e); } } private String toJarUrl(String relPath) { return "jar:file:" + jarFile.toAbsolutePath() + "!/" + relPath; } private InputStream getEntry(ZipInputStream zis, String name) throws IOException { for (ZipEntry entry; (entry = zis.getNextEntry()) != null;) { if (entry.getName().equals(name)) return zis; } return null; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Main Operations"> /////////// Main Operations /////////////////////////////////// void printVersion(List<String> args) { if (getAppId() != null) System.out.println(LOG_PREFIX + "Application " + getAppId()); System.out.println(LOG_PREFIX + "Capsule Version " + VERSION); } void printModes(List<String> args) { System.out.println(LOG_PREFIX + "Application " + getAppId()); System.out.println("Available modes:"); final Set<String> modes = getModes(); if (modes.isEmpty()) System.out.println("Default mode only"); else { for (String m : modes) { final String desc = getModeDescription(m); System.out.println("* " + m + (desc != null ? ": " + desc : "")); } } } void printJVMs(List<String> args) { final Map<String, Path> jres = getJavaHomes(); if (jres == null) println("No detected Java installations"); else { System.out.println(LOG_PREFIX + "Detected Java installations:"); for (Map.Entry<String, Path> j : jres.entrySet()) System.out.println(j.getKey() + (j.getKey().length() < 8 ? "\t\t" : "\t") + j.getValue()); } final Path javaHome = chooseJavaHome(); System.out.println(LOG_PREFIX + "selected " + (javaHome != null ? javaHome : (systemProperty(PROP_JAVA_HOME) + " (current)"))); } void printDependencyTree(List<String> args) { System.out.println("Dependencies for " + getAppId()); if (dependencyManager == null) System.out.println("No dependencies declared."); else if (hasAttribute(ATTR_APP_ARTIFACT)) { final String appArtifact = getAttribute(ATTR_APP_ARTIFACT); if (appArtifact == null) throw new IllegalStateException("capsule " + jarFile + " has nothing to run"); printDependencyTree(appArtifact, "jar"); } else printDependencyTree(getDependencies(), "jar"); final List<String> nativeDeps = getNativeDependencies(); if (nativeDeps != null) { System.out.println("\nNative Dependencies:"); printDependencyTree(nativeDeps, getNativeLibExtension()); } } void resolve(List<String> args) throws IOException, InterruptedException { ensureExtractedIfNecessary(); resolveDependency(getAttribute(ATTR_APP_ARTIFACT), "jar"); resolveDependencies(getDependencies(), "jar"); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH)); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH_P)); getPath(getListAttribute(ATTR_BOOT_CLASS_PATH_A)); resolveNativeDependencies(); log(LOG_QUIET, "Capsule resolved"); } private int launch(List<String> args) throws IOException, InterruptedException { final ProcessBuilder pb; try { final List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); pb = prepareForLaunch(jvmArgs, args); } catch (Throwable t) { cleanup(); throw t; } clearContext(); log(LOG_VERBOSE, join(pb.command(), " ")); if (isTrampoline()) { if (hasAttribute(ATTR_ENV)) throw new RuntimeException("Capsule cannot trampoline because manifest defines the " + ATTR_ENV + " attribute."); pb.command().remove("-D" + PROP_TRAMPOLINE); System.out.println(join(pb.command(), " ")); } else { Runtime.getRuntime().addShutdownHook(new Thread(this)); if (!isInheritIoBug()) pb.inheritIO(); this.child = pb.start(); if (isInheritIoBug()) pipeIoStreams(); final int pid = getPid(child); if (pid > 0) System.setProperty(PROP_CAPSULE_APP_PID, Integer.toString(pid)); child.waitFor(); } return child != null ? child.exitValue() : 0; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Launch"> /////////// Launch /////////////////////////////////// // directly used by CapsuleLauncher final ProcessBuilder prepareForLaunch(List<String> jvmArgs, List<String> args) { final long start = clock(); this.jvmArgs_ = nullToEmpty(jvmArgs); // hack this.args_ = nullToEmpty(jvmArgs); // hack log(LOG_VERBOSE, "Launching app " + appId + (mode != null ? " in mode " + mode : "")); try { ProcessBuilder pb = null; try { ensureExtractedIfNecessary(); pb = prelaunch(nullToEmpty(args)); return pb; } finally { markCache(pb != null); time("prepareForLaunch", start); } } catch (IOException e) { throw new RuntimeException(e); } } /** * @deprecated marked deprecated to exclude from javadoc */ @Override public final void run() { if (isInheritIoBug() && pipeIoStream()) return; // shutdown hook cleanup(); } /** * Called when the capsule exits after a successful or failed attempt to launch the application. * If you override this method, you must make sure to call {@code super.cleanup()} even in the event of an abnormal termination * (i.e. when an exception is thrown). This method must not throw any exceptions. All exceptions origination by {@code cleanup} * must be wither ignored completely or printed to STDERR. */ @SuppressWarnings("CallToPrintStackTrace") protected void cleanup() { try { if (child != null) child.destroy(); } catch (Throwable t) { t.printStackTrace(); } try { if (pathingJar != null) Files.delete(pathingJar); } catch (Throwable t) { t.printStackTrace(); } } private String chooseMode1() { String m = chooseMode(); if (m != null && !hasMode(m)) throw new IllegalArgumentException("Capsule " + jarFile + " does not have mode " + m); return m; } /** * Chooses this capsule's mode. * The mode is chosen during the preparations for launch (not at construction time). */ protected String chooseMode() { return emptyToNull(systemProperty(PROP_MODE)); } /** * Returns a configured {@link ProcessBuilder} that is later used to launch the capsule. * The ProcessBuilder's IO redirection is left in its default settings. * Custom capsules may override this method to display a message prior to launch, or to configure the process's IO streams. * For more elaborate manipulation of the Capsule's launched process, consider overriding {@link #buildProcess() buildProcess}. * * @param args the application command-line arguments * @return a configured {@code ProcessBuilder} (must never return {@code null}) */ protected ProcessBuilder prelaunch(List<String> args) { final ProcessBuilder pb = buildProcess(); final List<String> command = pb.command(); command.addAll(buildArgs(args)); buildEnvironmentVariables(pb.environment()); return pb; } /** * Constructs a {@link ProcessBuilder} that is later used to launch the capsule. * The returned process builder should contain the command <i>minus</i> the application arguments (which are later constructed by * {@link #buildArgs(List) buildArgs} and appended to the command).<br> * While environment variables may be set at this stage, the environment is later configured by * {@link #buildEnvironmentVariables(Map) buildEnvironmentVariables}. * <p> * This implementation tries to create a process running a startup script, and, if one has not been set, constructs a Java process. * <p> * This method should be overridden to add new types of processes the capsule can launch (like, say, Python scripts). * If all you want is to configure the returned {@link ProcessBuilder}, for example to set IO stream redirection, * you should override {@link #prelaunch(List) prelaunch}. * * @return a {@code ProcessBuilder} */ protected ProcessBuilder buildProcess() { if (jvmArgs_ == null) throw new IllegalStateException("Capsule has not been prepared for launch!"); final ProcessBuilder pb = new ProcessBuilder(); if (!buildScriptProcess(pb)) buildJavaProcess(pb, jvmArgs_, args_); return pb; } /** * Returns a list of command line arguments to pass to the application. * * @param args The command line arguments passed to the capsule at launch */ protected List<String> buildArgs(List<String> args) { return expandArgs(nullToEmpty(expand(getListAttribute(ATTR_ARGS))), args); } // visible for testing static List<String> expandArgs(List<String> args0, List<String> args) { final List<String> args1 = new ArrayList<String>(); boolean expanded = false; for (String a : args0) { if (a.startsWith("$")) { if (a.equals("$*")) { args1.addAll(args); expanded = true; continue; } else { try { final int i = Integer.parseInt(a.substring(1)); args1.add(args.get(i - 1)); expanded = true; continue; } catch (NumberFormatException e) { } } } args1.add(a); } if (!expanded) args1.addAll(args); return args1; } /** * Returns a map of environment variables (property-value pairs). * * @param env the current environment */ protected void buildEnvironmentVariables(Map<String, String> env) { final List<String> jarEnv = getListAttribute(ATTR_ENV); if (jarEnv != null) { for (String e : jarEnv) { String var = getBefore(e, '='); String value = getAfter(e, '='); if (var.isEmpty()) throw new IllegalArgumentException("Malformed env variable definition: " + e); boolean overwrite = false; if (var.endsWith(":")) { overwrite = true; var = var.substring(0, var.length() - 1); } if (overwrite || !env.containsKey(var)) env.put(var, value != null ? value : ""); } } if (appCache != null) env.put(VAR_CAPSULE_DIR, appCache.toAbsolutePath().toString()); env.put(VAR_CAPSULE_JAR, jarFile.toString()); assert appId != null; env.put(VAR_CAPSULE_APP, appId); } private static boolean isTrampoline() { return propertyDefined(PROP_TRAMPOLINE); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="App ID"> /////////// App ID /////////////////////////////////// /** * Computes and returns application's ID */ protected String buildAppId() { String appName = systemProperty(PROP_APP_ID); if (appName == null) appName = getAttribute(ATTR_APP_NAME); if (appName == null) { final String appArtifact = getAttribute(ATTR_APP_ARTIFACT); if (appArtifact != null && isDependency(appArtifact)) { if (hasModalAttribute(ATTR_APP_ARTIFACT)) throw new IllegalArgumentException("App ID-related attribute " + ATTR_APP_ARTIFACT + " is defined in a modal section of the manifest. " + " In this case, you must add the " + ATTR_APP_NAME + " attribute to the manifest's main section."); return getAppArtifactId(getAppArtifactSpecificVersion(appArtifact)); } } if (appName == null) { if (pom != null) return getPomAppName(); appName = getAttribute(ATTR_APP_CLASS); if (appName != null && hasModalAttribute(ATTR_APP_CLASS)) throw new IllegalArgumentException("App ID-related attribute " + ATTR_APP_CLASS + " is defined in a modal section of the manifest. " + " In this case, you must add the " + ATTR_APP_NAME + " attribute to the manifest's main section."); } if (appName == null) { throw new IllegalArgumentException("Capsule jar " + jarFile + " must either have the " + ATTR_APP_NAME + " manifest attribute, " + "the " + ATTR_APP_CLASS + " attribute, or contain a " + POM_FILE + " file."); } final String version = hasAttribute(ATTR_APP_VERSION) ? getAttribute(ATTR_APP_VERSION) : getAttribute(ATTR_IMPLEMENTATION_VERSION); return appName + (version != null ? "_" + version : ""); } /** * Returns the app's ID. */ protected final String getAppId() { return appId; } private static String getAppArtifactId(String coords) { if (coords == null) return null; final String[] cs = coords.split(":"); if (cs.length < 2) throw new IllegalArgumentException("Illegal main artifact coordinates: " + coords); String id = cs[0] + "_" + cs[1]; if (cs.length > 2) id += "_" + cs[2]; return id; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Capsule Cache"> /////////// Capsule Cache /////////////////////////////////// private static Path getCacheDir() { final Path cache; final String cacheDirEnv = System.getenv(ENV_CACHE_DIR); if (cacheDirEnv != null) cache = Paths.get(cacheDirEnv); else { final String cacheNameEnv = System.getenv(ENV_CACHE_NAME); final String cacheName = cacheNameEnv != null ? cacheNameEnv : CACHE_DEFAULT_NAME; cache = getCacheHome().resolve((isWindows() ? "" : ".") + cacheName); } return cache; } private static Path initCacheDir(Path cache) { try { if (!Files.exists(cache)) Files.createDirectory(cache); Files.createDirectories(cache.resolve(APP_CACHE_NAME)); Files.createDirectories(cache.resolve(DEPS_CACHE_NAME)); return cache; } catch (IOException e) { throw new RuntimeException("Error opening cache directory " + cache.toAbsolutePath(), e); } } private static Path getCacheHome() { final Path userHome = Paths.get(systemProperty(PROP_USER_HOME)); if (!isWindows()) return userHome; Path localData; final String localAppData = getenv("LOCALAPPDATA"); if (localAppData != null) { localData = Paths.get(localAppData); if (!Files.isDirectory(localData)) throw new RuntimeException("%LOCALAPPDATA% set to nonexistent directory " + localData); } else { localData = userHome.resolve(Paths.get("AppData", "Local")); if (!Files.isDirectory(localData)) localData = userHome.resolve(Paths.get("Local Settings", "Application Data")); if (!Files.isDirectory(localData)) throw new RuntimeException("%LOCALAPPDATA% is undefined, and neither " + userHome.resolve(Paths.get("AppData", "Local")) + " nor " + userHome.resolve(Paths.get("Local Settings", "Application Data")) + " have been found"); } return localData; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="App Cache"> /////////// App Cache /////////////////////////////////// private Path getAppCacheDir() throws IOException { assert appId != null; Path appDir = cacheDir.resolve(APP_CACHE_NAME).resolve(appId); try { if (!Files.exists(appDir)) Files.createDirectory(appDir); return appDir; } catch (IOException e) { throw new IOException("Application cache directory " + appDir.toAbsolutePath() + " could not be created."); } } private void ensureAppCacheIfNecessary() throws IOException { if (appCache != null) return; this.appCache = needsAppCache() ? getAppCacheDir() : null; this.cacheUpToDate = appCache != null ? isAppCacheUpToDate1() : false; } private void ensureExtractedIfNecessary() throws IOException { final long start = clock(); ensureAppCacheIfNecessary(); if (appCache != null) { if (!cacheUpToDate) { resetAppCache(); if (shouldExtract()) extractCapsule(); } else log(LOG_VERBOSE, "App cache " + appCache + " is up to date."); } time("ensureExtracted", start); } private boolean needsAppCache() { if (hasRenamedNativeDependencies()) return true; if (hasAttribute(ATTR_APP_ARTIFACT) && isDependency(getAttribute(ATTR_APP_ARTIFACT))) return false; return shouldExtract(); } private boolean shouldExtract() { final String extract = getAttribute(ATTR_EXTRACT); return extract == null || Boolean.parseBoolean(extract); } private void resetAppCache() throws IOException { try { log(LOG_DEBUG, "Creating cache for " + jarFile + " in " + appCache.toAbsolutePath()); final Path lockFile = appCache.resolve(LOCK_FILE_NAME); try (DirectoryStream<Path> ds = Files.newDirectoryStream(appCache)) { for (Path f : ds) { if (lockFile.equals(f)) continue; delete(f); } } } catch (IOException e) { throw new IOException("Exception while extracting jar " + jarFile + " to app cache directory " + appCache.toAbsolutePath(), e); } } private boolean isAppCacheUpToDate1() throws IOException { boolean res = isAppCacheUpToDate(); if (!res) { lockAppCache(); res = isAppCacheUpToDate(); if (res) unlockAppCache(); } return res; } /** * Tests if the app cache is up to date. * * The app cache directory is obtained by calling {@link #getAppCache() getAppCache}. * This creates a file in the app cache, whose timestamp is compared with the capsule's JAR timestamp. */ protected boolean isAppCacheUpToDate() throws IOException { if (systemPropertyEmptyOrTrue(PROP_RESET)) return false; Path extractedFile = appCache.resolve(TIMESTAMP_FILE_NAME); if (!Files.exists(extractedFile)) return false; FileTime extractedTime = Files.getLastModifiedTime(extractedFile); FileTime jarTime = Files.getLastModifiedTime(jarFile); return extractedTime.compareTo(jarTime) >= 0; } /** * Extracts the capsule's contents into the app cache directory. * This method may be overridden to write additional files to the app cache. */ protected void extractCapsule() throws IOException { try { log(LOG_VERBOSE, "Extracting " + jarFile + " to app cache directory " + appCache.toAbsolutePath()); extractJar(openJarInputStream(jarFile), appCache); } catch (IOException e) { throw new IOException("Exception while extracting jar " + jarFile + " to app cache directory " + appCache.toAbsolutePath(), e); } } private void markCache(boolean success) throws IOException { if (appCache == null || cacheUpToDate) return; if (success) Files.createFile(appCache.resolve(TIMESTAMP_FILE_NAME)); unlockAppCache(); } private void lockAppCache() throws IOException { final Path lockFile = appCache.resolve(LOCK_FILE_NAME); log(LOG_VERBOSE, "Locking " + lockFile); final FileChannel c = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE); this.appCacheLock = c.lock(); } private void unlockAppCache() throws IOException { if (appCacheLock != null) { log(LOG_VERBOSE, "Unocking " + appCache.resolve(LOCK_FILE_NAME)); appCacheLock.release(); appCacheLock.acquiredBy().close(); appCacheLock = null; } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Script Process"> /////////// Script Process /////////////////////////////////// private boolean hasScript() { return hasAttribute(isWindows() ? ATTR_WINDOWS_SCRIPT : ATTR_UNIX_SCRIPT); } private String getScript() { return getAttribute(isWindows() ? ATTR_WINDOWS_SCRIPT : ATTR_UNIX_SCRIPT); } private boolean buildScriptProcess(ProcessBuilder pb) { final String script = getScript(); if (script == null) return false; if (appCache == null) throw new IllegalStateException("Cannot run the startup script " + script + " when the " + ATTR_EXTRACT + " attribute is set to false"); setJavaHomeEnv(pb, getJavaHome()); final List<Path> classPath = buildClassPath(); resolveNativeDependencies(); pb.environment().put(VAR_CLASSPATH, compileClassPath(classPath)); final Path scriptPath = sanitize(appCache, script).toAbsolutePath(); ensureExecutable(scriptPath); pb.command().add(scriptPath.toString()); return true; } private Path setJavaHomeEnv(ProcessBuilder pb, Path javaHome) { if (javaHome == null) return null; pb.environment().put(VAR_JAVA_HOME, javaHome.toString()); return javaHome; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Java Process"> /////////// Java Process /////////////////////////////////// private boolean buildJavaProcess(ProcessBuilder pb, List<String> cmdLine, List<String> args) { final List<String> command = pb.command(); command.add(getJavaExecutable().toString()); command.addAll(buildJVMArgs(cmdLine)); command.addAll(compileSystemProperties(buildSystemProperties(cmdLine))); addOption(command, "-Xbootclasspath:", compileClassPath(buildBootClassPath(cmdLine))); addOption(command, "-Xbootclasspath/p:", compileClassPath(buildBootClassPathP())); addOption(command, "-Xbootclasspath/a:", compileClassPath(buildBootClassPathA())); for (String jagent : nullToEmpty(buildJavaAgents())) command.add("-javaagent:" + jagent); final List<Path> classPath = buildClassPath(); final String mainClass = getMainClass(classPath); command.add("-classpath"); command.add(compileClassPath(handleLongClasspath(classPath, mainClass.length(), command, args))); command.add(mainClass); return true; } private List<Path> handleLongClasspath(List<Path> cp, int extra, List<?>... args) { if (!isWindows()) return cp; // why work hard if we know the problem only exists on Windows? long len = extra + getStringsLength(cp) + cp.size(); for (List<?> list : args) len += getStringsLength(list) + list.size(); if (len >= getMaxCommandLineLength()) { log(LOG_DEBUG, "Command line length: " + len); if (isTrampoline()) throw new RuntimeException("Command line too long and trampoline requested."); this.pathingJar = createPathingJar(Paths.get(systemProperty(PROP_TMP_DIR)), cp); log(LOG_VERBOSE, "Writing classpath: " + cp + " to pathing JAR: " + pathingJar); return singletonList(pathingJar); } else return cp; } /** * Returns the path to the executable that will be used to launch Java. * The default implementation uses the {@code capsule.java.cmd} property or the {@code JAVACMD} environment variable, * and if not set, returns the value of {@code getJavaExecutable(getJavaHome())}. */ protected Path getJavaExecutable() { String javaCmd = emptyToNull(systemProperty(PROP_CAPSULE_JAVA_CMD)); if (javaCmd != null) return path(javaCmd); return getJavaExecutable(getJavaHome()); } /** * Finds the path to the executable that will be used to launch Java within the given {@code javaHome}. */ protected static final Path getJavaExecutable(Path javaHome) { final Path exec = getJavaExecutable0(javaHome); assert exec.startsWith(javaHome); return exec; } private static List<String> compileSystemProperties(Map<String, String> ps) { final List<String> command = new ArrayList<String>(); for (Map.Entry<String, String> entry : ps.entrySet()) command.add("-D" + entry.getKey() + (entry.getValue() != null && !entry.getValue().isEmpty() ? "=" + entry.getValue() : "")); return command; } private static String compileClassPath(List<Path> cp) { return join(cp, PATH_SEPARATOR); } private static void addOption(List<String> cmdLine, String prefix, String value) { if (value == null) return; cmdLine.add(prefix + value); } /** * Compiles and returns the application's classpath as a list of paths. */ protected List<Path> buildClassPath() { final long start = clock(); final List<Path> classPath = new ArrayList<Path>(); // the capsule jar final String isCapsuleInClassPath = getAttribute(ATTR_CAPSULE_IN_CLASS_PATH); if (isCapsuleInClassPath == null || Boolean.parseBoolean(isCapsuleInClassPath)) classPath.add(jarFile); else if (appCache == null) throw new IllegalStateException("Cannot set the " + ATTR_CAPSULE_IN_CLASS_PATH + " attribute to false when the " + ATTR_EXTRACT + " attribute is also set to false"); // the app artifact (mustn't be a capsule if we're here) if (hasAttribute(ATTR_APP_ARTIFACT)) { if (isGlob(getAttribute(ATTR_APP_ARTIFACT))) throw new IllegalArgumentException("Glob pattern not allowed in " + ATTR_APP_ARTIFACT + " attribute."); classPath.addAll(getPath(getAttribute(ATTR_APP_ARTIFACT))); } if (hasAttribute(ATTR_APP_CLASS_PATH)) { for (String sp : getListAttribute(ATTR_APP_CLASS_PATH)) { if (isDependency(sp)) throw new IllegalArgumentException("Dependency " + sp + " is not allowed in the " + ATTR_APP_CLASS_PATH + " attribute"); addAllIfNotContained(classPath, getPath(sp)); } } if (appCache != null) addAllIfNotContained(classPath, nullToEmpty(getDefaultCacheClassPath())); classPath.addAll(nullToEmpty(resolveDependencies(getDependencies(), "jar"))); time("buildClassPath", start); return classPath; } private List<Path> getDefaultCacheClassPath() { final List<Path> cp = new ArrayList<Path>(listDir(appCache, "*.jar", true)); cp.add(0, appCache); return cp; } /** * Returns a list of dependencies, each in the format {@code groupId:artifactId:version[:classifier]} (classifier is optional) */ protected List<String> getDependencies() { List<String> deps = getListAttribute(ATTR_DEPENDENCIES); if ((deps == null || deps.isEmpty()) && pom != null) deps = getPomDependencies(); return (deps != null && !deps.isEmpty()) ? unmodifiableList(deps) : null; } /** * Compiles and returns the application's boot classpath as a list of paths. */ private List<Path> buildBootClassPath(List<String> cmdLine) { String option = null; for (String o : cmdLine) { if (o.startsWith("-Xbootclasspath:")) option = o.substring("-Xbootclasspath:".length()); } if (option != null) return toPath(Arrays.asList(option.split(PATH_SEPARATOR))); return buildBootClassPath(); } /** * Compiles and returns the application's boot classpath as a list of paths. */ protected List<Path> buildBootClassPath() { return getPath(getListAttribute(ATTR_BOOT_CLASS_PATH)); } /** * Compiles and returns the paths to be prepended to the application's boot classpath. */ protected List<Path> buildBootClassPathP() { return buildClassPath(ATTR_BOOT_CLASS_PATH_P); } /** * Compiles and returns the paths to be appended to the application's boot classpath. */ protected List<Path> buildBootClassPathA() { return buildClassPath(ATTR_BOOT_CLASS_PATH_A); } private List<Path> buildClassPath(String attr) { return getPath(getListAttribute(attr)); } private Map<String, String> buildSystemProperties(List<String> cmdLine) { final Map<String, String> systemProperties = buildSystemProperties(); // command line overrides everything for (String option : cmdLine) { if (option.startsWith("-D")) addSystemProperty(option.substring(2), systemProperties); } return systemProperties; } /** * Returns a map of system properties (property-value pairs). */ protected Map<String, String> buildSystemProperties() { final Map<String, String> systemProperties = new HashMap<String, String>(); // attribute for (Map.Entry<String, String> pv : nullToEmpty(getMapAttribute(ATTR_SYSTEM_PROPERTIES, "")).entrySet()) systemProperties.put(pv.getKey(), expand(pv.getValue())); // library path final List<Path> libraryPath = buildNativeLibraryPath(); systemProperties.put(PROP_JAVA_LIBRARY_PATH, compileClassPath(libraryPath)); if (hasAttribute(ATTR_SECURITY_POLICY) || hasAttribute(ATTR_SECURITY_POLICY_A)) { systemProperties.put(PROP_JAVA_SECURITY_MANAGER, ""); if (hasAttribute(ATTR_SECURITY_POLICY_A)) systemProperties.put(PROP_JAVA_SECURITY_POLICY, toJarUrl(getAttribute(ATTR_SECURITY_POLICY_A))); if (hasAttribute(ATTR_SECURITY_POLICY)) systemProperties.put(PROP_JAVA_SECURITY_POLICY, "=" + toJarUrl(getAttribute(ATTR_SECURITY_POLICY))); } if (hasAttribute(ATTR_SECURITY_MANAGER)) systemProperties.put(PROP_JAVA_SECURITY_MANAGER, getAttribute(ATTR_SECURITY_MANAGER)); // Capsule properties if (appCache != null) systemProperties.put(PROP_CAPSULE_DIR, appCache.toAbsolutePath().toString()); systemProperties.put(PROP_CAPSULE_JAR, jarFile.toString()); assert appId != null; systemProperties.put(PROP_CAPSULE_APP, appId); return systemProperties; } private static void addSystemProperty(String p, Map<String, String> ps) { try { String name = getBefore(p, '='); String value = getAfter(p, '='); ps.put(name, value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Illegal system property definition: " + p); } } //<editor-fold desc="Native Dependencies"> /////////// Native Dependencies /////////////////////////////////// private List<Path> buildNativeLibraryPath() { final List<Path> libraryPath = new ArrayList<Path>(toPath(Arrays.asList(systemProperty(PROP_JAVA_LIBRARY_PATH).split(PATH_SEPARATOR)))); resolveNativeDependencies(); if (appCache != null) { libraryPath.addAll(0, nullToEmpty(toAbsolutePath(appCache, getListAttribute(ATTR_LIBRARY_PATH_P)))); libraryPath.addAll(nullToEmpty(toAbsolutePath(appCache, getListAttribute(ATTR_LIBRARY_PATH_A)))); libraryPath.add(appCache); } else if (hasAttribute(ATTR_LIBRARY_PATH_P) || hasAttribute(ATTR_LIBRARY_PATH_A)) throw new IllegalStateException("Cannot use the " + ATTR_LIBRARY_PATH_P + " or the " + ATTR_LIBRARY_PATH_A + " attributes when the " + ATTR_EXTRACT + " attribute is set to false"); return libraryPath; } private void resolveNativeDependencies() { final List<String> depsAndRename = getNativeDependencies(); if (depsAndRename == null || depsAndRename.isEmpty()) return; if (appCache == null) throw new IllegalStateException("Cannot have native dependencies when the " + ATTR_EXTRACT + " attribute is set to false"); final List<String> deps = new ArrayList<String>(depsAndRename.size()); final List<String> renames = new ArrayList<String>(depsAndRename.size()); splitDepsAndRename(depsAndRename, deps, renames); log(LOG_VERBOSE, "Resolving native libs " + deps); final List<Path> resolved = resolveDependencies(deps, getNativeLibExtension()); if (resolved.size() != deps.size()) throw new RuntimeException("One of the native artifacts " + deps + " reolved to more than a single file or to none"); assert appCache != null; if (!cacheUpToDate) { if (isLogging(LOG_DEBUG)) System.err.println("Copying native libs to " + appCache); try { for (int i = 0; i < deps.size(); i++) { final Path lib = resolved.get(i); final String rename = renames.get(i); Files.copy(lib, sanitize(appCache, rename != null ? rename : lib.getFileName().toString())); } } catch (IOException e) { throw new RuntimeException("Exception while copying native libs", e); } } } private void splitDepsAndRename(List<String> depsAndRename, List<String> deps, List<String> renames) { for (String depAndRename : depsAndRename) { String[] dna = depAndRename.split(","); deps.add(dna[0]); if (renames != null) renames.add(dna.length > 1 ? dna[1] : null); } } /** * Constructs this capsule's native dependency list. * * @return a list of native dependencies, each in the format {@code groupId:artifactId:version[:classifier][,renameTo]} * (classifier and renameTo are optional). */ protected List<String> getNativeDependencies() { if (isWindows()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_WIN); if (isMac()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_MAC); if (isUnix()) return getListAttribute(ATTR_NATIVE_DEPENDENCIES_LINUX); return null; } private boolean hasRenamedNativeDependencies() { final List<String> depsAndRename = getNativeDependencies(); if (depsAndRename == null) return false; for (String depAndRename : depsAndRename) { if (depAndRename.contains(",")) return true; } return false; } //</editor-fold> private List<String> buildJVMArgs(List<String> cmdLine) { final Map<String, String> jvmArgs = new LinkedHashMap<String, String>(); for (String option : buildJVMArgs()) addJvmArg(option, jvmArgs); for (String option : nullToEmpty(Capsule.split(systemProperty(PROP_JVM_ARGS), " "))) addJvmArg(option, jvmArgs); // command line overrides everything for (String option : cmdLine) { if (!option.startsWith("-D") && !option.startsWith("-Xbootclasspath:")) addJvmArg(option, jvmArgs); } return new ArrayList<String>(jvmArgs.values()); } /** * Returns a list of JVM arguments. */ protected List<String> buildJVMArgs() { final Map<String, String> jvmArgs = new LinkedHashMap<String, String>(); for (String a : nullToEmpty(getListAttribute(ATTR_JVM_ARGS))) { a = a.trim(); if (!a.isEmpty() && !a.startsWith("-Xbootclasspath:") && !a.startsWith("-javaagent:")) addJvmArg(expand(a), jvmArgs); } return new ArrayList<String>(jvmArgs.values()); } private static void addJvmArg(String a, Map<String, String> args) { args.put(getJvmArgKey(a), a); } private static String getJvmArgKey(String a) { if (a.equals("-client") || a.equals("-server")) return "compiler"; if (a.equals("-enablesystemassertions") || a.equals("-esa") || a.equals("-disablesystemassertions") || a.equals("-dsa")) return "systemassertions"; if (a.equals("-jre-restrict-search") || a.equals("-no-jre-restrict-search")) return "-jre-restrict-search"; if (a.startsWith("-Xloggc:")) return "-Xloggc"; if (a.startsWith("-Xss")) return "-Xss"; if (a.startsWith("-Xmx")) return "-Xmx"; if (a.startsWith("-Xms")) return "-Xms"; if (a.startsWith("-XX:+") || a.startsWith("-XX:-")) return "-XX:" + a.substring("-XX:+".length()); if (a.contains("=")) return a.substring(0, a.indexOf('=')); return a; } private List<String> buildJavaAgents() { final long start = clock(); final Map<String, String> agents0 = getMapAttribute(ATTR_JAVA_AGENTS, ""); if (agents0 == null) return null; final List<String> agents = new ArrayList<String>(agents0.size()); for (Map.Entry<String, String> agent : agents0.entrySet()) { final String agentJar = agent.getKey(); final String agentOptions = agent.getValue(); try { final Path agentPath = first(getPath(agent.getKey())); agents.add(agentPath + ((agentOptions != null && !agentOptions.isEmpty()) ? "=" + agentOptions : "")); } catch (IllegalStateException e) { if (appCache == null) throw new RuntimeException("Cannot run the embedded Java agent " + agentJar + " when the " + ATTR_EXTRACT + " attribute is set to false"); throw e; } } time("buildJavaAgents", start); return agents; } private String getMainClass(List<Path> classPath) { try { String mainClass = getAttribute(ATTR_APP_CLASS); if (mainClass == null && hasAttribute(ATTR_APP_ARTIFACT)) mainClass = getMainClass(getAppArtifactJarFromClasspath(classPath)); if (mainClass == null) throw new RuntimeException("Jar " + classPath.get(0).toAbsolutePath() + " does not have a main class defined in the manifest."); return mainClass; } catch (IOException e) { throw new RuntimeException(e); } } private Path getAppArtifactJarFromClasspath(List<Path> classPath) { return classPath.get(0).equals(jarFile) ? classPath.get(1) : classPath.get(0); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Get Java Home"> /////////// Get Java Home /////////////////////////////////// private Path javaHome_; // cached value /** * The path to the Java installation this capsule's app will use. */ protected final Path getJavaHome() { if (javaHome_ == null) { final Path jhome = chooseJavaHome(); this.javaHome_ = jhome != null ? jhome : Paths.get(systemProperty(PROP_JAVA_HOME)); log(LOG_VERBOSE, "Using JVM: " + javaHome_); } return javaHome_; } /** * Chooses which Java installation to use for running the app. * * @return the path of the Java installation to use for launching the app, or {@code null} if the current JVM is to be used. */ protected Path chooseJavaHome() { final long start = clock(); Path jhome = emptyToNull(systemProperty(PROP_CAPSULE_JAVA_HOME)) != null ? Paths.get(systemProperty(PROP_CAPSULE_JAVA_HOME)) : null; if (jhome == null && !isMatchingJavaVersion(systemProperty(PROP_JAVA_VERSION))) { final boolean jdk = hasAttribute(ATTR_JDK_REQUIRED) && Boolean.parseBoolean(getAttribute(ATTR_JDK_REQUIRED)); jhome = findJavaHome(jdk); if (isLogging(LOG_VERBOSE)) log(LOG_VERBOSE, "Finding JVM: " + ((System.nanoTime() - start) / 1_000_000) + "ms"); if (jhome == null) { throw new RuntimeException("Could not find Java installation for requested version " + '[' + "Min. Java version: " + getAttribute(ATTR_MIN_JAVA_VERSION) + " JavaVersion: " + getAttribute(ATTR_JAVA_VERSION) + " Min. update version: " + getAttribute(ATTR_MIN_UPDATE_VERSION) + ']' + " (JDK required: " + jdk + ")" + ". You can override the used Java version with the -D" + PROP_CAPSULE_JAVA_HOME + " flag."); } } time("chooseJavaHome", start); return jhome != null ? jhome.toAbsolutePath() : jhome; } private Path findJavaHome(boolean jdk) { Map<String, Path> homes = getJavaHomes(); if (jdk) homes = getJDKs(homes); if (homes == null) return null; Path best = null; String bestVersion = null; for (Map.Entry<String, Path> e : homes.entrySet()) { final String v = e.getKey(); log(LOG_DEBUG, "Trying JVM: " + e.getValue() + " (version " + e.getKey() + ")"); if (isMatchingJavaVersion(v)) { log(LOG_DEBUG, "JVM " + e.getValue() + " (version " + e.getKey() + ") matches"); if (bestVersion == null || compareVersions(v, bestVersion) > 0) { log(LOG_DEBUG, "JVM " + e.getValue() + " (version " + e.getKey() + ") is best so far"); bestVersion = v; best = e.getValue(); } } } return best; } private boolean isMatchingJavaVersion(String javaVersion) { try { if (hasAttribute(ATTR_MIN_JAVA_VERSION) && compareVersions(javaVersion, getAttribute(ATTR_MIN_JAVA_VERSION)) < 0) { log(LOG_DEBUG, "Java version " + javaVersion + " fails to match due to " + ATTR_MIN_JAVA_VERSION + ": " + getAttribute(ATTR_MIN_JAVA_VERSION)); return false; } if (hasAttribute(ATTR_JAVA_VERSION) && compareVersions(javaVersion, shortJavaVersion(getAttribute(ATTR_JAVA_VERSION)), 3) > 0) { log(LOG_DEBUG, "Java version " + javaVersion + " fails to match due to " + ATTR_JAVA_VERSION + ": " + getAttribute(ATTR_JAVA_VERSION)); return false; } if (getMinUpdateFor(javaVersion) > parseJavaVersion(javaVersion)[3]) { log(LOG_DEBUG, "Java version " + javaVersion + " fails to match due to " + ATTR_MIN_UPDATE_VERSION + ": " + getAttribute(ATTR_MIN_UPDATE_VERSION) + " (" + getMinUpdateFor(javaVersion) + ")"); return false; } log(LOG_DEBUG, "Java version " + javaVersion + " matches"); return true; } catch (IllegalArgumentException ex) { log(LOG_VERBOSE, "Error parsing Java version " + javaVersion); return false; } } private int getMinUpdateFor(String version) { final Map<String, String> m = getMapAttribute(ATTR_MIN_UPDATE_VERSION, null); if (m == null) return 0; final int[] ver = parseJavaVersion(version); for (Map.Entry<String, String> entry : m.entrySet()) { if (equals(ver, toInt(shortJavaVersion(entry.getKey()).split(SEPARATOR_DOT)), 3)) return Integer.parseInt(entry.getValue()); } return 0; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="POM"> /////////// POM /////////////////////////////////// private Object createPomReader(ZipInputStream zis) throws IOException { try { final InputStream is = getEntry(zis, POM_FILE); if (is == null) return null; return createPomReader0(is); } catch (IOException e) { throw new IOException("Could not read " + POM_FILE, e); } } private Object createPomReader0(InputStream is) { try { return new PomReader(is); } catch (NoClassDefFoundError e) { throw new RuntimeException("Jar " + jarFile + " contains a pom.xml file, while the necessary dependency management classes are not found in the jar"); } } private List<String> getPomRepositories() { return ((PomReader) pom).getRepositories(); } private List<String> getPomDependencies() { return ((PomReader) pom).getDependencies(); } private String getPomAppName() { final PomReader pr = (PomReader) pom; return pr.getGroupId() + "_" + pr.getArtifactId() + "_" + pr.getVersion(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Dependency Manager"> /////////// Dependency Manager /////////////////////////////////// private List<String> getRepositories() { final List<String> repos = new ArrayList<String>(); final List<String> envRepos = Capsule.split(getenv(ENV_CAPSULE_REPOS), "[,\\s]\\s*"); final List<String> attrRepos = getListAttribute(ATTR_REPOSITORIES); if (envRepos != null) repos.addAll(envRepos); if (attrRepos != null) repos.addAll(attrRepos); if (pom != null) { for (String repo : nullToEmpty(getPomRepositories())) { if (!repos.contains(repo)) repos.add(repo); } } return !repos.isEmpty() ? unmodifiableList(repos) : null; } private Object tryCreateDependencyManager() { if (systemPropertyEmptyOrTrue(PROP_NO_DEP_MANAGER)) return null; try { final boolean reset = systemPropertyEmptyOrTrue(PROP_RESET); final Path localRepo = getLocalRepo(); return new DependencyManagerImpl(localRepo.toAbsolutePath(), reset, logLevel); } catch (NoClassDefFoundError e) { return null; } } private void verifyDependencyManager() { if (dependencyManager == null) throw new RuntimeException("Capsule " + jarFile + " uses dependencies, while the necessary dependency management classes are not found in the capsule JAR"); } private void setDependencyRepositories(List<String> repositories) { verifyDependencyManager(); final boolean allowSnapshots = hasAttribute(ATTR_ALLOW_SNAPSHOTS) && Boolean.parseBoolean(getAttribute(ATTR_ALLOW_SNAPSHOTS)); ((DependencyManager) dependencyManager).setRepos(repositories, allowSnapshots); } private Path getLocalRepo() { Path localRepo = cacheDir.resolve(DEPS_CACHE_NAME); final String local = expandCommandLinePath(propertyOrEnv(PROP_USE_LOCAL_REPO, ENV_CAPSULE_LOCAL_REPO)); if (local != null) localRepo = !local.isEmpty() ? Paths.get(local) : null; return localRepo; } private void printDependencyTree(String root, String type) { verifyDependencyManager(); ((DependencyManager) dependencyManager).printDependencyTree(root, type, System.out); } private void printDependencyTree(List<String> dependencies, String type) { if (dependencies == null) return; verifyDependencyManager(); ((DependencyManager) dependencyManager).printDependencyTree(dependencies, type, System.out); } private List<Path> resolveDependencies(List<String> dependencies, String type) { if (dependencies == null) return null; verifyDependencyManager(); final long start = clock(); final List<Path> res = ((DependencyManager) dependencyManager).resolveDependencies(dependencies, type); time("resolveDependencies", start); return res; } private List<Path> resolveDependency(String coords, String type) { if (coords == null) return null; verifyDependencyManager(); final long start = clock(); final List<Path> res = ((DependencyManager) dependencyManager).resolveDependency(coords, type); time("resolveDependency " + coords, start); return res; } private String getAppArtifactSpecificVersion(String appArtifact) { return getArtifactLatestVersion(appArtifact, "jar"); } private String getArtifactLatestVersion(String coords, String type) { if (coords == null) return null; verifyDependencyManager(); return ((DependencyManager) dependencyManager).getLatestVersion(coords, type); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Attributes"> /////////// Attributes /////////////////////////////////// /* * The methods in this section are the only ones accessing the manifest. Therefore other means of * setting attributes can be added by changing these methods alone. */ private void validateManifest() { if (manifest.getMainAttributes().getValue(ATTR_CLASS_PATH) != null) throw new IllegalStateException("Capsule manifest contains a " + ATTR_CLASS_PATH + " attribute." + " Use " + ATTR_APP_CLASS_PATH + " and/or " + ATTR_DEPENDENCIES + " instead."); validateNonModalAttributes(); } private void validateNonModalAttributes() { for (Map.Entry<String, Attributes> entry : manifest.getEntries().entrySet()) { for (String attr : NON_MODAL_ATTRS) { if (entry.getValue().containsKey(new Attributes.Name(attr))) throw new IllegalStateException("Manifest section " + entry.getKey() + " contains non-modal attribute " + attr); } } } private boolean hasModalAttribute(String attr) { final Attributes.Name key = new Attributes.Name(attr); for (Map.Entry<String, Attributes> entry : manifest.getEntries().entrySet()) { if (entry.getValue().containsKey(key)) return true; } return false; } private boolean hasMode(String mode) { return manifest.getAttributes(mode) != null; } /** * Returns the names of all modes defined in this capsule's manifest. */ protected final Set<String> getModes() { return unmodifiableSet(manifest.getEntries().keySet()); } /** * Returns the description of the given mode. */ protected final String getModeDescription(String mode) { return manifest.getAttributes(mode).getValue(ATTR_MODE_DESC); } /** * Returns the value of the given manifest attribute with consideration to the capsule's mode. * * @param attr the attribute */ protected final String getAttribute(String attr) { String value = null; if (mode != null && !NON_MODAL_ATTRS.contains(attr)) value = manifest.getAttributes(mode).getValue(attr); if (value == null) value = manifest.getMainAttributes().getValue(attr); setContext("attribute", attr, value); return value; } /** * Tests whether the given attribute is found in the manifest. * * @param attr the attribute */ protected final boolean hasAttribute(String attr) { final Attributes.Name key = new Attributes.Name(attr); if (mode != null && !NON_MODAL_ATTRS.contains(attr)) { if (manifest.getAttributes(mode).containsKey(key)) return true; } return manifest.getMainAttributes().containsKey(key); } /** * Returns the value of the given attribute (with consideration to the capsule's mode) as a list. * The items comprising attribute's value must be whitespace-separated. * <p> * Same as {@code parse(getAttribute(attr))}. * * @param attr the attribute */ protected final List<String> getListAttribute(String attr) { return parse(getAttribute(attr)); } /** * Returns the value of the given attribute (with consideration to the capsule's mode) as a map. * The key-value pairs comprising attribute's value must be whitespace-separated, with each pair written as <i>key</i>=<i>value</i>. * <p> * Same as {@code parse(getAttribute(attr), defaultValue)}. * * @param attr the attribute * @param defaultValue a default value to use for keys without a value, or {@code null} if such an event should throw an exception */ protected final Map<String, String> getMapAttribute(String attr, String defaultValue) { return parse(getAttribute(attr), defaultValue); } /** * Parses an attribute's value string into a list. * The items comprising attribute's value must be whitespace-separated. * * @param value the attribute's value */ protected static final List<String> parse(String value) { return split(value, "\\s+"); } /** * Parses an attribute's value string into a map. * The key-value pairs comprising string must be whitespace-separated, with each pair written as <i>key</i>=<i>value</i>. * * @param value the attribute's value * @param defaultValue a default value to use for keys without a value, or {@code null} if such an event should throw an exception */ protected static final Map<String, String> parse(String value, String defaultValue) { return split(value, '=', "\\s+", defaultValue); } /** * Combines collection elements into a string that can be used as the value of an attribute. */ protected static final String toStringValue(Collection<String> list) { return join(list, " "); } /** * Combines map elements into a string that can be used as the value of an attribute. */ protected static final String toStringValue(Map<String, String> map) { return join(map, '=', " "); } private void merge(Manifest man1, Manifest man2) { if (man2 == null) return; merge(man1.getMainAttributes(), man2.getMainAttributes()); for (Map.Entry<String, Attributes> entry : man2.getEntries().entrySet()) { final Attributes attr = man1.getAttributes(entry.getKey()); if (attr != null) merge(attr, entry.getValue()); else man1.getEntries().put(entry.getKey(), entry.getValue()); } } private void merge(Attributes a1, Attributes a2) { for (Map.Entry<Object, Object> entry : a2.entrySet()) a1.put(entry.getKey(), merge(entry.getKey().toString(), (String) a1.get(entry.getKey()), (String) entry.getValue())); } /** * When using an empty capsule to launch another, this method will be called for each attribute in the wrapped (non-empty) manifest to merge * the wrapped capsule's attribute with the wrapper (empty) capsule's attribute. * When overriding this method, it may be useful to make use of {@link #parse(String) parse}, {@link #parse(String, String) parse map}, * {@link #toStringValue(Collection) toStringValue}, and {@link #toStringValue(Map) map toStringValue}. * <p> * The default implementation simply returns {@code value1}, unless it is {@code null} in which case it will pick {@code value2}; * in other words, it gives preference to the wrapper capsule's attributes. * * @param attribute the attribute's name * @param value1 the attribute's value in the wrapper (empty) capsule * @param value2 the attribute's value in the wrapped capsule * @return the value which will be used when launching the capsule */ protected String merge(String attribute, String value1, String value2) { return (value1 != null) ? value1 : value2; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Dependency Utils"> /////////// Dependency Utils /////////////////////////////////// private static boolean isDependency(String lib) { return lib.contains(":"); } private String dependencyToLocalJar(boolean withGroupId, String p) { String[] coords = p.split(":"); StringBuilder sb = new StringBuilder(); if (withGroupId) sb.append(coords[0]).append('-'); sb.append(coords[1]).append('-'); sb.append(coords[2]); if (coords.length > 3) sb.append('-').append(coords[3]); sb.append(".jar"); return sb.toString(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Paths"> /////////// Paths /////////////////////////////////// /** * Returns the path or paths to the given file descriptor. * The given descriptor can be a dependency, a file name (relative to the app cache) * or a glob pattern (again, relative to the app cache). The returned list can contain more than one element * if a dependency is given and it resolves to more than a single artifact, or if a glob pattern is given, * which matches more than one file. */ private List<Path> getPath(String p) { if (p == null) return null; if (isDependency(p) && dependencyManager != null) { final List<Path> res = resolveDependency(p, "jar"); if (res == null || res.isEmpty()) throw new RuntimeException("Dependency " + p + " was not found."); return res; } if (appCache == null) throw new IllegalStateException( (isDependency(p) ? "Dependency manager not found. Cannot resolve" : "Capsule not extracted. Cannot obtain path") + " " + p); if (isDependency(p)) { Path f = appCache.resolve(dependencyToLocalJar(true, p)); if (Files.isRegularFile(f)) return singletonList(f); f = appCache.resolve(dependencyToLocalJar(false, p)); if (Files.isRegularFile(f)) return singletonList(f); throw new IllegalArgumentException("Dependency manager not found, and could not locate artifact " + p + " in capsule"); } else if (isGlob(p)) return listDir(appCache, p, false); else return singletonList(toAbsolutePath(appCache, p)); } /** * Returns a list which is a concatenation of all lists returned by calling * {@link #getPath(String) getPath(String)} on each of the file descriptors in the given list. */ private List<Path> getPath(List<String> ps) { if (ps == null) return null; final List<Path> res = new ArrayList<Path>(ps.size()); for (String p : ps) res.addAll(getPath(p)); return res; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="JAR Extraction"> /////////// JAR Extraction /////////////////////////////////// private static void extractJar(JarInputStream jar, Path targetDir) throws IOException { for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) { if (entry.isDirectory() || !shouldExtractFile(entry.getName())) continue; writeFile(targetDir, entry.getName(), jar); } } private static boolean shouldExtractFile(String fileName) { if (fileName.equals(Capsule.class.getName().replace('.', '/') + ".class") || (fileName.startsWith(Capsule.class.getName().replace('.', '/') + "$") && fileName.endsWith(".class"))) return false; if (fileName.endsWith(".class")) return false; if (fileName.startsWith("capsule/")) return false; if (fileName.startsWith("META-INF/")) return false; return true; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Path Utils"> /////////// Path Utils /////////////////////////////////// private Path path(String p, String... more) { return cacheDir.getFileSystem().getPath(p, more); } private List<Path> toPath(List<String> ps) { if (ps == null) return null; final List<Path> aps = new ArrayList<Path>(ps.size()); for (String p : ps) aps.add(path(p)); return aps; } private static List<Path> toAbsolutePath(Path root, List<String> ps) { if (ps == null) return null; final List<Path> aps = new ArrayList<Path>(ps.size()); for (String p : ps) aps.add(toAbsolutePath(root, p)); return aps; } private static Path toAbsolutePath(Path root, String p) { return sanitize(root, p).toAbsolutePath(); } private static Path sanitize(Path dir, String p) { final Path path = dir.resolve(p).normalize().toAbsolutePath(); if (!path.startsWith(dir)) throw new IllegalArgumentException("Path " + p + " is not local"); return path; } private static String expandCommandLinePath(String str) { if (str == null) return null; // if (isWindows()) // return str; // else return str.startsWith("~/") ? str.replace("~", System.getProperty(PROP_USER_HOME)) : str; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="OS"> /** * Tests whether the current OS is Windows. */ protected static final boolean isWindows() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("windows"); } /** * Tests whether the current OS is MacOS. */ protected static final boolean isMac() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("mac"); } /** * Tests whether the current OS is UNIX/Linux. */ protected static final boolean isUnix() { return System.getProperty(PROP_OS_NAME).toLowerCase().contains("nux") || System.getProperty(PROP_OS_NAME).toLowerCase().contains("solaris") || System.getProperty(PROP_OS_NAME).toLowerCase().contains("aix"); } private String getNativeLibExtension() { if (isWindows()) return "dll"; if (isMac()) return "dylib"; if (isUnix()) return "so"; throw new RuntimeException("Unsupported operating system: " + System.getProperty(PROP_OS_NAME)); } private static long getMaxCommandLineLength() { if (isWindows()) return WINDOWS_MAX_CMD; return Long.MAX_VALUE; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="JAR Utils"> /////////// JAR Utils /////////////////////////////////// private static JarInputStream openJarInputStream(Path jar) throws IOException { return new JarInputStream(skipToZipStart(Files.newInputStream(jar))); } private static String getMainClass(Path jar) throws IOException { return getMainClass(getManifest(jar)); } private static String getMainClass(Manifest manifest) { if (manifest == null) return null; return manifest.getMainAttributes().getValue(ATTR_MAIN_CLASS); } private static Manifest getManifest(Path jar) throws IOException { try (JarInputStream jis = openJarInputStream(jar)) { return jis.getManifest(); } } private static final int[] ZIP_HEADER = new int[]{'\n', 'P', 'K', 0x03, 0x04}; private static InputStream skipToZipStart(InputStream is) throws IOException { if (!is.markSupported()) is = new BufferedInputStream(is); int state = 1; for (;;) { if (state == 1) is.mark(ZIP_HEADER.length); final int b = is.read(); if (b < 0) throw new IllegalArgumentException("Not a JAR/ZIP file"); if (b == ZIP_HEADER[state]) { state++; if (state == ZIP_HEADER.length) break; } else { state = 0; if (b == ZIP_HEADER[state]) state++; } } is.reset(); return is; } /** * @deprecated marked deprecated to exclude from javadoc. Visible for testing */ static Path createPathingJar(Path dir, List<Path> cp) { try { dir = dir.toAbsolutePath(); final List<Path> paths = new ArrayList<>(cp.size()); for (Path p : cp) // In order to use the Class-Path attribute, we must either relativize the paths, or specifiy them as file URLs paths.add(dir.relativize(p)); final Path pathingJar = Files.createTempFile(dir, "capsule_pathing_jar", ".jar"); final Manifest man = new Manifest(); man.getMainAttributes().putValue(ATTR_MANIFEST_VERSION, "1.0"); man.getMainAttributes().putValue(ATTR_CLASS_PATH, join(paths, " ")); new JarOutputStream(Files.newOutputStream(pathingJar), man).close(); return pathingJar; } catch (IOException e) { throw new RuntimeException("Pathing JAR creation failed", e); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="File Utils"> /////////// File Utils /////////////////////////////////// private static void writeFile(Path targetDir, String fileName, InputStream is) throws IOException { fileName = toNativePath(fileName); final String dir = getDirectory(fileName); if (dir != null) Files.createDirectories(targetDir.resolve(dir)); final Path targetFile = targetDir.resolve(fileName); Files.copy(is, targetFile); } private static String toNativePath(String filename) { final char ps = (!filename.contains("/") && filename.contains("\\")) ? '\\' : '/'; return ps != FILE_SEPARATOR_CHAR ? filename.replace(ps, FILE_SEPARATOR_CHAR) : filename; } private static String getDirectory(String filename) { final int index = filename.lastIndexOf(FILE_SEPARATOR_CHAR); if (index < 0) return null; return filename.substring(0, index); } // visible for testing static void delete(Path file) throws IOException { if (Files.isDirectory(file)) { try (DirectoryStream<Path> ds = Files.newDirectoryStream(file)) { for (Path f : ds) delete(f); } } Files.delete(file); } private static void ensureExecutable(Path file) { if (!Files.isExecutable(file)) { try { Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file); if (!perms.contains(PosixFilePermission.OWNER_EXECUTE)) { Set<PosixFilePermission> newPerms = EnumSet.copyOf(perms); newPerms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, newPerms); } } catch (UnsupportedOperationException e) { } catch (IOException e) { throw new RuntimeException(e); } } } /** * Returns the contents of a directory. <br> * Passing {@code null} as the glob pattern is the same as passing {@code "*"} * * @param dir the directory * @param glob the glob pattern to use to filter the entries, or {@code null} if all entries are to be returned * @param regular whether only regular files should be returned */ protected static final List<Path> listDir(Path dir, String glob, boolean regular) { return listDir(dir, glob, false, regular, false, new ArrayList<Path>()); } /** * Finds the first file matching the glob pattern in the given directory (or subdirectories, according to the glob). * * @param dir the directory * @param glob the glob pattern to use to filter the entries * @param regular whether only regular files should be returned * @return the path to the matching file or {@code null} if no matching file is found. */ protected static final Path findFile(Path dir, String glob, boolean regular) { final List<Path> list = listDir(dir, glob, false, regular, true, new ArrayList<Path>()); return !list.isEmpty() ? list.get(0) : null; } private static boolean isGlob(String s) { return s.contains("*") || s.contains("?") || s.contains("{") || s.contains("["); } private static List<Path> listDir(Path dir, String glob, boolean recursive, boolean regularFile, boolean firstMatch, List<Path> res) { return listDir(dir, splitGlob(glob), recursive, regularFile, firstMatch, res); } private static List<String> splitGlob(String glob) { // splits glob pattern by directory return glob != null ? Arrays.asList(glob.split(FILE_SEPARATOR_CHAR == '\\' ? "\\\\" : FILE_SEPARATOR)) : null; } @SuppressWarnings("null") private static List<Path> listDir(Path dir, List<String> globs, boolean recursive, boolean regularFile, boolean firstMatch, List<Path> res) { PathMatcher matcher = null; if (globs != null) { while (!globs.isEmpty() && "**".equals(globs.get(0))) { recursive = true; globs = globs.subList(1, globs.size()); } if (!globs.isEmpty()) matcher = dir.getFileSystem().getPathMatcher("glob:" + globs.get(0)); } final List<Path> ms = new ArrayList<>(); final List<Path> mds = matcher != null ? new ArrayList<Path>() : null; final List<Path> rds = recursive ? new ArrayList<Path>() : null; try (DirectoryStream<Path> fs = Files.newDirectoryStream(dir)) { for (Path f : fs) { if (recursive && Files.isDirectory(f)) rds.add(f); if (matcher == null) { if (!regularFile || Files.isRegularFile(f)) ms.add(f); } else { if (matcher.matches(f.getFileName())) { if (globs.size() == 1 && (!regularFile || Files.isRegularFile(f))) ms.add(f); else if (Files.isDirectory(f)) mds.add(f); } } if (firstMatch && !ms.isEmpty()) break; } } catch (IOException e) { throw new RuntimeException(e); } sort(ms); // sort to give same reults on all platforms (hopefully) res.addAll(ms); recurse: for (List<Path> ds : Arrays.asList(mds, rds)) { if (ds == null) continue; sort(ds); final List<String> gls = (ds == mds ? globs.subList(1, globs.size()) : globs); for (Path d : ds) { listDir(d, gls, recursive, regularFile, firstMatch, res); if (firstMatch && !res.isEmpty()) break recurse; } } return res; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="JRE Installations"> /////////// JRE Installations /////////////////////////////////// private static Map<String, Path> getJDKs(Map<String, Path> homes) { Map<String, Path> jdks = new HashMap<>(); for (Map.Entry<String, Path> entry : homes.entrySet()) { Path home = entry.getValue(); if (isJDK(home)) jdks.put(entry.getKey(), entry.getValue()); } return jdks.isEmpty() ? null : jdks; } private static boolean isJDK(Path javaHome) { final String name = javaHome.toString().toLowerCase(); return name.contains("jdk") && !name.contains("jre"); } /** * Returns all found Java installations. * * @return a map from installations' versions to their respective paths */ protected static Map<String, Path> getJavaHomes() { if (JAVA_HOMES == null) { Path dir = Paths.get(System.getProperty(PROP_JAVA_HOME)).getParent(); Map<String, Path> homes = null; while (dir != null) { homes = getJavaHomes(dir); if (homes != null) { if (isWindows()) homes = windowsJavaHomesHeuristics(dir, homes); break; } dir = dir.getParent(); } JAVA_HOMES = homes; } return JAVA_HOMES; } private static Map<String, Path> windowsJavaHomesHeuristics(Path dir, Map<String, Path> homes) { Path dir2 = null; if (dir.startsWith(WINDOWS_PROGRAM_FILES_1)) dir2 = WINDOWS_PROGRAM_FILES_2.resolve(WINDOWS_PROGRAM_FILES_1.relativize(dir)); else if (dir.startsWith(WINDOWS_PROGRAM_FILES_2)) dir2 = WINDOWS_PROGRAM_FILES_1.resolve(WINDOWS_PROGRAM_FILES_2.relativize(dir)); if (dir2 != null) { Map<String, Path> allHomes = new HashMap<>(homes); allHomes.putAll(getJavaHomes(dir2)); return allHomes; } else return homes; } private static Map<String, Path> getJavaHomes(Path dir) { if (!Files.isDirectory(dir)) return null; final Map<String, Path> dirs = new HashMap<String, Path>(); for (Path f : listDir(dir, null, false)) { if (Files.isDirectory(f)) { String dirName = f.getFileName().toString(); String ver = isJavaDir(dirName); if (ver != null) { Path home = searchJavaHomeInDir(f); if (home != null) { home = home.toAbsolutePath(); if (parseJavaVersion(ver)[3] == 0) ver = getActualJavaVersion(home); dirs.put(ver, home); } } } } return !dirs.isEmpty() ? dirs : null; } // visible for testing static String isJavaDir(String fileName) { fileName = fileName.toLowerCase(); if (fileName.startsWith("jdk") || fileName.startsWith("jre") || fileName.endsWith(".jdk") || fileName.endsWith(".jre")) { if (fileName.startsWith("jdk") || fileName.startsWith("jre")) fileName = fileName.substring(3); if (fileName.endsWith(".jdk") || fileName.endsWith(".jre")) fileName = fileName.substring(0, fileName.length() - 4); return shortJavaVersion(fileName); } else return null; } private static Path searchJavaHomeInDir(Path dir) { if (!Files.isDirectory(dir)) return null; for (Path f : listDir(dir, null, false)) { if (isJavaHome(f)) return f; Path home = searchJavaHomeInDir(f); if (home != null) return home; } return null; } private static boolean isJavaHome(Path dir) { if (Files.isDirectory(dir)) return findFile(dir, "bin" + FILE_SEPARATOR + "java{.exe,}", true) != null; return false; } private static Path getJavaExecutable0(Path javaHome) { final String exec = (isWindows() && System.console() == null) ? "javaw" : "java"; return javaHome.resolve("bin").resolve(exec + (isWindows() ? ".exe" : "")); } private static final Pattern PAT_JAVA_VERSION_LINE = Pattern.compile(".*?\"(.+?)\""); private static String getActualJavaVersion(Path javaHome) { try { final String versionLine = exec(1, getJavaExecutable0(javaHome).toString(), "-version").get(0); final Matcher m = PAT_JAVA_VERSION_LINE.matcher(versionLine); if (!m.matches()) throw new IllegalArgumentException("Could not parse version line: " + versionLine); final String version = m.group(1); return version; } catch (Exception e) { throw new RuntimeException(e); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Version Strings"> /////////// Version Strings /////////////////////////////////// // visible for testing static String shortJavaVersion(String v) { try { final String[] vs = v.split(SEPARATOR_DOT); if (vs.length == 1) { if (Integer.parseInt(vs[0]) < 5) throw new RuntimeException("Unrecognized major Java version: " + v); v = "1." + v + ".0"; } if (vs.length == 2) v += ".0"; return v; } catch (NumberFormatException e) { return null; } } /** * Compares two dotted software versions, regarding only the first several version components. * * @param a first version * @param b second version * @param n the number of (most significant) components to consider * @return {@code 0} if {@code a == b}; {@code > 0} if {@code a > b}; {@code < 0} if {@code a < b}; */ protected static final int compareVersions(String a, String b, int n) { return compareVersions(parseJavaVersion(a), parseJavaVersion(b), n); } /** * Compares two dotted software versions. * * @param a first version * @param b second version * @return {@code 0} if {@code a == b}; {@code > 0} if {@code a > b}; {@code < 0} if {@code a < b}; */ protected static final int compareVersions(String a, String b) { return compareVersions(parseJavaVersion(a), parseJavaVersion(b)); } private static int compareVersions(int[] a, int[] b) { return compareVersions(a, b, 5); } private static int compareVersions(int[] a, int[] b, int n) { for (int i = 0; i < n; i++) { if (a[i] != b[i]) return a[i] - b[i]; } return 0; } private static boolean equals(int[] a, int[] b, int n) { for (int i = 0; i < n; i++) { if (a[i] != b[i]) return false; } return true; } private static final Pattern PAT_JAVA_VERSION = Pattern.compile("(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)(_(?<update>\\d+))?(-(?<pre>[^-]+))?(-(?<build>.+))?"); // visible for testing static int[] parseJavaVersion(String v) { final Matcher m = PAT_JAVA_VERSION.matcher(v); if (!m.matches()) throw new IllegalArgumentException("Could not parse version: " + v); final int[] ver = new int[5]; ver[0] = toInt(m.group("major")); ver[1] = toInt(m.group("minor")); ver[2] = toInt(m.group("patch")); ver[3] = toInt(m.group("update")); final String pre = m.group("pre"); if (pre != null) { if (pre.startsWith("rc")) ver[4] = -1; else if (pre.startsWith("beta")) ver[4] = -2; else if (pre.startsWith("ea")) ver[4] = -3; } return ver; } // visible for testing static String toJavaVersionString(int[] version) { final StringBuilder sb = new StringBuilder(); sb.append(version[0]).append('.'); sb.append(version[1]).append('.'); sb.append(version[2]); if (version.length > 3 && version[3] > 0) sb.append('_').append(version[3]); if (version.length > 4 && version[4] != 0) { final String pre; switch (version[4]) { case -1: pre = "rc"; break; case -2: pre = "beta"; break; case -3: pre = "ea"; break; default: pre = "?"; } sb.append('-').append(pre); } return sb.toString(); } private static int toInt(String s) { return s != null ? Integer.parseInt(s) : 0; } private static int[] toInt(String[] ss) { int[] res = new int[ss.length]; for (int i = 0; i < ss.length; i++) res[i] = ss[i] != null ? Integer.parseInt(ss[i]) : 0; return res; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="String Expansion"> /////////// String Expansion /////////////////////////////////// private List<String> expand(List<String> strs) { if (strs == null) return null; final List<String> res = new ArrayList<String>(strs.size()); for (String s : strs) res.add(expand(s)); return res; } /** * Expands occurrences of {@code $VARNAME} in attribute values. * * @param str the original string * @return the expanded string */ protected String expand(String str) { if ("$0".equals(str)) return jarFile.toString(); if (appCache != null) str = str.replaceAll("\\$" + VAR_CAPSULE_DIR, appCache.toAbsolutePath().toString()); else if (str.contains("$" + VAR_CAPSULE_DIR)) throw new IllegalStateException("The $" + VAR_CAPSULE_DIR + " variable cannot be expanded when the " + ATTR_EXTRACT + " attribute is set to false"); str = expandCommandLinePath(str); assert appId != null; str = str.replaceAll("\\$" + VAR_CAPSULE_APP, appId); str = str.replaceAll("\\$" + VAR_CAPSULE_JAR, jarFile.toString()); final String jhome = toString(getJavaHome()); if (jhome != null) str = str.replaceAll("\\$" + VAR_JAVA_HOME, jhome); str = str.replace('/', FILE_SEPARATOR_CHAR); return str; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="String Utils"> /////////// String Utils /////////////////////////////////// private static String toString(Object obj) { return obj != null ? obj.toString() : null; } static List<String> split(String str, String separator) { if (str == null) return null; String[] es = str.split(separator); final List<String> list = new ArrayList<>(es.length); for (String e : es) { e = e.trim(); if (!e.isEmpty()) list.add(e); } return list; } static Map<String, String> split(String map, char kvSeparator, String separator, String defaultValue) { if (map == null) return null; Map<String, String> m = new HashMap<>(); for (String entry : Capsule.split(map, separator)) { final String key = getBefore(entry, kvSeparator); String value = getAfter(entry, kvSeparator); if (value == null) { if (defaultValue != null) value = defaultValue; else throw new IllegalArgumentException("Element " + entry + " in \"" + map + "\" is not a key-value entry separated with " + kvSeparator + " and no default value provided"); } m.put(key.trim(), value.trim()); } return m; } final static String join(Collection<?> coll, String separator) { if (coll == null) return null; if (coll.isEmpty()) return ""; StringBuilder sb = new StringBuilder(); for (Object e : coll) { if (e != null) sb.append(e).append(separator); } sb.delete(sb.length() - separator.length(), sb.length()); return sb.toString(); } final static String join(Map<String, String> map, char kvSeparator, String separator) { if (map == null) return null; StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) sb.append(entry.getKey()).append(kvSeparator).append(entry.getValue()).append(separator); sb.delete(sb.length() - separator.length(), sb.length()); return sb.toString(); } private static String getBefore(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return s; return s.substring(0, i); } private static String getAfter(String s, char separator) { final int i = s.indexOf(separator); if (i < 0) return null; return s.substring(i + 1); } private static long getStringsLength(Collection<?> coll) { if (coll == null) return 0; long len = 0; for (Object o : coll) len += o.toString().length(); return len; } private static String emptyToNull(String s) { if (s == null) return null; s = s.trim(); return s.isEmpty() ? null : s; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Collection Utils"> /////////// Collection Utils /////////////////////////////////// private static <T> List<T> nullToEmpty(List<T> list) { if (list == null) return emptyList(); return list; } private static <K, V> Map<K, V> nullToEmpty(Map<K, V> map) { if (map == null) return emptyMap(); return map; } private static <T> T first(List<T> c) { if (c == null || c.isEmpty()) throw new IllegalArgumentException("Not found"); return c.get(0); } private static <T> T firstOrNull(List<T> c) { if (c == null || c.isEmpty()) return null; return c.get(0); } private static <C extends Collection<T>, T> C addAllIfNotContained(C c, Collection<T> c1) { for (T e : c1) { if (!c.contains(e)) c.add(e); } return c; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Reflection Utils"> /////////// Reflection Utils /////////////////////////////////// private static Method getMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws NoSuchMethodException { try { final Method m = clazz.getDeclaredMethod(name, parameterTypes); m.setAccessible(true); return m; } catch (NoSuchMethodException e) { if (clazz.getSuperclass() == null) throw new NoSuchMethodException(name + "(" + Arrays.toString(parameterTypes) + ")"); return getMethod(clazz.getSuperclass(), name, parameterTypes); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Misc Utils"> /////////// Misc Utils /////////////////////////////////// private static boolean propertyDefined(String... props) { for (String prop : props) { if (System.getProperty(prop) != null) return true; } return false; } private static String propertyOrEnv(String propName, String envVar) { String val = systemProperty(propName); if (val == null) val = emptyToNull(getenv(envVar)); return val; } /** * Same as {@link System#getProperty(java.lang.String) System.getProperty(propName)} but sets context for error reporting. */ protected static final String systemProperty(String propName) { final String val = System.getProperty(propName); setContext("system property", propName, val); return val; } /** * Same as {@link System#getenv(java.lang.String) System.getenv(envName)} but sets context for error reporting. */ private static String getenv(String envName) { final String val = System.getenv(envName); setContext("environment variable", envName, val); return val; } private static boolean systemPropertyEmptyOrTrue(String property) { final String value = System.getProperty(property); if (value == null) return false; return value.isEmpty() || Boolean.parseBoolean(value); } /** * Executes a command and returns its output as a list of lines. * The method will wait for the child process to terminate, and throw an exception if the command returns an exit value {@code != 0}. * <br> * Same as calling {@code exec(-1, cmd}}. * * @param cmd the command * @return the lines output by the command */ protected static List<String> exec(String... cmd) throws IOException { return exec(-1, cmd); } /** * Executes a command and returns its output as a list of lines. * If the number of lines read is less than {@code numLines}, or if {@code numLines < 0}, then the method will wait for the child process * to terminate, and throw an exception if the command returns an exit value {@code != 0}. * * @param numLines the maximum number of lines to read, or {@code -1} for an unbounded number * @param cmd the command * @return the lines output by the command */ protected static List<String> exec(int numLines, String... cmd) throws IOException { return exec(numLines, new ProcessBuilder(Arrays.asList(cmd))); } /** * Executes a command and returns its output as a list of lines. * The method will wait for the child process to terminate, and throw an exception if the command returns an exit value {@code != 0}. * <br> * Same as calling {@code exec(-1, pb}}. * * @param pb the {@link ProcessBuilder} that will be used to launch the command * @return the lines output by the command */ protected static List<String> exec(ProcessBuilder pb) throws IOException { return exec(-1, pb); } /** * Executes a command and returns its output as a list of lines. * If the number of lines read is less than {@code numLines}, or if {@code numLines < 0}, then the method will wait for the child process * to terminate, and throw an exception if the command returns an exit value {@code != 0}. * * @param numLines the maximum number of lines to read, or {@code -1} for an unbounded number * @param pb the {@link ProcessBuilder} that will be used to launch the command * @return the lines output by the command */ protected static List<String> exec(int numLines, ProcessBuilder pb) throws IOException { final List<String> lines = new ArrayList<>(); final Process p = pb.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream(), Charset.defaultCharset()))) { for (int i = 0; numLines < 0 || i < numLines; i++) { final String line = reader.readLine(); if (line == null) break; lines.add(line); } } try { if (numLines < 0 || lines.size() < numLines) { final int exitValue = p.waitFor(); if (exitValue != 0) throw new RuntimeException("Command '" + join(pb.command(), " ") + "' has returned " + exitValue); } return lines; } catch (InterruptedException e) { throw new RuntimeException(e); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Logging"> /////////// Logging /////////////////////////////////// /** * Chooses and returns the capsules log level. */ protected int chooseLogLevel() { String level = System.getProperty(PROP_LOG_LEVEL); if (level == null && manifest != null) level = getAttribute(ATTR_LOG_LEVEL); int lvl = getLogLevel(level); if (lvl < 0) throw new IllegalArgumentException("Unrecognized log level: " + level); return lvl; } private static int getLogLevel(String level) { if (level == null || level.isEmpty()) level = "QUIET"; switch (level.toUpperCase()) { case "NONE": return LOG_NONE; case "QUIET": return LOG_QUIET; case "VERBOSE": return LOG_VERBOSE; case "DEBUG": case "ALL": return LOG_DEBUG; default: return -1; } } /** * Tests if the given log level is currently being logged */ protected final boolean isLogging(int level) { return level <= logLevel; } /** * Prints a message to stderr if the given log-level is being logged. */ protected final void log(int level, String str) { if (isLogging(level)) System.err.println(LOG_PREFIX + str); } private void println(String str) { log(LOG_QUIET, str); } private static boolean hasContext() { return contextType_ != null; } private static void clearContext() { setContext(null, null, null); } private static void setContext(String type, String key, String value) { contextType_ = type; contextKey_ = key; contextValue_ = value; } private static String reportContext() { return contextType_ + " " + contextKey_ + ": " + contextValue_; } private long clock() { return isLogging(PROFILE) ? System.nanoTime() : 0; } private void time(String op, long start) { if (isLogging(PROFILE)) log(PROFILE, "PROFILE " + op + " " + ((System.nanoTime() - start) / 1_000_000) + "ms"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Pipe Streams (workaround for inheritIO bug)"> /////////// Pipe Streams (workaround for inheritIO bug) /////////////////////////////////// private static boolean isInheritIoBug() { return isWindows() && compareVersions(System.getProperty(PROP_JAVA_VERSION), "1.8.0") < 0; } private void pipeIoStreams() { new Thread(this, "pipe-out").start(); new Thread(this, "pipe-err").start(); new Thread(this, "pipe-in").start(); } private boolean pipeIoStream() { switch (Thread.currentThread().getName()) { case "pipe-out": pipe(child.getInputStream(), System.out); return true; case "pipe-err": pipe(child.getErrorStream(), System.err); return true; case "pipe-in": pipe(System.in, child.getOutputStream()); return true; default: return false; } } private void pipe(InputStream in, OutputStream out) { try (OutputStream out1 = out) { final byte[] buf = new byte[1024]; int read; while (-1 != (read = in.read(buf))) { out.write(buf, 0, read); out.flush(); } } catch (Throwable e) { if (isLogging(LOG_VERBOSE)) e.printStackTrace(System.err); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="POSIX"> /////////// POSIX /////////////////////////////////// private static int getPid(Process p) { try { java.lang.reflect.Field pidField = p.getClass().getDeclaredField("pid"); pidField.setAccessible(true); return pidField.getInt(p); } catch (Exception e) { return -1; } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Object Methods"> /////////// Object Methods /////////////////////////////////// /** * Throws a {@link CloneNotSupportedException} */ @SuppressWarnings("CloneDoesntCallSuperClone") @Override protected final Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } @Override public final int hashCode() { int hash = 3; hash = 47 * hash + Objects.hashCode(this.jarFile); hash = 47 * hash + Objects.hashCode(this.mode); return hash; } @Override public final boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Capsule other = (Capsule) obj; if (!Objects.equals(this.jarFile, other.jarFile)) return false; if (!Objects.equals(this.mode, other.mode)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()).append('['); sb.append(jarFile); if (appId != null) { sb.append(", ").append(appId); sb.append(", ").append(getAttribute(ATTR_APP_CLASS) != null ? getAttribute(ATTR_APP_CLASS) : getAttribute(ATTR_APP_ARTIFACT)); } else sb.append(", ").append("empty"); if (mode != null) sb.append(", ").append("mode: ").append(mode); sb.append(']'); return sb.toString(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Capsule Loading and Launching"> /////////// Capsule Loading and Launching /////////////////////////////////// // visible for testing static Capsule newCapsule(Path jarFile, Path cacheDir) { try { final String mainClassName = getMainClass(jarFile); if (mainClassName != null) { final Class<?> clazz = Capsule.class.getClassLoader().loadClass(mainClassName); if (isCapsuleClass(clazz)) { final Constructor<?> ctor = clazz.getDeclaredConstructor(Path.class, Path.class); ctor.setAccessible(true); return (Capsule) ctor.newInstance(jarFile, cacheDir); } } throw new RuntimeException(jarFile + " does not appear to be a valid capsule."); } catch (IOException | ClassNotFoundException e) { throw new RuntimeException(jarFile + " does not appear to be a valid capsule.", e); } catch (InvocationTargetException e) { throw rethrow(e.getTargetException()); } catch (ReflectiveOperationException e) { throw new RuntimeException("Could not instantiate capsule.", e); } } private static RuntimeException rethrow(Throwable t) { while (t instanceof InvocationTargetException) t = ((InvocationTargetException) t).getTargetException(); if (t instanceof RuntimeException) throw (RuntimeException) t; if (t instanceof Error) throw (Error) t; throw new RuntimeException(t); } private static boolean isCapsuleClass(Class<?> clazz) { if (clazz == null) return false; return Capsule.class.getName().equals(clazz.getName()) || isCapsuleClass(clazz.getSuperclass()); } //</editor-fold> }
package org.lantern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.cometd.bayeux.Channel; import org.cometd.bayeux.Message; import org.cometd.bayeux.client.ClientSession; import org.cometd.bayeux.client.ClientSessionChannel; import org.cometd.bayeux.client.ClientSessionChannel.MessageListener; import org.cometd.client.BayeuxClient; import org.cometd.client.transport.ClientTransport; import org.cometd.client.transport.LongPollingTransport; import org.eclipse.jetty.client.HttpClient; import org.junit.Test; import org.lantern.event.Events; import org.lantern.event.UpdateEvent; import org.lantern.http.JettyLauncher; import org.lantern.state.StaticSettings; public class CometDTest { @Test public void test() throws Exception { final int port = LanternUtils.randomPort(); StaticSettings.setApiPort(port); //RuntimeSettings.setApiPort(port); //LanternHub.settings().setApiPort(LanternUtils.randomPort()); //final int port = LanternHub.settings().getApiPort(); startJetty(TestUtils.getJettyLauncher(), port); final HttpClient httpClient = new HttpClient(); // Here set up Jetty's HttpClient, for example: // httpClient.setMaxConnectionsPerAddress(2); httpClient.start(); // Prepare the transport final Map<String, Object> options = new HashMap<String, Object>(); final ClientTransport transport = LongPollingTransport.create(options, httpClient); final ClientSession session = new BayeuxClient("http://127.0.0.1:"+port+"/cometd", transport); final AtomicBoolean handshake = new AtomicBoolean(false); session.getChannel(Channel.META_HANDSHAKE).addListener( new ClientSessionChannel.MessageListener() { @Override public void onMessage(final ClientSessionChannel channel, final Message message) { if (message.isSuccessful()) { // Here handshake is successful handshake.set(true); } } }); session.handshake(); waitForBoolean(handshake); assertTrue("Could not handshake?", handshake.get()); final AtomicBoolean hasMessage = new AtomicBoolean(false); final AtomicReference<String> messagePath = new AtomicReference<String>("none"); final MessageListener ml = new MessageListener() { @Override public void onMessage(final ClientSessionChannel channel, final Message message) { Object[] data = (Object[]) message.getData(); @SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>) data[0]; //data.set(map); final String path = (String) map.get("path"); messagePath.set(path); hasMessage.set(true); } }; //final AtomicBoolean sync = new AtomicBoolean(false); //final AtomicReference<String> transferPathKey = new AtomicReference<String>(""); subscribe (session, ml); waitForBoolean(hasMessage); assertEquals("", messagePath.get()); hasMessage.set(false); messagePath.set("none"); final Map<String,Object> updateJson = new LinkedHashMap<String,Object>(); updateJson.put(LanternConstants.UPDATE_VERSION_KEY, 0.20); updateJson.put(LanternConstants.UPDATE_RELEASED_KEY, "2012-10-31T11:15:00Z"); updateJson.put(LanternConstants.UPDATE_URL_KEY, "http://s3.amazonaws.com/lantern/latest.dmg"); updateJson.put(LanternConstants.UPDATE_MESSAGE_KEY, "test update"); Events.asyncEventBus().post(new UpdateEvent(updateJson)); waitForBoolean(hasMessage); assertEquals("/version.latest", messagePath.get()); hasMessage.set(false); messagePath.set("none"); } private AtomicReference<Map<String, Object>> subscribe( final ClientSession session, final MessageListener ml) { final AtomicReference<Map<String, Object>> data = new AtomicReference<Map<String,Object>>(); session.getChannel("/sync").subscribe(ml); return data; } private void waitForBoolean(final AtomicBoolean bool) throws InterruptedException { int tries = 0; while (tries < 200) { if (bool.get()) { break; } tries++; Thread.sleep(100); } assertTrue("Expected variable to be true", bool.get()); } private void startJetty(final JettyLauncher jl, final int port) throws Exception { // The order of getting things from the injector matters unfortunately, // so we have to do the below. //injector.getInstance(DefaultXmppHandler.class); //final JettyLauncher jl = injector.getInstance(JettyLauncher.class); final Runnable runner = new Runnable() { @Override public void run() { jl.start(); } }; final Thread jetty = new Thread(runner, "Jetty-Test-Thread"); jetty.setDaemon(true); jetty.start(); //Thread.sleep(5000); waitForServer(port); } private void waitForServer(final int port) throws Exception { int attempts = 0; boolean connected = false; while (attempts < 200 && connected == false) { final Socket sock = new Socket(); try { sock.connect(new InetSocketAddress("127.0.0.1", port), 1000); connected = true; System.err.println("Got connected!!"); } catch (final IOException e) { //e.printStackTrace(); } Thread.sleep(100); attempts++; } } }
package water.fvec; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Assert; import org.junit.Test; import water.*; import water.api.ImportFiles2; import water.deploy.Node; import water.deploy.NodeVM; import water.util.Log; public class ParserTest2 extends TestUtil { private double[] d(double... ds) { return ds; } private final double NaN = Double.NaN; private final char[] SEPARATORS = new char[] {',', ' '}; public static boolean compareDoubles(double a, double b, double threshold){ if( a==b ) return true; if( ( Double.isNaN(a) && !Double.isNaN(b)) || (!Double.isNaN(a) && Double.isNaN(b)) ) return false; if( Double.isInfinite(a) || Double.isInfinite(b) ) return false; return Math.abs(a-b)/Math.max(Math.abs(a),Math.abs(b)) < threshold; } public static void testParsed(Key inputKey, double[][] expected) { testParsed(ParseDataset2.parse(Key.make("parsed"), new Key[]{inputKey}),expected, expected.length); } public static void testParsed(Frame fr, double[][] expected, int len) { try { Assert.assertEquals(len,fr.numRows()); Assert.assertEquals(expected[0].length,fr.numCols()); for (int i = 0; i < expected.length; ++i) for (int j = 0; j < fr.numCols(); ++j) { double parsedVal = fr.vecs()[j].at(i); Assert.assertTrue((Double.isNaN(parsedVal) == Double.isNaN(expected[i][j]))); Assert.assertTrue("Frame "+fr._key+", row="+i+", col="+j+", expect="+expected[i][j]+", found="+parsedVal, Double.isNaN(expected[i][j]) || compareDoubles(expected[i][j],parsedVal,1e-5)); } } finally { fr.delete(); } } @Test public void testBasic() { String[] data = new String[] { "1|2|3\n1|2|3\n", "4|5|6\n", "4|5.2|\n", "asdf|qwer|1\n", "1.3\n", "1.1|2.7|3.4", }; double[][] exp = new double[][] { d(1.0, 2.0, 3.0), d(1.0, 2.0, 3.0), d(4.0, 5.0, 6.0), d(4.0, 5.2, NaN), d(NaN, NaN, 1.0), d(1.3, NaN, NaN), d(1.1, 2.7, 3.4), }; for (char separator : SEPARATORS) { String[] dataset = getDataForSeparator(separator, data); StringBuilder sb = new StringBuilder(); for( String s : dataset ) sb.append(s).append("\n"); Key k = FVecTest.makeByteVec(Key.make().toString(),sb.toString()); testParsed(k,exp); sb = new StringBuilder(); for( String s : dataset ) sb.append(s).append("\r\n"); k = FVecTest.makeByteVec(k.toString(),sb.toString()); testParsed(k,exp); } } // test correctness of sparse chunks // added after failing to encode properly following data as // 0s were not considered when computing compression strategy and then // lemin was 6108 and there was Short overflow when encoding zeros. // So, the first column was compressed into C2SChunk with 0s causing short overflow, @Test public void testSparse2(){ String data = "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "35351, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "6108, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "35351, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "6334, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n" + "0, 0,0,0,0,0\n"; double[][] exp = new double[][] { d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(35351,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(6108,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(35351,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), d(6334,0,0,0,0,0), d(0,0,0,0,0,0), d(0,0,0,0,0,0), }; Key k = FVecTest.makeByteVec(Key.make().toString(),data); testParsed(k,exp); } @Test public void testChunkBoundaries() { String[] data = new String[] { "1|2|3\n1|2|3\n", "1|2|3\n1|2", "|3\n1|1|1\n", "2|2|2\n2|3|", "4\n3|3|3\n", "3|4|5\n5", ".5|2|3\n5.","5|2|3\n55e-","1|2.0|3.0\n55e","-1|2.0|3.0\n55","e-1|2.0|3.0\n" }; double[][] exp = new double[][] { d(1.0, 2.0, 3.0), d(1.0, 2.0, 3.0), d(1.0, 2.0, 3.0), d(1.0, 2.0, 3.0), d(1.0, 1.0, 1.0), d(2.0, 2.0, 2.0), d(2.0, 3.0, 4.0), d(3.0, 3.0, 3.0), d(3.0, 4.0, 5.0), d(5.5, 2.0, 3.0), d(5.5, 2.0, 3.0), d(5.5, 2.0, 3.0), d(5.5, 2.0, 3.0), d(5.5, 2.0, 3.0), }; for (char separator : SEPARATORS) { String[] dataset = getDataForSeparator(separator, data); Key k = FVecTest.makeByteVec("ChunkBoundaries",dataset); testParsed(k,exp); } } @Test public void testChunkBoundariesMixedLineEndings() { String[] data = new String[] { "1|2|3\n4|5|6\n7|8|9", "\r\n10|11|12\n13|14|15", "\n16|17|18\r", "\n19|20|21\n", "22|23|24\n25|26|27\r\n", "28|29|30" }; double[][] exp = new double[][] { d(1, 2, 3), d(4, 5, 6), d(7, 8, 9), d(10, 11, 12), d(13, 14, 15), d(16, 17, 18), d(19, 20, 21), d(22, 23, 24), d(25, 26, 27), d(28, 29, 30), }; for (char separator : SEPARATORS) { String[] dataset = getDataForSeparator(separator, data); Key k = FVecTest.makeByteVec("ChunkBoundariesMixedLineEndings",dataset); testParsed(k,exp); checkLeakedKeys(); } } @Test public void testNondecimalColumns() { String data[] = { "1| 2|one\n" + "3| 4|two\n" + "5| 6|three\n" + "7| 8|one\n" + "9| 10|two\n" + "11|12|three\n" + "13|14|one\n" + "15|16|\"two\"\n" + "17|18|\" four\"\n" + "19|20| three\n", }; double[][] expDouble = new double[][] { d(1, 2, 1), // preserve order d(3, 4, 3), d(5, 6, 2), d(7, 8, 1), d(9, 10, 3), d(11,12, 2), d(13,14, 1), d(15,16, 3), d(17,18, 0), d(19,20, 2), }; for (char separator : SEPARATORS) { String[] dataset = getDataForSeparator(separator, data); Key key = FVecTest.makeByteVec("NondecimalColumns",dataset); Frame fr = ParseDataset2.parse(Key.make(),new Key[]{key}); String[] cd = fr.vecs()[2]._domain; Assert.assertEquals(" four",cd[0]); Assert.assertEquals("one",cd[1]); Assert.assertEquals("three",cd[2]); Assert.assertEquals("two",cd[3]); testParsed(fr, expDouble,expDouble.length); } checkLeakedKeys(); } @Test public void testNumberFormats(){ String [] data = {"+.6e102|+.7e102|+.8e102\n.6e102|.7e102|.8e102\n"}; double[][] expDouble = new double[][] { d(+.6e102,.7e102,.8e102), // preserve order d(+.6e102, +.7e102,+.8e102), }; for (char separator : SEPARATORS) { String[] dataset = getDataForSeparator(separator, data); Key key = FVecTest.makeByteVec("NumberFormats",dataset); testParsed(key,expDouble); } } @Test public void testMultipleNondecimalColumns() { String data[] = { "foo| 2|one\n" + "bar| 4|two\n" + "foo| 6|three\n" + "bar| 8|one\n" + "bar|ten|two\n" + "bar| 12|three\n" + "foobar|14|one\n", }; double[][] expDouble = new double[][] { d(1, 2, 0), // preserve order d(0, 4, 2), d(1, 6, 1), d(0, 8, 0), d(0, NaN, 2), d(0, 12, 1), d(2, 14, 0), }; for (char separator : SEPARATORS) { String[] dataset = getDataForSeparator(separator, data); Key key = FVecTest.makeByteVec("MultipleNondecimalColumns",dataset); Key r = Key.make(); Frame fr = ParseDataset2.parse(r,new Key[]{key}); String[] cd = fr.vecs()[2]._domain; Assert.assertEquals("one",cd[0]); Assert.assertEquals("three",cd[1]); Assert.assertEquals("two",cd[2]); cd = fr.vecs()[0]._domain; Assert.assertEquals("bar",cd[0]); Assert.assertEquals("foo",cd[1]); Assert.assertEquals("foobar",cd[2]); testParsed(fr, expDouble,expDouble.length); } } // Test if the empty column is correctly handled. // NOTE: this test makes sense only for comma separated columns @Test public void testEmptyColumnValues() { String data[] = { "1,2,3,foo\n" + "4,5,6,bar\n" + "7,,8,\n" + ",9,10\n" + "11,,,\n" + "0,0,0,z\n" + "0,0,0,z\n" + "0,0,0,z\n" + "0,0,0,z\n" + "0,0,0,z\n" }; double[][] expDouble = new double[][] { d(1, 2, 3, 1), d(4, 5, 6, 0), d(7, NaN, 8, NaN), d(NaN, 9, 10, NaN), d(11, NaN, NaN, NaN), d(0, 0, 0, 2), d(0, 0, 0, 2), d(0, 0, 0, 2), d(0, 0, 0, 2), d(0, 0, 0, 2), }; final char separator = ','; String[] dataset = getDataForSeparator(separator, data); Key key = FVecTest.makeByteVec("EmptyColumnValues",dataset); Key r = Key.make(); Frame fr = ParseDataset2.parse(r,new Key[]{key}); String[] cd = fr.vecs()[3]._domain; Assert.assertEquals("bar",cd[0]); Assert.assertEquals("foo",cd[1]); testParsed(fr, expDouble, expDouble.length); } @Test public void testBasicSpaceAsSeparator() { String[] data = new String[] { " 1|2|3", " 4 | 5 | 6", "4|5.2 ", "asdf|qwer|1", "1.1", "1.1|2.1|3.4", }; double[][] exp = new double[][] { d(1.0, 2.0, 3.0), d(4.0, 5.0, 6.0), d(4.0, 5.2, NaN), d(NaN, NaN, 1.0), d(1.1, NaN, NaN), d(1.1, 2.1, 3.4), }; for (char separator : SEPARATORS) { String[] dataset = getDataForSeparator(separator, data); StringBuilder sb = new StringBuilder(); for( String s : dataset ) sb.append(s).append("\n"); Key k = FVecTest.makeByteVec("test_"+separator,sb.toString()); testParsed(k,exp); } } String[] getDataForSeparator(char sep, String[] data) { return getDataForSeparator('|', sep, data); } String[] getDataForSeparator(char placeholder, char sep, String[] data) { String[] result = new String[data.length]; for (int i = 0; i < data.length; i++) result[i] = data[i].replace(placeholder, sep); return result; } @Test public void testMixedSeps() { double[][] exp = new double[][] { d(NaN, 1, 1), d(NaN, 2, NaN), d( 3, NaN, 3), d( 4, NaN, NaN), d(NaN, NaN, NaN), d(NaN, NaN, NaN), d(NaN, NaN, 6), }; Key fkey = NFSFileVec.make(find_test_file("smalldata/test/is_NA.csv")); testParsed(ParseDataset2.parse(Key.make(),new Key[]{fkey}),exp,25); } @Test public void testNAs() { String [] data = new String[]{ "'C1Chunk',C1SChunk, 'C2Chunk', 'C2SChunk', 'C4Chunk', 'C4FChunk', 'C8Chunk', 'C8DChunk', 'Enum'\n" + "0, 0.0, 0, 0, 0, 0 , 0, 8.878979, A \n" , "1, 0.1, 1, 0.1, 1, 1 , 1, 1.985934, B \n" , "2, 0.2, 2, 0.2, 2, 2 , 2, 3.398018, C \n" , "3, 0.3, 3, 0.3, 3, 3 , 3, 9.329589, D \n" , "4, 0.4, 4, 4, 4, 4 , 2147483649, 0.290184, A \n" , "0, 0.5, 0, 0, -100000, 1.234e2 ,-2147483650, 1e-30, B \n" , "254, 0.25, 2550, 6553.4, 100000, 2.345e-2, 0, 1e30, C \n" , " , , , , , , , , \n" , " ?, NA, ?, ?, ?, ?, ?, ?, \n" , }; //File file = find_test_file("./smalldata/test/na_test.zip"); //Key key = NFSFileVec.make(file); Key rkey = FVecTest.makeByteVec("na_test",data); Key okey = Key.make("na_test.hex"); Frame fr = ParseDataset2.parse(okey, new Key[]{rkey}); int nlines = (int)fr.numRows(); // This variable could be declared static, except that that causes an issue // with the weaver trying to load these classes before a Cloud is formed. Class [] expectedTypes = new Class[]{C1Chunk.class,C1SChunk.class,C2Chunk.class,C2SChunk.class,C4Chunk.class,C4FChunk.class,C8Chunk.class,C8DChunk.class, C1Chunk.class}; assertTrue(fr.numCols() == expectedTypes.length); // for(int i = 0; i < expectedTypes.length; ++i) // assertTrue("unpextected vector type, got: " + fr.vecs()[i].chunkForChunkIdx(0).getClass().getSimpleName() + ", expected: " + expectedTypes[i].getSimpleName(),expectedTypes[i].isInstance(fr.vecs()[i].chunkForChunkIdx(0))); assertEquals(9,nlines); for(int i = 0; i < nlines-2; ++i) for( Vec v : fr.vecs() ) assertTrue("error at line "+i+", vec " + v.chunkForChunkIdx(0).getClass().getSimpleName(), !Double.isNaN(v.at(i)) && !v.isNA(i) ); int j = 0; for( Vec v:fr.vecs() ) { for( int i = nlines-2; i < nlines; ++i ) { assertTrue(i + ", " + j + ":" + v.at(i) + ", " + v.isNA(i), Double.isNaN(v.at(i)) && v.isNA(i) ); // v.replaceNAs(1.0, 2); // assertTrue(!v.isNA(v.at(i)) && !v.isNA(v.at8(i))); // assertTrue(v.at(i) == 1.0 && v.at8(i) == 2); // v.setNAs(3.0, 4); // assertTrue(v.isNA(v.at(i)) && v.isNA(v.at8(i))); // assertTrue(v.at(i) == 3.0 && v.at8(i) == 4); } ++j; } fr.delete(); } // @Test public void testSingleQuotes(){ // String [] data = new String[]{"Tomas's,test\n'Tomas''s,test2',test2\nlast,'line''","s, trailing, piece'"}; // CustomParser.ParserSetup gSetup = new CustomParser.ParserSetup(ParserType.CSV, (byte)',', false); // Key k = FVecTest.makeByteVec(Key.make().toString(), data); // Key r1 = Key.make("single_quotes_test"); // ParseDataset2.parse(r1, new Key[]{k},gSetup); @Test public void testSingleQuotes() { Key k = Key.make("q.hex"); try { Frame fr = TestUtil.parseFrame(k,"smalldata/test/test_quote.csv"); Assert.assertEquals(fr.numCols(),11); Assert.assertEquals(fr.numRows(), 7); } finally { Lockable.delete(k); } } @Test public void testSVMLight() { String[] data = new String[] { "1 2:.2 5:.5 9:.9\n-1 1:.1 4:.4 8:.8\n", "1 2:.2 5:.5 9:.9\n1 3:.3 6:.6\n", "-1 7:.7 8:.8 9:.9\n1 20:2.\n", "+1 1:.1 5:.5 6:.6 10:1\n1 19:1.9\n", "1 2:.2 5:.5 9:.9\n-1 1:.1 4:.4 8:.8\n", "1 2:.2 5:.5 9:.9\n1 3:.3 6:.6\n", "-1 7:.7 8:.8 9:.9\n1 20:2.\n", "+1 1:.1 5:.5 6:.6 10:1\n1 19:1.9\n", "1 2:.2 5:.5 9:.9\n-1 1:.1 4:.4 8:.8\n", "1 2:.2 5:.5 9:.9\n1 3:.3 6:.6\n", "-1 7:.7 8:.8 9:.9\n1 20:2.\n", "+1 1:.1 5:.5 6:.6 10:1\n1 19:1.9\n" }; double[][] exp = new double[][] { d( 1., .0, .2, .0, .0, .5, .0, .0, .0, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( -1., .1, .0, .0, .4, .0, .0, .0, .8, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .2, .0, .0, .5, .0, .0, .0, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .3, .0, .0, .6, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( -1., .0, .0, .0, .0, .0, .0, .7, .8, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .0, .0, .0, .0, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0,2.0), d( 1., .1, .0, .0, .0, .5, .6, .0, .0, .0, 1, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .0, .0, .0, .0, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0,1.9, .0), d( 1., .0, .2, .0, .0, .5, .0, .0, .0, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( -1., .1, .0, .0, .4, .0, .0, .0, .8, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .2, .0, .0, .5, .0, .0, .0, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .3, .0, .0, .6, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( -1., .0, .0, .0, .0, .0, .0, .7, .8, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .0, .0, .0, .0, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0,2.0), d( 1., .1, .0, .0, .0, .5, .6, .0, .0, .0, 1, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .0, .0, .0, .0, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0,1.9, .0), d( 1., .0, .2, .0, .0, .5, .0, .0, .0, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( -1., .1, .0, .0, .4, .0, .0, .0, .8, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .2, .0, .0, .5, .0, .0, .0, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .3, .0, .0, .6, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( -1., .0, .0, .0, .0, .0, .0, .7, .8, .9, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .0, .0, .0, .0, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .0,2.0), d( 1., .1, .0, .0, .0, .5, .6, .0, .0, .0, 1, 0, 0, 0, 0, 0, 0, 0, 0, .0, .0), d( 1., .0, .0, .0, .0, .0, .0, .0, .0, .0, 0, 0, 0, 0, 0, 0, 0, 0, 0,1.9, .0), }; Key k = FVecTest.makeByteVec(Key.make("svmtest_bits").toString(),data); testParsed(k,exp); } // Test very sparse data @Test public void testSparse() { for (char separator : SEPARATORS) { // Build 100 zero's and 1 one. double[][] exp = new double[101][1]; exp[50][0] = 1; StringBuilder sb = new StringBuilder(); for( int i=0; i<50; i++ ) sb.append("0.0\n"); sb.append("1.0\n"); for( int i=0; i<50; i++ ) sb.append("0.0\n"); Key k = FVecTest.makeByteVec(Key.make().toString(),sb.toString()); testParsed(k,exp); // Build 100 zero's and 1 non-zero. exp = new double[101][1]; exp[50][0] = 2; sb = new StringBuilder(); for( int i=0; i<50; i++ ) sb.append("0\n"); sb.append("2\n"); for( int i=0; i<50; i++ ) sb.append("0\n"); k = FVecTest.makeByteVec(Key.make().toString(),sb.toString()); testParsed(k,exp); // Build 100 zero's and some non-zeros. Last line is truncated. exp = new double[101][2]; exp[ 50][0] = 2; exp[ 50][1] = 3; exp[100][0] = 0; // Truncated final line exp[100][1] = Double.NaN; sb = new StringBuilder(); for( int i=0; i<50; i++ ) sb.append("0,0\n"); sb.append("2,3\n"); for( int i=0; i<49; i++ ) sb.append("0,0\n"); sb.append("0"); // Truncated final line k = FVecTest.makeByteVec(Key.make().toString(),sb.toString()); testParsed(k,exp); // Build 100000 zero's and some one's sb = new StringBuilder(); exp = new double[100100][1]; for( int i=0; i<100; i++ ) { for( int j=0; j<1000; j++ ) sb.append("0\n"); sb.append("1\n"); exp[i*1001+1000][0]=1; } k = FVecTest.makeByteVec(Key.make().toString(),sb.toString()); testParsed(k,exp); // Build 100 zero's, then 100 mix of -1001 & 1001's (to force a // sparse-short, that finally inflates to a full dense-short). sb = new StringBuilder(); for( int i=0; i<100; i++ ) sb.append("0\n"); for( int i=0; i<100; i+=2 ) sb.append("-1001\n1001\n"); exp = new double[200][1]; for( int i=0; i<100; i+=2 ) { exp[i+100][0]=-1001; exp[i+101][0]= 1001; } k = FVecTest.makeByteVec(Key.make().toString(),sb.toString()); testParsed(k,exp); // Build 100 zero's and 1 double. exp = new double[101][1]; exp[50][0] = 1.23456789; sb = new StringBuilder(); for( int i=0; i<50; i++ ) sb.append("0.0\n"); sb.append("1.23456789\n"); for( int i=0; i<50; i++ ) sb.append("0.0\n"); k = FVecTest.makeByteVec(Key.make().toString(),sb.toString()); testParsed(k,exp); } } // Mix of NA's, very large & very small, ^A Hive-style seperator, comments, labels @Test public void testParseMix() { double[][] exp = new double[][] { d( 0 , 0.5 , 1 , 0), d( 3 , NaN , 4 , 1), d( 6 , NaN , 8 , 0), d( 0.6 , 0.7 , 0.8 , 1), d(+0.6 , +0.7 , +0.8 , 0), d(-0.6 , -0.7 , -0.8 , 1), d( .6 , .7 , .8 , 0), d(+ .6 , +.7 , +.8 , 1), d(- .6 , -.7 , -.8 , 0), d(+0.6e0 , +0.7e0 , +0.8e0 , 1), d(-0.6e0 , -0.7e0 , -0.8e0 , 0), d( .6e0 , .7e0 , .8e0 , 1), d(+ .6e0 , +.7e0 , +.8e0 , 0), d( -.6e0 , -.7e0 , -.8e0 , 1), d(+0.6e00 , +0.7e00 , +0.8e00 , 0), d(-0.6e00 , -0.7e00 , -0.8e00 , 1), d( .6e00 , .7e00 , .8e00 , 0), d( +.6e00 , +.7e00 , +.8e00 , 1), d( -.6e00 , -.7e00 , -.8e00 , 0), d(+0.6e-01, +0.7e-01, +0.8e-01, 1), d(-0.6e-01, -0.7e-01, -0.8e-01, 0), d( .6e-01, .7e-01, .8e-01, 1), d( +.6e-01, +.7e-01, +.8e-01, 0), d( -.6e-01, -.7e-01, -.8e-01, 1), d(+0.6e+01, +0.7e+01, +0.8e+01, 0), d(-0.6e+01, -0.7e+01, -0.8e+01, 1), d( .6e+01, .7e+01, .8e+01, 0), d( +.6e+01, +.7e+01, +.8e+01, 1), d( -.6e+01, -.7e+01, -.8e+01, 0), d(+0.6e102, +0.7e102, +0.8e102, 1), d(-0.6e102, -0.7e102, -0.8e102, 0), d( .6e102, .7e102, .8e102, 1), d( +.6e102, +.7e102, +.8e102, 0), d( -.6e102, -.7e102, -.8e102, 1) }; testParsed(TestUtil.parseFrame(null,"smalldata/test/test_parse_mix.csv"),exp,exp.length); } // Test of parsing numbers with many digits @Test public void testParseManyDigits1() { String pows10 = "1\n"+ "10\n"+ "100\n"+ "1000\n"+ "10000\n"+ "100000\n"+ "1000000\n"+ "10000000\n"+ "100000000\n"+ "1000000000\n"+ "10000000000\n"+ "100000000000\n"+ "1000000000000\n"+ "10000000000000\n"+ "100000000000000\n"+ "1000000000000000\n"+ "10000000000000000\n"+ "100000000000000000\n"+ "1000000000000000000\n"+ "10000000000000000000\n"+ "100000000000000000000\n"+ "1000000000000000000000\n"+ "10000000000000000000000\n"+ "100000000000000000000000\n"; double[][] pows10_exp = new double[][] { d(1e0 ), d(1e1 ), d(1e2 ), d(1e3 ), d(1e4 ), d(1e5 ), d(1e6 ), d(1e7 ), d(1e8 ), d(1e9 ), d(1e10), d(1e11), d(1e12), d(1e13), d(1e14), d(1e15), d(1e16), d(1e17), d(1e18), d(1e19), d(1e20), d(1e21), d(1e22), d(1e23), }; Key k = FVecTest.makeByteVec("test_digits.csv",pows10); testParsed(k,pows10_exp); } // Test of parsing numbers with many digits @Test public void testParseManyDigits2() { String pows10 = "9\n"+ "99\n"+ "999\n"+ "9999\n"+ "99999\n"+ "999999\n"+ "9999999\n"+ "99999999\n"+ "999999999\n"+ "9999999999\n"+ "99999999999\n"+ "999999999999\n"+ "9999999999999\n"+ "99999999999999\n"+ "999999999999999\n"+ "9999999999999999\n"+ "99999999999999999\n"+ "999999999999999999\n"+ "9999999999999999999\n"+ "99999999999999999999\n"+ "999999999999999999999\n"+ "9999999999999999999999\n"+ "99999999999999999999999\n"+ "999999999999999999999999\n"; double[][] pows10_exp = new double[][] { d(9L), d(99L), d(999L), d(9999L), d(99999L), d(999999L), d(9999999L), d(99999999L), d(999999999L), d(9999999999L), d(99999999999L), d(999999999999L), d(9999999999999L), d(99999999999999L), d(999999999999999L), d(9999999999999999L), d(99999999999999999L), d(999999999999999999L), d(9.99999999999999999e18), d(9.99999999999999999e19), d(9.99999999999999999e20), d(9.99999999999999999e21), d(9.99999999999999999e22), d(9.99999999999999999e23), }; Key k = FVecTest.makeByteVec("test_digits.csv",pows10); testParsed(k,pows10_exp); } // Test of parsing numbers with many digits @Test public void testParseManyDigits3() { String pows10 = "0.00000000000001\n"+ "1000001\n"+ "2000001\n"+ ""; double[][] pows10_exp = new double[][] { d(1e-14), d(1000001L), d(2000001L), }; Key k = FVecTest.makeByteVec("test_digits.csv",pows10); testParsed(k,pows10_exp); } // Test of parsing numbers with many digits @Test public void testParseManyDigits4() { String pows10 = "3\n"+ "1e-18\n"+ "1e-34\n"+ ""; double[][] pows10_exp = new double[][] { d(3), d(1e-18), d(1e-34), }; Key k = FVecTest.makeByteVec("test_digits.csv",pows10); testParsed(k,pows10_exp); } @Test public void testMultiFileParseSmall(){ Key [] files = null,files2 = null; Frame f1 = null,f2 = null; try { files = ImportFiles2.importPath("smalldata/parse_folder_test"); f1 = ParseDataset2.parse(Key.make("multifile"), files); files2 = ImportFiles2.importPath("smalldata/glm_test/prostate_cat_replaced.csv"); f2 = f1.makeCompatible(ParseDataset2.parse(Key.make("singleFile"), files2)); DKV.put(f2._key,f2); // annoyingly, have to put the frame back into KV // can not assert on bit-identity, enums will generally have different types depending on how they were created, // since during parse they are first numbered racily (so the initial compression does not have to be optimal!) // and then renumbered later, but not recompressed (if they fit within the original compresison scheme) assertTrue(f1.isIdentical(f2)); } finally { if(f1 != null) f1.delete(); if(f2 != null)f2.delete(); if(files != null) for(Key k:files)UKV.remove(k); if(files2 != null) for(Key k:files2)UKV.remove(k); } } void runTests(){ System.out.println("testBasic"); testBasic(); System.out.println("testBasicSpaceAsSeparator"); testBasicSpaceAsSeparator(); System.out.println("testChunkBoundaries"); testChunkBoundaries(); System.out.println("testChunkBoundariesMixedLineEndings"); testChunkBoundariesMixedLineEndings(); System.out.println("testEmptyColumnValues"); testEmptyColumnValues(); System.out.println("testMixedSeps"); testMixedSeps(); System.out.println("testMultipleNondecimalColumns"); testMultipleNondecimalColumns(); System.out.println("testNondecimalColumns"); testNondecimalColumns(); System.out.println("testNumberFormats"); testNumberFormats(); System.out.println("testNAs"); testNAs(); checkLeakedKeys(); System.out.println("DONE!!!"); } public static void main(String [] args) throws Exception{ System.out.println("Running ParserTest2"); final int nnodes = 1; for( int i = 1; i < nnodes; i++ ) { Node n = new NodeVM(args); n.inheritIO(); n.start(); } H2O.waitForCloudSize(nnodes); new ParserTest2 ().runTests(); new ParseTimeTest().runTests(); System.out.println("DONE!"); } public static class ParseAllSmalldata { @Test public void run() { //for i in `find smalldata -type f`; do echo \"$i\",; done String[] files = new String[]{ "smalldata/1_100kx7_logreg.data.gz", "smalldata/2_100kx7_logreg.data.gz", "smalldata/Abalone.gz", "smalldata/adult.gz", "smalldata/AID362red_test.csv.gz", "smalldata/airlines/AirlinesTest.csv.zip", "smalldata/airlines/AirlinesTrain.csv.zip", "smalldata/airlines/airlineUUID.csv", "smalldata/airlines/allyears2k.zip", "smalldata/airlines/allyears2k_headers.zip", // "smalldata/airlines/hiveallyears2k/04c40d7c-33c8-486c-8f08-e24ebb8832ea_000000", // "smalldata/airlines/hiveallyears2k/04c40d7c-33c8-486c-8f08-e24ebb8832ed_000000", // "smalldata/airlines/hiveallyears2k/04c40d7c-33c8-486c-8f08-e24ebb8832ed_000001", // "smalldata/airlines/hiveallyears2k/04c40d7c-33c8-486c-8f08-e24ebb8832ed_000002", // "smalldata/airlines/hiveallyears2k/04c40d7c-33c8-486c-8f08-e24ebb8832ed_000005", "smalldata/airlines/uuid_airline.csv", // "smalldata/allstate/claim_prediction_dict.html", "smalldata/allstate/claim_prediction_train_set_10000.csv.gz", "smalldata/allstate/claim_prediction_train_set_10000_bool.csv.gz", "smalldata/allstate/claim_prediction_train_set_10000_int.csv.gz", "smalldata/anomaly/ecg_discord.csv", "smalldata/anomaly/ecg_discord_test.csv", "smalldata/anomaly/ecg_discord_train.csv", "smalldata/anomaly/toy_test.csv", "smalldata/anomaly/toy_train.csv", "smalldata/arcene/arcene_test.data", "smalldata/arcene/arcene_train.data", "smalldata/arcene/arcene_train_labels.labels", "smalldata/arcene/arcene_valid.data", "smalldata/arcene/arcene_valid_labels.labels", "smalldata/auto.csv", "smalldata/badchars.csv", "smalldata/baddata.data", "smalldata/bigburn.csv", "smalldata/boring.csv", "smalldata/BostonHousing.csv", "smalldata/cars.csv", "smalldata/cars_nice_header.csv", "smalldata/categoricals/30k_categoricals.csv.gz", "smalldata/categoricals/40k_categoricals.csv.gz", "smalldata/categoricals/AllBedrooms_Rent_Neighborhoods.csv.gz", "smalldata/categoricals/apartments_rec.csv", "smalldata/categoricals/Cleveland_heartDiseaseUCI_test.csv", "smalldata/categoricals/Cleveland_heartDiseaseUCI_train.csv", "smalldata/categoricals/TwoBedrooms_Rent_Neighborhoods.csv.gz", "smalldata/cebbinom.csv", "smalldata/cebexpanded.csv", "smalldata/cebexpandedREADME.rtf", "smalldata/chess/chess_1x2x1000/h2o/test.csv", "smalldata/chess/chess_1x2x1000/h2o/train.csv", "smalldata/chess/chess_2x1x1000/h2o/test.csv", "smalldata/chess/chess_2x1x1000/h2o/train.csv", "smalldata/chess/chess_2x2x10/h2o/test.csv", "smalldata/chess/chess_2x2x10/h2o/train.csv", "smalldata/chess/chess_2x2x10/R/test.csv", "smalldata/chess/chess_2x2x10/R/train.csv", "smalldata/chess/chess_2x2x10/rf.conf", "smalldata/chess/chess_2x2x10/weka/test.csv.arff", "smalldata/chess/chess_2x2x10/weka/train.csv.arff", "smalldata/chess/chess_2x2x100/h2o/test.csv", "smalldata/chess/chess_2x2x100/h2o/train.csv", "smalldata/chess/chess_2x2x100/R/test.csv", "smalldata/chess/chess_2x2x100/R/train.csv", "smalldata/chess/chess_2x2x100/rf.conf", "smalldata/chess/chess_2x2x100/weka/test.csv.arff", "smalldata/chess/chess_2x2x100/weka/train.csv.arff", "smalldata/chess/chess_2x2x1000/h2o/test.csv", "smalldata/chess/chess_2x2x1000/h2o/train.csv", "smalldata/chess/chess_2x2x1000/R/test.csv", "smalldata/chess/chess_2x2x1000/R/train.csv", "smalldata/chess/chess_2x2x1000/rf.conf", "smalldata/chess/chess_2x2x1000/weka/test.csv.arff", "smalldata/chess/chess_2x2x1000/weka/train.csv.arff", "smalldata/chess/chess_2x2x200/h2o/test.csv", "smalldata/chess/chess_2x2x200/h2o/train.csv", "smalldata/chess/chess_2x2x200/R/test.csv", "smalldata/chess/chess_2x2x200/R/train.csv", "smalldata/chess/chess_2x2x200/rf.conf", "smalldata/chess/chess_2x2x200/weka/test.csv.arff", "smalldata/chess/chess_2x2x200/weka/train.csv.arff", "smalldata/chess/chess_2x2x500/h2o/chess_2x2_500_int.csv", "smalldata/chess/chess_2x2x500/h2o/test.csv", "smalldata/chess/chess_2x2x500/h2o/train.csv", "smalldata/chess/chess_2x2x500/R/test.csv", "smalldata/chess/chess_2x2x500/R/train.csv", "smalldata/chess/chess_2x2x500/rf.conf", "smalldata/chess/chess_2x2x500/weka/test.csv.arff", "smalldata/chess/chess_2x2x500/weka/train.csv.arff", "smalldata/chess/chess_8x8x1000/R/test.csv", "smalldata/chess/chess_8x8x1000/R/train.csv", "smalldata/constantColumn.csv", "smalldata/covtype/covtype.20k.data", "smalldata/covtype/covtype.altered.gz", "smalldata/cuse.data.csv", "smalldata/cusedataREADME.rtf", "smalldata/cuseexpanded.csv", "smalldata/datagen1.csv", "smalldata/datetime/dd-mon-yr.csv", "smalldata/datetime/dd-mon-yy-with-other-cols.csv", "smalldata/drugs.csv", "smalldata/dummydata.csv", "smalldata/fail1_100x11000.csv.gz", "smalldata/fail2_24_100000_10.csv.gz", "smalldata/fish.csv", "smalldata/gaussian/sdss174052.csv.gz", "smalldata/gbm_test/CaliforniaHousing/cal_housing.data", "smalldata/gbm_test/CaliforniaHousing/cal_housing.domain", "smalldata/gbm_test/ecology_eval.csv", "smalldata/gbm_test/ecology_model.csv", "smalldata/gbm_test/Mfgdata_gaussian_GBM_testing.csv", "smalldata/gisette/Gisette_train_data.csv.gzip", "smalldata/gisette/Gisette_train_labels.csv.gzip", "smalldata/gisette/Gisette_valid_data.csv.gzip", "smalldata/gisette/Gisette_valid_labels.csv.gzip", "smalldata/glm_test/poisson_tst1.csv", "smalldata/glm_test/prostate_cat_replaced.csv", "smalldata/gt69436csv.data", "smalldata/handmade.csv", "smalldata/hex-443.parsetmp_1_0_0_0.data", "smalldata/hhp.cut3.214.data.gz", "smalldata/hhp_107_01.data.gz", "smalldata/hhp_9_17_12.predict.data.gz", "smalldata/histogram_test/30k_cattest.csv", "smalldata/histogram_test/50_cattest_test.csv", "smalldata/histogram_test/50_cattest_train.csv", "smalldata/histogram_test/alphabet_cattest.csv", "smalldata/histogram_test/bigcat_5000x2.csv", "smalldata/histogram_test/czechboard_300x300.csv", "smalldata/histogram_test/swpreds_1000x3.csv", "smalldata/housing.raw.txt", "smalldata/iris/iris.csv", "smalldata/iris/iris.csv.gz", "smalldata/iris/iris.csv.zip", "smalldata/iris/iris.xls", "smalldata/iris/iris.xlsx", "smalldata/iris/iris2.csv", "smalldata/iris/iris22.csv", // "smalldata/iris/iris_header.csv", "smalldata/iris/iris_test.csv", "smalldata/iris/iris_train.csv", "smalldata/iris/iris_wheader.csv", "smalldata/iris/iris_wheader.csv.gz", "smalldata/iris/iris_wheader.csv.zip", "smalldata/iris/iris_wheader.nonspd.csv", "smalldata/iris/leads.csv", "smalldata/jira/850.csv", "smalldata/jira/hex-1789.csv", "smalldata/jira/pub-180.csv", "smalldata/jira/pub-215.csv", "smalldata/jira/pub-35_test.csv", "smalldata/jira/pub-35_train.csv", "smalldata/jira/pub-569.csv", "smalldata/jira/pub_213.csv", "smalldata/jira/v-11.csv", "smalldata/jira/v-3.csv", "smalldata/kaggle/bestbuy_train_10k.csv.gz", "smalldata/kaggle/creditsample-test.csv.gz", "smalldata/kaggle/creditsample-training.csv.gz", "smalldata/kaggle/KDDTest.arff.gz", "smalldata/kaggle/KDDTrain.arff.gz", "smalldata/linreg/data.gz", "smalldata/logreg/100kx7_logreg.data.gz", "smalldata/logreg/benign.csv", "smalldata/logreg/benign.xls", "smalldata/logreg/failtoconverge_1000x501.csv.gz", "smalldata/logreg/failtoconverge_100x50.csv", "smalldata/logreg/logreg_trisum_int_cat_10000x10.csv", "smalldata/logreg/make_me_converge_10000x5.csv", "smalldata/logreg/princeton/copen.dat", "smalldata/logreg/princeton/cuse.dat", "smalldata/logreg/princeton/housing.raw", "smalldata/logreg/pros.xls", "smalldata/logreg/prostate.csv", "smalldata/logreg/prostate_long.csv.gz", "smalldata/logreg/prostate_test.csv", "smalldata/logreg/prostate_train.csv", "smalldata/logreg/syn_2659x1049.csv", "smalldata/logreg/syn_2659x1049x2enum.csv", "smalldata/logreg/syn_8686576441534898792_10000x100.csv", "smalldata/logreg/umass_chdage.csv", "smalldata/logreg/umass_statdata/cgd.dat", "smalldata/logreg/umass_statdata/cgd.txt", "smalldata/logreg/umass_statdata/chdage.dat", "smalldata/logreg/umass_statdata/chdage.txt", "smalldata/logreg/umass_statdata/chdage_cleaned.dat", "smalldata/logreg/umass_statdata/clslowbwt.dat", "smalldata/logreg/umass_statdata/clslowbwt.txt", "smalldata/logreg/umass_statdata/icu.dat", "smalldata/logreg/umass_statdata/icu.txt", "smalldata/logreg/umass_statdata/lowbwt.dat", "smalldata/logreg/umass_statdata/lowbwt.txt", "smalldata/logreg/umass_statdata/lowbwtm11.dat", "smalldata/logreg/umass_statdata/lowbwtm11.txt", "smalldata/logreg/umass_statdata/meexp.dat", "smalldata/logreg/umass_statdata/meexp.txt", "smalldata/logreg/umass_statdata/nhanes3.dat", "smalldata/logreg/umass_statdata/nhanes3.txt", "smalldata/logreg/umass_statdata/pbc.dat", "smalldata/logreg/umass_statdata/pbc.txt", "smalldata/logreg/umass_statdata/pharynx.dat", "smalldata/logreg/umass_statdata/pharynx.txt", "smalldata/logreg/umass_statdata/pros.dat", "smalldata/logreg/umass_statdata/pros.txt", "smalldata/logreg/umass_statdata/uis.dat", "smalldata/logreg/umass_statdata/uis.txt", "smalldata/logreg/why_perfect_training_100x500.csv", "smalldata/makedata.csv", "smalldata/marketing_naRemoved.csv", "smalldata/mixed_causes_NA.csv", "smalldata/mnist/readme.txt", "smalldata/mnist/test.csv.gz", "smalldata/mnist/train.csv.gz", "smalldata/mtcars.csv", "smalldata/Mushroom.gz", "smalldata/neural/Benchmark_dojo_test.data", "smalldata/neural/eightsq.data", "smalldata/neural/Readme.txt", "smalldata/neural/sin_pattern.data", "smalldata/neural/sumsigmoids.csv", "smalldata/neural/sumsigmoids_test.csv", "smalldata/neural/two_spiral.data", "smalldata/neural/two_spiral.png", "smalldata/parity_128_4_100_quad.data", "smalldata/parity_128_4_2_quad.data", "smalldata/parse_fail_double_space.csv", "smalldata/parse_folder_test/prostate_0.csv", "smalldata/parse_folder_test/prostate_1.csv", "smalldata/parse_folder_test/prostate_2.csv", "smalldata/parse_folder_test/prostate_3.csv", "smalldata/parse_folder_test/prostate_4.csv", "smalldata/parse_folder_test/prostate_5.csv", "smalldata/parse_folder_test/prostate_6.csv", "smalldata/parse_folder_test/prostate_7.csv", "smalldata/parse_folder_test/prostate_8.csv", "smalldata/parse_folder_test/prostate_9.csv", "smalldata/parse_zeros_100x8500.csv.gz", "smalldata/pca_test/AustraliaCoast.csv", "smalldata/pca_test/USArrests.csv", "smalldata/phbirths.raw.txt", "smalldata/pmml/cars-cater-rf-1tree.pmml", "smalldata/pmml/cars-cater-rf-50trees.pmml", "smalldata/pmml/cars-rf-1tree.pmml", "smalldata/pmml/cars-rf-50trees.pmml", "smalldata/pmml/copen-rf-1tree.pmml", "smalldata/pmml/copen-rf-50trees.pmml", "smalldata/pmml/iris_rf_1tree.pmml", "smalldata/pmml/iris_rf_500trees.pmml", "smalldata/pmml/SampleScorecard.pmml", "smalldata/poisson/Goalies.csv", "smalldata/poker/poker-hand-testing.data", "smalldata/poker/poker-hand.pl", "smalldata/poker/poker10", "smalldata/poker/poker100", "smalldata/poker/poker1000", "smalldata/prostate/prostate.bin.csv.zip", "smalldata/prostate/prostate.csv.zip", "smalldata/prostate/prostate.float.csv.zip", "smalldata/prostate/prostate.int.csv.zip", "smalldata/prostate/prostate.uuid.csv.zip", "smalldata/quantiles/breadth.csv", "smalldata/random1csv.data", "smalldata/randomdata2.csv", "smalldata/randomdata3.csv", "smalldata/runif.csv", "smalldata/runifA.csv", "smalldata/runifB.csv", "smalldata/runifC.csv", "smalldata/smtrees.csv", "smalldata/space_shuttle_damage.csv", "smalldata/stego/stego_testing.data", "smalldata/stego/stego_training.data", "smalldata/stego/stego_training_modified.data", "smalldata/swiss.csv", "smalldata/swiss_clean.csv", "smalldata/syn_binary10Kx100.csv.gz", "smalldata/syn_fp_prostate.csv", "smalldata/syn_sphere2.csv", "smalldata/syn_sphere3.csv", "smalldata/test/arit.csv", "smalldata/test/classifier/chess_test.csv", "smalldata/test/classifier/chess_train.csv", "smalldata/test/classifier/coldom_test_1.csv", "smalldata/test/classifier/coldom_test_1_2.csv", "smalldata/test/classifier/coldom_test_2.csv", "smalldata/test/classifier/coldom_test_3.csv", "smalldata/test/classifier/coldom_train_1.csv", "smalldata/test/classifier/coldom_train_2.csv", "smalldata/test/classifier/coldom_train_3.csv", "smalldata/test/classifier/iris_missing_values.csv", "smalldata/test/classifier/iris_test.csv", "smalldata/test/classifier/iris_test_extra.csv", "smalldata/test/classifier/iris_test_extra_with_na.csv", "smalldata/test/classifier/iris_test_missing.csv", "smalldata/test/classifier/iris_test_missing_extra.csv", "smalldata/test/classifier/iris_test_numeric.csv", "smalldata/test/classifier/iris_test_numeric_extra.csv", "smalldata/test/classifier/iris_test_numeric_extra2.csv", "smalldata/test/classifier/iris_test_numeric_missing.csv", "smalldata/test/classifier/iris_test_numeric_missing_extra.csv", "smalldata/test/classifier/iris_train.csv", "smalldata/test/classifier/iris_train_numeric.csv", "smalldata/test/classifier/multi_class.test.csv", "smalldata/test/classifier/multi_class.train.csv", "smalldata/test/cm/v1.csv", "smalldata/test/cm/v1n.csv", "smalldata/test/cm/v2.csv", "smalldata/test/cm/v2n.csv", "smalldata/test/cm/v3.csv", "smalldata/test/cm/v4.csv", "smalldata/test/cm/v4n.csv", "smalldata/test/HEX-287-small-files.data", "smalldata/test/hive.txt", "smalldata/test/HTWO-87-one-line-dataset-0.csv", "smalldata/test/HTWO-87-one-line-dataset-1dos.csv", "smalldata/test/HTWO-87-one-line-dataset-1unix.csv", "smalldata/test/HTWO-87-one-line-dataset-2dos.csv", "smalldata/test/HTWO-87-one-line-dataset-2unix.csv", "smalldata/test/HTWO-87-two-lines-dataset.csv", "smalldata/test/HTWO-87-two-unique-lines-dataset.csv", "smalldata/test/is_NA.csv", "smalldata/test/na_test.zip", "smalldata/test/R/titanic.csv", // "smalldata/test/rmodels/covtype-rf-50tree-as-factor-X5-20k.rdata", // "smalldata/test/rmodels/covtype-rf-50tree-as-factor-X5.rdata", "smalldata/test/rmodels/covtype.rf.2", // "smalldata/test/rmodels/iris_x-iris-1-4_y-species_ntree-3.rdata", // "smalldata/test/rmodels/iris_x-iris-1-4_y-species_ntree-500.rdata", // "smalldata/test/rmodels/ozone.rf.10trees.rdata", // "smalldata/test/rmodels/prostate-rf-10tree-asFactorCapsule.rdata", // "smalldata/test/rmodels/prostate-rf-1tree-asFactorCapsule.rdata", // "smalldata/test/rmodels/prostate-rf-2tree-asFactorCapsule.rdata", "smalldata/test/rmodels/rf-iris-1tree.model", "smalldata/test/test1.dat", "smalldata/test/test_26cols_comma_sep.csv", "smalldata/test/test_26cols_multi_space_sep.csv", "smalldata/test/test_26cols_single_space_sep.csv", "smalldata/test/test_26cols_single_space_sep_2.csv", "smalldata/test/test_all_raw_top10rows.csv", "smalldata/test/test_enum_domain_size.csv", "smalldata/test/test_less_than_65535_unique_names.csv", "smalldata/test/test_manycol_tree.csv", "smalldata/test/test_more_than_65535_unique_names.csv", "smalldata/test/test_parse_mix.csv", "smalldata/test/test_percentiles_distns.csv.gz", "smalldata/test/test_percentiles_distns.R", "smalldata/test/test_quote.csv", "smalldata/test/test_time.csv", "smalldata/test/test_tree.csv", "smalldata/test/test_tree_minmax.csv", "smalldata/test/test_uuid.csv", "smalldata/test/test_uuid_na.csv", "smalldata/test/test_var.csv", "smalldata/Test_Arabic_Digit_short.data", "smalldata/tinyburn.csv", "smalldata/titanicalt.csv", "smalldata/tnc3.csv", "smalldata/tnc3_10.csv", "smalldata/tnc6.csv", "smalldata/toy_data_RF.csv", "smalldata/toykm.csv", "smalldata/trees.csv", "smalldata/Twitter2DB.txt", "smalldata/unbalanced/orange_small_test.data.zip", "smalldata/unbalanced/orange_small_train.data.zip", "smalldata/WBIsparsedata", "smalldata/weather.csv", "smalldata/wine.data", "smalldata/winesPCA.csv", "smalldata/wonkysummary.csv", "smalldata/zero_dot_zero_one.csv", "smalldata/zero_dot_zero_zero_one.csv", "smalldata/zinb.csv", "smalldata/zip_code/zip_code_database.csv.gz", "smalldata/zip_code/zipcodes", "smalldata/zipcodes", }; for (String f : files) { try { Log.info("Trying to parse " + f); Key fkey = NFSFileVec.make(find_test_file(f)); ParseDataset2.parse(Key.make(), new Key[]{fkey}); } catch (Throwable t) { t.printStackTrace(); } } } } }
package thobe.mapview.kernel; /** * @author Thomas Obenaus * @source MapViewInfo.java * @date Oct 6, 2013 */ public class MapViewInfo { private static String LIB_NAME = "thobe.MapView"; private static Integer MAYOR_VERSION = 0; private static Integer MINOR_VERSION = 2; private static Integer PATCH_LEVEL = 0; private static Integer BUILD_NUMBER = 1; public static String getLibName( ) { return LIB_NAME; } public static String getLibVersion( ) { return MAYOR_VERSION + "." + MINOR_VERSION + "." + PATCH_LEVEL + "-" + BUILD_NUMBER; } }
import java.util.HashMap; import java.util.ArrayList; import spark.ModelAndView; import spark.template.velocity.VelocityTemplateEngine; import static spark.Spark.*; public class App { public static void main(String[] args) { staticFileLocation("/public"); String layout = "templates/layout.vtl"; } }
import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.time.LocalDate; import java.time.Month; import java.util.HashMap; import java.util.Iterator; import spark.ModelAndView; import spark.template.velocity.VelocityTemplateEngine; import static spark.Spark.*; public class App { public static void main(String[] args) { staticFileLocation("/public"); String layout = "templates/layout.vtl"; ProcessBuilder process = new ProcessBuilder(); Integer port; if (process.environment().get("PORT") != null) { port = Integer.parseInt(process.environment().get("PORT")); } else { port = 4567; } setPort(port); //ROUTES: Home Page get("/", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); model.put("words", Word.getAll()); model.put("template", "templates/allwords.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); //ROUTES: Identification of Resources get("/new", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); model.put("template", "templates/new.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); get("/:id", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); boolean wordNotAdded = false; String wordRequested = request.params(":id"); String decodedWord = ""; try { decodedWord = URLDecoder.decode(wordRequested, "UTF-8"); } catch (UnsupportedEncodingException uee) { System.err.println("Caught UnsupportedEncodingException: " + uee.getMessage()); } if (Word.getWord(decodedWord) == null) { wordNotAdded = true; } model.put("wordnotadded", wordNotAdded); model.put("word", Word.getWord(decodedWord)); model.put("template", "templates/word.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); //ROUTES: Changing Resources post("/", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); boolean alreadyAdded = false; String userWord = request.queryParams("userword"); if (Word.getWord(userWord) != null) { alreadyAdded = true; } else { Word newWord = new Word(userWord); } model.put("alreadyadded", alreadyAdded); model.put("words", Word.getAll()); model.put("template", "templates/allwords.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); post("/:id", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); String wordRequested = request.params(":id"); String decodedWord = ""; try { decodedWord = URLDecoder.decode(wordRequested, "UTF-8"); } catch (UnsupportedEncodingException uee) { System.err.println("Caught UnsupportedEncodingException: " + uee.getMessage()); } Word thisWord = Word.getWord(decodedWord); String userDefinition = request.queryParams("userdefinition"); String userExample = request.queryParams("userexample"); Definition newDefinition = new Definition(userDefinition, userExample); thisWord.addDefinition(newDefinition); model.put("word", thisWord); model.put("template", "templates/word.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); post("/:id/remove/:rmdef", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); String wordRequested = request.params(":id"); String decodedWord = ""; try { decodedWord = URLDecoder.decode(wordRequested, "UTF-8"); } catch (UnsupportedEncodingException uee) { System.err.println("Caught UnsupportedEncodingException: " + uee.getMessage()); } Word thisWord = Word.getWord(decodedWord); String removalRequest = request.params(":rmdef"); String decodedRemovalRequest = ""; try { decodedRemovalRequest = URLDecoder.decode(removalRequest, "UTF-8"); } catch (UnsupportedEncodingException uee) { System.err.println("Caught UnsupportedEncodingException: " + uee.getMessage()); } for (Iterator<Definition> iterator = thisWord.getAllDefinitions().iterator(); iterator.hasNext();) { Definition definition = iterator.next(); System.out.println(definition); if (definition.getString().equals(decodedRemovalRequest)) { iterator.remove(); } } model.put("word", thisWord); model.put("template", "templates/word.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); post("/remove/:id", (request, response) -> { HashMap<String, Object> model = new HashMap<String, Object>(); String removalRequest = request.params(":id"); String decodedRemovalRequest = ""; try { decodedRemovalRequest = URLDecoder.decode(removalRequest, "UTF-8"); } catch (UnsupportedEncodingException uee) { System.err.println("Caught UnsupportedEncodingException: " + uee.getMessage()); } Word.removeWord(decodedRemovalRequest); model.put("words", Word.getAll()); model.put("template", "templates/allwords.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); } }
public class Iwa { public Iwa() { System.out.println("Iwa !"); } public static final void main(String[] args) { echo(); } private static final void echo() { System.out.println("aaa"); } }
// S t e p // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr; import omr.sheet.Sheet; import omr.ui.StepView; import omr.util.Logger; import omr.util.Memory; import java.io.File; import java.lang.reflect.Field; /** * Class <code>Step</code> describes the ordered sequence of processing * steps that are defined on a sheet. The comprehensive ordered list of * step names is defined in {@link omr.sheet.Sheet} class. * * @author Herv&eacute Bitteur * @version $Id$ */ public class Step { private static final Logger logger = Logger.getLogger(Step.class); // Related UI when used in interactive mode private static StepView view; // The most popular step, so it's easier to get it directly private static Step LOAD; // Reflection field to the corresponding sheet InstanceStep private final Field field; // Readable description private final String description; /** * Create a step, related to a sheet InstanceStep * * @param field the reflection field of the related InstanceStep * @param description the verbose description of the related * InstanceStep */ public Step (Field field, String description) { this.field = field; this.description = description; } // getDescription // /** * Return a description for this step, usable for a tip for example. * * @return a description string */ public String getDescription () { return description; } // getField // /** * Return the reflection field of the related Sheet.InstanceStep * * @return the related field */ public Field getField () { return field; } // getLoadStep // /** * Return the most popular step accessed by name : LOAD * * @return the LOAD step */ public static Step getLoadStep () { if (LOAD == null) { LOAD = getStep("LOAD"); } return LOAD; } // getPosition // /** * Report the index of this step in the list of known steps * * @return the index, starting from 0. */ public int getPosition () { return Sheet.getSteps().indexOf(this); } // getStep // /** * Retrieve a step, knowing its name * * @param id the name of the step (case is not relevant) * * @return the step found, or null otherwise */ public static Step getStep (String id) { for (Step step : Sheet.getSteps()) { if (id.equalsIgnoreCase(step.toString())) { return step; } } logger.severe("Cannot find Step for id " + id); return null; } // doPerform // /** * Meant to actually perform the series of step(s), with or without UI. * * @param sheet the sheet on which analysis is performed, sheet may be * null (case of loading a brand new sheet) * @param param a potential parameter for the step. This is actually * used only when loading a new sheet. * * @throws ProcessingException Raised when processing has failed */ public void doPerform (Sheet sheet, Object param) throws ProcessingException { Step current = null; try { // Force execution of specified step current = this; doStep(sheet, param); } catch (ProcessingException ex) { // User has already been informed, so just stop //logger.warning("Processing aborted", ex); //logger.warning("Processing aborted"); } catch (Exception ex) { logger.error("Exception in performing step " + current, ex); } } // notifyMsg // /** * Notify a simple message, which may be not related to any step. * * @param msg the message to display on the UI window, or to write in * the log if there is no UI. */ public static void notifyMsg (String msg) { if (view != null) { view.notifyMsg(msg); } else { logger.info(msg); } } // perform // /** * Trigger the execution of all needed steps up to this one. * * <p> This is delegated to the UI if there is such interface, which * will ultimately call doPerform(). If there is no UI, doPerform() is * called directly. * * @param sheet the sheet on which analysis is performed * @param param a potential parameters (depending on the processing) */ public void perform (Sheet sheet, Object param) { try { if (view != null) { Step from = (sheet == null) ? LOAD : sheet.fromStep(this); view.perform(this, sheet, param, from); } else { doPerform(sheet, param); } } catch (ProcessingException ex) { // User has already been informed of the error details, so do // nothing } } // toString // /** * Usual method to return a readable string * * @return a short string */ @Override public String toString () { return field.getName(); } // setView // /** * Allows to couple the steps with a UI. This is done from 'Main' in * the same omr package. */ static void setView () { view = new StepView(); } // doStep // /** * Do just one step (probably within a larger series) * * @param sheet the sheet to be processed * @param param the potential step parameter * * @return the (created or modified) sheet * @throws ProcessingException */ private Sheet doStep (Sheet sheet, Object param) throws ProcessingException { long startTime = 0; if (logger.isDebugEnabled()) { logger.debug("Starting " + this); startTime = System.currentTimeMillis(); } notifyMsg(toString() + ((param != null) ? (" " + param) : "")); // Do we have the sheet already if (sheet == null) { // Load sheet using the provided parameter sheet = new Sheet((File) param); } // Check for loading of a sheet if (this != getLoadStep()) { // Standard processing on an existing sheet sheet.getInstanceStep(this).undo(); sheet.getInstanceStep(this).getResult(); } // Update user interface ? if (view != null) { sheet.getInstanceStep(this).displayUI(); } if (logger.isDebugEnabled()) { final long stopTime = System.currentTimeMillis(); logger.debug("Completed " + this + " in " + (stopTime - startTime) + " ms with " + Memory.getValue() + " bytes"); } return sheet; } }
package org.xbill.DNS; import java.io.*; import java.text.*; /** * A representation of a domain name. It may either be absolute (fully * qualified) or relative. * * @author Brian Wellington */ public class Name implements Comparable { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_MASK = 0xC0; /* The name data */ private byte [] name; /* * Effectively an 8 byte array, where the low order byte stores the number * of labels and the 7 higher order bytes store per-label offsets. */ private long offsets; /* Precomputed hashcode. */ private int hashcode; private static final byte [] emptyLabel = new byte[] {(byte)0}; private static final byte [] wildLabel = new byte[] {(byte)1, (byte)'*'}; /** The root name */ public static final Name root; /** The root name */ public static final Name empty; /** The maximum length of a Name */ private static final int MAXNAME = 255; /** The maximum length of a label a Name */ private static final int MAXLABEL = 63; /** The maximum number of labels in a Name */ private static final int MAXLABELS = 128; /** The maximum number of cached offsets */ private static final int MAXOFFSETS = 7; /* Used for printing non-printable characters */ private static final DecimalFormat byteFormat = new DecimalFormat(); /* Used to efficiently convert bytes to lowercase */ private static final byte lowercase[] = new byte[256]; /* Used in wildcard names. */ private static final Name wild; static { byteFormat.setMinimumIntegerDigits(3); for (int i = 0; i < lowercase.length; i++) { if (i < 'A' || i > 'Z') lowercase[i] = (byte)i; else lowercase[i] = (byte)(i - 'A' + 'a'); } root = new Name(); root.appendSafe(emptyLabel, 0, 1); empty = new Name(); empty.name = new byte[0]; wild = new Name(); wild.appendSafe(wildLabel, 0, 1); } private Name() { } private final void dump(String prefix) { String s; try { s = toString(); } catch (Exception e) { s = "<unprintable>"; } System.out.println(prefix + ": " + s); int labels = labels(); for (int i = 0; i < labels; i++) System.out.print(offset(i) + " "); System.out.println(""); for (int i = 0; name != null && i < name.length; i++) System.out.print((name[i] & 0xFF) + " "); System.out.println(""); } private final void setoffset(int n, int offset) { if (n >= MAXOFFSETS) return; int shift = 8 * (7 - n); offsets &= (~(0xFFL << shift)); offsets |= ((long)offset << shift); } private final int offset(int n) { if (n == 0 && getlabels() == 0) return 0; if (n < 0 || n >= getlabels()) throw new IllegalArgumentException("label out of range"); if (n < MAXOFFSETS) { int shift = 8 * (7 - n); return ((int)(offsets >>> shift) & 0xFF); } else { int pos = offset(MAXOFFSETS - 1); for (int i = MAXOFFSETS - 1; i < n; i++) pos += (name[pos] + 1); return (pos); } } private final void setlabels(int labels) { offsets &= ~(0xFF); offsets |= labels; } private final int getlabels() { return (int)(offsets & 0xFF); } private static final void copy(Name src, Name dst) { if (src.offset(0) == 0) { dst.name = src.name; dst.offsets = src.offsets; } else { int offset0 = src.offset(0); int namelen = src.name.length - offset0; int labels = src.labels(); dst.name = new byte[namelen]; System.arraycopy(src.name, offset0, dst.name, 0, namelen); for (int i = 0; i < labels && i < MAXOFFSETS; i++) dst.setoffset(i, src.offset(i) - offset0); dst.setlabels(labels); } } private final void append(byte [] array, int start, int n) throws NameTooLongException { int length = (name == null ? 0 : (name.length - offset(0))); int alength = 0; for (int i = 0, pos = start; i < n; i++) { int len = array[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); len++; pos += len; alength += len; } int newlength = length + alength; if (newlength > MAXNAME) throw new NameTooLongException(); int labels = getlabels(); int newlabels = labels + n; if (newlabels > MAXLABELS) throw new IllegalStateException("too many labels"); byte [] newname = new byte[newlength]; if (length != 0) System.arraycopy(name, offset(0), newname, 0, length); System.arraycopy(array, start, newname, length, alength); name = newname; for (int i = 0, pos = length; i < n; i++) { setoffset(labels + i, pos); pos += (newname[pos] + 1); } setlabels(newlabels); } private static TextParseException parseException(String str, String message) { return new TextParseException("'" + str + "': " + message); } private final void appendFromString(String fullName, byte [] array, int start, int n) throws TextParseException { try { append(array, start, n); } catch (NameTooLongException e) { throw parseException(fullName, "Name too long"); } } private final void appendSafe(byte [] array, int start, int n) { try { append(array, start, n); } catch (NameTooLongException e) { } } /** * Create a new name from a string and an origin. This does not automatically * make the name absolute; it will be absolute if it has a trailing dot or an * absolute origin is appended. * @param s The string to be converted * @param origin If the name is not absolute, the origin to be appended. * @throws TextParseException The name is invalid. */ public Name(String s, Name origin) throws TextParseException { if (s.equals("")) throw parseException(s, "empty name"); else if (s.equals("@")) { if (origin == null) copy(empty, this); else copy(origin, this); return; } else if (s.equals(".")) { copy(root, this); return; } int labelstart = -1; int pos = 1; byte [] label = new byte[MAXLABEL + 1]; boolean escaped = false; int digits = 0; int intval = 0; boolean absolute = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw parseException(s, "bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw parseException(s, "bad escape"); if (pos > MAXLABEL) throw parseException(s, "label too long"); labelstart = pos; label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw parseException(s, "invalid empty label"); label[0] = (byte)(pos - 1); appendFromString(s, label, 0, 1); labelstart = -1; pos = 1; } else { if (labelstart == -1) labelstart = i; if (pos > MAXLABEL) throw parseException(s, "label too long"); label[pos++] = b; } } if (digits > 0 && digits < 3) throw parseException(s, "bad escape"); if (escaped) throw parseException(s, "bad escape"); if (labelstart == -1) { appendFromString(s, emptyLabel, 0, 1); absolute = true; } else { label[0] = (byte)(pos - 1); appendFromString(s, label, 0, 1); } if (origin != null && !absolute) appendFromString(s, origin.name, 0, origin.getlabels()); } /** * Create a new name from a string. This does not automatically make the name * absolute; it will be absolute if it has a trailing dot. * @param s The string to be converted * @throws TextParseException The name is invalid. */ public Name(String s) throws TextParseException { this(s, null); } /** * Create a new name from a string and an origin. This does not automatically * make the name absolute; it will be absolute if it has a trailing dot or an * absolute origin is appended. This is identical to the constructor, except * that it will avoid creating new objects in some cases. * @param s The string to be converted * @param origin If the name is not absolute, the origin to be appended. * @throws TextParseException The name is invalid. */ public static Name fromString(String s, Name origin) throws TextParseException { if (s.equals("@") && origin != null) return origin; else if (s.equals(".")) return (root); return new Name(s, origin); } /** * Create a new name from a string. This does not automatically make the name * absolute; it will be absolute if it has a trailing dot. This is identical * to the constructor, except that it will avoid creating new objects in some * cases. * @param s The string to be converted * @throws TextParseException The name is invalid. */ public static Name fromString(String s) throws TextParseException { return fromString(s, null); } public static Name fromConstantString(String s) { try { return fromString(s, null); } catch (TextParseException e) { throw new IllegalArgumentException("Invalid name '" + s + "'"); } } /** * Create a new name from DNS a wire format message * @param in A stream containing the DNS message which is currently * positioned at the start of the name to be read. */ public Name(DNSInput in) throws WireParseException { int len, pos, currentpos; Name name2; boolean done = false; byte [] label = new byte[MAXLABEL + 1]; boolean savedState = false; while (!done) { len = in.readU8(); switch (len & LABEL_MASK) { case LABEL_NORMAL: if (getlabels() >= MAXLABELS) throw new WireParseException("too many labels"); if (len == 0) { append(emptyLabel, 0, 1); done = true; } else { label[0] = (byte)len; in.readByteArray(label, 1, len); append(label, 0, 1); } break; case LABEL_COMPRESSION: pos = in.readU8(); pos += ((len & ~LABEL_MASK) << 8); if (Options.check("verbosecompression")) System.err.println("currently " + in.current() + ", pointer to " + pos); if (pos >= in.current()) throw new WireParseException("bad compression"); if (!savedState) { in.save(); savedState = true; } in.jump(pos); if (Options.check("verbosecompression")) System.err.println("current name '" + this + "', seeking to " + pos); continue; } } if (savedState) { in.restore(); } } /** * Create a new name from DNS wire format * @param b A byte array containing the wire format of the name. */ public Name(byte [] b) throws IOException { this(new DNSInput(b)); } /** * Create a new name by removing labels from the beginning of an existing Name * @param src An existing Name * @param n The number of labels to remove from the beginning in the copy */ public Name(Name src, int n) { int slabels = src.labels(); if (n > slabels) throw new IllegalArgumentException("attempted to remove too " + "many labels"); name = src.name; setlabels(slabels - n); for (int i = 0; i < MAXOFFSETS && i < slabels - n; i++) setoffset(i, src.offset(i + n)); } /** * Creates a new name by concatenating two existing names. * @param prefix The prefix name. * @param suffix The suffix name. * @return The concatenated name. * @throws NameTooLongException The name is too long. */ public static Name concatenate(Name prefix, Name suffix) throws NameTooLongException { if (prefix.isAbsolute()) return (prefix); Name newname = new Name(); copy(prefix, newname); newname.append(suffix.name, suffix.offset(0), suffix.getlabels()); return newname; } /** * If this name is a subdomain of origin, return a new name relative to * origin with the same value. Otherwise, return the existing name. * @param origin The origin to remove. * @return The possibly relativized name. */ public Name relativize(Name origin) { if (origin == null || !subdomain(origin)) return this; Name newname = new Name(); copy(this, newname); int length = length() - origin.length(); int labels = newname.labels() - origin.labels(); newname.setlabels(labels); newname.name = new byte[length]; System.arraycopy(name, offset(0), newname.name, 0, length); return newname; } /** * Generates a new Name with the first n labels replaced by a wildcard * @return The wildcard name */ public Name wild(int n) { if (n < 1) throw new IllegalArgumentException("must replace 1 or more " + "labels"); try { Name newname = new Name(); copy(wild, newname); newname.append(name, offset(n), getlabels() - n); return newname; } catch (NameTooLongException e) { throw new IllegalStateException ("Name.wild: concatenate failed"); } } /** * Generates a new Name to be used when following a DNAME. * @param dname The DNAME record to follow. * @return The constructed name. * @throws NameTooLongException The resulting name is too long. */ public Name fromDNAME(DNAMERecord dname) throws NameTooLongException { Name dnameowner = dname.getName(); Name dnametarget = dname.getTarget(); if (!subdomain(dnameowner)) return null; int plabels = labels() - dnameowner.labels(); int plength = length() - dnameowner.length(); int pstart = offset(0); int dlabels = dnametarget.labels(); int dlength = dnametarget.length(); if (plength + dlength > MAXNAME) throw new NameTooLongException(); Name newname = new Name(); newname.setlabels(plabels + dlabels); newname.name = new byte[plength + dlength]; System.arraycopy(name, pstart, newname.name, 0, plength); System.arraycopy(dnametarget.name, 0, newname.name, plength, dlength); for (int i = 0, pos = 0; i < MAXOFFSETS && i < plabels + dlabels; i++) { newname.setoffset(i, pos); pos += (newname.name[pos] + 1); } return newname; } /** * Is this name a wildcard? */ public boolean isWild() { if (labels() == 0) return false; return (name[0] == (byte)1 && name[1] == (byte)'*'); } /** * Is this name absolute? */ public boolean isAbsolute() { if (labels() == 0) return false; return (name[name.length - 1] == 0); } /** * The length of the name. */ public short length() { if (getlabels() == 0) return 0; return (short)(name.length - offset(0)); } /** * The number of labels in the name. */ public int labels() { return getlabels(); } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { int labels = labels(); int dlabels = domain.labels(); if (dlabels > labels) return false; if (dlabels == labels) return equals(domain); return domain.equals(name, offset(labels - dlabels)); } private String byteString(byte [] array, int pos) { StringBuffer sb = new StringBuffer(); int len = array[pos++]; for (int i = pos; i < pos + len; i++) { int b = array[i] & 0xFF; if (b <= 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == '(' || b == ')' || b == '.' || b == ';' || b == '\\' || b == '@' || b == '$') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } return sb.toString(); } /** * Convert a Name to a String * @return The representation of this name as a (printable) String. */ public String toString() { int labels = labels(); if (labels == 0) return "@"; else if (labels == 1 && name[offset(0)] == 0) return "."; StringBuffer sb = new StringBuffer(); for (int i = 0, pos = offset(0); i < labels; i++) { int len = name[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); if (len == 0) break; sb.append(byteString(name, pos)); sb.append('.'); pos += (1 + len); } if (!isAbsolute()) sb.deleteCharAt(sb.length() - 1); return sb.toString(); } /** * Retrieve the nth label of a Name. This makes a copy of the label; changing * this does not change the Name. * @param n The label to be retrieved. The first label is 0. */ public byte [] getLabel(int n) { int pos = offset(n); byte len = (byte)(name[pos] + 1); byte [] label = new byte[len]; System.arraycopy(name, pos, label, 0, len); return label; } /** * Convert the nth label in a Name to a String * @param n The label to be converted to a (printable) String. The first * label is 0. */ public String getLabelString(int n) { int pos = offset(n); return byteString(name, pos); } public void toWire(DNSOutput out, Compression c) { if (!isAbsolute()) throw new IllegalArgumentException("toWire() called on " + "non-absolute name"); int labels = labels(); for (int i = 0; i < labels - 1; i++) { Name tname; if (i == 0) tname = this; else tname = new Name(this, i); int pos = -1; if (c != null) pos = c.get(tname); if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeU16(pos); return; } else { if (c != null) c.add(out.current(), tname); int off = offset(i); out.writeByteArray(name, off, name[off] + 1); } } out.writeU8(0); } public byte [] toWire() { DNSOutput out = new DNSOutput(); toWire(out, null); return out.toByteArray(); } /** * Emit a Name in canonical DNS wire format (all lowercase) * @param out The output stream to which the message is written. */ public void toWireCanonical(DNSOutput out) { byte [] b = toWireCanonical(); out.writeByteArray(b); } /** * Emit a Name in canonical DNS wire format (all lowercase) * @return The canonical form of the name. */ public byte [] toWireCanonical() { int labels = labels(); if (labels == 0) return (new byte[0]); byte [] b = new byte[name.length - offset(0)]; for (int i = 0, spos = offset(0), dpos = 0; i < labels; i++) { int len = name[spos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); b[dpos++] = name[spos++]; for (int j = 0; j < len; j++) b[dpos++] = lowercase[(name[spos++] & 0xFF)]; } return b; } public void toWire(DNSOutput out, Compression c, boolean canonical) { if (canonical) toWireCanonical(out); else toWire(out, c); } private final boolean equals(byte [] b, int bpos) { int labels = labels(); for (int i = 0, pos = offset(0); i < labels; i++) { if (name[pos] != b[bpos]) return false; int len = name[pos++]; bpos++; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); for (int j = 0; j < len; j++) if (lowercase[(name[pos++] & 0xFF)] != lowercase[(b[bpos++] & 0xFF)]) return false; } return true; } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == this) return true; if (arg == null || !(arg instanceof Name)) return false; Name d = (Name) arg; if (d.hashcode == 0) d.hashCode(); if (hashcode == 0) hashCode(); if (d.hashcode != hashcode) return false; if (d.labels() != labels()) return false; return equals(d.name, d.offset(0)); } /** * Computes a hashcode based on the value */ public int hashCode() { if (hashcode != 0) return (hashcode); int code = 0; for (int i = offset(0); i < name.length; i++) code += ((code << 3) + lowercase[(name[i] & 0xFF)]); hashcode = code; return hashcode; } /** * Compares this Name to another Object. * @param o The Object to be compared. * @return The value 0 if the argument is a name equivalent to this name; * a value less than 0 if the argument is less than this name in the canonical * ordering, and a value greater than 0 if the argument is greater than this * name in the canonical ordering. * @throws ClassCastException if the argument is not a Name. */ public int compareTo(Object o) { Name arg = (Name) o; if (this == arg) return (0); int labels = labels(); int alabels = arg.labels(); int compares = labels > alabels ? alabels : labels; for (int i = 1; i <= compares; i++) { int start = offset(labels - i); int astart = arg.offset(alabels - i); int length = name[start]; int alength = arg.name[astart]; for (int j = 0; j < length && j < alength; j++) { int n = lowercase[(name[j + start + 1]) & 0xFF] - lowercase[(arg.name[j + astart + 1]) & 0xFF]; if (n != 0) return (n); } if (length != alength) return (length - alength); } return (labels - alabels); } }
package org.xbill.DNS; import java.io.*; import java.util.*; /** * A DNS Zone. This encapsulates all data related to a Zone, and provides * convenient lookup methods. * * @author Brian Wellington */ public class Zone extends NameSet { class ZoneIterator implements Iterator { private Iterator znames; private Name nextName; private Object [] current; int count; boolean wantLastSOA; ZoneIterator(boolean axfr) { znames = names(); wantLastSOA = axfr; Object [] sets = findExactSets(origin); current = new Object[sets.length]; for (int i = 0, j = 2; i < sets.length; i++) { int type = ((RRset) sets[i]).getType(); if (type == Type.SOA) current[0] = sets[i]; else if (type == Type.NS) current[1] = sets[i]; else current[j++] = sets[i]; } } public boolean hasNext() { return (current != null || wantLastSOA); } public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } if (current == null && wantLastSOA) { wantLastSOA = false; return (RRset) findExactSet(origin, Type.SOA); } Object set = current[count++]; if (count == current.length) { nextName = null; current = null; while (znames.hasNext()) { Name name = (Name) znames.next(); if (name.equals(origin)) continue; Object [] sets = findExactSets(name); if (sets.length == 0) continue; nextName = name; current = sets; count = 0; break; } } return set; } public void remove() { throw new UnsupportedOperationException(); } } /** A primary zone */ public static final int PRIMARY = 1; /** A secondary zone */ public static final int SECONDARY = 2; private int type; private Name origin; private int dclass = DClass.IN; private RRset NS; private SOARecord SOA; private boolean hasWild; private void validate() throws IOException { RRset rrset = (RRset) findExactSet(origin, Type.SOA); if (rrset == null || rrset.size() != 1) throw new IOException(origin + ": exactly 1 SOA must be specified"); Iterator it = rrset.rrs(); SOA = (SOARecord) it.next(); NS = (RRset) findExactSet(origin, Type.NS); if (NS == null) throw new IOException(origin + ": no NS set specified"); } private final void maybeAddRecord(Record record, Cache cache, Object source) throws IOException { int type = record.getType(); Name name = record.getName(); if (origin == null) { if (type == Type.SOA) { origin = name; setOrigin(origin); } else { throw new IOException("non-SOA record seen at " + name + " with no origin set"); } } if (type == Type.SOA && !name.equals(origin)) { throw new IOException("SOA owner " + name + " does not match zone origin " + origin); } if (name.subdomain(origin)) addRecord(record); else if (cache != null) cache.addRecord(record, Credibility.GLUE, source); } /** * Creates a Zone from the records in the specified master file. All * records that do not belong in the Zone are added to the specified Cache. * @see Cache * @see Master */ public Zone(String file, Cache cache, Name initialOrigin) throws IOException { super(false); Master m = new Master(file, initialOrigin); Record record; origin = initialOrigin; while ((record = m.nextRecord()) != null) maybeAddRecord(record, cache, file); validate(); } /** * Creates a Zone from an array of records. All records that do not belong * in the Zone are added to the specified Cache. * @see Cache * @see Master */ public Zone(Record [] records, Cache cache, Name initialOrigin) throws IOException { super(false); origin = initialOrigin; for (int i = 0; i < records.length; i++) { maybeAddRecord(records[i], cache, records); } validate(); } /** * Creates a Zone from the records in the specified master file. All * records that do not belong in the Zone are added to the specified Cache. * @see Cache * @see Master */ public Zone(String file, Cache cache) throws IOException { this(file, cache, null); } public void fromXFR(Name zone, int dclass, String remote) throws IOException, ZoneTransferException { if (!zone.isAbsolute()) throw new RelativeNameException(zone); DClass.check(dclass); origin = zone; this.dclass = dclass; type = SECONDARY; ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(zone, remote, null); List records = xfrin.run(); for (Iterator it = records.iterator(); it.hasNext(); ) { Record rec = (Record) it.next(); if (!rec.getName().subdomain(origin)) { if (Options.check("verbose")) System.err.println(rec.getName() + "is not in zone " + origin); continue; } addRecord(rec); } validate(); } /** * Creates a Zone by performing a zone transfer to the specified host. * @see Master */ public Zone(Name zone, int dclass, String remote) throws IOException, ZoneTransferException { super(false); fromXFR(zone, dclass, remote); } /** * Creates a Zone by performing a zone transfer to the specified host. * The cache is unused. * @see Master */ public Zone(Name zone, int dclass, String remote, Cache cache) throws IOException { super(false); DClass.check(dclass); try { fromXFR(zone, dclass, remote); } catch (ZoneTransferException e) { throw new IOException(e.getMessage()); } } /** Returns the Zone's origin */ public Name getOrigin() { return origin; } /** Returns the Zone origin's NS records */ public RRset getNS() { return NS; } /** Returns the Zone's SOA record */ public SOARecord getSOA() { return SOA; } /** Returns the Zone's class */ public int getDClass() { return dclass; } /** * Looks up Records in the Zone. This follows CNAMEs and wildcards. * @param name The name to look up * @param type The type to look up * @return A SetResponse object * @see SetResponse */ public SetResponse findRecords(Name name, int type) { SetResponse zr = null; Object o = lookup(name, type); if (o == null) { /* The name does not exist */ if (name.isWild() || !hasWild) return SetResponse.ofType(SetResponse.NXDOMAIN); int labels = name.labels() - origin.labels(); SetResponse sr; Name tname = name; do { sr = findRecords(tname.wild(1), type); if (!sr.isNXDOMAIN()) return sr; tname = new Name(tname, 1); } while (labels return SetResponse.ofType(SetResponse.NXDOMAIN); } else if (o == NXRRSET) { /* The name exists but the type does not. */ return SetResponse.ofType(SetResponse.NXRRSET); } Object [] objects; RRset rrset; if (o instanceof RRset) { objects = null; rrset = (RRset) o; } else { objects = (Object []) o; rrset = (RRset) objects[0]; } if (name.equals(rrset.getName())) { if (type != Type.CNAME && type != Type.ANY && rrset.getType() == Type.CNAME) zr = new SetResponse(SetResponse.CNAME, rrset); else if (rrset.getType() == Type.NS && !name.equals(origin)) zr = new SetResponse(SetResponse.DELEGATION, rrset); else { zr = new SetResponse(SetResponse.SUCCESSFUL); zr.addRRset(rrset); if (objects != null) { for (int i = 1; i < objects.length; i++) zr.addRRset((RRset)objects[i]); } } } else { if (rrset.getType() == Type.CNAME) zr = SetResponse.ofType(SetResponse.NXDOMAIN); else if (rrset.getType() == Type.DNAME) zr = new SetResponse(SetResponse.DNAME, rrset); else if (rrset.getType() == Type.NS) zr = new SetResponse(SetResponse.DELEGATION, rrset); } return zr; } /** * Looks up Records in the zone, finding exact matches only. * @param name The name to look up * @param type The type to look up * @return The matching RRset * @see RRset */ public RRset findExactMatch(Name name, int type) { return (RRset) findExactSet(name, type); } /** * Adds a record to the Zone * @param r The record to be added * @see Record */ public void addRecord(Record r) { Name name = r.getName(); int type = r.getRRsetType(); RRset rrset = (RRset) findExactSet (name, type); if (rrset == null) addSet(name, type, rrset = new RRset()); rrset.addRR(r); } /** * Adds a set associated with a name/type. The data contained in the * set is abstract. */ protected void addSet(Name name, int type, TypedObject set) { if (!hasWild && name.isWild()) hasWild = true; super.addSet(name, type, set); } /** * Removes a record from the Zone * @param r The record to be removed * @see Record */ public void removeRecord(Record r) { Name name = r.getName(); int type = r.getRRsetType(); RRset rrset = (RRset) findExactSet (name, type); if (rrset != null) { rrset.deleteRR(r); if (rrset.size() == 0) removeSet(name, type, rrset); } } /** * Returns an Iterator over the RRsets in the zone. */ public Iterator iterator() { return new ZoneIterator(false); } /** * Returns an Iterator over the RRsets in the zone that can be used to * construct an AXFR response. This is identical to {@link #iterator} except * that the SOA is returned at the end as well as the beginning. */ public Iterator AXFR() { return new ZoneIterator(true); } /** * Returns the contents of a Zone in master file format. */ public String toMasterFile() { Iterator znames = names(); StringBuffer sb = new StringBuffer(); while (znames.hasNext()) { Name name = (Name) znames.next(); Object [] sets = findExactSets(name); for (int i = 0; i < sets.length; i++) { RRset rrset = (RRset) sets[i]; Iterator it = rrset.rrs(); while (it.hasNext()) sb.append(it.next() + "\n"); it = rrset.sigs(); while (it.hasNext()) sb.append(it.next() + "\n"); } } return sb.toString(); } }
package com.fireflysource.net.http.client; import java.net.SocketAddress; import java.util.concurrent.CompletableFuture; /** * The HTTP client connection manager maintains the HTTP client connections. If it creates connection and negotiates the * HTTP version is 2.0, and it maintains only one connection to send the request and receive the response. * If the HTTP version is 1.1, it maintains the HTTP connections in a pool. * * @author Pengtao Qiu */ public interface HttpClientConnectionManager { /** * Get HTTP client connection. * * @param address The socket address. * @return The HTTP client connection. */ CompletableFuture<HttpClientConnection> getConnection(SocketAddress address); }
package com.fuelpowered.lib.fuelsdk.unity; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.fuelpowered.lib.fuelsdk.fuel; import com.fuelpowered.lib.fuelsdk.fuelbroadcastreceiver; import com.fuelpowered.lib.fuelsdk.fuelbroadcasttype; import com.fuelpowered.lib.fuelsdk.fuelcompeteui; import com.fuelpowered.lib.fuelsdk.fuelimpl.fueljsonhelper; import com.unity3d.player.UnityPlayer; import org.json.JSONObject; import java.util.Map; public class FuelSDKUnitySharedActivity { private static final String LOG_TAG = "FuelSDKUnitySharedActiv"; private static Activity sActivity; private static IntentFilter mIntentFilter; public static void onCreate(Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreate()"); sActivity = UnityPlayer.currentActivity; Log.d(LOG_TAG, sActivity.getLocalClassName()); fuel.onCreate(sActivity); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_VG_LIST.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_VG_ROLLBACK.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_NOTIFICATION_ENABLED.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_NOTIFICATION_DISABLED.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_SOCIAL_LOGIN_REQUEST.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_SOCIAL_INVITE_REQUEST.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_SOCIAL_SHARE_REQUEST.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_IMPLICIT_LAUNCH_REQUEST.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_USER_VALUES.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_COMPETE_CHALLENGE_COUNT.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_COMPETE_TOURNAMENT_INFO.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_COMPETE_EXIT.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_COMPETE_MATCH.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_COMPETE_FAIL.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_IGNITE_EVENTS.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_IGNITE_LEADERBOARD.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_IGNITE_MISSION.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_IGNITE_QUEST.toString()); mIntentFilter.addAction(fuelbroadcasttype.FSDK_BROADCAST_IGNITE_JOIN_EVENT.toString()); } public static void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(LOG_TAG, "onActivityResult()"); fuel.onActivityResult(sActivity, requestCode, resultCode, data); } public static void onResume() { Log.d(LOG_TAG, "onResume()"); LocalBroadcastManager.getInstance(sActivity).registerReceiver( sBroadcastReceiver, mIntentFilter); fuel.onResume(sActivity); } public static void onPause() { Log.d(LOG_TAG, "onPause()"); LocalBroadcastManager.getInstance(sActivity).unregisterReceiver(sBroadcastReceiver); fuel.onPause(sActivity); } private static fuelbroadcastreceiver sBroadcastReceiver = new fuelbroadcastreceiver() { @SuppressWarnings("unchecked") @Override public void onReceive(Context context, String action, Map<String, Object> data) { String message = null; JSONObject jsonObject = new JSONObject(); if (data == null) { message = "{\"action\": \""+action+"\" , \"data\" : \"{}\"}"; } else { try { jsonObject.put( "action" , action ); jsonObject.put("data", fueljsonhelper.sharedInstance().toJSONObject(data) ); message = jsonObject.toString(); } catch (Exception exception) { Log.w(LOG_TAG, "Exception in processing broadcast message: " + exception.getMessage()); } } UnityPlayer.UnitySendMessage("FuelSDK", "DataReceiver", message); } }; }
package com.airhacks.headlands.notifications.boundary; import com.airhacks.headlands.notifications.entity.CacheChangedEvent; import java.io.IOException; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.ConcurrencyManagement; import javax.ejb.ConcurrencyManagementType; import javax.ejb.Singleton; import javax.enterprise.event.Observes; import javax.json.JsonArray; import javax.websocket.EncodeException; import javax.websocket.OnClose; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; /** * * @author airhacks.com */ @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) @ServerEndpoint(value = "/firehose/{cache-name}", encoders = JsonArrayEncoder.class) public class WebSocketFirehose { CopyOnWriteArrayList<Session> sessions; @PostConstruct public void init() { this.sessions = new CopyOnWriteArrayList<>(); } @OnOpen public void onConnect(Session session, @PathParam("cache-name") String cacheName) { System.out.println("uri: " + session.getRequestURI().toString()); this.sessions.add(session); } @OnClose public void onClose(Session session) { this.sessions.remove(session); } public void onChange(@Observes CacheChangedEvent event) { JsonArray payload = event.getPayload(); sessions.stream(). filter(s -> s.isOpen()). filter(s -> s.getRequestURI().toString().endsWith("*") || s.getRequestURI().toString().endsWith(event.getCacheName())). forEach(s -> this.send(s, payload)); } void send(Session session, JsonArray payload) { try { session.getBasicRemote().sendObject(payload); } catch (IOException | EncodeException ex) { Logger.getLogger(WebSocketFirehose.class.getName()).log(Level.SEVERE, null, ex); } } @PreDestroy public void shutdown() { this.sessions.forEach(s -> { try { s.close(); } catch (IOException ex) { Logger.getLogger(WebSocketFirehose.class.getName()).log(Level.SEVERE, null, ex); } }); } }
package net.fortuna.ical4j.model; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import net.fortuna.ical4j.model.parameter.Value; /** * Defines a list of iCalendar dates. * * @author Ben Fortuna */ public class DateList extends ArrayList implements Serializable { private static final long serialVersionUID = 5925108767897130313L; private Value type; private boolean utc; /** * Default constructor. * * @param aType * specifies the type of dates (either date or date-time) */ public DateList(final Value aType) { this.type = aType; } /** * Parses the specified string representation to create a list of dates. * * @param aValue * a string representation of a list of dates * @param aType * specifies the type of dates (either date or date-time) * @throws ParseException * if an invalid date representation exists in the date list * string */ public DateList(final String aValue, final Value aType) throws ParseException { this.type = aType; for (StringTokenizer t = new StringTokenizer(aValue, ","); t .hasMoreTokens();) { if (type != null && Value.DATE.equals(type)) { add(new Date(t.nextToken())); } else { add(new DateTime(t.nextToken())); } } } /** * Constructs a new date list of the specified type containing * the dates in the specified list. * @param list a list of dates to include in the new list * @param type the type of the new list */ public DateList(final DateList list, final Value type) { if (!Value.DATE.equals(type) && !Value.DATE_TIME.equals(type)) { throw new IllegalArgumentException( "Type must be either DATE or DATE-TIME"); } this.type = type; if (Value.DATE.equals(type)) { for (Iterator i = list.iterator(); i.hasNext();) { add(new Date((Date) i.next())); } } else if (Value.DATE_TIME.equals(type)) { for (Iterator i = list.iterator(); i.hasNext();) { add(new DateTime((Date) i.next())); } } } /** * @see java.util.AbstractCollection#toString() */ public final String toString() { StringBuffer b = new StringBuffer(); for (Iterator i = iterator(); i.hasNext();) { /* * if (type != null && Value.DATE.equals(type)) { * b.append(DateFormat.getInstance().format((Date) i.next())); } * else { b.append(DateTimeFormat.getInstance().format((Date) * i.next(), isUtc())); } */ b.append(i.next()); if (i.hasNext()) { b.append(','); } } return b.toString(); } /** * Add a date to the list. * * @param date * the date to add * @return true * @see List#add(java.lang.Object) */ public final boolean add(final Date date) { if (Value.DATE_TIME.equals(getType()) && !(date instanceof DateTime)) { return add((Object) new DateTime(date)); } return add((Object) date); } public final boolean add(final Object arg0) { if (!(arg0 instanceof Date)) { throw new IllegalArgumentException("Argument not a " + Date.class.getName()); } return super.add(arg0); } /** * Remove a date from the list * * @param date * the date to remove * @return true if the list contained the specified date * @see List#remove(java.lang.Object) */ public final boolean remove(final Date date) { return remove((Object) date); } /** * Returns the VALUE parameter specifying the type of dates (ie. date or * date-time) stored in this date list. * * @return Returns a Value parameter. */ public final Value getType() { return type; } /** * Indicates whether this list is in local or UTC format. This property will * have no affect if the type of the list is not DATE-TIME. * * @return Returns true if in UTC format, otherwise false. */ public final boolean isUtc() { return utc; } /** * Sets whether this list is in UTC or local time format. * * @param utc * The utc to set. */ public final void setUtc(final boolean utc) { if (Value.DATE_TIME.equals(type)) { for (Iterator i = iterator(); i.hasNext();) { ((DateTime) i.next()).setUtc(utc); } } this.utc = utc; } }
package com.puresol.osgi; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.log4j.Logger; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.launch.Framework; import org.osgi.framework.launch.FrameworkFactory; import com.puresol.ListenerSet; import com.puresol.utils.JARUtilities; /** * This is a small wrapper and utility class for starting and using a OSGi * framework. * * @author Rick-Rainer Ludwig * */ public class OSGi { private static final Logger logger = Logger.getLogger(OSGi.class); /** * This is the resource path for the class name of the OSGi framework * factory. */ public static final String OSGI_FRAMEWORK_FACTORY_PROPERTIES = "/META-INF/services/org.osgi.framework.launch.FrameworkFactory"; /** * This is the resource path to an additional properties file which defines * some options for framework startup. */ public static final String OSGI_PROPERTIES = "/META-INF/services/osgi.properties"; private final Map<String, Object> configuration = new HashMap<String, Object>(); private Framework framework = null; private BundleContext context = null; private final ListenerSet<OSGiFrameworkListener> frameworkListeners = new ListenerSet<OSGiFrameworkListener>(); /** * Used to force this class into singleton pattern. */ public OSGi() { loadConfiguration(); } public OSGi(Properties properties) { setConfiguration(properties); } public OSGi(Map<String, Object> configuration) { setConfiguration(configuration); } private void setConfiguration(Map<String, Object> configuration) { this.configuration.putAll(configuration); } private void setConfiguration(Properties properties) { for (Object key : properties.keySet()) { String value = (String) properties.get(key); logger.debug("OSGi setting: " + key.toString() + " --> " + value); configuration.put((String) key, value); } } public synchronized void start() throws OSGiException, BundleException { logger.info("Starting OSGi framework..."); preStart(); actualStart(); postStart(); logger.info("OSGi framework started."); logger.info("Bundle directory is '" + context.getProperty("org.osgi.framework.storage") + "'"); } private void preStart() { for (OSGiFrameworkListener listener : frameworkListeners) { listener.preStart(); } } private void actualStart() throws OSGiException, BundleException { FrameworkFactory factory = getFrameworkFactory(); framework = factory.newFramework(configuration); framework.start(); context = framework.getBundleContext(); } private void postStart() { for (OSGiFrameworkListener listener : frameworkListeners) { listener.postStart(); } } private void loadConfiguration() { try { Properties props = JARUtilities.readPropertyFile(getClass() .getResource(OSGi.OSGI_PROPERTIES)); setConfiguration(props); } catch (IOException e) { logger.warn("No '" + OSGI_PROPERTIES + "' file was found. Defaults from OSGi framework will be used!"); return; } } private FrameworkFactory getFrameworkFactory() throws OSGiException { try { return (FrameworkFactory) Class.forName( getFrameworkFactoryClassName()).newInstance(); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } throw new OSGiException("Could not load framework factory."); } private String getFrameworkFactoryClassName() throws OSGiException { URL url = getFrameworkFactoryConfigurationResource(); return readFrameworkFactoryClassName(url); } private URL getFrameworkFactoryConfigurationResource() { URL url = getClass().getResource(OSGI_FRAMEWORK_FACTORY_PROPERTIES); if (url == null) { throw new RuntimeException("Resource " + OSGI_FRAMEWORK_FACTORY_PROPERTIES + " is not available. " + "The resource is essential for defining the framework!"); } return url; } private String readFrameworkFactoryClassName(URL url) throws OSGiException { try { BufferedReader br = new BufferedReader(new InputStreamReader( url.openStream())); try { for (String s = br.readLine(); s != null; s = br.readLine()) { s = s.trim(); logger.info("Found class for OSGi FrameworkFactory in " + "'META-INF/services/org.osgi.framework.launch.FrameworkFactory': '" + s + "'"); logger.info("Creating instance..."); // Try to load first non-empty, non-commented line. if ((s.length() > 0) && (s.charAt(0) != ' return s; } } } finally { br.close(); } } catch (IOException e) { logger.error(e.getMessage(), e); } throw new OSGiException("Could not load framework factory."); } public synchronized void stop() throws BundleException { if (framework == null) { return; } logger.info("Stopping OSGi framework..."); preStop(); actualStop(); postStop(); logger.info("OSGi framework stopped."); } private void preStop() { for (OSGiFrameworkListener listener : frameworkListeners) { listener.preStop(); } } private void actualStop() throws BundleException { context = null; framework.stop(); framework = null; } private void postStop() { for (OSGiFrameworkListener listener : frameworkListeners) { listener.postStop(); } } /** * This method returns the frameworks BundleContext. * * @return The bundle context is returned. */ public BundleContext getContext() { return context; } public boolean isStarted() { return (context != null); } public void addOSGiFrameworkListener(OSGiFrameworkListener listener) { frameworkListeners.add(listener); } public void removeOSGiFrameworkListener(OSGiFrameworkListener listener) { frameworkListeners.remove(listener); } }
package com.raizlabs.graphics.drawable.async; import java.lang.ref.WeakReference; import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.widget.ImageView; /** * Base class which can be used for easy implementation of an * {@link AsyncDrawableTask}. Allows for different {@link Drawable}s * to be shown for the cancelled and loading states. * * @author Dylan James * * @param <T> The type of the key used to identify an {@link AsyncDrawableTask} * and whether it is trying to accomplish the same thing as another instance. */ public abstract class BaseAsyncDrawableTask<T> implements AsyncDrawableTask<T> { private boolean cancelled = false; @Override public boolean isCancelled() { synchronized (this) { return cancelled; } } private boolean completed = false; @Override public boolean isCompleted() { synchronized (this) { return completed; } } @Override public void cancel() { synchronized (this) { cancelled = true; // If this task isn't finished, update the drawable // to the cancelled drawable if (!completed && wrapper.getView() != null) { wrapper.update(getCancelledDrawable(), true); } } onCancel(); } /** * Wrapper for our current view to abstract the type */ private ViewWrapper wrapper; protected View getView() { return wrapper.getView(); } /** * Constructs a {@link BaseAsyncDrawableTask} which binds to the given * {@link ImageView}. * @param imageView The image view to bind to. */ public BaseAsyncDrawableTask(ImageView imageView) { // Wrap the view up with a wrapper which sets the image wrapper = new ImageWrapper(imageView); } /** * Constructs a {@link BaseAsyncDrawableTask} which binds to the given * {@link View} * @param view The view to bind to. */ public BaseAsyncDrawableTask(View view) { // Wrap the view up with a wrapper which sets the background wrapper = new BackgroundWrapper(view); } @Override public boolean bind() { // Attempt to cancel the existing work boolean cancelled = wrapper.cancelExistingWork(); // If we cancelled the work, set the loading drawable if (cancelled) { wrapper.update(getLoadingDrawable(), false); onBind(); } return cancelled; } @Override public void execute() { // Indicate that we haven't finished completed = false; // If our view is emptied, we can't do anything, abort if (wrapper.getView() == null) return; Drawable drawable = null; // If we aren't bound to the view, abort if (!wrapper.isBoundToView()) return; // If we aren't cancelled, start up the work if (!isCancelled()) { drawable = doExecute(); // Work has completed... synchronized (this) { // If we've been cancelled during the work, set the cancelled // drawable if (cancelled) { drawable = getCancelledDrawable(); } else { // Otherwise we completed successfully completed = true; } } } else { // We were cancelled, set the cancelled drawable drawable = getCancelledDrawable(); } // Push our new drawable through the wrapper, and ensure we are still bound wrapper.update(drawable, true); } /** * Interface which allows us to update different views polymorphically. * Wraps views of different types and interfaces with them appropriately. */ private interface ViewWrapper { /** * Updates the wrapped view to the given {@link Drawable}. * @param drawable The Drawable to update the view to show. * @param checkIfBound True to double check that the view is still * bound to our task */ void update(Drawable drawable, boolean checkIfBound); /** * Attempts to cancel the existing work associated with the view * @see AsyncDrawableUtils#cancelExistingWork(AsyncDrawableTask, ImageView) * @see AsyncDrawableUtils#cancelExistingWork(AsyncDrawableTask, View) * @return True if there was no work or the work was cancelled, false if * the work is already assigned to another task */ boolean cancelExistingWork(); /** * @return The view being wrapped by this wrapper. */ View getView(); /** * @return True if this task is still associated with the wrapped view. */ boolean isBoundToView(); } /** * {@link ViewWrapper} implementation which interfaces with the background * of a given view. */ private class BackgroundWrapper implements ViewWrapper { WeakReference<View> viewRef; /** * Constructs a {@link BackgroundWrapper} which wraps the given View. * @param view The View to wrap. */ public BackgroundWrapper(View view) { viewRef = new WeakReference<View>(view); } @Override public View getView() { return viewRef.get(); } @Override public boolean cancelExistingWork() { final View view = getView(); if (view == null) return false; return AsyncDrawableUtils.cancelExistingWork(BaseAsyncDrawableTask.this, view); } @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public void update(Drawable drawable, final boolean checkIfBound) { final View view = viewRef.get(); if (view != null) { // If we were told to check, only proceed if we are bound to the view if (!checkIfBound || isBoundToView(view)) { // Wrap the desired drawable in a wrapper that contains the information // about this task final Drawable newDrawable = new AsyncDrawableWrapper<T>(drawable, BaseAsyncDrawableTask.this); // Change the drawable on the UI thread view.post(new Runnable() { @Override public void run() { // Double check that we're still the bound task if (!checkIfBound || isBoundToView(view)) { // JellyBean+ deprecates setBackgroundDrawable if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.setBackground(newDrawable); } else { view.setBackgroundDrawable(newDrawable); } } } }); } } } @Override public boolean isBoundToView() { final View view = getView(); if (view == null) return false; return isBoundToView(view); } boolean isBoundToView(View view) { // We're bound if our task is the associated task return BaseAsyncDrawableTask.this.equals(AsyncDrawableUtils.getTask(view)); } } /** * {@link ViewWrapper} implementation which interfaces with the image * drawable of a given ImageView. */ private class ImageWrapper implements ViewWrapper { WeakReference<ImageView> viewRef; /** * Constructs a {@link BackgroundWrapper} which wraps the given ImageView. * @param imageView The ImageView to wrap. */ public ImageWrapper(ImageView imageView) { viewRef = new WeakReference<ImageView>(imageView); } @Override public View getView() { return viewRef.get(); } @Override public boolean cancelExistingWork() { ImageView view = viewRef.get(); if (view == null) return false; return AsyncDrawableUtils.cancelExistingWork(BaseAsyncDrawableTask.this, view); } @Override public void update(Drawable drawable, final boolean checkIfBound) { final ImageView view = viewRef.get(); if (view != null) { // If we were told to check, only proceed if we are bound to the view if (!checkIfBound || isBoundToView(view)) { // Wrap the desired drawable in a wrapper that contains the information // about this task final Drawable newDrawable = new AsyncDrawableWrapper<T>(drawable, BaseAsyncDrawableTask.this); // Change the drawable on the UI thread view.post(new Runnable() { @Override public void run() { // Double check that we're still the bound task if (!checkIfBound ||isBoundToView(view)) { view.setImageDrawable(newDrawable); } } }); } } } @Override public boolean isBoundToView() { ImageView view = viewRef.get(); if (view == null) return false; return isBoundToView(view); } boolean isBoundToView(ImageView imageView) { // We're bound if our task is the associated task return BaseAsyncDrawableTask.this.equals(AsyncDrawableUtils.getTask(imageView)); } } protected abstract void onBind(); protected abstract Drawable doExecute(); protected abstract Drawable getLoadingDrawable(); protected abstract Drawable getCancelledDrawable(); protected abstract void onCancel(); }
package org.bimserver.tools.generators; import java.io.File; import java.io.FileFilter; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.bimserver.shared.InterfaceList; import org.bimserver.shared.meta.SServicesMap; import org.codehaus.jettison.json.JSONException; public class CopyAdminAndBIMsieInterface { private static final File bootstrap = new File("D:\\git\\BootstrapBIM"); private static final File bimsie = new File("D:\\git\\BIMsie\\BIMsie\\BIMsie"); private static final File admin = new File("D:\\git\\BIMserver\\AdminGui");; public static void main(String[] args) { CopyAdminAndBIMsieInterface copyAdminAndBIMsieInterface = new CopyAdminAndBIMsieInterface(); copyAdminAndBIMsieInterface.copyAdminInterface(); copyAdminAndBIMsieInterface.copyBimsieInterface(); } private void copyBimsieInterface() { SServicesMap servicesMap = InterfaceList.createBimsie1SServicesMap(); try { FileUtils.writeStringToFile(new File(bimsie, "js/services.json"), servicesMap.toJson().toString(2)); } catch (JSONException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { FileUtils.copyFile(new File(bootstrap, "console.html"), new File(bimsie, "index.html")); FileUtils.copyDirectory(new File(bootstrap, "js"), new File(bimsie, "js"), new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getName().equals("settings.js") || pathname.getName().equals("consolesettings.js")) { return false; } return true; } }); FileUtils.copyDirectory(new File(bootstrap, "img"), new File(bimsie, "img"), new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getName().equals("consolelogo.png") || pathname.getName().equals("consolelogolarge.png")) { return false; } return true; } }); FileUtils.copyDirectory(new File(bootstrap, "css"), new File(bimsie, "css")); } catch (IOException e) { e.printStackTrace(); } } private void copyAdminInterface() { try { FileUtils.copyFileToDirectory(new File(bootstrap, "setup.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "header.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "index.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "login.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "basicserversettings.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "serversettings.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "serverinfo.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "plugins.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "console.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "extendeddataschemas.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "extendeddataschema.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "addnewextendeddataschema.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "addrepoextendeddataschema.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "main.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "migrations.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "webmodules.html"), admin); FileUtils.copyFileToDirectory(new File(bootstrap, "log.html"), admin); FileUtils.copyDirectory(new File(bootstrap, "js"), new File(admin, "js"), new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getName().equals("settings.js")) { return false; } return true; } }); FileUtils.copyDirectory(new File(bootstrap, "img"), new File(admin, "img")); FileUtils.copyDirectory(new File(bootstrap, "css"), new File(admin, "css"), new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getName().equals("bootstrap.min.css")) { return false; } return true; } }); } catch (IOException e) { e.printStackTrace(); } } }
package com.axelby.podax; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.content.Context; import android.database.Cursor; import android.util.Log; class PodcastDownloader { private Context _context; PodcastDownloader(Context context) { _context = context; } public void download(long podcastId) { if (!Helper.ensureWifi(_context)) return; Cursor cursor = null; try { String[] projection = { PodcastProvider.COLUMN_ID, PodcastProvider.COLUMN_TITLE, PodcastProvider.COLUMN_MEDIA_URL, PodcastProvider.COLUMN_FILE_SIZE, }; cursor = _context.getContentResolver().query(PodcastProvider.QUEUE_URI, projection, PodcastProvider.COLUMN_ID + " = ?", new String[] { String.valueOf(podcastId) }, null); if (!cursor.moveToNext()) return; PodcastCursor podcast = new PodcastCursor(cursor); if (podcast.isDownloaded()) return; File mediaFile = new File(podcast.getFilename()); Log.d("Podax", "Downloading " + podcast.getTitle()); HttpURLConnection c = openConnection(podcast, mediaFile); if (c == null) return; if (!downloadFile(c, mediaFile)) return; if (mediaFile.length() == c.getContentLength()) podcast.determineDuration(_context); // if there's no active podcast, this becomes active so tell the status to refresh PlayerStatus.refresh(_context); Log.d("Podax", "Done downloading " + podcast.getTitle()); } finally { if (cursor != null) cursor.close(); } } // returns null if connection should not be used (404, already downloaded, etc) private HttpURLConnection openConnection(PodcastCursor podcast, File mediaFile) { try { URL u = new URL(podcast.getMediaUrl()); HttpURLConnection c = (HttpURLConnection)u.openConnection(); if (mediaFile.exists() && mediaFile.length() > 0) c.setRequestProperty("Range", "bytes=" + mediaFile.length() + "-"); // response code 416 means range is invalid if (c.getResponseCode() == 416) { mediaFile.delete(); c = (HttpURLConnection)u.openConnection(); } // only valid response codes are 200 and 206 if (c.getResponseCode() != 200 && c.getResponseCode() != 206) return null; // response code 206 means partial content and range header worked if (c.getResponseCode() == 206) { // make sure there's more data to download if (c.getContentLength() <= 0) { podcast.setFileSize(_context, mediaFile.length()); return null; } } else { podcast.setFileSize(_context, c.getContentLength()); // all content returned so delete existing content mediaFile.delete(); } return c; } catch (IOException ex) { Log.e("Podax", "Unable to open connection to " + podcast.getMediaUrl() + ": " + ex.getMessage()); return null; } } private boolean downloadFile(HttpURLConnection conn, File file) { FileOutputStream outstream = null; InputStream instream = null; try { // file was deleted if accept-range header didn't work so always append outstream = new FileOutputStream(file, true); instream = conn.getInputStream(); int read; byte[] b = new byte[1024*64]; while (!Thread.currentThread().isInterrupted() && (read = instream.read(b)) != -1) outstream.write(b, 0, read); } catch (Exception e) { Log.e("Podax", "Interrupted while downloading " + conn.getURL().toExternalForm()); return false; } finally { close(outstream); close(instream); } return file.length() == conn.getContentLength(); } public static void close(Closeable c) { if (c == null) return; try { c.close(); } catch (IOException e) { } } }
package com.ecyrd.jspwiki; import java.io.*; import java.util.*; import org.apache.log4j.Logger; import org.apache.oro.text.*; import org.apache.oro.text.regex.*; import com.ecyrd.jspwiki.plugin.PluginManager; import com.ecyrd.jspwiki.plugin.PluginException; import com.ecyrd.jspwiki.attachment.AttachmentManager; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.providers.ProviderException; import com.ecyrd.jspwiki.acl.AccessControlList; import com.ecyrd.jspwiki.auth.modules.PageAuthorizer; import com.ecyrd.jspwiki.auth.WikiSecurityException; import com.ecyrd.jspwiki.auth.UserManager; /** * Handles conversion from Wiki format into fully featured HTML. * This is where all the magic happens. It is CRITICAL that this * class is tested, or all Wikis might die horribly. * <P> * The output of the HTML has not yet been validated against * the HTML DTD. However, it is very simple. * * @author Janne Jalkanen */ public class TranslatorReader extends Reader { public static final int READ = 0; public static final int EDIT = 1; private static final int EMPTY = 2; // Empty message private static final int LOCAL = 3; private static final int LOCALREF = 4; private static final int IMAGE = 5; private static final int EXTERNAL = 6; private static final int INTERWIKI = 7; private static final int IMAGELINK = 8; private static final int IMAGEWIKILINK = 9; public static final int ATTACHMENT = 10; private static final int ATTACHMENTIMAGE = 11; /** Lists all punctuation characters allowed in WikiMarkup. These will not be cleaned away. */ private static final String PUNCTUATION_CHARS_ALLOWED = "._"; /** Allow this many characters to be pushed back in the stream. In effect, this limits the size of a single heading line. */ private static final int PUSHBACK_BUFFER_SIZE = 10*1024; private PushbackReader m_in; private StringReader m_data = new StringReader(""); private static Logger log = Logger.getLogger( TranslatorReader.class ); //private boolean m_iscode = false; private boolean m_isbold = false; private boolean m_isitalic = false; private boolean m_isTypedText = false; private boolean m_istable = false; private boolean m_isPre = false; private boolean m_isEscaping = false; private boolean m_isdefinition = false; /** Contains style information, in multiple forms. */ private Stack m_styleStack = new Stack(); // general list handling private int m_genlistlevel = 0; private StringBuffer m_genlistBulletBuffer = new StringBuffer(); // stores the # and * pattern private boolean m_allowPHPWikiStyleLists = true; private boolean m_isOpenParagraph = false; /** Tag that gets closed at EOL. */ private String m_closeTag = null; private WikiEngine m_engine; private WikiContext m_context; /** Optionally stores internal wikilinks */ private ArrayList m_localLinkMutatorChain = new ArrayList(); private ArrayList m_externalLinkMutatorChain = new ArrayList(); private ArrayList m_attachmentLinkMutatorChain = new ArrayList(); private ArrayList m_headingListenerChain = new ArrayList(); /** Keeps image regexp Patterns */ private ArrayList m_inlineImagePatterns; private PatternMatcher m_inlineMatcher = new Perl5Matcher(); private ArrayList m_linkMutators = new ArrayList(); /** * This property defines the inline image pattern. It's current value * is jspwiki.translatorReader.inlinePattern */ public static final String PROP_INLINEIMAGEPTRN = "jspwiki.translatorReader.inlinePattern"; /** If true, consider CamelCase hyperlinks as well. */ public static final String PROP_CAMELCASELINKS = "jspwiki.translatorReader.camelCaseLinks"; /** If true, all hyperlinks are translated as well, regardless whether they are surrounded by brackets. */ public static final String PROP_PLAINURIS = "jspwiki.translatorReader.plainUris"; /** If true, all outward links (external links) have a small link image appended. */ public static final String PROP_USEOUTLINKIMAGE = "jspwiki.translatorReader.useOutlinkImage"; /** If set to "true", allows using raw HTML within Wiki text. Be warned, this is a VERY dangerous option to set - never turn this on in a publicly allowable Wiki, unless you are absolutely certain of what you're doing. */ public static final String PROP_ALLOWHTML = "jspwiki.translatorReader.allowHTML"; /** If set to "true", all external links are tagged with 'rel="nofollow"' */ public static final String PROP_USERELNOFOLLOW = "jspwiki.translatorReader.useRelNofollow"; /** If set to "true", enables plugins during parsing */ public static final String PROP_RUNPLUGINS = "jspwiki.translatorReader.runPlugins"; /** If true, then considers CamelCase links as well. */ private boolean m_camelCaseLinks = false; /** If true, consider URIs that have no brackets as well. */ // FIXME: Currently reserved, but not used. private boolean m_plainUris = false; /** If true, all outward links use a small link image. */ private boolean m_useOutlinkImage = true; /** If true, allows raw HTML. */ private boolean m_allowHTML = false; /** If true, executes plugins; otherwise ignores them. */ private boolean m_enablePlugins = true; private boolean m_useRelNofollow = false; private boolean m_inlineImages = true; private PatternMatcher m_matcher = new Perl5Matcher(); private PatternCompiler m_compiler = new Perl5Compiler(); private Pattern m_camelCasePtrn; private TextRenderer m_renderer; /** * The default inlining pattern. Currently "*.png" */ public static final String DEFAULT_INLINEPATTERN = "*.png"; /** * These characters constitute word separators when trying * to find CamelCase links. */ private static final String WORD_SEPARATORS = ",.|;+=&()"; protected static final int BOLD = 0; protected static final int ITALIC = 1; protected static final int TYPED = 2; /** * This list contains all IANA registered URI protocol * types as of September 2004 + a few well-known extra types. * * JSPWiki recognises all of them as external links. */ static final String[] c_externalLinks = { "http:", "ftp:", "https:", "mailto:", "news:", "file:", "rtsp:", "mms:", "ldap:", "gopher:", "nntp:", "telnet:", "wais:", "prospero:", "z39.50s", "z39.50r", "vemmi:", "imap:", "nfs:", "acap:", "tip:", "pop:", "dav:", "opaquelocktoken:", "sip:", "sips:", "tel:", "fax:", "modem:", "soap.beep:", "soap.beeps", "xmlrpc.beep", "xmlrpc.beeps", "urn:", "go:", "h323:", "ipp:", "tftp:", "mupdate:", "pres:", "im:", "mtqp", "smb:" }; /** * Creates a TranslatorReader using the default HTML renderer. */ public TranslatorReader( WikiContext context, Reader in ) { initialize( context, in, new HTMLRenderer() ); } public TranslatorReader( WikiContext context, Reader in, TextRenderer renderer ) { initialize( context, in, renderer ); } /** * Replaces the current input character stream with a new one. * @param in New source for input. If null, this method does nothing. * @return the old stream */ public Reader setInputReader( Reader in ) { Reader old = m_in; if( in != null ) { m_in = new PushbackReader( new BufferedReader( in ), PUSHBACK_BUFFER_SIZE ); } return old; } /** * @param engine The WikiEngine this reader is attached to. Is * used to figure out of a page exits. */ // FIXME: TranslatorReaders should be pooled for better performance. private void initialize( WikiContext context, Reader in, TextRenderer renderer ) { PatternCompiler compiler = new GlobCompiler(); ArrayList compiledpatterns = new ArrayList(); m_engine = context.getEngine(); m_context = context; m_renderer = renderer; setInputReader( in ); Collection ptrns = getImagePatterns( m_engine ); // Make them into Regexp Patterns. Unknown patterns // are ignored. for( Iterator i = ptrns.iterator(); i.hasNext(); ) { try { compiledpatterns.add( compiler.compile( (String)i.next() ) ); } catch( MalformedPatternException e ) { log.error("Malformed pattern in properties: ", e ); } } m_inlineImagePatterns = compiledpatterns; try { m_camelCasePtrn = m_compiler.compile( "^([[:^alnum:]]*|\\~)([[:upper:]]+[[:lower:]]+[[:upper:]]+[[:alnum:]]*)[[:^alnum:]]*$" ); } catch( MalformedPatternException e ) { log.fatal("Internal error: Someone put in a faulty pattern.",e); throw new InternalWikiException("Faulty camelcasepattern in TranslatorReader"); } // Set the properties. Properties props = m_engine.getWikiProperties(); String cclinks = (String)m_context.getPage().getAttribute( PROP_CAMELCASELINKS ); if( cclinks != null ) { m_camelCaseLinks = TextUtil.isPositive( cclinks ); } else { m_camelCaseLinks = TextUtil.getBooleanProperty( props, PROP_CAMELCASELINKS, m_camelCaseLinks ); } m_plainUris = TextUtil.getBooleanProperty( props, PROP_PLAINURIS, m_plainUris ); m_useOutlinkImage = TextUtil.getBooleanProperty( props, PROP_USEOUTLINKIMAGE, m_useOutlinkImage ); m_allowHTML = TextUtil.getBooleanProperty( props, PROP_ALLOWHTML, m_allowHTML ); m_useRelNofollow = TextUtil.getBooleanProperty( props, PROP_USERELNOFOLLOW, m_useRelNofollow ); String runplugins = m_engine.getVariable( m_context, PROP_RUNPLUGINS ); if( runplugins != null ) enablePlugins( TextUtil.isPositive(runplugins)); if( m_engine.getUserManager() == null || m_engine.getUserManager().getAuthenticator() == null ) { disableAccessRules(); } } /** * Sets the currently used renderer. This method is protected because * we only want to use it internally for now. The renderer interface * is not yet set to stone, so it's not expected that third parties * would use this. */ protected void setRenderer( TextRenderer renderer ) { m_renderer = renderer; } /** * Adds a hook for processing link texts. This hook is called * when the link text is written into the output stream, and * you may use it to modify the text. It does not affect the * actual link, only the user-visible text. * * @param mutator The hook to call. Null is safe. */ public void addLinkTransmutator( StringTransmutator mutator ) { if( mutator != null ) { m_linkMutators.add( mutator ); } } /** * Adds a hook for processing local links. The engine * transforms both non-existing and existing page links. * * @param mutator The hook to call. Null is safe. */ public void addLocalLinkHook( StringTransmutator mutator ) { if( mutator != null ) { m_localLinkMutatorChain.add( mutator ); } } public void addExternalLinkHook( StringTransmutator mutator ) { if( mutator != null ) { m_externalLinkMutatorChain.add( mutator ); } } /** * Adds a hook for processing attachment links. * * @param mutator The hook to call. Null is safe. */ public void addAttachmentLinkHook( StringTransmutator mutator ) { if( mutator != null ) { m_attachmentLinkMutatorChain.add( mutator ); } } public void addHeadingListener( HeadingListener listener ) { if( listener != null ) { m_headingListenerChain.add( listener ); } } private boolean m_parseAccessRules = true; public void disableAccessRules() { m_parseAccessRules = false; } /** * Can be used to turn on plugin execution on a translator-reader basis */ public void enablePlugins( boolean toggle ) { m_enablePlugins = toggle; } /** * Use this to turn on or off image inlining. * @param toggle If true, images are inlined (as per set in jspwiki.properties) * If false, then images won't be inlined; instead, they will be * treated as standard hyperlinks. * @since 2.2.9 */ public void enableImageInlining( boolean toggle ) { m_inlineImages = toggle; } /** * Figure out which image suffixes should be inlined. * @return Collection of Strings with patterns. */ protected static Collection getImagePatterns( WikiEngine engine ) { Properties props = engine.getWikiProperties(); ArrayList ptrnlist = new ArrayList(); for( Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); if( name.startsWith( PROP_INLINEIMAGEPTRN ) ) { String ptrn = props.getProperty( name ); ptrnlist.add( ptrn ); } } if( ptrnlist.size() == 0 ) { ptrnlist.add( DEFAULT_INLINEPATTERN ); } return ptrnlist; } /** * Returns link name, if it exists; otherwise it returns null. */ private String linkExists( String page ) { try { if( page == null || page.length() == 0 ) return null; return m_engine.getFinalPageName( page ); } catch( ProviderException e ) { log.warn("TranslatorReader got a faulty page name!",e); return page; // FIXME: What would be the correct way to go back? } } /** * Calls a transmutator chain. * * @param list Chain to call * @param text Text that should be passed to the mutate() method * of each of the mutators in the chain. * @return The result of the mutation. */ private String callMutatorChain( Collection list, String text ) { if( list == null || list.size() == 0 ) { return text; } for( Iterator i = list.iterator(); i.hasNext(); ) { StringTransmutator m = (StringTransmutator) i.next(); text = m.mutate( m_context, text ); } return text; } private void callHeadingListenerChain( Heading param ) { List list = m_headingListenerChain; for( Iterator i = list.iterator(); i.hasNext(); ) { HeadingListener h = (HeadingListener) i.next(); h.headingAdded( m_context, param ); } } /** * Write a HTMLized link depending on its type. * The link mutator chain is processed. * * @param type Type of the link. * @param link The actual link. * @param text The user-visible text for the link. */ public String makeLink( int type, String link, String text ) { if( text == null ) text = link; text = callMutatorChain( m_linkMutators, text ); return m_renderer.makeLink( type, link, text ); } /** * Just like makeLink, but also adds the section reference (#sect...) */ private String makeLink( int type, String link, String text, String sectref ) { if( text == null ) text = link; text = callMutatorChain( m_linkMutators, text ); return m_renderer.makeLink( type, link, text, sectref ); } /** * Cleans a Wiki name. * <P> * [ This is a link ] -&gt; ThisIsALink * * @param link Link to be cleared. Null is safe, and causes this to return null. * @return A cleaned link. * * @since 2.0 */ public static String cleanLink( String link ) { StringBuffer clean = new StringBuffer(); if( link == null ) return null; // Compress away all whitespace and capitalize // all words in between. StringTokenizer st = new StringTokenizer( link, " -" ); while( st.hasMoreTokens() ) { StringBuffer component = new StringBuffer(st.nextToken()); component.setCharAt(0, Character.toUpperCase( component.charAt(0) ) ); // We must do this, because otherwise compiling on JDK 1.4 causes // a downwards incompatibility to JDK 1.3. clean.append( component.toString() ); } // Remove non-alphanumeric characters that should not // be put inside WikiNames. Note that all valid // Unicode letters are considered okay for WikiNames. // It is the problem of the WikiPageProvider to take // care of actually storing that information. for( int i = 0; i < clean.length(); i++ ) { char ch = clean.charAt(i); if( !(Character.isLetterOrDigit(ch) || PUNCTUATION_CHARS_ALLOWED.indexOf(ch) != -1 )) { clean.deleteCharAt(i); --i; // We just shortened this buffer. } } return clean.toString(); } /** * Figures out if a link is an off-site link. This recognizes * the most common protocols by checking how it starts. */ // FIXME: Should really put the external link types to a sorted set, // then searching for them would be faster. private boolean isExternalLink( String link ) { for( int i = 0; i < c_externalLinks.length; i++ ) { if( link.startsWith( c_externalLinks[i] ) ) return true; } return false; } /** * Returns true, if the link in question is an access * rule. */ private static boolean isAccessRule( String link ) { return link.startsWith("{ALLOW") || link.startsWith("{DENY"); } /** * Matches the given link to the list of image name patterns * to determine whether it should be treated as an inline image * or not. */ private boolean isImageLink( String link ) { if( m_inlineImages ) { for( Iterator i = m_inlineImagePatterns.iterator(); i.hasNext(); ) { if( m_inlineMatcher.matches( link, (Pattern) i.next() ) ) return true; } } return false; } private static boolean isMetadata( String link ) { return link.startsWith("{SET"); } /** * Returns true, if the argument contains a number, otherwise false. * In a quick test this is roughly the same speed as Integer.parseInt() * if the argument is a number, and roughly ten times the speed, if * the argument is NOT a number. */ private boolean isNumber( String s ) { if( s == null ) return false; if( s.length() > 1 && s.charAt(0) == '-' ) s = s.substring(1); for( int i = 0; i < s.length(); i++ ) { if( !Character.isDigit(s.charAt(i)) ) return false; } return true; } /** * Checks for the existence of a traditional style CamelCase link. * <P> * We separate all white-space -separated words, and feed it to this * routine to find if there are any possible camelcase links. * For example, if "word" is "__HyperLink__" we return "HyperLink". * * @param word A phrase to search in. * @return The match within the phrase. Returns null, if no CamelCase * hyperlink exists within this phrase. */ private String checkForCamelCaseLink( String word ) { PatternMatcherInput input; input = new PatternMatcherInput( word ); if( m_matcher.contains( input, m_camelCasePtrn ) ) { MatchResult res = m_matcher.getMatch(); int start = res.beginOffset(2); int end = res.endOffset(2); String link = res.group(2); if( res.group(1) != null ) { if( res.group(1).equals("~") || res.group(1).indexOf('[') != -1 ) { // Delete the (~) from beginning. // We'll make '~' the generic kill-processing-character from // now on. return null; } } return link; } // if match return null; } /** * When given a link to a WikiName, we just return * a proper HTML link for it. The local link mutator * chain is also called. */ private String makeCamelCaseLink( String wikiname ) { String matchedLink; String link; callMutatorChain( m_localLinkMutatorChain, wikiname ); if( (matchedLink = linkExists( wikiname )) != null ) { link = makeLink( READ, matchedLink, wikiname ); } else { link = makeLink( EDIT, wikiname, wikiname ); } return link; } private String makeDirectURILink( String url ) { String last = ""; String result; if( url.endsWith(",") || url.endsWith(".") ) { last = url.substring( url.length()-1 ); url = url.substring( 0, url.length()-1 ); } callMutatorChain( m_externalLinkMutatorChain, url ); if( isImageLink( url ) ) { result = handleImageLink( url, url, false ); } else { result = makeLink( EXTERNAL, url, url ) + m_renderer.outlinkImage(); } result += last; return result; } /** * Image links are handled differently: * 1. If the text is a WikiName of an existing page, * it gets linked. * 2. If the text is an external link, then it is inlined. * 3. Otherwise it becomes an ALT text. * * @param reallink The link to the image. * @param link Link text portion, may be a link to somewhere else. * @param hasLinkText If true, then the defined link had a link text available. * This means that the link text may be a link to a wiki page, * or an external resource. */ private String handleImageLink( String reallink, String link, boolean hasLinkText ) { String possiblePage = cleanLink( link ); String matchedLink; String res = ""; if( isExternalLink( link ) && hasLinkText ) { res = makeLink( IMAGELINK, reallink, link ); } else if( (matchedLink = linkExists( possiblePage )) != null && hasLinkText ) { // System.out.println("Orig="+link+", Matched: "+matchedLink); callMutatorChain( m_localLinkMutatorChain, possiblePage ); res = makeLink( IMAGEWIKILINK, reallink, link ); } else { res = makeLink( IMAGE, reallink, link ); } return res; } private String handleAccessRule( String ruleLine ) { if( !m_parseAccessRules ) return ""; AccessControlList acl; WikiPage page = m_context.getPage(); UserManager mgr = m_context.getEngine().getUserManager(); if( ruleLine.startsWith( "{" ) ) ruleLine = ruleLine.substring( 1 ); if( ruleLine.endsWith( "}" ) ) ruleLine = ruleLine.substring( 0, ruleLine.length() - 1 ); log.debug("page="+page.getName()+", ACL = "+ruleLine); try { acl = PageAuthorizer.parseAcl( page, mgr, ruleLine ); page.setAcl( acl ); log.debug( acl.toString() ); } catch( WikiSecurityException wse ) { return m_renderer.makeError( wse.getMessage() ); } return ""; } /** * Handles metadata setting [{SET foo=bar}] */ private String handleMetadata( String link ) { try { String args = link.substring( link.indexOf(' '), link.length()-1 ); String name = args.substring( 0, args.indexOf('=') ); String val = args.substring( args.indexOf('=')+1, args.length() ); name = name.trim(); val = val.trim(); if( val.startsWith("'") ) val = val.substring( 1 ); if( val.endsWith("'") ) val = val.substring( 0, val.length()-1 ); // log.debug("SET name='"+name+"', value='"+val+"'."); if( name.length() > 0 && val.length() > 0 ) { val = m_engine.getVariableManager().expandVariables( m_context, val ); m_context.getPage().setAttribute( name, val ); } } catch( Exception e ) { m_renderer.makeError(" Invalid SET found: "+link); } return ""; } /** * Gobbles up all hyperlinks that are encased in square brackets. */ private String handleHyperlinks( String link ) { StringBuffer sb = new StringBuffer(); String reallink; int cutpoint; if( isAccessRule( link ) ) { return handleAccessRule( link ); } if( isMetadata( link ) ) { return handleMetadata( link ); } if( PluginManager.isPluginLink( link ) ) { String included = ""; try { if( m_enablePlugins ) { included = m_engine.getPluginManager().execute( m_context, link ); } } catch( PluginException e ) { log.info( "Failed to insert plugin", e ); log.info( "Root cause:",e.getRootThrowable() ); included = m_renderer.makeError("Plugin insertion failed: "+e.getMessage()); } sb.append( included ); return sb.toString(); } link = TextUtil.replaceEntities( link ); if( (cutpoint = link.indexOf('|')) != -1 ) { reallink = link.substring( cutpoint+1 ).trim(); link = link.substring( 0, cutpoint ); } else { reallink = link.trim(); } int interwikipoint = -1; // Yes, we now have the components separated. // link = the text the link should have // reallink = the url or page name. // In many cases these are the same. [link|reallink]. if( VariableManager.isVariableLink( link ) ) { String value; try { value = m_engine.getVariableManager().parseAndGetValue( m_context, link ); } catch( NoSuchVariableException e ) { value = m_renderer.makeError(e.getMessage()); } catch( IllegalArgumentException e ) { value = m_renderer.makeError(e.getMessage()); } sb.append( value ); } else if( isExternalLink( reallink ) ) { // It's an external link, out of this Wiki callMutatorChain( m_externalLinkMutatorChain, reallink ); if( isImageLink( reallink ) ) { sb.append( handleImageLink( reallink, link, (cutpoint != -1) ) ); } else { sb.append( makeLink( EXTERNAL, reallink, link ) ); sb.append( m_renderer.outlinkImage() ); } } else if( (interwikipoint = reallink.indexOf(":")) != -1 ) { // It's an interwiki link // InterWiki links also get added to external link chain // after the links have been resolved. // FIXME: There is an interesting issue here: We probably should // URLEncode the wikiPage, but we can't since some of the // Wikis use slashes (/), which won't survive URLEncoding. // Besides, we don't know which character set the other Wiki // is using, so you'll have to write the entire name as it appears // in the URL. Bugger. String extWiki = reallink.substring( 0, interwikipoint ); String wikiPage = reallink.substring( interwikipoint+1 ); String urlReference = m_engine.getInterWikiURL( extWiki ); if( urlReference != null ) { urlReference = TextUtil.replaceString( urlReference, "%s", wikiPage ); callMutatorChain( m_externalLinkMutatorChain, urlReference ); sb.append( makeLink( INTERWIKI, urlReference, link ) ); if( isExternalLink(urlReference) ) { sb.append( m_renderer.outlinkImage() ); } } else { sb.append( link+" "+m_renderer.makeError("No InterWiki reference defined in properties for Wiki called '"+extWiki+"'!)") ); } } else if( reallink.startsWith(" { // It defines a local footnote sb.append( makeLink( LOCAL, reallink, link ) ); } else if( isNumber( reallink ) ) { // It defines a reference to a local footnote sb.append( makeLink( LOCALREF, reallink, link ) ); } else { int hashMark = -1; // Internal wiki link, but is it an attachment link? String attachment = findAttachment( reallink ); if( attachment != null ) { callMutatorChain( m_attachmentLinkMutatorChain, attachment ); if( isImageLink( reallink ) ) { attachment = m_context.getURL( WikiContext.ATTACH, attachment ); sb.append( handleImageLink( attachment, link, (cutpoint != -1) ) ); } else { sb.append( makeLink( ATTACHMENT, attachment, link ) ); } } else if( (hashMark = reallink.indexOf(' { // It's an internal Wiki link, but to a named section String namedSection = reallink.substring( hashMark+1 ); reallink = reallink.substring( 0, hashMark ); reallink = cleanLink( reallink ); callMutatorChain( m_localLinkMutatorChain, reallink ); String matchedLink; if( (matchedLink = linkExists( reallink )) != null ) { String sectref = "section-"+m_engine.encodeName(matchedLink)+"-"+namedSection; sectref = sectref.replace('%', '_'); sb.append( makeLink( READ, matchedLink, link, sectref ) ); } else { sb.append( makeLink( EDIT, reallink, link ) ); } } else { // It's an internal Wiki link reallink = cleanLink( reallink ); callMutatorChain( m_localLinkMutatorChain, reallink ); String matchedLink = linkExists( reallink ); if( matchedLink != null ) { sb.append( makeLink( READ, matchedLink, link ) ); } else { sb.append( makeLink( EDIT, reallink, link ) ); } } } return sb.toString(); } private String findAttachment( String link ) { AttachmentManager mgr = m_engine.getAttachmentManager(); WikiPage currentPage = m_context.getPage(); Attachment att = null; /* System.out.println("Finding attachment of page "+currentPage.getName()); System.out.println("With name "+link); */ try { att = mgr.getAttachmentInfo( m_context, link ); } catch( ProviderException e ) { log.warn("Finding attachments failed: ",e); return null; } if( att != null ) { return att.getName(); } else if( link.indexOf('/') != -1 ) { return link; } return null; } /** * Closes all annoying lists and things that the user might've * left open. */ private String closeAll() { StringBuffer buf = new StringBuffer(); if( m_isbold ) { buf.append(m_renderer.closeTextEffect(BOLD)); m_isbold = false; } if( m_isitalic ) { buf.append(m_renderer.closeTextEffect(ITALIC)); m_isitalic = false; } if( m_isTypedText ) { buf.append(m_renderer.closeTextEffect(TYPED)); m_isTypedText = false; } /* for( ; m_listlevel > 0; m_listlevel-- ) { buf.append( "</ul>\n" ); } for( ; m_numlistlevel > 0; m_numlistlevel-- ) { buf.append( "</ol>\n" ); } */ // cleanup OL and UL lists buf.append(unwindGeneralList()); if( m_isPre ) { buf.append(m_renderer.closePreformatted()); m_isEscaping = false; m_isPre = false; } if( m_istable ) { buf.append( m_renderer.closeTable() ); m_istable = false; } if( m_isOpenParagraph ) { buf.append( m_renderer.closeParagraph() ); m_isOpenParagraph = false; } return buf.toString(); } // FIXME: should remove countChar() as it is unused /** * Counts how many consecutive characters of a certain type exists on the line. * @param line String of chars to check. * @param startPos Position to start reading from. * @param char Character to check for. */ private int countChar( String line, int startPos, char c ) { int count; for( count = 0; (startPos+count < line.length()) && (line.charAt(count+startPos) == c); count++ ); return count; } /** * Returns a new String that has char c n times. */ private String repeatChar( char c, int n ) { StringBuffer sb = new StringBuffer(); for( int i = 0; i < n; i++ ) sb.append(c); return sb.toString(); } private int nextToken() throws IOException { if( m_in == null ) return -1; return m_in.read(); } /** * Push back any character to the current input. Does not * push back a read EOF, though. */ private void pushBack( int c ) throws IOException { if( c != -1 && m_in != null ) { m_in.unread( c ); } } /** * Pushes back any string that has been read. It will obviously * be pushed back in a reverse order. * * @since 2.1.77 */ private void pushBack( String s ) throws IOException { for( int i = s.length()-1; i >= 0; i { pushBack( s.charAt(i) ); } } private String handleBackslash() throws IOException { int ch = nextToken(); if( ch == '\\' ) { int ch2 = nextToken(); if( ch2 == '\\' ) { return m_renderer.lineBreak(true); } pushBack( ch2 ); return m_renderer.lineBreak(false); } pushBack( ch ); return "\\"; } private String handleUnderscore() throws IOException { int ch = nextToken(); String res = "_"; if( ch == '_' ) { res = m_isbold ? m_renderer.closeTextEffect(BOLD) : m_renderer.openTextEffect(BOLD); m_isbold = !m_isbold; } else { pushBack( ch ); } return res; } /** * For example: italics. */ private String handleApostrophe() throws IOException { int ch = nextToken(); String res = "'"; if( ch == '\'' ) { res = m_isitalic ? m_renderer.closeTextEffect(ITALIC) : m_renderer.openTextEffect(ITALIC); m_isitalic = !m_isitalic; } else { pushBack( ch ); } return res; } private String handleOpenbrace( boolean isBlock ) throws IOException { int ch = nextToken(); String res = "{"; if( ch == '{' ) { int ch2 = nextToken(); if( ch2 == '{' ) { res = startBlockLevel()+m_renderer.openPreformatted( isBlock ); m_isPre = true; m_isEscaping = true; } else { pushBack( ch2 ); res = m_renderer.openTextEffect(TYPED); m_isTypedText = true; } } else { pushBack( ch ); } return res; } /** * Handles both }} and }}} */ private String handleClosebrace() throws IOException { String res = "}"; int ch2 = nextToken(); if( ch2 == '}' ) { int ch3 = nextToken(); if( ch3 == '}' ) { if( m_isPre ) { m_isPre = false; m_isEscaping = false; res = m_renderer.closePreformatted(); } else { res = "}}}"; } } else { pushBack( ch3 ); if( !m_isEscaping ) { res = m_renderer.closeTextEffect(TYPED); m_isTypedText = false; } else { pushBack( ch2 ); } } } else { pushBack( ch2 ); } return res; } private String handleDash() throws IOException { int ch = nextToken(); if( ch == '-' ) { int ch2 = nextToken(); if( ch2 == '-' ) { int ch3 = nextToken(); if( ch3 == '-' ) { // Empty away all the rest of the dashes. // Do not forget to return the first non-match back. while( (ch = nextToken()) == '-' ); pushBack(ch); return startBlockLevel()+m_renderer.makeRuler(); } pushBack( ch3 ); } pushBack( ch2 ); } pushBack( ch ); return "-"; } /** * This method peeks ahead in the stream until EOL and returns the result. * It will keep the buffers untouched. * * @return The string from the current position to the end of line. */ // FIXME: Always returns an empty line, even if the stream is full. private String peekAheadLine() throws IOException { String s = readUntilEOL().toString(); pushBack( s ); return s; } private String handleHeading() throws IOException { StringBuffer buf = new StringBuffer(); int ch = nextToken(); Heading hd = new Heading(); if( ch == '!' ) { int ch2 = nextToken(); if( ch2 == '!' ) { String title = peekAheadLine(); buf.append( m_renderer.makeHeading( Heading.HEADING_LARGE, title, hd) ); } else { pushBack( ch2 ); String title = peekAheadLine(); buf.append( m_renderer.makeHeading( Heading.HEADING_MEDIUM, title, hd ) ); } } else { pushBack( ch ); String title = peekAheadLine(); buf.append( m_renderer.makeHeading( Heading.HEADING_SMALL, title, hd ) ); } callHeadingListenerChain( hd ); return buf.toString(); } /** * Reads the stream until the next EOL or EOF. Note that it will also read the * EOL from the stream. */ private StringBuffer readUntilEOL() throws IOException { int ch; StringBuffer buf = new StringBuffer(); while( true ) { ch = nextToken(); if( ch == -1 ) break; buf.append( (char) ch ); if( ch == '\n' ) break; } return buf; } /** * Starts a block level element, therefore closing the * a potential open paragraph tag. */ private String startBlockLevel() { if( m_isOpenParagraph ) { m_isOpenParagraph = false; return m_renderer.closeParagraph(); } return ""; } /** * Like original handleOrderedList() and handleUnorderedList() * however handles both ordered ('#') and unordered ('*') mixed together. */ // FIXME: Refactor this; it's a bit messy. private String handleGeneralList() throws IOException { String cStrShortName = "handleGeneralList()"; //put log messages in some context StringBuffer buf = new StringBuffer(); buf.append( startBlockLevel() ); String strBullets = readWhile( "* String strBulletsRaw = strBullets; // to know what was original before phpwiki style substitution int numBullets = strBullets.length(); // override the beginning portion of bullet pattern to be like the previous // to simulate PHPWiki style lists if(m_allowPHPWikiStyleLists) { // only substitute if different if(!( strBullets.substring(0,Math.min(numBullets,m_genlistlevel)).equals (m_genlistBulletBuffer.substring(0,Math.min(numBullets,m_genlistlevel)) ) ) ) { if(numBullets <= m_genlistlevel) { // Substitute all but the last character (keep the expressed bullet preference) strBullets = (numBullets > 1 ? m_genlistBulletBuffer.substring(0, numBullets-1) : "") + strBullets.substring(numBullets-1, numBullets); } else { strBullets = m_genlistBulletBuffer + strBullets.substring(m_genlistlevel, numBullets); } } } // Check if this is still of the same type if( strBullets.substring(0,Math.min(numBullets,m_genlistlevel)).equals (m_genlistBulletBuffer.substring(0,Math.min(numBullets,m_genlistlevel)) ) ) { int chBullet; if( numBullets > m_genlistlevel ) { buf.append( m_renderer.openList(strBullets.charAt(m_genlistlevel++)) ); for( ; m_genlistlevel < numBullets; m_genlistlevel++ ) { // bullets are growing, get from new bullet list buf.append( m_renderer.openListItem() ); buf.append( m_renderer.openList(strBullets.charAt(m_genlistlevel)) ); } } else if( numBullets < m_genlistlevel ) { // Close the previous list item. buf.append( m_renderer.closeListItem() ); for( ; m_genlistlevel > numBullets; m_genlistlevel { // bullets are shrinking, get from old bullet list buf.append( m_renderer.closeList(m_genlistBulletBuffer.charAt(m_genlistlevel - 1)) ); if( m_genlistlevel > 0 ) buf.append( m_renderer.closeListItem() ); } } else { if( m_genlistlevel > 0 ) buf.append( m_renderer.closeListItem() ); } } else { // The pattern has changed, unwind and restart char chBullet; int numEqualBullets; int numCheckBullets; // find out how much is the same numEqualBullets = 0; numCheckBullets = Math.min(numBullets,m_genlistlevel); while( numEqualBullets < numCheckBullets ) { // if the bullets are equal so far, keep going if( strBullets.charAt(numEqualBullets) == m_genlistBulletBuffer.charAt(numEqualBullets)) numEqualBullets++; // otherwise giveup, we have found how many are equal else break; } //unwind for( ; m_genlistlevel > numEqualBullets; m_genlistlevel { buf.append( m_renderer.closeList( m_genlistBulletBuffer.charAt(m_genlistlevel - 1) ) ); if( m_genlistlevel > 0 ) buf.append( m_renderer.closeListItem() ); } //rewind buf.append( m_renderer.openList( strBullets.charAt(numEqualBullets++) ) ); for(int i = numEqualBullets; i < numBullets; i++) { buf.append( m_renderer.openListItem() ); buf.append( m_renderer.openList( strBullets.charAt(i) ) ); } m_genlistlevel = numBullets; } buf.append( m_renderer.openListItem() ); // work done, remember the new bullet list (in place of old one) m_genlistBulletBuffer.setLength(0); m_genlistBulletBuffer.append(strBullets); return buf.toString(); } private String unwindGeneralList() { // String cStrShortName = "unwindGeneralList()"; StringBuffer buf = new StringBuffer(); int bulletCh; //unwind for( ; m_genlistlevel > 0; m_genlistlevel { buf.append(m_renderer.closeListItem()); buf.append( m_renderer.closeList( m_genlistBulletBuffer.charAt(m_genlistlevel - 1) ) ); } m_genlistBulletBuffer.setLength(0); return buf.toString(); } private String handleDefinitionList() throws IOException { if( !m_isdefinition ) { m_isdefinition = true; m_closeTag = m_renderer.closeDefinitionItem()+m_renderer.closeDefinitionList(); return startBlockLevel()+m_renderer.openDefinitionList()+m_renderer.openDefinitionTitle(); } return ";"; } private String handleOpenbracket() throws IOException { StringBuffer sb = new StringBuffer(); int ch; boolean isPlugin = false; while( (ch = nextToken()) == '[' ) { sb.append( (char)ch ); } if( ch == '{' ) { isPlugin = true; } pushBack( ch ); if( sb.length() > 0 ) { return sb.toString(); } // Find end of hyperlink ch = nextToken(); while( ch != -1 ) { if( ch == ']' && (!isPlugin || sb.charAt( sb.length()-1 ) == '}' ) ) { break; } sb.append( (char) ch ); ch = nextToken(); } if( ch == -1 ) { log.debug("Warning: unterminated link detected!"); return sb.toString(); } return handleHyperlinks( sb.toString() ); } /** * Reads the stream until the current brace is closed or stream end. */ private String readBraceContent( char opening, char closing ) throws IOException { StringBuffer sb = new StringBuffer(); int braceLevel = 1; int ch; while(( ch = nextToken() ) != -1 ) { if( ch == '\\' ) { continue; } else if ( ch == opening ) { braceLevel++; } else if ( ch == closing ) { braceLevel if (braceLevel==0) { break; } } sb.append( (char)ch ); } return sb.toString(); } /** * Reads the stream until it meets one of the specified * ending characters, or stream end. The ending character will be left * in the stream. */ private String readUntil( String endChars ) throws IOException { StringBuffer sb = new StringBuffer(); int ch = nextToken(); while( ch != -1 ) { if( ch == '\\' ) { ch = nextToken(); if( ch == -1 ) { break; } } else { if( endChars.indexOf((char)ch) != -1 ) { pushBack( ch ); break; } } sb.append( (char) ch ); ch = nextToken(); } return sb.toString(); } /** * Reads the stream while the characters that have been specified are * in the stream, returning then the result as a String. */ private String readWhile( String endChars ) throws IOException { StringBuffer sb = new StringBuffer(); int ch = nextToken(); while( ch != -1 ) { if( endChars.indexOf((char)ch) == -1 ) { pushBack( ch ); break; } sb.append( (char) ch ); ch = nextToken(); } return sb.toString(); } /** * Handles constructs of type %%(style) and %%class * @param newLine * @return * @throws IOException */ private String handleDiv( boolean newLine ) throws IOException { int ch = nextToken(); if( ch == '%' ) { StringBuffer sb = new StringBuffer(); String style = null; String clazz = null; ch = nextToken(); boolean isspan = false; // Style or class? if( ch == '(' ) { style = readBraceContent('(',')'); } else if( Character.isLetter( (char) ch ) ) { pushBack( ch ); clazz = readUntil( " \t\n\r" ); ch = nextToken(); // Pop out only spaces, so that the upcoming EOL check does not check the // next line. if( ch == '\n' || ch == '\r' ) { pushBack(ch); } } else { // Anything else stops. pushBack(ch); try { Boolean isSpan = (Boolean)m_styleStack.pop(); if( isSpan == null ) { // Fail quietly } else if( isSpan.booleanValue() ) { sb.append( m_renderer.closeSpan() ); } else { sb.append( m_renderer.closeDiv() ); } } catch( EmptyStackException e ) { log.debug("Page '"+m_context.getPage().getName()+"' closes a %%-block that has not been opened."); } return sb.toString(); } // Decide if we should open a div or a span? String eol = peekAheadLine(); if( eol.trim().length() > 0 ) { // There is stuff after the class sb.append( m_renderer.openSpan( style, clazz ) ); m_styleStack.push( Boolean.TRUE ); } else { sb.append( startBlockLevel() ); sb.append( m_renderer.openDiv( style, clazz ) ); m_styleStack.push( Boolean.FALSE ); } return sb.toString(); } pushBack(ch); return "%"; } private String handleBar( boolean newLine ) throws IOException { StringBuffer sb = new StringBuffer(); if( !m_istable && !newLine ) { return "|"; } if( newLine ) { if( !m_istable ) { sb.append( startBlockLevel() ); sb.append( m_renderer.openTable() ); m_istable = true; } sb.append( m_renderer.openTableRow() ); m_closeTag = m_renderer.closeTableItem()+m_renderer.closeTableRow(); } int ch = nextToken(); if( ch == '|' ) { if( !newLine ) { sb.append( m_renderer.closeTableHeading() ); } sb.append( m_renderer.openTableHeading() ); m_closeTag = m_renderer.closeTableHeading()+m_renderer.closeTableRow(); } else { if( !newLine ) { sb.append( m_renderer.closeTableItem() ); } sb.append( m_renderer.openTableItem() ); pushBack( ch ); } return sb.toString(); } /** * Generic escape of next character or entity. */ private String handleTilde() throws IOException { int ch = nextToken(); if( ch == '|' || ch == '~' || ch == '\\' || ch == '*' || ch == ' ch == '-' || ch == '!' || ch == '\'' || ch == '_' || ch == '[' || ch == '{' || ch == ']' || ch == '}' ) { StringBuffer sb = new StringBuffer(); sb.append( (char)ch ); sb.append(readWhile( ""+(char)ch )); return sb.toString(); } if( Character.isUpperCase( (char) ch ) ) { return String.valueOf( (char)ch ); } // No escape. pushBack( ch ); return "~"; } private void fillBuffer() throws IOException { StringBuffer buf = new StringBuffer(); StringBuffer word = null; int previousCh = -2; int start = 0; boolean quitReading = false; boolean newLine = true; // FIXME: not true if reading starts in middle of buffer while(!quitReading) { int ch = nextToken(); String s = null; // Check if we're actually ending the preformatted mode. // We still must do an entity transformation here. if( m_isEscaping ) { if( ch == '}' ) { buf.append( handleClosebrace() ); } else if( ch == -1 ) { quitReading = true; } else { m_renderer.doChar( buf, (char)ch ); } continue; } // CamelCase detection, a non-trivial endeavour. // We keep track of all white-space separated entities, which we // hereby refer to as "words". We then check for an existence // of a CamelCase format text string inside the "word", and // if one exists, we replace it with a proper link. if( m_camelCaseLinks ) { // Quick parse of start of a word boundary. if( word == null && (Character.isWhitespace( (char)previousCh ) || WORD_SEPARATORS.indexOf( (char)previousCh ) != -1 || newLine ) && !Character.isWhitespace( (char) ch ) ) { word = new StringBuffer(); } // Are we currently tracking a word? if( word != null ) { // Check for the end of the word. if( Character.isWhitespace( (char)ch ) || ch == -1 || WORD_SEPARATORS.indexOf( (char) ch ) != -1 ) { String potentialLink = word.toString(); String camelCase = checkForCamelCaseLink(potentialLink); if( camelCase != null ) { // System.out.println("Buffer is "+buf); // System.out.println(" Replacing "+camelCase+" with proper link."); start = buf.toString().lastIndexOf( camelCase ); buf.replace(start, start+camelCase.length(), makeCamelCaseLink(camelCase) ); // System.out.println(" Resulting with "+buf); } else { // System.out.println("Checking for potential URI: "+potentialLink); if( isExternalLink( potentialLink ) ) { // System.out.println("buf="+buf); start = buf.toString().lastIndexOf( potentialLink ); if( start >= 0 ) { String link = readUntil(" \t()[]{}!\"'\n|"); link = potentialLink + (char)ch + link; // Do not forget the start. // System.out.println("start="+start+", pl="+potentialLink); buf.replace( start, start + potentialLink.length(), makeDirectURILink( link ) ); // System.out.println("Resulting with "+buf); ch = nextToken(); } } } // We've ended a word boundary, so time to reset. word = null; } else { // This should only be appending letters and digits. word.append( (char)ch ); } // if end of word } // if word's not null // Always set the previous character to test for word starts. previousCh = ch; } // if m_camelCaseLinks // An empty line stops a list if( newLine && ch != '*' && ch != '#' && ch != ' ' && m_genlistlevel > 0 ) { buf.append(unwindGeneralList()); } if( newLine && ch != '|' && m_istable ) { buf.append( m_renderer.closeTable() ); m_istable = false; m_closeTag = null; } // Now, check the incoming token. switch( ch ) { case '\r': // DOS linefeeds we forget s = null; break; case '\n': // Close things like headings, etc. if( m_closeTag != null ) { buf.append( m_closeTag ); m_closeTag = null; } m_isdefinition = false; if( newLine ) { // Paragraph change. buf.append( startBlockLevel() ); // Figure out which elements cannot be enclosed inside // a <p></p> pair according to XHTML rules. String nextLine = peekAheadLine(); if( nextLine.length() == 0 || (nextLine.length() > 0 && !nextLine.startsWith("{{{") && !nextLine.startsWith(" !nextLine.startsWith("%%") && "*#!;".indexOf( nextLine.charAt(0) ) == -1) ) { buf.append( m_renderer.openParagraph() ); m_isOpenParagraph = true; } } else { buf.append("\n"); newLine = true; } break; case '\\': s = handleBackslash(); break; case '_': s = handleUnderscore(); break; case '\'': s = handleApostrophe(); break; case '{': s = handleOpenbrace( newLine ); break; case '}': s = handleClosebrace(); break; case '-': s = handleDash(); break; case '!': if( newLine ) { s = handleHeading(); } else { s = "!"; } break; case ';': if( newLine ) { s = handleDefinitionList(); } else { s = ";"; } break; case ':': if( m_isdefinition ) { s = m_renderer.closeDefinitionTitle()+m_renderer.openDefinitionItem(); m_isdefinition = false; } else { s = ":"; } break; case '[': s = handleOpenbracket(); break; case '*': if( newLine ) { pushBack('*'); s = handleGeneralList(); } else { s = "*"; } break; case ' if( newLine ) { pushBack(' s = handleGeneralList(); } else { s = " } break; case '|': s = handleBar( newLine ); break; case '<': s = m_allowHTML ? "<" : "&lt;"; break; case '>': s = m_allowHTML ? ">" : "&gt;"; break; case '\"': s = m_allowHTML ? "\"" : "&quot;"; break; /* case '&': s = "&amp;"; break; */ case '~': s = handleTilde(); break; case '%': s = handleDiv( newLine ); break; case -1: if( m_closeTag != null ) { buf.append( m_closeTag ); m_closeTag = null; } quitReading = true; break; default: buf.append( (char)ch ); newLine = false; break; } if( s != null ) { buf.append( s ); newLine = false; } } m_data = new StringReader( buf.toString() ); } public int read() throws IOException { int val = m_data.read(); if( val == -1 ) { fillBuffer(); val = m_data.read(); if( val == -1 ) { m_data = new StringReader( closeAll() ); val = m_data.read(); } } return val; } public int read( char[] buf, int off, int len ) throws IOException { return m_data.read( buf, off, len ); } public boolean ready() throws IOException { log.debug("ready ? "+m_data.ready() ); if(!m_data.ready()) { fillBuffer(); } return m_data.ready(); } public void close() { } /** * All HTML output stuff is here. This class is a helper class, and will * be spawned later on with a proper API of its own so that we can have * different kinds of renderers. */ // FIXME: Not everything is yet, and in the future this class will be spawned // out to be its own class. private class HTMLRenderer extends TextRenderer { private boolean m_isPreBlock = false; private TranslatorReader m_cleanTranslator; /* FIXME: It's relatively slow to create two TranslatorReaders each time. */ public HTMLRenderer() { } /** * Does a lazy init. Otherwise, we would get into a situation * where HTMLRenderer would try and boot a TranslatorReader before * the TranslatorReader it is contained by is up. */ private TranslatorReader getCleanTranslator() { if( m_cleanTranslator == null ) { WikiContext dummyContext = new WikiContext( m_engine, m_context.getPage() ); m_cleanTranslator = new TranslatorReader( dummyContext, null, new TextRenderer() ); m_cleanTranslator.m_allowHTML = true; } return m_cleanTranslator; } public void doChar( StringBuffer buf, char ch ) { if( ch == '<' ) { buf.append("&lt;"); } else if( ch == '>' ) { buf.append("&gt;"); } else if( ch == '&' ) { buf.append("&amp;"); } else { buf.append( ch ); } } public String openDiv( String style, String clazz ) { StringBuffer sb = new StringBuffer(); sb.append( "<div" ); sb.append( style != null ? " style=\""+style+"\"" : "" ); sb.append( clazz != null ? " class=\""+clazz+"\"" : "" ); sb.append( ">" ); return sb.toString(); } public String openSpan( String style, String clazz ) { StringBuffer sb = new StringBuffer(); sb.append( "<span" ); sb.append( style != null ? " style=\""+style+"\"" : "" ); sb.append( clazz != null ? " class=\""+clazz+"\"" : "" ); sb.append( ">" ); return sb.toString(); } public String closeDiv() { return "</div>"; } public String closeSpan() { return "</span>"; } public String openParagraph() { return "<p>"; } public String closeParagraph() { return "</p>\n"; } /** * Writes out a text effect */ public String openTextEffect( int effect ) { switch( effect ) { case BOLD: return "<b>"; case ITALIC: return "<i>"; case TYPED: return "<tt>"; } return ""; } public String closeTextEffect( int effect ) { switch( effect ) { case BOLD: return "</b>"; case ITALIC: return "</i>"; case TYPED: return "</tt>"; } return ""; } public String openDefinitionItem() { return "<dd>"; } public String closeDefinitionItem() { return "</dd>\n"; } public String openDefinitionTitle() { return "<dt>"; } public String closeDefinitionTitle() { return "</dt>"; } public String openDefinitionList() { return "<dl>\n"; } public String closeDefinitionList() { return "</dl>"; } /** * Write a HTMLized link depending on its type. * * <p>This jsut calls makeLink() with "section" set to null. */ public String makeLink( int type, String link, String text ) { return makeLink( type, link, text, null ); } private final String getURL( String context, String link ) { return m_context.getURL( context, link, null ); } /** * Write a HTMLized link depending on its type. * * @param type Type of the link. * @param link The actual link. * @param text The user-visible text for the link. * @param section Which named anchor to point to. This may not have any * effect on certain link types. If null, will ignore it. */ public String makeLink( int type, String link, String text, String section ) { String result; if( text == null ) text = link; section = (section != null) ? ("#"+section) : ""; // Make sure we make a link name that can be accepted // as a valid URL. String encodedlink = m_engine.encodeName( link ); if( encodedlink.length() == 0 ) { type = EMPTY; } switch(type) { case READ: result = "<a class=\"wikipage\" href=\""+getURL(WikiContext.VIEW, link)+section+"\">"+text+"</a>"; break; case EDIT: result = "<a class=\"editpage\" title=\"Create '"+link+"'\" href=\""+ getURL(WikiContext.EDIT, link)+"\">"+ text+"</a>"; break; case EMPTY: result = "<u>"+text+"</u>"; break; // These two are for local references - footnotes and // references to footnotes. // We embed the page name (or whatever WikiContext gives us) // to make sure the links are unique across Wiki. case LOCALREF: result = "<a class=\"footnoteref\" href=\"#ref-"+ m_context.getPage().getName()+"-"+ link+"\">["+text+"]</a>"; break; case LOCAL: result = "<a class=\"footnote\" name=\"ref-"+ m_context.getPage().getName()+"-"+ link.substring(1)+"\">["+text+"]</a>"; break; // With the image, external and interwiki types we need to // make sure nobody can put in Javascript or something else // annoying into the links themselves. We do this by preventing // a haxor from stopping the link name short with quotes in // fillBuffer(). case IMAGE: result = "<img class=\"inline\" src=\""+link+"\" alt=\""+text+"\" />"; break; case IMAGELINK: result = "<a href=\""+text+"\"><img class=\"inline\" src=\""+link+"\" alt=\""+text+"\"/></a>"; break; case IMAGEWIKILINK: String pagelink = getURL(WikiContext.VIEW,text); result = "<a class=\"wikipage\" href=\""+pagelink+"\"><img class=\"inline\" src=\""+link+"\" alt=\""+text+"\" /></a>"; break; case EXTERNAL: result = "<a class=\"external\" "+ (m_useRelNofollow ? "rel=\"nofollow\" " : "")+ "href=\""+link+section+"\">"+text+"</a>"; break; case INTERWIKI: result = "<a class=\"interwiki\" href=\""+link+section+"\">"+text+"</a>"; break; case ATTACHMENT: String attlink = getURL( WikiContext.ATTACH, link ); String infolink = getURL( WikiContext.INFO, link ); String imglink = getURL( WikiContext.NONE, "images/attachment_small.png" ); result = "<a class=\"attachment\" href=\""+attlink+"\">"+text+"</a>"+ "<a href=\""+infolink+ "\"><img src=\""+imglink+"\" border=\"0\" alt=\"(info)\"/></a>"; break; default: result = ""; break; } return result; } /** * Writes HTML for error message. */ public String makeError( String error ) { return "<span class=\"error\">"+error+"</span>"; } /** * Emits a vertical line. */ public String makeRuler() { return "<hr />"; } /** * Modifies the "hd" parameter to contain proper values. Because * an "id" tag may only contain [a-zA-Z0-9:_-], we'll replace the * % after url encoding with '_'. */ private String makeHeadingAnchor( String baseName, String title, Heading hd ) { hd.m_titleText = title; title = cleanLink( title ); hd.m_titleSection = m_engine.encodeName(title); hd.m_titleAnchor = "section-"+m_engine.encodeName(baseName)+ "-"+hd.m_titleSection; hd.m_titleAnchor = hd.m_titleAnchor.replace( '%', '_' ); return hd.m_titleAnchor; } private String makeSectionTitle( String title ) { title = title.trim(); StringWriter outTitle = new StringWriter(); try { TranslatorReader read = getCleanTranslator(); read.setInputReader( new StringReader(title) ); FileUtil.copyContents( read, outTitle ); } catch( IOException e ) { log.fatal("CleanTranslator not working", e); throw new InternalWikiException("CleanTranslator not working as expected, when cleaning title"+ e.getMessage() ); } return outTitle.toString(); } /** * Returns XHTML for the start of the heading. Also sets the * line-end emitter. * @param level * @param headings A List to which heading should be added. */ public String makeHeading( int level, String title, Heading hd ) { String res = ""; String pageName = m_context.getPage().getName(); String outTitle = makeSectionTitle( title ); hd.m_level = level; switch( level ) { case Heading.HEADING_SMALL: res = "<h4 id='"+makeHeadingAnchor( pageName, outTitle, hd )+"'>"; m_closeTag = "</h4>"; break; case Heading.HEADING_MEDIUM: res = "<h3 id='"+makeHeadingAnchor( pageName, outTitle, hd )+"'>"; m_closeTag = "</h3>"; break; case Heading.HEADING_LARGE: res = "<h2 id='"+makeHeadingAnchor( pageName, outTitle, hd )+"'>"; m_closeTag = "</h2>"; break; } return res; } /** * @param bullet A character detailing which kind of a list * we are dealing with here. Options are '#' and '*'. */ public String openList( char bullet ) { String res = ""; if( bullet == ' res = "<ol>\n"; else if( bullet == '*' ) res = "<ul>\n"; else log.info("Warning: unknown bullet character '" + bullet + "' at (+)" ); return res; } public String openListItem() { return "<li>"; } public String closeListItem() { return "</li>\n"; } /** * @param bullet A character detailing which kind of a list * we are dealing with here. Options are '#' and '*'. */ public String closeList( char bullet ) { String res = ""; if( bullet == ' { res = "</ol>\n"; } else if( bullet == '*' ) { res = "</ul>\n"; } else { //FIXME unknown character -> error log.info("Warning: unknown character in unwind '" + bullet + "'" ); } return res; } public String openTable() { return "<table class=\"wikitable\" border=\"1\">\n"; } public String closeTable() { return "</table>\n"; } public String openTableRow() { return "<tr>"; } public String closeTableRow() { return "</tr>"; } public String openTableItem() { return "<td>"; } public String closeTableItem() { return "</td>"; } public String openTableHeading() { return "<th>"; } public String closeTableHeading() { return "</th>"; } public String openPreformatted( boolean isBlock ) { m_isPreBlock = isBlock; if( isBlock ) { return "<pre>"; } return "<span style=\"font-family:monospace; whitespace:pre;\">"; } public String closePreformatted() { if( m_isPreBlock ) return "</pre>\n"; return "</span>"; } /** * If outlink images are turned on, returns a link to the outward * linking image. */ public String outlinkImage() { if( m_useOutlinkImage ) { return "<img class=\"outlink\" src=\""+ getURL( WikiContext.NONE,"images/out.png" )+"\" alt=\"\" />"; } return ""; } /** * @param clear If true, then flushes all thingies. */ public String lineBreak( boolean clear ) { if( clear ) return "<br clear=\"all\" />"; return "<br />"; } } // HTMLRenderer /** * A very simple class for outputting plain text with no * formatting. */ private class TextRenderer { public void doChar( StringBuffer buf, char ch ) { buf.append( ch ); } public String openDiv( String style, String clazz ) { return ""; } public String closeDiv() { return ""; } public String openSpan( String style, String clazz ) { return ""; } public String closeSpan() { return ""; } public String openParagraph() { return ""; } public String closeParagraph() { return "\n\n"; } /** * Writes out a text effect */ public String openTextEffect( int effect ) { return ""; } public String closeTextEffect( int effect ) { return ""; } public String openDefinitionItem() { return " : "; } public String closeDefinitionItem() { return "\n"; } public String openDefinitionTitle() { return ""; } public String closeDefinitionTitle() { return ""; } public String openDefinitionList() { return ""; } public String closeDefinitionList() { return "\n"; } /** * Write a HTMLized link depending on its type. * * <p>This jsut calls makeLink() with "section" set to null. */ public String makeLink( int type, String link, String text ) { return text; } public String makeLink( int type, String link, String text, String section ) { return text; } /** * Writes HTML for error message. */ public String makeError( String error ) { return "ERROR: "+error; } /** * Emits a vertical line. */ public String makeRuler() { return " } /** * Returns XHTML for the start of the heading. Also sets the * line-end emitter. * @param level */ public String makeHeading( int level, String title, Heading hd ) { String res = ""; String pageName = m_context.getPage().getName(); title = title.trim(); hd.m_level = level; hd.m_titleText = title; hd.m_titleSection = ""; hd.m_titleAnchor = ""; switch( level ) { case Heading.HEADING_SMALL: res = title; m_closeTag = "\n\n"; break; case Heading.HEADING_MEDIUM: res = title; m_closeTag = "\n"+TextUtil.repeatString("-",title.length())+"\n\n"; break; case Heading.HEADING_LARGE: res = title.toUpperCase(); m_closeTag= "\n"+TextUtil.repeatString("=",title.length())+"\n\n"; break; } return res; } /** * @param bullet A character detailing which kind of a list * we are dealing with here. Options are '#' and '*'. */ // FIXME: Should really start a different kind of list depending // on the bullet type public String openList( char bullet ) { return "\n"; } public String openListItem() { return "- "; } public String closeListItem() { return "\n"; } /** * @param bullet A character detailing which kind of a list * we are dealing with here. Options are '#' and '*'. */ public String closeList( char bullet ) { return "\n\n"; } public String openTable() { return "\n"; } public String closeTable() { return "\n"; } public String openTableRow() { return ""; } public String closeTableRow() { return "\n"; } public String openTableItem() { return "\t"; } public String closeTableItem() { return ""; } public String openTableHeading() { return "\t"; } public String closeTableHeading() { return ""; } public String openPreformatted( boolean isBlock ) { return ""; } public String closePreformatted() { return "\n"; } /** * If outlink images are turned on, returns a link to the outward * linking image. */ public String outlinkImage() { return ""; } /** * @param clear If true, then flushes all thingies. */ public String lineBreak( boolean clear ) { return "\n"; } } // TextRenderer /** * This class is used to store the headings in a manner which * allow the building of a Table Of Contents. */ public class Heading { public static final int HEADING_SMALL = 1; public static final int HEADING_MEDIUM = 2; public static final int HEADING_LARGE = 3; public int m_level; public String m_titleText; public String m_titleAnchor; public String m_titleSection; } }
package org.basex.gui.dialog; import static org.basex.core.Text.*; import java.awt.BorderLayout; import java.io.File; import java.io.IOException; import java.net.BindException; import javax.swing.Box; import javax.swing.JPasswordField; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.basex.BaseXServer; import org.basex.core.Commands.CmdShow; import org.basex.core.Context; import org.basex.core.Main; import org.basex.core.Prop; import org.basex.core.proc.Exit; import org.basex.core.proc.Show; import org.basex.gui.GUI; import org.basex.gui.GUIProp; import org.basex.gui.layout.BaseXBack; import org.basex.gui.layout.BaseXButton; import org.basex.gui.layout.BaseXCombo; import org.basex.gui.layout.BaseXLabel; import org.basex.gui.layout.BaseXLayout; import org.basex.gui.layout.BaseXTabs; import org.basex.gui.layout.BaseXText; import org.basex.gui.layout.BaseXTextField; import org.basex.gui.layout.TableLayout; import org.basex.io.CachedOutput; import org.basex.io.IO; import org.basex.io.IOFile; import org.basex.server.ClientSession; import org.basex.server.LoginException; import org.basex.util.Token; public final class DialogServer extends Dialog { /** Context. */ final Context ctx = gui.context; /** ClientSession. */ ClientSession cs; /** Server panel. */ private final BaseXBack conn = new BaseXBack(); /** User panel. */ private final DialogUser user = new DialogUser(true, this, gui); /** Sessions/Databases panel. */ private final BaseXBack sedb = new BaseXBack(); /** Log panel. */ private final BaseXBack logs = new BaseXBack(); /** Stop button. */ private final BaseXButton stop; /** Start button. */ private final BaseXButton start; /** Connect button. */ private final BaseXButton connect; /** Disconnect button. */ private final BaseXButton disconnect; /** Refresh button. */ private final BaseXButton refresh; /** Shows log file. */ private final BaseXButton show; /** Deletes log file. */ private final BaseXButton delete; /** Deletes all log files. */ private final BaseXButton deleteAll; /** Server host. */ private final BaseXTextField host; /** Local server port. */ private final BaseXTextField ports; /** Server port. */ private final BaseXTextField portc; /** Log text. */ final BaseXText logt; /** Change button. */ private final BaseXTabs tabs; /** Username textfield. */ private final BaseXTextField loguser; /** Password textfield. */ private final JPasswordField logpass; /** Info label. */ private final BaseXLabel info; /** Info label. */ private final BaseXLabel info2; /** Combobox for log files. */ final BaseXCombo logc; /** String for log dir. */ private final String logdir = ctx.prop.get(Prop.DBPATH) + "/.logs/"; /** Boolean for check is server is running. */ private boolean running; /** Boolean for check if client is connected. */ private boolean connected; /** * Default constructor. * @param main reference to the main window */ public DialogServer(final GUI main) { super(main, SRVTITLE); tabs = new BaseXTabs(this); // Server panel conn.setLayout(new TableLayout(5, 1, 0, 4)); conn.setBorder(8, 8, 8, 8); tabs.add(SERVERN, conn); tabs.add(USERS, user); tabs.add(SESSIONS + "/" + DATABASES, sedb); tabs.add("Logs", logs); start = new BaseXButton(BUTTONSTASERV, this); stop = new BaseXButton(BUTTONSTOSERV, this); connect = new BaseXButton(BUTTONCONNECT, this); disconnect = new BaseXButton(BUTTONDISCONNECT, this); refresh = new BaseXButton(BUTTONREFRESH, this); host = new BaseXTextField(ctx.prop.get(Prop.HOST), this); host.addKeyListener(keys); ports = new BaseXTextField(Integer.toString(ctx.prop.num(Prop.SERVERPORT)), this); ports.addKeyListener(keys); portc = new BaseXTextField(Integer.toString(ctx.prop.num(Prop.PORT)), this); portc.addKeyListener(keys); loguser = new BaseXTextField(gui.prop.get(GUIProp.SERVERUSER), this); loguser.addKeyListener(keys); logpass = new JPasswordField(gui.prop.get(GUIProp.SERVERPASS)); logpass.addKeyListener(keys); BaseXLayout.setWidth(logpass, BaseXTextField.TWIDTH); info = new BaseXLabel(" "); info.setBorder(8, 0, 0, 0); // Local server panel. final BaseXBack p1 = new BaseXBack(); p1.setLayout(new TableLayout(2, 2, 8, 2)); p1.setBorder(8, 0, 8, 0); p1.add(new BaseXLabel(PORT + COLS)); p1.add(ports); final BaseXBack p11 = new BaseXBack(); p11.setLayout(new TableLayout(1, 2, 2, 2)); p11.add(start); p11.add(stop); p1.add(new BaseXLabel(" ")); p1.add(p11); // Login panel. final BaseXBack p2 = new BaseXBack(); p2.setLayout(new TableLayout(5, 2, 8, 2)); p2.add(new BaseXLabel(SERVERUSER + COLS)); p2.add(loguser); p2.add(new BaseXLabel(SERVERPW + COLS)); p2.add(logpass); p2.add(new BaseXLabel(HOST + COLS)); p2.add(host); p2.add(new BaseXLabel(PORT + COLS)); p2.add(portc); p2.add(new BaseXLabel(" ")); final BaseXBack p21 = new BaseXBack(); p21.setLayout(new TableLayout(1, 2, 2, 2)); p21.add(connect); p21.add(disconnect); p2.add(p21); conn.add(new BaseXLabel(LOCALSERVER + COLS, false, true)); conn.add(p1); conn.add(new BaseXLabel(LOGIN + COLS, false, true)); conn.add(p2); conn.add(info); logc = new BaseXCombo(new String[] {}, this); logt = new BaseXText(false, this); logs.setLayout(new BorderLayout(2, 0)); logs.setBorder(8, 8, 8, 8); final BaseXBack pl1 = new BaseXBack(); show = new BaseXButton("Show", this); delete = new BaseXButton("Delete", this); deleteAll = new BaseXButton("Delete All", this); pl1.add(logc); pl1.add(show); pl1.add(delete); pl1.add(deleteAll); pl1.add(Box.createHorizontalGlue()); logs.add(pl1, BorderLayout.NORTH); info2 = new BaseXLabel(" "); info2.setBorder(8, 0, 0, 0); logs.add(logt, BorderLayout.CENTER); logs.add(info2, BorderLayout.SOUTH); set(tabs, BorderLayout.CENTER); // test if server is running running = ping(true); // Register a change listener tabs.addChangeListener(new ChangeListener() { // This method is called whenever the selected tab changes public void stateChanged(final ChangeEvent evt) { BaseXTabs pane = (BaseXTabs) evt.getSource(); if (pane.getSelectedIndex() == 3) { Object tmp = logc.getSelectedItem(); int i = logc.getSelectedIndex(); if(i != -1) { action("Show"); } refreshLog(); logc.setSelectedItem(tmp); } } }); initLog(); action(null); finish(null); } /** * Checks if a server is running, ping like. * @param local local/remote flag * @return boolean success */ private boolean ping(final boolean local) { try { new ClientSession(local ? "localhost" : ctx.prop.get(Prop.HOST), ctx.prop.num(local ? Prop.SERVERPORT : Prop.PORT), "", ""); } catch(final IOException e) { if(e instanceof LoginException) return true; } return false; } @Override public void action(final String cmd) { String msg = null; String msg2 = null; try { if(BUTTONSTASERV.equals(cmd)) { final int p = Integer.parseInt(ports.getText()); ctx.prop.set(Prop.SERVERPORT, p); if(host.getText().equals("localhost")) { ctx.prop.set(Prop.PORT, p); portc.setText(ports.getText()); } final String path = IOFile.file(getClass().getProtectionDomain(). getCodeSource().getLocation().toString()); final String mem = "-Xmx" + Runtime.getRuntime().maxMemory(); final String clazz = org.basex.BaseXServer.class.getName(); new ProcessBuilder(new String[] { "java", mem, "-cp", path, clazz, "-p", String.valueOf(p)}).start(); running = ping(true); } else if(BUTTONSTOSERV.equals(cmd)) { BaseXServer.stop(gui.context); running = ping(true); connected = connected && ping(false); } else if(BUTTONCONNECT.equals(cmd)) { gui.prop.set(GUIProp.SERVERUSER, loguser.getText()); gui.prop.set(GUIProp.SERVERPASS, new String(logpass.getPassword())); ctx.prop.set(Prop.HOST, host.getText()); ctx.prop.set(Prop.PORT, Integer.parseInt(portc.getText())); cs = new ClientSession(ctx, gui.prop.get(GUIProp.SERVERUSER), gui.prop.get(GUIProp.SERVERPASS)); user.setSess(cs); fillsedb(); connected = true; } else if(BUTTONDISCONNECT.equals(cmd)) { cs.execute(new Exit()); connected = false; } else if(BUTTONREFRESH.equals(cmd)) { fillsedb(); } else if("Show".equals(cmd)) { final IO io = IO.get(logdir + logc.getSelectedItem().toString()); logt.setText(io.content()); } else if("Delete".equals(cmd)) { File f = new File(logdir + logc.getSelectedItem().toString()); if(f.delete()) { initLog(); } else { msg2 = "Delete not possible"; } } else if("Delete All".equals(cmd)) { boolean d = false; for(int i = 0; i < logc.getItemCount(); i++) { File f = new File(logdir + logc.getItemAt(i).toString()); d = f.delete(); } if(!d) msg2 = "Delete of all logs not possible"; initLog(); } else if(connected) { user.action(cmd); } } catch(final IOException ex) { Main.debug(ex); if(ex instanceof BindException) msg = SERVERBIND; else if(ex instanceof LoginException) msg = SERVERLOGIN; else msg = ex.getMessage(); //SERVERERR; } final boolean valp = portc.getText().matches("[\\d]+") && Integer.parseInt(portc.getText()) <= 65535; final boolean valpl = ports.getText().matches("[\\d]+") && Integer.parseInt(ports.getText()) <= 65535; final boolean vallu = loguser.getText().matches("[\\w]*"); final boolean vallp = new String(logpass.getPassword()).matches("[\\w]*"); final boolean valh = host.getText().matches("([\\w]+: boolean warn = true; if(msg != null || msg2 != null) { warn = false; } else if(!(valpl && valh && valp && vallu && vallp)) { msg = Main.info(INVALID, !valpl ? LOCALPORT : !valh ? HOST : !valp ? PORT : !vallu ? SERVERUSER : SERVERPW); } info.setError(msg, warn); info2.setError(msg2, warn); ports.setEnabled(!running); start.setEnabled(!running && valpl); stop.setEnabled(running); loguser.setEnabled(!connected); logpass.setEnabled(!connected); host.setEnabled(!connected); portc.setEnabled(!connected); connect.setEnabled(!connected && vallu && vallp && valh && valp && !loguser.getText().isEmpty() && logpass.getPassword().length != 0); disconnect.setEnabled(connected); tabs.setEnabledAt(1, connected); tabs.setEnabledAt(2, connected); show.setEnabled(logc.getSelectedIndex() != -1); delete.setEnabled(logc.getSelectedIndex() != -1); deleteAll.setEnabled(logc.getItemCount() > 0); ctx.prop.write(); } /** * Fills sessions/databases panel. * @throws IOException Exception */ private void fillsedb() throws IOException { sedb.removeAll(); sedb.setLayout(new TableLayout(4, 1, 2, 2)); sedb.setBorder(8, 8, 8, 8); final BaseXBack sess = new BaseXBack(); CachedOutput out = new CachedOutput(); sess.setLayout(new TableLayout(2, 1, 2, 2)); sess.add(new BaseXLabel(SESSIONS + COLS, false, true)); cs.execute(new Show(CmdShow.SESSIONS), out); BaseXText text = new BaseXText(false, this); text.setFont(getFont()); text.setBorder(new EmptyBorder(5, 5, 5, 5)); text.setText(out.finish()); BaseXLayout.setWidth(text, 420); BaseXLayout.setHeight(text, 100); sess.add(text); sedb.add(sess); sedb.add(new BaseXLabel(" ")); final BaseXBack dbs = new BaseXBack(); dbs.setLayout(new TableLayout(2, 1, 2, 2)); out = new CachedOutput(); cs.execute(new Show(CmdShow.DATABASES), out); BaseXText text1 = new BaseXText(false, this); text1.setFont(getFont()); text1.setBorder(new EmptyBorder(5, 5, 5, 5)); text1.setText(out.finish()); BaseXLayout.setWidth(text1, 420); BaseXLayout.setHeight(text1, 100); dbs.add(new BaseXLabel(DATABASES + COLS, false, true)); dbs.add(text1); sedb.add(dbs); sedb.add(refresh); } /** * Inits the log panel. */ void initLog() { refreshLog(); logc.setSelectedIndex(-1); logt.setText(Token.EMPTY); } /** * Refreshs the log panel. */ void refreshLog() { logc.removeAllItems(); final File f = new File(logdir); final String[] files = f.list(); if(files != null) { for(final String s : files) { if(s.endsWith(".log")) logc.addItem(s); } } } @Override public void cancel() { try { if(connected) cs.execute(new Exit()); } catch(final IOException ex) { Main.debug(ex); } super.cancel(); } }
package biomodel.gui.schematic; import java.awt.Rectangle; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Hashtable; import java.util.Properties; import java.util.Vector; import java.util.prefs.Preferences; import javax.swing.JOptionPane; import org.sbml.libsbml.CompModelPlugin; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.CompartmentGlyph; import org.sbml.libsbml.Constraint; import org.sbml.libsbml.Event; import org.sbml.libsbml.EventAssignment; import org.sbml.libsbml.GeneralGlyph; import org.sbml.libsbml.Layout; import org.sbml.libsbml.LineSegment; import org.sbml.libsbml.Model; import org.sbml.libsbml.ModifierSpeciesReference; import org.sbml.libsbml.Parameter; import org.sbml.libsbml.Reaction; import org.sbml.libsbml.ReactionGlyph; import org.sbml.libsbml.ReferenceGlyph; import org.sbml.libsbml.Rule; import org.sbml.libsbml.Species; import org.sbml.libsbml.SpeciesGlyph; import org.sbml.libsbml.SpeciesReference; import org.sbml.libsbml.SpeciesReferenceGlyph; import org.sbml.libsbml.TextGlyph; import main.Gui; //import javax.xml.bind.JAXBElement.GlobalScope; import biomodel.gui.Grid; import biomodel.gui.movie.MovieAppearance; import biomodel.gui.textualeditor.SBMLutilities; import biomodel.parser.BioModel; import biomodel.util.GlobalConstants; import biomodel.util.Utility; import com.mxgraph.model.mxCell; import com.mxgraph.model.mxGeometry; import com.mxgraph.model.mxICell; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.util.mxConstants; import com.mxgraph.util.mxPoint; import com.mxgraph.view.mxGraph; import com.mxgraph.view.mxStylesheet; /** * @author Tyler tpatterson80@gmail.com * */ public class BioGraph extends mxGraph { private double DIS_BETWEEN_NEIGHBORING_EDGES = 35.0; private double SECOND_SELF_INFLUENCE_DISTANCE = 20; private HashMap<String, mxCell> speciesToMxCellMap; private HashMap<String, mxCell> reactionsToMxCellMap; private HashMap<String, mxCell> compartmentsToMxCellMap; private HashMap<String, mxCell> rulesToMxCellMap; private HashMap<String, mxCell> constraintsToMxCellMap; private HashMap<String, mxCell> eventsToMxCellMap; private HashMap<String, mxCell> influencesToMxCellMap; private HashMap<String, mxCell> componentsToMxCellMap; private HashMap<String, mxCell> componentsConnectionsToMxCellMap; private HashMap<String, mxCell> drawnPromoterToMxCellMap; private HashMap<String, mxCell> variableToMxCellMap; private HashMap<String, mxCell> gridRectangleToMxCellMap; mxCell cell = new mxCell(); private BioModel bioModel; public final String CELL_NOT_FULLY_CONNECTED = "cell not fully connected"; private final String CELL_VALUE_NOT_FOUND = "cell value not found"; // only bother the user about bad promoters once. //This should be improved to happen once per GCM file if this will be a common error. public boolean isBuilding = false; public boolean dynamic = false; // Keep track of how many elements did not have positioning info. // This allows us to stack them in the topleft corner until they // are positioned by the user or a layout algorithm. int unpositionedElementCount = 0; private boolean lema; /** * constructor * @param bioModel */ public BioGraph(BioModel bioModel,boolean lema) { super(); // Turn editing off to prevent mxGraph from letting the user change the // label on the cell. We want to do this using the property windows. this.setCellsEditable(false); this.bioModel = bioModel; this.lema = lema; this.initializeMaps(); createStyleSheets(); } /** * sets the hash maps to null */ private void initializeMaps(){ speciesToMxCellMap = new HashMap<String, mxCell>(); reactionsToMxCellMap = new HashMap<String, mxCell>(); compartmentsToMxCellMap = new HashMap<String, mxCell>(); rulesToMxCellMap = new HashMap<String, mxCell>(); constraintsToMxCellMap = new HashMap<String, mxCell>(); eventsToMxCellMap = new HashMap<String, mxCell>(); componentsToMxCellMap = new HashMap<String, mxCell>(); influencesToMxCellMap = new HashMap<String, mxCell>(); componentsConnectionsToMxCellMap = new HashMap<String, mxCell>(); drawnPromoterToMxCellMap = new HashMap<String, mxCell>(); variableToMxCellMap = new HashMap<String, mxCell>(); gridRectangleToMxCellMap = new HashMap<String, mxCell>(); } //GRAPH BUILDING /** * appplies a layout to the graphComponent * * @param ident * @param graphComponent */ public void applyLayout(String ident, mxGraphComponent graphComponent){ Layouting.applyLayout(ident, this, graphComponent); } private void createLayoutConnection(Layout layout,String reactant,String product,String type) { ReactionGlyph reactionGlyph = layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+reactant+"__"+type+"__"+product); if (reactionGlyph!=null) reactionGlyph.removeFromParentAndDelete(); reactionGlyph = layout.createReactionGlyph(); reactionGlyph.setId(GlobalConstants.GLYPH+"__"+reactant+"__"+type+"__"+product); SpeciesReferenceGlyph speciesReferenceGlyph = reactionGlyph.createSpeciesReferenceGlyph(); speciesReferenceGlyph.setId(GlobalConstants.GLYPH+"__"+reactant+"__product__"+product); speciesReferenceGlyph.setSpeciesGlyphId(GlobalConstants.GLYPH+"__"+product); speciesReferenceGlyph.setRole("product"); LineSegment lineSegment = speciesReferenceGlyph.createLineSegment(); lineSegment.setStart(this.getSpeciesOrPromoterCell(reactant).getGeometry().getCenterX(), this.getSpeciesOrPromoterCell(reactant).getGeometry().getCenterY()); lineSegment.setEnd(this.getSpeciesOrPromoterCell(product).getGeometry().getCenterX(), this.getSpeciesOrPromoterCell(product).getGeometry().getCenterY()); } private void addSpeciesReferenceGlyph(mxCell cell,ReactionGlyph reactionGlyph,String reactionId,String speciesId, String role) { SpeciesReferenceGlyph speciesReferenceGlyph = reactionGlyph.createSpeciesReferenceGlyph(); speciesReferenceGlyph.setId(GlobalConstants.GLYPH+"__"+reactionId+"__"+role+"__"+speciesId); speciesReferenceGlyph.setSpeciesGlyphId(GlobalConstants.GLYPH+"__"+speciesId); speciesReferenceGlyph.setRole(role); LineSegment lineSegment = speciesReferenceGlyph.createLineSegment(); lineSegment.setStart(cell.getSource().getGeometry().getCenterX(),cell.getSource().getGeometry().getCenterY()); lineSegment.setEnd(cell.getTarget().getGeometry().getCenterX(),cell.getTarget().getGeometry().getCenterY()); } private void addReferenceGlyph(mxCell cell,GeneralGlyph generalGlyph,String objectId,String refId, String role) { ReferenceGlyph referenceGlyph = generalGlyph.createReferenceGlyph(); referenceGlyph.setId(GlobalConstants.GLYPH+"__"+objectId+"__"+role+"__"+refId); referenceGlyph.setGlyphId(GlobalConstants.GLYPH+"__"+refId); referenceGlyph.setRole(role); LineSegment lineSegment = referenceGlyph.createLineSegment(); lineSegment.setStart(cell.getSource().getGeometry().getCenterX(),cell.getSource().getGeometry().getCenterY()); lineSegment.setEnd(cell.getTarget().getGeometry().getCenterX(),cell.getTarget().getGeometry().getCenterY()); } /** * Builds the graph based on the internal representation * @return */ public boolean buildGraph() { this.isBuilding = true; this.allowDanglingEdges = false; // remove all the cells from the graph (vertices and edges) this.removeCells(this.getChildCells(this.getDefaultParent(), true, true)); initializeMaps(); assert(this.bioModel != null); // Start an undo transaction this.getModel().beginUpdate(); boolean needsPositioning = false; unpositionedElementCount = 0; //createGraphCompartmentFromModel("default"); //put the grid cells in first so that they're below the other cells addGridCells(); Layout layout = bioModel.createLayout(); for (long i = 0; i < bioModel.getSBMLDocument().getModel().getNumSpecies(); i++) { Species s = bioModel.getSBMLDocument().getModel().getSpecies(i); if (layout.getSpeciesGlyph(s.getId()) != null) { layout.getSpeciesGlyph(s.getId()).setId(GlobalConstants.GLYPH+"__"+s.getId()); layout.getTextGlyph(s.getId()).setId(GlobalConstants.TEXT_GLYPH+"__"+s.getId()); } } Model m = bioModel.getSBMLDocument().getModel(); // add compartments if (!bioModel.isGridEnabled()) { for (long i = 0; i < m.getNumCompartments(); i++) { Compartment c = m.getCompartment(i); if (layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+c.getId()) != null) { if(createGraphCompartmentFromModel(c.getId())) needsPositioning = true; } else { CompartmentGlyph compartmentGlyph = layout.createCompartmentGlyph(); compartmentGlyph.setId(GlobalConstants.GLYPH+"__"+c.getId()); compartmentGlyph.setCompartmentId(c.getId()); compartmentGlyph.getBoundingBox().setX((i*1070)/m.getNumCompartments()); compartmentGlyph.getBoundingBox().setY(0); compartmentGlyph.getBoundingBox().setWidth(1070/m.getNumCompartments()); compartmentGlyph.getBoundingBox().setHeight(425); TextGlyph textGlyph = null; if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+c.getId())!=null) { textGlyph = layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+c.getId()); } else { textGlyph = layout.createTextGlyph(); } textGlyph.setId(GlobalConstants.TEXT_GLYPH+"__"+c.getId()); textGlyph.setGraphicalObjectId(GlobalConstants.GLYPH+"__"+c.getId()); textGlyph.setText(c.getId()); textGlyph.setBoundingBox(compartmentGlyph.getBoundingBox()); if(createGraphCompartmentFromModel(c.getId())) needsPositioning = true; } } } // add species for(String sp : bioModel.getSpecies()){ if (bioModel.getSBMLDocument().getModel().getSpecies(sp).getAnnotationString().contains("type=\"grid\"")) continue; if(createGraphSpeciesFromModel(sp)) needsPositioning = true; } int x = 225; int y = 50; // add reactions for (int i = 0; i < m.getNumReactions(); i++) { Reaction r = m.getReaction(i); if (BioModel.isDegradationReaction(r)) continue; if (BioModel.isDiffusionReaction(r)) continue; if (BioModel.isProductionReaction(r)) continue; if (BioModel.isComplexReaction(r)) continue; if (BioModel.isConstitutiveReaction(r)) continue; if (r.getAnnotationString().contains("grid")) continue; if (layout.getReactionGlyph(r.getId()) != null) { layout.getReactionGlyph(r.getId()).setId(GlobalConstants.GLYPH+"__"+r.getId()); layout.getTextGlyph(r.getId()).setId(GlobalConstants.TEXT_GLYPH+"__"+r.getId()); } if (layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+r.getId()) != null) { if(createGraphReactionFromModel(r.getId())) needsPositioning = true; } else { if (r.getNumModifiers() > 0 || (r.getNumReactants()>1 && r.getNumProducts()>1) || r.getNumReactants()==0 || r.getNumProducts()==0) { if(createGraphReactionFromModel(r.getId())) needsPositioning = true; } } } // add rules for (long i = 0; i < m.getNumRules(); i++) { Rule rule = m.getRule(i); if (rule.getMetaId().endsWith("_"+GlobalConstants.RATE)) continue; if (rule.getVariable().startsWith(GlobalConstants.TRIGGER + "_")) continue; if (layout.getReactionGlyph(rule.getMetaId()) != null) { layout.getReactionGlyph(rule.getMetaId()).setId(GlobalConstants.GLYPH+"__"+rule.getMetaId()); layout.getTextGlyph(rule.getMetaId()).setId(GlobalConstants.TEXT_GLYPH+"__"+rule.getMetaId()); } if (layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+rule.getMetaId())!=null) { ReactionGlyph reactionGlyph = layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+rule.getMetaId()); GeneralGlyph generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(reactionGlyph.getId()); generalGlyph.unsetMetaIdRef(); generalGlyph.setReferenceId(reactionGlyph.getReactionId()); generalGlyph.setBoundingBox(reactionGlyph.getBoundingBox()); layout.removeReactionGlyph(GlobalConstants.GLYPH+"__"+rule.getMetaId()); } if(createGraphRuleFromModel(rule.getMetaId())) needsPositioning = true; } // add constraints for (long i = 0; i < m.getNumConstraints(); i++) { Constraint constraint = m.getConstraint(i); if (constraint.getMetaId().equals(GlobalConstants.FAIL_TRANSITION)) continue; if (layout.getReactionGlyph(constraint.getMetaId()) != null) { layout.getReactionGlyph(constraint.getMetaId()).setId(GlobalConstants.GLYPH+"__"+constraint.getMetaId()); layout.getTextGlyph(constraint.getMetaId()).setId(GlobalConstants.TEXT_GLYPH+"__"+constraint.getMetaId()); } if (layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+constraint.getMetaId())!=null) { ReactionGlyph reactionGlyph = layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+constraint.getMetaId()); GeneralGlyph generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(reactionGlyph.getId()); generalGlyph.unsetMetaIdRef(); generalGlyph.setReferenceId(reactionGlyph.getReactionId()); generalGlyph.setBoundingBox(reactionGlyph.getBoundingBox()); layout.removeReactionGlyph(GlobalConstants.GLYPH+"__"+constraint.getMetaId()); } if(createGraphConstraintFromModel(constraint.getMetaId())) needsPositioning = true; } // add events for (long i = 0; i < m.getNumEvents(); i++) { Event event = m.getEvent(i); if (layout.getReactionGlyph(event.getId()) != null) { layout.getReactionGlyph(event.getId()).setId(GlobalConstants.GLYPH+"__"+event.getId()); layout.getTextGlyph(event.getId()).setId(GlobalConstants.TEXT_GLYPH+"__"+event.getId()); } if (layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+event.getId())!=null) { ReactionGlyph reactionGlyph = layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+event.getId()); GeneralGlyph generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(reactionGlyph.getId()); generalGlyph.setReferenceId(reactionGlyph.getReactionId()); generalGlyph.setBoundingBox(reactionGlyph.getBoundingBox()); layout.removeReactionGlyph(GlobalConstants.GLYPH+"__"+event.getId()); } if (SBMLutilities.isTransition(event)) { if(createGraphTransitionFromModel(event.getId())) needsPositioning = true; } else { if(createGraphEventFromModel(event.getId())) needsPositioning = true; } } // add all variables if (!bioModel.isGridEnabled()) { for (long i = 0; i < m.getNumParameters(); i++) { Parameter p = m.getParameter(i); if (p.getId().equals(GlobalConstants.FAIL)) continue; if (p.getId().endsWith("_" + GlobalConstants.RATE)) continue; if (p.getId().startsWith(GlobalConstants.TRIGGER + "_")) continue; if (!p.getConstant()) { String id = p.getId(); if (layout.getSpeciesGlyph(GlobalConstants.GLYPH+"__"+id)!=null) { SpeciesGlyph speciesGlyph = layout.getSpeciesGlyph(GlobalConstants.GLYPH+"__"+id); GeneralGlyph generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(speciesGlyph.getId()); generalGlyph.setReferenceId(speciesGlyph.getSpeciesId()); generalGlyph.setBoundingBox(speciesGlyph.getBoundingBox()); layout.removeSpeciesGlyph(GlobalConstants.GLYPH+"__"+id); } if (SBMLutilities.isPlace(p)) { if(createGraphPlaceFromModel(p.getId(),p.getValue()==1.0)) needsPositioning = true; } else if (SBMLutilities.isBoolean(p)) { if(createGraphBooleanFromModel(p.getId(),p.getValue()==1.0)) needsPositioning = true; } else { if(createGraphVariableFromModel(p.getId())) needsPositioning = true; } } } } // add all components if (bioModel.isGridEnabled()) { for (long i = 0; i < m.getNumParameters(); ++i) { if (m.getParameter(i).getId().contains("__locations")) { String[] splitAnnotation = m.getParameter(i).getAnnotationString().replace("<annotation>","") .replace("</annotation>","").replace("\"","").replace("http: for (int j = 2; j < splitAnnotation.length; ++j) { splitAnnotation[j] = splitAnnotation[j].trim(); String submodelID = splitAnnotation[j].split("=")[0]; if (layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+submodelID)!=null) { CompartmentGlyph compartmentGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+submodelID); GeneralGlyph generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(compartmentGlyph.getId()); generalGlyph.setReferenceId(compartmentGlyph.getCompartmentId().replace(GlobalConstants.GLYPH+"__","")); generalGlyph.setBoundingBox(compartmentGlyph.getBoundingBox()); layout.removeReactionGlyph(GlobalConstants.GLYPH+"__"+submodelID); } if (createGraphComponentFromModel(submodelID)) needsPositioning = true; } } } // for (long i = 0; i < layout.getNumCompartmentGlyphs(); i++) { // String comp = layout.getCompartmentGlyph(i).getId(); // if (!comp.startsWith(GlobalConstants.GLYPH+"__")) { // layout.getCompartmentGlyph(i).setId(GlobalConstants.GLYPH+"__"+comp); // } else { // comp = comp.replace(GlobalConstants.GLYPH+"__",""); // //these are not meant to be displayed // //if (comp.contains("GRID__")) // // continue; // if (createGraphComponentFromModel(comp)) // needsPositioning = true; } else { CompModelPlugin sbmlCompModel = bioModel.getSBMLCompModel(); for (long i = 0; i < sbmlCompModel.getNumSubmodels(); i++) { String comp = sbmlCompModel.getSubmodel(i).getId(); //String comp = gcm.getSBMLCompModel().getSubmodel(i).getId(); //these are not meant to be displayed //if (comp.contains("GRID__")) // continue; if (layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+comp)!=null) { CompartmentGlyph compartmentGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+comp); GeneralGlyph generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(compartmentGlyph.getId()); generalGlyph.setReferenceId(compartmentGlyph.getCompartmentId()); generalGlyph.setBoundingBox(compartmentGlyph.getBoundingBox()); layout.removeCompartmentGlyph(GlobalConstants.GLYPH+"__"+comp); } if (createGraphComponentFromModel(comp)) needsPositioning = true; } } // add all the drawn promoters for(String prom : bioModel.getPromoters()){ if (bioModel.isPromoterExplicit(prom)) { if(createGraphDrawnPromoterFromModel(prom)) needsPositioning = true; } } boolean needsRedrawn = false; // add all the edges. for (int i = 0; i < m.getNumReactions(); i++) { Reaction r = m.getReaction(i); if (r.getAnnotationString().contains("grid")) continue; if (BioModel.isComplexReaction(r)) { for (int j = 0; j < r.getNumReactants(); j++) { String reactant = r.getReactant(j).getSpecies(); String product = r.getProduct(0).getSpecies(); String id = reactant + "+>" + product; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(reactant), this.getSpeciesCell(product)); String style = "COMPLEX"; mxCell cell = this.getInfluence(id); cell.setStyle(style); createLayoutConnection(layout,reactant,product,GlobalConstants.COMPLEX); } } else if (BioModel.isProductionReaction(r)) { String promoterId = r.getId().replace("Production_",""); if (bioModel.isPromoterExplicit(promoterId)) { for (int j = 0; j < r.getNumProducts(); j++) { if (r.getProduct(j).getSpecies().endsWith("_mRNA")) continue; String product = r.getProduct(j).getSpecies(); String id = promoterId + "->" + product; mxCell production = (mxCell)this.insertEdge(this.getDefaultParent(), id, "", this.getDrawnPromoterCell(promoterId),this.getSpeciesCell(product)); production.setStyle("PRODUCTION"); createLayoutConnection(layout,promoterId,product,GlobalConstants.PRODUCTION); } for (int j = 0; j < r.getNumModifiers(); j++) { if (BioModel.isRepressor(r.getModifier(j))) { String repressor = r.getModifier(j).getSpecies(); String id = repressor + "-|" + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(repressor),this.getDrawnPromoterCell(promoterId)); String style = "REPRESSION"; mxCell cell = this.getInfluence(id); cell.setStyle(style); createLayoutConnection(layout,repressor,promoterId,GlobalConstants.REPRESSION); } else if (BioModel.isActivator(r.getModifier(j))) { String activator = r.getModifier(j).getSpecies(); String id = activator + "->" + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(activator),this.getDrawnPromoterCell(promoterId)); String style = "ACTIVATION"; mxCell cell = this.getInfluence(id); cell.setStyle(style); createLayoutConnection(layout,activator,promoterId,GlobalConstants.ACTIVATION); } else if (BioModel.isRegulator(r.getModifier(j))) { String regulator = r.getModifier(j).getSpecies(); String id = regulator + "-|" + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(regulator),this.getDrawnPromoterCell(promoterId)); String style = "REPRESSION"; mxCell cell = this.getInfluence(id); cell.setStyle(style); id = regulator + "->" + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(regulator),this.getDrawnPromoterCell(promoterId)); style = "ACTIVATION"; cell = this.getInfluence(id); cell.setStyle(style); createLayoutConnection(layout,regulator,promoterId,GlobalConstants.REPRESSION); createLayoutConnection(layout,regulator,promoterId,GlobalConstants.ACTIVATION); } else if (BioModel.isNeutral(r.getModifier(j))) { String regulator = r.getModifier(j).getSpecies(); String id = regulator + "x>" + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(regulator),this.getDrawnPromoterCell(promoterId)); String style = "NOINFLUENCE"; mxCell cell = this.getInfluence(id); cell.setStyle(style); createLayoutConnection(layout,regulator,promoterId,GlobalConstants.NOINFLUENCE); } } } else { for (int j = 0; j < r.getNumModifiers(); j++) { for (int k = 0; k < r.getNumProducts(); k++) { if (BioModel.isRepressor(r.getModifier(j))) { String repressor = r.getModifier(j).getSpecies(); String product = r.getProduct(k).getSpecies(); String id = repressor + "-|" + product + "," + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(repressor),this.getSpeciesCell(product)); String style = "REPRESSION"; mxCell cell = this.getInfluence(id); cell.setStyle(style); cell.setValue(promoterId); createLayoutConnection(layout,repressor,product,GlobalConstants.REPRESSION); } else if (BioModel.isActivator(r.getModifier(j))) { String activator = r.getModifier(j).getSpecies(); String product = r.getProduct(k).getSpecies(); String id = activator + "->" + product + "," + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(activator),this.getSpeciesCell(product)); String style = "ACTIVATION"; mxCell cell = this.getInfluence(id); cell.setStyle(style); cell.setValue(promoterId); createLayoutConnection(layout,activator,product,GlobalConstants.REPRESSION); } else if (BioModel.isNeutral(r.getModifier(j))) { String regulator = r.getModifier(j).getSpecies(); String product = r.getProduct(k).getSpecies(); String id = regulator + "x>" + product + "," + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(regulator),this.getSpeciesCell(product)); String style = "NOINFLUENCE"; mxCell cell = this.getInfluence(id); cell.setStyle(style); cell.setValue(promoterId); createLayoutConnection(layout,regulator,product,GlobalConstants.NOINFLUENCE); } else if (BioModel.isRegulator(r.getModifier(j))) { String regulator = r.getModifier(j).getSpecies(); String product = r.getProduct(k).getSpecies(); String id = regulator + "-|" + product + "," + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(regulator),this.getSpeciesCell(product)); String style = "REPRESSION"; mxCell cell = this.getInfluence(id); cell.setStyle(style); cell.setValue(promoterId); id = regulator + "->" + product + "," + promoterId; this.insertEdge(this.getDefaultParent(), id, "", this.getSpeciesCell(regulator),this.getSpeciesCell(product)); style = "ACTIVATION"; cell = this.getInfluence(id); cell.setStyle(style); cell.setValue(promoterId); createLayoutConnection(layout,regulator,product,GlobalConstants.ACTIVATION); createLayoutConnection(layout,regulator,product,GlobalConstants.REPRESSION); } } } } } } //add reactions for (int i = 0; i < m.getNumReactions(); i++) { Reaction r = m.getReaction(i); if (BioModel.isDegradationReaction(r)) continue; if (BioModel.isDiffusionReaction(r)) continue; if (BioModel.isProductionReaction(r)) continue; if (BioModel.isComplexReaction(r)) continue; if (BioModel.isConstitutiveReaction(r)) continue; if (r.getAnnotationString().contains("grid")) continue; ReactionGlyph reactionGlyph = layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+r.getId()); if (reactionGlyph != null) { while (reactionGlyph.getNumSpeciesReferenceGlyphs() > 0) reactionGlyph.removeSpeciesReferenceGlyph(0); for (int j = 0; j < r.getNumReactants(); j++) { SpeciesReference s = r.getReactant(j); mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), s.getSpecies() + "__" + r.getId(), "", this.getSpeciesCell(s.getSpecies()), this.getReactionsCell(r.getId())); if (r.getReversible()) { if (s.getStoichiometry() != 1.0) cell.setValue(s.getStoichiometry()+",r"); else cell.setValue("r"); cell.setStyle("REV_REACTION_EDGE"); } else { if (s.getStoichiometry() != 1.0) cell.setValue(s.getStoichiometry()); cell.setStyle("REACTION_EDGE"); } String reactant = s.getSpecies(); addSpeciesReferenceGlyph(cell,reactionGlyph,r.getId(),reactant,"substrate"); } for (int j = 0; j < r.getNumModifiers(); j++) { ModifierSpeciesReference s = r.getModifier(j); mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), s.getSpecies() + "__" + r.getId(), "", this.getSpeciesCell(s.getSpecies()), this.getReactionsCell(r.getId())); if (r.getReversible()) cell.setValue("m"); cell.setStyle("MODIFIER_REACTION_EDGE"); String modifier = s.getSpecies(); addSpeciesReferenceGlyph(cell,reactionGlyph,r.getId(),modifier,"modifier"); } for (int k = 0; k < r.getNumProducts(); k++) { SpeciesReference s = r.getProduct(k); mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), r.getId() + "__" + s.getSpecies(), "", this.getReactionsCell(r.getId()), this.getSpeciesCell(s.getSpecies())); if (r.getReversible()) { if (s.getStoichiometry() != 1.0) cell.setValue(s.getStoichiometry()+",p"); else cell.setValue("p"); cell.setStyle("REV_REACTION_EDGE"); } else { if (s.getStoichiometry() != 1.0) cell.setValue(s.getStoichiometry()); cell.setStyle("REACTION_EDGE"); } String product = s.getSpecies(); addSpeciesReferenceGlyph(cell,reactionGlyph,r.getId(),product,"product"); } if (r.isSetKineticLaw()) { String initStr = SBMLutilities.myFormulaToString(r.getKineticLaw().getMath()); String[] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { Parameter parameter = m.getParameter(vars[j]); if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), parameter.getId() + "__" + r.getId(), "", this.getVariableCell(parameter.getId()), this.getReactionsCell(r.getId())); cell.setStyle("REACTION_EDGE"); addSpeciesReferenceGlyph(cell,reactionGlyph,r.getId(),parameter.getId(),"substrate"); } } } } else { for (int j = 0; j < r.getNumReactants(); j++) { SpeciesReference s1 = r.getReactant(j); for (int k = 0; k < r.getNumProducts(); k++) { SpeciesReference s2 = r.getProduct(k); mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), s1.getSpecies() + "_" + r.getId() + "_" + s2.getSpecies(), "", this.getSpeciesCell(s1.getSpecies()), this.getSpeciesCell(s2.getSpecies())); cell.setValue(r.getId()); if (r.getReversible()) { cell.setStyle("REV_REACTION_EDGE"); } else { cell.setStyle("REACTION_EDGE"); } } } } } //add rules for (int i = 0; i < m.getNumRules(); i++) { Rule r = m.getRule(i); if (r.getMetaId().endsWith("_"+GlobalConstants.RATE)) continue; if (r.getVariable().startsWith(GlobalConstants.TRIGGER+"_")) continue; GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+r.getMetaId()); if (generalGlyph != null) { while (generalGlyph.getNumReferenceGlyphs() > 0) generalGlyph.removeReferenceGlyph(0); String initStr = SBMLutilities.myFormulaToString(r.getMath()); String[] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { Species species = m.getSpecies(vars[j]); if (species != null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), species.getId() + "__" + r.getMetaId(), "", this.getSpeciesOrPromoterCell(species.getId()), this.getRulesCell(r.getMetaId())); cell.setStyle("RULE_EDGE"); addReferenceGlyph(cell,generalGlyph,r.getMetaId(),species.getId(),"substrate"); } else { Parameter parameter = m.getParameter(vars[j]); if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), parameter.getId() + "__" + r.getMetaId(), "", this.getVariableCell(parameter.getId()), this.getRulesCell(r.getMetaId())); cell.setStyle("RULE_EDGE"); addReferenceGlyph(cell,generalGlyph,r.getMetaId(),parameter.getId(),"substrate"); } } } // Add variable if (r.isAssignment() || r.isRate()) { Species species = m.getSpecies(r.getVariable()); if (species != null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), r.getMetaId() + "__" + species.getId(), "", this.getRulesCell(r.getMetaId()), this.getSpeciesOrPromoterCell(species.getId())); cell.setStyle("RULE_EDGE"); addReferenceGlyph(cell,generalGlyph,r.getMetaId(),species.getId(),"product"); } else { Parameter parameter = m.getParameter(r.getVariable()); if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), r.getMetaId() + "__" + parameter.getId(), "", this.getRulesCell(r.getMetaId()), this.getVariableCell(parameter.getId())); cell.setStyle("RULE_EDGE"); addReferenceGlyph(cell,generalGlyph,r.getMetaId(),parameter.getId(),"product"); } } } } } // add constraints for (int i = 0; i < m.getNumConstraints(); i++) { Constraint c = m.getConstraint(i); if (m.getMetaId().equals(GlobalConstants.FAIL_TRANSITION)) continue; GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+c.getMetaId()); if (generalGlyph != null) { while (generalGlyph.getNumReferenceGlyphs() > 0) generalGlyph.removeReferenceGlyph(0); String initStr = SBMLutilities.myFormulaToString(c.getMath()); String[] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { Species species = m.getSpecies(vars[j]); if (species != null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), species.getId() + "__" + c.getMetaId(), "", this.getSpeciesOrPromoterCell(species.getId()), this.getConstraintsCell(c.getMetaId())); cell.setStyle("CONSTRAINT_EDGE"); addReferenceGlyph(cell,generalGlyph,c.getMetaId(),species.getId(),"substrate"); } else { Parameter parameter = m.getParameter(vars[j]); if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), parameter.getId() + "__" + c.getMetaId(), "", this.getVariableCell(parameter.getId()), this.getConstraintsCell(c.getMetaId())); cell.setStyle("CONSTRAINT_EDGE"); addReferenceGlyph(cell,generalGlyph,c.getMetaId(),parameter.getId(),"substrate"); } } } } } // add event edges for (int i = 0; i < m.getNumEvents(); i++) { Event e = m.getEvent(i); boolean isTransition = SBMLutilities.isTransition(e); GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+e.getId()); if (generalGlyph != null) { while (generalGlyph.getNumReferenceGlyphs() > 0) generalGlyph.removeReferenceGlyph(0); if (!isTransition && e.isSetTrigger()) { String initStr = SBMLutilities.myFormulaToString(e.getTrigger().getMath()); String[] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { Species species = m.getSpecies(vars[j]); if (species != null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), species.getId() + "__" + e.getId(), "", this.getSpeciesOrPromoterCell(species.getId()), this.getEventsCell(e.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),species.getId(),"substrate"); } else { Parameter parameter = m.getParameter(vars[j]); if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), parameter.getId() + "__" + e.getId(), "", this.getVariableCell(parameter.getId()), this.getEventsCell(e.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),parameter.getId(),"substrate"); } } } } if (!isTransition && e.isSetDelay()) { String initStr = SBMLutilities.myFormulaToString(e.getDelay().getMath()); String [] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { Species species = m.getSpecies(vars[j]); if (species != null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), species.getId() + "__" + e.getId(), "", this.getSpeciesOrPromoterCell(species.getId()), this.getEventsCell(e.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),species.getId(),"substrate"); } else { Parameter parameter = m.getParameter(vars[j]); if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), parameter.getId() + "__" + e.getId(), "", this.getVariableCell(parameter.getId()), this.getEventsCell(e.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),parameter.getId(),"substrate"); } } } } if (!isTransition && e.isSetPriority()) { String initStr = SBMLutilities.myFormulaToString(e.getPriority().getMath()); String [] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { Species species = m.getSpecies(vars[j]); if (species != null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), species.getId() + "__" + e.getId(), "", this.getSpeciesOrPromoterCell(species.getId()), this.getEventsCell(e.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),species.getId(),"substrate"); } else { Parameter parameter = m.getParameter(vars[j]); if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), parameter.getId() + "__" + e.getId(), "", this.getVariableCell(parameter.getId()), this.getEventsCell(e.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),parameter.getId(),"substrate"); } } } } // Add variable for (int k = 0; k < e.getNumEventAssignments(); k++) { EventAssignment ea = e.getEventAssignment(k); String initStr = SBMLutilities.myFormulaToString(ea.getMath()); if (!isTransition) { String [] vars = initStr.split(" |\\(|\\)|\\,"); for (int j = 0; j < vars.length; j++) { Species species = m.getSpecies(vars[j]); if (species != null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), species.getId() + "__" + e.getId(), "", this.getSpeciesOrPromoterCell(species.getId()), this.getEventsCell(e.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),species.getId(),"substrate"); }else { Parameter parameter = m.getParameter(vars[j]); if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), parameter.getId() + "__" + e.getId(), "", this.getVariableCell(parameter.getId()), this.getEventsCell(e.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),parameter.getId(),"substrate"); } } } } Species species = m.getSpecies(ea.getVariable()); if (!isTransition && species != null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), e.getId() + "__" + species.getId(), "", this.getEventsCell(e.getId()), this.getSpeciesOrPromoterCell(species.getId())); cell.setStyle("EVENT_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),species.getId(),"product"); } else if (species==null){ Parameter parameter = m.getParameter(ea.getVariable()); if (parameter != null) { boolean isPlace = SBMLutilities.isPlace(parameter); if (!isTransition || (isPlace && initStr.equals("1"))) { if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), e.getId() + "__" + parameter.getId(), "", this.getEventsCell(e.getId()), this.getVariableCell(parameter.getId())); if (isTransition && isPlace) { cell.setStyle("TRANSITION_EDGE"); } else { cell.setStyle("EVENT_EDGE"); } addReferenceGlyph(cell,generalGlyph,e.getId(),parameter.getId(),"product"); } } else if (isPlace && initStr.equals("0")) { if (parameter != null && this.getVariableCell(parameter.getId())!=null) { mxCell cell = (mxCell)this.insertEdge(this.getDefaultParent(), e.getId() + "__" + parameter.getId(), "", this.getVariableCell(parameter.getId()), this.getEventsCell(e.getId())); cell.setStyle("TRANSITION_EDGE"); addReferenceGlyph(cell,generalGlyph,e.getId(),parameter.getId(),"substrate"); } } } } } } } addEdgeOffsets(); this.getModel().endUpdate(); this.isBuilding = false; // if we found any incorrectly marked promoters we need to redraw. Do so now. // The promoters should all pass the second time. if(needsRedrawn){ return buildGraph(); } return needsPositioning; } /** * Loop through all the edges and add control points to reposition them * if they are laying over the top of any other edges. */ public void addEdgeOffsets(){ // Make a hash where the key is a string built from the ids of the source and destination // of all the edges. The source and destination will be sorted so that the same two // source-destination pair will always map to the same key. The value is a list // of edges. That way if there are ever more then one edge between pairs, // we can modify the geometry so they don't overlap. HashMap<String, Vector<mxCell>> edgeHash = new HashMap<String, Vector<mxCell>>(); // build a temporary structure mapping sets of edge endpoints to edges // map influences Model m = bioModel.getSBMLDocument().getModel(); for (int i = 0; i < m.getNumReactions(); i++) { Reaction r = m.getReaction(i); if (BioModel.isComplexReaction(r)) { for (int j = 0; j < r.getNumReactants(); j++) { String endA = r.getReactant(j).getSpecies(); String endB = r.getProduct(0).getSpecies(); String id = r.getReactant(j).getSpecies() + "+>" + r.getProduct(0).getSpecies(); if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(id); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } } else if (BioModel.isProductionReaction(r)) { String promoterId = r.getId().replace("Production_",""); if (!bioModel.isPromoterExplicit(promoterId)) { for (int j = 0; j < r.getNumModifiers(); j++) { for (int k = 0; k < r.getNumProducts(); k++) { String endA = r.getModifier(j).getSpecies(); String endB = r.getProduct(k).getSpecies(); if (BioModel.isRepressor(r.getModifier(j))) { String id = r.getModifier(j).getSpecies() + "-|" + r.getProduct(k).getSpecies() + "," + promoterId; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(id); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } else if (BioModel.isActivator(r.getModifier(j))) { String id = r.getModifier(j).getSpecies() + "->" + r.getProduct(k).getSpecies() + "," + promoterId; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(id); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } else if (BioModel.isNeutral(r.getModifier(j))) { String id = r.getModifier(j).getSpecies() + "x>" + r.getProduct(k).getSpecies() + "," + promoterId; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(id); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } else if (BioModel.isRegulator(r.getModifier(j))) { String id = r.getModifier(j).getSpecies() + "->" + r.getProduct(k).getSpecies() + "," + promoterId; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(id); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); id = r.getModifier(j).getSpecies() + "-|" + r.getProduct(k).getSpecies() + "," + promoterId; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } key = endA + " " + endB; cell = this.getInfluence(id); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } } } } else { for (int j = 0; j < r.getNumModifiers(); j++) { String endA = r.getModifier(j).getSpecies(); String endB = promoterId; if (BioModel.isRegulator(r.getModifier(j))) { String id = r.getModifier(j).getSpecies() + "->" + promoterId; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(id); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); id = r.getModifier(j).getSpecies() + "-|" + promoterId; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } key = endA + " " + endB; cell = this.getInfluence(id); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } } } } } for (int i = 0; i < m.getNumReactions(); i++) { Reaction r = m.getReaction(i); if (BioModel.isDegradationReaction(r)) continue; if (BioModel.isDiffusionReaction(r)) continue; if (BioModel.isProductionReaction(r)) continue; if (BioModel.isComplexReaction(r)) continue; if (BioModel.isConstitutiveReaction(r)) continue; if (bioModel.getSBMLLayout().getLayout("iBioSim").getReactionGlyph(GlobalConstants.GLYPH+"__"+r.getId()) != null) { for (int j = 0; j < r.getNumReactants(); j++) { SpeciesReference s = r.getReactant(j); String endA = s.getSpecies(); String endB = r.getId(); if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(s.getSpecies() + "__" + r.getId()); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } for (int j = 0; j < r.getNumModifiers(); j++) { ModifierSpeciesReference s = r.getModifier(j); String endA = s.getSpecies(); String endB = r.getId(); if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(s.getSpecies() + "__" + r.getId()); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } for (int k = 0; k < r.getNumProducts(); k++) { SpeciesReference s = r.getProduct(k); String endA = r.getId(); String endB = s.getSpecies(); if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(r.getId() + "__" + s.getSpecies()); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } } else { for (int j = 0; j < r.getNumReactants(); j++) { SpeciesReference s1 = r.getReactant(j); for (int k = 0; k < r.getNumProducts(); k++) { SpeciesReference s2 = r.getProduct(k); String endA = s1.getSpecies(); String endB = s2.getSpecies(); // ignore anything connected directly to a drawn promoter //if(endA.equals(GlobalConstants.NONE) || endB.equals(GlobalConstants.NONE)) // continue; if(endA.compareTo(endB) > 0){ // swap the strings String t = endA; endA = endB; endB = t; } String key = endA + " " + endB; mxCell cell = this.getInfluence(s1.getSpecies() + "_" + r.getId() + "_" + s2.getSpecies()); if(edgeHash.containsKey(key) == false) edgeHash.put(key, new Vector<mxCell>()); edgeHash.get(key).add(cell); } } } } // map components edges for (long i = 0; i < bioModel.getSBMLCompModel().getNumSubmodels(); i++) { String id = bioModel.getSBMLCompModel().getSubmodel(i).getId(); BioModel compBioModel = new BioModel(bioModel.getPath()); String modelFileName = bioModel.getModelFileName(id); File compFile = new File(bioModel.getPath() + File.separator + modelFileName); compBioModel.load(bioModel.getPath() + File.separator + modelFileName); HashMap<String,String> connections = bioModel.getInputConnections(compBioModel,id); for (String propName : connections.keySet()) { String targetName = connections.get(propName); String type = "Input"; String key = id + " "+type+" " + targetName; mxCell cell = componentsConnectionsToMxCellMap.get(key); String simpleKey = id + " " + targetName; if(edgeHash.containsKey(simpleKey) == false) edgeHash.put(simpleKey, new Vector<mxCell>()); edgeHash.get(simpleKey).add(cell); } connections = bioModel.getOutputConnections(compBioModel,id); for (String propName : connections.keySet()) { String targetName = connections.get(propName); String type = "Output"; String key = id + " "+type+" " + targetName; mxCell cell = componentsConnectionsToMxCellMap.get(key); String simpleKey = id + " " + targetName; if(edgeHash.containsKey(simpleKey) == false) edgeHash.put(simpleKey, new Vector<mxCell>()); edgeHash.get(simpleKey).add(cell); } connections = bioModel.getVariableInputConnections(compBioModel,id); for (String propName : connections.keySet()) { String targetName = connections.get(propName); String type = "Input"; String key = id + " "+type+" " + targetName; mxCell cell = componentsConnectionsToMxCellMap.get(key); String simpleKey = id + " " + targetName; if(edgeHash.containsKey(simpleKey) == false) edgeHash.put(simpleKey, new Vector<mxCell>()); edgeHash.get(simpleKey).add(cell); } connections = bioModel.getVariableOutputConnections(compBioModel,id); for (String propName : connections.keySet()) { String targetName = connections.get(propName); String type = "Output"; String key = id + " "+type+" " + targetName; mxCell cell = componentsConnectionsToMxCellMap.get(key); String simpleKey = id + " " + targetName; if(edgeHash.containsKey(simpleKey) == false) edgeHash.put(simpleKey, new Vector<mxCell>()); edgeHash.get(simpleKey).add(cell); } } // loop through every set of edge endpoints and then move them if needed. for(Vector<mxCell> vec:edgeHash.values()){ if(vec.size() > 1 && vec.get(0) != null){ mxCell source = (mxCell)vec.get(0).getSource(); mxCell target = (mxCell)vec.get(0).getTarget(); // find the end and center points mxGeometry t; t = source.getGeometry(); mxPoint sp = new mxPoint(t.getCenterX(), t.getCenterY()); t = target.getGeometry(); mxPoint tp = new mxPoint(t.getCenterX(), t.getCenterY()); mxPoint cp = new mxPoint((tp.getX()+sp.getX())/2.0, (tp.getY()+sp.getY())/2.0); // check for self-influence if(source == target){ mxCell c = vec.get(0); mxGeometry geom = c.getGeometry(); // set the self-influence's point to the left of the influence. // This causes the graph library to draw it rounded in that direction. mxPoint p = new mxPoint( cp.getX() - t.getWidth()/2-SECOND_SELF_INFLUENCE_DISTANCE, cp.getY() ); Vector<mxPoint> points = new Vector<mxPoint>(); points.add(p); geom.setPoints(points); c.setGeometry(geom); continue; } // make a unit vector that points in the direction perpendicular to the // direction from one endpoint to the other. 90 degrees rotated means flip // the x and y coordinates. mxPoint dVec = new mxPoint(-(sp.getY()-tp.getY()), sp.getX()-tp.getX()); double magnitude = Math.sqrt(dVec.getX()*dVec.getX() + dVec.getY()*dVec.getY()); // avoid divide-by-zero errors magnitude = Math.max(magnitude, .1); // normalize dVec.setX(dVec.getX()/magnitude); dVec.setY(dVec.getY()/magnitude); // loop through all the edges, create a new midpoint and apply it. // also move the edge center to the midpoint so that labels won't be // on top of each other. for(int i=0; i<vec.size(); i++){ double offset = i-(vec.size()-1.0)/2.0; mxCell edge = vec.get(i); //cell.setGeometry(new mxGeometry(0, 0, 100, 100)); mxGeometry geom = edge.getGeometry(); Vector<mxPoint> points = new Vector<mxPoint>(); mxPoint p = new mxPoint( cp.getX()+dVec.getX()*offset*DIS_BETWEEN_NEIGHBORING_EDGES, cp.getY()+dVec.getY()*offset*DIS_BETWEEN_NEIGHBORING_EDGES ); points.add(p); geom.setPoints(points); // geom.setX(p.getX()); // geom.setY(p.getY()); edge.setGeometry(geom); } } } // for(Object edgeo:this.getSelectionCell()){ // mxCell edge = (mxCell)edgeo; // int s = edge.getSource().getEdgeCount(); // int t = edge.getTarget().getEdgeCount() // if(edge.getSource().getEdgeCount() > 1 && edge.getTarget().getEdgeCount() > 1){ // // the source and target have multiple edges, now loop through them all... // //cell.setGeometry(new mxGeometry(0, 0, 100, 100)); // mxGeometry geom = new mxGeometry(); // Vector<mxPoint> points = new Vector<mxPoint>(); // mxPoint p = new mxPoint(50.0, 50.0); // points.add(p); // geom.setPoints(points); // edge.setGeometry(geom); } /** * adds grid rectangles via cell vertices */ public void addGridCells() { if (bioModel.getGrid().isEnabled()) { int gridRows = bioModel.getGrid().getNumRows(); int gridCols = bioModel.getGrid().getNumCols(); double gridWidth = bioModel.getGrid().getGridGeomWidth(); double gridHeight = bioModel.getGrid().getGridGeomHeight(); //creates an mxCell/vertex for each grid rectangle //these are later accessible via ID via the hash map for (int row = 0; row < gridRows; ++row) { for (int col = 0; col < gridCols; ++col) { String id = "ROW" + row + "_COL" + col; double currX = 15 + col*gridWidth; double currY = 15 + row*gridHeight; CellValueObject cvo = new CellValueObject(id, "Rectangle", null); mxGeometry geometry = new mxGeometry(currX, currY, gridWidth, gridHeight); mxCell vertex = new mxCell(cvo, geometry, null); vertex.setId(id); vertex.setVertex(true); vertex.setConnectable(false); vertex.setStyle("GRID_RECTANGLE"); addCell(vertex, this.defaultParent); gridRectangleToMxCellMap.put(id, vertex); } } } } //POSITION UPDATING /** * Called after a layout is chosen and applied. * Updates the gcm's postitioning using the * positioning on the graph. */ public void updateAllInternalPosition(){ for(mxCell cell:this.compartmentsToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.speciesToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.reactionsToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.rulesToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.constraintsToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.eventsToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.componentsToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.drawnPromoterToMxCellMap.values()){ updateInternalPosition(cell); } for(mxCell cell:this.variableToMxCellMap.values()){ updateInternalPosition(cell); } } /** * Given a cell that must be a species or component, * update the internal model to reflect it's coordinates. * Called when a cell is dragged with the GUI. */ public void updateInternalPosition(mxCell cell){ mxGeometry geom = cell.getGeometry(); if (getCellType(cell).equals(GlobalConstants.SPECIES) || getCellType(cell).equals(GlobalConstants.PROMOTER)) { Layout layout = null; if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { layout = bioModel.getSBMLLayout().getLayout("iBioSim"); } else { layout = bioModel.getSBMLLayout().createLayout(); layout.setId("iBioSim"); } SpeciesGlyph speciesGlyph = null; if (layout.getSpeciesGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { speciesGlyph = layout.getSpeciesGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); } else { speciesGlyph = layout.createSpeciesGlyph(); speciesGlyph.setId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); speciesGlyph.setSpeciesId((String)cell.getId()); } String compartment = bioModel.getCompartmentByLocation((float)geom.getX(),(float)geom.getY(), (float)geom.getWidth(),(float)geom.getHeight()); if (compartment.equals("")) { geom.setX(speciesGlyph.getBoundingBox().x()); geom.setY(speciesGlyph.getBoundingBox().y()); geom.setWidth(speciesGlyph.getBoundingBox().width()); geom.setHeight(speciesGlyph.getBoundingBox().height()); Utility.createErrorMessage("Compartment Required", "Species must be placed within a compartment."); return; } bioModel.getSBMLDocument().getModel().getSpecies((String)cell.getId()).setCompartment(compartment); speciesGlyph.getBoundingBox().setX(geom.getX()); speciesGlyph.getBoundingBox().setY(geom.getY()); speciesGlyph.getBoundingBox().setWidth(geom.getWidth()); speciesGlyph.getBoundingBox().setHeight(geom.getHeight()); TextGlyph textGlyph = null; if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId())!=null) { textGlyph = layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); } else { textGlyph = layout.createTextGlyph(); } textGlyph.setId(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); textGlyph.setGraphicalObjectId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); textGlyph.setText((String)cell.getId()); textGlyph.setBoundingBox(speciesGlyph.getBoundingBox()); } else if (getCellType(cell).equals(GlobalConstants.VARIABLE) || getCellType(cell).equals(GlobalConstants.PLACE) || getCellType(cell).equals(GlobalConstants.BOOLEAN)) { Layout layout = null; if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { layout = bioModel.getSBMLLayout().getLayout("iBioSim"); } else { layout = bioModel.getSBMLLayout().createLayout(); layout.setId("iBioSim"); } GeneralGlyph generalGlyph = null; if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { generalGlyph = (GeneralGlyph)layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); } else { generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); generalGlyph.setReferenceId((String)cell.getId()); } generalGlyph.getBoundingBox().setX(geom.getX()); generalGlyph.getBoundingBox().setY(geom.getY()); generalGlyph.getBoundingBox().setWidth(geom.getWidth()); generalGlyph.getBoundingBox().setHeight(geom.getHeight()); TextGlyph textGlyph = null; if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId())!=null) { textGlyph = layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); } else { textGlyph = layout.createTextGlyph(); } textGlyph.setId(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); textGlyph.setGraphicalObjectId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); textGlyph.setText((String)cell.getId()); textGlyph.setBoundingBox(generalGlyph.getBoundingBox()); } else if (getCellType(cell).equals(GlobalConstants.REACTION)) { Layout layout = null; if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { layout = bioModel.getSBMLLayout().getLayout("iBioSim"); } else { layout = bioModel.getSBMLLayout().createLayout(); layout.setId("iBioSim"); } ReactionGlyph reactionGlyph = null; if (layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { reactionGlyph = layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); } else { reactionGlyph = layout.createReactionGlyph(); reactionGlyph.setId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); reactionGlyph.setReactionId((String)cell.getId()); } if (getCellType(cell).equals(GlobalConstants.REACTION)) { String compartment = bioModel.getCompartmentByLocation((float)geom.getX(),(float)geom.getY(), (float)geom.getWidth(),(float)geom.getHeight()); if (compartment.equals("")) { geom.setX(reactionGlyph.getBoundingBox().x()); geom.setY(reactionGlyph.getBoundingBox().y()); geom.setWidth(reactionGlyph.getBoundingBox().width()); geom.setHeight(reactionGlyph.getBoundingBox().height()); Utility.createErrorMessage("Compartment Required", "Reaction must be placed within a compartment."); return; } bioModel.getSBMLDocument().getModel().getReaction((String)cell.getId()).setCompartment(compartment); } reactionGlyph.getBoundingBox().setX(geom.getX()); reactionGlyph.getBoundingBox().setY(geom.getY()); reactionGlyph.getBoundingBox().setWidth(geom.getWidth()); reactionGlyph.getBoundingBox().setHeight(geom.getHeight()); TextGlyph textGlyph = null; if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId())!=null) { textGlyph = layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); } else { textGlyph = layout.createTextGlyph(); } textGlyph.setId(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); textGlyph.setGraphicalObjectId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); textGlyph.setText((String)cell.getId()); textGlyph.setBoundingBox(reactionGlyph.getBoundingBox()); } else if (getCellType(cell).equals(GlobalConstants.RULE)|| getCellType(cell).equals(GlobalConstants.CONSTRAINT)|| getCellType(cell).equals(GlobalConstants.EVENT)|| getCellType(cell).equals(GlobalConstants.TRANSITION)) { Layout layout = null; if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { layout = bioModel.getSBMLLayout().getLayout("iBioSim"); } else { layout = bioModel.getSBMLLayout().createLayout(); layout.setId("iBioSim"); } GeneralGlyph generalGlyph = null; if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); } else { generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); if (getCellType(cell).equals(GlobalConstants.EVENT)) { generalGlyph.setReferenceId((String)cell.getId()); } else { generalGlyph.unsetMetaIdRef(); generalGlyph.setReferenceId((String)cell.getId()); } } generalGlyph.getBoundingBox().setX(geom.getX()); generalGlyph.getBoundingBox().setY(geom.getY()); generalGlyph.getBoundingBox().setWidth(geom.getWidth()); generalGlyph.getBoundingBox().setHeight(geom.getHeight()); TextGlyph textGlyph = null; if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId())!=null) { textGlyph = layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); } else { textGlyph = layout.createTextGlyph(); } textGlyph.setId(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); textGlyph.setGraphicalObjectId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); textGlyph.setText((String)cell.getId()); textGlyph.setBoundingBox(generalGlyph.getBoundingBox()); } else if (!bioModel.isGridEnabled() && getCellType(cell).equals(GlobalConstants.COMPARTMENT)) { Layout layout = null; if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { layout = bioModel.getSBMLLayout().getLayout("iBioSim"); } else { layout = bioModel.getSBMLLayout().createLayout(); layout.setId("iBioSim"); } CompartmentGlyph compGlyph = null; if (layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { compGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); } else { compGlyph = layout.createCompartmentGlyph(); compGlyph.setId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); compGlyph.setCompartmentId((String)cell.getId()); } double x = compGlyph.getBoundingBox().x(); double y = compGlyph.getBoundingBox().y(); double width = compGlyph.getBoundingBox().width(); double height = compGlyph.getBoundingBox().height(); if (!bioModel.checkCompartmentLocation(cell.getId(),geom.getX(), geom.getY(), geom.getWidth(), geom.getHeight())) { geom.setX(x); geom.setY(y); geom.setWidth(width); geom.setHeight(height); Utility.createErrorMessage("Compartment Overlap", "Compartments must not overlap."); return; } compGlyph.getBoundingBox().setX(geom.getX()); compGlyph.getBoundingBox().setY(geom.getY()); compGlyph.getBoundingBox().setWidth(geom.getWidth()); compGlyph.getBoundingBox().setHeight(geom.getHeight()); if (bioModel.updateCompartmentsByLocation(true)) { bioModel.updateCompartmentsByLocation(false); } else { compGlyph.getBoundingBox().setX(x); compGlyph.getBoundingBox().setY(y); compGlyph.getBoundingBox().setWidth(width); compGlyph.getBoundingBox().setHeight(height); Utility.createErrorMessage("Missing Compartment", "All species and reactions must be within a compartment."); } geom.setX(compGlyph.getBoundingBox().x()); geom.setY(compGlyph.getBoundingBox().y()); geom.setWidth(compGlyph.getBoundingBox().width()); geom.setHeight(compGlyph.getBoundingBox().height()); TextGlyph textGlyph = null; if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId())!=null) { textGlyph = layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); } else { textGlyph = layout.createTextGlyph(); } textGlyph.setId(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); textGlyph.setGraphicalObjectId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); textGlyph.setText((String)cell.getId()); textGlyph.setBoundingBox(compGlyph.getBoundingBox()); } else if (getCellType(cell).equals(GlobalConstants.COMPONENT)) { Layout layout = null; if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { layout = bioModel.getSBMLLayout().getLayout("iBioSim"); } else { layout = bioModel.getSBMLLayout().createLayout(); layout.setId("iBioSim"); } GeneralGlyph generalGlyph = null; if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); } else { generalGlyph = layout.createGeneralGlyph(); generalGlyph.setId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); generalGlyph.setReferenceId((String)cell.getId()); } double x = generalGlyph.getBoundingBox().x(); double y = generalGlyph.getBoundingBox().y(); double width = generalGlyph.getBoundingBox().width(); double height = generalGlyph.getBoundingBox().height(); generalGlyph.getBoundingBox().setX(geom.getX()); generalGlyph.getBoundingBox().setY(geom.getY()); generalGlyph.getBoundingBox().setWidth(geom.getWidth()); generalGlyph.getBoundingBox().setHeight(geom.getHeight()); geom.setX(generalGlyph.getBoundingBox().x()); geom.setY(generalGlyph.getBoundingBox().y()); geom.setWidth(generalGlyph.getBoundingBox().width()); geom.setHeight(generalGlyph.getBoundingBox().height()); TextGlyph textGlyph = null; if (layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId())!=null) { textGlyph = layout.getTextGlyph(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); } else { textGlyph = layout.createTextGlyph(); } textGlyph.setId(GlobalConstants.TEXT_GLYPH+"__"+(String)cell.getId()); textGlyph.setGraphicalObjectId(GlobalConstants.GLYPH+"__"+(String)cell.getId()); textGlyph.setText((String)cell.getId()); textGlyph.setBoundingBox(generalGlyph.getBoundingBox()); } } /** * Given a species, component, or drawn promoter cell, position it * using the properties. */ private boolean sizeAndPositionFromProperties(mxCell cell,double width,double height){ double x = 0; double y = 0; boolean needsPositioning = false; if (getCellType(cell).equals(GlobalConstants.SPECIES)|| getCellType(cell).equals(GlobalConstants.PROMOTER)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getSpeciesGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { SpeciesGlyph speciesGlyph = layout.getSpeciesGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = speciesGlyph.getBoundingBox().getPosition().getXOffset(); y = speciesGlyph.getBoundingBox().getPosition().getYOffset(); width = speciesGlyph.getBoundingBox().getDimensions().getWidth(); height = speciesGlyph.getBoundingBox().getDimensions().getHeight(); } else { unpositionedElementCount += 1; needsPositioning = true; x = (unpositionedElementCount%50) * 20; y = (unpositionedElementCount%10) * (height + 10); if (bioModel.getSBMLDocument().getModel().getSpecies((String)cell.getId())!=null) { String compartment = bioModel.getSBMLDocument().getModel().getSpecies((String)cell.getId()).getCompartment(); if (!bioModel.getCompartmentByLocation((float)x, (float)y, (float)width, (float)height).equals(compartment)) { CompartmentGlyph compartmentGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+compartment); if (compartmentGlyph!=null) { x = x + compartmentGlyph.getBoundingBox().x(); if (!bioModel.getCompartmentByLocation((float)x, (float)y, (float)width, (float)height).equals(compartment)) { x = compartmentGlyph.getBoundingBox().x() + 10; } } } } bioModel.placeSpecies((String)cell.getId(), x, y, height, width); } } } else if (getCellType(cell).equals(GlobalConstants.VARIABLE)|| getCellType(cell).equals(GlobalConstants.PLACE)|| getCellType(cell).equals(GlobalConstants.BOOLEAN)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = generalGlyph.getBoundingBox().getPosition().getXOffset(); y = generalGlyph.getBoundingBox().getPosition().getYOffset(); width = generalGlyph.getBoundingBox().getDimensions().getWidth(); height = generalGlyph.getBoundingBox().getDimensions().getHeight(); } else { unpositionedElementCount += 1; needsPositioning = true; x = (unpositionedElementCount%50) * 20; y = (unpositionedElementCount%10) * (height + 10); if (bioModel.getSBMLDocument().getModel().getSpecies((String)cell.getId())!=null) { String compartment = bioModel.getSBMLDocument().getModel().getSpecies((String)cell.getId()).getCompartment(); if (!bioModel.getCompartmentByLocation((float)x, (float)y, (float)width, (float)height).equals(compartment)) { CompartmentGlyph compartmentGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+compartment); if (compartmentGlyph!=null) { x = x + compartmentGlyph.getBoundingBox().x(); if (!bioModel.getCompartmentByLocation((float)x, (float)y, (float)width, (float)height).equals(compartment)) { x = compartmentGlyph.getBoundingBox().x() + 10; } } } } bioModel.placeSpecies((String)cell.getId(), x, y, height, width); } } } else if (getCellType(cell).equals(GlobalConstants.REACTION)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { ReactionGlyph reactionGlyph = layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = reactionGlyph.getBoundingBox().getPosition().getXOffset(); y = reactionGlyph.getBoundingBox().getPosition().getYOffset(); width = reactionGlyph.getBoundingBox().getDimensions().getWidth(); height = reactionGlyph.getBoundingBox().getDimensions().getHeight(); } else { unpositionedElementCount += 1; needsPositioning = true; x = (unpositionedElementCount%50) * 20; y = (unpositionedElementCount%10) * (height + 10); if (bioModel.getSBMLDocument().getModel().getReaction((String)cell.getId())!=null) { String compartment = bioModel.getSBMLDocument().getModel().getReaction((String)cell.getId()).getCompartment(); if (!bioModel.getCompartmentByLocation((float)x, (float)y, (float)width, (float)height).equals(compartment)) { CompartmentGlyph compartmentGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+compartment); if (compartmentGlyph!=null) { x = x + compartmentGlyph.getBoundingBox().x(); if (!bioModel.getCompartmentByLocation((float)x, (float)y, (float)width, (float)height).equals(compartment)) { x = compartmentGlyph.getBoundingBox().x() + 10; } } } } bioModel.placeReaction((String)cell.getId(), x, y, height, width); } } } else if (getCellType(cell).equals(GlobalConstants.RULE) || getCellType(cell).equals(GlobalConstants.CONSTRAINT) || getCellType(cell).equals(GlobalConstants.EVENT) || getCellType(cell).equals(GlobalConstants.TRANSITION)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = generalGlyph.getBoundingBox().getPosition().getXOffset(); y = generalGlyph.getBoundingBox().getPosition().getYOffset(); width = generalGlyph.getBoundingBox().getDimensions().getWidth(); height = generalGlyph.getBoundingBox().getDimensions().getHeight(); } else { unpositionedElementCount += 1; needsPositioning = true; x = (unpositionedElementCount%50) * 20; y = (unpositionedElementCount%10) * (height + 10); if (bioModel.getSBMLDocument().getModel().getReaction((String)cell.getId())!=null) { String compartment = bioModel.getSBMLDocument().getModel().getReaction((String)cell.getId()).getCompartment(); if (!bioModel.getCompartmentByLocation((float)x, (float)y, (float)width, (float)height).equals(compartment)) { CompartmentGlyph compartmentGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+compartment); if (compartmentGlyph!=null) { x = x + compartmentGlyph.getBoundingBox().x(); if (!bioModel.getCompartmentByLocation((float)x, (float)y, (float)width, (float)height).equals(compartment)) { x = compartmentGlyph.getBoundingBox().x() + 10; } } } } bioModel.placeReaction((String)cell.getId(), x, y, height, width); } } } else if (!bioModel.isGridEnabled() && getCellType(cell).equals(GlobalConstants.COMPARTMENT)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { CompartmentGlyph compGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = compGlyph.getBoundingBox().getPosition().getXOffset(); y = compGlyph.getBoundingBox().getPosition().getYOffset(); width = compGlyph.getBoundingBox().getDimensions().getWidth(); height = compGlyph.getBoundingBox().getDimensions().getHeight(); } else { unpositionedElementCount += 1; needsPositioning = true; x = (unpositionedElementCount%50) * 20; y = (unpositionedElementCount%10) * (height + 10); bioModel.placeCompartment((String)cell.getId(), x, y, height, width); } } } else if (getCellType(cell).equals(GlobalConstants.COMPONENT)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = generalGlyph.getBoundingBox().getPosition().getXOffset(); y = generalGlyph.getBoundingBox().getPosition().getYOffset(); width = generalGlyph.getBoundingBox().getDimensions().getWidth(); height = generalGlyph.getBoundingBox().getDimensions().getHeight(); } else { unpositionedElementCount += 1; needsPositioning = true; x = (unpositionedElementCount%50) * 20; y = (unpositionedElementCount%10) * (height + 10); bioModel.placeCompartment((String)cell.getId(), x, y, height, width); } } } cell.setGeometry(new mxGeometry(x, y, width, height)); return needsPositioning; } /** * redraws the grid components */ public void updateGrid() { dynamic = true; this.removeCells(this.getChildCells(this.getDefaultParent(), true, true)); gridRectangleToMxCellMap.clear(); addGridCells(); componentsToMxCellMap.clear(); Grid grid = bioModel.getGrid(); double gridWidth = grid.getGridGeomWidth(); double gridHeight = grid.getGridGeomHeight(); componentsToMxCellMap.clear(); //ADD COMPONENTS for (int row = 0; row < grid.getNumRows(); ++row) { for (int col = 0; col < grid.getNumCols(); ++col) { if (grid.getOccupancyFromLocation(row, col) == true) { double currX = 15 + col*gridWidth; double currY = 15 + row*gridHeight; String compID = grid.getCompIDFromLocation(row, col); grid.setNodeRectangle(compID, new Rectangle((int) currX, (int) currY, (int) gridWidth, (int) gridHeight)); Rectangle componentRectangle = grid.getSnapRectangleFromCompID(compID); String fullCompID = compID; if (compID.contains("_of_")) compID = compID.split("_")[0]; if (compID.length() > 10) { compID = compID.substring(0,9) + "..."; } CellValueObject compcvo = new CellValueObject(compID, "Component", null); mxCell compCell = (mxCell) this.insertVertex(this.getDefaultParent(), fullCompID, compcvo, componentRectangle.getX(), componentRectangle.getY(), componentRectangle.getWidth(), componentRectangle.getHeight()); compCell.setConnectable(false); compCell.setStyle("GRIDCOMPARTMENT"); componentsToMxCellMap.put(fullCompID, compCell); } } } } //GET METHODS /** * returns GlobalConstants.SPECIES, GlobalConstants.COMPONENT, GlobalConstants.INFLUENCE, or GlobalConstants.COMPONENT_CONNECTION. * @param cell */ public String getCellType(mxCell cell){ if(cell != null && cell.isEdge()){ String sourceType = getCellType(cell.getSource()); String targetType = getCellType(cell.getTarget()); if(sourceType == CELL_VALUE_NOT_FOUND || targetType == CELL_VALUE_NOT_FOUND){ return CELL_NOT_FULLY_CONNECTED; } else if(sourceType == GlobalConstants.COMPONENT || targetType == GlobalConstants.COMPONENT){ return GlobalConstants.COMPONENT_CONNECTION; } else if(sourceType == GlobalConstants.PROMOTER && targetType == GlobalConstants.SPECIES){ return GlobalConstants.PRODUCTION; } else if (sourceType == GlobalConstants.SPECIES && targetType == GlobalConstants.SPECIES && (bioModel.getSBMLDocument().getModel().getNumReactions() > 0) && cell.getValue() != null && (bioModel.getSBMLDocument().getModel().getReaction((String)cell.getValue()) != null)) { return GlobalConstants.REACTION_EDGE; } else if (sourceType == GlobalConstants.REACTION || targetType == GlobalConstants.REACTION) { return GlobalConstants.REACTION_EDGE; } else if (sourceType == GlobalConstants.RULE || targetType == GlobalConstants.RULE) { return GlobalConstants.RULE_EDGE; } else if (sourceType == GlobalConstants.CONSTRAINT || targetType == GlobalConstants.CONSTRAINT) { return GlobalConstants.CONSTRAINT_EDGE; } else if (sourceType == GlobalConstants.EVENT || targetType == GlobalConstants.EVENT) { return GlobalConstants.EVENT_EDGE; } else if (sourceType == GlobalConstants.TRANSITION || targetType == GlobalConstants.TRANSITION) { return GlobalConstants.PETRI_NET_EDGE; } else { return GlobalConstants.INFLUENCE; } } //cell is a vertex else if (cell != null){ String type = ((CellValueObject)(cell.getValue())).type; if(type.equals("Component")) return GlobalConstants.COMPONENT; else if(type.equals("Species")) return GlobalConstants.SPECIES; else if(type.equals("Promoter")) return GlobalConstants.PROMOTER; else if(type.equals("Variable")) return GlobalConstants.VARIABLE; else if(type.equals("Place")) return GlobalConstants.PLACE; else if(type.equals("Boolean")) return GlobalConstants.BOOLEAN; else if(type.equals("Reaction")) return GlobalConstants.REACTION; else if(type.equals("Rule")) return GlobalConstants.RULE; else if(type.equals("Constraint")) return GlobalConstants.CONSTRAINT; else if(type.equals("Event")) return GlobalConstants.EVENT; else if(type.equals("Transition")) return GlobalConstants.TRANSITION; else if(type.equals("Compartment")) return GlobalConstants.COMPARTMENT; else if (type.equals("Rectangle")) return GlobalConstants.GRID_RECTANGLE; else return CELL_VALUE_NOT_FOUND; } return CELL_VALUE_NOT_FOUND; } /** * * @param cell * @return */ public String getCellType(mxICell cell) { return getCellType((mxCell)cell); } public String getModelFileName(String compId) { return bioModel.getModelFileName(compId).replace(".xml", ".gcm"); } /** * * @param id * @return */ public mxCell getSpeciesCell(String id){ return speciesToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getSpeciesOrPromoterCell(String id){ mxCell cell = speciesToMxCellMap.get(id); if (cell==null) { cell = drawnPromoterToMxCellMap.get(id); } return cell; } /** * * @param id * @return */ public mxCell getReactionsCell(String id){ return reactionsToMxCellMap.get(id); } public mxCell getCompartmentsCell(String id){ return compartmentsToMxCellMap.get(id); } public mxCell getRulesCell(String id){ return rulesToMxCellMap.get(id); } public mxCell getConstraintsCell(String id){ return constraintsToMxCellMap.get(id); } public mxCell getEventsCell(String id){ return eventsToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getComponentCell(String id){ return componentsToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getDrawnPromoterCell(String id){ return drawnPromoterToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getVariableCell(String id){ return variableToMxCellMap.get(id); } /** * * @param id * @return */ public mxCell getInfluence(String id){ return (influencesToMxCellMap.get(id)); } /** * returns the mxCell corresponding to the id passed in * this mxCell is a grid rectangle on the grid * * @param id the id of the grid rectangle's cell * @return the corresponding cell */ public mxCell getGridRectangleCellFromID(String id) { return gridRectangleToMxCellMap.get(id); } /** * returns if the cell is selectable or not * * @param cell the cell that is or isn't selectable */ @Override public boolean isCellSelectable(Object cell) { mxCell tempCell = (mxCell)cell; //if it's a grid cell, it's not selectable //otherwise, do the default behavior if (tempCell.getStyle().equals("GRID_RECTANGLE")) return false; return isCellsSelectable(); } //GRAPH PART CREATION /** * * @param id * @return */ private boolean createGraphComponentFromModel(String id){ boolean needsPositioning = false; //set the correct compartment status BioModel compBioModel = new BioModel(bioModel.getPath()); boolean compart = false; //String modelFileName = gcm.getModelFileName(id).replace(".xml", ".gcm"); String modelFileName = bioModel.getModelFileName(id); if (modelFileName.equals("")) { return false; } File compFile = new File(bioModel.getPath() + File.separator + modelFileName); if (compBioModel != null && compFile.exists()) { compBioModel.load(bioModel.getPath() + File.separator + modelFileName); compart = compBioModel.IsWithinCompartment(); } else { JOptionPane.showMessageDialog(Gui.frame, "A model definition cannot be found for " + modelFileName + ".\nDropping component from the schematic.\n", "Warning", JOptionPane.WARNING_MESSAGE); return false; } String truncGCM = modelFileName.replace(".xml", ""); String truncID = ""; //if the id is too long, truncate it if (truncGCM.length() > 10) truncGCM = truncGCM.substring(0, 9) + "..."; if (id.length() > 10) truncID = id.substring(0, 9) + "..."; else truncID = id; String label = truncID + "\n" + truncGCM; CellValueObject cvo = new CellValueObject(label, "Component", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.componentsToMxCellMap.put(id, (mxCell)insertedVertex); //pass whether or not the component is a compartment, as the styles are different this.setComponentStyles(id, compart); needsPositioning = sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_COMPONENT_WIDTH,GlobalConstants.DEFAULT_COMPONENT_HEIGHT); // now draw the edges that connect the component HashMap<String,String> connections = bioModel.getInputConnections(compBioModel,id); for (String propName : connections.keySet()) { // input, the arrow should point in from the species String topSpecies = connections.get(propName); Object createdEdge = this.insertEdge(this.getDefaultParent(), "", "", this.getSpeciesCell(topSpecies),insertedVertex); String key = id + " Input " + topSpecies; componentsConnectionsToMxCellMap.put(key, (mxCell)createdEdge); this.updateComponentConnectionVisuals((mxCell)createdEdge, propName); } // now draw the edges that connect the component connections = bioModel.getOutputConnections(compBioModel,id); for (String propName : connections.keySet()) { // output, the arrow should point out to the species String topSpecies = connections.get(propName); Object createdEdge = this.insertEdge(this.getDefaultParent(), "", "", insertedVertex, this.getSpeciesCell(topSpecies)); String key = id + " Output " + topSpecies; componentsConnectionsToMxCellMap.put(key, (mxCell)createdEdge); this.updateComponentConnectionVisuals((mxCell)createdEdge, propName); } // now draw the edges that connect variables to the component connections = bioModel.getVariableInputConnections(compBioModel,id); for (String propName : connections.keySet()) { String topSpecies = connections.get(propName); Object createdEdge = this.insertEdge(this.getDefaultParent(), "", "", this.getVariableCell(topSpecies), insertedVertex); String key = id + " Input " + topSpecies; componentsConnectionsToMxCellMap.put(key, (mxCell)createdEdge); this.updateComponentConnectionVisuals((mxCell)createdEdge, propName); } // now draw the edges that connect variables to the component connections = bioModel.getVariableOutputConnections(compBioModel,id); for (String propName : connections.keySet()) { String topSpecies = connections.get(propName); Object createdEdge = this.insertEdge(this.getDefaultParent(), "", "", insertedVertex, this.getVariableCell(topSpecies)); String key = id + " Output " + topSpecies; componentsConnectionsToMxCellMap.put(key, (mxCell)createdEdge); this.updateComponentConnectionVisuals((mxCell)createdEdge, propName); } return needsPositioning; } /** * creates a vertex on the graph using the internal model. * @param id * * @return: A bool, true if the species had to be positioned. */ private boolean createGraphSpeciesFromModel(String sp){ if (BioModel.isMRNASpecies(bioModel.getSBMLDocument().getModel().getSpecies(sp))) return false; String truncID = ""; if (sp.length() > 12) truncID = sp.substring(0, 11) + "..."; else truncID = sp; String label = truncID; if (bioModel.getDiffusionReaction(sp)!=null) label += " (D)"; if (bioModel.isSpeciesConstitutive(sp)) label += " (C)"; if (bioModel.isInput(sp)) { label += '\n' + GlobalConstants.INPUT; } else if (bioModel.isOutput(sp)) { label += '\n' + GlobalConstants.OUTPUT; } else { label += '\n' + GlobalConstants.INTERNAL; } CellValueObject cvo = new CellValueObject(label, "Species", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), sp, cvo, 1, 1, 1, 1); this.speciesToMxCellMap.put(sp, (mxCell)insertedVertex); this.setSpeciesStyles(sp); return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_SPECIES_WIDTH,GlobalConstants.DEFAULT_SPECIES_HEIGHT); } /** * creates a vertex on the graph using the internal model. * @param id * * @return: A bool, true if the reaction had to be positioned. */ private boolean createGraphReactionFromModel(String id){ CellValueObject cvo = new CellValueObject(id, "Reaction", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.reactionsToMxCellMap.put(id, (mxCell)insertedVertex); this.setReactionStyles(id); return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_REACTION_WIDTH,GlobalConstants.DEFAULT_REACTION_HEIGHT); } private boolean createGraphCompartmentFromModel(String id){ CellValueObject cvo = new CellValueObject(id, "Compartment", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); mxCell cell = (mxCell)insertedVertex; cell.setConnectable(false); this.compartmentsToMxCellMap.put(id, cell); if (bioModel.IsWithinCompartment()) { this.setCompartmentStyles(id,true); } else { this.setCompartmentStyles(id,false); } return sizeAndPositionFromProperties(cell,GlobalConstants.DEFAULT_COMPARTMENT_WIDTH, GlobalConstants.DEFAULT_COMPARTMENT_HEIGHT); } private boolean createGraphRuleFromModel(String id){ CellValueObject cvo = new CellValueObject(id, "Rule", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.rulesToMxCellMap.put(id, (mxCell)insertedVertex); this.setRuleStyles(id); return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_RULE_WIDTH,GlobalConstants.DEFAULT_RULE_HEIGHT); } private boolean createGraphConstraintFromModel(String id){ CellValueObject cvo = new CellValueObject(id, "Constraint", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.constraintsToMxCellMap.put(id, (mxCell)insertedVertex); this.setConstraintStyles(id); return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_CONSTRAINT_WIDTH,GlobalConstants.DEFAULT_CONSTRAINT_HEIGHT); } private boolean createGraphEventFromModel(String id){ CellValueObject cvo = new CellValueObject(id, "Event", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.eventsToMxCellMap.put(id, (mxCell)insertedVertex); this.setEventStyles(id); return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_EVENT_WIDTH,GlobalConstants.DEFAULT_EVENT_HEIGHT); } private boolean createGraphTransitionFromModel(String id){ CellValueObject cvo = new CellValueObject(id, "Transition", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.eventsToMxCellMap.put(id, (mxCell)insertedVertex); this.setTransitionStyles(id); return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_TRANSITION_WIDTH,GlobalConstants.DEFAULT_TRANSITION_HEIGHT); } /** * Creates a drawn promoter using the internal model * @param pname * @return */ private boolean createGraphDrawnPromoterFromModel(String id){ String truncID; if (id.length() > 8) truncID = id.substring(0, 7) + "..."; else truncID = id; CellValueObject cvo = new CellValueObject(truncID, "Promoter", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.drawnPromoterToMxCellMap.put(id, (mxCell)insertedVertex); this.setDrawnPromoterStyles(id); return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_SPECIES_WIDTH,GlobalConstants.DEFAULT_SPECIES_HEIGHT); } /** * Creates a variable using the internal model * @param pname * @return */ private boolean createGraphVariableFromModel(String id){ String truncID; if (id.length() > 8) truncID = id.substring(0, 7) + "..."; else truncID = id; CellValueObject cvo = new CellValueObject(truncID, "Variable", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.variableToMxCellMap.put(id, (mxCell)insertedVertex); this.setVariableStyles(id); return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_VARIABLE_WIDTH,GlobalConstants.DEFAULT_VARIABLE_HEIGHT); } /** * Creates a variable using the internal model * @param pname * @return */ private boolean createGraphPlaceFromModel(String id,boolean marked){ String truncID; if (id.length() > 8) truncID = id.substring(0, 7) + "..."; else truncID = id; CellValueObject cvo = new CellValueObject(truncID, "Place", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.variableToMxCellMap.put(id, (mxCell)insertedVertex); if (marked) { this.setMarkedPlaceStyles(id); } else { this.setPlaceStyles(id); } return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_VARIABLE_WIDTH,GlobalConstants.DEFAULT_VARIABLE_HEIGHT); } /** * Creates a variable using the internal model * @param pname * @return */ private boolean createGraphBooleanFromModel(String id,boolean initial){ String truncID; if (id.length() > 8) truncID = id.substring(0, 7) + "..."; else truncID = id; CellValueObject cvo = new CellValueObject(truncID, "Boolean", null); Object insertedVertex = this.insertVertex(this.getDefaultParent(), id, cvo, 1, 1, 1, 1); this.variableToMxCellMap.put(id, (mxCell)insertedVertex); if (initial) { this.setTrueBooleanStyles(id); } else { this.setBooleanStyles(id); } return sizeAndPositionFromProperties((mxCell)insertedVertex, GlobalConstants.DEFAULT_VARIABLE_WIDTH,GlobalConstants.DEFAULT_VARIABLE_HEIGHT); } /** * creates an edge between two graph entities */ @Override public Object insertEdge(Object parent, String id, Object value, Object source, Object target, String style){ Object ret = super.insertEdge(parent, id, value, source, target, style); this.influencesToMxCellMap.put(id, (mxCell)ret); return ret; } //VISUALS /** * Given an id, update the style of the influence based on the internal model. */ /* private void updateInfluenceVisuals(String id){ Properties prop = gcm.getInfluences().get(id); //gcm.getSBMLDocument().getModel(); if(prop == null) throw new Error("Invalid id '"+id+"'. Valid ids were:" + String.valueOf(gcm.getInfluences().keySet())); // build the edge style String style = "defaultEdge;" + mxConstants.STYLE_ENDARROW + "="; if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.ACTIVATION)) style = "ACTIVATION"; else if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.REPRESSION)) style = "REPRESSION"; else if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.NOINFLUENCE)) style = "NOINFLUENCE"; else if(prop.getProperty(GlobalConstants.TYPE).equals(GlobalConstants.COMPLEX)) style = "COMPLEX"; else style = "DEFAULT"; // apply the style mxCell cell = this.getInfluence(id); cell.setStyle(style); // apply the promoter name as a label, only if the promoter isn't drawn. if(gcm.influenceHasExplicitPromoter(id) == false) cell.setValue(prop.getProperty(GlobalConstants.PROMOTER)); }; */ /** * * @param cell * @param label */ public void updateComponentConnectionVisuals(mxCell cell, String label){ //cell.setStyle(mxConstants.STYLE_ENDARROW + "=" + mxConstants.ARROW_OPEN); cell.setStyle("COMPONENT_EDGE"); cell.setValue("Port " + label); // position the label as intelligently as possible mxGeometry geom = cell.getGeometry(); if(this.getCellType(cell.getSource()) == GlobalConstants.COMPONENT){ geom.setX(-.6); } else{ geom.setX(.6); } cell.setGeometry(geom); } /** * Builds the style sheets that will be used by the graph. */ public void createStyleSheets(){ Preferences biosimrc = Preferences.userRoot(); mxStylesheet stylesheet = this.getStylesheet(); String prefix; if (lema) { prefix = "lema"; } else { prefix = "biosim"; } //compartment Hashtable<String, Object> style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Compartment", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Compartment", "true").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Compartment", "#FFFFFF")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Compartment", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Compartment", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Compartment", "50"))); stylesheet.putCellStyle("SBMLCOMPARTMENT", style); //compartment style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Component", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Component", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Component", "#FFFFFF")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Component", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Component", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Component", "50"))); stylesheet.putCellStyle("SBMLCOMPONENT", style); //species style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Species", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Species", "true").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Species", "#5CB4F2")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Species", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Species", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Species", "50"))); stylesheet.putCellStyle("SPECIES", style); //reactions style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Reaction", mxConstants.SHAPE_ELLIPSE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Reaction", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Reaction", "#C7007B")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Reaction", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Reaction", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Reaction", "50"))); stylesheet.putCellStyle("REACTION", style); //rules style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Rule", mxConstants.SHAPE_SWIMLANE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Rule", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Rule", "#FFFF00")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Rule", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Rule", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Rule", "50"))); stylesheet.putCellStyle("RULE", style); //constraints style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Constraint", mxConstants.SHAPE_HEXAGON)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Constraint", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Constraint", "#FF0000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Constraint", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Constraint", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Constraint", "50"))); stylesheet.putCellStyle("CONSTRAINT", style); //events style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Event", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Event", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Event", "#00FF00")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Event", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Event", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Event", "50"))); stylesheet.putCellStyle("EVENT", style); //explicit promoter style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Promoter", mxConstants.SHAPE_RHOMBUS)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Promoter", "false").equals("true")); //style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_IMAGE); //style.put(mxConstants.STYLE_IMAGE,"file:/Users/myers/Downloads/SBOL/Symbols/promoter.png"); //style.put(mxConstants.STYLE_VERTICAL_LABEL_POSITION, mxConstants.ALIGN_BOTTOM); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Promoter", "#F00E0E")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Promoter", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Promoter", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Promoter", "50"))); stylesheet.putCellStyle("EXPLICIT_PROMOTER", style); //variable style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Variable", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Variable", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Variable", "#0000FF")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Variable", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Variable", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Variable", "50"))); stylesheet.putCellStyle("VARIABLE", style); //boolean (false) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Boolean_False", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Boolean_False", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Boolean_False", "#FFFFFF")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Boolean_False", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Boolean_False", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Boolean_False", "50"))); stylesheet.putCellStyle("BOOLEAN", style); //boolean (true) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Boolean_True", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Boolean_True", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Boolean_True", "#808080")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Boolean_True", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Boolean_True", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Boolean_True", "50"))); stylesheet.putCellStyle("TRUE_BOOLEAN", style); //place (not marked) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Place_NotMarked", mxConstants.SHAPE_ELLIPSE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Place_NotMarked", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Place_NotMarked", "#FFFFFF")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Place_NotMarked", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Place_NotMarked", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Place_NotMarked", "50"))); stylesheet.putCellStyle("PLACE", style); //marked place (marked) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Place_Marked", mxConstants.SHAPE_DOUBLE_ELLIPSE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Place_Marked", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Place_Marked", "#808080")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Place_Marked", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Place_Marked", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Place_Marked", "50"))); stylesheet.putCellStyle("MARKED_PLACE", style); //transitions style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.Transition", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.Transition", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Transition", "#FFFFFF")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Transition", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Transition", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Transition", "50"))); stylesheet.putCellStyle("TRANSITION", style); //components style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.subComponent", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.subComponent", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.subComponent", "#87F274")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.subComponent", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.subComponent", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.subComponent", "50"))); stylesheet.putCellStyle("COMPONENT", style); //compartments style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.subCompartment", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.subCompartment", "true").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.subCompartment", "#87F274")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.subCompartment", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.subCompartment", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.subCompartment", "50"))); stylesheet.putCellStyle("COMPARTMENT", style); //grid components style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.subComponent", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.subComponent", "false").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.subComponent", "#87F274")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.subComponent", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.subComponent", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.subComponent", "50"))); stylesheet.putCellStyle("GRIDCOMPONENT", style); //grid compartments style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, biosimrc.get(prefix+".schematic.shape.subCompartment", mxConstants.SHAPE_RECTANGLE)); style.put(mxConstants.STYLE_ROUNDED, biosimrc.get(prefix+".schematic.rounded.subCompartment", "true").equals("true")); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.subCompartment", "#87F274")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.subCompartment", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.subCompartment", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.subCompartment", "50"))); stylesheet.putCellStyle("GRIDCOMPARTMENT", style); //grid rectangle style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_RECTANGLE); style.put(mxConstants.STYLE_FILLCOLOR, "none"); style.put(mxConstants.STYLE_STROKECOLOR, "#000000"); style.put(mxConstants.STYLE_OPACITY, 100); style.put(mxConstants.STYLE_ROUNDED, false); style.put(mxConstants.STYLE_MOVABLE, false); style.put(mxConstants.STYLE_RESIZABLE, false); style.put(mxConstants.STYLE_NOLABEL, true); stylesheet.putCellStyle("GRID_RECTANGLE", style); //production edge (promoter to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Production_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Production_Edge", "#34BA04")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Production_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Production_Edge", "100"))); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Production_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_EDGE, mxConstants.EDGESTYLE_ENTITY_RELATION); stylesheet.putCellStyle("PRODUCTION", style); //activation edge (species to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Activation_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Activation_Edge", "#34BA04")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Activation_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Activation_Edge", "100"))); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Activation_Edge", mxConstants.ARROW_BLOCK)); stylesheet.putCellStyle("ACTIVATION", style); //repression edge (species to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Repression_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Repression_Edge", "#FA2A2A")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Repression_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Repression_Edge", "100"))); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Repression_Edge", mxConstants.ARROW_OVAL)); stylesheet.putCellStyle("REPRESSION", style); //no influence (species to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.NoInfluence_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.NoInfluence_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.NoInfluence_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.NoInfluence_Edge", "100"))); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.NoInfluence_Edge", mxConstants.ARROW_DIAMOND)); style.put(mxConstants.STYLE_DASHED, "true"); stylesheet.putCellStyle("NOINFLUENCE", style); //complex formation edge (species to species) style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Complex_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Complex_Edge", "#4E5D9C")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Complex_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Complex_Edge", "100"))); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Complex_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_DASHED, "true"); stylesheet.putCellStyle("COMPLEX", style); //component edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Default_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Default_Edge", "100"))); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Default_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("COMPONENT_EDGE", style); //reaction edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Default_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Default_Edge", "100"))); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Default_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("REACTION_EDGE", style); //reversible reaction edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Default_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Default_Edge", "100"))); style.put(mxConstants.STYLE_STARTARROW, biosimrc.get(prefix+".schematic.shape.Default_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Default_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("REV_REACTION_EDGE", style); //reversible reaction edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Default_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Default_Edge", "100"))); style.put(mxConstants.STYLE_STARTARROW, mxConstants.NONE); style.put(mxConstants.STYLE_ENDARROW, mxConstants.NONE); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("MODIFIER_REACTION_EDGE", style); //rule edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Default_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Default_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Default_Edge", "100"))); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("RULE_EDGE", style); //constraint edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Default_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Default_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Default_Edge", "100"))); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("CONSTRAINT_EDGE", style); //event edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Default_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Default_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Default_Edge", "100"))); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("EVENT_EDGE", style); //default edge style = new Hashtable<String, Object>(); style.put(mxConstants.STYLE_ENDARROW, biosimrc.get(prefix+".schematic.shape.Default_Edge", mxConstants.ARROW_OPEN)); style.put(mxConstants.STYLE_FILLCOLOR, biosimrc.get(prefix+".schematic.color.Default_Edge", "#000000")); style.put(mxConstants.STYLE_STROKECOLOR, biosimrc.get(prefix+".schematic.strokeColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_FONTCOLOR, biosimrc.get(prefix+".schematic.fontColor.Default_Edge", "#000000")); style.put(mxConstants.STYLE_OPACITY, Integer.parseInt(biosimrc.get(prefix+".schematic.opacity.Default_Edge", "100"))); style.put(mxConstants.STYLE_DASHED, "false"); stylesheet.putCellStyle("DEFAULT", style); } //STYLE SETTING /** * * @param id */ private void setSpeciesStyles(String id){ String style="SPECIES;"; mxCell cell = this.getSpeciesCell(id); cell.setStyle(style); } /** * * @param id */ private void setReactionStyles(String id){ String style="REACTION;"; mxCell cell = this.getReactionsCell(id); cell.setStyle(style); } private void setCompartmentStyles(String id, boolean compart){ String style; if (compart) { style="SBMLCOMPARTMENT;"; } else { style="SBMLCOMPONENT;"; } mxCell cell = this.getCompartmentsCell(id); cell.setStyle(style); } private void setRuleStyles(String id){ String style="RULE;"; mxCell cell = this.getRulesCell(id); cell.setStyle(style); } private void setConstraintStyles(String id){ String style="CONSTRAINT;"; mxCell cell = this.getConstraintsCell(id); cell.setStyle(style); } private void setEventStyles(String id){ String style="EVENT;"; mxCell cell = this.getEventsCell(id); cell.setStyle(style); } private void setTransitionStyles(String id){ String style="TRANSITION;"; mxCell cell = this.getEventsCell(id); cell.setStyle(style); } /** * * @param id * @param compart */ private void setComponentStyles(String id, boolean compart){ String style = ""; if (bioModel.getGrid().isEnabled()) { if (compart) style = "GRIDCOMPARTMENT;"; else style = "GRIDCOMPONENT;"; } else { if (compart) style = "COMPARTMENT;"; else style = "COMPONENT;"; } mxCell cell = this.getComponentCell(id); cell.setStyle(style); } /** * * @param id */ private void setDrawnPromoterStyles(String id){ String style="EXPLICIT_PROMOTER"; mxCell cell = this.getDrawnPromoterCell(id); cell.setStyle(style); } /** * * @param id */ private void setVariableStyles(String id){ String style="VARIABLE"; mxCell cell = this.getVariableCell(id); cell.setStyle(style); } /** * * @param id */ private void setBooleanStyles(String id){ String style="BOOLEAN"; mxCell cell = this.getVariableCell(id); cell.setStyle(style); } /** * * @param id */ private void setTrueBooleanStyles(String id){ String style="TRUE_BOOLEAN"; mxCell cell = this.getVariableCell(id); cell.setStyle(style); } /** * * @param id */ private void setPlaceStyles(String id){ String style="PLACE"; mxCell cell = this.getVariableCell(id); cell.setStyle(style); } /** * * @param id */ private void setMarkedPlaceStyles(String id){ String style="MARKED_PLACE"; mxCell cell = this.getVariableCell(id); cell.setStyle(style); } //ANIMATION public void setSpeciesAnimationValue(String species, MovieAppearance appearance) { mxCell cell = this.speciesToMxCellMap.get(species); if (cell != null) { setCellAnimationValue(cell, appearance); } } public void setParameterAnimationValue(String parameter, MovieAppearance appearance) { mxCell cell = this.variableToMxCellMap.get(parameter); if (cell != null) { setCellAnimationValue(cell, appearance); } } public void setComponentAnimationValue(String component, MovieAppearance appearance) { mxCell cell = this.componentsToMxCellMap.get(component); setCellAnimationValue(cell, appearance); } public void setGridRectangleAnimationValue(String gridLocation, MovieAppearance appearance) { mxCell cell = this.gridRectangleToMxCellMap.get(gridLocation); setCellAnimationValue(cell, appearance); } /** * Applies the MovieAppearance to the cell * @param cell * @param appearance * @param properties */ private void setCellAnimationValue(mxCell cell, MovieAppearance appearance) { if (appearance == null) return; // color String newStyle = cell.getStyle() + ";"; if (appearance.color != null) { newStyle += mxConstants.STYLE_FILLCOLOR + "=" + Integer.toHexString(appearance.color.getRGB()) + ";"; newStyle += mxConstants.STYLE_OPACITY + "=" + 75; } // opacity if (appearance.opacity != null) { newStyle += ";"; double op = (appearance.opacity) * 100.0; newStyle += mxConstants.STYLE_OPACITY + "=" + String.valueOf(op); } if (newStyle != null) cell.setStyle(newStyle); // size if (appearance.size != null) { double x = 0; double y = 0; double width = 0; double height = 0; if (getCellType(cell).equals(GlobalConstants.SPECIES)|| getCellType(cell).equals(GlobalConstants.PROMOTER)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getSpeciesGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { SpeciesGlyph speciesGlyph = layout.getSpeciesGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = speciesGlyph.getBoundingBox().getPosition().getXOffset(); y = speciesGlyph.getBoundingBox().getPosition().getYOffset(); width = speciesGlyph.getBoundingBox().getDimensions().getWidth(); height = speciesGlyph.getBoundingBox().getDimensions().getHeight(); } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_SPECIES_WIDTH; height = GlobalConstants.DEFAULT_SPECIES_HEIGHT; } } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_SPECIES_WIDTH; height = GlobalConstants.DEFAULT_SPECIES_HEIGHT; } } else if (getCellType(cell).equals(GlobalConstants.VARIABLE) || getCellType(cell).equals(GlobalConstants.PLACE) || getCellType(cell).equals(GlobalConstants.BOOLEAN)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = generalGlyph.getBoundingBox().getPosition().getXOffset(); y = generalGlyph.getBoundingBox().getPosition().getYOffset(); width = generalGlyph.getBoundingBox().getDimensions().getWidth(); height = generalGlyph.getBoundingBox().getDimensions().getHeight(); } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_SPECIES_WIDTH; height = GlobalConstants.DEFAULT_SPECIES_HEIGHT; } } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_SPECIES_WIDTH; height = GlobalConstants.DEFAULT_SPECIES_HEIGHT; } } else if (getCellType(cell).equals(GlobalConstants.REACTION)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { ReactionGlyph reactionGlyph = layout.getReactionGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = reactionGlyph.getBoundingBox().getPosition().getXOffset(); y = reactionGlyph.getBoundingBox().getPosition().getYOffset(); width = reactionGlyph.getBoundingBox().getDimensions().getWidth(); height = reactionGlyph.getBoundingBox().getDimensions().getHeight(); } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_REACTION_WIDTH; height = GlobalConstants.DEFAULT_REACTION_HEIGHT; } } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_REACTION_WIDTH; height = GlobalConstants.DEFAULT_REACTION_HEIGHT; } } else if (getCellType(cell).equals(GlobalConstants.RULE)|| getCellType(cell).equals(GlobalConstants.CONSTRAINT)|| getCellType(cell).equals(GlobalConstants.EVENT)|| getCellType(cell).equals(GlobalConstants.TRANSITION)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = generalGlyph.getBoundingBox().getPosition().getXOffset(); y = generalGlyph.getBoundingBox().getPosition().getYOffset(); width = generalGlyph.getBoundingBox().getDimensions().getWidth(); height = generalGlyph.getBoundingBox().getDimensions().getHeight(); } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_REACTION_WIDTH; height = GlobalConstants.DEFAULT_REACTION_HEIGHT; } } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_REACTION_WIDTH; height = GlobalConstants.DEFAULT_REACTION_HEIGHT; } } else if (getCellType(cell).equals(GlobalConstants.COMPARTMENT)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { CompartmentGlyph compGlyph = layout.getCompartmentGlyph(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = compGlyph.getBoundingBox().getPosition().getXOffset(); y = compGlyph.getBoundingBox().getPosition().getYOffset(); width = compGlyph.getBoundingBox().getDimensions().getWidth(); height = compGlyph.getBoundingBox().getDimensions().getHeight(); } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_COMPONENT_WIDTH; height = GlobalConstants.DEFAULT_COMPONENT_HEIGHT; } } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_COMPONENT_WIDTH; height = GlobalConstants.DEFAULT_COMPONENT_HEIGHT; } } else if (getCellType(cell).equals(GlobalConstants.COMPONENT)) { if (bioModel.getSBMLLayout().getLayout("iBioSim") != null) { Layout layout = bioModel.getSBMLLayout().getLayout("iBioSim"); if (layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId())!=null) { GeneralGlyph generalGlyph = (GeneralGlyph) layout.getAdditionalGraphicalObject(GlobalConstants.GLYPH+"__"+(String)cell.getId()); x = generalGlyph.getBoundingBox().getPosition().getXOffset(); y = generalGlyph.getBoundingBox().getPosition().getYOffset(); width = generalGlyph.getBoundingBox().getDimensions().getWidth(); height = generalGlyph.getBoundingBox().getDimensions().getHeight(); } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_COMPONENT_WIDTH; height = GlobalConstants.DEFAULT_COMPONENT_HEIGHT; } } else { x = -9999; y = -9999; width = GlobalConstants.DEFAULT_COMPONENT_WIDTH; height = GlobalConstants.DEFAULT_COMPONENT_HEIGHT; } } double aspect_ratio = height / width; double centerX = x + width/2.0; double centerY = y + height/2.0; mxGeometry startG = cell.getGeometry(); startG.setWidth(appearance.size); startG.setHeight(appearance.size * aspect_ratio); startG.setX(centerX - startG.getWidth()/2.0); startG.setY(centerY - startG.getHeight()/2.0); } } //CELL VALUE OBJECT CLASS /** * The object that gets set as the mxCell value object. * It is basically a way to store a property and label. */ public class CellValueObject extends Object implements Serializable{ private static final long serialVersionUID = 918273645; public Properties prop; public String label; public String type; @Override public String toString(){ return this.label; } /** * * @param oos * @throws IOException */ private void writeObject(ObjectOutputStream oos) throws IOException { oos.writeObject(label); oos.writeObject(prop); } /** * * @param ois * @throws ClassNotFoundException * @throws IOException */ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { label = ois.readObject().toString(); prop = (Properties)ois.readObject(); } /** * * * @param label * @param prop */ public CellValueObject(String label, String type, Properties prop){ if(label == null || type == null) throw new Error("Neither label nor type can be null!"); this.label = label; this.type = type; this.prop = prop; } } }
package com.ecyrd.jspwiki; import java.util.Properties; import java.util.Collection; import java.util.Date; /** * Each Wiki page provider should implement this interface. * <P> * You can build whatever page providers based on this, just * leave the unused methods do something useful. * * <P> * FIXME: In reality we should have an AbstractWikiPageProvider, * which would provide intelligent backups for subclasses. */ public interface WikiPageProvider { /** * Initializes the page provider. */ public void initialize( Properties properties ) throws NoRequiredPropertyException; /** * Return the page text for page "page". */ public String getPageText( String page ); /** * Attempts to save the page text for page "page". */ public void putPageText( WikiPage page, String text ); /** * Return true, if page exists. */ public boolean pageExists( String page ); /** * Finds pages based on the query. */ public Collection findPages( QueryItem[] query ); /** * Returns info about the page. */ public WikiPage getPageInfo( String page ); /** * Returns all pages. Each element in the returned * Collection should be a WikiPage. */ public Collection getAllPages(); /** * Returns version history. Each element should be * a WikiPage. */ public Collection getVersionHistory( String page ); /** * Gets a specific version out of the repository. */ public String getPageText( String page, int version ); }
package org.beanmaker; import java.util.List; import java.util.Set; import org.jcodegen.java.AnonymousClassCreation; import org.jcodegen.java.Assignment; import org.jcodegen.java.Comparison; import org.jcodegen.java.Condition; import org.jcodegen.java.ConstructorDeclaration; import org.jcodegen.java.ElseBlock; import org.jcodegen.java.ElseIfBlock; import org.jcodegen.java.ExceptionThrow; import org.jcodegen.java.ForLoop; import org.jcodegen.java.FunctionArgument; import org.jcodegen.java.FunctionCall; import org.jcodegen.java.FunctionDeclaration; import org.jcodegen.java.GenericType; import org.jcodegen.java.IfBlock; import org.jcodegen.java.JavaClass; import org.jcodegen.java.JavaCodeBlock; import org.jcodegen.java.LineOfCode; import org.jcodegen.java.ObjectCreation; import org.jcodegen.java.OperatorExpression; import org.jcodegen.java.ReturnStatement; import org.jcodegen.java.VarDeclaration; import org.jcodegen.java.Visibility; import org.jcodegen.java.WhileBlock; import org.dbbeans.util.Strings; import static org.beanmaker.SourceFiles.chopId; import static org.dbbeans.util.Strings.*; public class BaseClassSourceFile extends BeanCodeWithDBInfo { private final Set<String> types; private final String internalsVar; private final String parametersVar; public BaseClassSourceFile(final String beanName, final String packageName, final Columns columns, final String tableName) { super(beanName, packageName, "Base", columns, tableName); internalsVar = beanVarName + "Internals"; parametersVar = Strings.uncamelize(beanName).toUpperCase() + "_PARAMETERS"; types = columns.getJavaTypes(); createSourceCode(); } private void addImports() { importsManager.addImport("java.sql.PreparedStatement"); importsManager.addImport("java.sql.ResultSet"); importsManager.addImport("java.sql.SQLException"); importsManager.addImport("java.util.ArrayList"); importsManager.addImport("java.util.List"); importsManager.addImport("java.util.Locale"); importsManager.addImport("org.beanmaker.util.BeanInternals"); importsManager.addImport("org.beanmaker.util.DbBeanInterface"); importsManager.addImport("org.beanmaker.util.DBQueries"); importsManager.addImport("org.beanmaker.util.ErrorMessage"); importsManager.addImport("org.beanmaker.util.IdNamePair"); importsManager.addImport("org.dbbeans.sql.DBQueryRetrieveData"); importsManager.addImport("org.dbbeans.sql.DBQuerySetup"); importsManager.addImport("org.dbbeans.sql.DBQuerySetupProcess"); importsManager.addImport("org.dbbeans.sql.DBTransaction"); importsManager.addImport("org.dbbeans.util.Strings"); if (columns.containNumericalData()) importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); if (types.contains("Date")) { importsManager.addImport("java.sql.Date"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputDateFormat"); } if (types.contains("Time")) { importsManager.addImport("java.sql.Time"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputTimeFormat"); } if (types.contains("Timestamp")) { importsManager.addImport("java.sql.Timestamp"); importsManager.addImport("java.text.DateFormat"); importsManager.addImport("org.dbbeans.util.Dates"); importsManager.addImport("org.dbbeans.util.SimpleInputDateFormat"); importsManager.addImport("org.dbbeans.util.SimpleInputTimestampFormat"); } if (types.contains("Money")) { importsManager.addImport("org.dbbeans.util.Money"); importsManager.addImport("org.dbbeans.util.MoneyFormat"); } if (columns.hasLastUpdate()) importsManager.addImport("org.dbbeans.util.Dates"); } private void addClassModifiers() { javaClass.markAsAbstract().extendsClass("DbBean").implementsInterface("DbBeanInterface"); } private void addProperties() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); final VarDeclaration declaration; if (type.equals("String")) declaration = new VarDeclaration("String", field, EMPTY_STRING); else if (type.equals("Money")) declaration = new VarDeclaration("Money", field, new ObjectCreation("Money").addArgument("0").addArgument(new FunctionCall("getDefaultMoneyFormat"))); else declaration = new VarDeclaration(type, field); addProperty(declaration); if (type.equals("Money")) addProperty(new VarDeclaration("String", field + "Str", new FunctionCall("toString", field))); if (JAVA_TEMPORAL_TYPES.contains(type) || ((type.equals("int") || type.equals("long")) && !field.startsWith("id") && !field.equals("itemOrder"))) addProperty(new VarDeclaration("String", field + "Str", EMPTY_STRING)); } if (columns.hasLastUpdate()) addProperty("boolean", "updateOK"); if (columns.hasOneToManyRelationships()) { boolean first = true; for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { if (first) { newLine(); first = false; } addProperty(VarDeclaration.createListDeclaration(relationship.getBeanClass(), relationship.getJavaName())); } } newLine(); javaClass.addContent(new VarDeclaration("String", "DATABASE_TABLE_NAME", quickQuote(tableName)).visibility(Visibility.PROTECTED).markAsStatic().markAsFinal()); javaClass.addContent(new VarDeclaration("String", "DATABASE_FIELD_LIST", quickQuote(getStaticFieldList())).visibility(Visibility.PROTECTED).markAsStatic().markAsFinal()); newLine(); javaClass.addContent( new VarDeclaration("BeanInternals", internalsVar, new ObjectCreation("BeanInternals").addArgument(quickQuote(bundleName))).markAsFinal().visibility(Visibility.PROTECTED) ); final String parametersClass = beanName + "Parameters"; javaClass.addContent( new VarDeclaration(parametersClass, parametersVar, new ObjectCreation(parametersClass)).markAsFinal().markAsStatic().visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); if (columns.hasExtraFields()) { for (ExtraField extraField: columns.getExtraFields()) { javaClass.addContent(new LineOfCode(extraField.toString())); if (extraField.requiresImport()) importsManager.addImport(extraField.getRequiredImport()); if (extraField.requiresSecondaryImport()) importsManager.addImport(extraField.getSecondaryRequiredImport()); if (extraField.requiresTernaryImport()) importsManager.addImport(extraField.getTernaryRequiredImport()); } newLine(); } } private String getStaticFieldList() { final StringBuilder list = new StringBuilder(); for (Column column: columns.getList()) list.append(tableName).append(".").append(column.getSqlName()).append(", "); list.delete(list.length() - 2, list.length()); return list.toString(); } private void addConstructors() { javaClass.addContent(getBaseConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getIdArgumentConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getCopyConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getFieldConstructor()).addContent(EMPTY_LINE); javaClass.addContent(getResultSetConstructor()).addContent(EMPTY_LINE); } private ConstructorDeclaration getBaseConstructor() { return javaClass.createConstructor(); } private ConstructorDeclaration getIdArgumentConstructor() { return getBaseConstructor().addArgument(new FunctionArgument("long", "id")).addContent("setId(id);"); } private ConstructorDeclaration getCopyConstructor() { final ConstructorDeclaration copyConstructor = getBaseConstructor(); copyConstructor.addArgument(new FunctionArgument(beanName + "Base", "model")).addContent(new Assignment("id", "0")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { if (field.equals("itemOrder")) copyConstructor.addContent(new Assignment("itemOrder", "0")); else if (field.startsWith("id") || type.equals("boolean") || type.equals("String")) copyConstructor.addContent(new Assignment(field, "model." + field)); else copyConstructor.addContent(new FunctionCall("set" + capitalize(field)).addArgument("model." + field).byItself()); } } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { final String beanClass = relationship.getBeanClass(); final String beanObject = uncapitalize(beanClass); final String javaName = relationship.getJavaName(); copyConstructor.addContent(EMPTY_LINE).addContent( new ForLoop(beanClass + " " + beanObject + ": model." + javaName).addContent( new FunctionCall("add", javaName).byItself().addArgument( new ObjectCreation(beanClass).addArgument(new FunctionCall("getId", beanObject)) ) ) ); } return copyConstructor; } private ConstructorDeclaration getFieldConstructor() { final ConstructorDeclaration fieldConstructor = getBaseConstructor().visibility(Visibility.PROTECTED); for (Column column: columns.getList()) fieldConstructor.addArgument(new FunctionArgument(column.getJavaType(), column.getJavaName())); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (field.startsWith("id") || field.equals("itemOrder") || type.equals("boolean") || type.equals("String")) fieldConstructor.addContent(new Assignment("this." + field, field)); else fieldConstructor.addContent(new FunctionCall("set" + capitalize(field)).addArgument(field).byItself()); } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) { final String beanClass = relationship.getBeanClass(); final String beanObject = uncapitalize(beanClass); final String javaName = relationship.getJavaName(); fieldConstructor.addArgument(new FunctionArgument(new GenericType("List", beanClass).toString(), javaName)); fieldConstructor.addContent(EMPTY_LINE).addContent( new ForLoop(beanClass + " " + beanObject + ": " + javaName).addContent( new FunctionCall("add", "this." + javaName).byItself().addArgument(beanObject) ) ); } return fieldConstructor; } private ConstructorDeclaration getResultSetConstructor() { final ConstructorDeclaration rsConstructor = getBaseConstructor().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("ResultSet", "rs")).addException("SQLException"); for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) rsConstructor.addArgument(new FunctionArgument(new GenericType("List", relationship.getBeanClass()).toString(), relationship.getJavaName())); final FunctionCall thisCall = new FunctionCall("this").byItself(); int index = 0; for (Column column: columns.getList()) thisCall.addArgument(new FunctionCall("get" + capitalize(column.getJavaType()), "rs").addArgument(Integer.toString(++index))); for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) thisCall.addArgument(relationship.getJavaName()); return rsConstructor.addContent(thisCall); } private void addSetIdFunction() { final List<OneToManyRelationship> relationships = columns.getOneToManyRelationships(); final FunctionDeclaration function = new FunctionDeclaration("setId") .addArgument(new FunctionArgument("long", "id")); // function inner class for database row retrieval final JavaClass databaseInnerClass = new JavaClass("DataFromDBQuery").visibility(Visibility.NONE) .implementsInterface("DBQuerySetupProcess"); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { if (type.equals("int") || type.equals("long")) databaseInnerClass.addContent(new VarDeclaration(type, field, "0")); else if (type.equals("String") || JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money")) databaseInnerClass.addContent(new VarDeclaration(type, field, "null")); else if (type.equals("boolean")) databaseInnerClass.addContent(new VarDeclaration(type, field, "false")); else throw new IllegalStateException("Java type not allowed: " + type); } } databaseInnerClass.addContent(new VarDeclaration("boolean", "idOK", "false")) .addContent(EMPTY_LINE) .addContent(getInnerClassSetupPSWithIdFunction()) .addContent(EMPTY_LINE); final FunctionDeclaration processRS = getInnerClassProcessRSFunctionStart(); final IfBlock ifRsNext = new IfBlock(new Condition("rs.next()")); int index = 0; for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { ++index; if (type.equals("Money")) ifRsNext.addContent(new Assignment(field, new ObjectCreation("Money") .addArgument(new FunctionCall("getLong") .addArgument(Integer.toString(index)) .addArgument(new FunctionCall("getDefaultMoneyFormat"))))); else { final String getterName = "get" + capitalize(type); ifRsNext.addContent(new Assignment(field, new FunctionCall(getterName, "rs").addArgument(Integer.toString(index)))); } } } ifRsNext.addContent(new Assignment("idOK", "true")); processRS.addContent(ifRsNext); databaseInnerClass.addContent(processRS); function.addContent(databaseInnerClass).addContent(EMPTY_LINE); // for objects containing one or more list of other kind of objects for (OneToManyRelationship relationship: relationships) { if (!relationship.isListOnly()) { final JavaClass extraDBInnerClass = new JavaClass("DataFromDBQuery" + capitalize(relationship.getJavaName())) .visibility(Visibility.NONE).implementsInterface("DBQuerySetupProcess") .addContent(VarDeclaration.createListDeclaration(relationship.getBeanClass(), relationship.getJavaName()).markAsFinal()) .addContent(EMPTY_LINE) .addContent(getInnerClassSetupPSWithIdFunction()) .addContent(EMPTY_LINE); final FunctionDeclaration processRSExtra = getInnerClassProcessRSFunctionStart() .addContent(new WhileBlock(new Condition("rs.next()")) .addContent(new FunctionCall("add", relationship.getJavaName()) .byItself() .addArgument(new ObjectCreation(relationship.getBeanClass()) .addArgument("rs.getLong(1)")))); extraDBInnerClass.addContent(processRSExtra); function.addContent(extraDBInnerClass).addContent(EMPTY_LINE); } } // check for bad ID function.addContent(new IfBlock(new Condition("id <= 0")).addContent("throw new IllegalArgumentException(\"id = \" + id + \" <= 0\");")) .addContent(EMPTY_LINE); // instantiate DBQuery inner class & use it to retrieve data function.addContent( new VarDeclaration("DataFromDBQuery", "dataFromDBQuery", new ObjectCreation("DataFromDBQuery")).markAsFinal() ).addContent( new FunctionCall("processQuery", "dbAccess") .byItself() .addArgument(quickQuote(getReadSQLQuery())) .addArgument("dataFromDBQuery") ).addContent(EMPTY_LINE); // check if data was returned function.addContent( new IfBlock(new Condition("!dataFromDBQuery.idOK")).addContent( new ExceptionThrow("IllegalArgumentException").addArgument("\"id = \" + id + \" does not exist\"") ) ).addContent(EMPTY_LINE); // for objects containing one or more list of other kind of objects for (OneToManyRelationship relationship: relationships) { if (!relationship.isListOnly()) { final String cappedJavaName = capitalize(relationship.getJavaName()); function.addContent( new VarDeclaration("DataFromDBQuery" + cappedJavaName, "dataFromDBQuery" + cappedJavaName, new ObjectCreation("DataFromDBQuery" + cappedJavaName)).markAsFinal() ).addContent( new FunctionCall("processQuery", "dbAccess") .byItself() .addArgument(quickQuote(getReadSQLQueryOneToManyRelationship(relationship.getTable(), relationship.getIdSqlName()))) .addArgument("dataFromDBQuery" + cappedJavaName) ).addContent(EMPTY_LINE); } } // extra DB actions function.addContent("initExtraDbActions(id);").addContent(EMPTY_LINE); // fields assignment function.addContent(new Assignment("this.id", "id")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id")) { function.addContent(new Assignment("this." + field, "dataFromDBQuery." + field)); if (JAVA_TEMPORAL_TYPES.contains(type)) function.addContent( new Assignment(field +"Str", new FunctionCall("convert" + type + "ToString").addArgument(field)) ); if ((type.equals("int") || type.equals("long")) && !field.equals("itemOrder") && !field.startsWith("id")) function.addContent( new Assignment(field +"Str", new FunctionCall("valueOf", "String").addArgument(field)) ); if (type.equals("Money")) function.addContent( new Assignment(field +"Str", new FunctionCall("toString", field)) ); } } for (OneToManyRelationship relationship: relationships) if (!relationship.isListOnly()) function.addContent( new Assignment("this." + relationship.getJavaName(), "dataFromDBQuery" + capitalize(relationship.getJavaName()) + "." + relationship.getJavaName()) ); function.addContent(EMPTY_LINE).addContent("postInitActions();"); javaClass.addContent(function).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("initExtraDbActions") .visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("long", "id")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postInitActions") .visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("resetId") .addContent("id = 0;") ).addContent(EMPTY_LINE); } private FunctionDeclaration getInnerClassSetupPSWithIdFunction() { return new FunctionDeclaration("setupPreparedStatement") .addException("SQLException") .annotate("@Override") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .addContent("stat.setLong(1, id);"); } private FunctionDeclaration getInnerClassProcessRSFunctionStart() { return new FunctionDeclaration("processResultSet") .addException("SQLException") .annotate("@Override") .addArgument(new FunctionArgument("ResultSet", "rs")); } private void addEquals() { javaClass.addContent( new FunctionDeclaration("equals", "boolean").addArgument(new FunctionArgument("Object", "object")).annotate("@Override").addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( new ReturnStatement("false") ) ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition("object instanceof " + beanName)).addContent( new ReturnStatement("((" + beanName + ") object).getId() == id") ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("false") ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("hashCode", "int").annotate("@Override").addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( new ReturnStatement("-1") ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("31 * ((int) (id ^ (id >>> 32))) + 17") ) ).addContent(EMPTY_LINE); } private void addToString() { final String returnExpression = "\"[" + beanName + " - " + tableName + " javaClass.addContent( new FunctionDeclaration("toString", "String").annotate("@Override").addContent( new ReturnStatement(returnExpression) ) ).addContent(EMPTY_LINE); } private void addSetters() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!field.equals("id") && !field.equals("lastUpdate") && !field.equals("modifiedBy") && !field.equals("itemOrder")) { final FunctionDeclaration setter = new FunctionDeclaration("set" + capitalize(field)) .addArgument(new FunctionArgument(type, field)); if (JAVA_TEMPORAL_TYPES.contains(type)) setter.addContent( new IfBlock(new Condition(new Comparison(field, "null"))).addContent( new Assignment("this." + field, "null") ).elseClause(new ElseBlock().addContent( new Assignment("this." + field, new ObjectCreation(type) .addArgument(new FunctionCall("getTime", field))) )) ); else setter.addContent( new Assignment("this." + field, field) ); if (type.equals("int") && !field.startsWith("id")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", "Integer").addArgument(field)) ); if (type.equals("long") && !field.startsWith("id")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", "Long").addArgument(field)) ); if (JAVA_TEMPORAL_TYPES.contains(type)) setter.addContent( new Assignment(field + "Str", new FunctionCall("convert" + capitalize(type) + "ToString").addArgument(field)) ); if (type.equals("Money")) setter.addContent( new Assignment(field + "Str", new FunctionCall("toString", field)) ); javaClass.addContent(setter).addContent(EMPTY_LINE); if (column.couldHaveAssociatedBean() && column.hasAssociatedBean()) { final String associatedBeanClass = column.getAssociatedBeanClass(); final String associatedBeanObject = uncapitalize(chopId(field)); final FunctionDeclaration fromObjectSetter = new FunctionDeclaration("set" + capitalize(associatedBeanObject)) .addArgument(new FunctionArgument(associatedBeanClass, associatedBeanObject)) .addContent(new IfBlock(new Condition(new Comparison(new FunctionCall("getId", associatedBeanObject), "0"))) .addContent(new ExceptionThrow("IllegalArgumentException") .addArgument(quickQuote("Cannot accept uninitialized " + associatedBeanClass + " bean (id = 0) as argument.")))) .addContent(EMPTY_LINE) .addContent(new Assignment(field, new FunctionCall("getId", associatedBeanObject))); javaClass.addContent(fromObjectSetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("long")) && !field.startsWith("id"))) { final FunctionDeclaration strSetter = new FunctionDeclaration("set" + capitalize(field) + "Str") .addArgument(new FunctionArgument("String", field + "Str")) .addContent(new Assignment("this." + field + "Str", field + "Str")); javaClass.addContent(strSetter).addContent(EMPTY_LINE); } } } } private void addGetters() { for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String prefix; if (type.equals("boolean")) prefix = "is"; else prefix = "get"; final FunctionDeclaration getter = new FunctionDeclaration(prefix + capitalize(field), type); if (JAVA_TEMPORAL_TYPES.contains(type)) getter.addContent( new IfBlock(new Condition(new Comparison(field, "null"))).addContent(new ReturnStatement("null")) ).addContent( EMPTY_LINE ).addContent( new ReturnStatement(new ObjectCreation(type).addArgument(new FunctionCall("getTime", field))) ); else getter.addContent( new ReturnStatement(field) ); javaClass.addContent(getter).addContent(EMPTY_LINE); if (column.hasAssociatedBean()) { final String associatedBeanClass = column.getAssociatedBeanClass(); final FunctionDeclaration associatedBeanGetter = new FunctionDeclaration("get" + chopId(field), associatedBeanClass) .addContent(new ReturnStatement(new ObjectCreation(associatedBeanClass).addArgument(field))); javaClass.addContent(associatedBeanGetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("long")) && !field.startsWith("id") && !field.equals("itemOrder"))) { final FunctionDeclaration strGetter = new FunctionDeclaration("get" + capitalize(field) + "Str", "String") .addContent(new ReturnStatement(field + "Str")); javaClass.addContent(strGetter).addContent(EMPTY_LINE); } if (JAVA_TEMPORAL_TYPES.contains(type)) { final String capField = capitalize(field); final FunctionDeclaration formattedGetter = new FunctionDeclaration("get" + capField + "Formatted", "String") .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "Empty"))) .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "Required"))) .addContent(getCannotDisplayBadDataException())) .addContent(new ReturnStatement(EMPTY_STRING))) .addContent(EMPTY_LINE) .addContent(new IfBlock(new Condition(new FunctionCall("is" + capField + "OK"), true)).addContent(getCannotDisplayBadDataException())) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("format" + type).addArgument(new FunctionCall("convertStringTo" + type).addArgument(field + "Str")))); javaClass.addContent(formattedGetter).addContent(EMPTY_LINE); } if (type.equals("boolean")) { final FunctionDeclaration booleanValGetter = new FunctionDeclaration("get" + capitalize(field) + "Val", "String") .addContent(new IfBlock(new Condition(field)) .addContent(new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote("true_value"))))) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote("false_value")))); javaClass.addContent(booleanValGetter).addContent(EMPTY_LINE); } } } private void addLabelGetters() { for (Column column: columns.getList()) { final String field = column.getJavaName(); if (!column.isSpecial()) javaClass.addContent( new FunctionDeclaration("get" + capitalize(field) + "Label", "String").addContent( new ReturnStatement(new FunctionCall("getLabel", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } private ExceptionThrow getCannotDisplayBadDataException() { return new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot display bad data")); } private void addRequiredIndicators() { for (Column column: columns.getList()) addIndicator(column.getJavaName(), "Required", column.isRequired(), false); } private void addUniqueIndicators() { for (Column column: columns.getList()) addIndicator(column.getJavaName(), "ToBeUnique", column.isUnique(), false); } private void addOneToManyRelationshipManagement() { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { final String beanClass = relationship.getBeanClass(); final String itemName = uncapitalize(beanClass); final String listName = relationship.getJavaName(); if (relationship.isListOnly()) { importsManager.addImport("org.dbbeans.sql.DBQuerySetupRetrieveData"); final FunctionDeclaration preparedStatementSetup = new FunctionDeclaration("setupPreparedStatement") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .addContent(new FunctionCall("setLong", "stat") .addArgument("1") .addArgument("id") .byItself()); final FunctionCall dbAccessFunction = new FunctionCall("processQuery", "dbAccess").byItself(); final FunctionDeclaration listGetter = new FunctionDeclaration("get" + capitalize(listName), new GenericType("List", beanClass)) .addContent(VarDeclaration.createListDeclaration(beanClass, listName).markAsFinal()) .addContent(EMPTY_LINE) .addContent(dbAccessFunction .addArgument(new OperatorExpression(quickQuote("SELECT ") + " + " + beanClass + ".DATABASE_FIELD_LIST + " + quickQuote(" FROM " + relationship.getTable() + " WHERE " + relationship.getIdSqlName() + "=? ORDER BY "), new FunctionCall("getOrderByFields", beanClass + "." + Strings.uncamelize(beanClass).toUpperCase() + "_PARAMETERS"), OperatorExpression.Operator.ADD)) .addArgument(new AnonymousClassCreation("DBQuerySetupProcess").setContext(dbAccessFunction) .addContent(preparedStatementSetup) .addContent(EMPTY_LINE) .addContent(new FunctionDeclaration("processResultSet") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")) .addContent(new WhileBlock(new Condition("rs.next()")) .addContent(new FunctionCall("add", listName).byItself() .addArgument(new ObjectCreation(beanClass) .addArgument("rs"))))))) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(listName)); javaClass.addContent(listGetter).addContent(EMPTY_LINE); final FunctionCall dbAccessForCountFunction = new FunctionCall("processQuery", "dbAccess"); final FunctionDeclaration countGetter = new FunctionDeclaration("getCountFor" + capitalize(listName), "long") .addContent(new ReturnStatement( dbAccessForCountFunction .addArgument(quickQuote("SELECT COUNT(id) FROM " + relationship.getTable() + " WHERE " + relationship.getIdSqlName() + "=?")) .addArgument(new AnonymousClassCreation("DBQuerySetupRetrieveData<Long>").setContext(dbAccessFunction) .addContent(preparedStatementSetup) .addContent(new FunctionDeclaration("processResultSet", "Long") .annotate("@Override") .addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")) .addContent(new FunctionCall("next", "rs").byItself()) .addContent(new ReturnStatement(new FunctionCall("getLong", "rs").addArgument("1"))))) )); javaClass.addContent(countGetter).addContent(EMPTY_LINE); } else { importsManager.addImport("java.util.Collections"); javaClass.addContent( new FunctionDeclaration("add" + beanClass) .addArgument(new FunctionArgument(beanClass, itemName)) .addContent(new FunctionCall("add", listName).byItself() .addArgument(itemName)) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("get" + beanClass, beanClass) .addArgument(new FunctionArgument("int", "index")) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new ReturnStatement(new FunctionCall("get", listName).addArgument("index"))) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("insert" + beanClass) .addArgument(new FunctionArgument("int", "index")) .addArgument(new FunctionArgument(beanClass, itemName)) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new FunctionCall("add", listName).addArgument("index").addArgument(itemName).byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("delete" + beanClass) .addArgument(new FunctionArgument("int", "index")) .addContent(getOneToManyRelationshipIndexOutOfBoundTest(listName)) .addContent(EMPTY_LINE) .addContent(new FunctionCall("remove", listName).addArgument("index").byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("clear" + capitalize(listName)) .addContent(new FunctionCall("clear", listName).byItself()) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("get" + capitalize(listName), new GenericType("List", beanClass)) .addContent(new ReturnStatement(new FunctionCall("unmodifiableList", "Collections").addArgument(listName))) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("getCountFor" + capitalize(listName), "long") .addContent(new ReturnStatement(new FunctionCall("size", listName))) ).addContent(EMPTY_LINE); } } } private IfBlock getOneToManyRelationshipIndexOutOfBoundTest(final String listName) { return new IfBlock(new Condition(new Comparison("index", "0", Comparison.Comparator.LESS_THAN)) .orCondition(new Condition(new Comparison("index", new FunctionCall("size", listName), Comparison.Comparator.GT_EQUAL)))) .addContent(new ExceptionThrow("IndexOutOfBoundsException") .addArgument(getOneToManyRelationshipIndexOutOfBoundExceptionText(listName))); } private String getOneToManyRelationshipIndexOutOfBoundExceptionText(final String listName) { return "\"Bounds : 0-\" + " + listName + ".size() + \", index : \" + index"; } private void addItemOrderManagement() { if (!columns.hasItemOrder()) return; final Column itemOrderField = columns.getItemOrderField(); javaClass.addContent( new FunctionDeclaration("isFirstItemOrder", "boolean").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new ReturnStatement("itemOrder == 1") ) ).addContent(EMPTY_LINE); final FunctionDeclaration isLastItemOrderFunction = new FunctionDeclaration("isLastItemOrder", "boolean").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE); if (!itemOrderField.isUnique()) isLastItemOrderFunction.addContent( new IfBlock(new Condition(new Comparison(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())), "0"))).addContent( new ReturnStatement(new Comparison("itemOrder", getMaxItemOrderFunctionCall(itemOrderField, false, true))) ).addContent(EMPTY_LINE) ); isLastItemOrderFunction.addContent( new ReturnStatement(new Comparison("itemOrder", getMaxItemOrderFunctionCall(itemOrderField, false, false))) ); javaClass.addContent(isLastItemOrderFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("itemOrderMoveUp").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new FunctionCall("isFirstItemOrder"))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot move Item Order above position 1 which it currently occupies")) ) ).addContent(EMPTY_LINE).addContent( getItemOrderFunctionCalls("itemOrderMoveUp", itemOrderField) ).addContent(EMPTY_LINE).addContent( new LineOfCode("itemOrder ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("itemOrderMoveDown").addContent( checkForItemOrderOperationOnUninitializedBean() ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new FunctionCall("isLastItemOrder"))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument("\"Cannot move Item Order below max position: \" + itemOrder") ) ).addContent(EMPTY_LINE).addContent( getItemOrderFunctionCalls("itemOrderMoveDown", itemOrderField) ).addContent(EMPTY_LINE).addContent( new LineOfCode("itemOrder++;") ) ).addContent(EMPTY_LINE); if (itemOrderField.isUnique()) { javaClass.addContent( new FunctionDeclaration("itemOrderMoveAfter") .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) )) ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderMoveBefore") .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) )) ) ).addContent(EMPTY_LINE).addContent( getBaseItemOrderMoveFunction().addContent( new FunctionCall("updateItemOrdersInBetween", "DBQueries").addArguments("query", "transaction", "lowerBound", "upperBound").byItself() ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE); } else { final String associatedFieldJavaName = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); final String associatedFieldJavaFunction = "get" + camelize(itemOrderField.getItemOrderAssociatedField()); javaClass.addContent( new FunctionDeclaration("itemOrderMoveAfter").addArgument(new FunctionArgument(beanName, beanVarName)).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, new FunctionCall(associatedFieldJavaFunction, beanVarName)))).addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument("itemOrder") .addArgument(associatedFieldJavaName) )) ).elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(associatedFieldJavaName) )) )) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.ADD)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderMoveBefore").addArgument(new FunctionArgument(beanName, beanVarName)).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, new FunctionCall(associatedFieldJavaFunction, beanVarName)))).addContent( new IfBlock(new Condition(new Comparison("itemOrder", new FunctionCall("getItemOrder", beanVarName), Comparison.Comparator.GREATER_THAN))).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(new FunctionCall("getIncreaseItemOrderBetweenQuery", parametersVar)) .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument("itemOrder") .addArgument(associatedFieldJavaName) )) ).elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQueryWithNullSecondaryField", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new OperatorExpression(new FunctionCall("getItemOrder", beanVarName), "1", OperatorExpression.Operator.SUBTRACT)) .addArgument(new FunctionCall("getDecreaseItemOrderBetweenQuery", parametersVar)) .addArgument("itemOrder") .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(associatedFieldJavaName) )) )) ).elseClause(new ElseBlock().addContent( new FunctionCall("itemOrderMove").byItself() .addArgument(new FunctionCall("getItemOrder", beanVarName)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( getBaseItemOrderMoveFunction().addArgument(new FunctionArgument("long...", "parameters")).addContent( new FunctionCall("updateItemOrdersInBetween", "DBQueries").addArguments("query", "transaction", "lowerBound", "upperBound", "parameters").byItself() ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQueryWithNullSecondaryField", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQuery", parametersVar)) .addArgument(beanVarName) ).addElseIfClause(new ElseIfBlock(new Condition(new Comparison(new FunctionCall(associatedFieldJavaFunction, beanVarName), "0"))).addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQuery", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQueryWithNullSecondaryField", parametersVar)) .addArgument(beanVarName) )).elseClause(new ElseBlock().addContent( getItemOrderMoveCall() .addArgument(new FunctionCall("getPushItemOrdersUpQuery", parametersVar)) .addArgument("newItemOrder - 1") .addArgument(new FunctionCall("getPushItemOrdersDownQuery", parametersVar)) .addArgument(beanVarName) )) ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("String", "queryDest")) .addArgument(new FunctionArgument("long", "destLowerBound")) .addArgument(new FunctionArgument("String", "queryOrig")) .addArgument(new FunctionArgument(beanName, beanVarName)) .addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryDest", "transaction", "destLowerBound") ).elseClause(new ElseBlock().addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryDest", "transaction", "destLowerBound", associatedFieldJavaName) )) ).addContent( new IfBlock(new Condition(new Comparison(new FunctionCall(associatedFieldJavaFunction, beanVarName), "0"))).addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryOrig", "transaction", "itemOrder") ).elseClause(new ElseBlock().addContent( getDBQueriesUpdateItemOrdersAboveCall().addArguments("queryOrig", "transaction", "itemOrder", associatedFieldJavaName) )) ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE).addContent( new FunctionDeclaration("itemOrderReassociateWith").addArgument(new FunctionArgument("long", associatedFieldJavaName)).addContent( new IfBlock(new Condition(new Comparison("id", "0"))).addContent( ExceptionThrow.getThrowExpression("IllegalArgumentException", "Bean must be saved in DB before reassociation.") ) ).addContent( new IfBlock(new Condition(new Comparison("this." + associatedFieldJavaName, associatedFieldJavaName))).addContent( ExceptionThrow.getThrowExpression("IllegalArgumentException", "Association already exists.") ) ).addContent(EMPTY_LINE).addContent( new FunctionCall("itemOrderMove").addArgument(associatedFieldJavaName).byItself() ) ).addContent(EMPTY_LINE).addContent( getItemOrderMoveDeclarationStart().addArgument(new FunctionArgument("long", associatedFieldJavaName)).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new VarDeclaration("long", "newItemOrder") ).addContent( new IfBlock(new Condition(new Comparison(associatedFieldJavaName, "0"))).addContent( new Assignment("newItemOrder", new OperatorExpression( new FunctionCall("getMaxItemOrder", "DBQueries") .addArgument("transaction") .addArgument(new FunctionCall("getItemOrderMaxQueryWithNullSecondaryField", parametersVar)), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new Assignment("newItemOrder", new OperatorExpression( new FunctionCall("getMaxItemOrder", "DBQueries") .addArgument("transaction") .addArgument(new FunctionCall("getItemOrderMaxQuery", parametersVar)) .addArgument(associatedFieldJavaName), "1", OperatorExpression.Operator.ADD)) )) ).addContent( new IfBlock(new Condition(new Comparison("this." + associatedFieldJavaName, "0"))).addContent( new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall("getUpdateItemOrdersAboveQueryWithNullSecondaryField", parametersVar)) .addArgument("transaction").addArgument("itemOrder") ).elseClause(new ElseBlock().addContent( new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall("getUpdateItemOrdersAboveQuery", parametersVar)) .addArgument("transaction").addArgument("itemOrder") .addArgument("this." + associatedFieldJavaName) )) ).addContent( new Assignment("this." + associatedFieldJavaName, associatedFieldJavaName) ).addContent( getItemOrderCompleteTransactionFunctionCall() ) ).addContent(EMPTY_LINE); } javaClass.addContent( new FunctionDeclaration("itemOrderMoveCompleteTransaction").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addContent(new Assignment("itemOrder", "newItemOrder")) .addContent(new FunctionCall("updateRecord").addArgument("transaction").byItself()) .addContent(new FunctionCall("commit", "transaction").byItself()) ).addContent(EMPTY_LINE); } private FunctionDeclaration getItemOrderMoveDeclarationStart() { return new FunctionDeclaration("itemOrderMove").visibility(Visibility.PROTECTED); } private FunctionDeclaration getBaseItemOrderMoveFunction() { return getItemOrderMoveDeclarationStart() .addArgument(new FunctionArgument("long", "newItemOrder")) .addArgument(new FunctionArgument("String", "query")) .addArgument(new FunctionArgument("long", "lowerBound")) .addArgument(new FunctionArgument("long", "upperBound")) .addContent(new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()); } private FunctionCall getItemOrderMoveCall() { return new FunctionCall("itemOrderMove").byItself().addArgument("newItemOrder"); } private FunctionCall getDBQueriesUpdateItemOrdersAboveCall() { return new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself(); } private FunctionCall getItemOrderCompleteTransactionFunctionCall() { return new FunctionCall("itemOrderMoveCompleteTransaction").addArguments("newItemOrder", "transaction").byItself(); } private FunctionCall getMaxItemOrderFunctionCall(final Column itemOrderField, final boolean withTransaction, final boolean nullSecondaryVariant) { final FunctionCall functionCall = new FunctionCall("getMaxItemOrder", "DBQueries"); if (withTransaction) functionCall.addArgument("transaction"); else functionCall.addArgument("db"); if (nullSecondaryVariant) functionCall.addArgument(new FunctionCall("getItemOrderMaxQueryWithNullSecondaryField", parametersVar)); else { functionCall.addArgument(new FunctionCall("getItemOrderMaxQuery", parametersVar)); if (!itemOrderField.isUnique()) functionCall.addArgument(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField()))); } return functionCall; } private JavaCodeBlock getItemOrderFunctionCalls(final String functionName, final Column itemOrderField) { final FunctionCall itemOrderFunctionCall = getItemOrderFunctionCall(functionName, "getIdFromItemOrderQuery"); if (itemOrderField.isUnique()) return itemOrderFunctionCall; final String itemOrderAssociatedFieldJavaName = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); itemOrderFunctionCall.addArgument(itemOrderAssociatedFieldJavaName); final FunctionCall itemOrderFunctionCallNullCase = getItemOrderFunctionCall(functionName, "getIdFromItemOrderQueryWithNullSecondaryField"); return new IfBlock(new Condition(new Comparison(itemOrderAssociatedFieldJavaName, "0", Comparison.Comparator.GREATER_THAN))) .addContent(itemOrderFunctionCall) .elseClause(new ElseBlock().addContent(itemOrderFunctionCallNullCase)); } private FunctionCall getItemOrderFunctionCall(final String functionName, final String parameterFunctionName) { return new FunctionCall(functionName, "DBQueries") .addArgument("db") .addArgument(new FunctionCall(parameterFunctionName, parametersVar)) .addArgument(quickQuote(tableName)) .addArgument("id") .addArgument("itemOrder") .byItself(); } private IfBlock checkForItemOrderOperationOnUninitializedBean() { return new IfBlock(new Condition("id == 0")).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Item Order operations not allowed on beans that have not been saved to the database")) ); } private static FunctionCall getPreUpdateConversionCall() { return new FunctionCall("preUpdateConversions").byItself(); } private void addUpdateDB() { if (columns.hasLastUpdate()) javaClass.addContent( new FunctionDeclaration("isUpdateOK", "boolean").addContent( new ReturnStatement("updateOK") ) ).addContent(EMPTY_LINE); final FunctionDeclaration updateDBFunction = new FunctionDeclaration("updateDB"); if (columns.hasModifiedBy()) updateDBFunction.addArgument(new FunctionArgument("String", "username")); updateDBFunction.addContent( getPreUpdateConversionCall() ).addContent(EMPTY_LINE); final FunctionCall createRecordCall = new FunctionCall("createRecord").byItself(); if (columns.hasModifiedBy()) createRecordCall.addArgument("username"); updateDBFunction.addContent( new IfBlock(new Condition("id == 0")).addContent(createRecordCall).addContent(new ReturnStatement()) ).addContent(EMPTY_LINE); final FunctionCall updateRecordCall = new FunctionCall("updateRecord").byItself(); if (columns.hasModifiedBy()) updateRecordCall.addArgument("username"); updateDBFunction.addContent( new IfBlock(new Condition("id > 0")).addContent(updateRecordCall).addContent(new ReturnStatement()) ).addContent(EMPTY_LINE); updateDBFunction.addContent( new LineOfCode("assert (false) : \"id < 0 ?!?\";") ); javaClass.addContent(updateDBFunction).addContent(EMPTY_LINE); final FunctionDeclaration updateDBFunctionWithTransaction = new FunctionDeclaration("updateDB", "long").addArgument(new FunctionArgument("DBTransaction", "transaction")); if (columns.hasModifiedBy()) updateDBFunctionWithTransaction.addArgument(new FunctionArgument("String", "username")); updateDBFunctionWithTransaction.addContent( getPreUpdateConversionCall() ).addContent(EMPTY_LINE); final FunctionCall createRecordCallWithTransaction = new FunctionCall("createRecord").addArgument("transaction"); if (columns.hasModifiedBy()) createRecordCallWithTransaction.addArgument("username"); updateDBFunctionWithTransaction.addContent( new IfBlock(new Condition("id == 0")).addContent(new Assignment("id", createRecordCallWithTransaction)).addContent(new ReturnStatement("id")) ).addContent(EMPTY_LINE); final FunctionCall updateRecordCallWithTransaction = new FunctionCall("updateRecord").addArgument("transaction").byItself(); if (columns.hasModifiedBy()) updateRecordCallWithTransaction.addArgument("username"); updateDBFunctionWithTransaction.addContent( new IfBlock(new Condition("id > 0")).addContent(updateRecordCallWithTransaction).addContent(new ReturnStatement("id")) ).addContent(EMPTY_LINE); updateDBFunctionWithTransaction.addContent( new LineOfCode("assert (false) : \"id < 0 ?!?\";") ).addContent( new ReturnStatement("-1") ); javaClass.addContent(updateDBFunctionWithTransaction).addContent(EMPTY_LINE); final FunctionDeclaration preUpdateConversionsFunction = new FunctionDeclaration("preUpdateConversions"); preUpdateConversionsFunction.addContent( ifNotDataOK().addContent( ExceptionThrow.getThrowExpression("IllegalArgumentException", "BAD DATA") ) ).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if ((type.equals("int") || type.equals("long")) && !field.startsWith("id")) preUpdateConversionsFunction.addContent( new Assignment(field, new FunctionCall("Strings.get" + capitalize(type) + "Val").addArgument(field + "Str")) ); if (JAVA_TEMPORAL_TYPES.contains(type)) preUpdateConversionsFunction.addContent( new IfBlock(new Condition(new FunctionCall("isEmpty", "Strings").addArgument(field + "Str"), true)).addContent( new Assignment(field, new FunctionCall("convertStringTo" + type).addArgument(field + "Str")) ).elseClause(new ElseBlock().addContent( new Assignment(field, "null") )) ); if (type.equals("Money")) preUpdateConversionsFunction.addContent( new Assignment(field, new ObjectCreation("Money").addArgument(field + "Str").addArgument(new FunctionCall("getDefaultMoneyFormat"))) ); } } javaClass.addContent(preUpdateConversionsFunction).addContent(EMPTY_LINE); } private void addDataOK() { final FunctionDeclaration dataOKFunction = new FunctionDeclaration("isDataOK", "boolean").addContent( new FunctionCall("clearErrorMessages", internalsVar).byItself() ).addContent( new VarDeclaration("boolean", "ok", "true") ).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); final IfBlock checkRequired = new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Required"))).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "EmptyErrorMessage")) ).addContent(new Assignment("ok", "false")); final IfBlock checkOKAndUnique = new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "OK"), true)).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "BadFormatErrorMessage")) ).addContent(new Assignment("ok", "false")); if (column.isUnique()) checkOKAndUnique.elseClause(new ElseBlock().addContent( new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Unique"), true)).addContent( new FunctionCall("addErrorMessage", internalsVar).byItself() .addArgument("id") .addArgument(quickQuote(field)) .addArgument(new FunctionCall("get" + fieldCap + "Label")) .addArgument(new FunctionCall("get" + fieldCap + "NotUniqueErrorMessage")) ).addContent(new Assignment("ok", "false")) )); dataOKFunction.addContent( new IfBlock(new Condition(new FunctionCall("is" + fieldCap + "Empty"))).addContent(checkRequired) .elseClause(new ElseBlock().addContent(checkOKAndUnique)) ).addContent(EMPTY_LINE); } } dataOKFunction.addContent( new ReturnStatement("ok") ); javaClass.addContent(dataOKFunction).addContent(EMPTY_LINE); for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String fieldCap = capitalize(field); final ReturnStatement returnStatement; if ((type.equals("int") || type.equals("long")) && field.startsWith("id")) returnStatement = new ReturnStatement(new Comparison(field, "0", Comparison.Comparator.EQUAL)); else { final String arg; if (type.equals("String")) arg = field; else arg = field + "Str"; returnStatement = new ReturnStatement(new FunctionCall("isEmpty", "Strings").addArgument(arg)); } javaClass.addContent( new FunctionDeclaration("is" + fieldCap + "Empty", "boolean").addContent(returnStatement) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "EmptyErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getRequiredErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String type = column.getJavaType(); final String field = column.getJavaName(); final String fieldCap = capitalize(field); final FunctionDeclaration isOKFunction = new FunctionDeclaration("is" + fieldCap + "OK", "boolean"); if ((type.equals("int") || type.equals("long"))) { if (field.startsWith("id")) isOKFunction.addContent(new ReturnStatement(new FunctionCall("isIdOK", column.getAssociatedBeanClass()).addArgument(field))); else { importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); isOKFunction.addContent(new ReturnStatement(new FunctionCall("isNumber", "FormatCheckHelper").addArgument(field + "Str"))); } } else if (JAVA_TEMPORAL_TYPES.contains(type)) { isOKFunction.addContent(new ReturnStatement(new FunctionCall("validate" + type + "Format").addArgument(field + "Str"))); } else if (type.equals("String")) { if (field.equalsIgnoreCase("email") || field.equalsIgnoreCase("e-mail")) { importsManager.addImport("org.beanmaker.util.FormatCheckHelper"); isOKFunction.addContent(new ReturnStatement(new FunctionCall("isEmailValid", "FormatCheckHelper").addArgument(field))); } else isOKFunction.addContent(new ReturnStatement("true")); } else if (type.equals("Money")) { isOKFunction.addContent(new ReturnStatement(new FunctionCall("isValOK", "getDefaultMoneyFormat()").addArgument(field + "Str"))); } else throw new IllegalStateException("Apparently unsupported type " + type + " encountered."); javaClass.addContent(isOKFunction).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && !column.getJavaType().equals("boolean")) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "BadFormatErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getBadFormatErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && column.isUnique()) { importsManager.addImport("org.dbbeans.sql.queries.BooleanCheckQuery"); final FunctionCall dbAccessFunctionCall = new FunctionCall("processQuery", "!dbAccess"); javaClass.addContent( new FunctionDeclaration("is" + capitalize(column.getJavaName() + "Unique"), "boolean").addContent( // TODO: IMPLEMENT!!! new ReturnStatement( dbAccessFunctionCall .addArgument(Strings.quickQuote(getNotUniqueQuery(column))) .addArgument(new AnonymousClassCreation("BooleanCheckQuery").setContext(dbAccessFunctionCall, 1).addContent( new FunctionDeclaration("setupPreparedStatement") .addArgument(new FunctionArgument("PreparedStatement", "stat")) .annotate("@Override").addException("SQLException").addContent( new FunctionCall("set" + capitalize(column.getJavaType()), "stat") .addArgument("1").addArgument(column.getJavaName()).byItself() ).addContent( new FunctionCall("setLong", "stat") .addArguments("2", "id").byItself() ) )) ) ) ).addContent(EMPTY_LINE); } } for (Column column: columns.getList()) { if (!column.isSpecial() && column.isUnique()) { final String field = column.getJavaName(); final String fieldCap = capitalize(field); javaClass.addContent( new FunctionDeclaration("get" + fieldCap + "NotUniqueErrorMessage", "String").addContent( new ReturnStatement(new FunctionCall("getNotUniqueErrorMessage", internalsVar).addArgument(quickQuote(field))) ) ).addContent(EMPTY_LINE); } } javaClass.addContent( new FunctionDeclaration("getErrorMessages", "List<ErrorMessage>").addContent( new ReturnStatement(new FunctionCall("getErrorMessages", internalsVar)) ) ).addContent(EMPTY_LINE); } private String getNotUniqueQuery(final Column column) { return "SELECT id FROM " + tableName + " WHERE " + column.getSqlName() + "=? AND id <> ?"; } private void addReset() { final FunctionDeclaration resetFunction = new FunctionDeclaration("reset"); for (Column column: columns.getList()) { if (!column.isSpecial()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (type.equals("boolean")) resetFunction.addContent(new Assignment(field, "false")); else if (type.equals("int") || type.equals("long")) resetFunction.addContent(new Assignment(field, "0")); else if (type.equals("String")) resetFunction.addContent(new Assignment(field, EMPTY_STRING)); else if (type.equals("Money")) resetFunction.addContent(new Assignment(field, new ObjectCreation("Money").addArgument("0").addArgument(new FunctionCall("getDefaultMoneyFormat")))); else resetFunction.addContent(new Assignment(field, "null")); if (JAVA_TEMPORAL_TYPES.contains(type) || type.equals("Money") || ((type.equals("int") || type.equals("int")) && !field.startsWith("id"))) resetFunction.addContent(new Assignment(field + "Str", EMPTY_STRING)); } } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) resetFunction.addContent(new FunctionCall("clear", relationship.getJavaName()).byItself()); resetFunction.addContent(new FunctionCall("clearErrorMessages", internalsVar).byItself()); javaClass.addContent(resetFunction).addContent(EMPTY_LINE); final FunctionDeclaration fullResetFunction = new FunctionDeclaration("fullReset").addContent( new FunctionCall("reset").byItself() ).addContent( new Assignment("id", "0") ); for (Column column: columns.getList()) { if (column.isLastUpdate()) fullResetFunction.addContent(new Assignment("lastUpdate", "0")); if (column.isModifiedBy()) fullResetFunction.addContent(new Assignment("modifiedBy", "null")); if (column.isItemOrder()) fullResetFunction.addContent(new Assignment("itemOrder", "0")); } javaClass.addContent(fullResetFunction).addContent(EMPTY_LINE); } private void addDelete() { final FunctionDeclaration deleteFunction = new FunctionDeclaration("delete"); final FunctionCall accessDB = new FunctionCall("addUpdate", "transaction").byItself(); deleteFunction.addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ); if (columns.hasItemOrder()) deleteFunction.addContent( new VarDeclaration("long", "curItemOrder").markAsFinal() ).addContent( new IfBlock(new Condition(new FunctionCall("isLastItemOrder"))).addContent( new Assignment("curItemOrder", "0") ).elseClause(new ElseBlock().addContent( new Assignment("curItemOrder", "itemOrder") )) ); deleteFunction.addContent( accessDB.addArgument(quickQuote(getDeleteSQLQuery())) .addArgument(new AnonymousClassCreation("DBQuerySetup").setContext(accessDB).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override").addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setLong", "stat").addArguments("1", "id").byItself() ) )) ); if (columns.hasItemOrder()) { final IfBlock checkItemOrderNotMax = new IfBlock(new Condition(new Comparison("curItemOrder", "0", Comparison.Comparator.GREATER_THAN))); final Column itemOrderField = columns.getItemOrderField(); if (itemOrderField.isUnique()) checkItemOrderNotMax.addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQuery", null) ); else { final String itemOrderAssociatedField = uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())); checkItemOrderNotMax.addContent( new IfBlock(new Condition(new Comparison(itemOrderAssociatedField, "0"))).addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQueryWithNullSecondaryField", null) ).elseClause(new ElseBlock().addContent( getUpdateItemOrderAboveFunctionCall("getUpdateItemOrdersAboveQuery", itemOrderAssociatedField) ))); } deleteFunction.addContent(checkItemOrderNotMax); } deleteFunction.addContent( new FunctionCall("deleteExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent( EMPTY_LINE ).addContent( new FunctionCall("postDeleteActions").byItself() ).addContent( new FunctionCall("fullReset").byItself() ); javaClass.addContent(deleteFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("deleteExtraDbActions").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postDeleteActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private FunctionCall getUpdateItemOrderAboveFunctionCall(final String queryRetrievalFunction, final String itemOrderAssociatedField) { final FunctionCall functionCall = new FunctionCall("updateItemOrdersAbove", "DBQueries").byItself() .addArgument(new FunctionCall(queryRetrievalFunction, parametersVar)) .addArgument("transaction") .addArgument("curItemOrder"); if (itemOrderAssociatedField != null) functionCall.addArgument(itemOrderAssociatedField); return functionCall; } private FunctionCall getStatSetFunction(final String type, final String field, final int index) { return new FunctionCall("set" + capitalize(type), "stat").byItself().addArguments(Integer.toString(index), field); } private JavaCodeBlock getFieldCreationOrUpdate(final Column column, final int index) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (column.isRequired()) return getStatSetFunction(type, field, index); if (column.hasAssociatedBean()) return new IfBlock(new Condition(new Comparison(field, "0"))).addContent( new FunctionCall("setNull", "stat").byItself().addArguments(Integer.toString(index), "java.sql.Types.INTEGER") ).elseClause(new ElseBlock().addContent( getStatSetFunction(type, field, index) )); if (JAVA_TEMPORAL_TYPES.contains(type)) return new IfBlock(new Condition(new Comparison(field, "null"))).addContent( new FunctionCall("setNull", "stat").byItself().addArguments(Integer.toString(index), "java.sql.Types." + type.toUpperCase()) ).elseClause(new ElseBlock().addContent( getStatSetFunction(type, field, index) )); return getStatSetFunction(type, field, index); } private void addCreate() { int index = 0; final JavaClass recordCreationSetupClass = new JavaClass("RecordCreationSetup").implementsInterface("DBQuerySetup").visibility(Visibility.PRIVATE); final FunctionDeclaration setupStatFunction = new FunctionDeclaration("setupPreparedStatement").annotate("@Override") .addException("SQLException").addArgument(new FunctionArgument("PreparedStatement", "stat")); for (Column column: columns.getList()) { final String type = column.getJavaType(); final String field = column.getJavaName(); if (!column.isId()) { if (type.equals("Money")) { final String suggestedType = Column.getSuggestedType(column.getSqlTypeName(), column.getPrecision()); if (suggestedType.equals("int")) setupStatFunction.addContent( new FunctionCall("setInt", "stat").byItself().addArgument(Integer.toString(++index)).addArgument(new FunctionCall("getIntVal", field)) ); else if (suggestedType.equals("long")) setupStatFunction.addContent( new FunctionCall("setLong", "stat").byItself().addArgument(Integer.toString(++index)).addArgument(new FunctionCall("getVal", field)) ); else throw new IllegalStateException("Money cannot be used with non INTEGER SQL field: " + column.getSqlName()); } else { setupStatFunction.addContent( getFieldCreationOrUpdate(column, ++index) ); } } } javaClass.addContent(recordCreationSetupClass.addContent(setupStatFunction)).addContent(EMPTY_LINE); javaClass.addContent( new JavaClass("RecordUpdateSetup").extendsClass("RecordCreationSetup").visibility(Visibility.PRIVATE).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override") .addException("SQLException").addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setupPreparedStatement", "super").byItself().addArgument("stat") ).addContent( new FunctionCall("setLong", "stat").byItself().addArguments(Integer.toString(++index), "id") ) ) ).addContent(EMPTY_LINE); final FunctionDeclaration createRecordFunction = new FunctionDeclaration("createRecord").visibility(Visibility.PRIVATE).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal()).addContent( new FunctionCall("preCreateExtraDbActions").byItself().addArgument("transaction") ).addContent( new VarDeclaration("long", "id", new FunctionCall("createRecord").addArgument("transaction")).markAsFinal() ); addOneToManyRelationshipDBUpdateFunctionCalls(createRecordFunction); createRecordFunction.addContent( new FunctionCall("createExtraDbActions").byItself().addArguments("transaction", "id") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent(EMPTY_LINE).addContent( new Assignment("this.id", "id") ).addContent( new FunctionCall("postCreateActions").byItself() ); javaClass.addContent(createRecordFunction).addContent(EMPTY_LINE); final FunctionDeclaration createRecordFunctionWithTransaction = new FunctionDeclaration("createRecord", "long").addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PRIVATE); if (columns.hasItemOrder()) { final Column itemOrderField = columns.getItemOrderField(); final IfBlock uninitializedItemOrderCase = new IfBlock(new Condition(new Comparison("itemOrder", "0"))); if (itemOrderField.isUnique()) uninitializedItemOrderCase.addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, false), "1", OperatorExpression.Operator.ADD)) ); else { uninitializedItemOrderCase.addContent( new IfBlock(new Condition(new Comparison(uncapitalize(camelize(itemOrderField.getItemOrderAssociatedField())), "0"))).addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, true), "1", OperatorExpression.Operator.ADD)) ).elseClause(new ElseBlock().addContent( new Assignment("itemOrder", new OperatorExpression(getMaxItemOrderFunctionCall(columns.getItemOrderField(), true, false), "1", OperatorExpression.Operator.ADD)) )) ); } createRecordFunctionWithTransaction.addContent(uninitializedItemOrderCase).addContent(EMPTY_LINE); } createRecordFunctionWithTransaction.addContent( new ReturnStatement(new FunctionCall("addRecordCreation", "transaction") .addArgument(quickQuote(getInsertSQLQuery())) .addArgument(new ObjectCreation("RecordCreationSetup"))) ); javaClass.addContent(createRecordFunctionWithTransaction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("preCreateExtraDbActions") .addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("createExtraDbActions") .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addArgument(new FunctionArgument("long", "id")).visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postCreateActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private void addOneToManyRelationshipDBUpdateFunctionCalls(final FunctionDeclaration function) { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { if (!relationship.isListOnly()) function.addContent( new FunctionCall("update" + capitalize(relationship.getJavaName()) + "InDB").byItself().addArguments("transaction", "id") ); } } private void addUpdate() { final FunctionDeclaration updateRecordFunction = new FunctionDeclaration("updateRecord").visibility(Visibility.PRIVATE).addContent( new VarDeclaration("DBTransaction", "transaction", new FunctionCall("createDBTransaction")).markAsFinal() ).addContent( new FunctionCall("preUpdateExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("updateRecord").byItself().addArgument("transaction") ); addOneToManyRelationshipDBUpdateFunctionCalls(updateRecordFunction); updateRecordFunction.addContent( new FunctionCall("updateExtraDbActions").byItself().addArgument("transaction") ).addContent( new FunctionCall("commit", "transaction").byItself() ).addContent( new FunctionCall("postUpdateActions").byItself() ); javaClass.addContent(updateRecordFunction).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("updateRecord").addArgument(new FunctionArgument("DBTransaction", "transaction")).visibility(Visibility.PRIVATE).addContent( new FunctionCall("addUpdate", "transaction").byItself() .addArgument(quickQuote(getUpdateSQLQuery())) .addArgument(new ObjectCreation("RecordUpdateSetup")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("preUpdateExtraDbActions").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("updateExtraDbActions").visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("DBTransaction", "transaction")) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("postUpdateActions").visibility(Visibility.PROTECTED) ).addContent(EMPTY_LINE); } private void addOneToManyRelationshipInDB() { for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) { if (!relationship.isListOnly()) { final FunctionDeclaration updateRelationshipFunction = new FunctionDeclaration("update" + capitalize(relationship.getJavaName()) + "InDB") .addArgument(new FunctionArgument("DBTransaction", "transaction")) .addArgument(new FunctionArgument("long", "id")) .visibility(Visibility.PRIVATE); final FunctionCall dbAccessFunction = new FunctionCall("addUpdate", "transaction").byItself(); updateRelationshipFunction.addContent( dbAccessFunction .addArgument(quickQuote(getDeleteOneToManyRelationshipQuery(relationship.getTable(), relationship.getIdSqlName()))) .addArgument(new AnonymousClassCreation("DBQuerySetup").setContext(dbAccessFunction).addContent( new FunctionDeclaration("setupPreparedStatement").annotate("@Override").addException("SQLException") .addArgument(new FunctionArgument("PreparedStatement", "stat")).addContent( new FunctionCall("setLong", "stat").byItself().addArguments("1", "id") ) )) ).addContent(EMPTY_LINE); final String var = uncapitalize(relationship.getBeanClass()); updateRelationshipFunction.addContent( new ForLoop(relationship.getBeanClass() + " " + var + ": " + relationship.getJavaName()).addContent( new FunctionCall("resetId", var).byItself() ).addContent( new FunctionCall("setId" + beanName, var).addArgument("id").byItself() ).addContent( new FunctionCall("updateDB", var).addArgument("transaction").byItself() ) ); javaClass.addContent(updateRelationshipFunction).addContent(EMPTY_LINE); } } } private void addTemporalFunctions() { if (types.contains("Date")) { javaClass.addContent( new FunctionDeclaration("formatDate", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Date", "date")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getDateInstance", "DateFormat").addArgument("DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("date") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToDate", "Date").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getDateFromYYMD", "Dates").addArguments("str", quickQuote("-")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Date", "date")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateDateFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputDateFormat", "simpleInputDateFormat", new ObjectCreation("SimpleInputDateFormat") .addArguments("SimpleInputDateFormat.ElementOrder.YYMD", quickQuote("-")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputDateFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } if (types.contains("Time")) { javaClass.addContent( new FunctionDeclaration("formatTime", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Time", "time")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getTimeInstance", "DateFormat").addArgument("DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("time") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToTime", "Time").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getTimeFromString", "Dates").addArguments("str", quickQuote(":")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Time", "time")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateTimeFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputTimeFormat", "simpleInputTimeFormat", new ObjectCreation("SimpleInputTimeFormat").addArgument(quickQuote(":")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputTimeFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } if (types.contains("Timestamp")) { javaClass.addContent( new FunctionDeclaration("formatTimestamp", "String").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("Timestamp", "timestamp")).addContent( new ReturnStatement( new FunctionCall( "format", new FunctionCall( "getDateTimeInstance", "DateFormat").addArguments("DateFormat.LONG", "DateFormat.LONG").addArgument(new FunctionCall("getLocale", internalsVar)) ).addArgument("timestamp") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("convertStringToTimestamp", "Timestamp").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new ReturnStatement( new FunctionCall("getTimestampFromYYMD", "Dates").addArguments("str", quickQuote("-"), quickQuote(":")) ) ) ).addContent(EMPTY_LINE); javaClass.addContent(getTemporalConvertToStringFunction("Timestamp", "timestamp")).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("validateTimestampFormat", "boolean").visibility(Visibility.PROTECTED).addArgument(new FunctionArgument("String", "str")).addContent( new VarDeclaration( "SimpleInputTimestampFormat", "simpleInputTimestampFormat", new ObjectCreation("SimpleInputTimestampFormat") .addArguments("SimpleInputDateFormat.ElementOrder.YYMD", quickQuote("-"), quickQuote(":")) ).markAsFinal() ).addContent( new ReturnStatement( new FunctionCall( "validate", "simpleInputTimestampFormat" ).addArgument("str") ) ) ).addContent(EMPTY_LINE); } } private void addGetAll() { javaClass.addContent( new FunctionDeclaration("getAll", "List<" + beanName + ">").markAsStatic().addContent( new ReturnStatement(new FunctionCall("getAll").addArgument(new FunctionCall("getOrderByFields", parametersVar))) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getAll", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "orderBy")).addContent( new ReturnStatement(new FunctionCall("getSelection").addArguments("null", "orderBy", "null")) ) ).addContent(EMPTY_LINE); final ObjectCreation newBeanFromFields = new ObjectCreation(beanName); int index = 0; for (Column column: columns.getList()) { final String javaType = column.getJavaType(); if (javaType.equals("Money")) throw new UnsupportedOperationException("Money not supported for now."); // for now... ++index; newBeanFromFields.addArgument(new FunctionCall("get" + capitalize(javaType), "rs").addArguments(Integer.toString(index))); } for (OneToManyRelationship relationship: columns.getOneToManyRelationships()) if (!relationship.isListOnly()) newBeanFromFields.addArgument(new FunctionCall("getSelection", relationship.getBeanClass()) .addArgument(new OperatorExpression("\"id_" + uncamelize(beanVarName) + "=\"", new FunctionCall("getLong", "rs").addArgument("1"), OperatorExpression.Operator.ADD))); javaClass.addContent( new JavaClass("GetSelectionQueryProcess").implementsInterface("DBQueryRetrieveData<List<" + beanName + ">>").visibility(Visibility.PRIVATE).markAsStatic().addContent( new FunctionDeclaration("processResultSet", "List<" + beanName + ">").annotate("@Override").addException("SQLException") .addArgument(new FunctionArgument("ResultSet", "rs")).addContent( VarDeclaration.createListDeclaration(beanName, "list").markAsFinal() ).addContent(EMPTY_LINE).addContent( new WhileBlock(new Condition(new FunctionCall("next", "rs"))).addContent( new FunctionCall("add", "list").byItself().addArgument(newBeanFromFields) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement("list") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")).addContent( new ReturnStatement(new FunctionCall("getSelection").addArguments("whereClause", "null")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")) .addArgument(new FunctionArgument("DBQuerySetup", "setup")).addContent( new ReturnStatement(new FunctionCall("getSelection") .addArgument("whereClause") .addArguments(new FunctionCall("getOrderByFields", parametersVar)) .addArgument("setup")) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getSelection", "List<" + beanName + ">").markAsStatic().visibility(Visibility.PROTECTED) .addArgument(new FunctionArgument("String", "whereClause")) .addArgument(new FunctionArgument("String", "orderBy")) .addArgument(new FunctionArgument("DBQuerySetup", "setup")).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null")) .andCondition(new Condition(new Comparison("setup", "null", Comparison.Comparator.NEQ)))).addContent( new ExceptionThrow("IllegalArgumentException").addArgument(quickQuote("Cannot accept setup code without a WHERE clause.")) ) ).addContent(EMPTY_LINE).addContent( new VarDeclaration("StringBuilder", "query", new ObjectCreation("StringBuilder")).markAsFinal() ).addContent( new FunctionCall("append", "query").addArgument(quickQuote(getAllFieldsQuery())).byItself() ).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null", Comparison.Comparator.NEQ))).addContent( new FunctionCall("append", new FunctionCall("append", "query").addArgument(quickQuote(" WHERE "))).addArgument("whereClause").byItself() ) ).addContent( new IfBlock(new Condition(new Comparison("orderBy", "null", Comparison.Comparator.NEQ))).addContent( new FunctionCall("append", new FunctionCall("append", "query").addArgument(quickQuote(" ORDER BY "))).addArgument("orderBy").byItself() ) ).addContent(EMPTY_LINE).addContent( new IfBlock(new Condition(new Comparison("whereClause", "null")) .orCondition(new Condition(new Comparison("setup", "null")))).addContent( new ReturnStatement(new FunctionCall("processQuery", "dbAccess") .addArgument(new FunctionCall("toString", "query")) .addArgument(new ObjectCreation("GetSelectionQueryProcess"))) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement(new FunctionCall("processQuery", "dbAccess") .addArgument(new FunctionCall("toString", "query")) .addArgument("setup") .addArgument(new ObjectCreation("GetSelectionQueryProcess"))) ) ).addContent(EMPTY_LINE); } private void addGetIdNamePairs() { javaClass.addContent( new FunctionDeclaration("getIdNamePairs", "List<IdNamePair>").markAsStatic().addArguments( new FunctionArgument("List<String>", "dataFields"), new FunctionArgument("List<String>", "orderingFields") ).addContent( new ReturnStatement( new FunctionCall("getIdNamePairs").addArguments("null", "dataFields", "orderingFields") ) ) ).addContent(EMPTY_LINE); javaClass.addContent( new FunctionDeclaration("getIdNamePairs", "List<IdNamePair>").visibility(Visibility.PROTECTED).markAsStatic().addArguments( new FunctionArgument("String", "whereClause"), new FunctionArgument("List<String>", "dataFields"), new FunctionArgument("List<String>", "orderingFields") ).addContent( new ReturnStatement( new FunctionCall("getIdNamePairs", "DBQueries").addArguments("db", quickQuote(tableName), "whereClause", "dataFields", "orderingFields") ) ) ).addContent(EMPTY_LINE); } private void addGetCount() { javaClass.addContent( new FunctionDeclaration("getCount", "long").markAsStatic().addContent( new ReturnStatement(new FunctionCall("getLongCount", "DBQueries").addArguments("db", quickQuote(tableName))) ) ).addContent(EMPTY_LINE); } private void addIdOK() { javaClass.addContent( new FunctionDeclaration("isIdOK", "boolean").markAsStatic().addArgument(new FunctionArgument("long", "id")).addContent( new ReturnStatement(new FunctionCall("isIdOK", "DBQueries").addArguments("db", quickQuote(tableName), "id")) ) ).addContent(EMPTY_LINE); } private void addHumanReadableTitle() { javaClass.addContent( new FunctionDeclaration("getHumanReadableTitle", "String").markAsStatic().addArgument(new FunctionArgument("long", "id")).addContent( new ReturnStatement(new FunctionCall("getHumanReadableTitle", "DBQueries") .addArguments("db", quickQuote(tableName), "id") .addArgument(new FunctionCall("getNamingFields", parametersVar))) ) ).addContent(EMPTY_LINE); } private void addSetLocale() { javaClass.addContent( new FunctionDeclaration("setLocale").addArgument(new FunctionArgument("Locale", "locale")).addContent( new FunctionCall("setLocale", internalsVar).addArgument("locale").byItself() ) ).addContent(EMPTY_LINE); } private void createSourceCode() { sourceFile.setStartComment(SourceFiles.getCommentAndVersion()); addImports(); addClassModifiers(); addProperties(); addConstructors(); addSetIdFunction(); addEquals(); addToString(); addSetters(); addGetters(); addLabelGetters(); addRequiredIndicators(); addUniqueIndicators(); addOneToManyRelationshipManagement(); addItemOrderManagement(); addUpdateDB(); addDataOK(); addReset(); addDelete(); addCreate(); addUpdate(); addOneToManyRelationshipInDB(); addTemporalFunctions(); addGetAll(); addGetIdNamePairs(); addGetCount(); addIdOK(); addHumanReadableTitle(); addSetLocale(); } private String getReadSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("SELECT "); for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { buf.append(name); buf.append(", "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(" FROM "); buf.append(tableName); buf.append(" WHERE id=?"); return buf.toString(); } private String getAllFieldsQuery() { StringBuilder buf = new StringBuilder(); buf.append("SELECT "); for (Column column: columns.getList()) { final String name = column.getSqlName(); buf.append(name); buf.append(", "); } buf.delete(buf.length() - 2, buf.length()); buf.append(" FROM "); buf.append(tableName); return buf.toString(); } private String getReadSQLQueryOneToManyRelationship(final String tableName, final String indexField) { return "SELECT id FROM " + tableName + " WHERE " + indexField + "=?"; } private String getDeleteSQLQuery() { return "DELETE FROM " + tableName + " WHERE id=?"; } private String getInsertSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("INSERT INTO "); buf.append(tableName); buf.append(" ("); int count = 0; for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { count++; buf.append(name); buf.append(", "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(") VALUES ("); for (int i = 0; i < count; i++) buf.append("?, "); buf.delete(buf.length() - 2, buf.length()); buf.append(")"); return buf.toString(); } private String getUpdateSQLQuery() { StringBuilder buf = new StringBuilder(); buf.append("UPDATE "); buf.append(tableName); buf.append(" SET "); for (Column column: columns.getList()) { final String name = column.getSqlName(); if (!name.equals("id")) { buf.append(name); buf.append("=?, "); } } buf.delete(buf.length() - 2, buf.length()); buf.append(" WHERE id=?"); if (columns.hasLastUpdate()) buf.append(" AND last_update=?"); return buf.toString(); } private String getDeleteOneToManyRelationshipQuery(final String tableName, final String indexField) { return "DELETE FROM " + tableName + " WHERE " + indexField + "=?"; } private FunctionDeclaration getTemporalConvertToStringFunction(final String className, final String varName) { return new FunctionDeclaration("convert" + className + "ToString", "String").addArgument(new FunctionArgument(className, varName)).addContent( new IfBlock(new Condition(new Comparison(varName, "null"))).addContent( new ReturnStatement(EMPTY_STRING) ) ).addContent(EMPTY_LINE).addContent( new ReturnStatement(new FunctionCall("toString", varName)) ).visibility(Visibility.PROTECTED); } private void addIndicator(final String javaName, final String indicatorName, final boolean value, final boolean isFinal) { final FunctionDeclaration indicator = new FunctionDeclaration("is" + capitalize(javaName) + indicatorName, "boolean"); if (isFinal) indicator.markAsFinal(); if (value) indicator.addContent(new ReturnStatement("true")); else indicator.addContent(new ReturnStatement("false")); javaClass.addContent(indicator).addContent(EMPTY_LINE); } }
package com.ecyrd.jspwiki.plugin; import org.apache.log4j.Category; import com.ecyrd.jspwiki.*; import java.util.*; import java.io.StreamTokenizer; import java.io.StringReader; import java.io.IOException; /** * Plugin for doing go game diagrams. * * @author Janne Jalkanen */ public class GoDiagram implements WikiPlugin { private static Category log = Category.getInstance( GoDiagram.class ); public static final int BLACK_FIRST = 1; public static final int WHITE_FIRST = 0; public void initialize( WikiContext context, Map params ) throws PluginException { } private String makeImage( String content ) { //return "<IMG SRC=\"images/diagram/"+content+".gif\">"; return "<TD><IMG SRC=\"images/diagram/"+content+".gif\"></TD>"; } /** * @param first 'b', if black should have the first move, 'w' otherwise. */ private String parseDiagram( String dia, int first ) throws IOException { StringTokenizer tok = new StringTokenizer( dia.trim(), " \t\n-", true ); // System.out.println("dia="+dia); StringBuffer res = new StringBuffer(); //res.append("<DIV CLASS=\"diagram\">\n"); res.append("<TABLE BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"0\">"); res.append("<TR>"); int type; int row = 0; int col = -1; while( tok.hasMoreTokens() ) { col++; String item = tok.nextToken(); if( Character.isDigit(item.charAt(0)) ) { int num = Integer.parseInt( item ); String which = (num % 2 == first) ? "b" : "w"; res.append( makeImage( which+Integer.toString(num) ) ); continue; } switch( item.charAt(0) ) { case ' case 'X': res.append( makeImage("b") ); break; case 'O': res.append( makeImage("w") ); break; case '.': res.append( makeImage("empty") ); break; case ',': res.append( makeImage("hoshi") ); break; case '|': res.append( makeImage( (col == 0) ? "LS" : "RS" ) ); break; case '+': res.append( makeImage( (row == 0 ? "U" : "L") + (col == 0 ? "L" : "R") + "C" ) ); break; case '-': if( col % 2 == 1 ) { res.append( makeImage( (row == 0) ? "TS" : "BS" ) ); } break; case '\r': case '\n': // res.append("<BR>\n"); res.append("</TR>\n<TR>"); col = -1; row++; break; case ' ': case '\t': break; default: res.append( makeImage( "lc"+item ) ); break; } } //res.append("</DIV>\n"); res.append("</TR>\n"); res.append("</TABLE>"); return res.toString(); } // FIXME: Parameters should be checked against HTML entities. // FIXME: "label" should be run through parser public String execute( WikiContext context, Map params ) throws PluginException { String diagram = (String) params.get( "_body" ); String label = (String) params.get( "label" ); String first = (String) params.get( "first" ); if( diagram == null || diagram.length() == 0 ) { return "<B>No diagram detected.</B>"; } if( first == null || first.length() == 0 || !(first.startsWith("w") || first.startsWith("W")) ) { first = "b"; } try { StringBuffer sb = new StringBuffer(); sb.append("<table border=1 align=left style=\"margin: 10px;\">"); sb.append("<tr><td>\n"); sb.append( parseDiagram( diagram, (first.startsWith("b") ? BLACK_FIRST : WHITE_FIRST )) ); sb.append("</td></tr>\n"); if( label != null ) { sb.append( "<tr><td class=\"diagramlabel\">Dia: "+label+"</td></tr>\n" ); } sb.append("</table>\n"); return sb.toString(); } catch( IOException e ) { log.error("Something funny in diagram", e ); throw new PluginException("Error in diagram: "+e.getMessage()); } } }
package org.bouncycastle.jce.provider; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.PBEParametersGenerator; import org.bouncycastle.crypto.digests.MD2Digest; import org.bouncycastle.crypto.digests.MD5Digest; import org.bouncycastle.crypto.digests.RIPEMD160Digest; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.TigerDigest; import org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator; import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator; import org.bouncycastle.crypto.generators.PKCS5S1ParametersGenerator; import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; import org.bouncycastle.crypto.params.DESParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; public interface PBE { // PBE Based encryption constants - by default we do PKCS12 with SHA-1 static final int MD5 = 0; static final int SHA1 = 1; static final int RIPEMD160 = 2; static final int TIGER = 3; static final int SHA256 = 4; static final int MD2 = 5; static final int PKCS5S1 = 0; static final int PKCS5S2 = 1; static final int PKCS12 = 2; static final int OPENSSL = 3; /** * uses the appropriate mixer to generate the key and IV if necessary. */ static class Util { static private PBEParametersGenerator makePBEGenerator( int type, int hash) { PBEParametersGenerator generator; if (type == PKCS5S1) { switch (hash) { case MD2: generator = new PKCS5S1ParametersGenerator(new MD2Digest()); break; case MD5: generator = new PKCS5S1ParametersGenerator(new MD5Digest()); break; case SHA1: generator = new PKCS5S1ParametersGenerator(new SHA1Digest()); break; default: throw new IllegalStateException("PKCS5 scheme 1 only supports MD2, MD5 and SHA1."); } } else if (type == PKCS5S2) { generator = new PKCS5S2ParametersGenerator(); } else if (type == PKCS12) { switch (hash) { case MD2: generator = new PKCS12ParametersGenerator(new MD2Digest()); break; case MD5: generator = new PKCS12ParametersGenerator(new MD5Digest()); break; case SHA1: generator = new PKCS12ParametersGenerator(new SHA1Digest()); break; case RIPEMD160: generator = new PKCS12ParametersGenerator(new RIPEMD160Digest()); break; case TIGER: generator = new PKCS12ParametersGenerator(new TigerDigest()); break; case SHA256: generator = new PKCS12ParametersGenerator(new SHA256Digest()); break; default: throw new IllegalStateException("unknown digest scheme for PBE encryption."); } } else { generator = new OpenSSLPBEParametersGenerator(); } return generator; } /** * construct a key and iv (if necessary) suitable for use with a * Cipher. */ static CipherParameters makePBEParameters( JCEPBEKey pbeKey, AlgorithmParameterSpec spec, String targetAlgorithm) { if ((spec == null) || !(spec instanceof PBEParameterSpec)) { throw new IllegalArgumentException("Need a PBEParameter spec with a PBE key."); } PBEParameterSpec pbeParam = (PBEParameterSpec)spec; PBEParametersGenerator generator = makePBEGenerator(pbeKey.getType(), pbeKey.getDigest()); byte[] key = pbeKey.getEncoded(); CipherParameters param; if (pbeKey.shouldTryWrongPKCS12()) { key = new byte[2]; } generator.init(key, pbeParam.getSalt(), pbeParam.getIterationCount()); if (pbeKey.getIvSize() != 0) { param = generator.generateDerivedParameters(pbeKey.getKeySize(), pbeKey.getIvSize()); } else { param = generator.generateDerivedParameters(pbeKey.getKeySize()); } if (targetAlgorithm.startsWith("DES")) { if (param instanceof ParametersWithIV) { KeyParameter kParam = (KeyParameter)((ParametersWithIV)param).getParameters(); DESParameters.setOddParity(kParam.getKey()); } else { KeyParameter kParam = (KeyParameter)param; DESParameters.setOddParity(kParam.getKey()); } } for (int i = 0; i != key.length; i++) { key[i] = 0; } return param; } /** * generate a PBE based key suitable for a MAC algorithm, the * key size is chosen according the MAC size, or the hashing algorithm, * whichever is greater. */ static CipherParameters makePBEMacParameters( JCEPBEKey pbeKey, AlgorithmParameterSpec spec) { if ((spec == null) || !(spec instanceof PBEParameterSpec)) { throw new IllegalArgumentException("Need a PBEParameter spec with a PBE key."); } PBEParameterSpec pbeParam = (PBEParameterSpec)spec; PBEParametersGenerator generator = makePBEGenerator(pbeKey.getType(), pbeKey.getDigest()); byte[] key = pbeKey.getEncoded(); CipherParameters param; if (pbeKey.shouldTryWrongPKCS12()) { key = new byte[2]; } generator.init(key, pbeParam.getSalt(), pbeParam.getIterationCount()); param = generator.generateDerivedMacParameters(pbeKey.getKeySize()); for (int i = 0; i != key.length; i++) { key[i] = 0; } return param; } /** * construct a key and iv (if necessary) suitable for use with a * Cipher. */ static CipherParameters makePBEParameters( PBEKeySpec keySpec, int type, int hash, int keySize, int ivSize) { PBEParametersGenerator generator = makePBEGenerator(type, hash); byte[] key; CipherParameters param; if (type == PKCS12) { key = PBEParametersGenerator.PKCS12PasswordToBytes(keySpec.getPassword()); } else { key = PBEParametersGenerator.PKCS5PasswordToBytes(keySpec.getPassword()); } generator.init(key, keySpec.getSalt(), keySpec.getIterationCount()); if (ivSize != 0) { param = generator.generateDerivedParameters(keySize, ivSize); } else { param = generator.generateDerivedParameters(keySize); } for (int i = 0; i != key.length; i++) { key[i] = 0; } return param; } /** * generate a PBE based key suitable for a MAC algorithm, the * key size is chosen according the MAC size, or the hashing algorithm, * whichever is greater. */ static CipherParameters makePBEMacParameters( PBEKeySpec keySpec, int type, int hash, int keySize) { PBEParametersGenerator generator = makePBEGenerator(type, hash); byte[] key; CipherParameters param; if (type == PKCS12) { key = PBEParametersGenerator.PKCS12PasswordToBytes(keySpec.getPassword()); } else { key = PBEParametersGenerator.PKCS5PasswordToBytes(keySpec.getPassword()); } generator.init(key, keySpec.getSalt(), keySpec.getIterationCount()); param = generator.generateDerivedMacParameters(keySize); for (int i = 0; i != key.length; i++) { key[i] = 0; } return param; } } }
package com.example.chimerider; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.chimerider.util.PathUtil; public class MapFragment extends Fragment { public MapView mapView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.map_fragment, container); } @Override public void onResume() { mapView = (MapView) getActivity().findViewById(R.id.mapview); mapView.setClickable(true); //mapView.setUseDataConnection(false); mapView.setMinZoomLevel(8); mapView.setMaxZoomLevel(15); mapView.setBuiltInZoomControls(true); mapView.getController().setZoom(12); mapView.getController().setCenter(new GeoPoint(-29.302567, 28.483135)); mapView.getOverlays().addAll(PathUtil.defaultRoads(getActivity())); //mapView.getOverlays().add(new ScaleBarOverlay(getActivity())); mapView.getOverlays().add(PathUtil.defaultVillages(getActivity(), mapView)); //caleBarOverlay scale = new ScaleBarOverlay(getActivity(), new ResourceProxyImpl(getActivity())); //scale.setScaleBarOffset(10, 10); //mapView.getOverlays().add(scale); //Animate this mapView.getOverlays().add(0, PathUtil.constructRoad1(getActivity())); mapView.getOverlays().add(mapView.getOverlays().size() - 5, PathUtil.rconstructRoad1(getActivity())); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mapView.getOverlays().add(0, PathUtil.constructRoad2(getActivity())); mapView.getOverlays().add(mapView.getOverlays().size() - 5, PathUtil.rconstructRoad2(getActivity())); mapView.invalidate(); } }, 2000); final Handler handler2 = new Handler(); handler2.postDelayed(new Runnable() { @Override public void run() { mapView.getOverlays().add(0, PathUtil.constructRoad3(getActivity())); mapView.getOverlays().add(mapView.getOverlays().size() - 5, PathUtil.rconstructRoad3(getActivity())); mapView.invalidate(); } }, 4000); //mapView.getOverlays().add( 0, PathUtil.constructRoad3(getActivity())); //mapView.getOverlays().add(mapView.getOverlays().size() - 5, PathUtil.rconstructRoad3(getActivity())); super.onResume(); } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); } }
package org.exist.xmldb.test; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import junit.framework.TestCase; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.exist.storage.DBBroker; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.base.Resource; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XMLResource; public class ResourceTest extends TestCase { private final static String URI = "xmldb:exist://" + DBBroker.ROOT_COLLECTION; private final static String DRIVER = "org.exist.xmldb.DatabaseImpl"; /** * Constructor for XMLDBTest. * @param arg0 */ public ResourceTest(String arg0) { super(arg0); } public void testReadNonExistingResource() { try { Collection testCollection = DatabaseManager.getCollection(URI + "/test"); assertNotNull(testCollection); Resource nonExistent = testCollection.getResource("12345.xml"); assertNull(nonExistent); } catch(Exception e) { System.out.println("testReadNonExistingResource(): Exception: " + e); fail(e.getMessage()); } } public void testReadResource() { try { Collection testCollection = DatabaseManager.getCollection(URI + "/test"); assertNotNull(testCollection); String[] resources = testCollection.listResources(); assertEquals(resources.length, testCollection.getResourceCount()); System.out.println("reading " + resources[0]); XMLResource doc = (XMLResource) testCollection.getResource(resources[0]); assertNotNull(doc); System.out.println("testing XMLResource.getContentAsSAX()"); StringWriter sout = new StringWriter(); OutputFormat format = new OutputFormat("xml", "ISO-8859-1", true); format.setLineWidth(60); XMLSerializer xmlout = new XMLSerializer(sout, format); doc.getContentAsSAX(xmlout); System.out.println(" System.out.println(sout.toString()); System.out.println(" } catch (Exception e) { System.out.println("testReadResource(): Exception: " + e); fail(e.getMessage()); } } public void testReadDOM() { try { Collection testCollection = DatabaseManager.getCollection(URI + "/test"); assertNotNull(testCollection); XMLResource doc = (XMLResource) testCollection.getResource("r_and_j.xml"); assertNotNull(doc); Node n = doc.getContentAsDOM(); Element elem=null; if ( n instanceof Element ) { elem = (Element)n; } else if ( n instanceof Document ) { elem = ((Document)n).getDocumentElement(); } assertNotNull(elem); assertEquals(elem.getNodeName(), "PLAY"); System.out.println("Root element: " + elem.getNodeName()); NodeList children = elem.getChildNodes(); Node node; for (int i = 0; i < children.getLength(); i++) { node = children.item(i); System.out.println("Child: " + node.getNodeName()); assertNotNull(node); node = node.getFirstChild(); while(node != null) { System.out.println("child: " + node.getNodeName()); node = node.getNextSibling(); } } } catch (XMLDBException e) { fail(e.getMessage()); } } public void testSetContentAsSAX() { try { Collection testCollection = DatabaseManager.getCollection(URI + "/test"); assertNotNull(testCollection); XMLResource doc = (XMLResource) testCollection.createResource("test.xml", "XMLResource"); String xml = "<test><title>Title</title>" + "<para>Paragraph1</para>" + "<para>Paragraph2</para>" + "</test>"; ContentHandler handler = doc.setContentAsSAX(); SAXParserFactory saxFactory = SAXParserFactory.newInstance(); saxFactory.setNamespaceAware(true); saxFactory.setValidating(false); SAXParser sax = saxFactory.newSAXParser(); XMLReader reader = sax.getXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); testCollection.storeResource(doc); } catch (Exception e) { fail(e.getMessage()); } } public void testSetContentAsDOM() { try { Collection testCollection = DatabaseManager.getCollection(URI + "/test"); assertNotNull(testCollection); XMLResource doc = (XMLResource) testCollection.createResource("dom.xml", "XMLResource"); String xml = "<test><title>Title</title>" + "<para>Paragraph1</para>" + "<para>Paragraph2</para>" + "</test>"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = docFactory.newDocumentBuilder(); Document dom = builder.parse(new InputSource(new StringReader(xml))); doc.setContentAsDOM(dom.getDocumentElement()); testCollection.storeResource(doc); } catch (Exception e) { fail(e.getMessage()); } } public void testAddRemove() { try { final String resourceID = "addremove.xml"; XMLResource created = addResource(resourceID, xmlForTest()); assertNotNull(created); // need to test documents xml structure XMLResource located = resourceForId(resourceID); assertNotNull(located); //assertEquals((String) created.getContent(), (String) located.getContent()); removeDocument(resourceID); XMLResource locatedAfterRemove = resourceForId(resourceID); assertNull(locatedAfterRemove); } catch (Exception e) { fail(e.getMessage()); } } private void removeDocument(String id) { try { XMLResource resource = resourceForId(id); if (null != resource) { Collection collection = null; try { collection = DatabaseManager.getCollection(URI + "/test"); collection.removeResource(resource); } finally { closeCollection(collection); } } } catch (Exception e) { fail(e.getMessage()); } } private XMLResource addResource(String id, String content) { Collection collection = null; XMLResource result = null; try { collection = DatabaseManager.getCollection(URI + "/test"); result = (XMLResource) collection.createResource(id, XMLResource.RESOURCE_TYPE); result.setContent(content); collection.storeResource(result); } catch (Exception e) { fail(e.getMessage()); } finally { closeCollection(collection); } return result; } private XMLResource resourceForId(String id) { Collection collection = null; XMLResource result = null; try { collection = DatabaseManager.getCollection(URI + "/test"); result = (XMLResource) collection.getResource(id); } catch (Exception e) { fail(e.getMessage()); } finally { closeCollection(collection); } return result; } private void closeCollection(Collection collection) { try { if (null != collection) { collection.close(); } } catch (Exception e) { fail(e.getMessage()); } } private String xmlForTest() { return "<test><title>Title</title>" + "<para>Paragraph1</para>" + "<para>Paragraph2</para>" + "</test>"; } protected void setUp() { try { // initialize driver Class cl = Class.forName(DRIVER); Database database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); } catch (Exception e) { fail(e.getMessage()); } } public static void main(String[] args) { junit.textui.TestRunner.run(ResourceTest.class); //junit.swingui.TestRunner.run(LexerTest.class); } }
package com.garrapeta.gameengine; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.garrapeta.gameengine.module.SoundModule; import com.garrapeta.gameengine.module.VibrationModule; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Paint.Align; import android.util.Log; /** * Clase que representa un universo de juego. * * @author GaRRaPeTa */ public abstract class GameWorld { /** Frames por segundo por defecto */ private static final float DEFAULT_FPS = 36f; /** Source trazas de log */ public static final String LOG_SRC_GAME_ENGINE = "game"; /** Source trazas de log */ public static final String LOG_SRC = LOG_SRC_GAME_ENGINE + ".world"; /** Nombre del thread del game loop */ public static final String LOOP_THREAD_NAME = "gameLoop"; /** SurfaceView donde se renderiza el juego. */ public GameView mGameView; /** Viewport activo */ public Viewport mViewport; /** Hilo con el loop principal */ private Thread mGameLoopThread; /** Actores del juego */ public Vector<Actor<?>> mActors; private final List<GameMessage> mMessages; private final List<GameMessage> mMessagesAux; /** Frames por segundo que se intentan conseguir */ private float mFps; /** Milisegundos por frame (periodo) que se intentan conseguir */ private float mspf; /** FPS achieved in last frame */ private float mCurrentFps; /** If the game loop is running */ private boolean mRunning = false; /** If the game loop is pause */ private boolean mPaused = false; /** Paint usado para info de debug */ Paint mDebugPaint; /** Ms que el mundo del juego a avanzado */ private long mCurrentGameMillis; /** Si pintar la info de FPS, etc **/ private boolean drawDebugInfo = false; /** Bitmap manager user by the world */ private BitmapManager mBitmapManager; /** Sound manager user by the world */ private SoundModule mSoundModule; /** Vibrator manager user by the world */ private VibrationModule mVibrationModule; private final ThreadPoolExecutor mAsyncMessagesExecutor; // Constructor /** * Constructor * * @param view * @param context * @param soundLevel * @param vibratorLevel */ public GameWorld(GameView view, Context context, short soundLevel, short vibratorLevel) { mViewport = new Viewport(this, context.getResources().getDisplayMetrics()); mCurrentGameMillis = 0; mActors = new Vector<Actor<?>>(); mMessages = new ArrayList<GameMessage>(); mMessagesAux = new ArrayList<GameMessage>(); setFPS(DEFAULT_FPS); mDebugPaint = new Paint(); mDebugPaint.setColor(Color.RED); mGameLoopThread = new Thread(new GameLoopRunnable(), LOOP_THREAD_NAME); mAsyncMessagesExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); mBitmapManager = new BitmapManager(); mSoundModule = new SoundModule(context, soundLevel); mVibrationModule = new VibrationModule(context, vibratorLevel); mGameView = view; view.setGameWorld(this); } // Setters /** * @return the BitmapManager */ public final BitmapManager getBitmapManager() { return mBitmapManager; } /** * @return the SoundManager */ public final SoundModule getSoundManager() { return mSoundModule; } /** * @return the VibratorManager */ public final VibrationModule getVibratorManager() { return mVibrationModule; } /** * @param fPS * the fPS to set */ public void setFPS(float fps) { this.mFps = fps; mspf = 1000 / fps; } /** * @return the fPS */ public float getFPS() { return mFps; } /** * @return the mspf */ public float getMspf() { return mspf; } /** * @return los ms que el del juego ha avanzado */ public long currentGameMillis() { return mCurrentGameMillis; } /** * @return the printDebugInfo */ public boolean isDrawDebugInfo() { return drawDebugInfo; } /** * @param printDebugInfo * the printDebugInfo to set */ public void setDrawDebugInfo(boolean printDebugInfo) { this.drawDebugInfo = printDebugInfo; } // vida /** * Starts running the game loop */ public void start() { Log.i(LOG_SRC, "Start running..."); mRunning = true; if (!mGameLoopThread.isAlive()) { mGameLoopThread.start(); } } /** * Stops running the game loop. This method blocks until the game loop is * finished. */ public final void finish() { Log.i(LOG_SRC, "Stop running..."); mRunning = false; // Interrupt the thread, in case it was paused mGameLoopThread.interrupt(); // synchronized (mGameLoopThread) { // if (mGameLoopThread.isAlive()) { // try { // mGameLoopThread.wait(); // } catch (InterruptedException ie) {} } /** * If the game loop is running */ public final boolean isRunning() { return mRunning; } /** * Pauses the game loop */ public final void pause() { Log.i(LOG_SRC, "Pausing..."); synchronized (mGameLoopThread) { mPaused = true; } } /** * Resumes the game loop */ public final void resume() { Log.i(LOG_SRC, "Resuming..."); synchronized (mGameLoopThread) { mPaused = false; mGameLoopThread.notify(); } } /** * Notified when the game is paused. */ private final void onPaused() { // TODO: not only pause, but release the resources of the soundManager getSoundManager().pauseAll(); } /** * Notified when the game is resumed. */ private final void onResumed() { getSoundManager().resumeAll(); } /** * If the game loop is paused */ public final boolean isPaused() { return mPaused; } // juego public void post(GameMessage message) { post(message, 0); } public void post(GameMessage message, float delay) { if (mRunning) { message.setDelay(delay); message.onPosted(this); } } void executeAsynchronously(Runnable runnable) { mAsyncMessagesExecutor.execute(runnable); } void add(GameMessage message) { synchronized (mMessages) { int index = 0; for (GameMessage aux : mMessages) { if (aux.getPriority() > message.getPriority()) { break; } index++; } mMessages.add(index, message); } } private void processMessages(float lastFrameLength) { // collect the ones that are ready synchronized (mMessages) { int index = 0; while (index < mMessages.size()) { final GameMessage message = mMessages.get(index); if (message.isReadyToBeDispatched(lastFrameLength)) { mMessagesAux.add(message); mMessages.remove(message); } else { index++; } } } // process the ones that are ready if (!mMessagesAux.isEmpty()) { for (GameMessage message : mMessagesAux) { message.doInGameLoop(this); } mMessagesAux.clear(); } } public final void addActor(final Actor<?> actor) { Log.d(LOG_SRC, "GameWorld.addActor(" + actor + "). Thread: " + Thread.currentThread().getName()); actor.assertInnited(); // TODO: let adding an actor in same frame? // if user catches MotionEvent, post a message to handle it, and it // there post the adition of // one actor, one cycle is lost post(new SyncGameMessage(GameMessage.MESSAGE_PRIORITY_MAX) { @Override public void doInGameLoop(GameWorld world) { int length = mActors.size(); int index = length; while (index > 0) { Actor<?> aux = mActors.get(index - 1); if (aux.getZIndex() <= actor.getZIndex()) { break; } index } mActors.add(index, actor); onActorAdded(actor); actor.doOnAddedToWorld(); } }); } public void onActorAdded(Actor<?> actor) { } public final void removeActor(final Actor<?> actor) { Log.d(LOG_SRC, "GameWorld.removeActor(" + actor + "). Thread: " + Thread.currentThread().getName()); post(new SyncGameMessage(GameMessage.MESSAGE_PRIORITY_MAX) { @Override public void doInGameLoop(GameWorld world) { if (mActors.contains(actor)) { onActorRemoved(actor); actor.doOnRemovedFromWorld(); mActors.remove(actor); } } }); } public void onActorRemoved(Actor<?> actor) { } /** * Remove all the actors * * @param actor */ // TODO message for this? public void removeAllActors() { for (Actor<?>actor : mActors) { removeActor(actor); } } /** * Cdigo ejecutado para procesar la lgica del juego en cada frame * * @param lastFrameLength * tiempo que dur el frame anterior, en ms */ public boolean processFrame(float lastFrameLength) { return false; } protected void loadResources() { } /** * Called from the GameLoop when this has been created */ protected void onBeforeRunning() { } // pintado final void doDrawWorld(Canvas canvas) { Log.v(LOG_SRC, "Drawing frame"); // pintado del mundo drawWorld(canvas); // pintado de debug if (drawDebugInfo) { drawDebugInfo(canvas, mDebugPaint); } } /** * Cdigo ejecutado para pintar el mundo en cada frame * * @param canvas */ public final void drawWorld(Canvas canvas) { drawBackground(canvas); drawActors(canvas); } /** * Pinta el background * * @param canvas */ protected void drawBackground(Canvas canvas) { canvas.drawColor(Color.BLACK); mViewport.drawBoundaries(canvas, mDebugPaint); } protected void drawActors(Canvas canvas) { int l = mActors.size(); for (int i = 0; i < l; i++) { Actor<?> actor = mActors.elementAt(i); actor.draw(canvas); } } /** * Pinta informacin de debug * * @param canvas * @param debugPaint */ private final void drawDebugInfo(Canvas canvas, Paint debugPaint) { // se pintan los FPS actuales debugPaint.setTextAlign(Align.RIGHT); canvas.drawText(getDebugString(), mGameView.getWidth(), mGameView.getHeight() - 20, debugPaint); } protected String getDebugString() { return (int) mCurrentFps + " FPS"; } /** * Stops the game loop and disposes the world. This method does not block * until the world is disposed. */ protected void dispose() { Log.i(LOG_SRC, "GameWorld.dispose()"); synchronized (this) { mAsyncMessagesExecutor.shutdownNow(); } mViewport.dispose(); for (Actor<?> actor : mActors) { actor.dispose(); } mActors.clear(); mMessages.clear(); mMessagesAux.clear(); mBitmapManager.releaseAll(); mSoundModule.release(); mVibrationModule.release(); } final void gameViewSizeChanged(GameView gameView, int width, int height) { Log.i(LOG_SRC, "surfaceChanged (" + width + ", " + height + ")"); onGameViewSizeChanged(width, height); mViewport.gameViewSizeChanged(gameView, width, height); } /** * Invoked when the size of game view changes * * @param width, in pixels * @param height, in pixels */ public abstract void onGameViewSizeChanged(int width, int height); /** * Invoked when the size of the viewport changes * @param worldBoundaries */ public abstract void onGameWorldSizeChanged(RectF worldBoundaries); void doProcessFrame(float lastFrameLength) { processMessages(lastFrameLength); if (!processFrame(lastFrameLength)) { // TODO: do this with iterator int size = mActors.size(); for (int i = 0; i < size; i++) { mActors.get(i).processFrame(mspf); } } } void checkExecutedInGameLoopThread() { if (Thread.currentThread() != mGameLoopThread) { throw new IllegalStateException("This operation needs to be executed in the game loop thread"); } } /** * Method that can be overriden to receive errors that can happen in the * processing of the games * </p> * Remember to dispose the world after receiving this event. * * @param Throwable error */ public void onError(Throwable error) { } /** * Runnable del GameLoop * * @author GaRRaPeTa */ class GameLoopRunnable implements Runnable { @Override public void run() { try { Log.i(LOG_SRC, "Game loop thread started. Thread: " + Thread.currentThread().getName()); float lastFrameLength = 0; loadResources(); onBeforeRunning(); while (mRunning) { long begin = System.currentTimeMillis(); doProcessFrame(lastFrameLength); mGameView.draw(); long end = System.currentTimeMillis(); long elapsed = end - begin; long diff = (long) (mspf - elapsed); if (diff > 0) { try { Thread.sleep(diff); } catch (InterruptedException e) { e.printStackTrace(); } } lastFrameLength = System.currentTimeMillis() - begin; mCurrentGameMillis += lastFrameLength; mCurrentFps = 1000 / lastFrameLength; Log.v(LOG_SRC, "Game loop frame. Desired FPS: " + mFps + " Actual: " + mCurrentFps); Thread.yield(); synchronized (mGameLoopThread) { if (mPaused) { Log.d(LOG_SRC, "Game loop paused."); onPaused(); try { mGameLoopThread.wait(); Log.v(LOG_SRC, "Game loop resumed."); onResumed(); } catch (InterruptedException e) { } } } } dispose(); Log.i(LOG_SRC, "Game loop thread ended"); } catch (Throwable t) { Log.e(LOG_SRC, "Error happenend in the game loop", t); onError(t); } } } }
package org.helioviewer.jhv.camera; import org.helioviewer.jhv.astronomy.Position; import org.helioviewer.jhv.astronomy.Sun; import org.helioviewer.jhv.camera.viewpoint.UpdateViewpoint; import org.helioviewer.jhv.display.Display; import org.helioviewer.jhv.layers.Movie; import org.helioviewer.jhv.layers.MovieDisplay; import org.helioviewer.jhv.math.Mat4f; import org.helioviewer.jhv.math.MathUtils; import org.helioviewer.jhv.math.Quat; import org.helioviewer.jhv.math.Transform; import org.helioviewer.jhv.math.Vec2; import org.helioviewer.jhv.opengl.GLSLShape; import org.helioviewer.jhv.time.JHVTime; import org.json.JSONArray; import org.json.JSONObject; import com.jogamp.opengl.GL2; public class Camera { public static final double ZOOM_MULTIPLIER_WHEEL = 2.; public static final double ZOOM_MULTIPLIER_BUTTON = 2.; public static final double INITFOV = 1. * Math.PI / 180.; private static final double MIN_FOV = INITFOV / 60; private static final double MAX_FOV = INITFOV * 30; private double fov = INITFOV; private Quat rotation = Quat.ZERO; private final Vec2 currentTranslation = new Vec2(0, 0); private Quat currentDragRotation = Quat.ZERO; private double cameraWidth = 1; private boolean tracking; private Position viewpoint = Sun.StartEarth; private UpdateViewpoint updateViewpoint; private static final float clipNarrow = (float) (32 * Sun.Radius); // bit more than LASCO C3 private static final float clipWide = (float) (50 * Sun.MeanEarthDistance); // bit further than Pluto private final float[] invProj = new float[16]; public Camera(UpdateViewpoint _updateViewpoint) { updateViewpoint = _updateViewpoint; } public static boolean useWideProjection(double distance) { return distance > 100 * Sun.MeanEarthDistance; } public void projectionOrtho2D(double aspect) { Transform.setOrthoSymmetricProjection((float) (cameraWidth * aspect), (float) cameraWidth, -1, 1); Transform.setTranslateView((float) currentTranslation.x, (float) currentTranslation.y, 0); Transform.cacheMVP(); } public void projectionOrtho(double aspect, GL2 gl, GLSLShape blackCircle) { Transform.setOrthoSymmetricProjection((float) (cameraWidth * aspect), (float) cameraWidth, -clipNarrow, clipNarrow); Transform.setTranslateView((float) currentTranslation.x, (float) currentTranslation.y, 0); Transform.cacheMVP(); blackCircle.renderShape(gl, GL2.GL_TRIANGLE_STRIP); Transform.rotateView(rotation); Transform.cacheMVP(); } public float[] getTransformationInverse(double aspect) { Mat4f.orthoSymmetricInverse(invProj, (float) (cameraWidth * aspect), (float) cameraWidth, -1, 1); Mat4f.translate(invProj, -(float) currentTranslation.x, -(float) currentTranslation.y, 0); return invProj; } public void projectionOrthoWide(double aspect) { Transform.setOrthoSymmetricProjection((float) (cameraWidth * aspect), (float) cameraWidth, -clipWide, clipWide); } private void updateCamera(JHVTime time) { Position v = updateViewpoint.update(time); viewpoint = Display.mode == Display.DisplayMode.Orthographic ? v : new Position(time, Sun.MeanEarthDistance, v.lon, v.lat); updateRotation(); updateWidth(); } private void updateRotation() { rotation = Quat.rotate(currentDragRotation, viewpoint.toQuat()); } private void updateWidth() { cameraWidth = 2 * viewpoint.distance * Math.tan(0.5 * fov); } public void refresh() { updateCamera(Movie.getTime()); MovieDisplay.render(1); } public void reset() { currentTranslation.x = 0; currentTranslation.y = 0; currentDragRotation = Quat.ZERO; updateCamera(Movie.getTime()); CameraHelper.zoomToFit(this); MovieDisplay.render(1); } public Position getViewpoint() { return viewpoint; } public UpdateViewpoint getUpdateViewpoint() { return updateViewpoint; } public void setViewpointUpdate(UpdateViewpoint _updateViewpoint) { updateViewpoint = _updateViewpoint; reset(); } public Vec2 getCurrentTranslation() { return currentTranslation; } public void setCurrentTranslation(double x, double y) { currentTranslation.x = x; currentTranslation.y = y; } public Quat getCurrentDragRotation() { return currentDragRotation; } void rotateCurrentDragRotation(Quat _currentDragRotation) { currentDragRotation = Quat.rotate(currentDragRotation, _currentDragRotation); updateRotation(); } public void setFOV(double _fov) { fov = MathUtils.clip(_fov, MIN_FOV, MAX_FOV); updateWidth(); } public void setTrackingMode(boolean _tracking) { if (tracking != _tracking) { tracking = _tracking; refresh(); } } public boolean getTrackingMode() { return tracking; } public double getCameraWidth() { return cameraWidth; } public void zoom(double wr) { setFOV(fov * (1 + 0.015 * wr)); } public void timeChanged(JHVTime date) { if (!tracking) { updateCamera(date); } } public JSONObject toJson() { JSONObject jo = new JSONObject(); jo.put("dragRotation", currentDragRotation.toJson()); jo.put("translationX", currentTranslation.x); jo.put("translationY", currentTranslation.y); jo.put("fov", fov); return jo; } public void fromJson(JSONObject jo) { JSONArray ja = jo.optJSONArray("dragRotation"); if (ja != null) currentDragRotation = Quat.fromJson(ja); currentTranslation.x = jo.optDouble("translationX", currentTranslation.x); currentTranslation.y = jo.optDouble("translationY", currentTranslation.y); fov = jo.optDouble("fov", fov); } }
package com.humbughq.mobile; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.ArrayList; import org.apache.http.client.HttpResponseException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import com.j256.ormlite.dao.RuntimeExceptionDao; public class AsyncGetEvents extends Thread { HumbugActivity activity; ZulipApp app; Handler onRegisterHandler; Handler onEventsHandler; HTTPRequest request; MessageRange currentRange; AsyncGetEvents that = this; int failures = 0; boolean registeredOrGotEventsThisRun; public AsyncGetEvents(HumbugActivity humbugActivity) { super(); app = humbugActivity.app; activity = humbugActivity; request = new HTTPRequest(app); } public void start() { registeredOrGotEventsThisRun = false; onRegisterHandler = new Handler() { public void handleMessage(android.os.Message msg) { that.onRegister((JSONObject) msg.obj); } }; onEventsHandler = new Handler() { public void handleMessage(android.os.Message msg) { JSONArray events; try { events = ((JSONObject) msg.obj).getJSONArray("events"); that.onEvents(events); } catch (JSONException e) { ZLog.logException(e); } } }; super.start(); } public void abort() { // TODO: does this have race conditions? (if the thread is not in a // request when called) Log.i("asyncGetEvents", "Interrupting thread"); request.abort(); } private void backoff(Exception e) { if (e != null) { ZLog.logException(e); } failures += 1; long backoff = (long) (Math.exp(failures / 2.0) * 1000); Log.e("asyncGetEvents", "Failure " + failures + ", sleeping for " + backoff); SystemClock.sleep(backoff); } private void register() throws JSONException, IOException { request.setProperty("apply_markdown", "false"); JSONObject response = new JSONObject(request.execute("POST", "v1/register")); registeredOrGotEventsThisRun = true; app.setEventQueueId(response.getString("queue_id")); app.setLastEventId(response.getInt("last_event_id")); onRegisterHandler.obtainMessage(0, response).sendToTarget(); } public void run() { try { while (true) { try { request.clearProperties(); if (app.getEventQueueId() == null) { register(); } request.setProperty("queue_id", app.getEventQueueId()); request.setProperty("last_event_id", "" + app.getLastEventId()); if (registeredOrGotEventsThisRun == false) { request.setProperty("dont_block", "true"); } JSONObject response = new JSONObject(request.execute("GET", "v1/events")); JSONArray events = response.getJSONArray("events"); if (events.length() > 0) { JSONObject lastEvent = events.getJSONObject(events .length() - 1); app.setLastEventId(lastEvent.getInt("id")); onEventsHandler.obtainMessage(0, response) .sendToTarget(); failures = 0; } if (registeredOrGotEventsThisRun == false) { registeredOrGotEventsThisRun = true; activity.runOnUiThread(new Runnable() { @Override public void run() { activity.onReadyToDisplay(false); } }); } } catch (HttpResponseException e) { if (e.getStatusCode() == 400) { String msg = e.getMessage(); if (msg.contains("Bad event queue id") || msg.contains("too old")) { // Queue dead. Register again. Log.w("asyncGetEvents", "Queue dead"); app.setEventQueueId(null); continue; } } backoff(e); } catch (SocketTimeoutException e) { e.printStackTrace(); // Retry without backoff, since it's already been a while } catch (IOException e) { if (request.aborting) { Log.i("asyncGetEvents", "Thread aborted"); return; } else { backoff(e); } } catch (JSONException e) { backoff(e); } } } catch (Exception e) { ZLog.logException(e); } } protected void onRegister(JSONObject response) { try { app.setPointer(response.getInt("pointer")); app.setMaxMessageId(response.getInt("max_message_id")); // Get subscriptions JSONArray subscriptions = response.getJSONArray("subscriptions"); RuntimeExceptionDao<Stream, Object> streamDao = this.app .getDao(Stream.class); Log.i("stream", "" + subscriptions.length() + " streams"); for (int i = 0; i < subscriptions.length(); i++) { Stream stream = Stream.getFromJSON(app, subscriptions.getJSONObject(i)); streamDao.createOrUpdate(stream); } that.activity.streamsAdapter.refresh(); // Get people JSONArray people = response.getJSONArray("realm_users"); RuntimeExceptionDao<Person, Object> personDao = this.app .getDao(Person.class); for (int i = 0; i < people.length(); i++) { Person person = Person .getFromJSON(app, people.getJSONObject(i)); personDao.createOrUpdate(person); } that.activity.peopleAdapter.refresh(); that.activity.onReadyToDisplay(true); } catch (JSONException e) { ZLog.logException(e); } } protected void onEvents(JSONArray events) { try { ArrayList<Message> messages = new ArrayList<Message>(); RuntimeExceptionDao<Message, Object> messageDao = this.app .getDao(Message.class); for (int i = 0; i < events.length(); i++) { JSONObject event = events.getJSONObject(i); Log.i("Event:", event.toString()); String type = event.getString("type"); if (type.equals("message")) { Message message = new Message(this.app, event.getJSONObject("message")); messages.add(message); messageDao.createOrUpdate(message); } else if (type.equals("pointer")) { // Keep our pointer synced with global pointer app.setPointer(event.getInt("pointer")); } } if (messages.size() > 0) { onMessages(messages); } } catch (JSONException e) { ZLog.logException(e); } } protected void onMessages(ArrayList<Message> messages) { int lastMessageId = messages.get(messages.size() - 1).getID(); synchronized (app.updateRangeLock) { RuntimeExceptionDao<MessageRange, Integer> rangeDao = app .getDao(MessageRange.class); currentRange = MessageRange.getRangeContaining( app.getMaxMessageId(), rangeDao); if (currentRange == null) { currentRange = new MessageRange(app.getMaxMessageId(), app.getMaxMessageId()); } if (currentRange.high <= lastMessageId) { currentRange.high = lastMessageId; rangeDao.createOrUpdate(currentRange); } } app.setMaxMessageId(lastMessageId); this.activity.onNewMessages(messages.toArray(new Message[0])); } }
package com.humbughq.mobile; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.ClipData; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.PorterDuff.Mode; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SimpleCursorAdapter; import android.util.Log; import android.util.SparseArray; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.humbughq.mobile.HumbugAsyncPushTask.AsyncTaskCompleteListener; import com.j256.ormlite.android.AndroidDatabaseResults; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.SelectArg; import com.j256.ormlite.stmt.Where; public class HumbugActivity extends Activity { ZulipApp app; ListView listView; SparseArray<Message> messageIndex; MessageAdapter adapter; MessageAdapter narrowedAdapter; public enum LoadPosition { ABOVE, BELOW, NEW, INITIAL, } int firstMessageId = -1; int lastMessageId = -1; int lastAvailableMessageId = -1; boolean loadingMessages = true; boolean suspended = false; boolean logged_in = false; String api_key; View bottom_list_spacer; HumbugActivity that = this; // self-ref SharedPreferences settings; String client_id; private DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; protected int mIDSelected; private Menu menu; public Person you; private View composeView; protected HashMap<String, Bitmap> gravatars = new HashMap<String, Bitmap>(); private AsyncGetEvents event_poll; private ListView narrowedListView; private OnItemClickListener tileClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { Message m = (Message) parent.getItemAtPosition(position); openCompose(m.getType(), m.getStream(), m.getSubject(), m.getReplyTo(app)); } catch (IndexOutOfBoundsException e) { // We can ignore this because its probably before the data // has been fetched. } } }; private SimpleCursorAdapter.ViewBinder streamBinder = new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View arg0, Cursor arg1, int arg2) { switch (arg0.getId()) { case R.id.name: TextView name = (TextView) arg0; name.setText(arg1.getString(arg2)); return true; case R.id.stream_dot: // Set the color of the (currently white) dot arg0.setVisibility(View.VISIBLE); arg0.getBackground().setColorFilter(arg1.getInt(arg2), Mode.MULTIPLY); return true; } return false; } }; private NarrowFilter narrowFilter; protected RefreshableCursorAdapter streamsAdapter; protected RefreshableCursorAdapter peopleAdapter; /** Called when the activity is first created. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (ZulipApp) getApplicationContext(); settings = app.settings; if (!app.isLoggedIn()) { openLogin(); return; } // If we're creating a new Activity, but the app state is still around, // re-register anyway to update the view. Won't be necessary once we // pull messages from the DB. app.clearConnectionState(); this.onPrepareOptionsMenu(menu); this.logged_in = true; messageIndex = new SparseArray<Message>(); setContentView(R.layout.main); listView = (ListView) findViewById(R.id.listview); narrowedListView = (ListView) findViewById(R.id.narrowed_listview); this.bottom_list_spacer = new ImageView(this); this.size_bottom_spacer(); listView.addFooterView(this.bottom_list_spacer); narrowedListView.addFooterView(this.bottom_list_spacer); listView.setEmptyView(findViewById(R.id.listFYI)); adapter = new MessageAdapter(this, new ArrayList<Message>()); listView.setAdapter(adapter); // We want blue highlights when you longpress listView.setDrawSelectorOnTop(true); registerForContextMenu(listView); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { final int near = 6; if (!loadingMessages && firstMessageId > 0 && lastMessageId > 0) { if (firstVisibleItem + visibleItemCount > totalItemCount - near) { Log.i("scroll", "at bottom " + loadingMessages + " " + listHasMostRecent() + " " + lastMessageId + " " + lastAvailableMessageId); // At the bottom of the list if (!listHasMostRecent()) { loadMoreMessages(LoadPosition.BELOW); } } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { try { // Scrolling messages isn't meaningful unless we have // messages to scroll. int mID = ((Message) view.getItemAtPosition(view .getFirstVisiblePosition())).getID(); if (mIDSelected != mID) { Log.i("scrolling", "Now at " + mID); (new AsyncPointerUpdate(that)).execute(mID); mIDSelected = mID; } } catch (NullPointerException e) { Log.w("scrolling", "Could not find a location to scroll to!"); } } }); listView.setOnItemClickListener(tileClickListener); listView.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { try { int mID = (Integer) view.getTag(R.id.messageID); if (mIDSelected != mID) { Log.i("keyboard", "Now at " + mID); (new AsyncPointerUpdate(that)).execute(mID); mIDSelected = mID; } } catch (NullPointerException e) { Log.e("selected", "None, because we couldn't find the tag."); } } @Override public void onNothingSelected(AdapterView<?> parent) { // pass } }); this.startRequests(); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.streams_open, R.string.streams_close) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { // pass } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { // pass } }; // Set the drawer toggle as the DrawerListener drawerLayout.setDrawerListener(drawerToggle); ListView streamsDrawer = (ListView) findViewById(R.id.streams_drawer); ListView peopleDrawer = (ListView) findViewById(R.id.people_drawer); Callable<Cursor> streamsGenerator = new Callable<Cursor>() { @Override public Cursor call() throws Exception { return ((AndroidDatabaseResults) app.getDao(Stream.class) .queryBuilder().selectRaw("rowid _id", "*") .orderByRaw(Stream.NAME_FIELD + " COLLATE NOCASE") .queryRaw().closeableIterator().getRawResults()) .getRawCursor(); } }; Callable<Cursor> peopleGenerator = new Callable<Cursor>() { @Override public Cursor call() throws Exception { // TODO Auto-generated method stub return ((AndroidDatabaseResults) app.getDao(Person.class) .queryBuilder().selectRaw("rowid _id", "*") .orderByRaw(Person.NAME_FIELD + " COLLATE NOCASE") .where().eq(Person.ISBOT_FIELD, false).queryRaw() .closeableIterator().getRawResults()).getRawCursor(); } }; try { this.streamsAdapter = new RefreshableCursorAdapter( this.getApplicationContext(), R.layout.stream_tile, streamsGenerator.call(), streamsGenerator, new String[] { Stream.NAME_FIELD, Stream.COLOR_FIELD }, new int[] { R.id.name, R.id.stream_dot }, 0); streamsAdapter.setViewBinder(streamBinder); streamsDrawer.setAdapter(streamsAdapter); this.peopleAdapter = new RefreshableCursorAdapter( this.getApplicationContext(), R.layout.stream_tile, peopleGenerator.call(), peopleGenerator, new String[] { Person.NAME_FIELD }, new int[] { R.id.name }, 0); peopleDrawer.setAdapter(peopleAdapter); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } streamsDrawer.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO: is there a way to get the Stream from the adapter // without re-querying it? narrow(Stream.getById(app, (int) id)); } }); peopleDrawer.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { narrow_pm_with(Person.getById(app, (int) id)); } }); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } protected void narrow(final Stream stream) { Dao<Message, Integer> messageDao = app.getDao(Message.class); try { final SelectArg streamArg = new SelectArg(); NarrowFilter streamNarrow = new NarrowFilter() { @Override public Where<Message, Object> modWhere( Where<Message, Object> where) throws SQLException { where.eq(Message.STREAM_FIELD, streamArg); streamArg.setValue(stream); return where; } @Override public boolean matches(Message msg) { return msg.getType() == MessageType.STREAM_MESSAGE && msg.getStream().equals(stream); } @Override public String getTitle() { return stream.getName(); } @Override public String getSubtitle() { return null; } @Override public Stream getComposeStream() { return stream; } @Override public String getComposePMRecipient() { return null; } }; doNarrow(streamNarrow); } catch (SQLException e) { e.printStackTrace(); } } protected void narrow_pm_with(final Person person) { try { final String recipientString = Message.recipientList(new Person[] { person, app.you }); NarrowFilter pmNarrow = new NarrowFilter() { @Override public Where<Message, Object> modWhere( Where<Message, Object> where) throws SQLException { final SelectArg recipientsArg = new SelectArg( recipientString); where.eq(Message.RECIPIENTS_FIELD, recipientsArg); return where; } @Override public boolean matches(Message msg) { if (msg.getType() == MessageType.PRIVATE_MESSAGE) { return msg.getRawRecipients().equals(recipientString); } return false; } @Override public String getTitle() { return person.getName(); } @Override public String getSubtitle() { return null; } @Override public Stream getComposeStream() { return null; } @Override public String getComposePMRecipient() { return person.getEmail(); } }; doNarrow(pmNarrow); } catch (SQLException e) { e.printStackTrace(); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void doNarrow(NarrowFilter filter) throws SQLException { Where<Message, Object> filteredWhere = filter.modWhere(app .getDao(Message.class).queryBuilder().where()); List<Message> messages = filteredWhere.query(); this.narrowedAdapter = new MessageAdapter(this, messages); this.narrowedListView.setAdapter(this.narrowedAdapter); this.narrowFilter = filter; filteredWhere.and().le(Message.TIMESTAMP_FIELD, this.getMessageById(app.pointer).getTimestamp()); QueryBuilder<Message, Object> closestQuery = app.getDao(Message.class) .queryBuilder(); closestQuery.orderBy(Message.TIMESTAMP_FIELD, false).setWhere( filteredWhere); this.narrowedListView.setSelection(this.narrowedAdapter .getPosition(closestQuery.queryForFirst())); this.listView.setVisibility(View.GONE); this.narrowedListView.setVisibility(View.VISIBLE); String title = filter.getTitle(); if (title != null) { getActionBar().setTitle(title); } getActionBar().setSubtitle(filter.getSubtitle()); this.narrowedListView.setOnItemClickListener(tileClickListener); this.drawerToggle.setDrawerIndicatorEnabled(false); this.drawerLayout.closeDrawers(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void doUnnarrow() { this.narrowedAdapter.clear(); this.narrowedListView.setVisibility(View.GONE); this.listView.setVisibility(View.VISIBLE); this.drawerToggle.setDrawerIndicatorEnabled(true); getActionBar().setTitle("Zulip"); getActionBar().setSubtitle(null); this.narrowFilter = null; } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } public boolean onPrepareOptionsMenu(Menu menu) { /* * We want to show a menu only when we're logged in, so this function is * called by both Android and our own app when we encounter state * changes where we might want to update the menu. */ if (menu == null) { // We were called by a function before the menu had been // initialised, so we should bail. return false; } this.menu = menu; menu.clear(); if (this.logged_in) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options, menu); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Pass the event to ActionBarDrawerToggle, if it returns // true, then it has handled the app icon touch event if (drawerToggle.onOptionsItemSelected(item)) { return true; } // Handle item selection switch (item.getItemId()) { case android.R.id.home: doUnnarrow(); break; case R.id.compose_stream: Stream stream = null; if (narrowFilter != null) { stream = narrowFilter.getComposeStream(); } openCompose(MessageType.STREAM_MESSAGE, stream, null, null); break; case R.id.compose_pm: String recipient = null; if (narrowFilter != null) { recipient = narrowFilter.getComposePMRecipient(); } openCompose(MessageType.PRIVATE_MESSAGE, null, null, recipient); break; case R.id.refresh: Log.w("menu", "Refreshed manually by user. We shouldn't need this."); onRefresh(); ((RefreshableCursorAdapter) ((ListView) findViewById(R.id.streams_drawer)) .getAdapter()).refresh(); break; case R.id.logout: logout(); break; case R.id.legal: openLegal(); break; default: return super.onOptionsItemSelected(item); } return true; } /** * Switches the compose window's state to compose a personal message. */ protected void switchToPersonal() { EditText recipient = (EditText) composeView .findViewById(R.id.composeRecipient); EditText subject = (EditText) composeView .findViewById(R.id.composeSubject); subject.setVisibility(View.GONE); recipient.setGravity(Gravity.FILL_HORIZONTAL); recipient.setHint(R.string.pm_prompt); } /** * Switches the compose window's state to compose a stream message. */ protected void switchToStream() { EditText recipient = (EditText) composeView .findViewById(R.id.composeRecipient); EditText subject = (EditText) composeView .findViewById(R.id.composeSubject); subject.setVisibility(View.VISIBLE); recipient.setGravity(Gravity.NO_GRAVITY); recipient.setHint(R.string.stream); } protected void openCompose(MessageType type) { openCompose(type, null, null, null); } protected void openCompose(Stream stream, String topic) { openCompose(MessageType.STREAM_MESSAGE, stream, topic, null); } protected void openCompose(String pmRecipients) { openCompose(MessageType.PRIVATE_MESSAGE, null, null, pmRecipients); } private void openCompose(final MessageType type, Stream stream, String topic, String pmRecipients) { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = this.getLayoutInflater(); composeView = inflater.inflate(R.layout.compose, null); final EditText recipient = (EditText) composeView .findViewById(R.id.composeRecipient); final EditText subject = (EditText) composeView .findViewById(R.id.composeSubject); final EditText body = (EditText) composeView .findViewById(R.id.composeText); AlertDialog composeWindow = builder .setView(composeView) .setTitle("Compose") .setPositiveButton(R.string.send, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int id) { if (type == MessageType.STREAM_MESSAGE) { requireFilled(subject, "subject"); requireFilled(recipient, "recipient"); // stream } else if (type == MessageType.PRIVATE_MESSAGE) { requireFilled(recipient, "recipient"); } requireFilled(body, "message body"); Message msg = new Message(that.app); msg.setSender(that.you); if (type == MessageType.STREAM_MESSAGE) { msg.setType(MessageType.STREAM_MESSAGE); msg.setStream(new Stream(recipient .getText().toString())); msg.setSubject(subject.getText().toString()); } else if (type == MessageType.PRIVATE_MESSAGE) { msg.setType(MessageType.PRIVATE_MESSAGE); msg.setRecipient(recipient.getText() .toString().split(",")); } msg.setContent(body.getText().toString()); AsyncSend sender = new AsyncSend(that, msg); sender.execute(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int id) { d.dismiss(); } }).create(); if (type == MessageType.STREAM_MESSAGE) { this.switchToStream(); if (stream != null) { recipient.setText(stream.getName()); if (topic != null) { subject.setText(topic); body.requestFocus(); } else { subject.setText(""); subject.requestFocus(); } } else { recipient.setText(""); recipient.requestFocus(); } } else { this.switchToPersonal(); if (pmRecipients != null) { recipient.setText(pmRecipients); body.requestFocus(); } else { recipient.setText(""); recipient.requestFocus(); } } InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); composeWindow .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { // Hide physical keyboard if present. InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); } }); composeWindow.show(); } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void copyMessage(Message msg) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setPrimaryClip(ClipData.newPlainText("Zulip Message", msg.getContent())); } else { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(msg.getContent()); } } /** * Check if a field is nonempty and mark fields as invalid if they are. * * @param field * The field to check * @param fieldName * The human-readable name of the field * @return Whether the field correctly validated. */ protected boolean requireFilled(EditText field, String fieldName) { if (field.getText().toString().equals("")) { field.setError("You must specify a " + fieldName); field.requestFocus(); return false; } return true; } /** * Log the user out of the app, clearing our cache of their credentials. */ private void logout() { this.logged_in = false; app.logOut(); this.openLogin(); } /** * Switch to the login view. */ protected void openLogin() { Intent i = new Intent(this, LoginActivity.class); startActivity(i); finish(); } protected void openLegal() { Intent i = new Intent(this, LegalActivity.class); startActivityForResult(i, 0); } private void size_bottom_spacer() { @SuppressWarnings("deprecation") // needed for compat with API <13 int windowHeight = ((WindowManager) this .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay() .getHeight(); AbsListView.LayoutParams params = new AbsListView.LayoutParams(0, 0); params.height = windowHeight / 2; this.bottom_list_spacer.setLayoutParams(params); } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // our display has changed, lets recalculate the spacer this.size_bottom_spacer(); drawerToggle.onConfigurationChanged(newConfig); } protected void onPause() { super.onPause(); Log.i("status", "suspend"); this.suspended = true; if (event_poll != null) { event_poll.abort(); } } protected void onResume() { super.onResume(); Log.i("status", "resume"); this.suspended = false; startRequests(); } protected void onRefresh() { super.onResume(); if (event_poll != null) { event_poll.abort(); } app.clearConnectionState(); startRequests(); } protected void startRequests() { Log.i("zulip", "Starting requests"); if (event_poll != null) { event_poll.abort(); } loadingMessages = true; event_poll = new AsyncGetEvents(this); event_poll.start(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // Using menuInfo, determine which menu to show (stream or private) AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Message msg = messageIndex.get((int) info.id); if (msg == null) { return; } if (msg.getType().equals(MessageType.STREAM_MESSAGE)) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_stream, menu); } else if (msg.getPersonalReplyTo(app).length > 1) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_private, menu); } else { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_single_private, menu); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Message message = messageIndex.get((int) info.id); switch (item.getItemId()) { case R.id.reply_to_stream: openCompose(message.getStream(), message.getSubject()); return true; case R.id.reply_to_private: openCompose(message.getReplyTo(app)); return true; case R.id.reply_to_sender: openCompose(message.getSender().getEmail()); return true; case R.id.copy_message: copyMessage(message); return true; default: return super.onContextItemSelected(item); } } public void onRegister() { adapter.clear(); messageIndex.clear(); lastAvailableMessageId = app.max_message_id; firstMessageId = -1; lastMessageId = -1; AsyncGetOldMessages oldMessagesReq = new AsyncGetOldMessages(this); oldMessagesReq.execute(app.pointer, LoadPosition.INITIAL, 100, 100); oldMessagesReq.setCallback(new AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { that.selectMessage(that.getMessageById(app.pointer)); loadingMessages = false; } }); } public void onMessages(Message[] messages, LoadPosition pos) { Log.i("onMessages", "Adding " + messages.length + " messages at " + pos); if (pos == LoadPosition.NEW) { // listHasMostRecent check needs to occur before updating // lastAvailableMessageId boolean hasMostRecent = listHasMostRecent(); lastAvailableMessageId = messages[messages.length - 1].getID(); if (!hasMostRecent) { // If we don't have intermediate messages loaded, don't add new // messages -- they'll be loaded when we scroll down. Log.i("onMessage", "skipping new message " + messages[0].getID() + " " + lastAvailableMessageId); return; } } for (int i = 0; i < messages.length; i++) { Message message = messages[i]; if (this.messageIndex.get(message.getID()) != null) { // Already have this message. Log.i("onMessage", "Already have " + message.getID()); continue; } this.messageIndex.append(message.getID(), message); Stream stream = message.getStream(); if (stream == null || stream.getInHomeView()) { if (pos == LoadPosition.NEW || pos == LoadPosition.BELOW) { this.adapter.add(message); if (this.narrowFilter != null) { // For some reason calling adapter.add above shows the // main message list. Lets explicitly re-hide it here. this.listView.setVisibility(View.GONE); if (this.narrowFilter.matches(message)) { this.narrowedAdapter.add(message); } } } else if (pos == LoadPosition.ABOVE || pos == LoadPosition.INITIAL) { Log.i("onMessages", "Inserting at " + i); this.adapter.insert(message, i); } if (message.getID() > lastMessageId) { lastMessageId = message.getID(); } if (message.getID() < firstMessageId || firstMessageId == -1) { firstMessageId = message.getID(); } } } } public Boolean listHasMostRecent() { return lastMessageId == lastAvailableMessageId; } public void loadMoreMessages(LoadPosition pos) { int above = 0; int below = 0; int around; if (pos == LoadPosition.ABOVE) { above = 100; around = firstMessageId; } else if (pos == LoadPosition.BELOW) { below = 100; around = lastMessageId; } else { Log.e("loadMoreMessages", "Invalid position"); return; } Log.i("loadMoreMessages", "" + around + " " + pos + " " + above + " " + below); loadingMessages = true; AsyncGetOldMessages oldMessagesReq = new AsyncGetOldMessages(this); oldMessagesReq.execute(around, pos, above, below); oldMessagesReq.setCallback(new AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { loadingMessages = false; } }); } public void selectMessage(final Message message) { listView.post(new Runnable() { @Override public void run() { listView.setSelection(adapter.getPosition(message)); } }); } public Message getMessageById(int id) { return this.messageIndex.get(id); } }
/* * $Id: OpenUrlResolver.java,v 1.29 2012-03-28 21:05:31 pgust Exp $ */ package org.lockss.daemon; import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.lockss.app.LockssDaemon; import org.lockss.config.ConfigManager; import org.lockss.config.Tdb; import org.lockss.config.TdbAu; import org.lockss.config.TdbPublisher; import org.lockss.config.TdbTitle; import org.lockss.daemon.ConfigParamDescr.InvalidFormatException; import org.lockss.plugin.Plugin; import org.lockss.plugin.PluginManager; import org.lockss.plugin.PrintfConverter; import org.lockss.plugin.PrintfConverter.UrlListConverter; import org.lockss.util.ExternalizableMap; import org.lockss.util.IOUtil; import org.lockss.util.Logger; import org.lockss.util.MetadataUtil; import org.lockss.util.NumberUtil; import org.lockss.util.StringUtil; import org.lockss.util.TypedEntryMap; import org.lockss.util.UrlUtil; import org.lockss.util.urlconn.LockssUrlConnection; import org.lockss.util.urlconn.LockssUrlConnectionPool; /** * This class implements an OpenURL resolver that locates an article matching * properties corresponding to OpenURL keys. Both OpenURL 1.0 and the earlier * OpenURL 0.1 syntax are supported. Queries can be made by: * <ul> * <li>URL</li> * <li>DOI</li> * * <li>ISSN/volume/issue/page</li> * <li>ISSN/volume/issue/article-number</li> * <li>ISSN/volume/issue/author</li> * <li>ISSN/volume/issue/article-title</li> * <li>ISSN/date/page</li> * <li>ISSN/date/article-number</li> * <li>ISSN/date/author</li> * <li>ISSN/date/article-title</li> * * <li>journal-title/volume/issue/page</li> * <li>journal-title/volume/issue/article-number</li> * <li>journal-title/volume/issue/author</li> * <li>journal-title/volume/issue/article-title</li> * <li>journal-title/date/page</li> * <li>journal-title/date/article-number</li> * <li>journal-title/date/author</li> * <li>journal-title/date/article-title</li> * * <li>ISBN/page</li> * <li>ISBN/chapter-author</li> * <li>ISBN/chapter-title</li> * * <li>book-title/page</li> * <li>book-title/chapter-author</li> * <li>book-title/chapter-title</li> * * <li>book-publisher/book-title/page</li> * <li>book-publisher/book-title/chapter-author</li> * <li>book-publisher/book-title/chapter-title</li> * * <li>SICI</li> * <li>BICI</li> * </ul> * <p> * Note: the TDB of the current configuration is used to resolve journal or * if the entry is not in the metadata database, or if the query gives a * journal or book title but no ISSN or ISBN. If there are multiple entries * for the journal or book title, one of them is selected. OpenURL 1.0 allows * specifying a book publisher, so if both publisher and title are specified, * there is a good chance that the match will be unique. * * @author Philip Gust * @version 1.0 */ public class OpenUrlResolver { private static Logger log = Logger.getLogger("OpenUrlResolver"); /** the LOCKSS daemon */ private final LockssDaemon daemon; /** maximum redirects for looking up DOI url */ private static final int MAX_REDIRECTS = 10; private static final class FeatureEntry { final String auFeatureKey; final OpenUrlInfo.ResolvedTo resolvedTo; public FeatureEntry(String auFeatureKey, OpenUrlInfo.ResolvedTo resolvedTo) { this.auFeatureKey = auFeatureKey; this.resolvedTo = resolvedTo; } } /** * Keys to search for a matching journal feature. The order of the keys * is the order they will be tried, from article, to issue, to volume, * to title TOC. */ private static final FeatureEntry[] auJournalauFeatures = { // "au_feature_urls/au_abstract", new FeatureEntry("au_feature_urls/au_article",OpenUrlInfo.ResolvedTo.ARTICLE), new FeatureEntry("au_feature_urls/au_issue", OpenUrlInfo.ResolvedTo.ISSUE), new FeatureEntry("au_issue_url", OpenUrlInfo.ResolvedTo.ISSUE), new FeatureEntry("au_feature_urls/au_volume", OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry("au_volume_url", OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry("au_start_url", OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry("au_feature_urls/au_title", OpenUrlInfo.ResolvedTo.TITLE), new FeatureEntry("au_title_url", OpenUrlInfo.ResolvedTo.TITLE) }; /** * Keys to search for a matching book feature. The order of the keys is the * the order they will be tried, from chapter, to volume, to title TOC. */ private static final FeatureEntry[] auBookauFeatures = { new FeatureEntry("au_feature_urls/au_chapter", OpenUrlInfo.ResolvedTo.CHAPTER), new FeatureEntry("au_chapter_url", OpenUrlInfo.ResolvedTo.CHAPTER), new FeatureEntry("au_feature_urls/au_volume", OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry("au_volume_url", OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry("au_start_url", OpenUrlInfo.ResolvedTo.VOLUME), new FeatureEntry("au_feature_urls/au_title", OpenUrlInfo.ResolvedTo.TITLE), new FeatureEntry("au_title_url", OpenUrlInfo.ResolvedTo.TITLE), }; /** The name of the TDB au_feature key selector */ static final String AU_FEATURE_KEY = "au_feature_key"; // pre-defined OpenUrlInfo for no url public static final OpenUrlInfo noOpenUrlInfo = new OpenUrlInfo(null, OpenUrlInfo.ResolvedTo.NONE); /** * Information returned by OpenUrlResolver includes the resolvedUrl * and the resolvedTo enumeration. */ public static class OpenUrlInfo { static public enum ResolvedTo { PUBLISHER, TITLE, VOLUME, ISSUE, CHAPTER, ARTICLE, OTHER, NONE, }; public final String resolvedUrl; public final ResolvedTo resolvedTo; private OpenUrlInfo(String resolvedUrl, ResolvedTo resolvedTo) { this.resolvedUrl = resolvedUrl; this.resolvedTo = resolvedTo; } public static OpenUrlInfo newInstance( String resolvedUrl, ResolvedTo resolvedTo) { return ((resolvedTo == ResolvedTo.NONE) || (resolvedUrl == null)) ? OpenUrlResolver.noOpenUrlInfo : new OpenUrlInfo(resolvedUrl, resolvedTo); } public static OpenUrlInfo newInstance(String resolvedUrl) { return (resolvedUrl == null) ? noOpenUrlInfo : new OpenUrlInfo(resolvedUrl, OpenUrlInfo.ResolvedTo.OTHER); } } /** * Create a resolver for the specified metadata manager. * * @param daemon the LOCKSS daemon */ public OpenUrlResolver(LockssDaemon daemon) { if (daemon == null) { throw new IllegalArgumentException("LOCKSS daemon not specified"); } this.daemon = daemon; } /** * Get an parameter either without or with the "rft." prefix. * * @param params the parameters * @param key the key * @return the value or <code>null</code> if not present */ private String getRftParam(Map<String,String> params, String key) { String value = params.get(key); if (value == null) { value = params.get("rft." + key); } return value; } /** * Get date based on date, ssn (season), and quarter rft parameters. * * @param params the parameters * @return a normalized date string of the form YYYY{-MM{-DD}} * or YYYY-Qn for nth quarter, or YYYY-Sn for nth season for * n between 1 and 4. */ private String getRftDate(Map<String,String> params) { String ssn = getRftParam(params, "ssn"); // spring, summer, fall, winter String quarter = getRftParam(params, "quarter"); // 1, 2, 3, 4 String date = getRftParam(params, "date"); // YYYY{-MM{-DD}} // fill in month if only year specified if ((date != null) && (date.indexOf('-') < 0)) { if (quarter != null) { // fill in month based on quarter if (quarter.equals("1")) { date += "-Q1"; } else if (quarter.equals("2")) { date += "-Q2"; } else if (quarter.equals("3")) { date += "-Q3"; } else if (quarter.equals("4")) { date += "-Q4"; } else { log.warning("Invalid quarter: " + quarter); } } else if (ssn != null) { // fill in month based on season if (ssn.equalsIgnoreCase("spring")) { date += "-S1"; } else if (ssn.equalsIgnoreCase("summer")) { date += "-S2"; } else if (ssn.equalsIgnoreCase("fall")) { date += "-S3"; } else if (ssn.equalsIgnoreCase("winter")) { date += "-S4"; } log.warning("Invalid ssn: " + ssn); } } return date; } /** * Get start page base rft spage parameter or artnum if page not specified. * * @param params the parameters * @return a start page -- not necessarily numeric */ private String getRftStartPage(Map<String,String> params) { String spage = getRftParam(params, "spage"); if (spage == null) { spage = getRftParam(params, "artnum"); } return spage; } /** * Returns the TdbTitle corresponding to the specified OpenUrl params. * * @param params the OpenURL parameters * @return a TdbTitle or <code>null</code> if not found */ public TdbTitle resolveTdbTitleForOpenUrl(Map<String,String> params) { Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); if (tdb != null) { // get TdbTitle for ISBN String isbn = getRftParam(params, "isbn"); if (isbn != null) { Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); return tdbAus.isEmpty() ? null : tdbAus.iterator().next().getTdbTitle(); } // get TdbTitle for ISSN String issn = getRftParam(params, "issn"); if (issn != null) { return tdb.getTdbTitleByIssn(issn); } // get TdbTitle for BICI String bici = getRftParam(params, "bici"); if (bici != null) { int i = bici.indexOf('('); if (i > 0) { isbn = bici.substring(0,i); Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); return tdbAus.isEmpty() ? null : tdbAus.iterator().next().getTdbTitle(); } } // get TdbTitle for SICI String sici = getRftParam(params, "sici"); if (sici != null) { int i = sici.indexOf('('); if (i > 0) { issn = sici.substring(0,i); return tdb.getTdbTitleByIssn(issn); } } // get TdbTitle for journal pubisher and title String publisher = getRftParam(params, "publisher"); String title = getRftParam(params, "jtitle"); if (title == null) { title = getRftParam(params, "title"); } if (title != null) { Collection<TdbTitle> tdbTitles; if (publisher != null) { TdbPublisher tdbPublisher = tdb.getTdbPublisher(publisher); tdbTitles = (tdbPublisher == null) ? Collections.<TdbTitle>emptyList() :tdbPublisher.getTdbTitlesLikeName(title); } else { tdbTitles = tdb.getTdbTitlesByName(title); } return tdbTitles.isEmpty() ? null : tdbTitles.iterator().next(); } // get TdbTitle for book pubisher and title String btitle = getRftParam(params, "btitle"); if (btitle != null) { Collection<TdbAu> tdbAus; if (publisher != null) { TdbPublisher tdbPublisher = tdb.getTdbPublisher(publisher); tdbAus = (tdbPublisher == null) ? Collections.<TdbAu>emptyList() :tdbPublisher.getTdbAusLikeName(title); } else { tdbAus = tdb.getTdbAusByName(title); } return tdbAus.isEmpty() ? null : tdbAus.iterator().next().getTdbTitle(); } } return null; } /** * Resolve an OpenURL from a set of parameter keys and values. * * @param params the OpenURL parameters * @return a url or <code>null</code> if not found */ public OpenUrlInfo resolveOpenUrl(Map<String,String> params) { if (params.containsKey("rft_id")) { String rft_id = params.get("rft_id"); // handle rft_id that is an HTTP or HTTPS URL if (UrlUtil.isHttpUrl(rft_id)) { OpenUrlInfo resolved = resolveFromUrl(rft_id); if (resolved.resolvedUrl != null) { return resolved; } log.debug3("Failed to resolve from URL: " + rft_id); } else if (rft_id.startsWith("info:doi/")) { String doi = rft_id.substring("info:doi/".length()); OpenUrlInfo resolved = resolveFromDOI(doi); if (resolved.resolvedUrl != null) { return resolved; } log.debug3("Failed to resolve from DOI: " + doi); } } if (params.containsKey("id")) { // handle OpenURL 0.1 DOI specification String id = params.get("id"); if (id.startsWith("doi:")) { String doi = id.substring("doi:".length()); OpenUrlInfo resolved = resolveFromDOI(doi); if (resolved.resolvedUrl != null) { return resolved; } log.debug3("Failed to resolve from DOI: " + doi); } } String spage = getRftStartPage(params); String author = getRftParam(params, "au"); String atitle = getRftParam(params, "atitle"); String isbn = getRftParam(params, "isbn"); String edition = getRftParam(params, "edition"); String date = getRftDate(params); String volume = getRftParam(params, "volume"); if (isbn != null) { // process a book or monographic series based on ISBN OpenUrlInfo resolved = resolveFromIsbn( isbn, date, volume, edition, spage, author, atitle); if (resolved.resolvedUrl != null) { log.debug3( "Located url " + resolved.resolvedUrl + " for book ISBN " + isbn); return resolved; } log.debug3("Failed to resolve from ISBN: " + isbn); } String eissn = getRftParam(params, "eissn"); String issn = getRftParam(params, "issn"); String issue = getRftParam(params, "issue"); // process a journal based on EISSN or ISSN String anyIssn = (eissn != null) ? eissn : issn; if (anyIssn != null) { // resolve from its eISSN OpenUrlInfo resolved = resolveFromIssn(anyIssn, date, volume, issue, spage, author, atitle); if (resolved.resolvedUrl != null) { if (log.isDebug3()) { String title = getRftParam(params, "jtitle"); if (title == null) { title = getRftParam(params, "title"); } log.debug3("Located url " + resolved.resolvedUrl + " for article \"" + atitle + "\"" + ", ISSN " + anyIssn + ", title \"" + title + "\""); } return resolved; } log.debug3("Failed to resolve from ISSN: " + anyIssn); } String bici = params.get("rft.bici"); if (bici != null) { // get cached URL from book book ICI code OpenUrlInfo resolved = null; try { resolved = resolveFromBici(bici); if (resolved.resolvedUrl != null) { log.debug3( "Located url " + resolved.resolvedUrl + "for bici " + bici); return resolved; } } catch (ParseException ex) { log.warning(ex.getMessage()); } log.debug3("Failed to resolve from BICI: " + bici); } String sici = params.get("rft.sici"); // get cached URL from serial ICI code if (sici != null) { OpenUrlInfo resolved = null; try { resolved = resolveFromSici(sici); if (resolved.resolvedUrl != null) { log.debug3( "Located url " + resolved.resolvedUrl + "for sici " + sici); return resolved; } } catch (ParseException ex) { log.warning(ex.getMessage()); } log.debug3("Failed to resolve from SICI: " + sici); } // process a journal or book based on its title String title = getRftParam(params, "title"); boolean isbook = false; boolean isjournal = false; if (title == null) { title = params.get("rft.btitle"); isbook = title != null; } if (title == null) { title = params.get("rft.jtitle"); isjournal = title != null; } if (title != null) { Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); if (tdb != null) { Collection<TdbTitle> titles = Collections.emptySet(); String pub = getRftParam(params, "pub"); // only search the named publisher TdbPublisher tdbPub = (pub == null) ? null : tdb.getTdbPublisher(pub); if (isbook) { // search as though it is a book title Collection<TdbAu> tdbAus; if (tdbPub != null) { tdbAus = tdbPub.getTdbAusLikeName(title); } else { tdbAus = tdb.getTdbAusLikeName(title); } Collection<TdbAu> noTdbAus = new ArrayList<TdbAu>(); for (TdbAu tdbAu : tdbAus) { // search for journal through its ISBN String id = tdbAu.getIsbn(); if (id != null) { // try resolving from ISBN OpenUrlInfo resolved = resolveFromIsbn(id, date, volume, issue, spage, author, atitle); if (resolved.resolvedUrl != null) { if (log.isDebug3()) { log.debug3("Located url " + resolved.resolvedUrl + " for article \"" + atitle + "\"" + ", ISBN " + id + ", title \"" + title + "\"" + ", publisher \"" + tdbAu.getTdbPublisher().getName() + "\""); } return resolved; } } else { // add to list of titles with no ISBN noTdbAus.add(tdbAu); } } // search matching titles without ISBNs OpenUrlInfo resolved = resolveBookFromTdbAus(noTdbAus, date, volume, edition, spage); if (resolved != null) { if (log.isDebug3()) { log.debug3( "Located url " + resolved.resolvedUrl + ", title \"" + title + "\""); } return resolved; } } else { // search as though it is a journal title Collection<TdbTitle> tdbTitles; if (tdbPub != null) { tdbTitles = tdbPub.getTdbTitlesLikeName(title); } else { tdbTitles = tdb.getTdbTitlesLikeName(title); } Collection<TdbTitle> noTdbTitles = new ArrayList<TdbTitle>(); for (TdbTitle tdbTitle : tdbTitles) { // search for journal through its ISSN String id = tdbTitle.getIssn(); if (id != null) { // try resolving from ISSN OpenUrlInfo resolved = resolveFromIssn(id, date, volume, issue, spage, author, atitle); if (resolved.resolvedUrl != null) { if (log.isDebug3()) { log.debug3("Located url " + resolved.resolvedUrl + " for article \"" + atitle + "\"" + ", ISSN " + id + ", title \"" + title + "\"" + ", publisher \"" + tdbTitle.getTdbPublisher().getName() + "\""); } return resolved; } } else { // add to list of titles with no ISBN or ISSN noTdbTitles.add(tdbTitle); } } // search matching titles without ISSNs for (TdbTitle noTdbTitle : noTdbTitles) { Collection<TdbAu> tdbAus = noTdbTitle.getTdbAus(); OpenUrlInfo resolved = resolveJournalFromTdbAus(tdbAus,date,volume,issue, spage); if (resolved.resolvedUrl != null) { if (log.isDebug3()) { log.debug3( "Located url " + resolved.resolvedUrl + ", title \"" + title + "\""); } return resolved; } } } } log.debug3("Failed to resolve from title: \"" + title + "\""); } return noOpenUrlInfo; } /** * Resolve serials article based on the SICI descriptor. For an article * "Who are These Independent Information Brokers?", Bulletin of the * American Society for Information Science, Feb-Mar 1995, Vol. 21, no 3, * page 12, the SICI would be: 0095-4403(199502/03)21:3<12:WATIIB>2.0.TX;2-J * * @param sici a string representing the serials article SICI * @return the article url or <code>null</code> if not resolved * @throws ParseException if error parsing SICI */ public OpenUrlInfo resolveFromSici(String sici) throws ParseException { int i = sici.indexOf('('); if (i < 0) { // did not find end of date section throw new ParseException("Missing start of date section", 0); } // validate ISSN after normalizing to remove punctuation String issn = sici.substring(0,i).replaceFirst("-", ""); if (!MetadataUtil.isIssn(issn)) { // ISSN is 8 characters throw new ParseException("Malformed ISSN", 0); } // skip over date section (199502/03) int j = sici.indexOf(')',i+1); if (j < 0) { // did not find end of date section throw new ParseException("Missing end of date section", i+1); } // get volume and issue between end of // date section and start of article section i = j+1; // advance to start of volume j = sici.indexOf('<',i); if (j < 0) { // did not find start of issue section throw new ParseException("Missing start of issue section", i); } // get volume delimiter int k = sici.indexOf(':', i); if ((k < 0) || (k >= j)) { // no volume delimiter before start of issue section throw new ParseException("Missing volume delimiter", i); } String volume = sici.substring(i,k); String issue = sici.substring(k+1,j); // get end of issue section i = j+1; k = sici.indexOf('>', i+1); if (k < 0) { // did not find end of issue section throw new ParseException("Missing end of issue section", i+1); } j = sici.indexOf(':',i+1); if ((j < 0) || (j >= k)) { throw new ParseException("Missing page delimiter", i+1); } String spage = sici.substring(i,j); // get the cached URL from the parsed paramaters OpenUrlInfo resolved = resolveFromIssn(issn, null, volume, issue, spage, null, null); if ((resolved.resolvedUrl != null) && log.isDebug()) { // report on the found article Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); String jTitle = null; if (tdb != null) { TdbTitle title = tdb.getTdbTitleByIssn(issn); if (title != null) { jTitle = title.getName(); } } if (log.isDebug3()) { String s = "Located cachedURL " + resolved.resolvedUrl + " for ISSN " + issn + ", volume: " + volume + ", issue: " + issue + ", start page: " + spage; if (jTitle != null) { s += ", journal title \"" + jTitle + "\""; } log.debug3(s); } } return noOpenUrlInfo; } /** * Resolve a book chapter based on the BICI descriptor. For an item "English * as a World Language", Chapter 10, in "The English Language: A Historical * Introduction", 1993, pp. 234-261, ISBN 0-521-41620-5, the BICI would be * 0521416205(1993)(10;EAAWL;234-261)2.2.TX;1-1 * * @param bici a string representing the book chapter BICI * @return the article url or <code>null</code> if not resolved * @throws ParseException if error parsing BICI */ public OpenUrlInfo resolveFromBici(String bici) throws ParseException { int i = bici.indexOf('('); if (i < 0) { // did not find end of date section throw new ParseException("Missing start of date section", 0); } String isbn = bici.substring(0,i).replaceAll("-", ""); // match ISBN-10 or ISBN-13 with 0-9 or X checksum character if (!MetadataUtil.isIsbn(isbn, false)) { // ISSB is 10 or 13 characters throw new ParseException("Malformed ISBN", 0); } // skip over date section (1993) int j = bici.indexOf(')',i+1); if (j < 0) { // did not find end of date section throw new ParseException("Missing end of date section", i+5); } String date = bici.substring(i+1, j); // get volume and issue between end of // date section and start of article section if (bici.charAt(j+1) != '(') { // did not find start of chapter section throw new ParseException("Missing start of chapter section", j+1); } i = j+2; // advance to start of chapter j = bici.indexOf(')',i); if (j < 0) { // did not find end of chapter section throw new ParseException("Missing end of chapter section", i); } // get chapter number delimiter int k = bici.indexOf(';', i); if ((k < 0) || (k >= j)) { // no chapter number delimiter before end of chapter section throw new ParseException("Missing chapter number delimiter", i); } String chapter = bici.substring(i,k); // get end of chapter section i = k+1; k = bici.indexOf(';', i+1); if ((k < 0) || (k >= j)) { // no chapter abbreviation delimiter before end of chapter section throw new ParseException("Missing chapter abbreviation delimiter", i); } // extract the start page String spage = bici.substring(k+1,j); if (spage.indexOf('-') > 0) { spage = spage.substring(0, spage.indexOf('-')); } // PJG: what about chapter number? // (isbn, date, volume, edition, spage, author, title) OpenUrlInfo resolved = resolveFromIsbn(isbn, date, null, null, spage, null, null); if ((resolved.resolvedUrl != null) && log.isDebug()) { Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); String bTitle = null; if (tdb != null) { Collection<TdbAu> tdbAus = tdb.getTdbAusByIsbn(isbn); if (!tdbAus.isEmpty()) { bTitle = tdbAus.iterator().next().getJournalTitle(); } } if (log.isDebug3()) { String s = "Located cachedURL " + resolved.resolvedUrl + " for ISBN " + isbn + ", year: " + date + ", chapter: " + chapter + ", start page: " + spage; if (bTitle != null) { s += ", book title \"" + bTitle + "\""; } log.debug3(s); } } return noOpenUrlInfo; } /** * Resolves from a url. * * @param aUrl the URL * @return a resolved URL */ public OpenUrlInfo resolveFromUrl(String aUrl) { String url = resolveUrl(aUrl); return OpenUrlInfo.newInstance(url); } /** * Validates a URL and resolve it by following indirects, and stopping * early if a URL that is in the LOCKSS cache is found. * * @param aUrl the URL * @return a resolved URL */ public String resolveUrl(String aUrl) { String url = aUrl; try { final PluginManager pluginMgr = daemon.getPluginManager(); final LockssUrlConnectionPool connectionPool = daemon.getProxyManager().getQuickConnectionPool(); for (int i = 0; i < MAX_REDIRECTS; i++) { // no need to look further if content already cached if (pluginMgr.findCachedUrl(url,true) != null) { return url; } // test URL by opening connection LockssUrlConnection conn = null; try { conn = UrlUtil.openConnection(url, connectionPool); conn.setFollowRedirects(false); conn.setRequestProperty("user-agent", LockssDaemon.getUserAgent()); conn.execute(); // if not redirected, validate based on response code String url2 = conn.getResponseHeaderValue("Location"); if (url2 == null) { int response = conn.getResponseCode(); log.debug3(i + " response code: " + response); if (response == HttpURLConnection.HTTP_OK) { return url; } return null; } // resolve redirected URL and try again url = UrlUtil.resolveUri(url, url2); log.debug3(i + " resolved to: " + url); } finally { IOUtil.safeRelease(conn); } } } catch (IOException ex) { log.error("resolving from URL:" + aUrl + " with URL: " + url, ex); } return null; } /** * Return the article URL from a DOI, using either the MDB or TDB. * @param doi the DOI * @return the article url */ public OpenUrlInfo resolveFromDOI(String doi) { if (!MetadataUtil.isDoi(doi)) { return null; } OpenUrlInfo resolved = noOpenUrlInfo; try { // resolve from metadata manager MetadataManager metadataMgr = daemon.getMetadataManager(); resolved = resolveFromDoi(metadataMgr, doi); } catch (IllegalArgumentException ex) { } if (resolved.resolvedUrl == null) { // use DOI International resolver for DOI resolved = resolveFromUrl("http://dx.doi.org/" + doi); } return resolved; } /** * Return the article URL from a DOI using the MDB. * @param metadataMgr the metadata manager * @param doi the DOI * @return the OpenUrlInfo */ private OpenUrlInfo resolveFromDoi(MetadataManager metadataMgr, String doi) { String url = null; Connection conn = null; try { conn = metadataMgr.newConnection(); String MTN = MetadataManager.METADATA_TABLE; String DTN = MetadataManager.DOI_TABLE; String MDID = MetadataManager.MD_ID_FIELD; String query = "select " + MetadataManager.ACCESS_URL_FIELD + " from " + MTN + "," + DTN + " where " + DTN + "." + MDID + " = " + MTN + "." + MDID + " and upper(" + MetadataManager.DOI_FIELD + ") = ?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, doi.toUpperCase()); ResultSet resultSet = stmt.executeQuery(); if (resultSet.next()) { url = resultSet.getString(1); } } catch (SQLException ex) { log.error("Getting DOI:" + doi, ex); } finally { MetadataManager.safeClose(conn); } return new OpenUrlInfo(url, OpenUrlInfo.ResolvedTo.ARTICLE); } /** * Return article URL from an ISSN, date, volume, issue, spage, and author. * The first author will only be used when the starting page is not given. * * @param issn the issn * @param date the publication date * @param volume the volume * @param issue the issue * @param spage the starting page * @param author the first author's full name * @param atitle the article title * @return the article URL */ public OpenUrlInfo resolveFromIssn( String issn, String date, String volume, String issue, String spage, String author, String atitle) { OpenUrlInfo resolved = noOpenUrlInfo; Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); TdbTitle title = (tdb == null) ? null : tdb.getTdbTitleByIssn(issn); // only go to metadata manager if requesting individual article try { // resolve article from metadata manager String[] issns = (title == null) ? new String[] { issn } : title.getIssns(); MetadataManager metadataMgr = daemon.getMetadataManager(); resolved = resolveFromIssn(metadataMgr, issns, date, volume, issue, spage, author, atitle); } catch (IllegalArgumentException ex) { // intentionally ignore input error } if (resolved.resolvedUrl == null) { // resolve title, volume, AU, or issue TOC from TDB if (title == null) { log.debug3("No TdbTitle for issn " + issn); } else { resolved = resolveJournalFromTdbAus( title.getTdbAus(), date, volume, issue, spage); } } return resolved; } /** * Return article URL from an ISSN, date, volume, issue, spage, and author. * The first author will only be used when the starting page is not given. * * @param metadataMgr the metadata manager * @param issns a list of alternate ISSNs for the title * @param date the publication date * @param volume the volume * @param issue the issue * @param spage the starting page * @param author the first author's full name * @param atitle the article title * @return the article URL */ private OpenUrlInfo resolveFromIssn( MetadataManager metadataMgr, String[] issns, String date, String volume, String issue, String spage, String author, String atitle) { Connection conn = null; OpenUrlInfo resolved = noOpenUrlInfo; try { conn = metadataMgr.newConnection(); StringBuilder query = new StringBuilder(); ArrayList<String> args = new ArrayList<String>(); buildAuxiliaryTableQuery( MetadataManager.ISSN_TABLE, MetadataManager.ISSN_FIELD, issns, query, args); // true if properties specify an article boolean hasArticleSpec = (spage != null) || (author != null) || (atitle != null); // true if properties specified a journal item boolean hasJournalSpec = (date != null) || (volume != null) || (issue != null); if (hasJournalSpec) { // can specify an issue by a combination of date, volume and issue; // how these combine varies, so do the most liberal match possible // and filter based on multiple results query.append(" and "); if (date != null) { // enables query "2009" to match "2009-05-10" in database query.append(MetadataManager.DATE_FIELD); query.append(" like ? escape '\\'"); args.add(date.replace("\\","\\\\").replace("%","\\%") + "%"); } if (volume != null) { if (date != null) { query.append(" and "); } query.append(MetadataManager.VOLUME_FIELD); query.append(" = ?"); args.add(volume); } if (issue != null) { if ((date != null) || (volume != null)) { query.append(" and "); } query.append(MetadataManager.ISSUE_FIELD); query.append(" = ?"); args.add(issue); } } // handle start page, author, and article title as // equivalent ways to specify an article within an issue if (hasArticleSpec) { // accept any of the three query.append(" and ( "); if (spage != null) { query.append(MetadataManager.START_PAGE_FIELD); query.append(" = ?"); args.add(spage); } if (atitle != null) { if (spage != null) { query.append(" or "); } query.append("upper("); query.append(MetadataManager.ARTICLE_TITLE_FIELD); query.append(") like ? escape '\\'"); args.add(atitle.toUpperCase().replace("%","\\%") + "%"); } if ( author != null) { if ((spage != null) || (atitle != null)) { query.append(" or "); } // add the author query to the query addAuthorQuery(author, query, args); } query.append(" )"); } String url = resolveFromQuery(conn, query.toString(), args); return OpenUrlInfo.newInstance(url, OpenUrlInfo.ResolvedTo.ARTICLE); } catch (SQLException ex) { log.error("Getting ISSNs:" + Arrays.toString(issns), ex); } finally { MetadataManager.safeClose(conn); } return resolved; } /** * Resolve query if a single URL matches. * * @param conn the connection * @param query the query * @param args the args * @return a single URL * @throws SQLException */ private String resolveFromQuery( Connection conn, String query, List<String> args) throws SQLException { log.debug3("query: " + query); PreparedStatement stmt = conn.prepareStatement(query.toString()); for (int i = 0; i < args.size(); i++) { log.debug3(" query arg: " + args.get(i)); stmt.setString(i+1, args.get(i)); } stmt.setMaxRows(2); // only need 2 to to determine if unique ResultSet resultSet = stmt.executeQuery(); String url = null; if (resultSet.next()) { url = resultSet.getString(1); if (resultSet.next()) { log.debug3("entry not unique: " + url + " " + resultSet.getString(1)); url = null; } } return url; } /** * Return article URL from a TdbTitle, date, volume, and issue. * * @param title the TdbTitle * @param date the publication date * @param volume the volume * @param issue the issue * @param spage the start page or article number * @return the article URL */ private OpenUrlInfo resolveJournalFromTdbAus( Collection<TdbAu> tdbAus, String date, String volume, String issue, String spage) { // get the year from the date String year = null; if (date != null) { int y = new PublicationDate(date).getYear(); year = (y == 0) ? null : Integer.toString(y); } // list of AUs that match volume and year specified ArrayList<TdbAu> foundTdbAuList = new ArrayList<TdbAu>(); // list of AUs that do not match volume and year specified ArrayList<TdbAu> notFoundTdbAuList = new ArrayList<TdbAu>(); // find a TdbAu that matches the date, and volume for (TdbAu tdbAu : tdbAus) { // if neither year or volume specified, pick any TdbAu if ((volume == null) && (year == null)) { notFoundTdbAuList.add(tdbAu); continue; } // if volume specified, see if this TdbAu matches if (volume != null) { if (!tdbAu.includesVolume(volume)) { notFoundTdbAuList.add(tdbAu); continue; } } // if year specified, see if this TdbAu matches if (year != null) { if (!tdbAu.includesYear(year)) { notFoundTdbAuList.add(tdbAu); continue; } } foundTdbAuList.add(tdbAu); } final PluginManager pluginMgr = daemon.getPluginManager(); OpenUrlInfo resolved = noOpenUrlInfo; if (!foundTdbAuList.isEmpty()) { // look for URL that is cached from list of matching AUs for (TdbAu tdbau : foundTdbAuList) { String aYear = year; if (aYear == null) { aYear = tdbau.getStartYear(); } String aVolume = volume; if (aVolume == null) { aVolume = tdbau.getStartVolume(); } String anIssue = issue; if (anIssue == null) { anIssue = tdbau.getStartIssue(); } OpenUrlInfo aResolved = getJournalUrl(tdbau, aYear, aVolume, anIssue, spage); if (aResolved.resolvedUrl != null) { // found the URL if in cache if (pluginMgr.findCachedUrl(aResolved.resolvedUrl, true) != null) { resolved = aResolved; break; } // not a viable URL if the AU is down // note: even though getJournalUrl() checks that page exists, // we can't rely on it being usable if TdbAu is down if (!tdbau.isDown()) { resolved = aResolved; } else { log.debug2( "discarding URL " + aResolved.resolvedUrl + " because tdbau is down: " + tdbau.getName()); } } } } else { // look for URL that is cached from list of non-matching AUs for (TdbAu tdbau : notFoundTdbAuList) { OpenUrlInfo aResolved = getJournalUrl(tdbau, year, volume, issue, spage); if (aResolved != null) { // found the URL if in cache if (pluginMgr.findCachedUrl(aResolved.resolvedUrl, true) != null) { resolved = aResolved; break; } // not a viable URL if the AU is down // note: even though getJournalUrl() checks that page exists, // we can't rely on it being usable if TdbAu is down if (!tdbau.isDown()) { resolved = aResolved; } else { log.debug2( "discarding URL " + aResolved.resolvedUrl + " because tdbau is down: " + tdbau.getName()); } } } } return resolved; } /** * Return the type entry parameter map for the specified Plugin and TdbAu. * @param plugin the plugin * @param tdbau the AU * @return the parameter map */ private static TypedEntryMap getParamMap(Plugin plugin, TdbAu tdbau) { TypedEntryMap paramMap = new TypedEntryMap(); List<ConfigParamDescr> descrs = plugin.getAuConfigDescrs(); for (ConfigParamDescr descr : descrs) { String key = descr.getKey(); String sval = tdbau.getParam(key); if (sval == null) { sval = tdbau.getPropertyByName(key); if (sval == null) { sval = tdbau.getAttr(key); } } if (sval != null) { try { Object val = descr.getValueOfType(sval); paramMap.setMapElement(key, val); } catch (InvalidFormatException ex) { log.warning("invalid value for key: " + key + " value: " + sval, ex); } } } // add entries for attributes that do not correspond to AU params for (Map.Entry<String,String> entry : tdbau.getAttrs().entrySet()) { if (!paramMap.containsKey(entry.getKey())) { paramMap.setMapElement(entry.getKey(), entry.getValue()); } } return paramMap; } /** * Return the type entry parameter map for the specified AU. * @param au the AU * @return the parameter map */ /* for later use (pjg) private static TypedEntryMap getParamMap(ArchivalUnit au) { TypedEntryMap paramMap = new TypedEntryMap(); Configuration config = au.getConfiguration(); Plugin plugin = au.getPlugin(); for (ConfigParamDescr descr : plugin.getAuConfigDescrs()) { String key = descr.getKey(); if (config.containsKey(key)) { try { Object val = descr.getValueOfType(config.get(key)); paramMap.setMapElement(key, val); } catch (Exception ex) { log.error("Error configuring: " + key + " " + ex.getMessage()); } } } return paramMap; } */ /** * Gets the book URL for an AU indicated by the DefinablePlugin * and parameter definitions specified by the TdbAu. * * @param plugin the DefinablePlugin * @param tdbau the TdbAu * @param year the year * @param volumeName the volume name * @param issue the issue * @return the issue URL */ /* for later use (pjg) private static String getBooklUrl( ArchivalUnit au, String volumeName, String year, String edition) { TypedEntryMap paramMap = getParamMap(au); Plugin plugin = au.getPlugin(); String url = getBookUrl(plugin, paramMap, volumeName, year, edition); return url; } */ /** * Gets the book URL for a TdbAU indicated by the DefinablePlugin * and parameter definitions specified by the TdbAu. * @param tdbau the TdbAu * @param year the year * @param volumeName the volume name * @param edition the edition * @param spage the start page * @return the starting URL */ private OpenUrlInfo getBookUrl( TdbAu tdbau, String year, String volumeName, String edition, String spage) { PluginManager pluginMgr = daemon.getPluginManager(); String pluginKey = PluginManager.pluginKeyFromId(tdbau.getPluginId()); Plugin plugin = pluginMgr.getPlugin(pluginKey); OpenUrlInfo resolved = null; if (plugin != null) { log.debug3( "getting issue url for plugin: " + plugin.getClass().getName()); // get starting URL from a DefinablePlugin TypedEntryMap paramMap = getParamMap(plugin, tdbau); // add volume with type and spelling of existing element paramMap.setMapElement("volume", volumeName); paramMap.setMapElement("volume_str",volumeName); paramMap.setMapElement("volume_name", volumeName); paramMap.setMapElement("year", year); if (!StringUtil.isNullString(year)) { try { paramMap.setMapElement("au_short_year", String.format("%02d", NumberUtil.parseInt(year)%100)); } catch (NumberFormatException ex) { log.info( "Error parsing year '" + year + "' as an int -- not setting au_short_year"); } } paramMap.setMapElement("edition", edition); paramMap.setMapElement("chapter", spage); // auFeatureKey selects feature from a map of values // for the same feature (e.g. au_feature_urls/au_year) paramMap.setMapElement("auFeatureKey", tdbau.getAttr(AU_FEATURE_KEY)); String isbn = tdbau.getAttr("isbn"); if (isbn != null) { paramMap.setMapElement("isbn", isbn); } String eisbn = tdbau.getAttr("eisbn"); if (eisbn != null) { paramMap.setMapElement("eisbn", eisbn); } resolved = getBookUrl(plugin, paramMap); log.debug3( "Found starting url from definable plugin: " + resolved.resolvedUrl); } else { log.debug3("No plugin found for key: " + pluginKey); } return resolved; } /** * Gets the book URL for a DefinablePlugin and parameter definitions. * @param plugin the plugin * @param paramMap the param map * @return the issue URL */ private OpenUrlInfo getBookUrl(Plugin plugin, TypedEntryMap paramMap) { OpenUrlInfo resolved = getPluginUrl(plugin, auBookauFeatures, paramMap); if (resolved.resolvedUrl == null) { resolved = OpenUrlInfo.newInstance( paramMap.getString("base_url"), OpenUrlInfo.ResolvedTo.PUBLISHER); } return resolved; } /** * Gets the issue URL for an AU indicated by the DefinablePlugin * and parameter definitions specified by the TdbAu. * * @param plugin the DefinablePlugin * @param tdbau the TdbAu * @param year the year * @param volumeName the volume name * @param issue the issue * @return the issue URL */ /* for later use (pjg) private static String getJournalUrl( ArchivalUnit au, String year, String volumeName, String issue) { TypedEntryMap paramMap = getParamMap(au); Plugin plugin = au.getPlugin(); String url = getJournalUrl(plugin, paramMap, year, volumeName, issue); return url; } */ /** * Get starting url from TdbAu. * @param tdbau the TdbAu * @param year the year * @param volumeName the volume name * @param issue the issue * @param spage the start page or article number * @return the starting URL */ private OpenUrlInfo getJournalUrl( TdbAu tdbau, String year, String volumeName, String issue, String spage) { PluginManager pluginMgr = daemon.getPluginManager(); String pluginKey = PluginManager.pluginKeyFromId(tdbau.getPluginId()); Plugin plugin = pluginMgr.getPlugin(pluginKey); OpenUrlInfo resolved = noOpenUrlInfo; if (plugin != null) { log.debug3( "getting issue url for plugin: " + plugin.getClass().getName()); // get starting URL from a DefinablePlugin // add volume with type and spelling of existing element TypedEntryMap paramMap = getParamMap(plugin, tdbau); paramMap.setMapElement("volume", volumeName); paramMap.setMapElement("volume_str", volumeName); paramMap.setMapElement("volume_name", volumeName); paramMap.setMapElement("year", year); String issn = tdbau.getPrintIssn(); if (issn != null) { paramMap.setMapElement("issn", issn); } String eissn = tdbau.getEissn(); if (eissn != null) { paramMap.setMapElement("eissn", eissn); } if (!StringUtil.isNullString(year)) { try { paramMap.setMapElement("au_short_year", String.format("%02d", NumberUtil.parseInt(year)%100)); } catch (NumberFormatException ex) { log.info("Error parsing year '" + year + "' as an integer -- not setting au_short_year"); } } paramMap.setMapElement("issue", issue); paramMap.setMapElement("article", spage); // AU_FEATURE_KEY selects feature from a map of values // for the same feature (e.g. au_feature_urls/au_year) paramMap.setMapElement(AU_FEATURE_KEY, tdbau.getAttr(AU_FEATURE_KEY)); resolved = getJournalUrl(plugin, paramMap); log.debug3( "Found starting url from definable plugin: " + resolved.resolvedUrl); } else { log.debug3("No plugin found for key: " + pluginKey); } return resolved; } /** * Get the issueURL for the plugin. * @param plugin the plugin * @param paramMap the param map * @return the issue URL */ private OpenUrlInfo getJournalUrl(Plugin plugin, TypedEntryMap paramMap) { OpenUrlInfo resolved = getPluginUrl(plugin, auJournalauFeatures, paramMap); if (resolved.resolvedUrl == null) { resolved = OpenUrlInfo.newInstance(paramMap.getString("base_url"), OpenUrlInfo.ResolvedTo.PUBLISHER); } return resolved; } /** * Get the URL for the specified key from the plugin. * @param plugin the plugin * @param pluginKeys the plugin keys * @param paramMap the param map * @return the URL for the specified key */ private OpenUrlInfo getPluginUrl(Plugin plugin, FeatureEntry[] pluginEntries, TypedEntryMap paramMap) { ExternalizableMap map; // get printf pattern for pluginKey property try { Method method = plugin.getClass().getMethod("getDefinitionMap", (new Class[0])); Object obj = method.invoke(plugin); if (!(obj instanceof ExternalizableMap)) { return noOpenUrlInfo; } map = (ExternalizableMap)obj; } catch (Exception ex) { log.error("getDefinitionMap", ex); return noOpenUrlInfo; } for (FeatureEntry pluginEntry : pluginEntries) { // locate object value for plugin key path String pluginKey = pluginEntry.auFeatureKey; String[] pluginKeyPath = pluginKey.split("/"); Object obj = map.getMapElement(pluginKeyPath[0]); for (int i = 1; (i < pluginKeyPath.length); i++) { if (obj instanceof Map) { obj = ((Map<String,?>)obj).get(pluginKeyPath[i]); } else { // all path elements except last one must be a map; obj = null; break; } } if (obj instanceof Map) { // match TDB AU_FEATURE_KEY value to key in map String auFeatureKey = "*"; // default entry try { auFeatureKey = paramMap.getString(AU_FEATURE_KEY); } catch (NoSuchElementException ex) {} // entry may have multiple keys; '*' is the default entry Object val = null; for (Map.Entry<String,?> entry : ((Map<String,?>)obj).entrySet()) { String key = entry.getKey(); if ( key.equals(auFeatureKey) || key.startsWith(auFeatureKey + ";") || key.endsWith(";" + auFeatureKey) || (key.indexOf(";" + auFeatureKey + ";") >= 0)) { val = entry.getValue(); break; } } obj = val; pluginKey += "/" + auFeatureKey; } if (obj == null) { log.debug("unknown plugin key: " + pluginKey); continue; } Collection<String> printfStrings = null; if (obj instanceof String) { // get single pattern for start url printfStrings = Collections.singleton((String)obj); } else if (obj instanceof Collection) { printfStrings = (Collection<String>)obj; } else { log.debug( "unknown type for plugin key: " + pluginKey + ": " + obj.getClass().getName()); continue; } log.debug3( "Trying plugin key: " + pluginKey + " for plugin: " + plugin.getPluginId() + " with " + printfStrings.size() + " printf strings"); // set up converter for use with feature URL printf strings UrlListConverter converter = PrintfConverter.newUrlListConverter(plugin, paramMap); for (String s : printfStrings) { String url = null; try { List<String> urls = converter.getUrlList(s); if ((urls != null) && !urls.isEmpty()) { // if multiple urls match, the first one will do url = urls.get(0); } } catch (Throwable ex) { log.debug("invalid conversion for " + s, ex); continue; } // validate URL: either it's cached, or it can be reached if (!StringUtil.isNullString(url)) { log.debug3("Resolving from url: " + url); url = resolveUrl(url); if (url != null) { return OpenUrlInfo.newInstance(url, pluginEntry.resolvedTo); } } } } return noOpenUrlInfo; } /** * Return the book URL from TdbTitle and edition. * * @param tdbAus a collection of TdbAus that match an ISBN * @param date the publication date * @param volume the volume * @param edition the edition * @param spage the start page * @return the book URL */ private OpenUrlInfo resolveBookFromTdbAus( Collection<TdbAu> tdbAus, String date, String volume, String edition, String spage) { // get the year from the date String year = null; if (date != null) { int y = new PublicationDate(date).getYear(); year = (y == 0) ? null : Integer.toString(y); } // list of AUs that match volume and year specified ArrayList<TdbAu> foundTdbAuList = new ArrayList<TdbAu>(); // list of AUs that do not match volume, edition, and year specified ArrayList<TdbAu> notFoundTdbAuList = new ArrayList<TdbAu>(); for (TdbAu tdbAu : tdbAus) { // if none of year, volume, or edition specified, pick any TdbAu if ((volume == null) && (year == null) && (edition == null)) { notFoundTdbAuList.add(tdbAu); continue; } // if volume specified, see if this TdbAu matches if (volume != null) { if (!tdbAu.includesVolume(volume)) { notFoundTdbAuList.add(tdbAu); continue; } } // if year specified, see if this TdbAu matches if (year != null) { if (!tdbAu.includesYear(year)) { notFoundTdbAuList.add(tdbAu); continue; } } // get the plugin id for the TdbAu that matches the specified edition if (edition != null) { String auEdition = tdbAu.getEdition(); if ((auEdition != null) && !edition.equals(auEdition)) { notFoundTdbAuList.add(tdbAu); continue; } } foundTdbAuList.add(tdbAu); } final PluginManager pluginMgr = daemon.getPluginManager(); OpenUrlInfo resolved = noOpenUrlInfo; if (!foundTdbAuList.isEmpty()) { // look for URL that is cached from list of matching AUs for (TdbAu tdbau : foundTdbAuList) { String aYear = year; if (aYear == null) { aYear = tdbau.getStartYear(); } String aVolume = volume; if (aVolume == null) { aVolume = tdbau.getStartVolume(); } String anEdition = edition; if (edition == null) { anEdition = tdbau.getEdition(); } OpenUrlInfo aResolved = getBookUrl(tdbau, year, aVolume, anEdition, spage); if (aResolved != null) { // found the URL if in cache if (pluginMgr.findCachedUrl(aResolved.resolvedUrl, true) != null) { resolved = aResolved; break; } // not a viable URL if the AU is down // note: even though getBookUrl() checks that page exists, // we can't rely on it being usable if TdbAu is down if (!tdbau.isDown()) { resolved = aResolved; } else { log.debug2( "discarding URL " + aResolved.resolvedUrl + " because tdbau is down: " + tdbau.getName()); } } } } else { // look for URL that is cached from list of non-matching AUs for (TdbAu tdbau : notFoundTdbAuList) { OpenUrlInfo aResolved = getBookUrl(tdbau, year, volume, edition, spage); if (aResolved.resolvedUrl != null) { // found the URL if in cache if (pluginMgr.findCachedUrl(aResolved.resolvedUrl, true) != null) { resolved = aResolved; break; } // not a viable URL if the AU is down // note: even though getBookUrl() checks that page exists, // we can't rely on it being usable if TdbAu is down if (!tdbau.isDown()) { resolved = aResolved; } else { log.debug2( "discarding URL " + aResolved.resolvedUrl + " because tdbau is down: " + tdbau.getName()); } } } } return resolved; } /** * Return the article URL from an ISBN, edition, spage, and author. * The first author will only be used when the starting page is not given. * "Volume" is used to hold edition information in the metadata manager * schema for books. First author can be used in place of start page. * * @param isbn the isbn * @param date the date * @param volume the volume * @param edition the edition * @param spage the start page * @param author the first author * @param atitle the chapter title * @return the article URL */ public OpenUrlInfo resolveFromIsbn( String isbn, String date, String volume, String edition, String spage, String author, String atitle) { OpenUrlInfo resolved = noOpenUrlInfo; // only go to metadata manager if requesting individual article/chapter try { // resolve from metadata manager MetadataManager metadataMgr = daemon.getMetadataManager(); resolved = resolveFromIsbn( metadataMgr, isbn, date, volume, edition, spage, author, atitle); } catch (IllegalArgumentException ex) { } if (resolved.resolvedUrl == null) { // resolve from TDB Tdb tdb = ConfigManager.getCurrentConfig().getTdb(); Collection<TdbAu> tdbAus = (tdb == null) ? Collections.<TdbAu>emptySet() : tdb.getTdbAusByIsbn(isbn); if (tdbAus.isEmpty()) { log.debug3("No TdbAus for isbn " + isbn); return null; } resolved = resolveBookFromTdbAus(tdbAus, date, volume, edition, spage); } return resolved; } /** * Return the article URL from an ISBN, edition, start page, author, and * article title using the metadata database. * <p> * The algorithm matches the ISBN and optionally the edition, and either * the start page, author, or article title. The reason for matching on any * of the three is that typos in author and article title are always * possible so we want to be more forgiving in matching an article. * <p> * If none of the three are specified, the URL for the book table of contents * is returned. * * @param metadataMgr the metadata manager * @param isbn the isbn * @param String date the date * @param String volumeName the volumeName * @param edition the edition * @param spage the start page * @param author the first author * @param atitle the chapter title * @return the url */ private OpenUrlInfo resolveFromIsbn( MetadataManager metadataMgr, String isbn, String date, String volume, String edition, String spage, String author, String atitle) { OpenUrlInfo resolved = noOpenUrlInfo; Connection conn = null; try { conn = metadataMgr.newConnection(); // strip punctuation isbn = isbn.replaceAll("[- ]", ""); StringBuilder query = new StringBuilder(); ArrayList<String> args = new ArrayList<String>(); buildAuxiliaryTableQuery( MetadataManager.ISBN_TABLE, MetadataManager.ISBN_FIELD, new String[] {isbn}, query, args); boolean hasBookSpec = (date != null) || (volume != null) || (edition != null); boolean hasArticleSpec = (spage != null) || (author != null) || (atitle != null); if (hasBookSpec) { // can specify an issue by a combination of date, volume and issue; // how these combine varies, so do the most liberal match possible // and filter based on multiple results query.append(" and "); if (date != null) { // enables query "2009" to match "2009-05-10" in database query.append(MetadataManager.DATE_FIELD); query.append(" like ? escape '\\'"); args.add(date.replace("\\","\\\\").replace("%","\\%") + "%"); } if (volume != null) { if (date != null) { query.append(" and "); } query.append(MetadataManager.VOLUME_FIELD); query.append(" = ?"); args.add(volume); } if (edition != null) { if ((date != null) || (volume != null)) { query.append(" and "); } query.append(MetadataManager.EDITION_FIELD); query.append(" = ?"); args.add(edition); } } // handle start page, author, and article title as // equivalent ways to specify an article within an issue if (hasArticleSpec) { // accept any of the three query.append(" and ( "); if (spage != null) { query.append(MetadataManager.START_PAGE_FIELD); query.append(" = ?"); args.add(spage); } if (atitle != null) { if (spage != null) { query.append(" or "); } query.append(MetadataManager.ARTICLE_TITLE_FIELD); query.append(" like ? escape '\\'"); args.add(atitle.replace("%","\\%") + "%"); } if ( author != null) { if ((spage != null) || (atitle != null)) { query.append(" or "); } // add the author query to the query addAuthorQuery(author, query, args); } query.append(" )"); } String url = resolveFromQuery(conn, query.toString(), args); resolved = OpenUrlInfo.newInstance(url, OpenUrlInfo.ResolvedTo.CHAPTER); } catch (SQLException ex) { log.error("Getting ISBN:" + isbn, ex); } finally { MetadataManager.safeClose(conn); } return resolved; } /** * Build a query for the field in the specified auxiliary table * (e.g. MetadataManager.ISSN_TABLE, MetadataManager.ISBN_TABLE * or MetadataManager.DOI_TABLE) that shares a foreign key with * the Metadata table. * @param tableId the table ID * @param fieldId the field ID in the specified table * @param fieldValues the list of acceptable field values * @param query the query string builder * @param args the query args */ private void buildAuxiliaryTableQuery( String tableId, String fieldId, String[] fieldValues, StringBuilder query, List<String>args) { String MTN = MetadataManager.METADATA_TABLE; query.append("select distinct "); query.append(MetadataManager.ACCESS_URL_FIELD); query.append(","); query.append(MetadataManager.PLUGIN_ID_FIELD); query.append(","); query.append(MetadataManager.AU_KEY_FIELD); query.append(" from "); query.append(MTN); query.append(","); query.append(tableId); query.append(" where "); query.append(tableId); query.append("."); query.append(MetadataManager.MD_ID_FIELD); query.append(" = "); query.append(MTN); query.append("."); query.append(MetadataManager.MD_ID_FIELD); query.append(" and "); query.append(fieldId); query.append(" in ("); String querystr = "?"; for (String issn : fieldValues) { query.append(querystr); args.add(issn.replaceAll("-", "")); // strip punctuation querystr = ",?"; } query.append(")"); } /** * Add author query to the query buffer and argument list. * @param author the author * @param query the query buffer * @param args the argument list */ private void addAuthorQuery( String author, StringBuilder query, List<String>args) { String authorUC = author.toUpperCase(); // match single author // (last, first name separated by ',') query.append("upper("); query.append(MetadataManager.AUTHOR_FIELD); query.append(") = ?"); args.add(authorUC); // escape escape character and then wildcard characters String authorEsc = authorUC.replace("\\", "\\\\").replace("%","\\%"); for (int i = 0; i < 5; i++) { query.append(" or upper("); query.append(MetadataManager.AUTHOR_FIELD); query.append(") like ? escape '\\'"); } // match last name of first author // (last, first name separated by ',') args.add(authorEsc+",%"); // match entire first author // (authors separated by ';', last, first name separated by ',') args.add(authorEsc+";%"); // match last name of middle or last author // (authors separated by ';', last, first name separated by ',') args.add("%;" + authorEsc + ",%"); // match entire middle author // (authors separated by ';') args.add("%;" + authorEsc + ";%"); // match entire last author // (authors separated by ';') args.add("%;" + authorEsc); } }
/* * $Id: VoterActions.java,v 1.18 2007-07-31 00:30:37 smorabito Exp $ */ package org.lockss.poller.v3; import java.io.IOException; import java.util.*; import java.security.*; import org.apache.commons.collections.CollectionUtils; import org.lockss.config.ConfigManager; import org.lockss.plugin.*; import org.lockss.protocol.*; import org.lockss.protocol.psm.*; import org.lockss.util.*; public class VoterActions { private static final Logger log = Logger.getLogger("VoterActions"); // Start participating in a V3 poll when a POLL message is received public static PsmEvent handleReceivePoll(PsmMsgEvent evt, PsmInterp interp) { V3LcapMessage msg = (V3LcapMessage)evt.getMessage(); VoterUserData ud = getUserData(interp); ud.setDeadline(TimeBase.nowMs() + msg.getDuration()); ud.setVoteDeadline(TimeBase.nowMs() + msg.getVoteDuration()); return V3Events.evtOk; } public static PsmEvent handleVerifyPollEffort(PsmEvent evt, PsmInterp interp) { // XXX: Implement effort service. return V3Events.evtOk; } public static PsmEvent handleProvePollAck(PsmEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); // XXX: Implement effort service. // If we don't want to participate, just send back a pollack // with null effort proof at this point. byte[] pollAckEffort = ByteArray.makeRandomBytes(20); ud.setPollAckEffortProof(pollAckEffort); return V3Events.evtOk; } /* * Verify whether the poller is in our platform group. If they * are not, return false. */ private static boolean isOurGroup(V3LcapMessage msgIn) { List<String> pollerGroups = new ArrayList<String>(); if (msgIn != null) { for (String group: (List<String>)StringUtil.breakAt(msgIn.getGroups(), ';')) { pollerGroups.add(group.toLowerCase()); } } List<String> ourGroups = new ArrayList<String>(); for (String group : (List<String>)ConfigManager.getPlatformGroupList()) { ourGroups.add(group.toLowerCase()); } log.debug2("Our groups: " + ourGroups + "; Their groups: " + pollerGroups); return pollerGroups != null && CollectionUtils.containsAny(ourGroups, pollerGroups); } public static PsmEvent handleSendPollAck(PsmEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); V3LcapMessage msg = ud.makeMessage(V3LcapMessage.MSG_POLL_ACK); msg.setEffortProof(ud.getPollAckEffortProof()); try { /* decline the poll, and send a NAK with the status * NAK_GROUP_MISMATCH if we should not reply to this poll. */ if (isOurGroup((V3LcapMessage)ud.getPollMessage())) { // Accept the poll and set status ud.setStatus(V3Voter.STATUS_ACCEPTED_POLL); msg.setVoterNonce(ud.getVoterNonce()); // Send message ud.sendMessageTo(msg, ud.getPollerId()); log.debug2("Sent PollAck message to " + ud.getPollerId() + " in poll " + ud.getPollKey()); return V3Events.evtOk; } else { // Reject the poll and set status msg.setVoterNonce(null); msg.setNak(V3LcapMessage.PollNak.NAK_GROUP_MISMATCH); // Send message ud.sendMessageTo(msg, ud.getPollerId()); // Stop the poll. ud.getVoter().getIdentityManager().removePeer(ud.getPollerId().getIdString()); ud.getVoter().stopPoll(V3Voter.STATUS_DECLINED_POLL); log.debug2("Rejected message for " + ud.getPollerId() + " in poll " + ud.getPollKey()); return V3Events.evtDeclinePoll; } } catch (Throwable t) { log.error("Unable to send message: ", t); return V3Events.evtError; } } public static PsmEvent handleReceivePollProof(PsmMsgEvent evt, PsmInterp interp) { log.debug2("Received PollProof message"); VoterUserData ud = getUserData(interp); V3LcapMessage msg = (V3LcapMessage)evt.getMessage(); ud.setRemainingEffortProof(msg.getEffortProof()); return V3Events.evtOk; } public static PsmEvent handleVerifyPollProof(PsmEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); // XXX: Implement effort service // After effort has been proven, prepare to nominate some peers. ud.nominatePeers(); return V3Events.evtOk; } public static PsmEvent handleSendNominate(PsmEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); V3LcapMessage msg = ud.makeMessage(V3LcapMessage.MSG_NOMINATE); msg.setNominees(ud.getNominees()); try { ud.sendMessageTo(msg, ud.getPollerId()); } catch (IOException ex) { log.error("Unable to send message: ", ex); return V3Events.evtError; } return V3Events.evtOk; } public static PsmEvent handleGenerateVote(PsmEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); try { if (ud.generateVote()) { ud.setStatus(V3Voter.STATUS_HASHING); return V3Events.evtOk; } else { return V3Events.evtError; } } catch (NoSuchAlgorithmException ex) { log.error("No such hashing algorithm: " + ex.getMessage()); return V3Events.evtError; } } public static PsmEvent handleReceiveVoteRequest(PsmMsgEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); // If we're ready to cast our vote right away, do so. Otherwise, wait // until V3Voter tells us to. if (ud.hashingDone()) { return V3Events.evtReadyToVote; } else { ud.voteRequested(true); return V3Events.evtWaitHashingDone; } } public static PsmEvent handleSendVote(PsmEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); V3LcapMessage msg = ud.makeMessage(V3LcapMessage.MSG_VOTE); // XXX: Fix when multiple-message voting is supported. msg.setVoteComplete(true); msg.setVoteBlocks(ud.getVoteBlocks()); // Actually cast our vote. try { ud.sendMessageTo(msg, ud.getPollerId()); ud.setStatus(V3Voter.STATUS_VOTED); } catch (IOException ex) { log.error("Unable to send message: ", ex); return V3Events.evtError; } return V3Events.evtOk; } public static PsmEvent handleReceiveRepairRequest(PsmMsgEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); V3Voter voter = ud.getVoter(); IdentityManager idmgr = voter.getIdentityManager(); V3LcapMessage msg = (V3LcapMessage)evt.getMessage(); PeerIdentity voterId = msg.getOriginatorId(); String targetUrl = msg.getTargetUrl(); CachedUrlSet cus = ud.getCachedUrlSet(); if (cus.containsUrl(targetUrl) && voter.serveRepairs(msg.getOriginatorId(), ud.getVoter().getAu(), targetUrl)) { // I have this repair and I'm willing to serve it. log.debug2("Accepting repair request from " + ud.getPollerId() + " for URL: " + targetUrl); ud.setRepairTarget(targetUrl); return V3Events.evtRepairRequestOk; } else { // I don't have this repair log.error("No repair available to serve for URL: " + targetUrl); return V3Events.evtNoSuchRepair; } } public static PsmEvent handleSendRepair(PsmEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); log.debug2("Sending repair to " + ud.getPollerId() + " for URL : " + ud.getRepairTarget()); try { V3LcapMessage msg = ud.makeMessage(V3LcapMessage.MSG_REPAIR_REP); ArchivalUnit au = ud.getCachedUrlSet().getArchivalUnit(); CachedUrl cu = au.makeCachedUrl(ud.getRepairTarget()); msg.setTargetUrl(ud.getRepairTarget()); msg.setRepairDataLength(cu.getContentSize()); msg.setRepairProps(cu.getProperties()); msg.setInputStream(cu.getUnfilteredInputStream()); ud.sendMessageTo(msg, ud.getPollerId()); } catch (IOException ex) { log.error("Unable to send message: ", ex); return V3Events.evtError; } return V3Events.evtOk; } public static PsmEvent handleReceiveReceipt(PsmMsgEvent evt, PsmInterp interp) { // XXX: Implement. return V3Events.evtReceiptOk; } public static PsmEvent handleProcessReceipt(PsmEvent evt, PsmInterp interp) { VoterUserData ud = getUserData(interp); // XXX: Once the receipt is a bit more interesting, use it here. ud.getVoter().stopPoll(V3Voter.STATUS_COMPLETE); return V3Events.evtOk; } public static PsmEvent handleError(PsmEvent evt, PsmInterp interp) { // XXX: Implement. return V3Events.evtOk; } private static VoterUserData getUserData(PsmInterp interp) { return (VoterUserData)interp.getUserData(); } }
package com.opencms.file; import java.util.*; import javax.servlet.http.*; import com.opencms.core.*; public class CmsRequestContext implements I_CmsConstants { /** * The rb to get access to the OpenCms. */ private I_CmsResourceBroker m_rb; /** * The current CmsRequest. */ private I_CmsRequest m_req; /** * The current CmsResponse. */ private I_CmsResponse m_resp; /** * The current user. */ private CmsUser m_user; /** * The current group of the user. */ private CmsGroup m_currentGroup; /** * The current project. */ private CmsProject m_currentProject; /** * The default constructor. * */ public CmsRequestContext() { super(); } /** * Returns the current folder object. * * @return the current folder object. * * @exception CmsException if operation was not successful. */ public CmsFolder currentFolder() throws CmsException { // truncate the filename from the pathinformation String folderName = getUri().substring(0, getUri().lastIndexOf("/") + 1); return (m_rb.readFolder(currentUser(), currentProject(), folderName, "")); } /** * Returns the current group of the current user. * * @return the current group of the current user. */ public CmsGroup currentGroup() { return(m_currentGroup); } /** * Returns the current project of the current user. * * @return the current project of the current user. */ public CmsProject currentProject() { return m_currentProject; } /** * Returns the current user object. * * @return the current user object. */ public CmsUser currentUser() { return(m_user); } /** * Gets the name of the requested file without any path-information. * * @return the requested filename. */ public String getFileUri() { String uri = m_req.getRequestedResource(); uri=uri.substring(uri.lastIndexOf("/")+1); return uri; } /** * Gets the current request, if availaible. * * @return the current request, if availaible. */ public I_CmsRequest getRequest() { return( m_req ); } /** * Gets the current response, if availaible. * * @return the current response, if availaible. */ public I_CmsResponse getResponse() { return( m_resp ); } /** * Gets the Session for this request. * <br> * This method should be used instead of the originalRequest.getSession() method. * @param value indicates, if a session should be created when a session for the particular client does not already exist. * @return the CmsSession, or <code>null</code> if no session already exists and value was set to <code>false</code> * */ public I_CmsSession getSession(boolean value) { return (I_CmsSession) new CmsSession(((HttpServletRequest)m_req.getOriginalRequest()).getSession(value)); } public String getUri() { if( m_req != null ) { return( m_req.getRequestedResource() ); } else { return( C_ROOT ); } } /** * Initializes this RequestContext. * * @param req the CmsRequest. * @param resp the CmsResponse. * @param user the current user for this request. * @param currentGroup the current group for this request. * @param currentProjectId the id of the current project for this request. * * @exception CmsException if operation was not successful. */ void init(I_CmsResourceBroker rb, I_CmsRequest req, I_CmsResponse resp, String user, String currentGroup, int currentProjectId) throws CmsException { m_rb = rb; m_req = req; m_resp = resp; m_user = m_rb.readUser(null, null, user); // check, if the user is disabled if( m_user.getDisabled() == true ) { m_user = null; } // set current project and group for this request setCurrentProject(currentProjectId); m_currentGroup = m_rb.readGroup(m_user, m_currentProject, currentGroup); } /** * Determines if the users is in the admin-group. * * @return <code>true</code> if the users current group is the admin-group; <code>false</code> otherwise. * * @exception CmsException if operation was not successful. */ public boolean isAdmin() throws CmsException { return( m_rb.isAdmin(m_user, m_currentProject) ); } /** * Determines if the users current group is the projectmanager-group. * <BR> * All projectmanagers can create new projects, or close their own projects. * * @return <code>true</code> if the users current group is the projectleader-group; <code>false</code> otherwise. * * @exception CmsException if operation was not successful. */ public boolean isProjectManager() throws CmsException { return( m_rb.isProjectManager(m_user, m_currentProject) ); } /** * Sets the current group of the current user. * * @param groupname the name of the group to be set as current group. * * @exception CmsException if operation was not successful. */ public void setCurrentGroup(String groupname) throws CmsException { // is the user in that group? if(m_rb.userInGroup(m_user, m_currentProject, m_user.getName(), groupname)) { // Yes - set it to the current Group. m_currentGroup = m_rb.readGroup(m_user, m_currentProject, groupname); } else { // No - throw exception. throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } /** * Sets the current project for the user. * * @param projectId the id of the project to be set as current project. * @exception CmsException if operation was not successful. */ public CmsProject setCurrentProject(int projectId) throws CmsException { CmsProject newProject = m_rb.readProject(m_user, m_currentProject, projectId); if( newProject != null ) { m_currentProject = newProject; } return( m_currentProject ); } }
package org.myrobotlab.service; import org.myrobotlab.framework.Peers; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.Status; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.LeapMotion2.LeapData; import org.myrobotlab.service.interfaces.LeapDataListener; import org.slf4j.Logger; public class InMoovHand extends Service implements LeapDataListener { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(InMoovHand.class); /** * peer services */ transient public LeapMotion2 leap; transient public Servo thumb; transient public Servo index; transient public Servo majeure; transient public Servo ringFinger; transient public Servo pinky; transient public Servo wrist; transient public Arduino arduino; private String side; // static in Java are not overloaded but overwritten - there is no // polymorphism for statics public static Peers getPeers(String name) { Peers peers = new Peers(name); peers.put("thumb", "Servo", "Thumb servo"); peers.put("index", "Servo", "Index servo"); peers.put("majeure", "Servo", "Majeure servo"); peers.put("ringFinger", "Servo", "RingFinger servo"); peers.put("pinky", "Servo", "Pinky servo"); peers.put("wrist", "Servo", "Wrist servo"); peers.put("arduino", "Arduino", "Arduino controller for this arm"); peers.put("leap", "LeapMotion2", "Leap Motion Service"); // peers.put("keyboard", "Keyboard", "Keyboard control"); // peers.put("xmpp", "XMPP", "XMPP control"); return peers; } public InMoovHand(String n) { super(n); thumb = (Servo) createPeer("thumb"); index = (Servo) createPeer("index"); majeure = (Servo) createPeer("majeure"); ringFinger = (Servo) createPeer("ringFinger"); pinky = (Servo) createPeer("pinky"); wrist = (Servo) createPeer("wrist"); arduino = (Arduino) createPeer("arduino"); thumb.setRest(2); index.setRest(2); majeure.setRest(2); ringFinger.setRest(2); pinky.setRest(2); wrist.setRest(90); // connection details thumb.setPin(2); index.setPin(3); majeure.setPin(4); ringFinger.setPin(5); pinky.setPin(6); wrist.setPin(7); thumb.setController(arduino); index.setController(arduino); majeure.setController(arduino); ringFinger.setController(arduino); pinky.setController(arduino); wrist.setController(arduino); } // FIXME make // .isValidToStart() !!! < check all user data !!! @Override public void startService() { super.startService(); thumb.startService(); index.startService(); majeure.startService(); ringFinger.startService(); pinky.startService(); wrist.startService(); arduino.startService(); } // FIXME FIXME - this method must be called // user data needed /** * connect - user data needed * * @param port * @return */ public boolean connect(String port) { startService(); if (arduino == null) { error("arduino is invalid"); return false; } arduino.connect(port); if (!arduino.isConnected()) { error("arduino %s not connected", arduino.getName()); return false; } attach(); setSpeed(0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f); rest(); sleep(2000); setSpeed(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); broadcastState(); return true; } /** * attach all the servos - this must be re-entrant and accomplish the * re-attachment when servos are detached * * @return */ public boolean attach() { sleep(InMoov.attachPauseMs); thumb.attach(); sleep(InMoov.attachPauseMs); index.attach(); sleep(InMoov.attachPauseMs); majeure.attach(); sleep(InMoov.attachPauseMs); ringFinger.attach(); sleep(InMoov.attachPauseMs); pinky.attach(); sleep(InMoov.attachPauseMs); wrist.attach(); return true; } public void startLeapTracking() { if (leap == null) { leap = (LeapMotion2) startPeer("leap");} leap.addLeapDataListener(this); leap.startTracking(); return; } @Override public String getDescription() { return "hand service for inmoov"; } // TODO - waving thread fun public void moveTo(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky) { moveTo(thumb, index, majeure, ringFinger, pinky, null); } public void moveTo(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) { if (log.isDebugEnabled()) { log.debug(String.format("%s.moveTo %d %d %d %d %d %d", getName(), thumb, index, majeure, ringFinger, pinky, wrist)); } this.thumb.moveTo(thumb); this.index.moveTo(index); this.majeure.moveTo(majeure); this.ringFinger.moveTo(ringFinger); this.pinky.moveTo(pinky); if (wrist != null) this.wrist.moveTo(wrist); } public void rest() { // initial positions setSpeed(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); thumb.rest(); index.rest(); majeure.rest(); ringFinger.rest(); pinky.rest(); wrist.rest(); } public void broadcastState() { // notify the gui thumb.broadcastState(); index.broadcastState(); majeure.broadcastState(); ringFinger.broadcastState(); pinky.broadcastState(); wrist.broadcastState(); } public void detach() { thumb.detach(); sleep(InMoov.attachPauseMs); index.detach(); sleep(InMoov.attachPauseMs); majeure.detach(); sleep(InMoov.attachPauseMs); ringFinger.detach(); sleep(InMoov.attachPauseMs); pinky.detach(); sleep(InMoov.attachPauseMs); wrist.detach(); } public void release() { detach(); thumb.releaseService(); index.releaseService(); majeure.releaseService(); ringFinger.releaseService(); pinky.releaseService(); wrist.releaseService(); } public void setSpeed(Float thumb, Float index, Float majeure, Float ringFinger, Float pinky, Float wrist) { this.thumb.setSpeed(thumb); this.index.setSpeed(index); this.majeure.setSpeed(majeure); this.ringFinger.setSpeed(ringFinger); this.pinky.setSpeed(pinky); this.wrist.setSpeed(wrist); } public void victory() { moveTo(150, 0, 0, 180, 180, 90); } public void devilHorns() { moveTo(150, 0, 180, 180, 0, 90); } public void hangTen() { moveTo(0, 180, 180, 180, 0, 90); } public void bird() { moveTo(150, 180, 0, 180, 180, 90); } public void thumbsUp() { moveTo(0, 180, 180, 180, 180, 90); } public void ok() { moveTo(150, 180, 0, 0, 0, 90); } public void one() { moveTo(150, 0, 180, 180, 180, 90); } public void two() { victory(); } public void three() { moveTo(150, 0, 0, 0, 180, 90); } public void four() { moveTo(150, 0, 0, 0, 0, 90); } public void five() { open(); } public void count() { one(); sleep(1); two(); sleep(1); three(); sleep(1); four(); sleep(1); five(); } public String getScript(String inMoovServiceName) { return String.format("%s.moveHand(\"%s\",%d,%d,%d,%d,%d,%d)\n", inMoovServiceName, side, thumb.getPos(), index.getPos(), majeure.getPos(), ringFinger.getPos(), pinky.getPos(), wrist.getPos()); } public void setPins(int thumb, int index, int majeure, int ringFinger, int pinky, int wrist) { log.info(String.format("setPins %d %d %d %d %d %d", thumb, index, majeure, ringFinger, pinky, wrist)); this.thumb.setPin(thumb); this.index.setPin(index); this.majeure.setPin(majeure); this.ringFinger.setPin(ringFinger); this.pinky.setPin(pinky); this.wrist.setPin(wrist); } public void close() { moveTo(130, 180, 180, 180, 180); } public void open() { rest(); } public void openPinch() { moveTo(0, 0, 180, 180, 180); } public void closePinch() { moveTo(130, 140, 180, 180, 180); } public Status test() { Status status = Status.info("starting %s %s test", getName(), getType()); try { if (arduino == null) { // gson encoding prevents this throw new Exception("arduino is null"); } if (!arduino.isConnected()) { throw new Exception("arduino not connected"); } thumb.moveTo(thumb.getPos() + 2); index.moveTo(index.getPos() + 2); majeure.moveTo(majeure.getPos() + 2); ringFinger.moveTo(ringFinger.getPos() + 2); pinky.moveTo(pinky.getPos() + 2); wrist.moveTo(wrist.getPos() + 2); } catch (Exception e) { status.addError(e); } status.addInfo("test completed"); return status; } public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); InMoovHand rightHand = new InMoovHand("r01"); Runtime.createAndStart("gui", "GUIService"); rightHand.connect("COM12"); rightHand.startService(); Runtime.createAndStart("webgui", "WebGUI"); // rightHand.connect("COM12"); TEST RECOVERY !!! rightHand.close(); rightHand.open(); rightHand.openPinch(); rightHand.closePinch(); rightHand.rest(); /* * GUIService gui = new GUIService("gui"); gui.startService(); */ } public void setSide(String side) { this.side = side; } public String getSide() { return side; } public long getLastActivityTime() { long lastActivityTime = Math.max(index.getLastActivityTime(), thumb.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, index.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, majeure.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, ringFinger.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, pinky.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, wrist.getLastActivityTime()); return lastActivityTime; } public boolean isAttached() { boolean attached = false; attached |= thumb.isAttached(); attached |= index.isAttached(); attached |= majeure.isAttached(); attached |= ringFinger.isAttached(); attached |= pinky.isAttached(); attached |= wrist.isAttached(); return attached; } public void setRest(int thumb, int index, int majeure, int ringFinger, int pinky){ setRest(thumb, index, majeure, ringFinger, pinky, null); } public void setRest(int thumb, int index, int majeure, int ringFinger, int pinky, Integer wrist) { log.info(String.format("setRest %d %d %d %d %d %d", thumb, index, majeure, ringFinger, pinky, wrist)); this.thumb.setRest(thumb); this.index.setRest(index); this.majeure.setRest(majeure); this.ringFinger.setRest(ringFinger); this.pinky.setRest(pinky); if (wrist != null){ this.wrist.setRest(wrist); } } public void map(int minX, int maxX, int minY, int maxY){ thumb.map(minX, maxX, minY, maxY); index.map(minX, maxX, minY, maxY); majeure.map(minX, maxX, minY, maxY); ringFinger.map(minX, maxX, minY, maxY); pinky.map(minX, maxX, minY, maxY); } public boolean save(){ super.save(); thumb.save(); index.save(); majeure.save(); ringFinger.save(); pinky.save(); wrist.save(); return true; } @Override public LeapData onLeapData(LeapData data) { //if (this.getSide() == "right") { index.moveTo(data.rightHand.index); thumb.moveTo(data.rightHand.thumb); pinky.moveTo(data.rightHand.pinky); ringFinger.moveTo(data.rightHand.ring); majeure.moveTo(data.rightHand.middle); return data; } }
package org.selfip.bkimmel.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.DigestOutputStream; import java.security.MessageDigest; import org.selfip.bkimmel.io.NullOutputStream; import org.selfip.bkimmel.io.StreamUtil; /** * Utility methods for working with classes. * @author brad */ public final class ClassUtil { /** * Gets an <code>InputStream</code> from which the specified class' * bytecode definition may be read. * @param cl The <code>Class</code> for which to get the stream. * @return An <code>InputStream</code> from which the specified class' * bytecode definition may be read. */ public static InputStream getClassAsStream(Class<?> cl) { String resourceName = cl.getName() + ".class"; return cl.getResourceAsStream(resourceName); } /** * Computes a digest from a class' bytecode. * @param cl The <code>Class</code> for which to compute the digest. * @param digest The <code>MessageDigest</code> to update. */ public static void getClassDigest(Class<?> cl, MessageDigest digest) { DigestOutputStream out = new DigestOutputStream(NullOutputStream.getInstance(), digest); try { writeClassTo(cl, out); } catch (IOException e) { e.printStackTrace(); throw new UnexpectedException(e); } } /** * Writes a class' bytecode to an <code>OutputStream</code>. * @param cl The <code>Class</code> to write. * @param out The <code>OutputStream</code> to write to. * @throws IOException If unable to write to <code>out</code>. */ public static void writeClassTo(Class<?> cl, OutputStream out) throws IOException { InputStream in = getClassAsStream(cl); StreamUtil.writeStream(in, out); } /** * Gets the outer class (a class with no enclosing class) that contains the * given class. * @param cl The <code>Class</code> for which to find the outer class. If * <code>class_</code> is an outer class, then <code>class_</code> is * returned. * @return The outer <code>Outer</code> class containing * <code>class_</code>. */ public static Class<?> getOuterClass(Class<?> cl) { Class<?> enclosingClass; while ((enclosingClass = cl.getEnclosingClass()) != null) { cl = enclosingClass; } return cl; } /** Declared private to prevent this class from being instantiated. */ private ClassUtil() {} }
package com.redomar.game.objects; import com.redomar.game.Game; public class Inventory { public static int x; public static int y; public static boolean open = false; public static boolean closing; public static boolean reset; public static boolean enabled; private static InventoryWindow inv_window = new InventoryWindow(); public static void activate() { x = (int) Game.getPlayer().getX(); y = (int) Game.getPlayer().getY(); if (Game.getLevel().getTile(x >> 3, y >> 3).getId() == 8) { if (enabled) { if (!open) { if (!closing) { System.out.println("Opened\nInside this Bag their is:" + inside()); open = true; Game.getPlayer().setMoving(false); Game.getInput().untoggle(true); inv_window.start(); } } else { if (closing) { Game.getPlayer().setMoving(true); Game.getInput().untoggle(false); inv_window.stop(); inv_window.getFrame().setVisible(false); inv_window.getFrame().stopFrame(); if (Game.getLevel().getTile(x >> 3, y >> 3).getId() == 8) { reset = true; System.out.println("rest"); } } } } } else { if (open == true || reset == true || closing == true) { reset = false; open = false; closing = false; } } } private static String inside() { String items = " "; for (Items item : Items.values()) { items = items + item.toString() + ", "; } return items; } }
package com.sudoku.grid.editor; import com.sudoku.data.model.Grid; import com.sudoku.grid.ihm_grid_cells.IhmGridLines.Flags; import com.sudoku.grid.ihm_popups.IhmPopupsList; import com.sudoku.grid.manager.IhmGridLayout; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; /** * @author mecton08 */ public abstract class IhmGridView extends IhmGridLayout { protected final BorderPane border; public IhmGridView(Flags flagStatus, Grid gr) { super(flagStatus, gr); border = new BorderPane(); getChildren().add(border); HBox topHBox = new HBox(); VBox leftVBox = new VBox(); VBox bottomHBox = new VBox(); VBox rightVBox = new VBox(); VBox centerVBox = new VBox(); // center a faire border.setTop(topHBox); border.setLeft(leftVBox); border.setBottom(bottomHBox); border.setRight(rightVBox); border.setCenter(centerVBox); //VBox centerLayout = (VBox)border.getCenter(); //centerLayout.getChildren().add(sudokuGrid); centerVBox.getChildren().add(gridLines); IhmPopupsList.init(150.0, 500.0, 10); final IhmPopupsList popupList = IhmPopupsList.getInstance(); rightVBox.getChildren().add(popupList); /* A IMPLEMENTER POUR LE BON FONCTIONNEMENT DE L'APPLICATION primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>(){ @Override public void handle(WindowEvent t) { if(t.getEventType() == WindowEvent.WINDOW_CLOSE_REQUEST){ popupList.finalize(); } } }); */ //border.setCenter(); } //protected textItemInput textInput; //protected textItemView textView; protected enum mode { Play, Edit } }
package org.zaproxy.zap.view; import java.awt.Component; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.commons.configuration.ConfigurationException; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.AbstractPanel; import org.parosproxy.paros.extension.option.OptionsParamView; import org.parosproxy.paros.model.Model; import org.parosproxy.paros.view.TabbedPanel; /** * A tabbed panel that adds the option to hide individual tabs via a cross button on the tab. */ public class TabbedPanel2 extends TabbedPanel { private static final long serialVersionUID = 1L; private static final Icon CLOSE_TAB_GREY_ICON = new ImageIcon( TabbedPanel2.class.getResource("/resource/icon/fugue/cross-small-grey.png")); private static final Icon CLOSE_TAB_RED_ICON = new ImageIcon( TabbedPanel2.class.getResource("/resource/icon/fugue/cross-small-red.png")); private List<Component> fullTabList = new ArrayList<Component>(); private List<Component> removedTabList = new ArrayList<Component>(); private final Logger logger = Logger.getLogger(TabbedPanel2.class); public TabbedPanel2() { super(); this.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { setCloseButtonStates(); } }); } private void setCloseButtonStates() { // Hide all 'close' buttons except for the selected tab for (int i = 0; i < this.getTabCount(); i++) { Component tabCom = this.getTabComponentAt(i); if (tabCom != null && tabCom instanceof JPanel) { JPanel jp = (JPanel) tabCom; if (jp.getComponentCount() > 1) { Component c = ((JPanel)tabCom).getComponent(1); if (c != null && c instanceof JButton) { ((JButton)c).setEnabled(i == getSelectedIndex()); ((JButton)c).setVisible(i == getSelectedIndex()); } } } } } /** * Returns a name save to be used in the XML config file * @param str * @return */ private String safeName(String str) { return str.replaceAll("[^A-Za-z0-9]", ""); } private boolean isTabVisible(Component c) { return Model.getSingleton().getOptionsParam().getConfig().getBoolean( OptionsParamView.TAB_OPTION + "." + safeName(c.getName()), true); } private void saveTabState(Component c, boolean visible) { Model.getSingleton().getOptionsParam().getConfig().setProperty( OptionsParamView.TAB_OPTION + "." + safeName(c.getName()), visible); try { Model.getSingleton().getOptionsParam().getConfig().save(); } catch (ConfigurationException e) { logger.error(e.getMessage(), e); } } @Override public void addTab(String title, Icon icon, final Component c) { boolean hideable = false; if (c instanceof AbstractPanel) { hideable = ((AbstractPanel)c).isHideable(); } this.addTab(title, icon, c, hideable); } public void setVisible(Component c, boolean visible) { if (visible) { this.saveTabState(c, true); if (this.removedTabList.contains(c)) { // Work out the index to add it back in int index = this.fullTabList.indexOf(c); while (index >= 0) { if (index > 0 && ! this.removedTabList.contains(this.fullTabList.get(index -1))) { // Found the first preceding tab that isnt hidden break; } index } if (c instanceof AbstractPanel) { AbstractPanel panel = (AbstractPanel)c; this.addTab(c.getName(), panel.getIcon(), panel, true, index+1); } else { this.addTab(c.getName(), null, c, true, index); } c.setVisible(true); this.removedTabList.remove(c); } } else { remove(c); this.removedTabList.add(c); this.saveTabState(c, false); } } public void addTab(String title, Icon icon, final Component c, boolean hideable) { this.addTab(title, icon, c, hideable, this.getTabCount()); } public void addTab(String title, Icon icon, final Component c, boolean hideable, int index) { if (c.getName() == null) { c.setName(title); } if (c instanceof AbstractPanel) { ((AbstractPanel)c).setParent(this); } if (index > this.getTabCount()) { index = this.getTabCount(); } super.insertTab(title, icon, c, null, index); if ( ! this.fullTabList.contains(c)) { this.fullTabList.add(c); } int pos = this.indexOfComponent(c); // Create a FlowLayout so that the buttons are not too large FlowLayout f = new FlowLayout(FlowLayout.CENTER, 0, 0); // Make a small JPanel with the layout and make it non-opaque JPanel pnlTab = new JPanel(f); pnlTab.setOpaque(false); // Add a JLabel with title and the left-side tab icon JLabel lblTitle = new JLabel(title); lblTitle.setIcon(icon); // Create a JButton for the close tab button JButton btnClose = new JButton(); btnClose.setOpaque(false); // Configure icon and rollover icon for button btnClose.setRolloverIcon(CLOSE_TAB_RED_ICON); btnClose.setRolloverEnabled(true); btnClose.setToolTipText(Constant.messages.getString("all.button.close")); btnClose.setIcon(CLOSE_TAB_GREY_ICON); // Set border null so the button doesn't make the tab too big btnClose.setBorder(null); // Make sure the button can't get focus, otherwise it looks funny btnClose.setFocusable(false); // All close buttons start off hidden and disabled - they are enabled when the tab is selected btnClose.setEnabled(false); btnClose.setVisible(false); // Put the panel together pnlTab.add(lblTitle); if (hideable) { // Only include the close button is the tab is hideable pnlTab.add(btnClose); } // Now assign the component for the tab this.setTabComponentAt(pos, pnlTab); // Add the listener that removes the tab ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // The component parameter must be declared "final" so that it // can be // referenced in the anonymous listener class like this. setVisible(c, false); } }; btnClose.addActionListener(listener); if (! this.isTabVisible(c)) { // Only add back visible tabs setVisible(c, false); } } public void setIconAt(int index, Icon icon) { Component tabCom = this.getTabComponentAt(index); if (tabCom != null && tabCom instanceof JPanel) { Component c = ((JPanel)tabCom).getComponent(0); if (c != null && c instanceof JLabel) { ((JLabel)c).setIcon(icon); } } } public List<Component> getTabList() { return Collections.unmodifiableList(this.fullTabList); } public void removeTab(AbstractPanel panel) { this.remove(panel); this.fullTabList.remove(panel); this.removedTabList.remove(panel); } }
package water.rapids; import water.*; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.NewChunk; import water.fvec.Vec; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.H2OKeyNotFoundArgumentException; import java.util.ArrayList; import java.util.Arrays; /** * Each node in the syntax tree knows how to parse a piece of text from the passed tree. */ abstract public class AST extends Iced { String[] _arg_names; AST[] _asts; AST parse_impl(Exec e) { throw H2O.fail("Missing parse_impl for "+this.getClass()); } abstract String opStr(); abstract void exec(Env e); abstract String value(); abstract int type(); abstract AST make(); public int numChildren() { return _asts.length; } // Must "apply" each arg, then put the results into ASTOp/UDF /** * Walk an AST and execute. */ Env treeWalk(Env e) { // First check if we're a top-level node of type astop if (this instanceof ASTOp) { if (this instanceof ASTBinOp) { // Exec the right branch _asts[1].treeWalk(e); // Exec the left branch _asts[0].treeWalk(e); // Perform the binary operation ((ASTBinOp) this).apply(e); } else if (this instanceof ASTUniPrefixOp) { for (int i = 0; i < _asts.length; ++i) _asts[i].treeWalk(e); ((ASTUniPrefixOp) this).apply(e); } else if (this instanceof ASTReducerOp) { for (int i = 0; i < _asts.length; ++i) _asts[i].treeWalk(e); ((ASTReducerOp) this).apply(e); } else if (this instanceof ASTLs) { ((ASTLs) this).apply(e); } else if (this instanceof ASTFunc) { ((ASTFunc) this).apply(e); } else if (this instanceof ASTApply) { _asts[0].treeWalk(e); // push the frame we're `apply`ing over ((ASTApply) this).apply(e); } else if(this instanceof ASTMMult) { _asts[1].treeWalk(e); _asts[0].treeWalk(e); ((ASTMMult)this).apply(e); } else if(this instanceof ASTTranspose) { _asts[0].treeWalk(e); ((ASTTranspose)this).apply(e); } else if (this instanceof ASTddply) { _asts[0].treeWalk(e); ((ASTddply)this).apply(e); } else if (this instanceof ASTMerge) { _asts[1].treeWalk(e); _asts[0].treeWalk(e); ((ASTMerge)this).apply(e); } else { throw H2O.fail("Unknown AST in tree walk: " + this.getClass()); // TODO: do the udf op thing: capture env... } // Check if there's an assignment } else if (this instanceof ASTAssign) { // Exec the right branch _asts[1].treeWalk(e); // Do the assignment this.exec(e); // Special case exec => apply for assignment // Check if we have an ID node (can be an argument, or part of an assignment). } else if (this instanceof ASTId) { ASTId id = (ASTId) this; assert id.isValid(); if (id.isLookup()) { // lookup the ID and return an AST AST ast = e.lookup(id); // e.put(id._id, ast.type(), id._id); ast.exec(e); } else if (id.isLocalSet() || id.isGlobalSet()) { e.put(((ASTId) this)._id, Env.ID, ""); id.exec(e); } else { throw new H2OIllegalArgumentException("Got a bad identifier: '" + id.value() + "'. It has no type '!' or '$'.", "Got a bad identifier: '" + id.value() + "'. It has no type '!' or '$'." + " AST: " + this); } } else if(this instanceof ASTStatement) { if (this instanceof ASTIf) { this.exec(e); } else if (this instanceof ASTElse) { this.exec(e); } else if (this instanceof ASTFor) { throw H2O.unimpl("`for` loops are currently unsupported."); } else if (this instanceof ASTReturn) { this.exec(e); return e; } else this.exec(e); // Check if we have a slice. } else if(this instanceof ASTSlice) { _asts[0].treeWalk(e); // push hex _asts[1].treeWalk(e); // push rows _asts[2].treeWalk(e); // push cols this.exec(e); // do the slice // Check if String, Num, Null, Series, Key, Span, Frame, or Raft } else if (this instanceof ASTString || this instanceof ASTNum || this instanceof ASTNull || this instanceof ASTSeries || this instanceof ASTKey || this instanceof ASTSpan || this instanceof ASTFrame || this._asts[0] instanceof ASTFrame || this instanceof ASTDelete ) { this.exec(e); } else { throw H2O.fail("Unknown AST class: " + this.getClass());} return e; } protected StringBuilder indent( StringBuilder sb, int d ) { for( int i=0; i<d; i++ ) sb.append(" "); return sb.append(' '); } StringBuilder toString( StringBuilder sb, int d ) { return indent(sb,d).append(this); } } class ASTId extends AST { String opStr() { switch( _type ) { case '$': return "$"; case '!': return "!"; case '&': return "&"; default: throw new IllegalArgumentException("No such type for ID: " + _type); } } final String _id; final char _type; // either '$' or '!' or '&' ASTId(char type, String id) { _type = type; _id = id; } AST parse_impl(Exec E) { String id = E.isQuoted(E.peek()) ? E.parseString(E.getQuote()) : E.parseID(); // allows for quoted ID here... AST ast = Env.staticLookup(new ASTId(_type, id)); return ast; } @Override public String toString() { return _type+_id; } @Override void exec(Env e) { e.push(new ValId(_type, _id)); } // should this be H2O.fail() ?? @Override int type() { return Env.ID; } @Override String value() { return _id; } boolean isLocalSet() { return _type == '&'; } boolean isGlobalSet() { return _type == '!'; } boolean isLookup() { return _type == '%'; } boolean isValid() { return isLocalSet() || isGlobalSet() || isLookup(); } @Override ASTId make() { return new ASTId(_type, ""); } } class ASTKey extends AST { String opStr() {throw H2O.unimpl("No such opStr for ASTKey."); } final String _key; ASTKey(String key) { _key = key; } ASTKey parse_impl(Exec E) { if (!E.hasNext()) throw new IllegalArgumentException("End of input unexpected. Badly formed AST."); return new ASTKey(E.parseID()); } @Override public String toString() { return _key; } @Override void exec(Env e) { (new ASTFrame(_key)).exec(e); } @Override int type () { return Env.NULL; } @Override String value() { return _key; } @Override ASTKey make() { return new ASTKey(""); } } class ASTFrame extends AST { String opStr() {return "%";} final String _key; final Frame _fr; boolean isFrame; boolean _g; ASTFrame(Frame fr) { _key = fr._key == null ? null : fr._key.toString(); _fr = fr; } ASTFrame(Key key) { this(key.toString()); } ASTFrame(String key) { Key k = Key.make(key); Keyed val = DKV.getGet(k); if (val == null) throw new H2OKeyNotFoundArgumentException(key); _key = key; _fr = (isFrame=(val instanceof Frame)) ? (Frame)val : new Frame((Vec)val); _g = true; } @Override public String toString() { return "Frame with key " + _key + ". Frame: :" +_fr.toString(); } @Override void exec(Env e) { if (_key != null) { e._locked.add(Key.make(_key)); if (e.isGlobal()) e._global._frames.put(_key, _fr); else e._local._frames.put(_key, _fr); } e.addKeys(_fr); e.push(new ValFrame(_fr, !isFrame, _g)); } @Override int type () { return Env.ARY; } @Override String value() { return _key; } boolean isGlobal() { return _g; } @Override ASTFrame make() { throw H2O.unimpl(); } } class ASTNum extends AST { final double _d; ASTNum(double d) { _d = d; } String opStr() {return " ASTNum parse_impl(Exec E) { try { return new ASTNum(Double.valueOf(E.parseID())); } catch (NumberFormatException e) { e.printStackTrace(); throw new IllegalArgumentException("Unexpected numerical argument. Badly formed AST."); } } @Override public String toString() { return Double.toString(_d); } @Override void exec(Env e) { e.push(new ValNum(_d)); } @Override int type () { return Env.NUM; } @Override String value() { return Double.toString(_d); } double dbl() { return _d; } @Override ASTNum make() { return new ASTNum(0); } } /** * ASTSpan parses phrases like 1:10. */ class ASTSpan extends AST { String opStr() { return ":"; } final long _min; final long _max; final ASTNum _ast_min; final ASTNum _ast_max; boolean _isCol; boolean _isRow; ASTSpan() {_min=0;_max=0;_ast_max=null;_ast_min=null;} ASTSpan(ASTNum min, ASTNum max) { _ast_min = min; _ast_max = max; _min = (long)min._d; _max = (long)max._d; if( _min <= 0 && _max <= 0) { if (_max > _min) throw new IllegalArgumentException("max>min: All negative, incorrect order."); } else { if (_min > _max) throw new IllegalArgumentException("min > max: min <= max for `:` operator."); } } ASTSpan(long min, long max) { _ast_min = new ASTNum(min); _ast_max = new ASTNum(max); _min = min; _max = max; if( _min < 0 && _max < 0) { if (_max > _min) throw new IllegalArgumentException("max>min: All negative, incorrect order."); } else { if (_min > _max) throw new IllegalArgumentException("min > max: min <= max for `:` operator."); } } ASTSpan parse_impl(Exec E) { AST l = E.parse(); AST r = E.parse(); E.eatEnd(); // eat ending ')' return new ASTSpan((ASTNum)l, (ASTNum)r); } boolean contains(long a) { if (all_neg()) return _max <= a && a <= _min; return _min <= a && a <= _max; } boolean isColSelector() { return _isCol; } boolean isRowSelector() { return _isRow; } void setSlice(boolean row, boolean col) { _isRow = row; _isCol = col; } @Override void exec(Env e) { ValSpan v = new ValSpan(_ast_min, _ast_max); v.setSlice(_isRow, _isCol); e.push(v); } @Override String value() { return null; } @Override int type() { return Env.SPAN; } @Override public String toString() { return _min + ":" + _max; } long length() { return _max - _min + 1; } long[] toArray() { long[] res = new long[(int)_max - (int)_min + 1]; long min = _min; for (int i = 0; i < res.length; ++i) res[i] = min++; return res; } boolean all_neg() { return _min<0||_max<0; } boolean all_pos() { return !all_neg(); } boolean isNum() { return _min == _max; } long toNum() { return _min; } // @Override public AutoBuffer write_impl(AutoBuffer ab) { // ab.put8(_min); // ab.put8(_max); // return ab; // @Override public ASTSpan read_impl(AutoBuffer ab) { // return new ASTSpan(ab.get8(), ab.get8()); @Override ASTSpan make() {return new ASTSpan(new ASTNum(0),new ASTNum(0)); } } class ASTSeries extends AST { String opStr() { return "{";} final long[] _idxs; final ASTSpan[] _spans; final double[] _d; boolean _isCol; boolean _isRow; int[] _order; // a sequence of 0s and 1s. 0 -> span; 1 -> index ASTSeries(long[] idxs, double[] d, ASTSpan[] spans) { _idxs=idxs; _d=d; _spans=spans; } ASTSeries(long[] idxs, ASTSpan[] spans) { _idxs = idxs; _d=null; _spans = spans; } ASTSeries parse_impl(Exec E) { ArrayList<Long> l_idxs = new ArrayList<>(); ArrayList<ASTSpan> s_spans = new ArrayList<>(); if (!E.hasNext()) throw new IllegalArgumentException("End of input unexpected. Badly formed AST."); String[] strs = E.parseString('}').split(";"); _order = new int[strs.length]; int o = 0; for (String s : strs) { if (s.charAt(0) == '(') { _order[o] = 0; // get a non ASTSpan as next elt try { s_spans.add((ASTSpan) (new Exec(s, null)).parse()); } catch (ClassCastException e) { try { ASTOp anum = (ASTOp) (new Exec(s, null)).parse(); long n = (long)anum.treeWalk(E._env).popDbl(); _order[o] = 1; l_idxs.add(n); } catch (ClassCastException e2) { throw new IllegalArgumentException("AST in sequence did not evaluate to a range or number.\n Only (: min max), #, and ASTs that evaluate to # are valid."); } } o++; } else { _order[o++] = 1; if (s.charAt(0) == '#') s = s.substring(1, s.length()); try { Long.valueOf(s); } catch (Exception e) { throw new IllegalArgumentException("Invalid input. Value was not long or int: "+s); } l_idxs.add(Long.valueOf(s)); } } long[] idxs = new long[l_idxs.size()]; ASTSpan[] spans = new ASTSpan[s_spans.size()]; for (int i = 0; i < idxs.length; ++i) idxs[i] = l_idxs.get(i); for (int i = 0; i < spans.length; ++i) spans[i] = s_spans.get(i); ASTSeries aa = new ASTSeries(idxs, spans); aa._order = _order; return aa; } boolean contains(long a) { if (_spans != null) for (ASTSpan s : _spans) if (s.contains(a)) return true; if (_idxs != null) for (long l : _idxs) if (l == a) return true; return false; } boolean isColSelector() { return _isCol; } boolean isRowSelector() { return _isRow; } void setSlice(boolean row, boolean col) { _isRow = row; _isCol = col; } @Override void exec(Env e) { ValSeries v = new ValSeries(_idxs, _d, _spans); v._order = _order; v.setSlice(_isRow, _isCol); e.push(v); } @Override String value() { return null; } @Override int type() { return Env.SERIES; } @Override public String toString() { String res = "c("; if (_spans != null) { for (ASTSpan s : _spans) { res += s.toString(); res += ","; } if (_idxs == null) res = res.substring(0, res.length() - 1); // remove last comma? } if (_idxs != null) { for (long l : _idxs) { res += l; res += ","; } res = res.substring(0, res.length() - 1); // remove last comma. } res += ")"; return res; } long[] toArray() { int res_length = 0; if (_spans != null) for (ASTSpan s : _spans) res_length += (int) s._max - (int) s._min + 1; if (_idxs != null) res_length += _idxs.length; long[] res = new long[res_length]; int cur = 0; if (_spans != null) { for (ASTSpan s : _spans) { long[] l = s.toArray(); for (int i = 0; i < l.length; ++i) res[cur++] = l[i]; } } if (_idxs != null) { for (int i = 0; i < _idxs.length; ++i) res[cur++] = _idxs[i]; } return res; } // @Override public AutoBuffer write_impl(AutoBuffer ab) { // ab.putA8(_idxs); // ab.put1(_spans.length); // for (int i = 0; i < _spans.length; ++i) { // ab = _spans[i].write_impl(ab); // ab.putZ(_isCol); // ab.putA4(_order); // return ab; // @Override public ASTSeries read_impl(AutoBuffer ab) { // long[] idxs = ab.getA8(); // int nspans = ab.get1(); // ASTSpan[] spans = new ASTSpan[nspans]; // for (int i = 0; i < nspans; ++i) { // spans[i] = ab.get(ASTSpan.class); // boolean isCol = ab.getZ(); // int[] order = ab.getA4(); // ASTSeries series = new ASTSeries(idxs, spans); // series._order = order; // series._isCol = isCol; // series._isRow = !isCol; // return series; @Override ASTSeries make() { return new ASTSeries(null, null); } } class ASTStatement extends AST { @Override ASTStatement make() { return new ASTStatement(); } String opStr() {return ","; } // must parse all statements: {(ast);(ast);(ast);...;(ast)} @Override ASTStatement parse_impl( Exec E ) { ArrayList<AST> ast_ary = new ArrayList<AST>(); // an ASTStatement is an array of ASTs. May have ASTStatements within ASTStatements. while( !E.isEnd() ) ast_ary.add(E.parse()); E.eatEnd(); // eat the ending ')' ASTStatement res = (ASTStatement) clone(); res._asts = ast_ary.toArray(new AST[ast_ary.size()]); return res; } @Override void exec(Env env) { ArrayList<Frame> cleanup = new ArrayList<>(); if( _asts.length==0 ) { env.push(new ValNull()); return; } for( int i=0; i<_asts.length-1; i++ ) { if (_asts[i] instanceof ASTReturn) { _asts[i].treeWalk(env); return; } _asts[i].treeWalk(env); // Execute the statements by walking the ast env.pop(); } _asts[_asts.length-1].treeWalk(env); // Return final statement as result for (Frame f : cleanup) f.delete(); } @Override String value() { return null; } @Override int type() {return 0; } @Override public String toString() { return toString(new StringBuilder(""), 0).toString() + ";;;"; } @Override public StringBuilder toString( StringBuilder sb, int d ) { for (int i = 0; i < _asts.length - 1; i++) _asts[i].toString(sb, d + 1).append(";\n"); return _asts[_asts.length - 1].toString(sb, d + 1); } } class ASTReturn extends ASTStatement { protected AST _stmnt; ASTReturn() {} @Override ASTReturn parse_impl(Exec E) { if (!E.hasNext()) throw new IllegalArgumentException("End of input unexpected. Badly formed AST."); AST stmnt = E.parse(); E.eatEnd(); // eat the ending ')' ASTReturn res = (ASTReturn) clone(); res._stmnt = stmnt; return res; } @Override void exec(Env e) { _stmnt.treeWalk(e); } @Override String value() { return null; } @Override int type() { return 0; } } class ASTIf extends ASTStatement { protected AST _pred; protected ASTElse _else = null; ASTIf() {} // (if pred body) @Override ASTIf parse_impl(Exec E) { // parse the predicate AST pred = E.parse(); ASTStatement statement = super.parse_impl(E); ArrayList<AST> ast_list = new ArrayList<>(); for (int i = 0; i < statement._asts.length; ++i) { if (statement._asts[i] instanceof ASTElse) _else = (ASTElse)statement._asts[i]; else ast_list.add(statement._asts[i]); } E.eatEnd(); // eat the ending ')' ASTIf res = (ASTIf) clone(); res._pred = pred; res._asts = ast_list.toArray(new AST[ast_list.size()]); return res; } @Override void exec(Env e) { Env captured = e.capture(); captured = _pred.treeWalk(captured); if (captured.isAry()) throw new IllegalArgumentException("Frames not supported in the if's condition."); double v = captured.popDbl(); captured.popScope(); if (v == 0) if (_else == null) return; else _else.exec(e); else super.exec(e); // run the statements } @Override String value() { return null; } @Override int type() { return 0; } } class ASTElse extends ASTStatement { // (else body) ASTElse() {} @Override ASTElse parse_impl(Exec E) { if (!E.hasNext()) throw new IllegalArgumentException("End of input unexpected. Badly formed AST."); ASTStatement statements = super.parse_impl(E); E.eatEnd(); // eat the ending ')' ASTElse res = (ASTElse)clone(); res._asts = statements._asts; return res; } @Override void exec(Env e) { super.exec(e); } @Override String value() { return null; } @Override int type() { return 0; } } class ASTFor extends ASTStatement { protected int _start; protected int _end; // protected Object[] confusion_matrix; // (for #start #end body) @Override ASTFor parse_impl(Exec E) { if (!E.hasNext()) throw new IllegalArgumentException("End of input unexpected. Badly formed AST."); int s = (int)((ASTNum)E.skipWS().parse())._d; if (!E.hasNext()) throw new IllegalArgumentException("End of input unexpected. Badly formed AST."); int e = (int)((ASTNum)E.skipWS().parse())._d; ASTStatement stmts = super.parse_impl(E); ASTFor res = (ASTFor)clone(); res._asts = stmts._asts; res._start = s; res._end = e; return res; } @Override void exec(Env e) { for (int i = _start; i < _end; ++i) super.exec(e); } @Override String value() { return null; } @Override int type() { return 0; } } class ASTWhile extends ASTStatement { // protected AST _pred; // (while pred body) @Override ASTWhile parse_impl(Exec E) { throw H2O.unimpl("while loops are not supported."); } } // AST pred = E.parse(); // ASTStatement statement = super.parse_impl(E); // ASTWhile res = (ASTWhile) clone(); // res._pred = pred; // res._asts = statement._asts; // return res; // @Override void exec(Env e) { // while(checkPred(e)) { // private boolean checkPred(Env e) { // Env captured = e.capture(); // captured = _pred.treeWalk(captured); // double v = captured.popDbl(); // captured.popScope(); // if (v == 0) return false; // return true; // @Override String value() { return null; } // @Override int type() { return 0; } class ASTString extends AST { @Override ASTString make() { return new ASTString(_eq,""); } String opStr() { return String.valueOf(_eq); } final String _s; final char _eq; ASTString(char eq, String s) { _eq = eq; _s = s; } AST parse_impl(Exec E) { if (!E.hasNext()) throw new IllegalArgumentException("End of input unexpected. Badly formed AST."); ASTString as = new ASTString(_eq, E.parseString(_eq)); return Env.staticLookup(as); } @Override public String toString() { return _s; } @Override void exec(Env e) { e.push(new ValStr(_s)); } @Override int type () { return Env.STR; } @Override String value() { return _s; } } class ASTNull extends AST { @Override ASTNull make() { return new ASTNull(); } String opStr() { throw H2O.unimpl();} ASTNull() {} @Override void exec(Env e) { e.push(new ValNull());} @Override String value() { return null; } @Override int type() { return Env.NULL; } } /** * The ASTAssign Class * * Handle the four cases of assignment: * * 1. Whole frame assignment: hexA = RHS * 2. Three flavors of slot assignment: * A. hex[,col(s)] = RHS // column(s) re-assign * B. hex[row(s),] = RHS // row(s) re-assign * C. hex[row(s),col(s)] = RHS // row(s) AND col(s) re-assign * * NB: RHS is any arbitrary (but valid) AST * * This also supports adding a new column. * (e.g., hex$new_column &lt;- 10, creates "new_column" vector in hex with values set to 10) * * The RHS is already on the stack, the LHS is not yet on the stack. * * Note about Categorical/Non-Categorical Vecs: * * If the vec is enum, then the RHS must also be enum (if enum is not in domain of LHS produce NAs). * If the vec is numeric, then the RHS must also be numeric (if enum, then produce NAs or throw IAE). */ class ASTAssign extends AST { @Override ASTAssign make() { return new ASTAssign(); } String opStr() { return "="; } ASTAssign parse_impl(Exec E) { AST l; // LHS parsing // LHS can be one of six things: // !ID, &ID, "ID" / 'ID', %ID, ID, or (...) // ! means do a dkv put -- essentially keep the result global for all the world // & means do a local put -- do not keep result around // " and ' mean parse and do local put (semantically an '&') // nothing on the ID implies & semantics // % on the LHS is semantically equivalent to & -- does not overwrite the global with the same ID // ( implies that the LHS is a new AST -- result locality depends on the AST if (E.isSpecial(E.peek())) { // LHS is NOT an AST... no slice assignment boolean putkv = E.peek() == '!'; boolean skip1 = (E.peek() == '\'' || E.peek() == '\"'); // skip one more at the end if quoted ID... E._x++; // skip the special char... l = new ASTId(putkv ? '!' : '&', E.parseID()); // parse the ID on the left, or could be a column, or entire frame, or a row if( skip1 ) E._x++; } else { if( E.peek() == '(' ) l = E.parse(); // thing on the LHS is an AST => slot assign [<- else l = new ASTId('&', E.parseID()); // else got plain old ID, assume local put } // RHS parsing if (!E.hasNext()) throw new IllegalArgumentException("Missing RHS in ASTAssign."); AST r = E.parse(); // parse double, String, or Frame on the right E.eatEnd(); // eat ending ')' // clone and return ASTAssign res = (ASTAssign)clone(); res._asts = new AST[]{l,r}; return res; } @Override int type () { return -1; } @Override String value() { throw H2O.unimpl("No value() for ASTAssign."); } private static boolean in(String s, String[] matches) { return Arrays.asList(matches).contains(s); } private static void replaceRow(Chunk[] chks, int row, double d0, String s0, long[] cols) { for (int c = 0; c < cols.length; ++c) { int col = (int)cols[c]; // have an enum column if (chks[col].vec().isEnum()) { if (s0 == null) { chks[col].setNA(row); continue; } String[] dom = chks[col].vec().domain(); if (in(s0, dom)) { chks[col].set(row, Arrays.asList(dom).indexOf(s0)); continue; } chks[col].setNA(row); continue; // have a numeric column } else if (chks[col].vec().isNumeric()) { if (Double.isNaN(d0) || s0 != null) { chks[col].setNA(row); continue; } chks[col].set(row, d0); continue; } } } // replace thing on the RHS -> LHS. set from cs to ary private static void replaceRow(Chunk[] cs, int row0, long row_id, long[] cols, Frame ary) { for (int c = 0; c < cols.length; ++c) { int col = (int)cols[c]; // got an enum trying to set into enum // got an enum trying to set into something else -> NA if (cs[c].vec().isEnum()) { if (ary.vecs()[col].isEnum()) { ary.vecs()[col].set(row_id, cs[c].atd(row0)); } else { ary.vecs()[col].set(row_id, Double.NaN); } } // got numeric trying to set into something non-numeric -> NA // got numeric trying to set into numeric if (cs[c].vec().isNumeric()) { if (ary.vecs()[col].isNumeric()) { ary.vecs()[col].set(row_id, cs[c].atd(row0)); } else { ary.vecs()[col].set(row_id, Double.NaN); } } } } private static void assignRows(Env e, Object rows, final Frame lhs_ary, Object cols) { // For every col at the range of indexes, set the value to be the rhs, which is expected to be a scalar (or possibly a string). // If the rhs is a double or str, then fill with doubles or NA when type is Categorical. final long[] cols0 = cols == null ? new long[lhs_ary.numCols()] : (long[])cols; if (cols == null) for (int i = 0; i < lhs_ary.numCols(); ++i) cols0[i] = i; if (!e.isAry()) { String s = null; double d = Double.NaN; if (e.isStr()) s = e.popStr(); else if (e.isNum()) d = e.popDbl(); else if (e.isNul()) d = Double.NaN; else throw new IllegalArgumentException("Did not get a single number or factor level on the RHS of the assignment. Got type #:" + Env.typeToString(e.peekType())); final double d0 = d; final String s0 = s; // Case: Have a long[] of rows if (rows instanceof long[]) { final long[] rows0 = (long[]) rows; // MRTask over the lhs array new MRTask() { @Override public void map(Chunk[] chks) { for (int row = 0; row < chks[0]._len; ++row) if (Arrays.asList(rows0).contains(row)) replaceRow(chks, row, d0, s0, cols0); } }.doAll(lhs_ary); e.push(new ValFrame(lhs_ary)); return; // Case: rows is a Frame -- in this case it's expected to be a predicate vec } else if (rows instanceof Frame) { Frame rr = new Frame(lhs_ary).add((Frame) rows); if (rr.numCols() != lhs_ary.numCols() + 1) throw new IllegalArgumentException("Got multiple columns for row predicate."); // treat rows as a bit vec, nonzeros mean rows should be replaced with s0 or d0, 0s mean continue new MRTask() { @Override public void map(Chunk[] cs, NewChunk[] ncs) { Chunk pred = cs[cs.length - 1]; int rows = cs[0]._len; for (int r = 0; r < rows; ++r) if (pred.atd(r) != 0) replaceRow(cs, r, d0, s0, cols0); } }.doAll(rr); e.push(new ValFrame(lhs_ary)); return; } else throw new IllegalArgumentException("Invalid row selection. (note: RHS was a constant)"); // If the rhs is an array, then fail if `height` of the rhs != rows.length. Otherwise, fetch-n-fill! (expensive) } else { // RHS shape must match LHS shape... // Example: hex[1:50,] <- hex2[90:100,] will fail, but swap out 90:100 w/ 101:150 should pass // LHS.numCols() == RHS.numCols() // mismatch in types results in NA final Frame rhs_ary = e.popAry(); if ( ( cols == null && rhs_ary.numCols() != lhs_ary.numCols()) || (cols != null && rhs_ary.numCols() != ((long[]) cols).length ) ) throw new IllegalArgumentException("Right-hand frame has does not match the number of columns required in the assignment to the left-hand side." ); if (rhs_ary.numRows() > lhs_ary.numRows()) throw new IllegalArgumentException("Right-hand side frame has more rows than the left-hand side."); // case where rows is a long[] if (rows instanceof long[]) { final long[] rows0 = (long[])rows; if (rows0.length != rhs_ary.numRows()) throw new IllegalArgumentException("Right-hand side array does not match the number of rows selected in the left-hand side."); // rows0 will have access to the index of the row to grab, use this to get the correct row from the rhs ary // MRTask over the lhs array new MRTask() { @Override public void map(Chunk[] chks) { for (int row = 0; row < chks[0]._len; ++row) { if (Arrays.asList(rows0).contains(row)) { long row_id = (long)Arrays.asList(rows0).indexOf(row); for (int c = 0; c < cols0.length; ++c) { int col = (int)cols0[c]; // vec is enum if (chks[col].vec().isEnum()) if (!rhs_ary.vecs()[col].isEnum()) { chks[col].setNA(row); continue; } // else vec is numeric else if (chks[col].vec().isNumeric()) if (!rhs_ary.vecs()[col].isNumeric()) { chks[col].setNA(row); continue; } chks[col].set(row, rhs_ary.vecs()[col].at(row_id)); } } } } }.doAll(lhs_ary); e.push(new ValFrame(lhs_ary)); return; // case where rows is a Frame } else if (rows instanceof Frame) { // MRTask over the lhs frame + rows predicate vec. the value of the predicate vec will be 1 + the row index // in the corresponding rhs frame // MRTask over the pred vec to collapse to a dense set of row IDs if (((Frame)rows).numCols() != 1) throw new IllegalArgumentException("Got multiple columns for row predicate."); Frame pred = new MRTask() { @Override public void map(Chunk c, NewChunk nc) { for (int r = 0; r < c._len; ++r) { double d = c.atd(r); if (d != 0) nc.addNum(d); } } }.doAll(1, (Frame)rows).outputFrame(null, null); if (pred.numRows() != rhs_ary.numRows()) throw new IllegalArgumentException("Right-hand side array does not match the number of rows selected in the left-hand side."); Frame rr = new Frame(rhs_ary).add(pred); // MRTask over the RHS ary, pushing data out to the LHS ary based on the pred vec new MRTask() { @Override public void map(Chunk[] cs) { Chunk pred = cs[cs.length-1]; int rows = cs[0]._len; for (int r=0; r<rows; ++r) { long row_id = (long)pred.atd(r) - 1; replaceRow(cs, r, row_id, cols0, lhs_ary); } } }.doAll(rr); e.push(new ValFrame(lhs_ary)); return; } else throw new IllegalArgumentException("Invalid row selection. (note: RHS was Frame"); } } @Override void exec(Env e) { // Case 1: Whole Frame assignment // Check if lhs is ID, update the symbol table; Otherwise it's a slice! if( this._asts[0] instanceof ASTId ) { ASTId id = (ASTId)this._asts[0]; assert id.isGlobalSet() || id.isLocalSet() : "Expected to set result into the LHS!."; // RHS is a frame if (e.isAry() || (id.isGlobalSet() && e.isNum())) { Frame f = e.isAry() ? e.popAry() // pop without lowering counts : new Frame(null, new String[]{"C1"}, new Vec[]{Vec.makeCon(e.popDbl(), 1)}); Key k = Key.make(id._id); Vec[] vecs = f.vecs(); if (id.isGlobalSet()) vecs = f.deepSlice(null,null).vecs(); Frame fr = new Frame(k, f.names(), vecs); if (id.isGlobalSet()) DKV.put(k, fr); e._locked.add(k); e.addKeys(fr); if (!e.isGlobal()) e._local._frames.put(k.toString(), fr); else e._global._frames.put(k.toString(), fr); e.push(new ValFrame(fr, id.isGlobalSet())); e.put(id._id, Env.ARY, id._id); } // The other three cases of assignment follow } else { // Peel apart a slice assignment AST x = _asts[0]; while( x instanceof ASTAssign ) x = x._asts[1]; ASTSlice lhs_slice = (ASTSlice) x; // asts of ASTSlice => AST[]{hex, rows, cols} // push the slice onto the stack lhs_slice._asts[0].treeWalk(e); // push hex lhs_slice._asts[1].treeWalk(e); // push rows lhs_slice._asts[2].treeWalk(e); // push cols // Case C: Simple case where we have a single row and a single column if (e.isNum() && e.peekTypeAt(-1) == Env.NUM) { int col = (int) e.popDbl(); long row = (long) e.popDbl(); Frame ary = e.popAry(); if (Math.abs(row) > ary.numRows()) throw new IllegalArgumentException("New rows would leave holes after existing rows."); if (Math.abs(col) > ary.numCols()) throw new IllegalArgumentException("New columns would leave holes after existing columns."); if (row < 0 && Math.abs(row) > ary.numRows()) throw new IllegalArgumentException("Cannot extend rows."); if (col < 0 && Math.abs(col) > ary.numCols()) throw new IllegalArgumentException("Cannot extend columns."); if (e.isNum()) { double d = e.popDbl(); if (ary.vecs()[col].isEnum()) ary.vecs()[col].set(row, Double.NaN); else ary.vecs()[col].set(row, d); if (ary._key != null && DKV.get(ary._key) != null) DKV.put(ary); e.push(new ValFrame(ary)); return; } else if (e.isAry()) { Frame one_by_one_ary = e.popAry(); if (one_by_one_ary.numCols() != 1 && one_by_one_ary.numRows() != 1) throw new IllegalArgumentException("Expected RHS to be a 1x1 (one row, one column). Got: " + one_by_one_ary.numRows() + " rows " + one_by_one_ary.numCols() + " cols."); Vec theVec = one_by_one_ary.anyVec(); // RHS is enum if (theVec.isEnum()) { String s = theVec.domain()[(int)theVec.at(0)]; String[] dom = ary.vecs()[col].domain(); if (in(s, dom)) ary.vecs()[col].set(row, Arrays.asList(dom).indexOf(s)); else ary.vecs()[col].set(row, Double.NaN); if (ary._key != null && DKV.get(ary._key) != null) DKV.put(ary); e.push(new ValFrame(ary)); return; // LHS is enum but RHS is not } else if (ary.vecs()[col].isEnum()) { ary.vecs()[col].set(row, Double.NaN); if (ary._key != null && DKV.get(ary._key) != null) DKV.put(ary); e.push(new ValFrame(ary)); return; // LHS and RHS are both numeric } else { double d = theVec.at(0); ary.vecs()[col].set(row, d); if (ary._key != null && DKV.get(ary._key) != null) DKV.put(ary); e.push(new ValFrame(ary)); return; } } else if (e.isStr()) { if (!ary.vecs()[col].isEnum()) throw new IllegalArgumentException("Currently can only set categorical columns."); String s = e.popStr(); String[] dom = ary.vecs()[col].domain(); if (in(s, dom)) ary.vecs()[col].set(row, Arrays.asList(dom).indexOf(s)); else ary.vecs()[col].set(row, Double.NaN); if (ary._key != null && DKV.get(ary._key) != null) DKV.put(ary); e.push(new ValFrame(ary)); return; } else throw new IllegalArgumentException("Did not get a single number or factor level on the RHS of the assignment."); } // Get the LHS slicing rows/cols. This is a more complex case than the simple 1x1 re-assign Val colSelect = e.pop(); Val rowSelect = e.pop(); Frame lhs_ary = e.peekAry(); // Now the stack looks like [ ..., RHS, LHS_FRAME] Object cols = ASTSlice.select(lhs_ary.numCols(), colSelect, e, true); Object rows = ASTSlice.select(lhs_ary.numRows(), rowSelect, e, false); lhs_ary = e.popAry(); // Now the stack looks like [ ..., RHS] long[] cs1; long[] rs1; // Repeat of case C with a single col and row specified, but possibly packaged into ASTSeries objects. if (cols != null && rows != null && (cols instanceof long[]) && (rows instanceof long[]) && (cs1 = (long[]) cols).length == 1 && (rs1 = (long[]) rows).length == 1) { long row = rs1[0]; int col = (int) cs1[0]; if (Math.abs(row) > lhs_ary.numRows()) throw new IllegalArgumentException("New rows would leave holes after existing rows."); if (Math.abs(col) > lhs_ary.numCols()) throw new IllegalArgumentException("New columnss would leave holes after existing columns."); if (row < 0 && Math.abs(row) > lhs_ary.numRows()) throw new IllegalArgumentException("Cannot extend rows."); if (col < 0 && Math.abs(col) > lhs_ary.numCols()) throw new IllegalArgumentException("Cannot extend columns."); if (e.isNum()) { if (lhs_ary.vecs()[col].isEnum()) throw new IllegalArgumentException("Currently can only set numeric columns"); lhs_ary.vecs()[col].set(row, e.popDbl()); e.pushAry(lhs_ary); if (lhs_ary._key != null && DKV.get(lhs_ary._key) != null) DKV.put(lhs_ary); return; } else if (e.isStr()) { if (!lhs_ary.vecs()[col].isEnum()) throw new IllegalArgumentException("Currently can only set categorical columns."); String s = e.popStr(); String[] dom = lhs_ary.vecs()[col].domain(); if (in(s, dom)) lhs_ary.vecs()[col].set(row, Arrays.asList(dom).indexOf(s)); else lhs_ary.vecs()[col].set(row, Double.NaN); if (lhs_ary._key != null && DKV.get(lhs_ary._key) != null) DKV.put(lhs_ary); e.pushAry(lhs_ary); return; } else throw new IllegalArgumentException("Did not get a single number or factor level on the RHS of the assignment."); } // Partial row assignment? Cases B and C if (rows != null) { // Only have partial row assignment, Case B if (cols == null) { assignRows(e, rows, lhs_ary, null); // Have partial row and col assignment? Case C } else { assignRows(e, rows, lhs_ary, cols); } // Case A, just cols } else if (cols != null) { Frame rhs_ary; // convert constant into a whole vec if (e.isNum()) rhs_ary = new Frame(lhs_ary.anyVec().makeCon(e.popDbl())); else if (e.isStr()) rhs_ary = new Frame(lhs_ary.anyVec().makeZero(new String[]{e.popStr()})); else if (e.isAry()) rhs_ary = e.popAry(); else throw new IllegalArgumentException("Bad RHS on the stack: " + e.peekType() + " : " + e.toString()); long[] cs = (long[]) cols; if (rhs_ary.numCols() != 1 && rhs_ary.numCols() != cs.length) throw new IllegalArgumentException("Can only assign to a matching set of columns; trying to assign " + rhs_ary.numCols() + " cols over " + cs.length + " cols"); // Replace the LHS cols with the RHS cols Vec rvecs[] = rhs_ary.vecs(); Futures fs = new Futures(); for (int i = 0; i < cs.length; i++) { int cidx = (int) cs[i]; Vec rv = rvecs[rvecs.length == 1 ? 0 : i]; e.addVec(rv); if (cidx == lhs_ary.numCols()) { if (!rv.group().equals(lhs_ary.anyVec().group())) { e.subRef(rv); rv = lhs_ary.anyVec().align(rv); e.addVec(rv); } lhs_ary.add("C" + String.valueOf(cidx + 1), rv); // New column name created with 1-based index } else { if (!(rv.group().equals(lhs_ary.anyVec().group())) && rv.length() == lhs_ary.anyVec().length()) { e.subRef(rv); rv = lhs_ary.anyVec().align(rv); e.addVec(rv); } lhs_ary.replace(cidx, rv); // returns the new vec, but we don't care... (what happens to the old vec?) } } fs.blockForPending(); if (lhs_ary._key != null && DKV.get(lhs_ary._key) != null) DKV.put(lhs_ary); e.pushAry(lhs_ary); return; } else throw new IllegalArgumentException("Invalid row/col selections."); } } // String argName() { return this._asts[0] instanceof ASTId ? ((ASTId)this._asts[0])._id : null; } @Override public String toString() { return "="; } // @Override public StringBuilder toString( StringBuilder sb, int d ) { // indent(sb,d).append(this).append('\n'); // _lhs.toString(sb,d+1).append('\n'); // _eval.toString(sb,d+1); // return sb; } // AST Slice class ASTSlice extends AST { @Override ASTSlice make() { return new ASTSlice(); } String opStr() { return "["; } ASTSlice() {} ASTSlice parse_impl(Exec E) { // ([ %fr rows cols) // parse the frame, could be an AST... AST fr = E.parse(); // parse the rows // Five possibilties: AST, Vec/Frame, String, Span, Series // AST and Vec/Frame must produce single column of booleans. // String -- Automatically assume it's null (could also be "wakka wakka", or any string, but mapped automatically to null) // null means "all" // Span -- A span is a contiguous range of whole numbers specified like this (: #lo #hi) // List -- A list... AST rows = E.parse(); switch( rows.type() ) { case Env.STR: rows = new ASTNull(); break; case Env.SPAN: ((ASTSpan) rows).setSlice(true, false); break; case Env.SERIES: ((ASTSeries) rows).setSlice(true, false); break; case Env.LIST: rows = new ASTSeries(((ASTLongList)rows)._l,null,((ASTLongList)rows)._spans); ((ASTSeries)rows).setSlice(true,false); break; default: //pass thru } if (!E.hasNext()) throw new IllegalArgumentException("Slice expected 3 arguments (frame, rows, cols), but got 2"); // parse the cols AST cols = E.parse(); switch( cols.type() ) { case Env.STR: cols = cols.value().equals("null") ? new ASTNull() : cols; break; case Env.SPAN: ((ASTSpan) cols).setSlice(false, true); break; case Env.SERIES: ((ASTSeries) cols).setSlice(false, true); break; case Env.LIST: cols = new ASTSeries(((ASTLongList)cols)._l,null,((ASTLongList)cols)._spans); ((ASTSeries)cols).setSlice(false,true); break; default: // pass thru } E.eatEnd(); // eat ending ')' ASTSlice res = (ASTSlice) clone(); res._asts = new AST[]{fr,rows,cols}; return res; } @Override String value() { return null; } @Override int type() { return 0; } // Read-only execution. Assignment to the left-hand-side is handled by // ASTAssign. Here we do copy-on-write when possible. @Override void exec(Env env) { // stack looks like: [....,hex,rows,cols], so pop, pop ! int cols_type = env.peekType(); Val cols = env.pop(); int rows_type = env.peekType(); Val rows = env.pop(); if( cols_type == Env.STR ) { Frame ary = env.peekAry(); int idx = ary.find(((ValStr)cols)._s); if( idx == -1 ) throw new IllegalArgumentException("Column name not in frame, "+cols); cols = new ValNum(idx); cols_type = Env.NUM; } // Scalar load? Throws AIIOOB if out-of-bounds if(cols_type == Env.NUM && rows_type == Env.NUM) { // Known that rows & cols are simple positive constants. // Use them directly, throwing a runtime error if OOB. long row = (long)((ValNum)rows)._d; int col = (int )((ValNum)cols)._d; Frame ary=env.popAry(); try { if (ary.vecs()[col].isEnum()) { env.push(new ValStr(ary.vecs()[col].domain()[(int) ary.vecs()[col].at(row)])); } else env.push(new ValNum(ary.vecs()[col].at(row))); } catch (ArrayIndexOutOfBoundsException e) { if( col < 0 ) { int rm_col = -1*col - 1; // 1 -> 0 idx... // really want to do all columns BUT this one... so not a single scalar result => recurse long[] columns = new long[ary.numCols()-1]; int v=0; for(int i=0;i<columns.length;++i) { if (i == rm_col) v++; columns[i] = v++; } ValSeries vs = new ValSeries(columns,null); vs.setSlice(false,true); // make it a column selector... env.pushAry(ary); env.push(rows); env.push(vs); this.exec(env); return; } if (row < 0 || row >= ary.vecs()[col].length()) throw new IllegalArgumentException("Row index out of bounds: tried to select row 0<="+row+"<="+(ary.vecs()[col].length()-1)+"."); } } else { // Else It's A Big Copy. Some Day look at proper memory sharing, // disallowing unless an active-temp is available, etc. // Eval cols before rows (R's eval order). Frame fr2,ary = env.peekAry(); // Get without popping if (rows_type == Env.ARY) env.addRef(((ValFrame)rows)._fr); Object colSelect = select(ary.numCols(),cols, env, true); Object rowSelect = select(ary.numRows(),rows,env, false); if( rowSelect == null && (colSelect==null || colSelect instanceof long[]) ) { if( colSelect == null ) { fr2 = ary; // All of it } else { long[] cols2 = (long[])colSelect; if( cols2.length > 0 && cols2[0] < 0 ) { // Dropping cols fr2 = new Frame(ary); for( int i=0; i<cols2.length; i++ ) fr2.remove((int)-cols2[i]-1); } else { // Else selecting positive cols fr2 = new Frame(); for( int i=0; i<cols2.length; i++ ) fr2.add(ary._names[(int) cols2[i]], ary.vec((int) cols2[i])); } } } else { fr2 = ary.deepSlice(rowSelect,colSelect); if (colSelect instanceof Frame && cols_type != Env.ARY) for (Vec v : ((Frame)colSelect).vecs()) Keyed.remove(v._key); if (rowSelect instanceof Frame && rows_type != Env.ARY) for (Vec v : ((Frame)rowSelect).vecs()) Keyed.remove(v._key); if( fr2 == null ) fr2 = new Frame(); // Replace the null frame with the zero-column frame if (rows_type == Env.ARY) env.subRef(((ValFrame)rows)._fr); } env.poppush(1, new ValFrame(fr2)); } } // Execute a col/row selection & return the selection. NULL means "all". // Error to mix negatives & positive. Negative list is sorted, with dups // removed. Positive list can have dups (which replicates cols) and is // ordered. numbers. 1-based numbering; 0 is ignored & removed. static Object select( long len, Val v, Env env, boolean isCol) { if( v.type() == Env.NULL ) return null; // Trivial "all" env.push(v); long cols[]; if( env.isNum()) { int col = (int)env.popDbl(); // Pop double; Silent truncation (R semantics) if( col < 0 && col < -len ) col=0; // Ignore a non-existent column if (col < 0) { ValSeries s = new ValSeries(new long[]{col}, null); s.setSlice(!isCol, isCol); return select(len, s, env, isCol); } return new long[]{col}; } if (env.isSeries()) { ValSeries a = env.popSeries(); if (!a.isValid()) throw new IllegalArgumentException("Cannot mix negative and positive array selection."); // if selecting out columns, build a long[] cols and return that. if (a.isColSelector()) return a.toArray(); // Check the case where we have c(1), e.g., a series of a single digit... if (a.isNum() && !a.all_neg()) return select(len, new ValNum(a.toNum()), env, isCol); // Otherwise, we have rows selected: Construct a compatible "predicate" vec Frame ary = env.peekAry(); Vec v0 = a.all_neg() ? ary.anyVec().makeCon(1) : ary.anyVec().makeZero(); final ValSeries a0 = a; Frame fr = a0.all_neg() ? new MRTask() { @Override public void map(Chunk cs) { for (long i = cs.start(); i < cs._len + cs.start(); ++i) if (a0.contains(-i)) cs.set((int) (i - cs.start()), 0); } }.doAll(v0).getResult()._fr : new MRTask() { @Override public void map(Chunk cs) { for (long i = cs.start(); i < cs._len + cs.start(); ++i) if (a0.contains(i)) cs.set((int) (i - cs.start()), i + 1); } }.doAll(v0).getResult()._fr; return fr; } if (env.isSpan()) { ValSpan a = env.popSpan(); if (!a.isValid()) throw new IllegalArgumentException("Cannot mix negative and positive array selection."); // if selecting out columns, build a long[] cols and return that. if (a.isColSelector()) return a.toArray(); // Otherwise, we have rows selected: Construct a compatible "predicate" vec Frame ary = env.peekAry(); final ValSpan a0 = a; Vec v0 = a.all_neg() ? ary.anyVec().makeCon(1) : ary.anyVec().makeZero(); Frame fr = a0.all_neg() ? new MRTask() { @Override public void map(Chunk cs) { for (long i = cs.start(); i < cs._len + cs.start(); ++i) if (a0.contains(-i)) cs.set((int) (i - cs.start() - 1), 0); // -1 for indexing } }.doAll(v0).getResult()._fr : new MRTask() { @Override public void map(Chunk cs) { for (long i = cs.start(); i < cs._len + cs.start(); ++i) if (a0.contains(i)) cs.set((int) (i - cs.start()), i + 1); } }.doAll(v0).getResult()._fr; return fr; } // Got a frame/list of results. // Decide if we're a toss-out or toss-in list Frame ary = env.popAry(); if( ary.numCols() != 1 ) throw new IllegalArgumentException("Selector must be a single column: "+AtoS(ary.names())); Vec vec = ary.anyVec(); // Check for a matching column of bools. if( ary.numRows() == len && vec.min()>=0 && vec.max()<=1 && vec.isInt() ) return ary; // Boolean vector selection. // Convert single vector to a list of longs selecting rows if(ary.numRows() > 10000000) throw H2O.fail("Unimplemented: Cannot explicitly select > 10000000 rows in slice."); cols = MemoryManager.malloc8((int)ary.numRows()); for(int i = 0; i < cols.length; ++i){ if(vec.isNA(i))throw new IllegalArgumentException("Can not use NA as index!"); cols[i] = vec.at8(i); } return cols; } private static String AtoS(String[] s) { StringBuilder sb = new StringBuilder(); for (String ss : s) sb.append(ss).append(','); return sb.toString(); } @Override public String toString() { return "[,]"; } @Override public StringBuilder toString( StringBuilder sb, int d ) { indent(sb,d).append(this).append('\n'); _asts[0].toString(sb,d+1).append("\n"); if( _asts[2]==null ) indent(sb,d+1).append("all\n"); else _asts[2].toString(sb,d+1).append("\n"); if( _asts[1]==null ) indent(sb,d+1).append("all"); else _asts[1].toString(sb,d+1); return sb; } } class ASTDelete extends AST { @Override ASTDelete make() { return new ASTDelete(); } String opStr() { return "del"; } ASTDelete parse_impl(Exec E) { AST ary = E.parse(); AST cols = null; if( !E.isEnd() ) cols = E.parse(); E.eatEnd(); // eat ending ')' ASTDelete res = (ASTDelete) clone(); res._asts = new AST[]{ary,cols}; return res; } @Override String value() { return null; } @Override int type() { return 0; } @Override public String toString() { return "(del)"; } @Override void exec(Env env) { // stack looks like: [....,hex,cols] AST ast = _asts[0]; String s = ast instanceof ASTFrame ? ((ASTFrame)ast)._key : (ast instanceof ASTString ? ast.value() : ((ASTId)ast)._id); DKV.remove(Key.make(s)); env.push(new ValNum(0)); } } // typed lists // lists look like this // (list a1 a2 a3 ...) abstract class ASTList extends AST { @Override void exec(Env e) { throw H2O.unimpl("Illegal: cannot do anything with " + getClass()); } @Override String value() { return null; } @Override int type() { return Env.LIST; } ASTSpan[] _spans; ArrayList<ASTSpan> spans; ASTList() { spans=new ArrayList<>(); } } class ASTDoubleList extends ASTList { ASTDoubleList() {super();} double[] _d; @Override String opStr() { return "dlist"; } @Override ASTDoubleList make() { return new ASTDoubleList(); } ASTDoubleList parse_impl(Exec E) { ArrayList<Double> dbls = new ArrayList<>(); while( !E.isEnd() ) { AST a = E.parse(); if( a instanceof ASTNum ) dbls.add(((ASTNum)a)._d); else if( a instanceof ASTSpan ) spans.add((ASTSpan)a); } E.eatEnd(); _d = new double[dbls.size()]; int i=0; for( double d:dbls ) _d[i++] = d; if( spans.size()!=0 ) _spans = spans.toArray(new ASTSpan[spans.size()]); ASTDoubleList res = (ASTDoubleList) clone(); res._d = _d; //probably useless res._spans = _spans; return res; } @Override public Env treeWalk(Env e) { e.push(new ValDoubleList(_d,_spans)); return e; } } class ASTLongList extends ASTList { ASTLongList() {super();} long[] _l; @Override String opStr() { return "llist"; } @Override ASTLongList make() { return new ASTLongList(); } ASTLongList parse_impl(Exec E) { ArrayList<Long> longs = new ArrayList<>(); while( !E.isEnd() ) { AST a = E.parse(); if( a instanceof ASTNum ) longs.add((long)((ASTNum)a)._d); else if( a instanceof ASTSpan ) spans.add((ASTSpan)a); } E.eatEnd(); _l = new long[longs.size()]; int i=0; for( long l:longs ) _l[i++] = l; if( spans.size()!=0 ) _spans = spans.toArray(new ASTSpan[spans.size()]); ASTLongList res = (ASTLongList) clone(); res._l = _l; //probably useless res._spans = _spans; return res; } @Override public Env treeWalk(Env e) { e.push(new ValLongList(_l,_spans)); return e; } } class ASTStringList extends ASTList { String[] _s; @Override String opStr() { return "slist"; } @Override ASTStringList make() { return new ASTStringList(); } ASTStringList parse_impl(Exec E) { ArrayList<String> strs = new ArrayList<>(); while( !E.isEnd() ) // read until we hit a ")" strs.add(E.nextStr()); E.eatEnd(); _s = new String[strs.size()]; int i=0; for( String s:strs ) _s[i++] = s; ASTStringList res = (ASTStringList) clone(); res._s = _s; //probably useless return res; } @Override public Env treeWalk(Env e) { e.push(new ValStringList(_s)); return e; } } class ASTShortList extends ASTList { short[] _s; @Override String opStr() { return "shortlist"; } @Override ASTShortList make() { return new ASTShortList(); } ASTShortList parse_impl(Exec E) { ArrayList<Short> shorts = new ArrayList<>(); while( !E.isEnd() ) // read until we hit a ")" shorts.add((short)E.nextDbl()); E.eatEnd(); _s = new short[shorts.size()]; int i=0; for( short s:shorts ) _s[i++] = s; ASTShortList res = (ASTShortList) clone(); res._s = _s; //probably useless return res; } } class ASTFloatList extends ASTList { float[] _f; @Override String opStr() { return "flist"; } @Override ASTFloatList make() { return new ASTFloatList(); } ASTFloatList parse_impl(Exec E) { ArrayList<Float> flts = new ArrayList<>(); while( !E.isEnd() ) // read until we hit a ")" flts.add((float)E.nextDbl()); E.eatEnd(); _f = new float[flts.size()]; int i=0; for( float f:flts ) _f[i++] = f; ASTFloatList res = (ASTFloatList) clone(); res._f = _f; //probably useless return res; } } class ASTIntList extends ASTList { int[] _i; @Override String opStr() { return "ilist"; } @Override ASTIntList make() { return new ASTIntList(); } ASTIntList parse_impl(Exec E) { ArrayList<Integer> ints = new ArrayList<>(); while( !E.isEnd() ) // read until we hit a ")" ints.add((int)E.nextDbl()); E.eatEnd(); _i = new int[ints.size()]; int j=0; for( int i:ints ) _i[j++] = i; ASTIntList res = (ASTIntList) clone(); res._i = _i; //probably useless return res; } } class ASTBoolList extends ASTList { boolean[] _b; @Override String opStr() { return "blist"; } @Override ASTBoolList make() { return new ASTBoolList(); } ASTBoolList parse_impl(Exec E) { ArrayList<Boolean> bools = new ArrayList<>(); while( !E.isEnd() ) // read until we hit a ")" bools.add((int)E.nextDbl()==1?true:false); E.eatEnd(); _b = new boolean[bools.size()]; int j=0; for( boolean b:bools ) _b[j++] = b; ASTBoolList res = (ASTBoolList) clone(); res._b = _b; //probably useless return res; } } class ASTByteList extends ASTList { byte[] _b; @Override String opStr() { return "bytelist"; } @Override ASTByteList make() { return new ASTByteList(); } ASTByteList parse_impl(Exec E) { ArrayList<Byte> bytes = new ArrayList<>(); while( !E.isEnd() ) // read until we hit a ")" bytes.add((byte)E.nextDbl()); E.eatEnd(); _b = new byte[bytes.size()]; int j=0; for( byte b:bytes ) _b[j++] = b; ASTByteList res = (ASTByteList) clone(); res._b = _b; //probably useless return res; } } class ASTCharList extends ASTList { char[] _c; @Override String opStr() { return "clist"; } @Override ASTCharList make() { return new ASTCharList(); } ASTCharList parse_impl(Exec E) { ArrayList<Character> chars = new ArrayList<>(); while( !E.isEnd() ) // read until we hit a ")" chars.add(E.nextStr().charAt(0)); E.eatEnd(); _c = new char[chars.size()]; int j=0; for( char c:chars ) _c[j++] = c; ASTCharList res = (ASTCharList) clone(); res._c = _c; //probably useless return res; } }
package water.rapids; import hex.Model; import hex.ObjectConsistencyChecker; import water.*; import water.fvec.Frame; import water.rapids.ast.*; import water.rapids.ast.params.AstConst; import water.rapids.ast.prims.advmath.*; import water.rapids.ast.prims.assign.*; import water.rapids.ast.prims.filters.dropduplicates.AstDropDuplicates; import water.rapids.ast.prims.math.*; import water.rapids.ast.prims.matrix.*; import water.rapids.ast.prims.misc.*; import water.rapids.ast.prims.models.AstPerfectAUC; import water.rapids.ast.prims.models.AstSegmentModelsAsFrame; import water.rapids.ast.prims.models.*; import water.rapids.ast.prims.mungers.*; import water.rapids.ast.prims.operators.*; import water.rapids.ast.prims.reducers.*; import water.rapids.ast.prims.repeaters.*; import water.rapids.ast.prims.search.*; import water.rapids.ast.prims.string.*; import water.rapids.ast.prims.time.*; import water.rapids.ast.prims.timeseries.*; import water.rapids.vals.ValFrame; import water.rapids.vals.ValFun; import water.rapids.vals.ValKeyed; import water.rapids.vals.ValModel; import java.io.Closeable; import java.util.ArrayList; import java.util.HashMap; public class Env extends Iced { /** * for DEVELOPMENT/TESTING only - can be used to enable DKV object consistency check, this check is generally expensive * and should only be used when hunting down bugs or for running tests on CI */ static final boolean DEV_CHECK_OBJECT_CONSISTENCY = H2O.getSysBoolProperty("rapids.checkObjectConsistency", false); // Session holds the ref-counts across multiple executions. public final Session _ses; // Current lexical scope lookup public AstFunction _scope; // Frames that are alive in mid-execution; usually because we have evaluated // some first expression and need to hang onto it while evaluating the next // expression. private ArrayList<Frame> _stk = new ArrayList<>(); // Built-in constants, checked before other namespace lookups happen private static final HashMap<String, AstPrimitive> PRIMS = new HashMap<>(); // Built-in primitives, done after other namespace lookups happen private static final HashMap<String, AstParameter> CONSTS = new HashMap<>(); static void init(AstPrimitive ast) { PRIMS.put(ast.str(), ast); } static void init(AstPrimitive ast, String name) { PRIMS.put(name, ast); } static { // Constants CONSTS.put("FALSE", AstConst.FALSE); CONSTS.put("False", AstConst.FALSE); CONSTS.put("false", AstConst.FALSE); CONSTS.put("TRUE", AstConst.TRUE); CONSTS.put("True", AstConst.TRUE); CONSTS.put("true", AstConst.TRUE); CONSTS.put("NaN", AstConst.NAN); CONSTS.put("NA", AstConst.NAN); CONSTS.put("nan", AstConst.NAN); CONSTS.put("PI", AstConst.PI); CONSTS.put("Pi", AstConst.PI); CONSTS.put("null", null); // Standard math functions init(new AstAbs()); init(new AstAcos()); init(new AstAcosh()); init(new AstAsin()); init(new AstAsinh()); init(new AstAtan()); init(new AstAtanh()); init(new AstCeiling()); init(new AstCos()); init(new AstCosh()); init(new AstCosPi()); init(new AstDiGamma()); init(new AstExp()); init(new AstExpm1()); init(new AstFloor()); init(new AstGamma()); init(new AstLGamma()); init(new AstLog()); init(new AstLog1P()); init(new AstLog2()); init(new AstLog10()); init(new AstNoOp()); init(new AstNot()); init(new AstNot(), "!!"); init(new AstRound()); init(new AstSgn()); init(new AstSignif()); init(new AstSin()); init(new AstSinh()); init(new AstSinPi()); init(new AstSqrt()); init(new AstTan()); init(new AstTanh()); init(new AstTanPi()); init(new AstTriGamma()); init(new AstTrunc()); // Math binary operators init(new AstAnd()); init(new AstDiv()); init(new AstEq()); init(new AstGe()); init(new AstGt()); init(new AstIntDiv()); init(new AstIntDivR()); init(new AstLAnd()); init(new AstLe()); init(new AstLOr()); init(new AstLt()); init(new AstMod()); init(new AstModR()); init(new AstMul()); init(new AstNe()); init(new AstOr()); init(new AstPlus()); init(new AstPow()); init(new AstSub()); init(new AstIfElse()); init(new AstIfElse()); // this one is ternary // Reducers init(new AstAll()); init(new AstAny()); init(new AstAnyNa()); init(new AstCumMax()); init(new AstCumMin()); init(new AstCumProd()); init(new AstCumSum()); init(new AstMad()); init(new AstMax()); init(new AstMaxNa()); init(new AstMean()); init(new AstMedian()); init(new AstMin()); init(new AstMinNa()); init(new AstNaCnt()); init(new AstProd()); init(new AstProdNa()); init(new AstSdev()); init(new AstSum()); init(new AstSumAxis()); init(new AstSumNa()); init(new AstTopN()); // top N% // Time init(new AstAsDate()); init(new AstDay()); init(new AstDayOfWeek()); init(new AstGetTimeZone()); init(new AstHour()); init(new AstListTimeZones()); init(new AstMillis()); init(new AstMinute()); init(new AstMktime()); init(new AstMoment()); init(new AstMonth()); init(new AstSecond()); init(new AstSetTimeZone()); init(new AstWeek()); init(new AstYear()); // Time Series init(new AstDiffLag1()); init(new AstIsax()); // Advanced Math init(new AstCorrelation()); init(new AstDistance()); init(new AstHist()); init(new AstFillNA()); init(new AstImpute()); init(new AstKFold()); init(new AstMode()); init(new AstSkewness()); init(new AstKurtosis()); init(new AstModuloKFold()); init(new AstQtile()); init(new AstRunif()); init(new AstSort()); init(new AstStratifiedKFold()); init(new AstStratifiedSplit()); init(new AstTable()); init(new AstUnique()); init(new AstVariance()); init(new AstTfIdf()); // Generic data mungers init(new AstAnyFactor()); init(new AstApply()); init(new AstAsFactor()); init(new AstAsCharacter()); init(new AstAsNumeric()); init(new AstCBind()); init(new AstColNames()); init(new AstColPySlice()); init(new AstColSlice()); init(new AstCut()); init(new AstDdply()); init(new AstFilterNaCols()); init(new AstFlatten()); init(new AstGetrow()); init(new AstGroup()); init(new AstGroupedPermute()); init(new AstIsCharacter()); init(new AstIsFactor()); init(new AstIsNa()); init(new AstIsNumeric()); init(new AstLevels()); init(new AstMelt()); init(new AstMerge()); init(new AstNaOmit()); init(new AstColumnsByType()); init(new AstNcol()); init(new AstNLevels()); init(new AstNrow()); init(new AstRBind()); init(new AstReLevel()); init(new AstRename()); init(new AstRowSlice()); init(new AstScale()); init(new AstScale.AstScaleInPlace()); init(new AstSetDomain()); init(new AstSetLevel()); init(new AstPivot()); init(new AstRankWithinGroupBy()); // provide ranking withing groupby groups sorted after certain columns // init(new AstTargetEncoderFit()); // we register it with services approach // Assignment; all of these lean heavily on Copy-On-Write optimizations. init(new AstAppend()); // Add a column init(new AstAssign()); // Overwrite a global init(new AstRectangleAssign()); // Overwrite a rectangular slice init(new AstRm()); // Remove a frame, but maintain internal sharing init(new AstTmpAssign()); // Create a new immutable tmp frame // Matrix functions init(new AstTranspose()); init(new AstMMult()); // String functions init(new AstCountMatches()); init(new AstCountSubstringsWords()); init(new AstEntropy()); init(new AstLStrip()); init(new AstGrep()); init(new AstReplaceAll()); init(new AstReplaceFirst()); init(new AstRStrip()); init(new AstStrLength()); init(new AstStrSplit()); init(new AstTokenize()); init(new AstSubstring()); init(new AstToLower()); init(new AstToUpper()); init(new AstTrim()); init(new AstStrDistance()); // Miscellaneous init(new AstComma()); init(new AstLs()); init(new AstSetProperty()); init(new AstPerfectAUC()); // Search init(new AstMatch()); init(new AstWhich()); init(new AstWhichMax()); init(new AstWhichMin()); // Repeaters init(new AstRepLen()); init(new AstSeq()); init(new AstSeqLen()); // Segment Models init(new AstSegmentModelsAsFrame()); // Reset model threshold init(new AstModelResetThreshold()); // Filters init(new AstDropDuplicates()); // Custom (eg. algo-specific) for (AstPrimitive prim : PrimsService.INSTANCE.getAllPrims()) init(prim); } public Env(Session ses) { _ses = ses; } public int sp() { return _stk.size(); } private Frame peek(int x) { return _stk.get(sp() + x); } // Deletes dead Frames & forces good stack cleanliness at opcode end. One // per Opcode implementation. Track frames that are alive mid-execution, but // dead at Opcode end. public StackHelp stk() { return new StackHelp(); } public class StackHelp implements Closeable { final int _sp = sp(); // Push & track. Called on every Val that spans a (nested) exec call. // Used to track Frames with lifetimes spanning other AstRoot executions. public Val track(Val v) { if (v instanceof ValFrame) track(v.getFrame()); return v; } public Frame track(Frame fr) { _stk.add(sp(), new Frame(fr._names, fr.vecs().clone())); // Push and track a defensive copy return fr; } // Pop-all and remove dead. If a Frame was not "tracked" above, then if it // goes dead it will leak on function exit. If a Frame is returned from a // function and not declared "returning", any Vecs it shares with Frames // that are dying in this opcode will be deleted out from under it. @Override public void close() { Futures fs = null; int sp = sp(); while (sp > _sp) { Frame fr = _stk.remove(--sp); // Pop and stop tracking fs = _ses.downRefCnt(fr, fs); // Refcnt -1 all Vecs, and delete if zero refs } if (fs != null) fs.blockForPending(); } // Pop last element and lower refcnts - but do not delete. Lifetime is // responsibility of the caller. public Val untrack(Val vfr) { if (!vfr.isFrame()) return vfr; Frame fr = vfr.getFrame(); _ses.addRefCnt(fr, -1); // Lower counts, but do not delete on zero return vfr; } } // If an opcode is returning a Frame, it must call "returning(frame)" to // track the returned Frame. Otherwise shared input Vecs who's last use is // in this opcode will get deleted as the opcode exits - even if they are // shared in the returning output Frame. public <V extends Val> V returning(V val) { if (val instanceof ValFrame) _ses.addRefCnt(val.getFrame(), 1); return val; } // Variable lookup public Val lookup(String id) { // Lexically scoped functions first Val val = _scope == null ? null : _scope.lookup(id); if (val != null) return val; // disallow TRUE/FALSE/NA to be overwritten by keys in the DKV... just way way saner this way if (CONSTS.containsKey(id)) { return CONSTS.get(id).exec(this); } // Now the DKV Value value = DKV.get(Key.make(expand(id))); if (value != null) { if (DEV_CHECK_OBJECT_CONSISTENCY) { // executed for every id => expensive => should only be enabled in test mode new ObjectConsistencyChecker(value._key).doAllNodes(); } if (value.isFrame()) return addGlobals(value.get()); if (value.isModel()) return new ValModel(value.get()); Object other = value.get(); if (other instanceof Keyed) return new ValKeyed((Keyed) other); // Only understand Frames/Models/Keyed right now throw new IllegalArgumentException("DKV name lookup of " + id + " yielded an instance of type " + value.className() + ", but only Frame, Model & Keyed are supported"); } // Now the built-ins AstPrimitive ast = PRIMS.get(id); if (ast != null) return new ValFun(ast); throw new IllegalArgumentException("Name lookup of '" + id + "' failed"); } public String expand(String id) { return id.startsWith("$")? id.substring(1) + "~" + _ses.id() : id; } // Add these Vecs to the global list, and make a new defensive copy of the // frame - so we can hack it without changing the global frame view. ValFrame addGlobals(Frame fr) { _ses.addGlobals(fr); return new ValFrame(new Frame(fr._names.clone(), fr.vecs().clone())); } /* * Utility & Cleanup */ @Override public String toString() { String s = "{"; for (int i = 0, sp = sp(); i < sp; i++) s += peek(-sp + i).toString() + ","; return s + "}"; } }
package cryptohelper.data; import cryptohelper.data.proxy.ProxyFrequenzaFiller; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class AnalisiFrequenza { private static final Log log = LogFactory.getLog(Messaggio.class); SessioneLavoro sessione; double[] frequenzaTestoCifrato; int[][] bigrammiTesto; int numCaratteri; int numBigrammi; String lingua; String testoCifrato; ProxyFrequenzaFiller proxyFile; public AnalisiFrequenza(String lingua, String testoCifrato) { this.lingua = lingua; this.testoCifrato = testoCifrato; numCaratteri = testoCifrato.length(); numBigrammi = 0; calcolaAnalisiBigrami(); if (lingua.endsWith(Lingua.italiano)) { System.out.println(Lingua.italiano); proxyFile = new ProxyFrequenzaFiller("frequenzeIta.txt", "bgItaliano.txt"); } else if (lingua.endsWith(Lingua.inglese)) { System.out.println(Lingua.inglese); proxyFile = new ProxyFrequenzaFiller("frequenzeIng.txt", "bgInglese.txt"); } } /** * Utiliza questo metodo con NumberFormat formatter = new * DecimalFormat("#0.00"); formatter.format(doubleNumber); * * @return array con le frequenze del testoCifrato */ public double[] getFrequenzaMsg() { calcolaAnalisiFrequenza(); return frequenzaTestoCifrato; } /** * Metodo ausiliario che calcola la frequenza dei caratteri nel testoCifrato * e riempe il array frequenzaTestoCifrato con le frequenza */ private void calcolaAnalisiFrequenza() { if (testoCifrato == null) { log.fatal("Null"); throw new NullPointerException("testoCifrato is null!"); } frequenzaTestoCifrato = new double[26]; for (int i = 0; i < frequenzaTestoCifrato.length; i++) { frequenzaTestoCifrato[i] = 0; } testoCifrato = testoCifrato.toUpperCase(); //trasforma caratteri in maiuscolo - facilita il conteggio //conteggio dei ogni singoli caratteri for (int i = 0; i < testoCifrato.length(); i++) { for (int j = 'A'; j <= 'Z'; j++) { if (testoCifrato.charAt(i) == j) { double temp = frequenzaTestoCifrato[(int) j - 65]; temp++; frequenzaTestoCifrato[(int) j - 65] = temp; } } } //il array viene modificato per contenere frequenze for (int i = 0; i < 26; i++) { double temp = frequenzaTestoCifrato[i]; temp = (temp / numCaratteri) * 100; frequenzaTestoCifrato[i] = temp; } } /** * Metodo ausiliario che calcola i bigrammi nel testoCifrato e riempe * l'array bigrammiTesto con i respetivi numeri di bigrammi */ private void calcolaAnalisiBigrami() { if (testoCifrato == null) { log.fatal("Null"); throw new NullPointerException("testoCifrato is null!"); } testoCifrato = testoCifrato.toUpperCase(); //trasforma caratteri in maiuscolo - facilita il conteggio bigrammiTesto = new int[26][26]; for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { bigrammiTesto[i][j] = 0; } } for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { String bigrammo = (char) (i + 65) + "" + (char) (j + 65); //System.out.print(bigrammo + " "); int numBigramm = StringUtils.countMatches(testoCifrato, bigrammo); bigrammiTesto[i][j] = numBigramm; numBigrammi = numBigrammi + numBigramm; } //System.out.println(); } } /** * Restituisce una Map con bigrammi del carattere ch. Puo essere utilizato * per visualizare i bigrammi del testoCifrato che viene passato al * costrutore * * @param ch carattere * @return una Map di tutte le occorenze dei caraterri prima e dopo * carattere ch */ public Map<Character, ArrayList<Integer>> getBigrammiMsg(char ch) { Map<Character, ArrayList<Integer>> hMap = new HashMap<>(); for (int i = 0; i < 26; i++) { ArrayList<Integer> arrL = new ArrayList<>(); arrL.add(bigrammiTesto[ch - 65][i]); hMap.put((char) (i + 65), arrL); } for (int i = 0; i < 26; i++) { ArrayList<Integer> arrL = hMap.get((char) (i + 65)); arrL.add(bigrammiTesto[i][ch - 65]); hMap.put((char) (i + 65), arrL); } return hMap; } public Map<Character, ArrayList<Integer>> getBigrammiLingua(char ch) { Map<Character, ArrayList<Integer>> hMap = new HashMap<>(); int[][] bigrammiLingua = null; try { bigrammiLingua = proxyFile.getBigrammi(); } catch (IOException ex) { log.fatal(ex.getMessage()); } for (int i = 0; i < 26; i++) { ArrayList<Integer> arrL = new ArrayList<>(); arrL.add(bigrammiLingua[ch - 65][i]); hMap.put((char) (i + 65), arrL); } for (int i = 0; i < 26; i++) { ArrayList<Integer> arrL = hMap.get((char) (i + 65)); arrL.add(bigrammiLingua[i][ch - 65]); hMap.put((char) (i + 65), arrL); } return hMap; } public double[] getFrequenzaLingua() { try { return proxyFile.getFreq(); } catch (IOException ex) { log.fatal(ex.getMessage()); } return null; } public void display() { if (frequenzaTestoCifrato != null) { System.out.println("FREQUENZA:"); for (int i = 'A'; i <= 'Z'; i++) { System.out.print((char) (i) + "=" + frequenzaTestoCifrato[i - 65] + " "); } System.out.println(); } if (bigrammiTesto != null) { System.out.println("BIGRAMMI: " + numBigrammi); System.out.print(" "); for (int i = 'A'; i <= 'Z'; i++) { System.out.print((char) i + " "); } System.out.println(); for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { if (j == 0) { System.out.print((char) (i + 65) + " "); } System.out.print(bigrammiTesto[i][j] + " "); } System.out.println(); } } } public ArrayList<Character> getCaratteriSingoli(Object aLang) { throw new UnsupportedOperationException(); } public ArrayList<Character> getCaratteriSingoliTestoCifrato(Object aTestoCifrato) { throw new UnsupportedOperationException(); } public double[] getFrequenzaTestoCifrato() { return frequenzaTestoCifrato; } public void setFrequenzaTestoCifrato(double[] frequenzaTestoCifrato) { this.frequenzaTestoCifrato = frequenzaTestoCifrato; } }
package polyglot.ext.jl5.ast; import java.util.ArrayList; import polyglot.ast.Case; import polyglot.ast.Expr; import polyglot.ast.Node; import polyglot.ast.Switch; import polyglot.ast.SwitchElement; import polyglot.ext.jl5.types.JL5Flags; import polyglot.ext.jl5.types.JL5TypeSystem; import polyglot.types.SemanticException; import polyglot.types.Type; import polyglot.types.TypeSystem; import polyglot.util.SerialVersionUID; import polyglot.visit.TypeChecker; public class JL5SwitchExt extends JL5TermExt implements JL5SwitchOps { private static final long serialVersionUID = SerialVersionUID.generate(); @Override public Switch node() { return (Switch) super.node(); } @Override public Node typeCheckOverride(Node parent, TypeChecker tc) throws SemanticException { TypeSystem ts = tc.typeSystem(); Switch s = node(); Expr expr = s.visitChild(s.expr(), tc); if (!expr.isTypeChecked()) { return s; } Type type = expr.type(); if (!((J5Lang) tc.lang()).isAcceptableSwitchType(s, expr.type())) { throw new SemanticException("Switch index must be of type char, byte," + " short, int, Character, Byte, Short, Integer, or an enum type.", s.position()); } ArrayList<SwitchElement> newels = new ArrayList<>(s.elements().size()); Type switchType = expr.type(); for (SwitchElement el : s.elements()) { if (el instanceof Case) { Case c = (Case) el; c = ((J5Lang) tc.lang()).resolveCaseLabel(c, tc, switchType); Expr cExpr = c.expr(); if (cExpr != null && !ts.isImplicitCastValid(cExpr.type(), type) && !ts.typeEquals(cExpr.type(), type) && !ts.numericConversionValid(type, tc.lang() .constantValue(cExpr, tc.lang()))) { throw new SemanticException("Case constant \"" + cExpr + "\" is not assignable to " + type + ".", c.position()); } el = c; } else el = s.visitChild(el, tc); newels.add(el); } return s.expr(expr).elements(newels); } @Override public boolean isAcceptableSwitchType(Type type) { JL5TypeSystem ts = (JL5TypeSystem) type.typeSystem(); if (ts.Char().equals(type) || ts.Byte().equals(type) || ts.Short().equals(type) || ts.Int().equals(type)) { return true; } if (ts.wrapperClassOfPrimitive(ts.Char()).equals(type) || ts.wrapperClassOfPrimitive(ts.Byte()).equals(type) || ts.wrapperClassOfPrimitive(ts.Short()).equals(type) || ts.wrapperClassOfPrimitive(ts.Int()).equals(type)) { return true; } if (type.isClass() && JL5Flags.isEnum(type.toClass().flags())) { return true; } return false; } }
package de.unitrier.st.gitlogparser; import java.util.ArrayList; class Commit { private String project; private String branch; private String hashValue; private String authorName; private String authorEmail; private String authorDate; private String commitName; private String commitEmail; private String commitDate; private String logMessage; private int logMessageLength; // only for regular commit private final ArrayList<CommitFile> files; // only for merge private String mergedCommits; private String sourceBranch; // remote-tracking branches usually start with "origin/" private String targetBranch; // only for merged pull request private int pullRequestId; private String pullRequestUser; // only for merged tag private String tagName; Commit(String project, String branch, String hashValue) { this.project = project; this.branch = branch; this.hashValue = hashValue; files = new ArrayList<>(); } @Override public String toString() { String output = ""; output += "Project: " + project + "; "; output += "Branch: " + branch + "; "; output += "Hash: " + hashValue + "; "; output += "Author: " + authorName + " " + authorEmail + "; "; output += "AuthorDate: " + authorDate + "; "; output += "Committer: " + commitName + " " + commitEmail + "; "; output += "CommitDate: " + commitDate + "; "; output += "LogMessageLength: " + logMessageLength + "; "; output += "FileCount: " + files.size() + "; "; output += "MergedCommits: " + mergedCommits + "; "; output += "SourceBranch: " + sourceBranch + "; "; output += "TargetBranch: " + targetBranch + "; "; output += "PullRequestId: " + pullRequestId + "; "; output += "PullRequestUser: " + pullRequestUser + "; "; output += "TagName: " + tagName + "; "; return output; } ArrayList<CommitFile> getFiles() { return files; } void addFile(CommitFile file) { files.add(file); } String getProject() { return project; } void setProject(String project) { this.project = project.trim(); } String getBranch() { return branch; } void setBranch(String branch) { this.branch = branch.trim(); } String getHashValue() { return hashValue; } void setHashValue(String hashValue) { this.hashValue = hashValue.trim(); } String getAuthorName() { return authorName; } void setAuthorName(String authorName) { this.authorName = authorName.trim(); } String getAuthorEmail() { return authorEmail; } void setAuthorEmail(String authorEmail) { this.authorEmail = authorEmail.trim(); } String getAuthorDate() { return authorDate; } void setAuthorDate(String authorDate) { this.authorDate = authorDate.trim(); } String getCommitName() { return commitName; } void setCommitName(String commitName) { this.commitName = commitName.trim(); } String getCommitEmail() { return commitEmail; } void setCommitEmail(String commitEmail) { this.commitEmail = commitEmail.trim(); } String getCommitDate() { return commitDate; } void setCommitDate(String commitDate) { this.commitDate = commitDate.trim(); } String getLogMessage() { return logMessage; } void setLogMessage(String logMessage) { this.logMessage = logMessage; this.logMessageLength = logMessage.length(); } int getLogMessageLength() { return logMessageLength; } String getMergedCommits() { return mergedCommits; } void setMergedCommits(String mergedCommits) { this.mergedCommits = mergedCommits.trim(); } String getSourceBranch() { return sourceBranch; } void setSourceBranch(String sourceBranch) { this.sourceBranch = sourceBranch.trim(); } String getTargetBranch() { return targetBranch; } void setTargetBranch(String targetBranch) { this.targetBranch = targetBranch.trim(); } int getPullRequestId() { return pullRequestId; } void setPullRequestId(int pullRequestId) { this.pullRequestId = pullRequestId; } String getPullRequestUser() { return pullRequestUser; } void setPullRequestUser(String pullRequestUser) { this.pullRequestUser = pullRequestUser.trim(); } String getTagName() { return tagName; } void setTagName(String tagName) { this.tagName = tagName.trim(); } String[] getValues() { // TODO: add all values (or distinguish between merges and commits) return new String[]{getProject(), getBranch(), getHashValue(), getLogMessage()}; } }
package edu.mit.streamjit.apps; import com.google.common.base.Stopwatch; import edu.mit.streamjit.api.CompiledStream; import edu.mit.streamjit.api.StreamCompiler; import edu.mit.streamjit.apps.Benchmark.Input; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.common.BlobHostStreamCompiler; import edu.mit.streamjit.impl.common.CheckVisitor; import edu.mit.streamjit.impl.compiler.CompilerBlobFactory; import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 8/12/2013 */ public final class Benchmarker { private static final long TIMEOUT = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES); public static void main(String[] args) throws InterruptedException { StreamCompiler sc = new BlobHostStreamCompiler(new CompilerBlobFactory(), 1); ServiceLoader<Benchmark> loader = ServiceLoader.load(Benchmark.class); for (Benchmark benchmark : loader) { benchmark.instantiate().visit(new CheckVisitor()); for (Input input : benchmark.inputs()) run(benchmark, input, sc); } } private static void run(Benchmark benchmark, Input input, StreamCompiler compiler) { String statusText = null; long compileMillis = -1, runMillis = -1; try { Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); CompiledStream<Object, Object> stream = compiler.compile(benchmark.instantiate()); stopwatch.stop(); compileMillis = stopwatch.elapsed(TimeUnit.MILLISECONDS); stopwatch.reset(); Thread ot = new OutputThread(input.output(), stream); ot.start(); Thread it = new InputThread(input.input(), stream); stopwatch.start(); it.start(); it.join(TIMEOUT); if (it.isAlive()) throw new TimeoutException(); ot.join(TIMEOUT); if (ot.isAlive()) throw new TimeoutException(); stopwatch.stop(); runMillis = stopwatch.elapsed(TimeUnit.MILLISECONDS); } catch (TimeoutException ex) { statusText = "timed out"; } catch (InterruptedException ex) { statusText = "interrupted"; } catch (Throwable t) { statusText = "failed: "+t; } if (statusText == null) statusText = String.format("%d ms compile, %d ms run", compileMillis, runMillis); System.out.format("%s / %s / %s: %s%n", compiler, benchmark, input, statusText); } private static class InputThread extends Thread { private final Buffer input; private final CompiledStream<Object, Object> stream; private InputThread(Buffer input, CompiledStream<Object, Object> stream) { super("benchmark-input"); this.input = input; this.stream = stream; } @Override @SuppressWarnings("empty-statement") public void run() { Object o; while ((o = input.read()) != null) { while (!stream.offer(o)) /* intentional empty statement */; } stream.drain(); } } private static class OutputThread extends Thread { private final Buffer output; private final CompiledStream<Object, Object> stream; private OutputThread(Buffer output, CompiledStream<Object, Object> stream) { super("benchmark-output"); this.output = output; this.stream = stream; } @Override public void run() { Object o; while ((o = stream.poll()) != null || !stream.isDrained()) { if (output != null && o != null) if (!o.equals(output.read())) throw new AssertionError("bad output"); } } } }
package edu.toronto.bb.core; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collection; import java.util.LinkedHashMap; import org.biojava3.core.sequence.DNASequence; import org.biojava3.core.sequence.compound.DNACompoundSet; import org.biojava3.core.sequence.compound.NucleotideCompound; import org.biojava3.core.sequence.io.FastaReader; import org.biojava3.core.sequence.io.FastaWriter; import org.biojava3.core.sequence.io.FileProxyDNASequenceCreator; import org.biojava3.core.sequence.io.GenericFastaHeaderParser; import org.biojava3.core.sequence.io.template.FastaHeaderFormatInterface; import org.biojava3.core.sequence.io.template.SequenceCreatorInterface; import edu.toronto.bb.core.phred.PhredReader; import edu.toronto.bb.core.phred.PhredScoreSequence; import edu.toronto.bb.core.phred.PhredWriter; public class BarcodeBooster { private File fnaIn; private File fnaOut; private File qualIn; private File qualOut; private InputStream fnaInputStream; private InputStream qualInputStream; private FileOutputStream fnaOutputStream; private FileOutputStream qualOutputStream; private FastaReader<DNASequence, NucleotideCompound> fastaReader; private FastaWriter<DNASequence, NucleotideCompound> fastaWriter; private PhredReader phredReader; private PhredWriter phredWriter; private LinkedHashMap<String,DNASequence> dnaSequences; private LinkedHashMap<String,PhredScoreSequence> qualSequences; private String barcodes; // contains the CSV formats of the barcode private final String pathToBarcodes = "config/barcodes"; private String key = ""; // key to be inserted public BarcodeBooster(File fnaIn, File fnaOut, File qualIn, File qualOut) throws FileNotFoundException { this.fnaIn = fnaIn; this.fnaOut = fnaOut; this.qualIn = qualIn; this.qualOut = qualOut; initIO(); } public void process() throws Throwable { barcodes = loadBarcodes(); dnaSequences = fastaReader.process(); qualSequences = phredReader.process(); searchForBarcodeAndInsertKeyToSequence(); fastaWriter.process(); phredWriter.process(); closeIO(); } public String getKey() { return key; } public void setKey(String key) { this.key = key; } private void searchForBarcodeAndInsertKeyToSequence() { } private void initIO() throws FileNotFoundException { fnaInputStream = new FileInputStream(fnaIn); fnaOutputStream = new FileOutputStream(fnaOut); qualInputStream = new FileInputStream(qualIn); qualOutputStream = new FileOutputStream(qualOut); fastaReader = new FastaReader<DNASequence, NucleotideCompound>(fnaIn, new GenericFastaHeaderParser<DNASequence, NucleotideCompound>(), (SequenceCreatorInterface<NucleotideCompound>) new FileProxyDNASequenceCreator(fnaIn, DNACompoundSet.getDNACompoundSet())); BufferedOutputStream fnaBO = new BufferedOutputStream(fnaOutputStream); fastaWriter = new FastaWriter<DNASequence, NucleotideCompound>(fnaBO, dnaSequences.values(), (FastaHeaderFormatInterface<DNASequence, NucleotideCompound>) new GenericFastaHeaderParser<DNASequence, NucleotideCompound>()); phredReader = new PhredReader(qualInputStream); BufferedOutputStream qualBO = new BufferedOutputStream(qualOutputStream); phredWriter = new PhredWriter(qualBO, qualSequences.values()); } private void closeIO() throws IOException { fnaInputStream.close(); fnaOutputStream.close(); qualInputStream.close(); qualOutputStream.close(); } private String loadBarcodes() throws IOException { FileInputStream barcodeFile = new FileInputStream(pathToBarcodes); InputStreamReader reader = new InputStreamReader(barcodeFile); BufferedReader br = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String delimiter =","; String line = br.readLine(); while (line != null ) { sb.append(line); sb.append(delimiter); line = br.readLine(); } return sb.toString(); } }
package org.voltdb.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import org.voltcore.utils.DBBPool; import org.voltcore.utils.DBBPool.BBContainer; /* * Extend the File class and override its constructors to allow a property to be specified * that places a prefix exactly one before all paths used by the process. Also * contains utility methods for manipulating files and directories and generating temporary * directories that are unlikely to collide with files from other users in /tmp * * This class should have not differ from File when used outside of test cases that set * the property or invoked initNewSubrootForThisProcess. */ public class VoltFile extends File { /* * The prefix to attach to the beginning of all paths */ private static File m_voltFilePrefix = System.getProperty("VoltFilePrefix") != null ? new File (System.getProperty("VoltFilePrefix")) : null; /* * String of characters that is used to ensure that the prefix is only prepended * once */ public static final String m_magic = "3909498365727147224L"; /* * Generic root for this user to contain other subroots. * This is /tmp/${username} */ public static final File m_root = new File(getRootUserPortion()); public static void setSubrootForThisProcess(File prefix) { m_voltFilePrefix = prefix; } private static String getRootUserPortion() { return "/tmp/" + System.getProperty("user.name"); } /* * Do some basic checking to make sure that the root for all the subroots * exists and can be manipulated */ private static void ensureUserRootExists() throws IOException { if (!m_root.exists()) { if (!m_root.mkdir()) { throw new IOException("Unable to create \"" + m_root + "\""); } } if (!m_root.isDirectory()) { throw new IOException("\"" + m_root + "\" exists but is not a directory"); } if (!m_root.canRead()) { throw new IOException("\"" + m_root + "\" exists but is not readable"); } if (!m_root.canWrite()) { throw new IOException("\"" + m_root + "\" exists but is not writable"); } if (!m_root.canExecute()) { throw new IOException("\"" + m_root + "\" exists but is not writable"); } } /* * Create a "root filesystem" complete with its very own /tmp/${username} * to fool a process into thinking it has a private filesystem */ public static File getNewSubroot() throws IOException { ensureUserRootExists(); File tempFile = File.createTempFile("foo", "", m_root); if (!tempFile.delete()) { throw new IOException(); } tempFile = new File(tempFile.getPath() + m_magic); if (!tempFile.mkdir()) { throw new IOException(); } File tempDir = new File(tempFile, "tmp"); if (!tempDir.mkdir()) { throw new IOException(); } File tempUserDir = new File(tempDir, System.getProperty("user.name")); if (!tempUserDir.mkdir()) { throw new IOException(); } return tempFile; } /* * Basic kill it with fire. Deletes everything in /tmp/${username} of * the actual filesystem (not one of the created subroots) */ public static void deleteAllSubRoots() throws IOException { ensureUserRootExists(); for (File f : m_root.listFiles()) { recursivelyDelete(f); } } /* * Merge one directory into another via copying. Useful for simulating * node removal or files being moved from node to node or duplicated. */ public static void moveSubRootContents(File fromSubRoot, File toSubRoot) throws IOException { assert(fromSubRoot.exists() && fromSubRoot.isDirectory()); assert(toSubRoot.exists() && toSubRoot.isDirectory()); for (File f : fromSubRoot.listFiles()) { File fInOtherSubroot = new File(toSubRoot, f.getName()); if (f.isDirectory()) { if (!fInOtherSubroot.exists()) { if (!fInOtherSubroot.mkdir()) { throw new IOException("Can't create directory " + fInOtherSubroot); } } moveSubRootContents( f, fInOtherSubroot); } else { if (!fInOtherSubroot.exists()) { if (!fInOtherSubroot.createNewFile()) { throw new IOException(); } FileInputStream fis = new FileInputStream(f); FileOutputStream fos = new FileOutputStream(fInOtherSubroot); FileChannel inputChannel = fis.getChannel(); FileChannel outputChannel = fos.getChannel(); BBContainer bufC = DBBPool.allocateDirect(8192); ByteBuffer buf = bufC.b(); try { while (inputChannel.read(buf) != -1) { buf.flip(); outputChannel.write(buf); buf.clear(); } inputChannel.close(); outputChannel.close(); } finally { bufC.discard(); } } else { throw new IOException(fInOtherSubroot + " already exists"); } } } } /* * Tests that use ServerThread and LocalSingleProcessServer can't use the * property to set m_voltFilePrefix so they have to invoke this to make * sure a clean filesystem is generated. */ public static File initNewSubrootForThisProcess() throws IOException { m_voltFilePrefix = getNewSubroot(); return m_voltFilePrefix; } /* * Disable the prefixing functionality. Useful if there is a previous test case that has set * a subroot that needs to be cleaned up in tearDown() */ public static void resetSubrootForThisProcess() throws IOException { m_voltFilePrefix = null; } public static void recursivelyDelete(File file, boolean deleteRoot) throws IOException { if (!file.exists()) { return; } if (deleteRoot) { recursivelyDelete(file); } else { if (file.isDirectory()) { for (File f : file.listFiles()) { recursivelyDelete(f); } } } } /* * One of those why doesn't Java ship with this functions */ public static void recursivelyDelete(File f) throws IOException { if (!f.exists()) { return; } if (f.isDirectory()) { for (File f1 : f.listFiles()) { recursivelyDelete(f1); } if (!f.delete()) { throw new IOException("Unable to delete directory " + f); } } else { if (!f.delete()) { throw new IOException("Unable to delete file " + f); } } } /** * Check if the given absolute path is a temp test path. * @param path An absolute path * @return true if the path contains the magic string in it. */ public static boolean isTestPath(final String path) { return path.contains(m_magic); } /** * Strip the magic temp test path prefix from the given path * if it is a test path, no-op if it's not. * @param path An absolute path * @return A new absolute path with the temp test path prefix removed. */ public static String removeTestPrefix(final String path) { if (isTestPath(path)) { return path.substring(m_voltFilePrefix.getAbsolutePath().length()); } else { return path; } } /* * These methods override file behavior and prefix a root path to all the files exactly once */ public VoltFile(String pathname) { super(getFixedPathname(pathname)); } /* * Given the requested pathname, come up with the altered one based on the value * of m_voltFilePrefix */ private static String getFixedPathname(final String pathname) { if (pathname == null || m_voltFilePrefix == null) { return pathname; } if (pathname.contains(m_magic)) { if (pathname.contains(m_voltFilePrefix.getAbsolutePath())) { return pathname; } int offset = pathname.indexOf(m_magic) + m_magic.length(); String relativePath = pathname.substring(offset); // The this is probably a snapshot path and needs to be re-mapped to our snapshot // directory because truncation snapshot requests specify absolute paths return m_voltFilePrefix.getAbsolutePath() + relativePath; } return m_voltFilePrefix + File.separator + pathname; } public VoltFile(String parent, String child) { super(getFixedPathname(parent), child); } public VoltFile(File parent, String child) { super(getFixedPathname(parent.getPath()), child); } public VoltFile(VoltFile parent, String child) { super(parent, child); } private static final long serialVersionUID = -3909498365727147224L; }
package ibis.frontend.rmi; import ibis.util.BT_Analyzer; import java.io.PrintWriter; import java.util.Vector; import org.apache.bcel.Repository; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.ExceptionTable; import org.apache.bcel.generic.Type; class RMIStubGenerator extends RMIGenerator { BT_Analyzer data; PrintWriter output; boolean verbose; RMIStubGenerator(BT_Analyzer data, PrintWriter output, boolean verbose) { this.data = data; this.output = output; this.verbose = verbose; } void methodHeader(Method m, int number) { Type ret = getReturnType(m); Type[] params = getParameterTypes(m); output.print("\tpublic final " + ret + " " + m.getName() + "("); for (int j=0;j<params.length;j++) { output.print(params[j] + " p" + j); if (j<params.length-1) { output.print(", "); } } ExceptionTable et = m.getExceptionTable(); output.print(") throws "); if (et != null) { String[] names = et.getExceptionNames(); for (int i = 0; i < names.length; i++) { output.print(names[i]); if (i < names.length-1) output.print(", "); } } else { output.print("RemoteException"); } output.print(" {\n"); } private boolean caught(ExceptionTable t, String name) { String[] names = t.getExceptionNames(); for (int i = 0; i < names.length; i++) { if (Repository.instanceOf(name, names[i])) { return true; } } return false; } void methodBody(Method m, int number) { Type ret = getReturnType(m); Type[] params = getParameterTypes(m); //if (verbose) System.out.println(m.getName() + " is a " + (write ? "write" : "read") + " method"); // output.println("\t\t\tif (RTS.DEBUG) System.out.println(\"rmi_stub_" + data.classname + "." + m.getName() + " doing RMI call\");"); if (!ret.equals(Type.VOID)) { output.println("\t\t" + getInitedLocal(ret, "result") + ";"); } output.println("\t\ttry {"); output.println("\t\t\tException remoteex = null;"); output.println("\t\t\ttry {"); output.println("\t\t\t\tinitSend();"); output.println("\t\t\t\tWriteMessage w = newMessage();"); output.println("\t\t\t\tw.writeInt(" + number + ");"); output.println("\t\t\t\tw.writeInt(stubID);"); for (int j=0;j<params.length;j++) { output.println(writeMessageType("\t\t\t\t", "w", params[j], "p" + j)); } output.println("\t\t\t\tw.send();"); output.println("\t\t\t\tw.finish();"); output.println("\t\t\t\tReadMessage r = reply.receive();"); output.println("\t\t\t\tif (r.readByte() == ibis.rmi.Protocol.EXCEPTION) {"); output.println("\t\t\t\t\tremoteex = (Exception) r.readObject();"); output.println("\t\t\t\t}"); output.println("\t\t\t\telse {"); if (!ret.equals(Type.VOID)) { output.println(readMessageType("\t\t\t\t\t", "result", "r", ret)); } output.println("\t\t\t\t}"); output.println("\t\t\t\tr.finish();"); output.println("\t\t\t} catch(java.io.IOException ioex) {"); output.println("\t\t\t\tthrow new RemoteException(\"IO exception\", ioex);"); output.println("\t\t\t}"); output.println("\t\t\tif (remoteex != null) throw remoteex;"); ExceptionTable et = m.getExceptionTable(); if (et != null) { String[] names = et.getExceptionNames(); /* If the method throws E1 and E2 and E2 is a superclass of E1, * this will yield a compiler error: * } catch (E2 e2) { * .... * } catch (E1 e1) { * .... * because e1 has already been caught under the E2 clause. * Solution: traverse the hierarchy for the exceptions, and * disable catching for all E1s that have a superclass that * is also caught. * RFHH */ JavaClass[] excpt = new JavaClass[names.length]; for (int i = 0, n = names.length; i < n; i++) { excpt[i] = Repository.lookupClass(names[i]); } boolean[] disable = new boolean[names.length]; for (int i = 0, n = names.length; i < n; i++) { disable[i] = false; JavaClass[] supers = excpt[i].getSuperClasses(); outer: for (int s = 0; s < supers.length; s++) { for (int j = 0; j < n; j++) { if (excpt[j].equals(supers[s])) { disable[i] = true; break outer; } } } } for (int i = 0; i < names.length; i++) { if (! disable[i]) { output.println("\t\t} catch (" + names[i] + " e" + i + ") {"); output.println("\t\t\tthrow e" + i + ";"); } } } else { output.println("\t\t} catch (RemoteException e0) {"); output.println("\t\t\tthrow e0;"); } if (et == null || ! (caught(et, "java.lang.RuntimeException"))) { output.println("\t\t} catch (RuntimeException re) {"); output.println("\t\t\tthrow re;"); } if (et == null || ! (caught(et, "java.lang.Exception"))) { output.println("\t\t} catch (Exception e) {"); output.println("\t\t\tthrow new RemoteException(\"undeclared checked exception\", e);"); } output.println("\t\t}"); } void methodTrailer(Method m) { Type ret = getReturnType(m); if (!ret.equals(Type.VOID)) { output.println("\t\treturn result;"); } output.println("\t}\n"); } void header() { Vector interfaces = data.specialInterfaces; if (data.packagename != null && ! data.packagename.equals("")) { output.println("package " + data.packagename + ";"); output.println(); } output.println("import ibis.rmi.*;"); output.println("import ibis.ipl.*;"); output.println(); output.print("public final class rmi_stub_" + data.classname + " extends ibis.rmi.server.Stub implements "); for (int i=0;i<interfaces.size();i++) { output.print(((JavaClass) interfaces.get(i)).getClassName()); if (i<interfaces.size()-1) { output.print(", "); } } output.println(" {\n"); } void constructor() { output.println("\tpublic rmi_stub_" + data.classname + "() {"); // output.println("\t\tsuper();"); output.println("\t}\n"); } void body(Vector methods) { for (int i=0;i<methods.size();i++) { Method m = (Method) methods.get(i); methodHeader(m, i); methodBody(m, i); methodTrailer(m); } } void trailer() { output.println("}\n"); } void generate() { header(); constructor(); body(data.specialMethods); trailer(); } }
package vektah.rust; import com.intellij.lang.Language; import vektah.rust.i18n.RustBundle; public class RustLanguage extends Language { public static final RustLanguage INSTANCE = new RustLanguage(); private RustLanguage() { super("Rust", "text/rust", "text/x-rust", "application/x-rust"); } @Override public boolean isCaseSensitive() { return true; } @Override public String getDisplayName() { return RustBundle.message("language.name.rust"); } }
package net.sf.samtools; import net.sf.samtools.seekablestream.SeekableBufferedStream; import net.sf.samtools.util.*; import net.sf.samtools.seekablestream.SeekableHTTPStream; import net.sf.samtools.seekablestream.SeekableStream; import java.io.*; import java.util.Arrays; import java.util.zip.GZIPInputStream; import java.net.URL; /** * Class for reading and querying SAM/BAM files. Delegates to appropriate concrete implementation. */ public class SAMFileReader implements Iterable<SAMRecord>, Closeable { private static ValidationStringency defaultValidationStringency = ValidationStringency.DEFAULT_STRINGENCY; public static ValidationStringency getDefaultValidationStringency() { return defaultValidationStringency; } /** * Set validation stringency for all subsequently-created SAMFileReaders. This is the only way to * change the validation stringency for SAM header. * NOTE: Programs that change this should make sure to have a try/finally clause wrapping the work that * they do, so that the original stringency can be restored after the program's work is done. This facilitates * calling a program that is usually run stand-alone from another program, without messing up the original * validation stringency. */ public static void setDefaultValidationStringency(final ValidationStringency defaultValidationStringency) { SAMFileReader.defaultValidationStringency = defaultValidationStringency; } /** * Returns the SAMSequenceDictionary from the provided FASTA. */ public static SAMSequenceDictionary getSequenceDictionary(final File dictionaryFile) { final SAMFileReader samFileReader = new SAMFileReader(dictionaryFile); final SAMSequenceDictionary dict = samFileReader.getFileHeader().getSequenceDictionary(); CloserUtil.close(dictionaryFile); return dict; } private boolean mIsBinary = false; private BAMIndex mIndex = null; private SAMRecordFactory samRecordFactory = new DefaultSAMRecordFactory(); private ReaderImplementation mReader = null; private File samFile = null; /** * How strict to be when reading a SAM or BAM, beyond bare minimum validation. */ public enum ValidationStringency { /** * Do the right thing, throw an exception if something looks wrong. */ STRICT, /** * Emit warnings but keep going if possible. */ LENIENT, /** * Like LENIENT, only don't emit warning messages. */ SILENT; public static final ValidationStringency DEFAULT_STRINGENCY = STRICT; } /** * Internal interface for SAM/BAM file reader implementations. * Implemented as an abstract class to enforce better access control. */ static abstract class ReaderImplementation { abstract void enableFileSource(final SAMFileReader reader, final boolean enabled); abstract void enableIndexCaching(final boolean enabled); abstract void enableIndexMemoryMapping(final boolean enabled); abstract void enableCrcChecking(final boolean enabled); abstract void setSAMRecordFactory(final SAMRecordFactory factory); abstract boolean hasIndex(); abstract BAMIndex getIndex(); abstract SAMFileHeader getFileHeader(); abstract CloseableIterator<SAMRecord> getIterator(); abstract CloseableIterator<SAMRecord> getIterator(SAMFileSpan fileSpan); abstract SAMFileSpan getFilePointerSpanningReads(); abstract CloseableIterator<SAMRecord> query(String sequence, int start, int end, boolean contained); abstract CloseableIterator<SAMRecord> queryAlignmentStart(String sequence, int start); abstract public CloseableIterator<SAMRecord> queryUnmapped(); abstract void close(); // If true, emit warnings about format errors rather than throwing exceptions; abstract void setValidationStringency(final ValidationStringency validationStringency); abstract ValidationStringency getValidationStringency(); } /** * Prepare to read a SAM or BAM file. Indexed lookup not allowed because reading from InputStream. */ public SAMFileReader(final InputStream stream) { this(stream, false); } /** * Prepare to read a SAM or BAM file. If the given file is a BAM, and has a companion BAI index file * that is named according to the convention, it will be found and opened, and indexed query will be allowed. */ public SAMFileReader(final File file) { this(file, null, false); } /** * Prepare to read a SAM or BAM file. If the given file is a BAM, and an index is present, indexed query * will be allowed. * * @param file SAM or BAM to read. * @param indexFile Index file that is companion to BAM, or null if no index file, or if index file * should be found automatically. */ public SAMFileReader(final File file, final File indexFile) { this(file, indexFile, false); } /** * Read a SAM or BAM file. Indexed lookup not allowed because reading from InputStream. * * @param stream input SAM or BAM. * @param eagerDecode if true, decode SAM record entirely when reading it. */ public SAMFileReader(final InputStream stream, final boolean eagerDecode) { init(stream, null, null, eagerDecode, defaultValidationStringency); } /** * Read a SAM or BAM file, possibly with an index file if present. * If the given file is a BAM, and an index is present, indexed query will be allowed. * * @param file SAM or BAM. * @param eagerDecode if true, decode SAM record entirely when reading it. */ public SAMFileReader(final File file, final boolean eagerDecode) { this(file, null, eagerDecode); } /** * Read a SAM or BAM file, possibly with an index file. If the given file is a BAM, and an index is present, * indexed query will be allowed. * * @param file SAM or BAM. * @param indexFile Location of index file, or null in order to use the default index file (if present). * @param eagerDecode eagerDecode if true, decode SAM record entirely when reading it. */ public SAMFileReader(final File file, final File indexFile, final boolean eagerDecode){ init(null, file, indexFile, eagerDecode, defaultValidationStringency); } /** * Read a BAM file by http * indexed query will be allowed. * * @param url BAM. * @param indexFile Location of index file, or null if indexed access not required. * @param eagerDecode eagerDecode if true, decode SAM record entirely when reading it. */ public SAMFileReader(final URL url, final File indexFile, final boolean eagerDecode) { init(new SeekableBufferedStream(new SeekableHTTPStream(url)), indexFile, eagerDecode, defaultValidationStringency); } /** * Read a BAM file via caller-supplied mechanism. Indexed query will be allowed, but * index file must be provided in that case. * @param strm BAM -- If the stream is not buffered, caller should wrap in SeekableBufferedStream for * better performance. * @param indexFile Location of index file, or null indexed access not required. * @param eagerDecode if true, decode SAM record entirely when reading it. */ public SAMFileReader(final SeekableStream strm, final File indexFile, final boolean eagerDecode) { init(strm, indexFile, eagerDecode, defaultValidationStringency); } public SAMFileReader(final SeekableStream strm, final SeekableStream indexStream, final boolean eagerDecode) { init(strm, indexStream, eagerDecode, defaultValidationStringency); } public void close() { if (mReader != null) { mReader.close(); } mReader = null; mIndex = null; } /** * If true, writes the source of every read into the source SAMRecords. * @param enabled true to write source information into each SAMRecord. */ public void enableFileSource(final boolean enabled) { mReader.enableFileSource(this,enabled); } /** * If true, uses the caching version of the index reader. * @param enabled true to write source information into each SAMRecord. */ public void enableIndexCaching(final boolean enabled) { if(mIndex != null) throw new SAMException("Unable to turn on index caching; index file has already been loaded."); mReader.enableIndexCaching(enabled); } /** * If false, disable the use of memory mapping for accessing index files (default behavior is to use memory mapping). * This is slower but more scalable when accessing large numbers of BAM files sequentially. * @param enabled True to use memory mapping, false to use regular I/O. */ public void enableIndexMemoryMapping(final boolean enabled) { if (mIndex != null) { throw new SAMException("Unable to change index memory mapping; index file has already been loaded."); } mReader.enableIndexMemoryMapping(enabled); } /** * Only meaningful for BAM file readers - enables or disables checking of checksums on uncompressed * data during decompression. Enabling this will increase decompression time by 15-30%. */ public void enableCrcChecking(final boolean enabled) { this.mReader.enableCrcChecking(enabled); } /** * Override the default SAMRecordFactory class used to instantiate instances of SAMRecord and BAMRecord. */ public void setSAMRecordFactory(final SAMRecordFactory factory) { this.samRecordFactory = factory; this.mReader.setSAMRecordFactory(factory); } /** * @return True if this is a BAM reader. */ public boolean isBinary() { return mIsBinary; } /** * @return true if ths is a BAM file, and has an index */ public boolean hasIndex() { return mReader.hasIndex(); } /** * Retrieves the index for the given file type. Ensure that the index is of the specified type. * @return An index of the given type. */ public BAMIndex getIndex() { return mReader.getIndex(); } /** * Returns true if the supported index is browseable, meaning the bins in it can be traversed * and chunk data inspected and retrieved. * @return True if the index supports the BrowseableBAMIndex interface. False otherwise. */ public boolean hasBrowseableIndex() { return hasIndex() && getIndex() instanceof BrowseableBAMIndex; } /** * Gets an index tagged with the BrowseableBAMIndex interface. Throws an exception if no such * index is available. * @return An index with a browseable interface, if possible. * @throws SAMException if no such index is available. */ public BrowseableBAMIndex getBrowseableIndex() { BAMIndex index = getIndex(); if(!(index instanceof BrowseableBAMIndex)) throw new SAMException("Cannot return index: index created by BAM is not browseable."); return BrowseableBAMIndex.class.cast(index); } public SAMFileHeader getFileHeader() { return mReader.getFileHeader(); } /** * Control validation of SAMRecords as they are read from file. * In order to control validation stringency for SAM Header, call SAMFileReader.setDefaultValidationStringency * before constructing a SAMFileReader. */ public void setValidationStringency(final ValidationStringency validationStringency) { mReader.setValidationStringency(validationStringency); } /** * Iterate through file in order. For a SAMFileReader constructed from an InputStream, and for any SAM file, * a 2nd iteration starts where the 1st one left off. For a BAM constructed from a File, each new iteration * starts at the first record. * <p/> * Only a single open iterator on a SAM or BAM file may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. */ public SAMRecordIterator iterator() { return new AssertableIterator(mReader.getIterator()); } /** * Iterate through the given chunks in the file. * @param chunks List of chunks for which to retrieve data. * @return An iterator over the given chunks. */ public SAMRecordIterator iterator(final SAMFileSpan chunks) { return new AssertableIterator(mReader.getIterator(chunks)); } /** * Gets a pointer spanning all reads in the BAM file. * @return Unbounded pointer to the first record, in chunk format. */ public SAMFileSpan getFilePointerSpanningReads() { return mReader.getFilePointerSpanningReads(); } /** * Iterate over records that match the given interval. Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SAMFileReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. You can use a second SAMFileReader to iterate * in parallel over the same underlying file. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param sequence Reference sequence of interest. * @param start 1-based, inclusive start of interval of interest. Zero implies start of the reference sequence. * @param end 1-based, inclusive end of interval of interest. Zero implies end of the reference sequence. * @param contained If true, each SAMRecord returned is will have its alignment completely contained in the * interval of interest. If false, the alignment of the returned SAMRecords need only overlap the interval of interest. * @return Iterator over the SAMRecords matching the interval. */ public SAMRecordIterator query(final String sequence, final int start, final int end, final boolean contained) { return new AssertableIterator(mReader.query(sequence, start, end, contained)); } /** * Iterate over records that overlap the given interval. Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SAMFileReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param sequence Reference sequence of interest. * @param start 1-based, inclusive start of interval of interest. Zero implies start of the reference sequence. * @param end 1-based, inclusive end of interval of interest. Zero implies end of the reference sequence. * @return Iterator over the SAMRecords overlapping the interval. */ public SAMRecordIterator queryOverlapping(final String sequence, final int start, final int end) { return query(sequence, start, end, false); } /** * Iterate over records that are contained in the given interval. Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SAMFileReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * is in the query region. * * @param sequence Reference sequence of interest. * @param start 1-based, inclusive start of interval of interest. Zero implies start of the reference sequence. * @param end 1-based, inclusive end of interval of interest. Zero implies end of the reference sequence. * @return Iterator over the SAMRecords contained in the interval. */ public SAMRecordIterator queryContained(final String sequence, final int start, final int end) { return query(sequence, start, end, true); } public SAMRecordIterator queryUnmapped() { return new AssertableIterator(mReader.queryUnmapped()); } /** * Iterate over records that map to the given sequence and start at the given position. Only valid to call this if hasIndex() == true. * <p/> * Only a single open iterator on a given SAMFileReader may be extant at any one time. If you want to start * a second iteration, the first one must be closed first. * <p/> * Note that indexed lookup is not perfectly efficient in terms of disk I/O. I.e. some SAMRecords may be read * and then discarded because they do not match the interval of interest. * <p/> * Note that an unmapped read will be returned by this call if it has a coordinate for the purpose of sorting that * matches the arguments. * * @param sequence Reference sequence of interest. * @param start Alignment start of interest. * @return Iterator over the SAMRecords with the given alignment start. */ public SAMRecordIterator queryAlignmentStart(final String sequence, final int start) { return new AssertableIterator(mReader.queryAlignmentStart(sequence, start)); } /** * Fetch the mate for the given read. Only valid to call this if hasIndex() == true. * This will work whether the mate has a coordinate or not, so long as the given read has correct * mate information. This method iterates over the SAM file, so there may not be an unclosed * iterator on the SAM file when this method is called. * * Note that it is not possible to call queryMate when iterating over the SAMFileReader, because queryMate * requires its own iteration, and there cannot be two simultaneous iterations on the same SAMFileReader. The * work-around is to open a second SAMFileReader on the same input file, and call queryMate on the second * reader. * * @param rec Record for which mate is sought. Must be a paired read. * @return rec's mate, or null if it cannot be found. */ public SAMRecord queryMate(final SAMRecord rec) { if (!rec.getReadPairedFlag()) { throw new IllegalArgumentException("queryMate called for unpaired read."); } if (rec.getFirstOfPairFlag() == rec.getSecondOfPairFlag()) { throw new IllegalArgumentException("SAMRecord must be either first and second of pair, but not both."); } final boolean firstOfPair = rec.getFirstOfPairFlag(); final CloseableIterator<SAMRecord> it; if (rec.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) { it = queryUnmapped(); } else { it = queryAlignmentStart(rec.getMateReferenceName(), rec.getMateAlignmentStart()); } try { SAMRecord mateRec = null; while (it.hasNext()) { final SAMRecord next = it.next(); if (!next.getReadPairedFlag()) { if (rec.getReadName().equals(next.getReadName())) { throw new SAMFormatException("Paired and unpaired reads with same name: " + rec.getReadName()); } continue; } if (firstOfPair) { if (next.getFirstOfPairFlag()) continue; } else { if (next.getSecondOfPairFlag()) continue; } if (rec.getReadName().equals(next.getReadName())) { if (mateRec != null) { throw new SAMFormatException("Multiple SAMRecord with read name " + rec.getReadName() + " for " + (firstOfPair ? "second" : "first") + " end."); } mateRec = next; } } return mateRec; } finally { it.close(); } } private void init(final SeekableStream strm, final File indexFile, final boolean eagerDecode, final ValidationStringency validationStringency) { try { if (streamLooksLikeBam(strm)) { mIsBinary = true; mReader = new BAMFileReader(strm, indexFile, eagerDecode, validationStringency, this.samRecordFactory); } else { throw new SAMFormatException("Unrecognized file format: " + strm); } setValidationStringency(validationStringency); } catch (IOException e) { throw new RuntimeIOException(e); } } private void init(final SeekableStream strm, final SeekableStream indexStream, final boolean eagerDecode, final ValidationStringency validationStringency) { try { if (streamLooksLikeBam(strm)) { mIsBinary = true; mReader = new BAMFileReader(strm, indexStream, eagerDecode, validationStringency, this.samRecordFactory); } else { throw new SAMFormatException("Unrecognized file format: " + strm); } setValidationStringency(validationStringency); } catch (IOException e) { throw new RuntimeIOException(e); } } // Its too expensive to examine the remote file to determine type. // Rely on file extension. private boolean streamLooksLikeBam(SeekableStream strm) { String source = strm.getSource(); if(source == null) return true; source = source.toLowerCase(); //Source will typically be a file path or URL //If it's a URL we require one of the query parameters to be bam file return source.endsWith(".bam") || source.contains(".bam?")|| source.contains(".bam&") || source.contains(".bam%26"); } private void init(final InputStream stream, final File file, File indexFile, final boolean eagerDecode, final ValidationStringency validationStringency) { if (stream != null && file != null) throw new IllegalArgumentException("stream and file are mutually exclusive"); this.samFile = file; try { final BufferedInputStream bufferedStream; if (file != null) bufferedStream = new BufferedInputStream(new FileInputStream(file), IOUtil.STANDARD_BUFFER_SIZE); else bufferedStream = IOUtil.toBufferedStream(stream); if (isBAMFile(bufferedStream)) { mIsBinary = true; if (file == null || !file.isFile()) { mReader = new BAMFileReader(bufferedStream, indexFile, eagerDecode, validationStringency, this.samRecordFactory); } else { bufferedStream.close(); mReader = new BAMFileReader(file, indexFile, eagerDecode, validationStringency, this.samRecordFactory); } } else if (BlockCompressedInputStream.isValidFile(bufferedStream)) { mIsBinary = false; mReader = new SAMTextReader(new BlockCompressedInputStream(bufferedStream), validationStringency, this.samRecordFactory); } else if (isGzippedSAMFile(bufferedStream)) { mIsBinary = false; mReader = new SAMTextReader(new GZIPInputStream(bufferedStream), validationStringency, this.samRecordFactory); } else if (isSAMFile(bufferedStream)) { if (indexFile != null) { bufferedStream.close(); throw new RuntimeException("Cannot use index file with textual SAM file"); } mIsBinary = false; mReader = new SAMTextReader(bufferedStream, file, validationStringency, this.samRecordFactory); } else { bufferedStream.close(); throw new SAMFormatException("Unrecognized file format"); } setValidationStringency(validationStringency); mReader.setSAMRecordFactory(this.samRecordFactory); } catch (IOException e) { throw new RuntimeIOException(e); } } /** * @param stream stream.markSupported() must be true * @return true if this looks like a BAM file. */ private boolean isBAMFile(final InputStream stream) throws IOException { if (!BlockCompressedInputStream.isValidFile(stream)) { return false; } final int buffSize = BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE; stream.mark(buffSize); final byte[] buffer = new byte[buffSize]; readBytes(stream, buffer, 0, buffSize); stream.reset(); final byte[] magicBuf = new byte[4]; final int magicLength = readBytes(new BlockCompressedInputStream(new ByteArrayInputStream(buffer)), magicBuf, 0, 4); return magicLength == BAMFileConstants.BAM_MAGIC.length && Arrays.equals(BAMFileConstants.BAM_MAGIC, magicBuf); } private static int readBytes(final InputStream stream, final byte[] buffer, final int offset, final int length) throws IOException { int bytesRead = 0; while (bytesRead < length) { final int count = stream.read(buffer, offset + bytesRead, length - bytesRead); if (count <= 0) { break; } bytesRead += count; } return bytesRead; } /** * Attempts to check whether the file is a gzipped sam file. Returns true if it * is and false otherwise. */ private boolean isGzippedSAMFile(final BufferedInputStream stream) { if (!stream.markSupported()) { throw new IllegalArgumentException("Cannot test a stream that doesn't support marking."); } stream.mark(8000); try { final GZIPInputStream gunzip = new GZIPInputStream(stream); final int ch = gunzip.read(); return true; } catch (IOException ioe) { return false; } finally { try { stream.reset(); } catch (IOException ioe) { throw new IllegalStateException("Could not reset stream."); } } } private boolean isSAMFile(final InputStream stream) { // For now, assume every non-binary file is a SAM text file. return true; } @Override public String toString() { if (this.samFile == null) { return getClass().getSimpleName() + "{initialized with stream}"; } else { return getClass().getSimpleName() + "{" + this.samFile.getAbsolutePath() + "}"; } } /** * Wrapper class to let calls to Iterator return a SAMRecordIterator */ static class AssertableIterator implements SAMRecordIterator { private final CloseableIterator<SAMRecord> wrappedIterator; private SAMRecord previous = null; private SAMRecordComparator comparator = null; public AssertableIterator(CloseableIterator<SAMRecord> iterator) { wrappedIterator = iterator; } public SAMRecordIterator assertSorted(SAMFileHeader.SortOrder sortOrder) { if (sortOrder == null || sortOrder == SAMFileHeader.SortOrder.unsorted) { comparator = null; return this; } comparator = sortOrder.getComparatorInstance(); return this; } public SAMRecord next() { SAMRecord result = wrappedIterator.next(); if (comparator != null) { if (previous != null) { if (comparator.fileOrderCompare(previous, result) > 0) { throw new IllegalStateException("Records " + previous.getReadName() + " (" + previous.getReferenceName() + ":" + previous.getAlignmentStart() + ") " + "should come after " + result.getReadName() + " (" + result.getReferenceName() + ":" + result.getAlignmentStart() + ") when sorting with " + comparator.getClass().getName()); } } previous = result; } return result; } public void close() { wrappedIterator.close(); } public boolean hasNext() { return wrappedIterator.hasNext(); } public void remove() { wrappedIterator.remove(); } } }
package javax.usb.tck; import javax.usb.*; import javax.usb.event.*; import javax.usb.util.*; import junit.framework.TestCase; /** * Request Test - Get Status tests * * This test creates a Request object and verifies that the GetStatus * method sends messages to the Default Control Pipe * * @author Bob Rossi * * The topology.b6 image must be programmed into the programmable device EEPROM * for the StandardRequestTest. * */ public class RequestTestGetStatus extends TestCase { public void setUp() { usbDevice = FindProgrammableDevice.getInstance().getTopologyTestDevice(); assertNotNull("Device required for test not found",usbDevice); usbDevice.addUsbDeviceListener(deviceListener); } public void tearDown() { usbDevice.removeUsbDeviceListener(deviceListener); } public void testGetStatusStatic() { short configurationNumber; byte recipientType; short featureSelection; short target; short wIndex; short status; short statusExpected; byte requestType; boolean usbExceptionThrown = false; configurationNumber = 1; status = 0; //no target needed when recipient is a device target = 0; //set recipientType to Device recipientType = UsbConst.REQUESTTYPE_RECIPIENT_DEVICE; requestType = UsbConst.REQUESTTYPE_DIRECTION_IN; statusExpected = 0; // @P2D16 LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = StandardRequest.getStatus(usbDevice, recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } /*status is unknown at this point, so don't check the value yet*/ } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(target, requestType); featureSelection = UsbConst.FEATURE_SELECTOR_DEVICE_REMOTE_WAKEUP; statusExpected = 2; try { StandardRequest.setFeature(usbDevice, recipientType, featureSelection, target); try { /*Wait for setConfiguration Data event before continuing */ Thread.sleep(250); } catch ( InterruptedException e ) { fail("Sleep was interrupted."); } } catch ( UsbException uE ) { fail ("Got exception setting Feature. Exception message: " + uE.getMessage() ); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = StandardRequest.getStatus(usbDevice, recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(target, requestType); featureSelection = UsbConst.FEATURE_SELECTOR_DEVICE_REMOTE_WAKEUP; statusExpected = 0; try { StandardRequest.clearFeature(usbDevice, recipientType, featureSelection, target); try { /*Wait for setConfiguration Data event before continuing */ Thread.sleep(250); } catch ( InterruptedException e ) { fail("Sleep was interrupted."); } } catch ( UsbException uE ) { fail ("Got exception clearing Feature. Exception message: " + uE.getMessage() ); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = StandardRequest.getStatus(usbDevice, recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(target, requestType); recipientType = 3; LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = StandardRequest.getStatus(usbDevice, recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { usbExceptionThrown = true; } finally { assertTrue("UsbException should have been thrown for using an illegal recipient type: " + UsbUtil.toHexString(recipientType), usbExceptionThrown); } try { Thread.sleep (250); } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } /* Verify proper listener event received */ assertNull("DeviceDataEvent should be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); configurationNumber = 1; //no target needed when recipient is a device target = 0; //set recipientType to Interface recipientType = UsbConst.REQUESTTYPE_RECIPIENT_INTERFACE; requestType = UsbConst.REQUESTTYPE_DIRECTION_IN + UsbConst.REQUESTTYPE_RECIPIENT_INTERFACE; statusExpected = 0; // @P2D15 LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { try { usbDevice.getActiveUsbConfiguration().getUsbInterface((byte) target).claim(); } catch ( UsbClaimException uCE ) { fail("Config " + configurationNumber + " Interface " + target + " is already claimed!"); } catch ( UsbNotActiveException uNAE ) { fail("Config " + configurationNumber + " is not active!"); } catch ( UsbException uE ) { fail("Config " + configurationNumber + " could not be claimed!"); } catch ( UsbDisconnectedException uDE ) // @P1C { // @P1A fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A } // @P1A status = StandardRequest.getStatus(usbDevice, recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } // status should be 0 since interface status cannot be changed status = 0; assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } // Verify proper listener event received assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(target, requestType); short endpoint; configurationNumber = 1; status = 0; //no target needed when recipient is a device target = 0; //set recipientType to Interface recipientType = UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; requestType = UsbConst.REQUESTTYPE_DIRECTION_IN + UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; statusExpected = 1; endpoint = 0x82; // @P2D15 LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = StandardRequest.getStatus(usbDevice, recipientType, endpoint); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } /*status is unknown at this point, so don't check the value yet */ } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(endpoint, requestType); featureSelection = UsbConst.FEATURE_SELECTOR_ENDPOINT_HALT; statusExpected = 1; try { StandardRequest.setFeature(usbDevice, recipientType, featureSelection, endpoint); try { /*Wait for setConfiguration Data event before continuing */ Thread.sleep(250); } catch ( InterruptedException e ) { fail("Sleep was interrupted."); } } catch ( UsbException uE ) { fail ("Got exception setting Feature. Exception message: " + uE.getMessage() ); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = StandardRequest.getStatus(usbDevice, recipientType, endpoint); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(endpoint, requestType); featureSelection = UsbConst.FEATURE_SELECTOR_ENDPOINT_HALT; statusExpected = 0; try { StandardRequest.clearFeature(usbDevice, recipientType, featureSelection, endpoint); try { /*Wait for setConfiguration Data event before continuing */ Thread.sleep(250); } catch ( InterruptedException e ) { fail("Sleep was interrupted."); } } catch ( UsbException uE ) { fail ("Got exception clearing Feature. Exception message: " + uE.getMessage() ); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = StandardRequest.getStatus(usbDevice, recipientType, endpoint); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(endpoint, requestType); recipientType = 3; LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = StandardRequest.getStatus(usbDevice, recipientType, endpoint); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { usbExceptionThrown = true; } finally { assertTrue("UsbException should have been thrown for using an illegal recipient type: " + UsbUtil.toHexString(recipientType), usbExceptionThrown); } try { Thread.sleep (250); } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } try { usbDevice.getActiveUsbConfiguration().getUsbInterface((byte) target).release(); } catch ( UsbClaimException uCE ) { fail("Config " + configurationNumber + " Interface " + target + " is not claimed!"); } catch ( UsbException uE ) { fail("Config " + configurationNumber + " could not be released!"); } catch ( UsbDisconnectedException uDE ) // @P1C { // @P1A fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A } // @P1A /* Verify proper listener event received */ assertNull("DeviceDataEvent should be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); } public void testGetStatusNonStatic() { StandardRequest standardRequest = new StandardRequest(usbDevice); short configurationNumber; byte recipientType; short featureSelection; short target; short wIndex; short status; short statusExpected; byte requestType; boolean usbExceptionThrown = false; configurationNumber = 1; status = 0; //no target needed when recipient is a device target = 0; //set recipientType to Device recipientType = UsbConst.REQUESTTYPE_RECIPIENT_DEVICE; requestType = UsbConst.REQUESTTYPE_DIRECTION_IN; statusExpected = 0; // @P2D16 LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = standardRequest.getStatus(recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } /*status is unknown at this point, so don't check the value yet*/ } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(target, requestType); featureSelection = UsbConst.FEATURE_SELECTOR_DEVICE_REMOTE_WAKEUP; statusExpected = 2; try { standardRequest.setFeature(recipientType, featureSelection, target); try { /*Wait for setConfiguration Data event before continuing */ Thread.sleep(250); } catch ( InterruptedException e ) { fail("Sleep was interrupted."); } } catch ( UsbException uE ) { fail ("Got exception setting Feature. Exception message: " + uE.getMessage() ); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = standardRequest.getStatus(recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(target, requestType); featureSelection = UsbConst.FEATURE_SELECTOR_DEVICE_REMOTE_WAKEUP; statusExpected = 0; try { standardRequest.clearFeature(recipientType, featureSelection, target); try { /*Wait for setConfiguration Data event before continuing */ Thread.sleep(250); } catch ( InterruptedException e ) { fail("Sleep was interrupted."); } } catch ( UsbException uE ) { fail ("Got exception clearing Feature. Exception message: " + uE.getMessage() ); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = standardRequest.getStatus(recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(target, requestType); recipientType = 3; LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = standardRequest.getStatus(recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { usbExceptionThrown = true; } finally { assertTrue("UsbException should have been thrown for using an illegal recipient type: " + UsbUtil.toHexString(recipientType), usbExceptionThrown); } try { Thread.sleep (250); } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } /* Verify proper listener event received */ assertNull("DeviceDataEvent should be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); configurationNumber = 1; //no target needed when recipient is a device target = 0; //set recipientType to Interface recipientType = UsbConst.REQUESTTYPE_RECIPIENT_INTERFACE; requestType = UsbConst.REQUESTTYPE_DIRECTION_IN + UsbConst.REQUESTTYPE_RECIPIENT_INTERFACE; statusExpected = 0; // @P2D16 LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { try { usbDevice.getActiveUsbConfiguration().getUsbInterface((byte) target).claim(); } catch ( UsbClaimException uCE ) { fail("Config " + configurationNumber + " Interface " + target + " is already claimed!"); } catch ( UsbNotActiveException uNAE ) { fail("Config " + configurationNumber + " is not active!"); } catch ( UsbException uE ) { fail("Config " + configurationNumber + " could not be claimed!"); } catch ( UsbDisconnectedException uDE ) // @P1C { // @P1A fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A } // @P1A status = standardRequest.getStatus(recipientType, target); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } // status should be 0 since interface status cannot be changed status = 0; assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } // Verify proper listener event received assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(target, requestType); short endpoint; configurationNumber = 1; status = 0; //no target needed when recipient is a device target = 0; //set recipientType to Interface recipientType = UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; requestType = UsbConst.REQUESTTYPE_DIRECTION_IN + UsbConst.REQUESTTYPE_RECIPIENT_ENDPOINT; statusExpected = 1; endpoint = 0x82; // @P2D16 LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = standardRequest.getStatus(recipientType, endpoint); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } /*status is unknown at this point, so don't check the value yet */ } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(endpoint, requestType); featureSelection = UsbConst.FEATURE_SELECTOR_ENDPOINT_HALT; statusExpected = 1; try { standardRequest.setFeature(recipientType, featureSelection, endpoint); try { /*Wait for setConfiguration Data event before continuing */ Thread.sleep(250); } catch ( InterruptedException e ) { fail("Sleep was interrupted."); } } catch ( UsbException uE ) { fail ("Got exception setting Feature. Exception message: " + uE.getMessage() ); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = standardRequest.getStatus(recipientType, endpoint); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(endpoint, requestType); featureSelection = UsbConst.FEATURE_SELECTOR_ENDPOINT_HALT; statusExpected = 0; try { standardRequest.clearFeature(recipientType, featureSelection, endpoint); try { /*Wait for setConfiguration Data event before continuing */ Thread.sleep(250); } catch ( InterruptedException e ) { fail("Sleep was interrupted."); } } catch ( UsbException uE ) { fail ("Got exception clearing Feature. Exception message: " + uE.getMessage() ); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = standardRequest.getStatus(recipientType, endpoint); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } assertEquals("Status is not as expected. Expected value = " + statusExpected + ", Actual value = " + status, statusExpected, status); } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { fail ("Got illegal argument exception. Exception message" + iE.getMessage() ); } /* Verify proper listener event received */ assertNotNull("DeviceDataEvent should not be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); verifyGetStatusIrp(endpoint, requestType); recipientType = 3; LastUsbDeviceDataEvent = null; LastUsbDeviceErrorEvent = null; try { status = standardRequest.getStatus(recipientType, endpoint); try { /* * Wait for device event before leaving setFeature routine */ for ( int i = 0; i < 100; i++ ) { if ( (LastUsbDeviceDataEvent != null)| (LastUsbDeviceErrorEvent != null) ) { break; } Thread.sleep( 20 ); //wait 20 ms before checking for event } } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } } catch ( UsbException uE ) { fail ("Got exception getting the device status. Exception message: " + uE.getMessage()); } catch ( IllegalArgumentException iE ) { usbExceptionThrown = true; } finally { assertTrue("UsbException should have been thrown for using an illegal recipient type: " + UsbUtil.toHexString(recipientType), usbExceptionThrown); } try { Thread.sleep (250); } catch ( InterruptedException e ) { fail("Sleep was interrupted"); } try { usbDevice.getActiveUsbConfiguration().getUsbInterface((byte) target).release(); } catch ( UsbClaimException uCE ) { fail("Config " + configurationNumber + " Interface " + target + " is not claimed!"); } catch ( UsbException uE ) { fail("Config " + configurationNumber + " could not be released!"); } catch ( UsbDisconnectedException uDE ) // @P1C { // @P1A fail ("A connected device should't throw the UsbDisconnectedException!"); // @P1A } // @P1A /* Verify proper listener event received */ assertNull("DeviceDataEvent should be null.", LastUsbDeviceDataEvent); assertNull("DeviceErrorEvent should be null.", LastUsbDeviceErrorEvent); } private void verifyGetStatusIrp (short expectedwIndex,byte expectedbmRequestType) { //IRP values expected in get feature Irp byte expectedbRequest = UsbConst.REQUEST_GET_STATUS; short expectedwValue = 0; short expectedLength = 2; byte[] expectedData = new byte[expectedLength]; expectedbmRequestType = (byte)(expectedbmRequestType | // @P3A UsbConst.REQUESTTYPE_TYPE_STANDARD | // @P3A UsbConst.REQUESTTYPE_DIRECTION_IN); // @P3A expectedData[1] = (byte)0; expectedData[0] = (byte)0; VerifyIrpMethods.verifyRequestTestData(LastUsbDeviceDataEvent.getUsbControlIrp(), expectedbmRequestType, expectedbRequest, expectedwValue, expectedwIndex, expectedLength); } private UsbDeviceListener deviceListener = new UsbDeviceListener() { public void dataEventOccurred(UsbDeviceDataEvent uddE) { assertNotNull(uddE); LastUsbDeviceDataEvent = uddE; } public void errorEventOccurred(UsbDeviceErrorEvent udeE) { assertNotNull(udeE); LastUsbDeviceErrorEvent = udeE; } public void usbDeviceDetached(UsbDeviceEvent udE) { assertNotNull(udE); fail("No devices should be detached during this test."); } }; private UsbDeviceDataEvent LastUsbDeviceDataEvent = null ; private UsbDeviceErrorEvent LastUsbDeviceErrorEvent = null; private UsbDevice usbDevice; }
package joshua.decoder; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.logging.Logger; import joshua.util.Regex; import joshua.util.io.LineReader; /** * Configuration file for Joshua decoder. * * When adding new features to Joshua, any new configurable parameters should be added to this * class. * * @author Zhifei Li, <zhifei.work@gmail.com> * @author Matt Post <post@cs.jhu.edu> */ public class JoshuaConfiguration { // List of language models to load public static ArrayList<String> lms = new ArrayList<String>(); // List of grammar files to read public static ArrayList<String> tms = new ArrayList<String>(); /* * The file to read the weights from (part of the sparse features implementation). Weights can * also just be listed in the main config file. */ public static String weights_file = ""; // Default symbols. The symbol here should be enclosed in square brackets. public static String default_non_terminal = "[X]"; public static String goal_symbol = "[GOAL]"; /* * If false, sorting of the complete grammar is done at load time. If true, grammar tries are not * sorted till they are first accessed. Amortized sorting means you get your first translation * much, much quicker (good for debugging), but that per-sentence decoding is a bit slower. */ public static boolean amortized_sorting = true; // syntax-constrained decoding public static boolean constrain_parse = false; public static boolean use_pos_labels = false; // oov-specific public static boolean true_oovs_only = false; /* Dynamic sentence-level filtering. */ public static boolean filter_grammar = false; /* The cube pruning pop limit. Set to 0 for exhaustive pruning. */ public static int pop_limit = 100; /* Maximum sentence length. Sentences longer than this are truncated. */ public static int maxlen = 200; /* * N-best configuration. */ // Make sure output strings in the n-best list are unique. public static boolean use_unique_nbest = false; /* Include the phrasal alignments in the output (not word-level alignmetns at the moment). */ public static boolean include_align_index = false; /* The number of hypotheses to output by default. */ public static int topN = 1; /* * This string describes the format of each line of output from the decoder (i.e., the * translations). The string can include arbitrary text and also variables. The following * variables are available: * * <pre> * %i the 0-indexed sentence number * %e the source string * %s the translated sentence * %S the translated sentence with some basic capitalization and denormalization * %t the synchronous derivation * %f the list of feature values (as name=value pairs) * %c the model cost * %w the weight vector * %a the alignments between source and target words (currently unimplemented) * %d a verbose, many-line version of the derivation * </pre> */ public static String outputFormat = "%i ||| %s ||| %f ||| %c"; /* The number of decoding threads to use (-threads). */ public static int num_parallel_decoders = 1; // disk hg public static String hypergraphFilePattern = ""; // hypergraph visualization public static boolean visualize_hypergraph = false; // use google linear corpus gain? public static boolean useGoogleLinearCorpusGain = false; public static double[] linearCorpusGainThetas = null; /* * When true, _OOV is appended to all words that are passed through (useful for something like * transliteration on the target side */ public static boolean mark_oovs = true; // used to extract oracle hypotheses from the forest public static String oracleFile = null; /* Enables synchronous parsing. */ public static boolean parse = false; // perform synchronous parsing private static final Logger logger = Logger.getLogger(JoshuaConfiguration.class.getName()); /* A list of the feature functions. */ public static ArrayList<String> features = new ArrayList<String>(); /* A list of weights found in the main config file (instead of in a separate weights file) */ public static ArrayList<String> weights = new ArrayList<String>(); /* If set, Joshua will start a (multi-threaded, per "threads") TCP/IP server on this port. */ public static int server_port = 0; // Methods /** * To process command-line options, we write them to a file that looks like the config file, and * then call readConfigFile() on it. It would be more general to define a class that sits on a * stream and knows how to chop it up, but this was quicker to implement. */ public static void processCommandLineOptions(String[] options) { try { File tmpFile = File.createTempFile("options", null, null); PrintWriter out = new PrintWriter(new FileWriter(tmpFile)); for (int i = 0; i < options.length; i++) { String key = options[i].substring(1); if (i + 1 == options.length || options[i + 1].startsWith("-")) { // if this is the last item, or if the next item // is another flag, then this is an argument-less // flag out.println(key + "=true"); } else { out.println(key + "=" + options[i + 1]); // skip the next item i++; } } out.close(); JoshuaConfiguration.readConfigFile(tmpFile.getCanonicalPath()); tmpFile.delete(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } // This is static instead of a constructor because all the fields // are static. public static void readConfigFile(String configFile) throws IOException { LineReader configReader = new LineReader(configFile); try { for (String line : configReader) { line = line.trim(); // .toLowerCase(); if (Regex.commentOrEmptyLine.matches(line)) continue; /* * There are two kinds of substantive (non-comment, non-blank) lines: parameters and feature * values. Parameters match the pattern "key = value"; all other substantive lines are * interpreted as features. */ if (line.indexOf("=") != -1) { // parameters; (not feature function) String[] fds = Regex.equalsWithSpaces.split(line); if (fds.length != 2) { logger.severe("* FATAL: bad config file line '" + line + "'"); System.exit(1); } String parameter = normalize_key(fds[0]); // store the line for later processing if (parameter.equals(normalize_key("lm"))) { lms.add(fds[1]); } else if (parameter.equals(normalize_key("tm"))) { tms.add(fds[1]); } else if (parameter.equals(normalize_key("parse"))) { parse = Boolean.parseBoolean(fds[1]); logger.finest(String.format("parse: %s", parse)); } else if (parameter.equals(normalize_key("dump-hypergraph"))) { hypergraphFilePattern = fds[1].trim(); logger .finest(String.format(" hypergraph dump file format: %s", hypergraphFilePattern)); } else if (parameter.equals(normalize_key("default-non-terminal"))) { default_non_terminal = "[" + fds[1].trim() + "]"; // default_non_terminal = fds[1].trim(); logger.finest(String.format("default_non_terminal: %s", default_non_terminal)); } else if (parameter.equals(normalize_key("goal-symbol"))) { goal_symbol = fds[1].trim(); // If the goal symbol was not enclosed in square brackets, then add them if (!goal_symbol.matches("\\[.*\\]")) goal_symbol = "[" + goal_symbol + "]"; logger.finest("goalSymbol: " + goal_symbol); } else if (parameter.equals(normalize_key("weights-file"))) { weights_file = fds[1]; } else if (parameter.equals(normalize_key("constrain_parse"))) { constrain_parse = Boolean.parseBoolean(fds[1]); } else if (parameter.equals(normalize_key("true_oovs_only"))) { true_oovs_only = Boolean.parseBoolean(fds[1]); } else if (parameter.equals(normalize_key("filter-grammar"))) { filter_grammar = Boolean.parseBoolean(fds[1]); } else if (parameter.equals(normalize_key("amortize"))) { amortized_sorting = Boolean.parseBoolean(fds[1]); } else if (parameter.equals(normalize_key("use_pos_labels"))) { use_pos_labels = Boolean.parseBoolean(fds[1]); } else if (parameter.equals(normalize_key("use_unique_nbest"))) { use_unique_nbest = Boolean.valueOf(fds[1]); logger.finest(String.format("use_unique_nbest: %s", use_unique_nbest)); } else if (parameter.equals(normalize_key("output-format"))) { outputFormat = fds[1]; logger.finest(String.format("output-format: %s", outputFormat)); } else if (parameter.equals(normalize_key("include_align_index"))) { include_align_index = Boolean.valueOf(fds[1]); logger.finest(String.format("include_align_index: %s", include_align_index)); } else if (parameter.equals(normalize_key("top_n"))) { topN = Integer.parseInt(fds[1]); logger.finest(String.format("topN: %s", topN)); } else if (parameter.equals(normalize_key("num_parallel_decoders")) || parameter.equals(normalize_key("threads"))) { num_parallel_decoders = Integer.parseInt(fds[1]); if (num_parallel_decoders <= 0) { throw new IllegalArgumentException( "Must specify a positive number for num_parallel_decoders"); } logger.finest(String.format("num_parallel_decoders: %s", num_parallel_decoders)); } else if (parameter.equals(normalize_key("visualize_hypergraph"))) { visualize_hypergraph = Boolean.valueOf(fds[1]); logger.finest(String.format("visualize_hypergraph: %s", visualize_hypergraph)); } else if (parameter.equals(normalize_key("mark_oovs"))) { mark_oovs = Boolean.valueOf(fds[1]); logger.finest(String.format("mark_oovs: %s", mark_oovs)); } else if (parameter.equals(normalize_key("pop-limit"))) { pop_limit = Integer.valueOf(fds[1]); logger.finest(String.format("pop-limit: %s", pop_limit)); } else if (parameter.equals(normalize_key("useGoogleLinearCorpusGain"))) { useGoogleLinearCorpusGain = new Boolean(fds[1].trim()); logger .finest(String.format("useGoogleLinearCorpusGain: %s", useGoogleLinearCorpusGain)); } else if (parameter.equals(normalize_key("googleBLEUWeights"))) { String[] googleWeights = fds[1].trim().split(";"); if (googleWeights.length != 5) { logger.severe("wrong line=" + line); System.exit(1); } linearCorpusGainThetas = new double[5]; for (int i = 0; i < 5; i++) linearCorpusGainThetas[i] = new Double(googleWeights[i]); logger.finest(String.format("googleBLEUWeights: %s", linearCorpusGainThetas)); } else if (parameter.equals(normalize_key("oracleFile"))) { oracleFile = fds[1].trim(); logger.info(String.format(" oracle file: %s", oracleFile)); if (!new File(oracleFile).exists()) { logger.warning("FATAL: can't find oracle file '" + oracleFile + "'"); System.exit(1); } } else if (parameter.equals(normalize_key("server-port"))) { server_port = Integer.parseInt(fds[1]); logger.info(String.format(" server-port: %d", server_port)); } else if (parameter.equals("c") || parameter.equals("config")) { // this was used to send in the config file, just ignore it ; } else if (parameter.equals(normalize_key("feature-function"))) { // add the feature to the list of features for later processing features.add("feature_function = " + fds[1]); } else if (parameter.equals(normalize_key("maxlen"))) { // add the feature to the list of features for later processing maxlen = Integer.parseInt(fds[1]); } else { if (parameter.equals(normalize_key("use-sent-specific-tm")) || parameter.equals(normalize_key("add-combined-cost")) || parameter.equals(normalize_key("use-tree-nbest")) || parameter.equals(normalize_key("use-kenlm")) || parameter.equals(normalize_key("useCubePrune")) || parameter.equals(normalize_key("useBeamAndThresholdPrune")) || parameter.equals(normalize_key("regexp-grammar"))) { logger.warning(String.format("WARNING: ignoring deprecated parameter '%s'", fds[0])); } else { logger.warning("FATAL: unknown configuration parameter '" + fds[0] + "'"); System.exit(1); } } logger.info(String.format(" %s = '%s'", normalize_key(fds[0]), fds[1])); } else { /* * Lines that don't have an equals sign and are not blank lines, empty lines, or comments, * are feature values, which can be present in this file */ weights.add(line); } } } finally { configReader.close(); } if (useGoogleLinearCorpusGain) { if (linearCorpusGainThetas == null) { logger.info("linearCorpusGainThetas is null, did you set googleBLEUWeights properly?"); System.exit(1); } else if (linearCorpusGainThetas.length != 5) { logger .info("linearCorpusGainThetas does not have five values, did you set googleBLEUWeights properly?"); System.exit(1); } } } /** * Checks for invalid variable configurations */ public static void sanityCheck() { } /** * Normalizes parameter names by removing underscores and hyphens and lowercasing. This defines * equivalence classes on external use of parameter names, permitting arbitrary_under_scores and * camelCasing in paramter names without forcing the user to memorize them all. Here are some * examples of equivalent ways to refer to parameter names: * * {pop-limit, poplimit, PopLimit, popLimit, pop_lim_it} {lmfile, lm-file, LM-FILE, lm_file} */ public static String normalize_key(String text) { return text.replaceAll("[-_]", "").toLowerCase(); } }
package algorithms; import algorithms.util.ObjectSpaceEstimator; import gnu.trove.map.TLongLongMap; import gnu.trove.map.TLongObjectMap; import gnu.trove.map.hash.TLongLongHashMap; import gnu.trove.map.hash.TLongObjectHashMap; import java.util.Arrays; import thirdparty.edu.princeton.cs.algs4.RedBlackBSTLongInt2; import thirdparty.ods.Longizer; import thirdparty.ods.XFastTrieLong; import thirdparty.ods.XFastTrieNodeLong; public class YFastTrieLong { /* designing from browsing a few different lecture notes online. the yfast trie uses same w and maxC as the XFastTrie. YFastTrie let w = max bit length specified by user, else is default 62 bits. a few examples here with data in mind for image pixel indexes, in which the maximum pixel index = width * height: If instead, one uses binSz = w to get the suggested yfasttrie runtime, one would have nEntries/binSz number of representatives. This is fewer entries into xfasttrie than if using xfasttrie alone so is conserving space. The calculations above for the suggested yfasttrie model: binsz = w mem is in MB: width=5000, height=7000 n= 35000000 mem= 61507: 505405 w=62 rt= 6 width=5000, height=7000 n= 35000000 mem= 9111: 14213 w=25 rt= 5 width=5000, height=7000 n= 3500000 mem= 53336: 492908 w=62 rt= 6 width=5000, height=7000 n= 3500000 mem= 940: 1716 w=25 rt= 5 width=1024, height=1024 n= 1048576 mem= 52700: 491936 w=62 rt= 6 width=1024, height=1024 n= 1048576 mem= 273: 428 w=20 rt= 4 width=1024, height=1024 n= 104858 mem= 52456: 491561 w=62 rt= 6 width=1024, height=1024 n= 104858 mem= 28: 54 w=20 rt= 4 width= 512, height= 512 n= 262144 mem= 52496: 491624 w=62 rt= 6 width= 512, height= 512 n= 262144 mem= 68: 107 w=18 rt= 4 width= 512, height= 512 n= 26214 mem= 52435: 491530 w=62 rt= 6 width= 512, height= 512 n= 26214 mem= 7: 13 w=18 rt= 4 width= 256, height= 256 n= 65536 mem= 52445: 491546 w=62 rt= 6 width= 256, height= 256 n= 65536 mem= 17: 27 w=16 rt= 4 width= 256, height= 256 n= 6554 mem= 52430: 491522 w=62 rt= 6 width= 256, height= 256 n= 6554 mem= 1: 3 w=16 rt= 4 width= 128, height= 128 n= 16384 mem= 52433: 491526 w=62 rt= 6 width= 128, height= 128 n= 16384 mem= 4: 6 w=14 rt= 4 width= 128, height= 128 n= 1638 mem= 52429: 491520 w=62 rt= 6 width= 128, height= 128 n= 1638 mem= 0: 0 w=14 rt= 4 width= 64, height= 64 n= 4096 mem= 52429: 491521 w=62 rt= 6 width= 64, height= 64 n= 4096 mem= 1: 1 w=12 rt= 4 width= 64, height= 64 n= 4096 mem= 1: 1 w=12 rt= 4 width= 64, height= 64 n= 410 mem= 52428: 491520 w=62 rt= 6 width= 64, height= 64 n= 410 mem= 0: 0 w=12 rt= 4 */ private int n = 0; private final int w; private final long maxC; private final long binSz; private long nBins; /** the minimum of each bin range, if it is populated, is the representative node, and that is held in 2 data structures: xft holds the number, allowing fast repr prev and next lookups. xftReps holds the repr as the value, found by key = binNumber. * the max number of trie entries will be nBins but there will be prefix trie nodes too */ private final XFastTrieLong<XFastTrieNodeLong<Long>, Long> xft; // key = bin index (which is node/binSz), value = repr value. // each repr value is the minimum stored in the bin. // * the max number of map entries will be nBins. private final TLongLongMap xftReps = new TLongLongHashMap(); // all inserts of this class are held in // * at most nBins number of trees which each // hold at most binSz number of entries. // each list item is a sorted binary search tree of numbers in that bin. // the value in the tree holds multiplicity of the number. // each list index can be found by node/binSz // each sorted tree has // key = node (inserted number), w/ value= // the number of times that number is present (multiplicity). private final TLongObjectMap<RedBlackBSTLongInt2> rbs; /** * constructor specifying the maximum number of bits of any future add or * find, etc, and is by default choosing the model for the fast runtime * which may be expensive in space requirements. * * @param wBits */ public YFastTrieLong(int wBits) { if (wBits < 63 && wBits > 1) { this.w = wBits; } else { throw new IllegalStateException("wBits " + " shoulw be greater than 1 and less than 32"); } maxC = (1L << w) - 1; binSz = w; nBins = (long)Math.ceil((double)maxC/(double)binSz); System.out.println("nBins=" + nBins + " rt of ops=" + (Math.log(binSz)/Math.log(2))); rbs = new TLongObjectHashMap<RedBlackBSTLongInt2>(); XFastTrieNodeLong<Long> clsNode = new XFastTrieNodeLong<Long>(); Longizer<Long> it = new Longizer<Long>() { @Override public long longValue(Long x) { return x; } }; xft = new XFastTrieLong<XFastTrieNodeLong<Long>, Long>(clsNode, it, w); } /** * constructor using the the maximum number of bits of 62 * and the default model for the fast runtime * which may be expensive in space requirements. * */ public YFastTrieLong() { this.w = 62; maxC = (1L << w) - 1; binSz = w; nBins = (long)Math.ceil((double)maxC/(double)binSz); System.out.println("nBins=" + nBins + " rt of ops=" + (Math.log(binSz)/Math.log(2))); rbs = new TLongObjectHashMap<RedBlackBSTLongInt2>(); XFastTrieNodeLong<Long> clsNode = new XFastTrieNodeLong<Long>(); Longizer<Long> it = new Longizer<Long>() { @Override public long longValue(Long x) { return x; } }; xft = new XFastTrieLong<XFastTrieNodeLong<Long>, Long>(clsNode, it, w); } protected RedBlackBSTLongInt2 getTreeMap(long index) { RedBlackBSTLongInt2 tree = rbs.get(index); if (tree == null) { tree = new RedBlackBSTLongInt2(); rbs.put(index, tree); } return tree; } /** * * @param node * @param index */ private void addToRBTree(long node, long index) { RedBlackBSTLongInt2 tree = getTreeMap(index); assert(tree != null); int[] output = new int[2]; tree.get(node, output); int multiplicity; if (output[0] == -1) { multiplicity = 1; } else { multiplicity = 1 + output[1]; } tree.put(node, multiplicity); } /** * * @param node * @param index */ private boolean deleteFromRBTree(long node, long index) { RedBlackBSTLongInt2 tree = getTreeMap(index); assert(tree != null); int[] output = new int[2]; tree.get(node, output); if (output[0] == -1) { return false; } int multiplicity = output[1]; if (multiplicity > 0) { multiplicity = output[1] - 1; if (multiplicity > 0) { tree.put(node, multiplicity); } } if (multiplicity == 0) { tree.delete(node); } return true; } /** * add node to the data structure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @param node a number >= 0 and having bit length * less than or equal to w. * @return true if successfully added node. */ public boolean add(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node.key must " + "be less than " + maxC + " node=" + node); } long index = node/binSz; long existingRepr = xftReps.get(index); if (!xftReps.containsKey(index)) { // insert is O(log_2(w)) + O(l-w) xft.add(Long.valueOf(node)); xftReps.put(index, node); } else if (node < existingRepr) { // delete is O(log_2(w)) + O(l-w) // insert is O(log_2(w)) + O(l-w) xft.remove(Long.valueOf(existingRepr)); xft.add(Long.valueOf(node)); xftReps.put(index, node); } addToRBTree(node, index); n++; return true; } /** * remove node from the data structure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * * @param node * @return */ public boolean remove(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node must " + "be less than " + maxC); } long index = node/binSz; boolean removed = deleteFromRBTree(node, index); if (!removed) { return false; } if (!xftReps.containsKey(index)) { return false; } RedBlackBSTLongInt2 tree = getTreeMap(index); long existingRepr = xftReps.get(index); if (tree.isEmpty()) { // just deleted the last item so remove from rbs // delete is O(log_2(w)) + O(w-l) if (xftReps.containsKey(index)) { xft.remove(Long.valueOf(existingRepr)); xftReps.remove(index); } } else if (node == existingRepr) { //existingRepr is maintained as the minimum in the bin, // so if a node w/ this value is removed and the multiplicity // was 1, need to assign a new repr int[] output = new int[2]; tree.get(node, output); int multiplicity = output[1]; if (output[0] == -1) { // remove the current repr and assign a new one // delete is O(log_2(w)) + O(w-l) xft.remove(Long.valueOf(existingRepr)); xftReps.remove(index); // O(log_2(N/w)) long[] kOutput = new long[2]; tree.min(kOutput); // tree is not empty assert(kOutput[0] != -1); long minKey = kOutput[1]; xft.add(minKey); xftReps.put(index, minKey); } } n return true; } /** * find node in the data structure and return it, else return -1. * * runtime complexity is at most O(log_2(w)) but since the map might not * be completely populated, the complexity might be smaller. * * @param node * @return the value of the node if present, else -1 */ public long find(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node must " + "be less than " + maxC + ". node=" + node); } long index = node/binSz; RedBlackBSTLongInt2 tree = getTreeMap(index); int[] output = new int[2]; tree.get(node, output); if (output[0] == -1) { return -1; } return node; } /** * find the largest node smaller in value than node in the datastructure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @param node * @return value preceding node, else -1 if there is not one */ public long predecessor(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node must " + "be less than " + maxC); } long nodeIndex = node/binSz; // the repr is stored in xft and it is always the minium for the bin boolean isAMinimum = xft.find(Long.valueOf(node)) != null; /* if the node is not a minima, the answer is in the node's map if its size is larger > 1 */ RedBlackBSTLongInt2 tree = getTreeMap(nodeIndex); if (!isAMinimum && (tree.size() > 1)) { long[] output = new long[2]; //tree.printPreOrderTraversal(); tree.lower(node, output); if (output[0] != -1) { return output[1]; } } // else, predeccessor is in the closest bin < nodeIndex that has // items in it. Long prev = xft.predecessor(Long.valueOf(node)); if (prev == null) { return -1; } long prev0Index = prev.longValue()/binSz; tree = getTreeMap(prev0Index); if (tree.isEmpty()) { return -1; } long[] kOutput = new long[2]; tree.max(kOutput); // tree is not empty assert(kOutput[0] != -1); long lastKey = kOutput[1]; return lastKey; } /** * find the smallest value larger than node in the data structure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @param node * @return the next node in the ordered data strucure, else -1 if no such * node exists. */ public long successor(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node must " + "be less than " + maxC); } Long nodeKey = Long.valueOf(node); long nodeIndex = node/binSz; boolean isAMinimum = xft.find(nodeKey) != null; RedBlackBSTLongInt2 tree = getTreeMap(nodeIndex); if (tree.size() > 1) { // if tree size > 1, the next key is the successor // else, the xft sucessor to nodeIndex is the successor long[] output = new long[2]; tree.higher(node, output); if (isAMinimum) { assert(output[0] != -1); return output[1]; } // else, the node is not a repr // if there is a tree successor to the node, that is the successor // else, the xft successor to nodeIndex is the successor if (output[0] != -1) { return output[1]; } } Long successorRepr = xft.successor(nodeKey); if (successorRepr == null) { return -1; } // the successor representative is then the next value return successorRepr; } /** * find the smallest node in the datastructure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @return minimum, else -1 if empty */ public long minimum() { if (xft.size() == 0) { return -1; } Long repr = xft.minimum(); // cannot be null if size > 0 assert(repr != null); return repr.longValue(); } /** * find the largest node in the data structure. * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @return maximum, else -1 if empty */ public long maximum() { if (xft.size() == 0) { return -1; } Long maxRepr = xft.maximum(); assert(maxRepr != null); long index = maxRepr.longValue()/binSz; RedBlackBSTLongInt2 tree = getTreeMap(index); assert(tree != null); assert(!tree.isEmpty()); long[] kOutput = new long[2]; tree.max(kOutput); assert(kOutput[0] != -1); long lastKey = kOutput[1]; return lastKey; } /** * find and remove the smallest value in the data structure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @return minimum, else -1 if empty */ public long extractMinimum() { //O(log_2(w)) long min = minimum(); if (min == -1) { assert(xft.size() == 0); return -1; } remove(min); return min; } /** * find and remove the largest value in the data structure. * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @return maximum, else -1 if empty */ public long extractMaximum() { long max = maximum(); if (max == -1) { assert(xft.size() == 0); return -1; } remove(max); return max; } /** * get the current number of values stored in the data structure. * @return */ public int size() { return n; } protected long getBinSz() { return binSz; } /** * estimate the size that an instance of YFastTrieLong with * n added entries, maxNumberOfBits, and * use binSzModel * would occupy in heap space in Bytes. * * NOTE: there are some varying components to estimating the memory that * depend upon the properties of the numbers inserted. * For example: * <pre> * -- xft is an XFastTrie instantiated with maxNumberOfBits. * It will have at most, * * nBins number of entries, where nBins * is determined by the BinSizeModel. * In addition to the number of inserted items (which is only one * per bin of numberOfEntries), there will be some undetermined * number of prefix nodes created in the process. * A factor of 5 more is assumed here to over estimate the total * number of trie nodes that includes the internal prefix nodes. * -- THE LOGIC is still in progress to determine * an upper and lower limit to estimate the number of populated * nBins w/o knowing properties of the numbers, such as whether * they are sequential, or have large gaps, etc. * -- xftReps is a hashMap with same number of inserts as xft, * so has the same need for an upper and lower estimate. * </pre> * * @param numberOfEntries amount of space for this object's instance * with n entries in Bytes on the heap. * @param maxNumberOfBits all entries must have bit lengths .lte. this * * @return array with 2 estimates, (1) estimate using all bins and a * factor of 5 for creating trie prefix nodes, (2) estimate from using 1/4 of the bins and a factor of 3 for creating the trie prefix nodes. */ public static long[] estimateSizeOnHeap(int numberOfEntries, int maxNumberOfBits) { long ww = maxNumberOfBits; long maxNumber = (1L << ww) - 1; long binSz = maxNumberOfBits; int nBins = (int)Math.ceil((double)maxNumber/(double)binSz); long total = 0; ObjectSpaceEstimator est = new ObjectSpaceEstimator(); est.setNIntFields(2); est.setNLongFields(3); est.setNBooleanFields(1); //objects: xft, xftReps, rbs est.setNObjRefsFields(3); total += est.estimateSizeOnHeap(); /* the minimum of each bin range, if it is populated, is the representative node, and that is held in 2 data structures: xft holds the number, allowing fast repr prev and next lookups. xftReps holds the repr as the value, found by key = binNumber. * the max number of trie entries will be nBins but there will be prefix trie nodes too private final XFastTrieLong<XFastTrieNodeLong<Long>, Long> xft; // key = bin index (which is node/binSz), value = repr value. // each repr value is the minimum stored in the bin. // * the max number of map entries will be nBins. private final TLongLongMap xftReps = new TLongLongHashMap(); // all inserts of this class are held in // * at most nBins number of trees which each // hold at most binSz number of entries. // each list item is a sorted binary search tree of numbers in that bin. // the value in the tree holds multiplicity of the number. // each list index can be found by node/binSz // each sorted tree has // key = node (inserted number), w/ value= // the number of times that number is present (multiplicity). TLongObjectMap<RedBlackBSTLongInt2> rbs; */ // returning 2 estimates // (1) estimate using all bins w/ factor 5 for tries // (2) estimate from using nBinsSparse of the nBins w/ factor 3 for tries int nBinsSparse = nBins/10; if (nBinsSparse < 1) { nBinsSparse = 1; } // using factor of 5 for total w/ prefix nodes long total2_1 = numberOfEntries * 5 * XFastTrieNodeLong.estimateSizeOnHeap(); // all nBins are filled w/ a repr total2_1 += XFastTrieLong.estimateSizeOnHeap(nBins, maxNumberOfBits); long total2_2 = numberOfEntries * 3 * XFastTrieNodeLong.estimateSizeOnHeap(); // nBinsSparse of nBins are filled w/ a repr total2_2 += XFastTrieLong.estimateSizeOnHeap(nBinsSparse, maxNumberOfBits); //TLongLongMap total2_1 += ObjectSpaceEstimator.estimateTLongLongHashMap(); //nBins number of repr entries in map total2_1 += (2 * nBins * ObjectSpaceEstimator.estimateLongSize()); //TLongLongMap total2_2 += ObjectSpaceEstimator.estimateTLongLongHashMap(); //nBins/4 number of repr entries in map total2_2 += (2 * nBinsSparse * ObjectSpaceEstimator.estimateLongSize()); // 1 TLongObjectMap<RedBlackBSTLongInt> rbs; total2_1 += ObjectSpaceEstimator.estimateTLongObjectHashMap(); total2_2 += ObjectSpaceEstimator.estimateTLongObjectHashMap(); // nBins number of RedBlackBSTLongInt long rbtree = RedBlackBSTLongInt2.estimateSizeOnHeap(0); long rbtreeNodes = RedBlackBSTLongInt2.estimateSizeOnHeap(numberOfEntries) - rbtree; total2_1 += (nBins * rbtree); total2_2 += (nBinsSparse * rbtree); // nEntries number of long, int nodes total2_1 += rbtreeNodes; total2_2 += rbtreeNodes; return new long[]{total2_1 + total, total2_2 + total}; } /** * print all entries in data structure to standard out. */ public void debugPrint() { long[] binIndexes = rbs.keys(); Arrays.sort(binIndexes); for (long binIdx : binIndexes) { System.out.println("binNumber=" + binIdx); RedBlackBSTLongInt2 rbt = rbs.get(binIdx); rbt.printPreOrderTraversal(); } } }
package atg.test; import static atg.test.AtgDustTestCase.AtgDustSystemProperties.ATG_DUST_DROP_TABLES; import static atg.test.AtgDustTestCase.AtgDustSystemProperties.HSQL_DB_LOCATION; import static atg.test.AtgDustTestCase.DbVendor.HSQLDBDefaultInMemoryDBConnection; import static atg.test.AtgDustTestCase.DbVendor.HSQLDBFileDBConnection; import static atg.test.AtgDustTestCase.DbVendor.HSQLDBRegularDBConnection; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import atg.adapter.gsa.GSATestUtils; import atg.nucleus.Nucleus; import atg.nucleus.NucleusTestUtils; import atg.nucleus.ServiceException; public class AtgDustTestCase extends TestCase { private static final Log log = LogFactory.getLog(AtgDustTestCase.class); private transient File configDir; private transient String configPath; private transient DBUtils dbUtils; private transient Nucleus nucleus; /** * An enum containing frequently set System properties * * @author robert * */ public static enum AtgDustSystemProperties { /** * Override Property. If this one is set to true at the beginning of your * test (System.setProperty(ATG_DUST_DO_NOT_DROP_TABLES.getPropertyName(), * "true")) then the InitializingGSA will not drop tables. This one was * needed (?) because never the less I configured the property file with * 'dropTablesIfExist=false' the tables would still be dropped because some * generated config file overwrote the existing one. <br/><br/> <b>This * should be a temporarily solution and should be fixed in future! </b> * */ ATG_DUST_DROP_TABLES("ATG_DUST_DROP_TABLES"), HSQL_DB_LOCATION(System.getProperty("java.io.tmpdir") + File.separator + "hsql_db"); private final String propertyName; private AtgDustSystemProperties(final String propertyName) { this.propertyName = propertyName; } public String getPropertyName() { return propertyName; } } public static enum DbVendor { DB2DBConnection, HSQLDBDefaultInMemoryDBConnection, HSQLDBFileDBConnection, HSQLDBRegularDBConnection, MSSQLDBConnection, MySQLDBConnection, OracleDBConnection, SolidDBConnection, SybaseDBConnection; } @Override protected void tearDown() throws Exception { super.tearDown(); if (dbUtils != null) { dbUtils.shutdown(); } if (nucleus != null) { log.info("Nucleus service stopping"); nucleus.stopService(); nucleus.doStopService(); nucleus.destroy(); } // log.info("Deleting: " + configDir.getAbsolutePath()); // deleteDir(configDir); } /** * @param servicePath * where to store the created property file for the given service, * relative to the {@link AtgDustTestCase#configDir} directory, set * by {@link #AtgDuster()#setConfigPath(String)} * @param serviceClass * a class that will be resolved by * {@link AtgDustTestCase#getService(String)} in a later step * @throws IOException */ protected final void createPropertyFile(final String servicePath, final Class<?> serviceClass) throws IOException { final Map<String, Class<?>> map = new HashMap<String, Class<?>>(); map.put(servicePath, serviceClass); createPropertyFiles(map); } /** * The same as {@link AtgDuster#createPropertyFile(String, Class)} but this * time uses a map with servicePath/serviceClass key/value pairs to facilitate * the creation of multiple config files at once * * @param pathsAndClasses * @throws IOException */ protected final void createPropertyFiles( final Map<String, Class<?>> pathsAndClasses) throws IOException { for (final Iterator<Entry<String, Class<?>>> it = pathsAndClasses .entrySet().iterator(); it.hasNext();) { final Entry<String, Class<?>> entry = it.next(); final File property = NucleusTestUtils.createProperties(entry.getKey(), configDir, entry.getValue().getName(), new Properties()); log.info("file: " + property.getAbsolutePath()); property.deleteOnExit(); } } /** * @param serviceName * the service to lookup and to be returned as a running usable * instance. Before calling this method make sure that the needed * property files are generated correctly using either * {@link AtgDustTestCase#createPropertyFile(String, Class)} or * {@link AtgDustTestCase#createPropertyFiles(Map)}. Another option * is to use existing property files by * {@link AtgDustTestCase#useExistingPropertyFiles(String, String[])} * @return a running usable instance of the serviceName or <code>null</code> * if there is an error. */ protected final Object getService(final String serviceName) { startNucleus(); return nucleus.resolveName(serviceName); } /** * Will prepare a test against an default in-memory hsql db. * * @param configpath * the location of the configuration directory * @param definitionFiles * the location of the repository definition files without trailing * slash * @param repoPath * the location of the repository in the 'nucleus' */ public void prepareRepositoryTest(final File configpath, final String[] definitionFiles, final String repoPath) throws Exception { prepareRepositoryTest(configpath, definitionFiles, repoPath, null, null, null, null, null, HSQLDBDefaultInMemoryDBConnection, false); } /** * Will prepare a repository test against an existing or an on-the-fly created * database. See SongRepositoryTest for example usage. * * * If {@link AtgDustTestCase.DbVendor} is {@link DbVendor#HSQLDBInMemoryDB} * then we only need configpath, definitionFiles, repoPath and dbName. <br/> * * If {@link AtgDustTestCase.DbVendor} is * {@link DbVendor#HSQLDBRegularDBConnection} then we only need the * configpath, definitionFiles, repoPath, dbName, host, userName and password * <br/> * * If {@link AtgDustTestCase.DbVendor} is * {@link DbVendor#HSQLDBFileDBConnection} then we only need the configpath, * definitionFiles, repoPath. The database will be created in * {@link System#getProperty("java.io.tmpdir")} + File.separator + "hsql_db")<br/> * * * If {@link AtgDustTestCase.DbVendor} is * {@link DbVendor#HSQLDBDefaultInMemoryDBConnection} then we only need the * configpath, definitionFiles, repoPath. The database will be created in * memory <br/> * * * @param configpath * the location of the configuration directory * @param definitionFiles * the location of the repository definition files without trailing * slash * @param repoPath * the location of the repository in the 'nucleus' * @param userName * the name of the schema owner. Can be null if * {@link AtgDustTestCase.DbVendor} is * {@link DbVendor#HSQLDBInMemoryDB} or * {@link DbVendor#HSQLDBFileDBConnection} or * {@link DbVendor#HSQLDBDefaultInMemoryDBConnection} * @param password * the schema owner password. Can be null if * {@link AtgDustTestCase.DbVendor} is * {@link DbVendor#HSQLDBInMemoryDB} or * {@link DbVendor#HSQLDBFileDBConnection} or * {@link DbVendor#HSQLDBDefaultInMemoryDBConnection} * @param host * the host of the database to use. Can be null if * {@link AtgDustTestCase.DbVendor} is * {@link DbVendor#HSQLDBInMemoryDB} or * {@link DbVendor#HSQLDBFileDBConnection} or * {@link DbVendor#HSQLDBDefaultInMemoryDBConnection} * @param port * the port of the database to use * @param dbName * the name of the database to use. Can be null if * {@link AtgDustTestCase.DbVendor} is * {@link DbVendor#HSQLDBFileDBConnection} or * {@link DbVendor#HSQLDBDefaultInMemoryDBConnection} * @param dbVendor * the vendor of the Database. Must be one of the * {@link AtgDustTestCase.DbVendor} types. * * @param dropTable * if set to <code>true</code> then existing tables will be dropped * and re-created if set to <code>false</code> the exiting tables * will be used * @throws Exception */ protected void prepareRepositoryTest(final File configpath, final String[] definitionFiles, final String repoPath, final String userName, final String password, final String host, final String port, final String dbName, final DbVendor dbVendor, final boolean dropTable) throws Exception { this.configDir = configpath; Properties props = null; switch (dbVendor) { case HSQLDBRegularDBConnection: props = DBUtils.getHSQLDBRegularDBConnection(dbName, host, userName, password); break; case HSQLDBFileDBConnection: props = DBUtils.getHSQLDBFileDBConnection(HSQL_DB_LOCATION .getPropertyName()); break; case MSSQLDBConnection: props = DBUtils.getMSSQLDBConnection(host, port, dbName, userName, password); break; case MySQLDBConnection: props = DBUtils.getMySQLDBConnection(host, port, dbName, userName, password); break; case DB2DBConnection: props = DBUtils .getDB2DBConnection(host, port, dbName, userName, password); break; case OracleDBConnection: props = DBUtils.getOracleDBConnection(host, port, dbName, userName, password); break; case SolidDBConnection: props = DBUtils.getSolidDBConnection(host, port, userName, password); break; case SybaseDBConnection: props = DBUtils.getSybaseDBConnection(host, port, dbName, userName, password); break; case HSQLDBDefaultInMemoryDBConnection: props = DBUtils.getHSQLDBInMemoryDBConnection(); break; default: log.error("Unsupported Database Vendor: " + dbVendor); break; } stopNucleus(); tearDown(); // TODO: Still have to come up with something better... System.setProperty(ATG_DUST_DROP_TABLES.getPropertyName(), Boolean .toString(dropTable)); if (dbVendor == HSQLDBDefaultInMemoryDBConnection || dbVendor == HSQLDBFileDBConnection || dbVendor == HSQLDBRegularDBConnection) { // Start up our database dbUtils = new DBUtils(props.getProperty("URL"), props .getProperty("driver"), props.getProperty("user"), props .getProperty("password")); } // Setup our test configpath GSATestUtils.getGSATestUtils().initializeMinimalConfigpath(configDir, repoPath, definitionFiles, props, null, null, null, true); } protected void startNucleus() { if (nucleus == null || !nucleus.isRunning()) { nucleus = NucleusTestUtils.startNucleus(configDir); } } protected void stopNucleus() { if (nucleus != null) { try { nucleus.stopService(); nucleus.doStopService(); nucleus.destroy(); } catch (ServiceException e) { log.error("Error: ", e); } } } /** * @param configPath * the configPath to be used. If the configuration files are located * in project/config then set this value to config. */ protected final void setConfigPath(final String configPath) { this.configPath = configPath; configDir = NucleusTestUtils.getConfigpath(this.getClass(), configPath); } /** * @param confPath * the configPath to be used. If the configuration files are for * example located in project/config then set this value to config * @param propertyFiles * an {@link String[]} with file path's as {@link java.lang.String}'s * with all needed properties files relative to * {@link AtgDustTestCase#configDir} <br/> Example: * /some/service/SomeService (Pay attention to the leading slash!) * @throws IOException */ protected final void useExistingPropertyFiles(final String confPath, final String[] propertyFiles) throws IOException { this.configPath = confPath.replace("/", File.separator); configDir = NucleusTestUtils.getConfigpath(this.getClass(), configPath); log.info("configPath: " + configPath); for (final String service : propertyFiles) { log.debug("Service: " + service); final String serviceDir = service.substring(0, service.lastIndexOf('/')); final File path = new File(configDir + File.separator + serviceDir); if (path.exists() ? true : path.mkdirs()) { log.debug("Created: " + path.getPath()); } else { log.error("unable to create: " + path.getPath()); } copyFile(configPath + File.separator + service.replace("/", File.separator) + ".properties", configDir .getPath() + service + ".properties".replaceAll("/", File.separator)); } } private void copyFile(final String src, final String dst) { try { log.info("Source: " + src); log.info("Dest: " + dst); final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { log.error("Error: ", e); } } // Delete all files and sub directories under dir. // Returns true if all deletions were successful. // If a deletion fails, the method stops attempting to delete and returns // false. @SuppressWarnings("unused") private boolean deleteDir(final File dir) { if (dir.isDirectory()) { final String[] children = dir.list(); for (int i = 0; i < children.length; i++) { final boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is now empty so delete it return dir.delete(); } }
package biweekly.util; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; /** * <p> * Represents a recurrence rule value. * </p> * <p> * This class is immutable. Use the inner class {@link Builder} to construct a * new instance. * </p> * <p> * <b>Code sample:</b> * * <pre class="brush:java"> * Recurrence rrule = new Recurrence.Builder(Frequency.WEEKLY).interval(2).build(); * Recurrence copy = new Recurrence.Builder(rrule).interval(3).build(); * </pre> * * </p> * @author Michael Angstadt * @rfc 5545 p.38-45 */ public final class Recurrence { private final Frequency frequency; private final Integer interval; private final Integer count; private final Date until; private final boolean untilHasTime; private final List<Integer> bySecond; private final List<Integer> byMinute; private final List<Integer> byHour; private final List<Integer> byMonthDay; private final List<Integer> byYearDay; private final List<Integer> byWeekNo; private final List<Integer> byMonth; private final List<Integer> bySetPos; private final List<DayOfWeek> byDay; private final List<Integer> byDayPrefixes; private final DayOfWeek workweekStarts; private final Map<String, List<String>> xrules; private Recurrence(Builder builder) { frequency = builder.frequency; interval = builder.interval; count = builder.count; until = builder.until; untilHasTime = builder.untilHasTime; bySecond = Collections.unmodifiableList(builder.bySecond); byMinute = Collections.unmodifiableList(builder.byMinute); byHour = Collections.unmodifiableList(builder.byHour); byMonthDay = Collections.unmodifiableList(builder.byMonthDay); byYearDay = Collections.unmodifiableList(builder.byYearDay); byWeekNo = Collections.unmodifiableList(builder.byWeekNo); byMonth = Collections.unmodifiableList(builder.byMonth); bySetPos = Collections.unmodifiableList(builder.bySetPos); byDay = Collections.unmodifiableList(builder.byDay); byDayPrefixes = Collections.unmodifiableList(builder.byDayPrefixes); workweekStarts = builder.workweekStarts; Map<String, List<String>> map = builder.xrules.getMap(); for (Map.Entry<String, List<String>> entry : map.entrySet()) { String key = entry.getKey(); List<String> value = entry.getValue(); map.put(key, Collections.unmodifiableList(value)); } xrules = Collections.unmodifiableMap(map); } /** * Gets the frequency. * @return the frequency or null if not set */ public Frequency getFrequency() { return frequency; } /** * Gets the date that the recurrence stops. * @return the date or null if not set */ public Date getUntil() { return (until == null) ? null : new Date(until.getTime()); } /** * Determines whether the UNTIL date has a time component. * @return true if it has a time component, false if it is strictly a date */ public boolean hasTimeUntilDate() { return untilHasTime; } /** * Gets the number of times the rule will be repeated. * @return the number of times to repeat the rule or null if not set */ public Integer getCount() { return count; } /** * Gets how often the rule repeats, in relation to the frequency. * @return the repetition interval or null if not set */ public Integer getInterval() { return interval; } /** * Gets the BYSECOND rule part. * @return the BYSECOND rule part or empty list if not set */ public List<Integer> getBySecond() { return bySecond; } /** * Gets the BYMINUTE rule part. * @return the BYMINUTE rule part or empty list if not set */ public List<Integer> getByMinute() { return byMinute; } /** * Gets the BYHOUR rule part. * @return the BYHOUR rule part or empty list if not set */ public List<Integer> getByHour() { return byHour; } /** * Gets the day components of the BYDAY rule part. * @return the day components of the BYDAY rule part or empty list if not * set */ public List<DayOfWeek> getByDay() { return byDay; } /** * Gets the numeric components of the BYDAY rule part. * @return the numeric components of the BYDAY rule part or empty list if * not set (BYDAY values without numeric components will have a "null" * number) */ public List<Integer> getByDayPrefixes() { return byDayPrefixes; } /** * Gets the BYMONTHDAY rule part. * @return the BYMONTHDAY rule part or empty list if not set */ public List<Integer> getByMonthDay() { return byMonthDay; } /** * Gets the BYYEARDAY rule part. * @return the BYYEARDAY rule part or empty list if not set */ public List<Integer> getByYearDay() { return byYearDay; } /** * Gets the BYWEEKNO rule part. * @return the BYWEEKNO rule part or empty list if not set */ public List<Integer> getByWeekNo() { return byWeekNo; } /** * Gets the BYMONTH rule part. * @return the BYMONTH rule part or empty list if not set */ public List<Integer> getByMonth() { return byMonth; } /** * Gets the BYSETPOS rule part. * @return the BYSETPOS rule part or empty list if not set */ public List<Integer> getBySetPos() { return bySetPos; } /** * Gets the day that the work week starts. * @return the day that the work week starts or null if not set */ public DayOfWeek getWorkweekStarts() { return workweekStarts; } /** * Gets the non-standard rule parts. * @return the non-standard rule parts */ public Map<String, List<String>> getXRules() { return xrules; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((byDay == null) ? 0 : byDay.hashCode()); result = prime * result + ((byDayPrefixes == null) ? 0 : byDayPrefixes.hashCode()); result = prime * result + ((byHour == null) ? 0 : byHour.hashCode()); result = prime * result + ((byMinute == null) ? 0 : byMinute.hashCode()); result = prime * result + ((byMonth == null) ? 0 : byMonth.hashCode()); result = prime * result + ((byMonthDay == null) ? 0 : byMonthDay.hashCode()); result = prime * result + ((bySecond == null) ? 0 : bySecond.hashCode()); result = prime * result + ((bySetPos == null) ? 0 : bySetPos.hashCode()); result = prime * result + ((byWeekNo == null) ? 0 : byWeekNo.hashCode()); result = prime * result + ((byYearDay == null) ? 0 : byYearDay.hashCode()); result = prime * result + ((count == null) ? 0 : count.hashCode()); result = prime * result + ((xrules == null) ? 0 : xrules.hashCode()); result = prime * result + ((frequency == null) ? 0 : frequency.hashCode()); result = prime * result + ((interval == null) ? 0 : interval.hashCode()); result = prime * result + ((until == null) ? 0 : until.hashCode()); result = prime * result + (untilHasTime ? 1231 : 1237); result = prime * result + ((workweekStarts == null) ? 0 : workweekStarts.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Recurrence other = (Recurrence) obj; if (byDay == null) { if (other.byDay != null) return false; } else if (!byDay.equals(other.byDay)) return false; if (byDayPrefixes == null) { if (other.byDayPrefixes != null) return false; } else if (!byDayPrefixes.equals(other.byDayPrefixes)) return false; if (byHour == null) { if (other.byHour != null) return false; } else if (!byHour.equals(other.byHour)) return false; if (byMinute == null) { if (other.byMinute != null) return false; } else if (!byMinute.equals(other.byMinute)) return false; if (byMonth == null) { if (other.byMonth != null) return false; } else if (!byMonth.equals(other.byMonth)) return false; if (byMonthDay == null) { if (other.byMonthDay != null) return false; } else if (!byMonthDay.equals(other.byMonthDay)) return false; if (bySecond == null) { if (other.bySecond != null) return false; } else if (!bySecond.equals(other.bySecond)) return false; if (bySetPos == null) { if (other.bySetPos != null) return false; } else if (!bySetPos.equals(other.bySetPos)) return false; if (byWeekNo == null) { if (other.byWeekNo != null) return false; } else if (!byWeekNo.equals(other.byWeekNo)) return false; if (byYearDay == null) { if (other.byYearDay != null) return false; } else if (!byYearDay.equals(other.byYearDay)) return false; if (count == null) { if (other.count != null) return false; } else if (!count.equals(other.count)) return false; if (xrules == null) { if (other.xrules != null) return false; } else if (!xrules.equals(other.xrules)) return false; if (frequency != other.frequency) return false; if (interval == null) { if (other.interval != null) return false; } else if (!interval.equals(other.interval)) return false; if (until == null) { if (other.until != null) return false; } else if (!until.equals(other.until)) return false; if (untilHasTime != other.untilHasTime) return false; if (workweekStarts != other.workweekStarts) return false; return true; } /** * Represents the frequency at which a recurrence rule repeats itself. * @author Michael Angstadt */ public static enum Frequency { SECONDLY, MINUTELY, HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY } /** * Represents each of the seven days of the week. * @author Michael Angstadt */ public static enum DayOfWeek { MONDAY("MO"), TUESDAY("TU"), WEDNESDAY("WE"), THURSDAY("TH"), FRIDAY("FR"), SATURDAY("SA"), SUNDAY("SU"); private final String abbr; private DayOfWeek(String abbr) { this.abbr = abbr; } /** * Gets the day's abbreviation. * @return the abbreviation (e.g. "MO" for Monday) */ public String getAbbr() { return abbr; } /** * Gets a day by its abbreviation. * @param abbr the abbreviation (case-insensitive, e.g. "MO" for Monday) * @return the day or null if not found */ public static DayOfWeek valueOfAbbr(String abbr) { for (DayOfWeek day : values()) { if (day.abbr.equalsIgnoreCase(abbr)) { return day; } } return null; } } /** * Constructs {@link Recurrence} objects. * @author Michael Angstadt */ public static class Builder { private Frequency frequency; private Integer interval; private Integer count; private Date until; private boolean untilHasTime; private List<Integer> bySecond; private List<Integer> byMinute; private List<Integer> byHour; private List<DayOfWeek> byDay; private List<Integer> byDayPrefixes; private List<Integer> byMonthDay; private List<Integer> byYearDay; private List<Integer> byWeekNo; private List<Integer> byMonth; private List<Integer> bySetPos; private DayOfWeek workweekStarts; private ListMultimap<String, String> xrules; /** * Constructs a new builder. * @param frequency the recurrence frequency */ public Builder(Frequency frequency) { this.frequency = frequency; bySecond = new ArrayList<Integer>(0); byMinute = new ArrayList<Integer>(0); byHour = new ArrayList<Integer>(0); byDay = new ArrayList<DayOfWeek>(0); byDayPrefixes = new ArrayList<Integer>(0); byMonthDay = new ArrayList<Integer>(0); byYearDay = new ArrayList<Integer>(0); byWeekNo = new ArrayList<Integer>(0); byMonth = new ArrayList<Integer>(0); bySetPos = new ArrayList<Integer>(0); xrules = new ListMultimap<String, String>(0); } /** * Constructs a new builder * @param recur the recurrence object to copy from */ public Builder(Recurrence recur) { frequency = recur.frequency; interval = recur.interval; count = recur.count; until = recur.until; untilHasTime = recur.untilHasTime; bySecond = new ArrayList<Integer>(recur.bySecond); byMinute = new ArrayList<Integer>(recur.byMinute); byHour = new ArrayList<Integer>(recur.byHour); byDay = new ArrayList<DayOfWeek>(recur.byDay); byDayPrefixes = new ArrayList<Integer>(recur.byDayPrefixes); byMonthDay = new ArrayList<Integer>(recur.byMonthDay); byYearDay = new ArrayList<Integer>(recur.byYearDay); byWeekNo = new ArrayList<Integer>(recur.byWeekNo); byMonth = new ArrayList<Integer>(recur.byMonth); bySetPos = new ArrayList<Integer>(recur.bySetPos); workweekStarts = recur.workweekStarts; xrules = new ListMultimap<String, String>(recur.xrules); } /** * Sets the frequency * @param frequency the frequency * @return this */ public Builder frequency(Frequency frequency) { this.frequency = frequency; return this; } /** * Sets the date that the recurrence stops. Note that the UNTIL and * COUNT fields cannot both be defined within the same rule. * @param until the date (time component is included) * @return this */ public Builder until(Date until) { return until(until, true); } /** * Sets the date that the recurrence stops. Note that the UNTIL and * COUNT fields cannot both be defined within the same rule. * @param until the date * @param hasTime true if the date has a time component, false if it's * strictly a date * @return this */ public Builder until(Date until, boolean hasTime) { if (until == null) { this.until = null; this.untilHasTime = false; } else { this.until = new Date(until.getTime()); this.untilHasTime = hasTime; } return this; } /** * Gets the number of times the rule will be repeated. Note that the * UNTIL and COUNT fields cannot both be defined within the same rule. * @param count the number of times to repeat the rule * @return this */ public Builder count(Integer count) { this.count = count; return this; } /** * Gets how often the rule repeats, in relation to the frequency. * @param interval the repetition interval * @return this */ public Builder interval(Integer interval) { this.interval = interval; return this; } /** * Adds a BYSECOND rule part. * @param bySecond the value to add * @return this */ public Builder bySecond(Integer bySecond) { this.bySecond.add(bySecond); return this; } /** * Adds a BYMINUTE rule part. * @param byMinute the value to add * @return this */ public Builder byMinute(Integer byMinute) { this.byMinute.add(byMinute); return this; } /** * Adds a BYHOUR rule part. * @param byHour the value to add * @return this */ public Builder byHour(Integer byHour) { this.byHour.add(byHour); return this; } /** * Adds a BYMONTHDAY rule part. * @param byMonthDay the value to add * @return this */ public Builder byMonthDay(Integer byMonthDay) { this.byMonthDay.add(byMonthDay); return this; } /** * Adds a BYYEARDAY rule part. * @param byYearDay the value to add * @return this */ public Builder byYearDay(Integer byYearDay) { this.byYearDay.add(byYearDay); return this; } /** * Adds a BYWEEKNO rule part. * @param byWeekNo the value to add * @return this */ public Builder byWeekNo(Integer byWeekNo) { this.byWeekNo.add(byWeekNo); return this; } /** * Adds a BYMONTH rule part. * @param byMonth the value to add * @return this */ public Builder byMonth(Integer byMonth) { this.byMonth.add(byMonth); return this; } /** * Adds a BYSETPOS rule part. * @param bySetPos the value to add * @return this */ public Builder bySetPos(Integer bySetPos) { this.bySetPos.add(bySetPos); return this; } /** * Adds a BYDAY rule part. * @param byDay the value to add * @return this */ public Builder byDay(DayOfWeek byDay) { return byDay(null, byDay); } /** * Adds a BYDAY rule part. * @param prefix the numeric prefix * @param byDay the value to add * @return this */ public Builder byDay(Integer prefix, DayOfWeek byDay) { this.byDayPrefixes.add(prefix); this.byDay.add(byDay); return this; } /** * Sets the day that the work week starts. * @param workweekStarts the day * @return this */ public Builder workweekStarts(DayOfWeek workweekStarts) { this.workweekStarts = workweekStarts; return this; } /** * Adds a non-standard rule part. * @param name the name * @param value the value or null to remove the rule part * @return this */ public Builder xrule(String name, String value) { name = name.toUpperCase(); if (value == null) { xrules.removeAll(name); } else { xrules.put(name, value); } return this; } /** * Builds the final {@link Recurrence} object. * @return the object */ public Recurrence build() { return new Recurrence(this); } } }
package com.cdboo.rest; import java.io.Serializable; import java.util.Date; import java.util.List; public class RestModel implements Serializable { private static final long serialVersionUID = 1L; private String userName; private String shopOwnerName; private String phoneNumber; private String businessHoursBegin; private String businessHoursEnd; private String address; private String photo; private Date serviceTimeBegin; private Date serviceTimeEnd; List<PlanModel> planModelList; // list public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getShopOwnerName() { return shopOwnerName; } public void setShopOwnerName(String shopOwnerName) { this.shopOwnerName = shopOwnerName; } public String getBusinessHoursBegin() { return businessHoursBegin; } public void setBusinessHoursBegin(String businessHoursBegin) { this.businessHoursBegin = businessHoursBegin; } public String getBusinessHoursEnd() { return businessHoursEnd; } public void setBusinessHoursEnd(String businessHoursEnd) { this.businessHoursEnd = businessHoursEnd; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public List<PlanModel> getPlanModelList() { return planModelList; } public void setPlanModelList(List<PlanModel> planModelList) { this.planModelList = planModelList; } public Date getServiceTimeBegin() { return serviceTimeBegin; } public void setServiceTimeBegin(Date serviceTimeBegin) { this.serviceTimeBegin = serviceTimeBegin; } public Date getServiceTimeEnd() { return serviceTimeEnd; } public void setServiceTimeEnd(Date serviceTimeEnd) { this.serviceTimeEnd = serviceTimeEnd; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } }
package com.kodcu.other; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.fop.apps.FopFactory; import org.joox.JOOX; import org.joox.Match; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.imageio.ImageIO; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.awt.image.BufferedImage; import java.io.*; import java.net.URLDecoder; import java.nio.charset.Charset; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.BiPredicate; import java.util.stream.Stream; public class IOHelper { private static final Logger logger = LoggerFactory.getLogger(IOHelper.class); public static void writeToFile(File file, String content, StandardOpenOption... openOption) { writeToFile(file.toPath(), content, openOption); } public static Optional<Exception> writeToFile(Path path, String content, StandardOpenOption... openOption) { try { Files.write(path, content.getBytes(Charset.forName("UTF-8")), openOption); } catch (Exception e) { logger.error("Problem occured while writing to {}", path, e); return Optional.of(e); } return Optional.empty(); } public static void writeToFile(Path path, byte[] content, StandardOpenOption... openOption) { try { Files.write(path, content, openOption); } catch (Exception e) { logger.error("Problem occured while writing {}", path, e); } } public static String readFile(InputStream inputStream) { String content = ""; try { content = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); } catch (Exception e) { logger.error("Problem occured while reading inputstream", e); } return content; } public static String readFile(Path path) { String content = ""; try (InputStream is = Files.newInputStream(path, StandardOpenOption.READ, StandardOpenOption.SYNC)) { content = IOUtils.toString(is, "UTF-8"); } catch (Exception e) { logger.error("Problem occured while reading file {}", path, e); } return content; } public static void createDirectories(Path path) { try { Files.createDirectories(path); } catch (Exception e) { logger.error("Problem occured while creating directories {}", path, e); } } public static Path createTempFile(String suffix) { try { return Files.createTempFile("asciidoc-temp", suffix); } catch (Exception e) { logger.error("Problem occured while creating temp file", e); } return null; } public static Path createTempFile(Path path, String suffix) { if (Objects.isNull(path)) { return createTempFile(suffix); } try { return Files.createTempFile(path, "asciidoc-temp", suffix); } catch (Exception e) { logger.error("Problem occured while creating temp file {}", path, e); } return null; } public static void copy(Path source, Path target, CopyOption... copyOptions) { try { Files.copy(source, target, copyOptions); } catch (Exception e) { logger.error("Problem occured while copying {} to {}", source, target, e); } } public static String pathToUrl(Path path) { try { return path.toUri().toURL().toString(); } catch (Exception e) { logger.error("Problem occured while getting URL of {}", path, e); } return null; } public static Stream<Path> list(Path path) { try { return Files.list(path); } catch (Exception e) { logger.error("Problem occured while listing {}", path, e); } return Stream.empty(); } public static void imageWrite(BufferedImage bufferedImage, String format, File output) { try { ImageIO.write(bufferedImage, format, output); } catch (Exception e) { logger.error("Problem occured while writing buff image to {}", output, e); } } public static byte[] readAllBytes(Path path) { try { return Files.readAllBytes(path); } catch (Exception e) { logger.error("Problem occured while reading {}", path, e); } return new byte[]{}; } public static void move(Path source, Path target, StandardCopyOption... option) { try { Files.move(source, target, option); } catch (Exception e) { logger.error("Problem occured while moving {} to {}", source, target, e); } } public static Match $(InputSource inputSource) { try { return JOOX.$(inputSource); } catch (SAXException | IOException e) { logger.error("Problem occured while selecting Match", e); } return null; } public static Match $(File file) { try { return JOOX.$(file); } catch (SAXException | IOException e) { logger.error("Problem occured while selecting Match for {}", file, e); } return JOOX.$(); } public static void transform(Transformer transformer, StreamSource xmlSource, StreamResult streamResult) { try { transformer.transform(xmlSource, streamResult); } catch (TransformerException e) { logger.error("Problem occured while transforming XML Source to Stream result", e); } } public static void matchWrite(Match root, File file) { try { root.write(file); } catch (Exception e) { logger.error("Problem occured while writing XML Match to {}", file, e); } } public static void copyDirectoryToDirectory(File source, File target) { try { FileUtils.copyDirectoryToDirectory(source, target); } catch (Exception e) { logger.error("Problem occured while copying {} to {}", source, target, e); } } public static void setUserConfig(FopFactory fopFactory, String configUri) { try { fopFactory.setUserConfig(configUri); } catch (SAXException | IOException e) { logger.error("Problem occured while setting {} as UserConfig", configUri, e); } } public static void deleteIfExists(Path path) { try { Files.deleteIfExists(path); } catch (Exception e) { logger.error("Problem occured while deleting {}", path, e); } } public static void copyDirectory(Path sourceDir, Path targetDir) { try { FileUtils.copyDirectory(sourceDir.toFile(), targetDir.toFile()); } catch (Exception e) { logger.error("Problem occured while copying {} to {}", sourceDir, targetDir, e); } } public static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes> matcher, FileVisitOption... options) { try { return Files.find(start, Integer.MAX_VALUE, matcher, options); } catch (Exception e) { logger.error("Problem occured while finding in path {}", start, e); } return Stream.empty(); } public static boolean isHidden(Path path) { try { return Files.exists(path) && (Files.isHidden(path) || path.getFileName().toString().startsWith(".")); } catch (Exception e) { // logger.error("Problem occured while detecting hidden path {}", path, e); } return false; } public static void copyFileToDirectory(File file, File directory) { try { FileUtils.copyFileToDirectory(file, directory); } catch (Exception e) { logger.error("Problem occured while copying {} to {}", file, directory, e); } } public static void copyFile(File file, File dest) { try { FileUtils.copyFile(file, dest); } catch (Exception e) { logger.error("Problem occured while copying {} to {}", file, dest, e); } } public static void createDirectory(Path path) { try { Files.createDirectory(path); } catch (Exception e) { logger.error("Problem occured while creating {} path", path, e); } } public static void deleteDirectory(Path path) { try { FileUtils.deleteDirectory(path.toFile()); } catch (Exception e) { logger.error("Problem occured while deleting {} path", path, e); } } public static List<String> readAllLines(Path path) { try { return Files.readAllLines(path); } catch (Exception e) { logger.error("Problem occured while reading {} path", path, e); } return new ArrayList<>(); } public static Reader fileReader(Path path) { try { FileInputStream fileInputStream = new FileInputStream(path.toFile()); return new InputStreamReader(fileInputStream, "UTF-8"); } catch (Exception e) { logger.error("Problem occured while creating FileReader for {} path", path, e); } return null; } public static void close(Closeable... closeables) { for (Closeable closeable : closeables) { try { closeable.close(); } catch (Exception e) { logger.error("Problem occured while closing resource"); } } } public static FileTime getLastModifiedTime(Path path) { try { return Files.getLastModifiedTime(path); } catch (Exception e) { // e.printStackTrace(); } return null; } public static String decode(String uri, String encoding) { try { return URLDecoder.decode(uri, encoding); } catch (UnsupportedEncodingException e) { // e.printStackTrace(); } return uri; } public static Path createTempDirectory(Path path, String prefix, FileAttribute<?>... attrs) { try { return Files.createTempDirectory(path, prefix, attrs); } catch (Exception e) { logger.error("Problem occured while creating temp directory"); } return null; } public static String getPathCleanName(Path object) { return object.getFileName().toString().replaceAll("\\..*", ""); } public static <T> T readFile(Path path, Class<T> clazz) { if (clazz.isAssignableFrom(byte[].class)) { return clazz.cast(readAllBytes(path)); } else { return clazz.cast(readFile(path)); } } }
package com.mergesort; import java.io.*; import java.util.Arrays; import java.util.Scanner; /** * Output data: 1 - to txt files, 2 - to console. * Default output to console! */ public class OutputData { private static final String fileName = "/Users/apple/IdeaProjects/mergesort/files/SortedDataValuesArray.txt"; public static void setArray(int[] array) { chooseOutput(array); } private static void chooseOutput(int[] array) { System.out.println("\n Please choose output data: 1 - to txt file, 2 - to console.\n Default output to console!"); Scanner in = new Scanner(System.in); System.out.print("\n Choose: "); String methodOutput = in.nextLine(); try { if (Integer.parseInt(methodOutput) == 1) { writeToFile(array); } else { consoleOutput(array); } } catch (NumberFormatException e) { consoleOutput(array); } } // private static void writeToFile(int[] array) { // ClassLoader classLoader = OutputData.class.getClassLoader(); // File file = new File(classLoader.getResource("SortedDataValuesArray.txt").getFile()); // try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { // for (int i : array) { // writer.write(i + " "); // } catch (IOException e) { // System.err.println("Something wrong"); private static void writeToFile(int[] array) { File file = new File(fileName); try (PrintWriter writer = new PrintWriter(file.getAbsoluteFile())) { for (int i : array) { writer.print(i + " "); } } catch (IOException e) { System.err.println(" Something wrong!"); } } private static void consoleOutput(int[] array) { System.out.println(Arrays.toString(array)); } }
package com.pillar; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class RomanNumerals { final private Map<Integer, String> numeralByNumber; public RomanNumerals() { Map<Integer, String> numeralByNumber = new LinkedHashMap<Integer, String>(); numeralByNumber.put(1, "I"); numeralByNumber.put(5, "V"); numeralByNumber.put(10, "X"); numeralByNumber.put(50, "L"); numeralByNumber.put(100, "C"); numeralByNumber.put(1000, "M"); this.numeralByNumber = numeralByNumber; } public String getNumeral(Integer number) { List<Entry<Integer,String>> tuple = findAdjacentNumerals(number); return toNumeral(number, tuple); } private String toNumeral(Integer number, List<Entry<Integer, String>> tuple) { if(number == 0){ return ""; } Entry<Integer, String> lower = tuple.get(0); if(tuple.size() == 1){ return lower.getValue(); } else { Entry<Integer, String> upper = tuple.get(1); if(upper == null){ return lower.getValue() + getNumeral(number - lower.getKey()); } else { if(upper.getKey() - lower.getKey() == number){ return lower.getValue() + upper.getValue(); }else if(3 * lower.getKey() == number){ return String.format("%s%s%s", lower.getValue(),lower.getValue(),lower.getValue()); }else if(upper.getKey() > number){ Entry<Integer,String> lowest = findAdjacentNumerals(lower.getKey() - 1).get(0); if(upper.getKey() - lower.getKey() == number){ return lower.getValue() + upper.getValue() + getNumeral(number - (lower.getKey() - upper.getKey())); }else if(upper.getKey() - lowest.getKey() <= number){ return lowest.getValue() + upper.getValue() + getNumeral(number - (upper.getKey() - lowest.getKey())); }else{ return lower.getValue() + lowest.getValue() + getNumeral(number - (lower.getKey() + lowest.getKey())); } }else{ return lower.getValue() + upper.getValue() + getNumeral(number - upper.getKey() - lower.getKey()); } } } } private List<Entry<Integer, String>> findAdjacentNumerals(Integer number) { Entry<Integer, String> lower = null, upper = null; for(Entry<Integer, String> entry : numeralByNumber.entrySet()){ if(number > entry.getKey()){ lower = entry; }else if(number < entry.getKey()){ upper = entry; break; }else{ return Arrays.asList(entry); } } return Arrays.asList(lower, upper); } }
package com.qiniu.sms; import com.qiniu.common.QiniuException; import com.qiniu.http.Client; import com.qiniu.http.MethodType; import com.qiniu.http.Response; import com.qiniu.sms.model.SignatureInfo; import com.qiniu.sms.model.TemplateInfo; import com.qiniu.util.Auth; import com.qiniu.util.Json; import com.qiniu.util.StringMap; import com.qiniu.util.UrlUtils; import java.util.Map; public class SmsManager { /** * Auth * Auth */ private final Auth auth; /** * HTTP Client * HTTP */ private final Client client; /** * Configuration * HTTP */ private Configuration configuration; /** * SmsManager * * @param auth Auth */ public SmsManager(Auth auth) { this.auth = auth; this.configuration = new Configuration(); client = new Client(this.configuration); } /** * SmsManager * * @param auth Auth * @param cfg Configuration */ public SmsManager(Auth auth, Configuration cfg) { this.auth = auth; this.configuration = cfg.clone(); client = new Client(this.configuration); } /** * * * @param templateId Id * @param mobiles * @param parameters , */ public Response sendMessage(String templateId, String[] mobiles, Map<String, String> parameters) throws QiniuException { String requestUrl = String.format("%s/v1/message", configuration.smsHost()); StringMap bodyMap = new StringMap(); bodyMap.put("template_id", templateId); bodyMap.put("mobiles", mobiles); bodyMap.put("parameters", parameters); return post(requestUrl, Json.encode(bodyMap).getBytes()); } /** * * * @param templateId Id * @param mobile * @param parameters , */ public Response sendSingleMessage(String templateId, String mobile, Map<String, String> parameters) throws QiniuException { String requestUrl = String.format("%s/v1/message/single", configuration.smsHost()); StringMap bodyMap = new StringMap(); bodyMap.put("template_id", templateId); bodyMap.put("mobile", mobile); bodyMap.put("parameters", parameters); return post(requestUrl, Json.encode(bodyMap).getBytes()); } /** * * * @param templateId Id * @param mobile * @param parameters , */ public Response sendOverseaMessage(String templateId, String mobile, Map<String, String> parameters) throws QiniuException { String requestUrl = String.format("%s/v1/message/oversea", configuration.smsHost()); StringMap bodyMap = new StringMap(); bodyMap.put("template_id", templateId); bodyMap.put("mobile", mobile); bodyMap.put("parameters", parameters); return post(requestUrl, Json.encode(bodyMap).getBytes()); } /** * ( ID) * * @param mobiles * @param content * 2877125 */ public Response sendFulltextMessage(String[] mobiles, String content) throws QiniuException { String requestUrl = String.format("%s/v1/message/fulltext", configuration.smsHost()); StringMap bodyMap = new StringMap(); bodyMap.put("mobiles", mobiles); bodyMap.put("content", content); return post(requestUrl, Json.encode(bodyMap).getBytes()); } /** * * * @param auditStatus , * : "passed"(), "rejected"(), "reviewing"() * @param page 1, * @param pageSize 20, */ public Response describeSignature(String auditStatus, int page, int pageSize) throws QiniuException { String requestUrl = String.format("%s/v1/signature", configuration.smsHost()); StringMap queryMap = new StringMap(); queryMap.putNotEmpty("audit_status", auditStatus); queryMap.putWhen("page", page, page > 0); queryMap.putWhen("page_size", pageSize, pageSize > 0); requestUrl = UrlUtils.composeUrlWithQueries(requestUrl, queryMap); return get(requestUrl); } public SignatureInfo describeSignatureItems(String auditStatus, int page, int pageSize) throws QiniuException { Response resp = describeSignature(auditStatus, page, pageSize); SignatureInfo signatureInfo = Json.decode(resp.bodyString(), SignatureInfo.class); return signatureInfo; } /** * * * @param signature * @param source * * enterprises_and_institutions * website * app APP * public_number_or_small_program * store_name * trade_name * @param pics base64 , */ public Response createSignature(String signature, String source, String[] pics) throws QiniuException { String requestUrl = String.format("%s/v1/signature", configuration.smsHost()); StringMap bodyMap = new StringMap(); bodyMap.put("signature", signature); bodyMap.put("source", source); bodyMap.putWhen("pics", pics, pics.length > 0); return post(requestUrl, Json.encode(bodyMap).getBytes()); } /** * * * @param signatureId Id, * @param signature , */ public Response modifySignature(String signatureId, String signature) throws QiniuException { String reqUrl = String.format("%s/v1/signature/%s", configuration.smsHost(), signatureId); StringMap bodyMap = new StringMap(); bodyMap.put("signature", signature); return put(reqUrl, Json.encode(bodyMap).getBytes()); } /** * * * @param signatureId Id, */ public Response deleteSignature(String signatureId) throws QiniuException { String requestUrl = String.format("%s/v1/signature/%s", configuration.smsHost(), signatureId); return delete(requestUrl); } /** * * * @param auditStatus , * : "passed"(), "rejected"(), "reviewing"() * @param page 1, * @param pageSize 20, */ public Response describeTemplate(String auditStatus, int page, int pageSize) throws QiniuException { String requestUrl = String.format("%s/v1/template", configuration.smsHost()); StringMap queryMap = new StringMap(); queryMap.putNotEmpty("audit_status", auditStatus); queryMap.putWhen("page", page, page > 0); queryMap.putWhen("page_size", pageSize, pageSize > 0); requestUrl = UrlUtils.composeUrlWithQueries(requestUrl, queryMap); return get(requestUrl); } public TemplateInfo describeTemplateItems(String auditStatus, int page, int pageSize) throws QiniuException { Response resp = describeTemplate(auditStatus, page, pageSize); TemplateInfo templateInfo = Json.decode(resp.bodyString(), TemplateInfo.class); return templateInfo; } /** * * * @param name , * @param template , * @param type , * : notification (), verification (), marketing () * @param description , * @param signatureId , */ public Response createTemplate(String name, String template, String type, String description, String signatureId) throws QiniuException { String requestUrl = String.format("%s/v1/template", configuration.smsHost()); StringMap bodyMap = new StringMap(); bodyMap.put("name", name); bodyMap.put("template", template); bodyMap.put("type", type); bodyMap.put("description", description); bodyMap.put("signature_id", signatureId); return post(requestUrl, Json.encode(bodyMap).getBytes()); } /** * * * @param templateId Id, * @param name , * @param template , * @param description , * @param signatureId , */ public Response modifyTemplate(String templateId, String name, String template, String description, String signatureId) throws QiniuException { String requestUrl = String.format("%s/v1/template/%s", configuration.smsHost(), templateId); StringMap bodyMap = new StringMap(); bodyMap.put("name", name); bodyMap.put("template", template); bodyMap.put("description", description); bodyMap.put("signature_id", signatureId); return put(requestUrl, Json.encode(bodyMap).getBytes()); } /** * * * @param templateId Id, */ public Response deleteTemplate(String templateId) throws QiniuException { String requestUrl = String.format("%s/v1/template/%s", configuration.smsHost(), templateId); return delete(requestUrl); } private Response get(String url) throws QiniuException { StringMap headers = composeHeader(url, MethodType.GET.toString(), null, Client.FormMime); return client.get(url, headers); } private Response post(String url, byte[] body) throws QiniuException { StringMap headers = composeHeader(url, MethodType.POST.toString(), body, Client.JsonMime); return client.post(url, body, headers, Client.JsonMime); } private Response put(String url, byte[] body) throws QiniuException { StringMap headers = composeHeader(url, MethodType.PUT.toString(), body, Client.JsonMime); return client.put(url, body, headers, Client.JsonMime); } private Response delete(String url) throws QiniuException { StringMap headers = composeHeader(url, MethodType.DELETE.toString(), null, Client.DefaultMime); return client.delete(url, headers); } private StringMap composeHeader(String url, String method, byte[] body, String contentType) { StringMap headers = auth.authorizationV2(url, method, body, contentType); headers.put("Content-Type", contentType); return headers; } }
package com.rultor.dynamo; import com.google.common.collect.Iterables; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Tv; import com.jcabi.dynamo.AttributeUpdates; import com.jcabi.dynamo.Item; import com.jcabi.xml.StrictXML; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; import com.jcabi.xml.XSL; import com.jcabi.xml.XSLDocument; import com.rultor.spi.Talk; import java.io.IOException; import java.util.Date; import lombok.EqualsAndHashCode; import lombok.ToString; import org.w3c.dom.Node; import org.xembly.Directive; import org.xembly.ImpossibleModificationException; import org.xembly.Xembler; /** * Talk in Dynamo. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.0 */ @Immutable @ToString @EqualsAndHashCode(of = "item") public final class DyTalk implements Talk { /** * Upgrade XSL. */ private static final XSL CLEANUP = XSLDocument.make( DyTalk.class.getResourceAsStream("cleanup.xsl") ); /** * Item. */ private final transient Item item; /** * Ctor. * @param itm Item */ DyTalk(final Item itm) { this.item = itm; } @Override public Long number() throws IOException { return Long.parseLong(this.item.get(DyTalks.ATTR_NUMBER).getN()); } @Override public String name() throws IOException { return this.item.get(DyTalks.HASH).getS(); } @Override public Date updated() throws IOException { return new Date( Long.parseLong(this.item.get(DyTalks.ATTR_UPDATED).getN()) ); } @Override public XML read() throws IOException { return new StrictXML( Talk.UPGRADE.transform( new XMLDocument(this.item.get(DyTalks.ATTR_XML).getS()) ), Talk.SCHEMA ); } @Override public void modify(final Iterable<Directive> dirs) throws IOException { if (!Iterables.isEmpty(dirs)) { final XML xml = this.read(); final Node node = xml.node(); try { new Xembler(dirs).apply(node); } catch (final ImpossibleModificationException ex) { throw new IllegalStateException( String.format( "failed to apply %s to %s", dirs.toString(), xml ), ex ); } final String body = DyTalk.CLEANUP.transform( new StrictXML(new XMLDocument(node), Talk.SCHEMA) ).toString(); if (body.length() > Tv.FIFTY * Tv.THOUSAND) { throw new IllegalArgumentException("XML is too big"); } this.item.put( new AttributeUpdates() .with(DyTalks.ATTR_XML, body) .with(DyTalks.ATTR_UPDATED, System.currentTimeMillis()) ); } } @Override public void active(final boolean yes) throws IOException { this.item.put( new AttributeUpdates() .with(DyTalks.ATTR_ACTIVE, yes) .with(DyTalks.ATTR_UPDATED, System.currentTimeMillis()) ); } }
package de.teiesti.postie; import org.pmw.tinylog.Logger; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * An {@link Office} accepts network connection on a given {@link ServerSocket} and spawns {@link Postman} to respond * to requests. A running {@link Office} awaits incoming connection, then clones the configured {@link Postman}, * hands over the connection and starts it. Afterwards it repeats this procedure.<br> * <br> * To setup an {@link Office} call {@link #spawn(Postman)} with a {@link Postman} that was configured with a {@link * Serializer} and all necessary {@link Recipient}s. If a {@link Socket} was bound it will be ignored. There is no * trouble if the {@link Postman} is running but the system may behaves strange if the {@link Postman}'s state is * changing. In addition, you must call {@link #bind(ServerSocket)} with a {@link ServerSocket}. To complete the * setup, call {@link #start()} which starts the required thread. If work is done call {@link #stop()}. */ public class Office { private ServerSocket serverSocket; private Postman blueprint; private Set<Postman> postmen = Collections.synchronizedSet(new HashSet<Postman>()); private final Recipient postmanHelper = new Recipient() { @Override public void accept(Object o, Postman from) { /* nothing to do */ } @Override public void noticeStart(Postman from) { /* nothing to do */ } @Override public void noticeStop(Postman from) { postmen.remove(from); } }; private Thread acceptor; public final synchronized Office bind(ServerSocket serverSocket) { if (serverSocket == null) throw new IllegalArgumentException("serverSocket == null"); this.serverSocket = serverSocket; return this; } public final synchronized Office spawn(Postman blueprint) { if (isRunning()) throw new IllegalStateException("cannot configure a blueprint because this is running"); if (blueprint == null) throw new IllegalArgumentException("blueprint == null"); this.blueprint = blueprint.register(postmanHelper); return this; } public final synchronized Office start() { if (isRunning()) throw new IllegalStateException("cannot start because this is already running"); // TODO check configuration, how? acceptor = new Acceptor(); acceptor.start(); return this; } public final synchronized Office stop() { return stop(false); } public final synchronized Office stop(boolean stopPostmen) { if (!isRunning()) throw new IllegalStateException("cannot stop because this is not running"); try { serverSocket.close(); acceptor.join(); } catch (IOException | InterruptedException e) { Logger.error(e); System.exit(1); } acceptor = null; if (stopPostmen) synchronized (postmen) { for (Postman p : postmen) { p.unregister(postmanHelper); p.stop(); } postmen.clear(); } return this; } /** * Returns weather this {@link Office} is running. * * @return if this {@link Office} is running. */ public final boolean isRunning() { return acceptor != null && acceptor.isAlive(); } private class Acceptor extends Thread { @Override public void run() { Socket socket; Postman postman; while (true) { try { socket = serverSocket.accept(); postman = blueprint.clone().bind(socket); postmen.add(postman); postman.start(); } catch (IOException | CloneNotSupportedException e) { if (e instanceof SocketException) break; Logger.error(e); System.exit(1); } } } } }
package de.teiesti.postie; import org.pmw.tinylog.Logger; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.Set; public class Office { private ServerSocket serverSocket; private Postman blueprint; private Set<Postman> postmen; private Thread acceptor; public Office bind(ServerSocket socket) { } public Office spawn(Postman blueprint) { } public Office start() { acceptor = new Acceptor(); acceptor.start(); return this; } public Office stop() { // TODO how to do this? } private class Acceptor extends Thread { @Override public void run() { Socket socket; Postman postman; while (!isInterrupted()) { try { socket = serverSocket.accept(); postman = blueprint.clone().bind(socket).start(); postmen.add(postman); } catch (IOException e) { Logger.error(e); System.exit(1); } } } } }
package dk.es.br.dibs; import java.io.*; import java.net.*; import java.security.Security; import com.sun.net.ssl.internal.ssl.Provider; import java.math.BigDecimal; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Currency; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DibsClient { private final static Logger LOG = LoggerFactory.getLogger(DibsClient.class); static { try { System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); Provider provider = new Provider(); Security.addProvider(provider); LOG.info("Added com.sun.net.ssl.internal.www.protocol security provider"); } catch (Exception e) { LOG.error("Error setting protocol handlers needed by DIBS: " + e); } } private final DibsConfig cfg; public DibsClient(DibsConfig cfg) { this.cfg = cfg; } /** * Deletes the specified account from the DIBS system. The account template * MUST define the merchant and the account id properties * * @param accountId the account to delete * @throws DibsException if the account does not exist or for some reason cannot be deleted */ public void deleteAccount(String accountId) throws DibsException { // First fill out the message to dibs Map msg = new HashMap(); msg.put("merchant", getMerchantId()); msg.put("ticket", accountId); // Query the DIBS server Map result = post("/cgi-adm/delticket.cgi", msg, true); String status = (String) result.get("status"); if (status == null || !status.equalsIgnoreCase("ACCEPTED")) throw new DibsException("'" + accountId + "': failed to delete account: " + result.get("message") + " (" + result.get("reason") + ")"); } private static enum Iso4217 { DKK("208"), EUR("978"), USD("840"), GBP("826"), SEK("752"), AUD("036"), CAD("124"), ISK("352"), JPY("392"), NZD("554"), NOK("578"), CHF("756"), TRL("792"); private final String code; private Iso4217(String code) { this.code = code; } } public static String codeOf(Currency currency) { /* replace with currency.getNumericCode() (as of java 1.7) sometime... */ Iso4217 dc = Iso4217.valueOf(currency.getCurrencyCode()); return dc.code; } /** * Checks the validity of the specified account in the DIBS system. This is * done by attempting to authorize a small transaction, and then immediately cancel * the authorization. * * @param accountId the account to check * @param cents the amount to test authorization against * @param currency the currency to test authorization against * @return "ok" if there are no problems. Or the response */ public DibsResponse validateCardSubscription(String accountId, int cents, Currency currency) throws DibsException { // First fill out the message to dibs - authorize a 1kr transfer Map params = new HashMap(); params.put("merchant", getMerchantId()); params.put("ticket", accountId); params.put("orderid", "checking-account"); params.put("amount", String.valueOf(cents)); params.put("currency", codeOf(currency)); // Query the DIBS server Map result = post("/cgi-ssl/ticket_auth.cgi", params, false); String status = (String)result.get("status"); if ("ACCEPTED".equalsIgnoreCase(status)) { // Checked out find. Now cancel the authorization: String transact = (String)result.get("transact"); // Change the status to be canceled params = new HashMap(); params.put("merchant", getMerchantId()); params.put("transact", transact); try { post("/cgi-adm/cancel.cgi", params, true); } catch (Exception ex) { LOG.error("Validate Account: Exception trying to cancel authorization " + transact, ex); } LOG.info(accountId + " checked positive"); return new CheckAccountResponse(true, result); } String reason = (String)result.get("reason"); String message = (String)result.get("message"); // Presume auth failed. Need to see if the cardholder is to blame switch (new Integer(reason)) { case 1: // Communication problems case 2: // Error in the parameters sent to the DIBS server case 3: // Error at the acquirer throw new RuntimeException("Account validation failed, " + result); } LOG.info(accountId + " checked negative (" + reason + ": " + message + ")"); return new CheckAccountResponse(false, result); } private Map post(String path, Map params, boolean auth) throws DibsException { long t1 = System.currentTimeMillis(); String query = formatQuery(params); URL url = dibsUrl(path); try { String response = _post(url, query, auth); Map res = parseResponse(response); LOG.info(path + "["+params+"] : " + res); return res; } finally { long t2 = System.currentTimeMillis(); LOG.info("DIBS call:" + path + " " + query + ": " + (t2-t1) + "ms"); } } private static URL dibsUrl(String path) { try { return new URL("https://payment.architrade.com" + path); } catch (MalformedURLException ex) { throw new IllegalArgumentException(path, ex); } } /** * This method will authorize and deduct the specified amount of money from * the specified account * * @param accountId the account to check * @param orderId the unique order id * @param amount the amount of money to deduct * @return the transaction id */ public TransactionInfo withdraw(String accountId, String orderId, BigDecimal amount, Currency currency) throws DibsException { long cents = Math.round(amount.doubleValue() * 100.0); // Sanity checks if (StringUtils.isEmpty(accountId)) throw new IllegalArgumentException("Account id missing"); if (StringUtils.isEmpty(orderId)) throw new IllegalArgumentException("Order id missing"); if (cents < 0) throw new DibsException("Cannot withdraw kr: " + amount); long t1 = System.currentTimeMillis(); LOG.info("Withdraw " + amount + " from card account " + accountId + ", orderId " + orderId); TransactionInfo transaction = withdrawCents(accountId, orderId, cents, currency); Long transactionId = transaction.transactionId(); BigDecimal feeAmount = transaction.feeAmount(); long t2 = System.currentTimeMillis(); LOG.info("Withdrew " + amount + " from card account " + accountId + ", orderId " + orderId + ": transaction " + transactionId + ", fee reported by Dibs: " + feeAmount + " (" + (t2-t1) + "ms)"); return transaction; } private TransactionInfo withdrawCents(String accountId, String orderId, long cents, Currency currency) throws DibsException { // First fill out the message to dibs Map msg = new HashMap(); msg.put("merchant", getMerchantId()); msg.put("ticket", accountId); msg.put("orderid", orderId); msg.put("amount", cents); msg.put("currency", codeOf(currency)); msg.put("capturenow", "yes"); msg.put("uniqueoid", "yes"); String md5key = md5of("merchant=" + getMerchantId() + "&orderid=" + orderId + "&ticket=" + accountId + "&currency=" + codeOf(currency) + "&amount=" + cents); msg.put("md5key", md5key); if (isTesting()) { msg.put("test", "yes"); msg.put("calcfee", "yes"); } // Query the DIBS server Map result = post("/cgi-ssl/ticket_auth.cgi", msg, false); String status = (String)result.get("status"); String message = (String)result.get("message"); if (!"ACCEPTED".equals(status)) throw new DibsException("Withdrawal " + status + ": " + message, (String)result.get("reason"), (String)result.get("actioncode")); String transact = (String)result.get("transact"); if (StringUtils.isEmpty(transact)) throw new DibsException("Withdrawal " + status + " without transaction: " + message, (String)result.get("reason"), (String)result.get("actioncode")); String reportedFee = (String)result.get("fee"); Long feeCents = reportedFee != null ? Long.valueOf(reportedFee) : new Long(0); final BigDecimal feeAmount = new BigDecimal(feeCents).scaleByPowerOfTen(-2); final Long transactionId = Long.valueOf(transact); return new TransactionInfo() { @Override public Long transactionId() { return transactionId; } @Override public BigDecimal feeAmount() { return feeAmount; } }; } public String getCardType(Long transactionId) throws DibsException { // First fill out the message to dibs Map msg = new HashMap(); msg.put("merchant", getMerchantId()); msg.put("transact", transactionId); // Query the DIBS server Map res = post("/cardtype.pml", msg, true); // Check that the transaction was executed properly. // If the card type is not recognized, "0" is returned String arg1 = (String)res.get("1"); if ("0".equals(arg1)) { LOG.info(transactionId + ": card type not recognized"); return null; } // The reply is the card type return arg1; } private String getMerchantId() { return cfg.getMerchantId(); } private String basicAuth() { String dibsUser = cfg.getDibsUser(); String dibsPass = cfg.getDibsPassword(); String userpass = dibsUser + ":" + dibsPass; return "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); } /** * Posts a request to the DIBS server. Solemnly stolen from DIBS' sample * DeltapayHTTP class. Small changes implemented. * * @param url the server * @param message the parameters * @param auth should we use basic authentication * @return the result */ private String _post(URL url, String message, boolean auth) throws DibsException { PrintWriter wrt; URLConnection conn; try { conn = url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); // conn.setConnectTimeout(...); // conn.setReadTimeout(....); if (auth) conn.setRequestProperty("Authorization", basicAuth()); OutputStream os = conn.getOutputStream(); wrt = new PrintWriter(os); } catch (IOException ex) { LOG.error(url + ": failed to connect", ex); throw new DibsException("failed to connect", ex); } try { wrt.println(message); } finally { wrt.close(); } StringBuilder res = new StringBuilder(); try { BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream())); try { String line; while ((line = rdr.readLine()) != null) res.append(line); } finally { rdr.close(); } } catch (IOException ex) { LOG.error(url + "[" + message + "]: failed to get response", ex); throw new DibsException("failed to get response", ex); } return res.toString(); } /** * Parses the response sent from the DIBS server and converts it into a param * name value map. * * @param s the response received from the server * @return the result map */ private static Map parseResponse(String s) { Map res = new HashMap(); StringTokenizer st = new StringTokenizer(s, "&"); while (st.hasMoreTokens()) { String s1 = st.nextToken(); StringTokenizer st2 = new StringTokenizer(s1, "="); String key = st2.countTokens() == 2 ? st2.nextToken().toLowerCase() : String.valueOf(res.size() + 1); String val = urlDecodeUTF8(st2.nextToken()); res.put(key, val); } return res; } private static String formatQuery(Map params) { StringBuilder msg = new StringBuilder(); // Always required params.put("textreply", "yes"); Iterator es = params.entrySet().iterator(); while (es.hasNext()) { Map.Entry e = (Map.Entry)es.next(); Object k = e.getKey(); Object v = e.getValue(); if (k == null || v == null) continue; if (msg.length() > 0) msg.append("&"); msg.append(k.toString()).append("=").append(urlEncodeUTF8(v.toString())); } return msg.toString(); } private static class CheckAccountResponse implements DibsResponse { private final boolean m_valid; private final String m_reason; private final String m_actionCode; private final Long m_transactionId; private CheckAccountResponse(boolean success, Map resultMap) { m_valid = success; m_reason = (String)resultMap.get("reason"); m_actionCode = (String)resultMap.get("actioncode"); String transact = (String)resultMap.get("transact"); m_transactionId = transact == null ? null : Long.valueOf(transact); } public boolean isValid() { return m_valid; } public String getReason() { return m_reason; } public String getActionCode() { return m_actionCode; } public Long getTransactionId() { return m_transactionId; } } private static String urlEncodeUTF8(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException ex) { // Can't happen throw new RuntimeException(ex); } } private static String urlDecodeUTF8(String nn) { try { return URLDecoder.decode(nn, "UTF-8"); } catch (UnsupportedEncodingException ex) { // Can't happen throw new RuntimeException(ex); } } private boolean isTesting() { return cfg.isTesting(); } public String md5of(String src) { return MD5(cfg.getMd5K1(), cfg.getMd5K2(), src); } public static String MD5(String src) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } md.update(src.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String res = "0000000000000000000000000000000" + hash.toString(16); res = res.substring(res.length() - 32); return res; } public static String MD5(String k1, String k2, String src) { return MD5(k2 + MD5(k1 + src)); } public interface TransactionInfo { Long transactionId(); BigDecimal feeAmount(); } }
package edu.hm.hafner; /** * Useless class - only for test-cases. * * @author Christian M&ouml;stl */ public class EmptyBlock { /** * Creates a new instance of {@link EmptyBlock}. * * @param a * number */ public EmptyBlock(final int a) { if (a > 0) { } } }
package froop.domain; import lombok.NonNull; import lombok.Value; @Value(staticConstructor = "of") public class SampleValue { private final int id; @NonNull private final String name; }
package hackerrank; import java.util.Arrays; import java.util.Scanner; public class FindTheMedian { private static int median(int[] array) { Arrays.sort(array); return array[array.length / 2]; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] array = new int[n]; for (int i = 0; i < array.length; i++) { array[i] = in.nextInt(); } System.out.println(median(array)); } }
package io.bitsquare; import io.bitsquare.btc.WalletFacade; import io.bitsquare.di.BitSquareModule; import io.bitsquare.gui.AWTSystemTray; import io.bitsquare.gui.Navigation; import io.bitsquare.gui.components.Popups; import io.bitsquare.gui.util.ImageUtil; import io.bitsquare.gui.util.Profiler; import io.bitsquare.msg.MessageFacade; import io.bitsquare.persistence.Persistence; import io.bitsquare.settings.Settings; import io.bitsquare.user.User; import io.bitsquare.util.ViewLoader; import com.google.common.base.Throwables; import com.google.inject.Guice; import com.google.inject.Injector; import java.io.IOException; import javafx.application.Application; import javafx.scene.*; import javafx.scene.image.*; import javafx.scene.input.*; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import akka.actor.ActorSystem; import lighthouse.files.AppDirectory; public class BitSquareUI extends Application { private static final Logger log = LoggerFactory.getLogger(BitSquareUI.class); public static final boolean fillFormsWithDummyData = true; private static Injector injector; private static Stage primaryStage; private WalletFacade walletFacade; private MessageFacade messageFacade; public void BitSquareUI() { Profiler.init(); } public static Stage getPrimaryStage() { return primaryStage; } @Override public void start(Stage primaryStage) { Profiler.printMsgWithTime("BitSquare.start called"); BitSquareUI.primaryStage = primaryStage; Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> Popups.handleUncaughtExceptions (Throwables.getRootCause(throwable))); try { AppDirectory.initAppDir(BitSquare.getAppName()); } catch (IOException e) { log.error(e.getMessage()); } final Injector injector = Guice.createInjector(new BitSquareModule()); // currently there is not SystemTray support for java fx (planned for version 3) so we use the old AWT AWTSystemTray.createSystemTray(primaryStage, injector.getInstance(ActorSystem.class)); walletFacade = injector.getInstance(WalletFacade.class); messageFacade = injector.getInstance(MessageFacade.class); Profiler.printMsgWithTime("BitSquare: messageFacade, walletFacade created"); // apply stored data final User user = injector.getInstance(User.class); final Settings settings = injector.getInstance(Settings.class); final Persistence persistence = injector.getInstance(Persistence.class); persistence.init(); User persistedUser = (User) persistence.read(user); user.applyPersistedUser(persistedUser); settings.applyPersistedSettings((Settings) persistence.read(settings.getClass().getName())); primaryStage.setTitle("BitSquare (" + BitSquare.getAppName() + ")"); if (ImageUtil.isRetina()) primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/images/window_icon@2x.png"))); else primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/images/window_icon.png"))); ViewLoader.setInjector(injector); final ViewLoader loader = new ViewLoader(getClass().getResource(Navigation.Item.MAIN.getFxmlUrl()), false); try { final Parent view = loader.load(); final Scene scene = new Scene(view, 1000, 600); scene.getStylesheets().setAll(getClass().getResource("/io/bitsquare/gui/bitsquare.css").toExternalForm(), getClass().getResource("/io/bitsquare/gui/images.css").toExternalForm()); setupCloseHandlers(primaryStage, scene); primaryStage.setScene(scene); // TODO resizing not fully supported yet primaryStage.setMinWidth(75); primaryStage.setMinHeight(50); /* primaryStage.setMinWidth(1000); primaryStage.setMinHeight(750);*/ Profiler.initScene(primaryStage.getScene()); primaryStage.show(); } catch (IOException e) { e.printStackTrace(); log.error(e.getMessage()); } } private void setupCloseHandlers(Stage primaryStage, Scene scene) { primaryStage.setOnCloseRequest(e -> AWTSystemTray.setStageHidden()); KeyCodeCombination keyCodeCombination = new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN); scene.setOnKeyReleased(keyEvent -> { if (keyCodeCombination.match(keyEvent)) AWTSystemTray.setStageHidden(); }); } @Override public void stop() throws Exception { walletFacade.shutDown(); messageFacade.shutDown(); super.stop(); System.exit(0); } }
package jalf.optimizer; import jalf.Relation; import jalf.Visitor; import jalf.relation.algebra.Dee; import jalf.relation.algebra.Dum; import jalf.relation.algebra.Join; import jalf.relation.algebra.LeafOperand; import jalf.relation.algebra.Project; import jalf.relation.algebra.Rename; import jalf.relation.algebra.Restrict; import jalf.relation.algebra.Select; import java.util.function.Function; import java.util.function.Function; /** * Logical optimizer of relational expressions. * * Logical optimization is a process that rewrites relational expressions as * equivalent ones, but presenting a profile that leads to a better execution * plan when compiled. Typical optimizations include pushing restrictions and * projections as deep as possible in the tree. * * This visitor provides logical optimization and works in a similar way to the * compiler itself (from an architectural point of view at least). That is, it * optimizes using a depth-first visit of the AST. Leaf operands are optimized * as themselves. Result of optimizations are successively decorated as * `Optimized` and its subclasses (per operator) and the optimizations delegated * to those by pure AST rewriting. The optimization strategies are thus * implemented in the various algebra methods of Optimized and its subclasses. */ public class Optimizer implements Visitor<Relation> { private Function<Relation,Optimized<?>> mapper; public Optimizer(Function<Relation,Optimized<?>> mapper) { this.mapper = mapper; } public Optimizer() { this.mapper = new DefaultMapper(this); } protected Relation optimized(Relation relation) { return mapper.apply(relation); } public Relation visit(Select relation) { Relation optimized = relation.getOperand().accept(this); return optimized(optimized).select(relation.getSelection()); } public Relation visit(Project relation) { Relation optimized = relation.getOperand().accept(this); return optimized(optimized).project(relation.getAttributes()); } public Relation visit(Rename relation) { Relation optimized = relation.getOperand().accept(this); return optimized(optimized).rename(relation.getRenaming()); } public Relation visit(Restrict relation) { Relation optimized = relation.getOperand().accept(this); return optimized(optimized).restrict(relation.getPredicate()); } public Relation visit(Join relation) { Relation left = relation.getLeft().accept(this); Relation right = relation.getRight().accept(this); return optimized(left).join(right); } public Relation visit(LeafOperand relation) { return relation; } @Override public Relation visit(Dee relation) { return relation; } @Override public Relation visit(Dum relation) { return relation; } }
package javaschool.app; import asg.cliche.Command; import asg.cliche.Shell; import asg.cliche.ShellDependent; import asg.cliche.ShellFactory; import javaschool.app.personfactory.PersonFactory; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class PhoneBook implements ShellDependent { private Map<Integer, Record> map = new HashMap<>(); private Shell theShell; @Override public void cliSetShell(Shell theShell) { this.theShell = theShell; } @Command(description = "Add a new person") public void addPerson(String name) { add(new Person(name)); } @Command(description = "Add a new note") public void addNote(String name) { add(new Note(name)); } @Command(description = "Add a new reminder") public void addReminder(String name) { add(new Reminder(name)); } @Command(description = "Edit a record by id") public void edit(Integer id) throws IOException { Record record = lookup(id); if (record == null) { System.out.printf("Record with id \"%d\" not found.\n", id); } else { ShellFactory.createSubshell(record.getName(), theShell, "Editing " + record.getName(), record).commandLoop(); } } @Command public Collection<Record> list() { return map.values(); } @Command public List<Record> list(String type) { type = type.toLowerCase(); if (type.equals("note")) { return map.values().stream().filter(record -> record instanceof Note).collect(Collectors.toList()); } if (type.equals("person")) { return map.values().stream().filter(record -> record instanceof Person).collect(Collectors.toList()); } if (type.equals("reminder")) { return map.values().stream().filter(record -> record instanceof Reminder).collect(Collectors.toList()); } return new ArrayList<>(); } @Command public List<Record> list(String type, String... types) { final List<Record> result = this.list(type); for (String otherType : types) { result.addAll(this.list(otherType)); } return result; } @Command public void clear() { map.clear(); } @Command public void getReminds() { // see what reminders already finished } @Command(description = "Search in records") public List<Record> search(String criteria) { return map.values().stream().filter((r) -> r.contains(criteria.toLowerCase())).collect(Collectors.toList()); } @Command public void generate(Integer count) { List<Person> result = PersonFactory.generate(count, PersonFactory.API_RANDOM_USER); result.forEach(this::add); System.out.format("Created %s new users\n", result.size()); } private Record lookup(Integer id) { return map.get(id); // return map.values().stream().filter((r) -> r.getId().equals(id)).findFirst(); } private void add(Record r) { map.put(r.getId(), r); } }
package mezz.jei; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import org.lwjgl.input.Mouse; import mezz.jei.gui.ItemListOverlay; import mezz.jei.gui.RecipesGui; import mezz.jei.input.InputHandler; public class GuiEventHandler { @Nullable private ItemListOverlay itemListOverlay; @Nonnull private final RecipesGui recipesGui = new RecipesGui(); @Nullable private InputHandler inputHandler; public void setItemListOverlay(@Nullable ItemListOverlay itemListOverlay) { if (this.itemListOverlay != null) { this.itemListOverlay.close(); } this.itemListOverlay = itemListOverlay; if (this.recipesGui.isOpen()) { this.recipesGui.close(); } } @SubscribeEvent public void onGuiInit(@Nonnull GuiScreenEvent.InitGuiEvent.Post event) { if (itemListOverlay == null) { return; } Minecraft minecraft = Minecraft.getMinecraft(); GuiContainer guiContainer = asGuiContainer(minecraft.currentScreen); if (guiContainer == null) { return; } itemListOverlay.initGui(guiContainer); recipesGui.initGui(minecraft); inputHandler = new InputHandler(recipesGui, itemListOverlay, guiContainer); itemListOverlay.open(); } @SubscribeEvent public void onGuiOpen(@Nonnull GuiOpenEvent event) { if (itemListOverlay == null) { return; } if (event.gui == null && itemListOverlay.isOpen()) { itemListOverlay.close(); } } @SubscribeEvent public void onDrawScreenEventPre(@Nonnull GuiScreenEvent.DrawScreenEvent.Pre event) { GuiContainer guiContainer = asGuiContainer(event.gui); if (guiContainer == null) { return; } if (recipesGui.isOpen()) { event.setCanceled(true); } } @SubscribeEvent public void onDrawScreenEventPost(@Nonnull GuiScreenEvent.DrawScreenEvent.Post event) { if (itemListOverlay == null) { return; } GuiContainer guiContainer = asGuiContainer(event.gui); if (guiContainer == null) { return; } if (recipesGui.isOpen()) { recipesGui.drawBackground(); } itemListOverlay.drawScreen(guiContainer.mc, event.mouseX, event.mouseY); if (recipesGui.isOpen()) { recipesGui.draw(event.mouseX, event.mouseY); } itemListOverlay.drawHovered(guiContainer.mc, event.mouseX, event.mouseY); if (!recipesGui.isOpen()) { /** * There is no way to render between the existing inventory tooltip and the dark background layer, * so we have to re-render the inventory tooltip over the item list. **/ Slot slotUnderMouse = guiContainer.getSlotUnderMouse(); if (slotUnderMouse != null && slotUnderMouse.getHasStack()) { ItemStack itemStack = slotUnderMouse.getStack(); guiContainer.renderToolTip(itemStack, event.mouseX, event.mouseY); } } } @SubscribeEvent public void onClientTick(@Nonnull TickEvent.ClientTickEvent event) { if (itemListOverlay == null || event.phase == TickEvent.Phase.END) { return; } Minecraft minecraft = Minecraft.getMinecraft(); GuiContainer guiContainer = asGuiContainer(minecraft.currentScreen); if (guiContainer == null) { return; } itemListOverlay.handleTick(); } @SubscribeEvent public void onGuiKeyboardEvent(GuiScreenEvent.KeyboardInputEvent.Pre event) { if (!(event.gui instanceof GuiContainer)) { return; } if (inputHandler != null) { if (inputHandler.handleKeyEvent()) { event.setCanceled(true); } } } @SubscribeEvent public void onGuiMouseEvent(GuiScreenEvent.MouseInputEvent.Pre event) { GuiScreen gui = event.gui; if (!(gui instanceof GuiContainer)) { return; } if (inputHandler != null) { int x = Mouse.getEventX() * gui.width / gui.mc.displayWidth; int y = gui.height - Mouse.getEventY() * gui.height / gui.mc.displayHeight - 1; if (inputHandler.handleMouseEvent(x, y)) { event.setCanceled(true); } } } @Nullable private GuiContainer asGuiContainer(GuiScreen guiScreen) { if (!(guiScreen instanceof GuiContainer)) { return null; } return (GuiContainer) guiScreen; } }
package mil.dds.anet.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.json.JsonSanitizer; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.imageio.ImageIO; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response.Status; import mil.dds.anet.AnetObjectEngine; import mil.dds.anet.beans.ApprovalStep; import mil.dds.anet.beans.ApprovalStep.ApprovalStepType; import mil.dds.anet.beans.Organization; import mil.dds.anet.beans.Task; import mil.dds.anet.database.ApprovalStepDao; import mil.dds.anet.database.mappers.MapperUtils; import mil.dds.anet.views.AbstractAnetBean; import net.coobird.thumbnailator.Thumbnails; import org.jsoup.Jsoup; import org.owasp.html.HtmlPolicyBuilder; import org.owasp.html.PolicyFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Utils { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private static final ObjectMapper mapper = MapperUtils.getDefaultMapper(); /** * Crude method to check whether a uuid is purely integer, in which case it is probably a legacy * id; used for backwards-compatibility only. * * @param uuid the uuid to check * @return the integer value of the uuid, or null if it isn't */ public static Integer getInteger(String uuid) { try { return Integer.parseInt(uuid); } catch (NumberFormatException ignored) { return null; } } public static boolean uuidEqual(AbstractAnetBean a, AbstractAnetBean b) { if (a == null && b == null) { return true; } if (a == null || b == null) { return false; } return Objects.equals(a.getUuid(), b.getUuid()); } public static boolean containsByUuid(List<AbstractAnetBean> list, String uuid) { for (AbstractAnetBean el : list) { if (el.getUuid().equals(uuid)) { return true; } } return false; } public static <T extends AbstractAnetBean> T getByUuid(List<T> list, String uuid) { return list.stream().filter(el -> Objects.equals(uuid, el.getUuid())).findFirst().orElse(null); } /* * Performs a diff of the two lists of elements For each element that is in newElements but is not * in oldElements it will call addFunc For each element that is in oldElements but is not in * newElements, it will call removeFunc */ public static <T extends AbstractAnetBean> void addRemoveElementsByUuid(List<T> oldElements, List<T> newElements, Consumer<T> addFunc, Consumer<String> removeFunc) { List<String> existingUuids = oldElements.stream().map(p -> p.getUuid()).collect(Collectors.toList()); for (T newEl : newElements) { if (existingUuids.remove(newEl.getUuid()) == false) { // Add this element addFunc.accept(newEl); } } // Now remove all items in existingUuids. for (String uuid : existingUuids) { removeFunc.accept(uuid); } } public static <T> T orIfNull(T value, T ifNull) { if (value == null) { return ifNull; } else { return value; } } /** * Given a list of organizations and a topParentUuid, this function maps all of the organizations * to their highest parent within this list excluding the topParent. This can be used to check for * loops, or to generate graphs/tables that bubble things up to their highest parent. This is used * in the daily rollup graphs. */ public static Map<String, Organization> buildParentOrgMapping(List<Organization> orgs, @Nullable String topParentUuid) { final Map<String, Organization> result = new HashMap<>(); final Map<String, Organization> orgMap = new HashMap<>(); for (final Organization o : orgs) { orgMap.put(o.getUuid(), o); } for (final Organization o : orgs) { final Set<String> seenUuids = new HashSet<>(); String curr = o.getUuid(); seenUuids.add(curr); String parentUuid = o.getParentOrgUuid(); while (!Objects.equals(parentUuid, topParentUuid) && orgMap.containsKey(parentUuid)) { curr = parentUuid; if (seenUuids.contains(curr)) { final String errorMsg = String.format( "Loop detected in organization hierarchy: %1$s is its own (grand…)parent!", curr); logger.error(errorMsg); throw new IllegalArgumentException(errorMsg); } seenUuids.add(curr); parentUuid = orgMap.get(parentUuid).getParentOrgUuid(); } result.put(o.getUuid(), orgMap.get(curr)); } return result; } /** * Given a list of tasks and a topParentUuid, this function maps all of the tasks to their highest * parent within this list excluding the topParent. This can be used to check for loops. */ public static Map<String, Task> buildParentTaskMapping(List<Task> tasks, @Nullable String topParentUuid) { final Map<String, Task> result = new HashMap<>(); final Map<String, Task> taskMap = new HashMap<>(); for (final Task t : tasks) { taskMap.put(t.getUuid(), t); } for (final Task t : tasks) { final Set<String> seenUuids = new HashSet<>(); String curr = t.getUuid(); seenUuids.add(curr); String parentUuid = t.getCustomFieldRef1Uuid(); while (!Objects.equals(parentUuid, topParentUuid) && taskMap.containsKey(parentUuid)) { curr = parentUuid; if (seenUuids.contains(curr)) { final String errorMsg = String .format("Loop detected in task hierarchy: %1$s is its own (grand…)parent!", curr); logger.error(errorMsg); throw new IllegalArgumentException(errorMsg); } seenUuids.add(curr); parentUuid = taskMap.get(parentUuid).getCustomFieldRef1Uuid(); } result.put(t.getUuid(), taskMap.get(curr)); } return result; } public static final PolicyFactory HTML_POLICY_DEFINITION = new HtmlPolicyBuilder() .allowStandardUrlProtocols() // Allow in-line image data .allowUrlProtocols("data").allowAttributes("src").matching(Pattern.compile("^data:image/.*$")) .onElements("img") // Allow some image attributes .allowAttributes("align", "alt", "border", "name", "height", "width", "hspace", "vspace") .onElements("img") // Allow title="..." on any element. .allowAttributes("title").globally() // Allow href="..." on <a> elements (but not the 'data:' protocol!). .allowAttributes("href").matching(Pattern.compile("^(?!data:).*$")).onElements("a") // Defeat link spammers. .requireRelNofollowOnLinks() // The align attribute on <p> elements can have any value below. .allowAttributes("align").matching(true, "center", "left", "right", "justify", "char") .onElements("p").allowAttributes("border", "cellpadding", "cellspacing").onElements("table") .allowAttributes("colspan", "rowspan").onElements("td", "th").allowStyling() // These elements are allowed. .allowElements("a", "p", "div", "i", "b", "u", "em", "blockquote", "tt", "strong", "br", "ul", "ol", "li", "table", "tr", "td", "thead", "tbody", "th", "span", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "img", "strike", "mark") .toFactory(); public static String sanitizeHtml(String input) { if (input == null) { return null; } return HTML_POLICY_DEFINITION.sanitize(input); } public static String sanitizeJson(String inputJson) throws JsonProcessingException { if (inputJson == null) { // `JsonSanitizer.sanitize(null)` would return `"null"` in this case, // but we prefer plain `null` return null; } final String sanitizedJson = JsonSanitizer.sanitize(inputJson); final JsonNode jsonTree = mapper.readTree(sanitizedJson); internalSanitizeJsonForHtml(jsonTree); return mapper.writeValueAsString(jsonTree); } private static void internalSanitizeJsonForHtml(JsonNode jsonNode) { if (jsonNode.isObject()) { final ObjectNode objectNode = (ObjectNode) jsonNode; for (final Iterator<Map.Entry<String, JsonNode>> entryIter = objectNode.fields(); entryIter .hasNext();) { final Map.Entry<String, JsonNode> entry = entryIter.next(); final JsonNode newValue = entry.getValue().isTextual() ? objectNode.textNode(sanitizeHtml(entry.getValue().asText())) : entry.getValue(); final String sanitizedKey = sanitizeHtml(entry.getKey()); if (!entry.getKey().equals(sanitizedKey)) { objectNode.remove(entry.getKey()); } objectNode.set(sanitizedKey, newValue); internalSanitizeJsonForHtml(entry.getValue()); } } else if (jsonNode.isArray()) { final ArrayNode arrayNode = (ArrayNode) jsonNode; for (int i = 0; i < arrayNode.size(); i++) { if (arrayNode.get(i).isTextual()) { arrayNode.set(i, arrayNode.textNode(sanitizeHtml(arrayNode.get(i).asText()))); } else { internalSanitizeJsonForHtml(arrayNode.get(i)); } } } } public static JsonNode parseJsonSafe(String inputJson) throws JsonProcessingException { final String sanitizedJson = Utils.sanitizeJson(inputJson); return sanitizedJson == null ? null : mapper.readTree(sanitizedJson); } public static String trimStringReturnNull(String input) { if (input == null) { return null; } return input.trim(); } /** * Check for empty HTML. * * @param s string * @return true if string renders to 'empty' HTML, i.e. just whitespace */ public static boolean isEmptyHtml(String s) { return isEmptyOrNull(trimStringReturnNull(s)) || isEmptyOrNull(trimStringReturnNull(htmlToText(s))); } private static String htmlToText(String s) { return Jsoup.parse(s).text(); } /** * Check for empty or null string. * * @param s string * @return true if string is null or empty */ public static boolean isEmptyOrNull(String s) { return s == null || s.isEmpty(); } /** * Check for empty or null collection. * * @param c collection * @return true if collection is null or empty */ public static boolean isEmptyOrNull(Collection<?> c) { return c == null || c.isEmpty(); } /** * Transform a result list from a database query by grouping. For example, given a result list: * <code> * [{"uuid": 3, "name": "alice", "someprop": "x", "week": 39, "nrdone": 2, "nrtodo": 0}, * {"uuid": 3, "name": "alice", "someprop": "x", "week": 40, "nrdone": 1, "nrtodo": 3}, * {"uuid": 3, "name": "alice", "someprop": "x", "week": 41, "nrdone": 0, "nrtodo": 5}, * {"uuid": 5, "name": "bob", "someprop": "y", "week": 39, "nrdone": 8, "nrtodo": 2}, * {"uuid": 5, "name": "bob", "someprop": "y", "week": 41, "nrdone": 3, "nrtodo": 0}, * {"uuid": 6, "name": "eve", "someprop": "z", "week": 39, "nrdone": 6, "nrtodo": 1}] * </code> then transforming it like so: <code> * final Set&lt;String&gt; tlf = Stream.of("name", "someprop").collect(Collectors.toSet()); * return resultGrouper(list, "stats", "uuid", tlf); * </code> will return the list: <code> * [{"uuid": 3, "name": "alice", "someprop": "x", * "stats": [{"week": 39, "nrdone": 2, "nrtodo": 0}, * {"week": 40, "nrdone": 1, "nrtodo": 3}, * {"week": 41, "nrdone": 0, "nrtodo": 5}]}, * {"uuid": 5, "name": "bob", "someprop": "y", * "stats": [{"week": 39, "nrdone": 8, "nrtodo": 2}, * {"week": 41, "nrdone": 3, "nrtodo": 0}]}, * {"uuid": 6, "name": "eve", "someprop": "z", * "stats": [{"week": 39, "nrdone": 6, "nrtodo": 1}]}] * </code> * * @param results a result list from a database query * @param groupName the name of the group in the resulting list elements * @param groupingField the key field on which to group * @param topLevelFields the fields to appear in the top-level object (i.e. not in the group) * @return the grouped results from the query */ public static List<Map<String, Object>> resultGrouper(List<Map<String, Object>> results, String groupName, String groupingField, Set<String> topLevelFields) { final List<Map<String, Object>> groupedResults = new ArrayList<>(); final Map<Object, Map<String, Object>> seenResults = new HashMap<>(); for (final Map<String, Object> result : results) { final Map<String, Object> topLevelObject; final Object groupingKey = result.get(groupingField); if (seenResults.containsKey(groupingKey)) { topLevelObject = seenResults.get(groupingKey); } else { topLevelObject = new HashMap<>(); topLevelObject.put(groupingField, groupingKey); topLevelObject.put(groupName, new ArrayList<>()); groupedResults.add(topLevelObject); seenResults.put(groupingKey, topLevelObject); } @SuppressWarnings("unchecked") final List<Map<String, Object>> groupList = (List<Map<String, Object>>) topLevelObject.get(groupName); final Map<String, Object> group = new HashMap<>(); groupList.add(group); for (final Map.Entry<String, Object> entry : result.entrySet()) { if (groupingField.equals(entry.getKey())) { // already present } else if (topLevelFields.contains(entry.getKey())) { topLevelObject.put(entry.getKey(), entry.getValue()); } else { group.put(entry.getKey(), entry.getValue()); } } } return groupedResults; } /** * Checks whether an email address is allowed according to a list of whitelisted domains. * * @param email The email address to check * @param whitelistDomainNames The list of whitelisted domain names (wildcards allowed) * @return Whether the email is whitelisted */ public static boolean isEmailWhitelisted(final String email, final List<String> whitelistDomainNames) { try { return isLogonDomainInList(email, whitelistDomainNames); } catch (IllegalArgumentException e) { logger.error("Failed to process email: {}", email); return false; } } public static boolean isDomainUserNameIgnored(final String domainUserName, final List<String> ignoredDomainNames) { try { return isLogonDomainInList(domainUserName, ignoredDomainNames); } catch (IllegalArgumentException e) { logger.error("Failed to process domain user name: {}", domainUserName); return true; } } private static boolean isLogonDomainInList(final String logon, final List<String> list) throws IllegalArgumentException { final String wildcard = "*"; // Separator for 'User Principal Name' format final String upnSeparator = "@"; // Separator for 'Down-Level Logon Name' format final String dlSeparator = "\\"; if (isEmptyOrNull(logon) || isEmptyOrNull(list)) { return false; } // Logon has no domain if (!logon.contains(upnSeparator) && !logon.contains(dlSeparator)) { return false; } // Find out the format boolean isDownLevelFormat = logon.contains(dlSeparator); final String[] splittedLogon = logon.trim().split(isDownLevelFormat ? dlSeparator + "\\" : upnSeparator); // A logon (domain user name or email) is expected to have two parts: username<separator>domain if (splittedLogon.length != 2) { throw new IllegalArgumentException("Malformed logon: " + logon); } // Find the domain name depending on the format final String domainName = (isDownLevelFormat ? splittedLogon[0] : splittedLogon[1]).toLowerCase(); // Compile a list of regex patterns we want to use to filter and then find any match return list.stream().map(domain -> domainToRegexPattern(domain, wildcard)) .anyMatch(domainPattern -> domainPattern.matcher(domainName).matches()); } private static Pattern domainToRegexPattern(final String domain, final String wildcard) { final String regex = domain.replace(".", "[.]") // replace dots .replace(wildcard, ".*?"); // replace wildcards return Pattern.compile("^" + regex + "$"); } /** * Resizes an image. * * @param imageBytes The image as a byte-array * @param width The desired output width * @param height The desired output height * @param imageFormatName The desired output format (png, jpg) * @return The resized image as a byte-array * @throws Exception When the binary data cannot be converted to an image string representation */ public static byte[] resizeImage(byte[] imageBytes, int width, int height, String imageFormatName) throws Exception { if (imageBytes == null) { return null; } // From byte-array to BufferedImage final BufferedImage imageBinary = convert(imageBytes); if (imageBinary == null) { throw new Exception("Cannot interpret image binary data."); } // Resizing final ByteArrayOutputStream os = new ByteArrayOutputStream(); Thumbnails.of(imageBinary).size(width, height).outputFormat(imageFormatName).outputQuality(1.0f) .toOutputStream(os); return os.toByteArray(); } /** * Converts an image represented as a byte-array into a BufferedImage. * * @param imageBytes The image as a byte-array * @return The BufferedImage object * @throws IOException When an error occurs while reading the string */ public static BufferedImage convert(byte[] imageBytes) throws IOException { final ByteArrayInputStream is = new ByteArrayInputStream(imageBytes); return ImageIO.read(is); } /** * Converts a BufferedImage representing an image into a byte-array. * * @param imageBytes The image as bytes * @param imageFormatName The desired output format * @return The image as byte-array * @throws IOException When an error occurs while writing the string */ public static byte[] convert(BufferedImage imageBytes, String imageFormatName) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(imageBytes, imageFormatName, os); return os.toByteArray(); } public static void updateApprovalSteps(AbstractAnetBean entity, List<ApprovalStep> planningApprovalSteps, List<ApprovalStep> existingPlanningApprovalSteps, List<ApprovalStep> approvalSteps, List<ApprovalStep> existingApprovalSteps) { final AnetObjectEngine engine = AnetObjectEngine.getInstance(); if (planningApprovalSteps != null) { logger.debug("Editing planning approval steps for {}", entity); for (ApprovalStep step : planningApprovalSteps) { Utils.validateApprovalStep(step); step.setType(ApprovalStepType.PLANNING_APPROVAL); step.setRelatedObjectUuid(entity.getUuid()); } Utils.addRemoveElementsByUuid(existingPlanningApprovalSteps, planningApprovalSteps, newStep -> engine.getApprovalStepDao().insert(newStep), oldStepUuid -> engine.getApprovalStepDao().delete(oldStepUuid)); Utils.updateSteps(planningApprovalSteps, existingPlanningApprovalSteps); } if (approvalSteps != null) { logger.debug("Editing approval steps for {}", entity); for (ApprovalStep step : approvalSteps) { Utils.validateApprovalStep(step); step.setType(ApprovalStepType.REPORT_APPROVAL); step.setRelatedObjectUuid(entity.getUuid()); } Utils.addRemoveElementsByUuid(existingApprovalSteps, approvalSteps, newStep -> engine.getApprovalStepDao().insert(newStep), oldStepUuid -> engine.getApprovalStepDao().delete(oldStepUuid)); Utils.updateSteps(approvalSteps, existingApprovalSteps); } } // Helper method that diffs the name/members of an approvalStep private static void updateStep(ApprovalStep newStep, ApprovalStep oldStep) { final AnetObjectEngine engine = AnetObjectEngine.getInstance(); final ApprovalStepDao approvalStepDao = engine.getApprovalStepDao(); newStep.setUuid(oldStep.getUuid()); // Always want to make changes to the existing step approvalStepDao.update(newStep); if (newStep.getApprovers() != null) { Utils.addRemoveElementsByUuid(oldStep.loadApprovers(engine.getContext()).join(), newStep.getApprovers(), newPosition -> approvalStepDao.addApprover(newStep, DaoUtils.getUuid(newPosition)), oldPositionUuid -> approvalStepDao.removeApprover(newStep, oldPositionUuid)); } } // Helper method that updates a list of approval steps private static void updateSteps(List<ApprovalStep> steps, List<ApprovalStep> existingSteps) { final AnetObjectEngine engine = AnetObjectEngine.getInstance(); final ApprovalStepDao approvalStepDao = engine.getApprovalStepDao(); for (int i = 0; i < steps.size(); i++) { ApprovalStep curr = steps.get(i); ApprovalStep next = (i == (steps.size() - 1)) ? null : steps.get(i + 1); curr.setNextStepUuid(DaoUtils.getUuid(next)); ApprovalStep existingStep = Utils.getByUuid(existingSteps, curr.getUuid()); // If this step didn't exist before, we still need to set the nextStepUuid on it, but // don't need to do a deep update. if (existingStep == null) { approvalStepDao.update(curr); } else { // Check for updates to name, nextStepUuid and approvers. Utils.updateStep(curr, existingStep); } } } public static void validateApprovalStep(ApprovalStep step) { if (Utils.isEmptyOrNull(step.getName())) { throw new WebApplicationException("A name is required for every approval step", Status.BAD_REQUEST); } if (Utils.isEmptyOrNull(step.getApprovers())) { throw new WebApplicationException("An approver is required for every approval step", Status.BAD_REQUEST); } } }